import os os.environ.setdefault("HF_HUB_ENABLE_HF_TRANSFER", "1") os.environ.setdefault("HF_HUB_DOWNLOAD_TIMEOUT", "120") import gradio as gr import json import io import shutil import tempfile import torch import spaces import random import time import math import numpy as np import traceback from prompt_rewrite import rewrite from functools import partial from diffusers import Krea2Pipeline, Krea2Transformer2DModel from huggingface_hub import HfFileSystem, ModelCard, HfApi, hf_hub_download from gradio_client import Client from PIL import Image DETAIL_ENHANCER_SPACE = "hugging-apps/krea2-detail-enhancer-edit-lora" GALLERY_DATASET_SUFFIX = "krea2-lora-gallery" GALLERY_PAGE_SIZE = 24 DEFAULT_GALLERY_FOLDER = "General" NUM_LORAS = 4 # Transformer del finetune de grounding de jimmycarter, text encoder y VAE de Krea-2-Turbo. # El finetune parte de `krea/Krea-2-Raw` con el delta de destilación Turbo mergeado, y ~90% de # su entrenamiento usó un DSL de grounding que ubica paneles, personajes, objetos y texto en # cajas `[x0,y0,x1,y1]` sobre una grilla 0-1000. Ese DSL vive en los pesos, no en el prompt: # sobre `krea/Krea-2-Turbo` puro las coordenadas se ignoran. # # El config del transformer es idéntico byte por byte al de `krea/Krea-2-Turbo` (28 capas, # 48 heads, mismos dims), así que entra como drop-in. Es bf16 completo (25,6 GB), no hay # versión cuantizada: se pierde la ventaja de arranque que tenía el NF4. base_model = "krea/Krea-2-Turbo" # bf16, gated: aporta text encoder y VAE transformer_model = "jimmycarter/krea2-turbo-bbox" # bf16, público: sólo el transformer transformer_subfolder = "epoch-5-step-26137/transformer" # Los LoRAs siguen declarando `krea/Krea-2-Turbo` en su model card, y la arquitectura es la # misma, así que cargan. Pero se entrenaron contra los pesos del Turbo y acá corren sobre un # finetune de 5 épocas: el delta asume otra base y el estilo puede degradarse. La validación # se mantiene porque sigue siendo el chequeo de compatibilidad de arquitectura. ACCEPTABLE_BASE_MODELS = {"krea/Krea-2-Turbo"} MAX_SEED = np.iinfo(np.int32).max DEFAULT_ASPECT_RATIO = "16:9" 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)) def load_loras_from_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 [] dtype = torch.bfloat16 device = "cuda" if torch.cuda.is_available() else "cpu" def _patch_krea2_attention(): """Krea-2 nunca llega a usar flash attention, y por eso corre ~8x más lento por paso que Qwen-Image a igual resolución y pasos (medido: 2,7 s/paso contra 0,33). Hay dos cosas que lo bloquean y hay que sacar las dos: 1. `Krea2AttnProcessor` pasa `enable_gqa=True` (48 query heads contra 12 KV heads), y todos los backends rápidos de `attention_dispatch` lo rechazan con ValueError("enable_gqa is not yet supported"): cuDNN, native flash, flash-attn 2/3 y los hub kernels. Sólo sobrevive el backend `native` (el SDPA de PyTorch). 2. El pipeline tokeniza con padding="max_length" a 512 tokens, así que siempre viaja una attention_mask densa. Con máscara, SDPA tampoco puede usar su kernel flash y cae a mem-efficient/math, que materializa la matriz de atención completa: 48 heads x 4608^2 en bf16 son ~2 GB por capa, x28 capas, x8 pasos. Fix: expandir K/V a mano para poder pasar enable_gqa=False, y recortar los tokens de padding en vez de enmascararlos. El recorte es seguro porque el docstring del forward dice "Pass `None` when every text token is valid" y las filas de texto de position_ids son todas cero, así que sacar filas no mueve las posiciones de las que quedan. El padding queda en el medio (el sufijo del template se concatena después), por eso el recorte va por índice booleano y no por slice. """ try: import diffusers.models.transformers.transformer_krea2 as krea2_mod from diffusers.models.transformers.transformer_krea2 import Krea2Transformer2DModel except ImportError as e: print(f"Could not apply krea2 attention patch: {e}") return _orig_dispatch = krea2_mod.dispatch_attention_fn def dispatch_attention_fn(query, key, value, attn_mask=None, enable_gqa=False, **kwargs): # Layout (batch, seq, heads, head_dim): el processor hace unflatten(-1, ...) sin transpose. if enable_gqa and key.shape[2] != query.shape[2]: n_rep = query.shape[2] // key.shape[2] key = key.repeat_interleave(n_rep, dim=2) value = value.repeat_interleave(n_rep, dim=2) enable_gqa = False return _orig_dispatch(query, key, value, attn_mask=attn_mask, enable_gqa=enable_gqa, **kwargs) krea2_mod.dispatch_attention_fn = dispatch_attention_fn _orig_forward = Krea2Transformer2DModel.forward def forward(self, hidden_states, encoder_hidden_states, timestep, position_ids, encoder_attention_mask=None, **kwargs): if encoder_attention_mask is not None: mask = encoder_attention_mask.bool() # Sólo si todas las filas del batch coinciden; si no, recortar cambiaría el # significado por muestra y conviene dejar la máscara. if mask.shape[0] == 1 or bool((mask == mask[:1]).all()): keep = mask[0] if not bool(keep.all()): text_seq_len = encoder_hidden_states.shape[1] encoder_hidden_states = encoder_hidden_states[:, keep] position_ids = torch.cat( [position_ids[:text_seq_len][keep], position_ids[text_seq_len:]], dim=0 ) encoder_attention_mask = None return _orig_forward(self, hidden_states, encoder_hidden_states, timestep, position_ids, encoder_attention_mask, **kwargs) Krea2Transformer2DModel.forward = forward print("Applied krea2 attention patch (GQA expansion + text padding trim).") _patch_krea2_attention() def _patch_krea2_text_fusion_cache(): """`text_fusion` se ejecuta dentro del loop de denoising (`transformer_krea2.py:501`) con una entrada que no cambia entre pasos: son 12 capas de atención sobre el texto más los bloques layerwise y refiner, recalculados en los 8 pasos de cada imagen. Sólo la primera pasada aporta algo. El cache se limpia al entrar y al salir de `Krea2Pipeline.__call__`, así que nunca sobrevive a una generación. Eso es lo que lo hace seguro: la clave incluye el `data_ptr` del tensor, y sin el reset podría colisionar con el de otro prompt si el allocator reusa la misma dirección. Si dentro de una misma llamada aparecieran dos tensores distintos (por ejemplo con CFG), la clave no coincide y simplemente se recalcula. """ try: from diffusers.models.transformers.transformer_krea2 import Krea2TextFusion except ImportError as e: print(f"Could not apply krea2 text_fusion cache: {e}") return _orig_text_fusion_forward = Krea2TextFusion.forward def forward(self, encoder_hidden_states, attention_mask=None): key = ( encoder_hidden_states.data_ptr(), tuple(encoder_hidden_states.shape), None if attention_mask is None else attention_mask.data_ptr(), ) cached = getattr(self, "_krea2_tf_cache", None) if cached is not None and cached[0] == key: return cached[1] out = _orig_text_fusion_forward(self, encoder_hidden_states, attention_mask=attention_mask) self._krea2_tf_cache = (key, out) return out Krea2TextFusion.forward = forward _orig_pipe_call = Krea2Pipeline.__call__ def __call__(self, *args, **kwargs): text_fusion = getattr(getattr(self, "transformer", None), "text_fusion", None) if text_fusion is not None: text_fusion._krea2_tf_cache = None try: return _orig_pipe_call(self, *args, **kwargs) finally: if text_fusion is not None: text_fusion._krea2_tf_cache = None Krea2Pipeline.__call__ = __call__ print("Applied krea2 text_fusion cache.") _patch_krea2_text_fusion_cache() transformer = Krea2Transformer2DModel.from_pretrained( transformer_model, subfolder=transformer_subfolder, torch_dtype=dtype ) pipe = Krea2Pipeline.from_pretrained( base_model, transformer=transformer, torch_dtype=dtype ).to(device) # El shift de timestep destilado (mu=1.15) es un flag del pipeline, no del transformer, así que # no puede viajar en un upload de sólo-transformer. `krea/Krea-2-Turbo` ya lo trae en su # `model_index.json`; el assert está para que un cambio de base no lo apague en silencio (sin el # shift las imágenes salen degradadas, sin error). assert pipe.config.is_distilled is True, "el shift de timestep destilado (mu=1.15) no está activo" 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_history(new_images, history): 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(): return [], [], [], None def update_version_selection(version_title, current_state, loras_list, idx): new_state = [tuple(item) for item in current_state] current_image_index, current_version_index, current_scale = new_state[idx] if current_image_index is None: return gr.update(), new_state lora = loras_list[current_image_index] versions = lora.get("versions", []) selected_version = next((v for v in versions if v["title"] == version_title), None) selected_version_index = next((i for i, v in enumerate(versions) if v["title"] == version_title), None) if selected_version: lora_name = lora["title"] version_image = selected_version.get("image", lora.get("image")) markdown_content = f"\n\n**{lora_name}** ({version_title})" new_state[idx] = (current_image_index, selected_version_index, current_scale) return gr.update(value=markdown_content), new_state return gr.update(), new_state def _loras_key(loras_meta): return tuple(sorted((l.get("repo"), l.get("weight_name"), l.get("scale")) for l in loras_meta)) def save_to_gallery(selected_idx, generation_records, folder, profile: gr.OAuthProfile | None, oauth_token: gr.OAuthToken | None): if profile is None or oauth_token is None: raise gr.Error("Iniciá sesión con Hugging Face (botón de arriba) para guardar imágenes en tu galería.") if selected_idx is None: raise gr.Error("Seleccioná primero una imagen generada (haciendo click en ella) para guardar.") if not generation_records or selected_idx >= len(generation_records): raise gr.Error("La imagen seleccionada ya no está disponible; generá de nuevo y volvé a seleccionarla.") # Deshabilitar el botón mientras se sube, para que un doble click no # dispare dos subidas en paralelo de la misma imagen. yield gr.update(interactive=False), gr.update(value="Guardando...") try: record = generation_records[selected_idx] username = profile.username dataset_repo_id = f"{username}/{GALLERY_DATASET_SUFFIX}" api = HfApi(token=oauth_token.token) api.create_repo(repo_id=dataset_repo_id, repo_type="dataset", exist_ok=True, private=True) try: metadata_path = hf_hub_download(dataset_repo_id, "gallery.json", repo_type="dataset", token=oauth_token.token) with open(metadata_path, "r", encoding="utf-8") as f: entries = json.load(f) except Exception: entries = [] already_saved = any( e.get("prompt") == record["prompt"] and e.get("seed") == record["seed"] and e.get("width") == record.get("width") and e.get("height") == record.get("height") and e.get("guidance_scale") == record.get("guidance_scale") and e.get("steps") == record.get("steps") and e.get("negative_prompt") == record.get("negative_prompt") and _loras_key(e.get("loras", [])) == _loras_key(record["loras"]) for e in entries ) if already_saved: yield gr.update(interactive=True), gr.update(value="ℹ️ Esta imagen ya estaba guardada en tu galería, no se subió de nuevo.") return timestamp = int(time.time()) image_filename = f"images/{timestamp}_{record['seed']}.png" buf = io.BytesIO() record["image"].save(buf, format="PNG") buf.seek(0) api.upload_file( path_or_fileobj=buf, path_in_repo=image_filename, repo_id=dataset_repo_id, repo_type="dataset", ) entries.append({ "image": image_filename, "prompt": record["prompt"], "negative_prompt": record.get("negative_prompt", ""), "seed": record["seed"], "guidance_scale": record.get("guidance_scale"), "steps": record.get("steps"), "width": record.get("width"), "height": record.get("height"), "loras": record["loras"], "timestamp": timestamp, "folder": (folder or "").strip() or DEFAULT_GALLERY_FOLDER, }) api.upload_file( path_or_fileobj=io.BytesIO(json.dumps(entries, ensure_ascii=False, indent=2).encode("utf-8")), path_in_repo="gallery.json", repo_id=dataset_repo_id, repo_type="dataset", ) yield gr.update(interactive=True), gr.update(value=f"✅ Guardada en [{dataset_repo_id}](https://huggingface.co/datasets/{dataset_repo_id})") except Exception as e: yield gr.update(interactive=True), gr.update(value=f"❌ Error al guardar: {e}") def fetch_gallery_metadata(profile: gr.OAuthProfile | None, oauth_token: gr.OAuthToken | None): """Downloads only gallery.json (no images) and returns entries newest-first.""" if profile is None or oauth_token is None: return [] dataset_repo_id = f"{profile.username}/{GALLERY_DATASET_SUFFIX}" try: metadata_path = hf_hub_download(dataset_repo_id, "gallery.json", repo_type="dataset", token=oauth_token.token) with open(metadata_path, "r", encoding="utf-8") as f: entries = json.load(f) except Exception: return [] return list(reversed(entries)) def get_gallery_folders(entries): return sorted({e.get("folder", DEFAULT_GALLERY_FOLDER) for e in entries}) def refresh_gallery_metadata(profile: gr.OAuthProfile | None, oauth_token: gr.OAuthToken | None): """Full refresh: re-fetches metadata and resets the folder filter to 'Todas' and the page to 0.""" entries = fetch_gallery_metadata(profile, oauth_token) folders = get_gallery_folders(entries) return ( entries, gr.update(choices=["Todas"] + folders, value="Todas"), gr.update(choices=folders or [DEFAULT_GALLERY_FOLDER]), 0, ) def refresh_gallery_entries_only(profile: gr.OAuthProfile | None, oauth_token: gr.OAuthToken | None): """Light refresh (after save/delete): re-fetches metadata and updates folder choices without resetting the current filter/page.""" entries = fetch_gallery_metadata(profile, oauth_token) folders = get_gallery_folders(entries) return ( entries, gr.update(choices=["Todas"] + folders), gr.update(choices=folders or [DEFAULT_GALLERY_FOLDER]), ) def render_gallery_page(entries, folder_filter, page, profile: gr.OAuthProfile | None, oauth_token: gr.OAuthToken | None): if profile is None or oauth_token is None: return gr.update(value=[]), [], "Página 0 de 0", 0 filtered = [ e for e in entries if not folder_filter or folder_filter == "Todas" or e.get("folder", DEFAULT_GALLERY_FOLDER) == folder_filter ] total_pages = max(1, math.ceil(len(filtered) / GALLERY_PAGE_SIZE)) page = max(0, min(page, total_pages - 1)) page_entries = filtered[page * GALLERY_PAGE_SIZE : (page + 1) * GALLERY_PAGE_SIZE] dataset_repo_id = f"{profile.username}/{GALLERY_DATASET_SUFFIX}" local_dir = os.path.join(tempfile.gettempdir(), "krea2_my_gallery", profile.username) os.makedirs(local_dir, exist_ok=True) gallery_items = [] valid_entries = [] for entry in page_entries: try: image_path = hf_hub_download(dataset_repo_id, entry["image"], repo_type="dataset", token=oauth_token.token) # Gradio refuses to serve files from the huggingface_hub cache dir # (outside cwd/tmp), so copy into an explicitly allowed tmp path. local_copy = os.path.join(local_dir, os.path.basename(entry["image"])) shutil.copyfile(image_path, local_copy) except Exception as e: print(f"Could not download {entry.get('image')}: {e}") continue gallery_items.append((local_copy, entry.get("prompt", "")[:60])) valid_entries.append(entry) page_label = f"Página {page + 1} de {total_pages}" return gr.update(value=gallery_items), valid_entries, page_label, page def delete_from_gallery(selected_idx, entries, profile: gr.OAuthProfile | None, oauth_token: gr.OAuthToken | None): if profile is None or oauth_token is None: raise gr.Error("Iniciá sesión con Hugging Face para eliminar imágenes de tu galería.") if selected_idx is None or not entries or selected_idx >= len(entries): raise gr.Error("Seleccioná primero una imagen de tu galería (haciendo click en ella) para eliminarla.") dataset_repo_id = f"{profile.username}/{GALLERY_DATASET_SUFFIX}" api = HfApi(token=oauth_token.token) entry_to_delete = entries[selected_idx] try: api.delete_file(path_in_repo=entry_to_delete["image"], repo_id=dataset_repo_id, repo_type="dataset") except Exception as e: print(f"Could not delete image file {entry_to_delete.get('image')}: {e}") # `entries` here is only the currently displayed page (see render_gallery_page), so # re-fetch the full list before removing the entry, or every other page would be lost. metadata_path = hf_hub_download(dataset_repo_id, "gallery.json", repo_type="dataset", token=oauth_token.token) with open(metadata_path, "r", encoding="utf-8") as f: full_entries = json.load(f) remaining = [e for e in full_entries if e.get("image") != entry_to_delete["image"]] api.upload_file( path_or_fileobj=io.BytesIO(json.dumps(remaining, ensure_ascii=False, indent=2).encode("utf-8")), path_in_repo="gallery.json", repo_id=dataset_repo_id, repo_type="dataset", ) return None, gr.update(value="🗑️ Imagen eliminada de tu galería.") def build_slot_updates(assignments, loras_list): """assignments: list of NUM_LORAS (lora_index, version_index, scale) tuples, None slots as (None, None, 1.0).""" radio_updates = [] md_updates = [] scale_updates = [] del_btn_updates = [] dropdown_updates = [] new_state = [] for i, (lora_index, version_index, scale) in enumerate(assignments): if lora_index is None: radio_updates.append(gr.update(value=None)) md_updates.append(gr.update(value="")) scale_updates.append(gr.update(visible=False, value=1.0)) del_btn_updates.append(gr.update(visible=False)) dropdown_updates.append(gr.update(visible=False, value=None, choices=[])) new_state.append((None, None, 1.0)) continue lora = loras_list[lora_index] lora_name = lora.get("title") or lora.get("repo") lora_image = lora.get("image") versions = lora.get("versions", []) version_title = "" version_image = lora_image if versions and version_index is not None: version_data = versions[version_index] version_title = version_data["title"] version_image = version_data.get("image", lora_image) version_choices = [v["title"] for v in versions] dropdown_updates.append(gr.update(visible=True, choices=version_choices, value=version_title)) else: dropdown_updates.append(gr.update(visible=False, value=None, choices=[])) markdown_content = f"\n\n**{lora_name}**{' ('+version_title+')' if version_title else ''}" md_updates.append(gr.update(value=markdown_content)) scale_updates.append(gr.update(visible=True, value=scale)) del_btn_updates.append(gr.update(visible=True)) radio_updates.append(gr.update(value=str(i + 1))) new_state.append((lora_index, version_index, scale)) return radio_updates, md_updates, scale_updates, del_btn_updates, dropdown_updates, new_state def reuse_from_gallery(selected_idx, entries, loras_list): if selected_idx is None or not entries or selected_idx >= len(entries): raise gr.Error("Seleccioná primero una imagen de tu galería (haciendo click en ella).") entry = entries[selected_idx] loras_list = list(loras_list) assignments = [(None, None, 1.0)] * NUM_LORAS for i, meta in enumerate(entry.get("loras", [])[:NUM_LORAS]): repo = meta.get("repo") weight_name = meta.get("weight_name") scale = meta.get("scale", 1.0) lora_index = next((idx for idx, l in enumerate(loras_list) if l.get("repo") == repo), None) version_index = None if lora_index is not None: versions = loras_list[lora_index].get("versions", []) if versions: version_index = next((vi for vi, v in enumerate(versions) if v.get("weights") == weight_name), len(versions) - 1) else: loras_list.append({ "repo": repo, "weights": weight_name, "title": meta.get("title") or repo, "trigger_word": "", "image": None, }) lora_index = len(loras_list) - 1 assignments[i] = (lora_index, version_index, scale) radio_updates, md_updates, scale_updates, del_btn_updates, dropdown_updates, new_state = build_slot_updates(assignments, loras_list) return ( [gr.update(value=entry.get("prompt", ""))] + radio_updates + md_updates + scale_updates + del_btn_updates + dropdown_updates + [ new_state, gr.update(value=False), gr.update(value=entry.get("seed", 0)), gr.update(value=entry.get("negative_prompt", "")), gr.update(value=entry.get("guidance_scale", 0.0)), gr.update(value=entry.get("steps", 8)), gr.update(value=entry.get("width", 1365)), gr.update(value=entry.get("height", 768)), gr.update(value="✅ Parámetros restaurados"), loras_list, ] ) def enhance_selected_history_image(selected_idx, history_records, history, oauth_token: gr.OAuthToken | None = None): if selected_idx is None or not history_records or selected_idx >= len(history_records): raise gr.Error("Seleccioná primero una imagen del historial (haciendo click en ella) para mejorar detalles.") history_records = history_records or [] history = history or [] record = history_records[selected_idx] yield gr.update(interactive=False), history, history, history_records, selected_idx tmp_path = None try: with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp: record["image"].save(tmp.name, format="PNG") tmp_path = tmp.name client = Client(DETAIL_ENHANCER_SPACE, token=oauth_token.token if oauth_token else None) enhanced_path, seed_used = client.predict(source_image=tmp_path, api_name="/enhance") enhanced_img = Image.open(enhanced_path).convert("RGB") new_record = dict(record) new_record["image"] = enhanced_img new_record["prompt"] = f"[detalle mejorado] {record.get('prompt', '')}" new_record["seed"] = int(seed_used) if seed_used is not None else record.get("seed") new_history = [(enhanced_img, str(new_record["seed"]))] + history new_history = new_history[:24] new_history_records = [new_record] + history_records new_history_records = new_history_records[:24] yield gr.update(interactive=True), new_history, new_history, new_history_records, 0 except Exception as e: yield gr.update(interactive=True), history, history, history_records, selected_idx raise gr.Error(f"No se pudo mejorar la imagen con {DETAIL_ENHANCER_SPACE}: {e}") finally: if tmp_path and os.path.exists(tmp_path): os.unlink(tmp_path) def gpu_duration(*args, **kwargs): """Presupuesto de GPU dinámico: pasos × imágenes × resolución, con margen.""" try: prompts = [p for p in args[0:4] if p and str(p).strip()] n_prompts = max(1, len(prompts)) steps = int(args[6]) width, height = int(args[10]), int(args[11]) mult = float(str(args[12]).replace("x", "")) real_quantity = int(args[13]) + 1 n_images = n_prompts * real_quantity pixels_factor = max(1.0, (width * mult * height * mult) / (1024 * 1024)) per_image = 1.2 * steps * pixels_factor # Tope 80s: el slice `large` aplica duration_factor=1.5, asi que 80 -> 120s # solicitados, el cupo diario de un visitante no logueado. return int(min(80, 30 + per_image * n_images)) except Exception: return 60 @spaces.GPU(duration=gpu_duration) def run_lora_multi( prompt_1, prompt_2, prompt_3, prompt_4, negative_prompt, guidance_scale, steps, selected_loras_state, randomize_seed, seed, width, height, quality_multiplier, quantity, history, history_records, loras_list, prompt_enhance=False, progress=gr.Progress(track_tqdm=True), ): if selected_loras_state is None: selected_loras_state = [] loaded_loras = [] for idx, item in enumerate(selected_loras_state): if item[0] is not None: loaded_loras.append((idx, item[0], item[1], item[2])) if not loaded_loras: raise gr.Error("You must select at least one 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.") pipe.unload_lora_weights() adapter_names = [] adapter_weights = [] used_loras_meta = [] for col_idx, image_idx, version_idx, scale in loaded_loras: selected_lora = loras_list[image_idx] if version_idx is not None and "versions" in selected_lora: version_data = selected_lora["versions"][version_idx] lora_path = version_data.get("repo") or selected_lora.get("repo") weight_name = version_data.get("weights", selected_lora.get("weights")) else: lora_path = selected_lora.get("repo") weight_name = selected_lora.get("weights") adapter_name = f"lora_{col_idx}" try: pipe.load_lora_weights(lora_path, weight_name=weight_name, adapter_name=adapter_name) except Exception as e: error_detail = str(e) if len(error_detail) > 300: error_detail = error_detail[:300] + "..." raise gr.Error( f"No se pudo cargar el LoRA '{lora_path}' — probablemente un formato incompatible " f"(ej. LyCORIS/LoKr en vez de LoRA estándar de diffusers). Detalle: {error_detail}" ) print(f"Loaded LoRA: {lora_path} ({weight_name}) as {adapter_name} with scale {scale}") adapter_names.append(adapter_name) adapter_weights.append(scale) used_loras_meta.append({ "repo": lora_path, "weight_name": weight_name, "title": selected_lora.get("title"), "scale": scale, }) pipe.set_adapters(adapter_names, adapter_weights=adapter_weights) # No se fusionan los LoRAs acá. Se probó `fuse_lora()` el 2026-08-01, cuando el transformer # era NF4, y el tiempo total subió de 15 s a 30 s: cada merge tenía que dequantizar el peso # de 4 bits, sumarle el delta y volver a cuantizarlo, por 264 módulos y en cada request. # Ese motivo ya no aplica: el transformer volvió a bf16, donde fusionar sale casi gratis. # Queda sin fusionar porque no se volvió a medir. all_trigger_words = [] for _, image_idx, _, _ in loaded_loras: trigger = loras_list[image_idx].get("trigger_word", "") if trigger: all_trigger_words.append(trigger) combined_trigger = " ".join(all_trigger_words) final_prompts = [] for p in prompts: final_prompts.append(f"{combined_trigger} {p}" if combined_trigger else p) prompts = final_prompts if randomize_seed: seed = random.randint(0, MAX_SEED) multiplier = float(quality_multiplier.replace("x", "")) width = int(width * multiplier) height = int(height * multiplier) real_quantity = int(quantity) + 1 try: if width * height > 1048 * 1048: pipe.vae.enable_tiling() else: pipe.vae.disable_tiling() except Exception as e: print(f"Could not toggle VAE tiling: {e}") if history is None: history = [] if history_records is None: history_records = [] for prompt in prompts: current_seed = seed if prompt_enhance: prompt = rewrite(prompt) for _ in range(real_quantity): generator = torch.Generator(device=device).manual_seed(current_seed) result = pipe( prompt=prompt, negative_prompt=negative_prompt if guidance_scale > 0 else None, num_inference_steps=steps, guidance_scale=guidance_scale, width=width, height=height, num_images_per_prompt=1, generator=generator, ) img = result.images[0] record = { "image": img, "prompt": prompt, "negative_prompt": negative_prompt, "seed": current_seed, "guidance_scale": guidance_scale, "steps": steps, "width": width, "height": height, "loras": used_loras_meta, } history = [(img, str(current_seed))] + history history = history[:24] history_records = [record] + history_records history_records = history_records[:24] yield history, history, history_records, 0, seed current_seed += 100 def get_huggingface_safetensors(link): split_link = link.split("/") if len(split_link) != 2: raise Exception("Invalid Hugging Face repository link format.") model_card = ModelCard.load(link) base_model_tag = model_card.data.get("base_model") models_to_check = base_model_tag if isinstance(base_model_tag, list) else [base_model_tag] if not any(m in ACCEPTABLE_BASE_MODELS for m in models_to_check): raise Exception("Not a Krea-2-Turbo 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): 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 Exception: trigger_word = "" image_url = None return repo_name, repo, safetensors_name, trigger_word, image_url except Exception: 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, loras_list, *args): num_radios = NUM_LORAS radio_vals = args[:num_radios] scale_vals = args[num_radios:num_radios * 2] selected_loras_state = args[-1] loras_list = list(loras_list) if custom_lora: try: title, repo, path, trigger_word, image = check_custom_model(custom_lora) print(f"Loaded custom LoRA: {repo}") card = f'''
Loaded custom LoRA:

