File size: 29,909 Bytes
be27524
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
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
import traceback
from prompt_rewrite import rewrite
import hashlib


def apply_aspect_ratio(ratio):
    sizes = {
        "1:1": (1024, 1024),
        "16:9": (1365, 768),
        "9:16": (768, 1365),
        "3:2": (1254, 836),
        "2:3": (836, 1254),
        "3:1": (1774, 591),
        "2:1": (1448, 724),
    }
    return sizes.get(ratio, (1024, 1024))

DEFAULT_ASPECT_RATIO = "16:9"

# ✅ NUEVO: importar optimización avanzada tipo Qwen-Image-MultipleAngles
#from optimization import optimize_pipeline_

LORAS_CACHE = {
    "data": [],
    "last_hash": None,
}
def load_loras_hot():
    """Load loras.json and detect changes."""
    path = hf_hub_download(
        repo_id="lichorosario/qwen-image-lora-dlc-v3",
        filename="loras.json",
        repo_type="space",
    )

    with open(path, "r", encoding="utf-8") as f:
        raw = f.read()

    current_hash = hashlib.sha256(raw.encode("utf-8")).hexdigest()

    if current_hash != LORAS_CACHE["last_hash"]:
        LORAS_CACHE["data"] = json.loads(raw)
        LORAS_CACHE["last_hash"] = current_hash
        print("🔁 LoRA config updated")

    return LORAS_CACHE["data"]

    
# Load LoRAs from JSON file
def load_loras_from_file():
    """Load LoRA configurations from external JSON file."""
    try:
        with open('loras.json', 'r', encoding='utf-8') as f:
            return json.load(f)
    except FileNotFoundError:
        print("Warning: loras.json file not found. Using empty list.")
        return []
    except json.JSONDecodeError as e:
        print(f"Error parsing loras.json: {e}")
        return []


# Load the LoRAs
#loras = load_loras_from_file()
loras = load_loras_hot()

saved_loras = []

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


# 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(
    "Qwen/Qwen-Image-2512", scheduler=scheduler, torch_dtype=dtype
).to(device)



"""
# ✅ NUEVO BLOQUE: aplicar AOT optimization (igual que Qwen-Image-MultipleAngles)
try:
    example_args = (
        "a cute cat in a spacesuit",
    )
    example_kwargs = dict(
        num_inference_steps=4,
        true_cfg_scale=3.5,
        width=1024,
        height=1024,
        num_images_per_prompt=1,
    )
    optimize_pipeline_(pipe, *example_args, **example_kwargs)
    print("✅ Transformer AOT optimization complete.")
except Exception as e:
    print(f"⚠️ AOT optimization skipped: {e}")
"""


# Lightning LoRA info (no global state)
LIGHTNING_LORA_REPO = "lightx2v/Qwen-Image-2512-Lightning"
LIGHTNING_LORA_WEIGHT = "Qwen-Image-2512-Lightning-4steps-V1.0-fp32.safetensors"
LIGHTNING8_LORA_WEIGHT = "Qwen-Image-2512-Lightning-8steps-V1.0-fp32.safetensors"
LIGHTNING_FP8_4STEPS_LORA_WEIGHT = "Qwen-Image-fp8-e4m3fn-Lightning-4steps-V1.0-bf16.safetensors"

#LIGHTNING_LORA_REPO = "Wuli-art/Qwen-Image-2512-Turbo-LoRA"
#LIGHTNING_LORA_WEIGHT = "Wuli-Qwen-Image-2512-Turbo-LoRA-4steps-V1.0-bf16.safetensors"
#LIGHTNING8_LORA_WEIGHT = "Wuli-Qwen-Image-2512-Turbo-LoRA-4steps-V1.0-bf16.safetensors"

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


### MODIFICACIÓN 1: AÑADIR FUNCIONES PARA GESTIONAR EL HISTORIAL ###
def update_history(new_images, history):
    """Añade las nuevas imágenes generadas al principio de la lista del historial."""
    if history is None:
        history = []
    if new_images is not None and len(new_images) > 0:
        updated_history = new_images + history
        return updated_history[:24]
    return history


def clear_history():
    """Devuelve una lista vacía para limpiar la galería de historial."""
    return []
### FIN DE LA MODIFICACIÓN 1 ###




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 update_selection(evt: gr.SelectData, width, height):
    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}) ✨"
    
    examples_list = []
    try:
        model_card = ModelCard.load(lora_repo)
        widget_data = model_card.data.get("widget", [])
        if widget_data and len(widget_data) > 0:
            for example in widget_data[:4]:
                if "output" in example and "url" in example["output"]:
                    image_url = f"https://huggingface.co/{lora_repo}/resolve/main/{example['output']['url']}"
                    prompt_text = example.get("text", "")
                    examples_list.append([prompt_text])
    except Exception as e:
        print(f"Could not load model card for {lora_repo}: {e}")
    
    return (
        gr.update(placeholder=new_placeholder),
        updated_text,
        evt.index,
        width,
        height,
        gr.update(interactive=True)
    )


def handle_speed_mode(speed_mode):
    """Update UI based on speed/quality toggle."""
    if speed_mode == "light 4":
        return gr.update(value="Light mode (4 steps) selected"), 4, 1.0
    elif speed_mode == "light 4 fp8":
        return gr.update(value="Light mode (4 steps fp8) selected"), 4, 1.0
    elif speed_mode == "light 8":
        return gr.update(value="Light mode (8 steps) selected"), 8, 1.0
    elif speed_mode == "Wuli-art":
        return gr.update(value="Light mode (4 steps) Wuli-art selected"), 4, 1.0
    else: 
        return gr.update(value="Normal quality (45 steps) selected"), 45, 3.5


@spaces.GPU(duration=70)
def generate_image(
    prompt_mash,
    steps,
    seed,
    cfg_scale,
    width,
    height,
    lora_scale,
    negative_prompt="",
    num_images=1,
    prompt_enhance=False,
):
    pipe.to("cuda")
#    if negative_prompt == '':
#        negative_prompt =  "低分辨率,低画质,肢体畸形,手指畸形,画面过饱和,蜡像感,人脸无细节,过度光滑,画面具有AI感。构图混乱。文字模糊,扭曲。"

        
    if prompt_enhance:
        with calculateDuration("Enjancing prompt"):
            print(f"Calling pipeline with prompt: '{prompt_mash}'")
            prompt_mash = rewrite(prompt_mash)

    seeds = [seed + (i * 100) for i in range(num_images)]
    generators = [torch.Generator(device="cuda").manual_seed(s) for s in seeds]
    
    images = []

    with calculateDuration("Generating images (sequential)"):
        for i in range(num_images):
            current_seed = seed + (i * 100)
            generator = torch.Generator(device="cuda").manual_seed(current_seed)
    
            result = pipe(
                prompt=prompt_mash,
                negative_prompt=negative_prompt,
                num_inference_steps=steps,
                true_cfg_scale=cfg_scale,
                width=width,
                height=height,
                num_images_per_prompt=1,
                generator=generator,
            )
    
            images.append((result.images[0], current_seed))
    return images



def generate_images_for_prompts(
    prompts,
    negative_prompt,
    steps,
    seed,
    cfg_scale,
    width,
    height,
    quantity,  # ✅ FIX: ahora entra como parámetro
    prompt_enhance=False,
):
    pipe.to("cuda")
#    if negative_prompt == '':
#        negative_prompt =  "低分辨率,低画质,肢体畸形,手指畸形,画面过饱和,蜡像感,人脸无细节,过度光滑,画面具有AI感。构图混乱。文字模糊,扭曲。"
    
    images = []

    for prompt in prompts:
        current_seed = seed
        if prompt_enhance:
            prompt = rewrite(prompt)

        # ✅ FIX: quantity ya no es el componente global; es un int real
        for _ in range(int(quantity)):
            generator = torch.Generator(device="cuda").manual_seed(current_seed)
    
            result = pipe(
                prompt=prompt,
                negative_prompt=negative_prompt,
                num_inference_steps=steps,
                true_cfg_scale=cfg_scale,
                width=width,
                height=height,
                num_images_per_prompt=1,
                generator=generator,
            )
    
            images.append((result.images[0], current_seed))
            current_seed += 100  # separación segura

    return images