{title}

{"Using: "+trigger_word+" as the trigger word" if trigger_word else "No trigger word found. If there's a trigger word, include it in your prompt"}
''' existing_item_index = next((index for (index, item) in enumerate(loras_list) 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} loras_list.append(new_item) existing_item_index = len(loras_list) - 1 md_updates, new_state, scale_updates, del_btn_updates, dropdown_updates, _ = update_slot_with_lora( existing_item_index, radio_vals, scale_vals, selected_loras_state, loras_list ) return ( gr.update(visible=True, value=card), gr.update(visible=True), reload_loras_gallery(loras_list), ) + tuple(md_updates) + (new_state,) + tuple(scale_updates) + tuple(del_btn_updates) + tuple(dropdown_updates) + (loras_list,) 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-Krea-2-Turbo LoRA, this was the issue: {e}") empty_updates = [gr.update()] * num_radios return ( gr.update(visible=True, value="Invalid LoRA: either you entered an invalid link, or a non-Krea-2-Turbo LoRA"), gr.update(visible=True), gr.update(), ) + tuple(empty_updates) + (selected_loras_state,) + tuple(empty_updates) + tuple(empty_updates) + tuple(empty_updates) + (loras_list,) else: empty_updates = [gr.update()] * num_radios return ( gr.update(visible=False), gr.update(visible=False), gr.update(), ) + tuple(empty_updates) + (selected_loras_state,) + tuple(empty_updates) + tuple(empty_updates) + tuple(empty_updates) + (loras_list,) def remove_custom_lora(): return gr.update(visible=False), gr.update(visible=False), gr.update(), "" def reload_loras_gallery(loras_list): gallery_items = [ (item["image"], item.get("title") or item.get("name")) for item in loras_list if item.get("image") ] return gr.update(value=gallery_items) def init(aspect_ratio, loras_list): loras_result = reload_loras_gallery(loras_list) aspect_ratio_result = apply_aspect_ratio(aspect_ratio) return ( *aspect_ratio_result, loras_result, "1", ) def update_slider_state(val, state, idx): new_state = [tuple(item) for item in state] current_image, current_version, _ = new_state[idx] new_state[idx] = (current_image, current_version, float(val)) return new_state def remove_lora(state, idx): new_state = list(state) new_state[idx] = (None, None, 1.0) return ( new_state, gr.update(value=None), gr.update(visible=False, value=1.0), gr.update(value=""), gr.update(visible=False), gr.update(visible=False, value=None, choices=[]), ) def validate_generate_button(state): has_lora = any(item[0] is not None for item in state) return gr.update(interactive=has_lora) def update_slot_with_lora(lora_index, radio_vals, scale_vals, current_state, loras_list): num_radios = NUM_LORAS selected_slot_index = -1 for i, val in enumerate(radio_vals): if val is not None: selected_slot_index = i break md_updates = [gr.update() for _ in range(num_radios)] scale_updates = [gr.update() for _ in range(num_radios)] del_btn_updates = [gr.update() for _ in range(num_radios)] dropdown_updates = [gr.update() for _ in range(num_radios)] new_state = list(current_state) if selected_slot_index != -1 and lora_index is not None: lora = loras_list[lora_index] lora_name = lora["title"] lora_image = lora["image"] versions = lora.get("versions", []) version_index = None version_title = "" if versions: found_best = False version_index = -1 for i, v in enumerate(versions): if v.get("best", False): version_index = i found_best = True break if not found_best: version_index = len(versions) - 1 version_data = versions[version_index] version_title = version_data["title"] version_image = version_data.get("image", lora_image) version_choices = [v["title"] for v in versions] dropdown_updates[selected_slot_index] = gr.update(visible=True, choices=version_choices, value=version_title) else: version_image = lora_image dropdown_updates[selected_slot_index] = gr.update(visible=False, value=None, choices=[]) markdown_content = f"\n\n**{lora_name}**{' ('+version_title+')' if version_title else ''}" md_updates[selected_slot_index] = gr.update(value=markdown_content) scale_updates[selected_slot_index] = gr.update(visible=True) del_btn_updates[selected_slot_index] = gr.update(visible=True) current_scale = scale_vals[selected_slot_index] if len(scale_vals) > selected_slot_index else 1.0 new_state[selected_slot_index] = (lora_index, version_index, current_scale) return md_updates, new_state, scale_updates, del_btn_updates, dropdown_updates, selected_slot_index def on_gallery_select(evt: gr.SelectData): return evt.index def get_selection(evt: gr.SelectData, *args): num_radios = NUM_LORAS radio_vals = args[:num_radios] scale_vals = args[num_radios:num_radios * 2] loras_list = args[-3] current_state = args[-2] md_updates, new_state, scale_updates, del_btn_updates, dropdown_updates, _ = update_slot_with_lora( evt.index, radio_vals, scale_vals, current_state, loras_list ) return md_updates + [new_state] + scale_updates + del_btn_updates + dropdown_updates # -------------------------------------------------------------------------------------- # Canvas de cajas del DSL de grounding # # Portado de `jimmycarter/krea2-turbo-bbox-canvas`. El canvas y el textbox de Prompt 1 son # dos vistas del mismo string: arrastrar una caja reescribe sus coordenadas, y editar el # texto redibuja el canvas. Todo pasa en el navegador — el JS lee y escribe el `