@spaces.GPU(duration=70)
def run_lora_multi(
    prompt_1, prompt_2, prompt_3, prompt_4,
    negative_prompt,
    cfg_scale, steps,
    selected_index,
    randomize_seed, seed,
    width, height,
    lora_scale,
    speed_mode,
    quality_multiplier,
    quantity,  # se ignora acá (pero ahora lo usamos bien)
    history,
    prompt_enhance=False,
    progress=gr.Progress(track_tqdm=True)
):
    if selected_index is None:
        raise gr.Error("You must select a LoRA before proceeding.")

    prompts = [
        p.strip() for p in [prompt_1, prompt_2, prompt_3, prompt_4]
        if p and p.strip()
    ]

    if not prompts:
        raise gr.Error("You must fill at least one prompt.")

    selected_lora = loras[selected_index]
    lora_path = selected_lora["repo"]
    trigger_word = selected_lora["trigger_word"]

    # aplicar trigger word por prompt
    final_prompts = []
    for p in prompts:
        if trigger_word:
            if selected_lora.get("trigger_position") == "append":
                final_prompts.append(f"{p} {trigger_word}")
            else:
                final_prompts.append(f"{trigger_word} {p}")
        else:
            final_prompts.append(p)

    # limpiar LoRAs previas
    pipe.unload_lora_weights()

    # 🔥 CARGA DE LORAs (UNA SOLA VEZ)
    if speed_mode == "light 4":
        pipe.load_lora_weights(
            LIGHTNING_LORA_REPO,
            weight_name=LIGHTNING_LORA_WEIGHT,
            adapter_name="lightning"
        )
        pipe.load_lora_weights(
            lora_path,
            weight_name=selected_lora.get("weights"),
            adapter_name="style"
        )
        pipe.set_adapters(["lightning", "style"], adapter_weights=[1.0, lora_scale])

    elif speed_mode == "light 8":
        pipe.load_lora_weights(
            LIGHTNING_LORA_REPO,
            weight_name=LIGHTNING8_LORA_WEIGHT,
            adapter_name="lightning"
        )
        pipe.load_lora_weights(
            lora_path,
            weight_name=selected_lora.get("weights"),
            adapter_name="style"
        )
        pipe.set_adapters(["lightning", "style"], adapter_weights=[1.0, lora_scale])

    else:
        pipe.load_lora_weights(
            lora_path,
            weight_name=selected_lora.get("weights"),
            adapter_name="style"
        )
        pipe.set_adapters(["style"], adapter_weights=[lora_scale])

    if randomize_seed:
        seed = random.randint(0, MAX_SEED)

    multiplier = float(quality_multiplier.replace("x", ""))
    width = int(width * multiplier)
    height = int(height * multiplier)

    # ✅ FIX: quantity viene como index 0..3 (por type="index"), convertimos a 1..4
    real_quantity = int(quantity) + 1


    if (history is None):
        history = []
    gallery_images = []
        
    for prompt in prompts:
        current_seed = seed
        if prompt_enhance:
            prompt = rewrite(prompt)
    
        # ✅ FIX: quantity ya no es el componente global; es un int real
        for _ in range(real_quantity):
            generator = torch.Generator(device="cuda").manual_seed(current_seed)
    
            result = pipe(
                prompt=prompt,
                negative_prompt=negative_prompt,
                num_inference_steps=steps,
                true_cfg_scale=cfg_scale,
                width=width,
                height=height,
                num_images_per_prompt=1,
                generator=generator,
            )
            
            img = result.images[0]
            imgtuple = (img, str(current_seed))
#            images.append(imgtuple)
            gallery_images.append(imgtuple)
            
            # history persistente (acumula)
            history = [(img, str(current_seed))] + history
            history = history[:24]

            yield gallery_images, history, history, seed
            
            current_seed += 100  # separación segura
    
    #return images
    
    #images = generate_images_for_prompts(
    #    prompts=final_prompts,
    #    negative_prompt=negative_prompt,
    #    steps=steps,
    #    seed=seed,
    #    cfg_scale=cfg_scale,
    #    width=width,
    #    height=height,
    #    quantity=real_quantity,  # ✅ FIX: ahora se pasa
    #    prompt_enhance=prompt_enhance,
    #)

    #gallery_images = [(img, str(s)) for img, s in images]
    #return gallery_images, seed



# ... (El resto de las funciones como get_huggingface_safetensors, check_custom_model, etc., permanecen sin cambios) ...
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}")
    model_card = ModelCard.load(link)
    base_model = model_card.data.get("base_model")
    print(f"Base model: {base_model}")
    acceptable_models = {
        "Qwen/Qwen-Image",
        "Qwen/Qwen-Image-2512",
    }
    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!")
    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
    fs = HfFileSystem()
    try:
        list_of_files = fs.ls(link, detail=False)
        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}")
            model_card_examples = ""
            try:
                model_card = ModelCard.load(repo)
                widget_data = model_card.data.get("widget", [])
                if widget_data and len(widget_data) > 0:
                    examples_html = '<div style="margin-top: 10px;">'
                    examples_html += '<h4 style="margin-bottom: 8px; font-size: 0.9em;">Sample Images:</h4>'
                    examples_html += '<div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px;">'
                    for i, example in enumerate(widget_data[:4]):
                        if "output" in example and "url" in example["output"]:
                            image_url = f"https://huggingface.co/{repo}/resolve/main/{example['output']['url']}"
                            caption = example.get("text", f"Example {i+1}")
                            examples_html += f'''
                            <div style="text-align: center;">
                                <img src="{image_url}" style="width: 100%; height: auto; border-radius: 4px;" />
                                <p style="font-size: 0.7em; margin: 2px 0;">{caption[:30]}{'...' if len(caption) > 30 else ''}</p>
                            </div>
                            '''
                    examples_html += '</div></div>'
                    model_card_examples = examples_html
            except Exception as e:
                print(f"Could not load model card examples for custom LoRA: {e}")
            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>
              {model_card_examples}
            </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
            return gr.update(visible=True, value=card), gr.update(visible=True), gr.Gallery(selected_index=None), f"Custom: {path}", existing_item_index, trigger_word, gr.update(interactive=True)
        except Exception as e:
            full_traceback = traceback.format_exc()
            print(f"Full traceback:\n{full_traceback}")
            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, "", gr.update(interactive=False)
    else:
        return gr.update(visible=False), gr.update(visible=False), gr.update(), "", None, "", gr.update(interactive=False)


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


def reload_loras_gallery():
    global loras
    loras = load_loras_hot()

    gallery_items = [
        (item["image"], item.get("title") or item.get("name"))
        for item in loras
        if item.get("image")
    ]

    return gr.update(value=gallery_items)



def init(speed_mode, aspect_ratio):
    loras_result = reload_loras_gallery()
    speed_mode_result = handle_speed_mode(speed_mode)
    aspect_ratio_result = apply_aspect_ratio(aspect_ratio)
    return (
        *speed_mode_result,
        *aspect_ratio_result,
        loras_result
    )




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(
        """<h1 style=\"color:#644fea\">Qwen-Image-2512</h1>        
        <h3 style=\"margin-top: -10px\">LoRA🦜 ChoquinLabs Explorer</h3>""",
        elem_id="title",
    )
    
    selected_index = gr.State(None)
    
    with gr.Row():
        with gr.Column(scale=3):
    
            prompt_1 = gr.Textbox(label="Prompt 1", lines=1)
            prompt_2 = gr.Textbox(label="Prompt 2", lines=1)
            prompt_3 = gr.Textbox(label="Prompt 3", lines=1)
            prompt_4 = gr.Textbox(label="Prompt 4", lines=1)
            
            negative_prompt = gr.Textbox(label="Negative Prompt", lines=1, placeholder="Optional: what to avoid")
            prompt_enhance = gr.Checkbox(label="Prompt Enhance", value=False)
        with gr.Column(scale=1, elem_id="gen_column"):
            generate_button = gr.Button("Generate", variant="primary", elem_id="gen_btn", interactive=False)


    
    with gr.Row():
        with gr.Column():
            selected_info = gr.Markdown("")
            examples_component = gr.Examples(examples=[], inputs=[prompt_1], label="Sample Prompts", visible=False)
            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
            )
            reload_btn = gr.Button("🔄 Reload LoRAs")            
            
            
            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.Gallery(label="Generated Images", show_label=True, elem_id="result_gallery")
            history_state = gr.State([]) 
            ### MODIFICACIÓN 2: AÑADIR LOS COMPONENTES DE LA UI DEL HISTORIAL ###
            with gr.Group():
                with gr.Row():
                    gr.Markdown("### 📜 History")
                    clear_history_button = gr.Button("🗑️ Clear History", size="sm")


                history_gallery = gr.Gallery(
                    label="Generation History",
                    show_label=False,
                    columns=4,
                    object_fit="contain",
                    height="auto",
                    interactive=False
                )
            ### FIN DE LA MODIFICACIÓN 2 ###
            
            with gr.Row():
                with gr.Column():
                    speed_mode = gr.Radio(
                        label="Generation Mode",
                        choices=["light 4", "Wuli-art", "light 4 fp8", "light 8", "normal"],
                        value="light 4",
                        info="'light' modes use Lightning LoRA for faster generation"
                    )
                with gr.Column():
                    quantity = gr.Radio(
                        label="Quantity",
                        choices=["1", "2", "3", "4"],
                        value="1",
                        type="index"
                    )
            
            speed_status = gr.Markdown("Quality mode active", elem_id="speed_status")

            with gr.Row():
                aspect_ratio = gr.Radio(
                    label="Aspect Ratio",
                    choices=["1:1", "16:9", "9:16", "3:2", "2:3", "3:1", "2:1"],
                    value="16:9"
                )


            with gr.Row():
                width = gr.Slider(
                    label="Width",
                    minimum=256,
                    maximum=1920,
                    step=1,
                    value=1920
                )
                height = gr.Slider(
                    label="Height",
                    minimum=256,
                    maximum=1920,
                    step=1,
                    value=1080
                )


            with gr.Row():
                quality_multiplier = gr.Radio(
                    label="Quality (Size Multiplier)",
                    choices=["0.5x", "0.75x", "1x", "1.5x", "2x"],
                    value="1x"
                )


    with gr.Row():
        with gr.Accordion("Advanced Settings", open=False):
            with gr.Column():
                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=3, step=0.01, value=1.0)


    # Event handlers
    gallery.select(
        update_selection,
        inputs=[width, height],
        outputs=[prompt_1, selected_info, selected_index, width, height, generate_button]
    )
    
    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_1, generate_button]
    )
    
    custom_lora_button.click(
        remove_custom_lora,
        outputs=[custom_lora_info, custom_lora_button, gallery, selected_info, selected_index, custom_lora, generate_button]
    )
    
    ### MODIFICACIÓN 3: CONECTAR LOS EVENTOS DEL HISTORIAL ###
    # Evento principal de generación
    generate_event = gr.on(
        triggers=[generate_button.click, prompt_1.submit],
    
        fn=run_lora_multi,
        inputs=[
            prompt_1, prompt_2, prompt_3, prompt_4,
            negative_prompt,
            cfg_scale, steps, selected_index,
            randomize_seed, seed,
            width, height, lora_scale,
            speed_mode, quality_multiplier,
            quantity,
            history_state,
            prompt_enhance
        ],
        outputs=[result, history_gallery, history_state, seed]
    )


    
    # Encadenar la actualización del historial para que se ejecute DESPUÉS de la generación
#    generate_event.then(
#        fn=update_history,
#        inputs=[result, history_gallery],
#        outputs=history_gallery,
#        show_api=False
#    )


    # Evento para el botón de limpiar historial
    clear_history_button.click(
        fn=clear_history,
        inputs=None,
        outputs=[history_state, history_gallery],
        show_api=False
    )
    ### FIN DE LA MODIFICACIÓN 3 ###

    aspect_ratio.change(
        fn=apply_aspect_ratio,
        inputs=[aspect_ratio],
        outputs=[width, height]
    )

    reload_btn.click(
        fn=reload_loras_gallery,
        outputs=gallery,
    )
 
    app.load(
        fn=init,
        inputs=[gr.State("light 4"), gr.State(DEFAULT_ASPECT_RATIO)],
        outputs=[speed_status, steps, cfg_scale, width, height, gallery]
    )


app.queue()
app.launch()