import os import math import inspect import functools from contextlib import contextmanager from contextvars import ContextVar os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True") import re import gc import hashlib import json import struct import tempfile import traceback import urllib.parse import requests import gradio as gr from lora_cpu_picker import rank_prompt_loras, requests_nudity from heretic_lora_picker import rerank_loras from economy_prompt import ( ECONOMY_SPACE, ECONOMY_LABEL, ECONOMY_TOKENS, ECONOMY_NOTE, is_economy, economy_instruction, economy_prompt, economy_status, ) import numpy as np import spaces import torch import random from PIL import Image, ImageDraw, ImageOps from typing import Iterable, Optional from transformers import ( AutoImageProcessor, AutoModelForDepthEstimation, ) from huggingface_hub import hf_hub_download from guidance import guidance_values from safetensors.torch import load_file as safetensors_load_file from gradio.themes import Soft from gradio.themes.utils import colors, fonts, sizes # ============================================================ # Theme # ============================================================ colors.orange_red = colors.Color( name="orange_red", c50="#FFF0E5", c100="#FFE0CC", c200="#FFC299", c300="#FFA366", c400="#FF8533", c500="#FF4500", c600="#E63E00", c700="#CC3700", c800="#B33000", c900="#992900", c950="#802200", ) class OrangeRedTheme(Soft): def __init__( self, *, primary_hue: colors.Color | str = colors.gray, secondary_hue: colors.Color | str = colors.orange_red, neutral_hue: colors.Color | str = colors.slate, text_size: sizes.Size | str = sizes.text_lg, font: fonts.Font | str | Iterable[fonts.Font | str] = ( "Segoe UI", "Arial", "sans-serif", ), font_mono: fonts.Font | str | Iterable[fonts.Font | str] = ( "Cascadia Code", "ui-monospace", "monospace", ), ): super().__init__( primary_hue=primary_hue, secondary_hue=secondary_hue, neutral_hue=neutral_hue, text_size=text_size, font=font, font_mono=font_mono, ) # Native component rules also define their own colors. Keep both theme # branches dark so labels/accordions never fall back to the old light UI. palette = { "body_background_fill": "#131815", "body_text_color": "#edf2ed", "body_text_color_subdued": "#b0bdb2", "background_fill_primary": "#1c2420", "background_fill_secondary": "#232d27", "border_color_primary": "#35423a", "border_color_accent": "#80513c", "color_accent_soft": "#38281f", "code_background_fill": "#171f1a", "error_background_fill": "#3b2020", "error_border_color": "#94594f", "error_text_color": "#ffd0c7", "error_icon_color": "#ff9a8b", "block_background_fill": "#1c2420", "block_border_color": "#35423a", "block_border_width": "1px", "block_label_background_fill": "#232d27", "block_label_border_color": "#617468", "block_label_text_color": "#edf2ed", "block_title_background_fill": "#232d27", "block_title_border_color": "#35423a", "block_title_text_color": "#edf2ed", "block_info_text_color": "#b0bdb2", "accordion_text_color": "#edf2ed", "panel_background_fill": "#232d27", "panel_border_color": "#35423a", "input_background_fill": "#171f1a", "input_background_fill_focus": "#171f1a", "input_background_fill_hover": "#1c2420", "input_border_color": "#617468", "input_border_color_focus": "#ef8158", "input_border_color_hover": "#80513c", "input_placeholder_color": "#b0bdb2", "button_primary_background_fill": "#ef8158", "button_primary_background_fill_hover": "#fa946f", "button_primary_border_color": "#ef8158", "button_primary_border_color_hover": "#fa946f", "button_primary_text_color": "#20150f", "button_primary_text_color_hover": "#20150f", "button_secondary_background_fill": "#1c2420", "button_secondary_background_fill_hover": "#232d27", "button_secondary_border_color": "#617468", "button_secondary_border_color_hover": "#80513c", "button_secondary_text_color": "#edf2ed", "button_secondary_text_color_hover": "#edf2ed", "checkbox_background_color": "#171f1a", "checkbox_background_color_selected": "#ef8158", "checkbox_border_color": "#617468", "checkbox_border_color_selected": "#ef8158", "checkbox_label_background_fill": "#1c2420", "checkbox_label_background_fill_hover": "#232d27", "checkbox_label_background_fill_selected": "#38281f", "checkbox_label_border_color": "#35423a", "checkbox_label_border_color_selected": "#80513c", "checkbox_label_text_color": "#edf2ed", "checkbox_label_text_color_selected": "#edf2ed", "slider_color": "#ef8158", "link_text_color": "#ef8158", "link_text_color_hover": "#fa946f", "table_text_color": "#edf2ed", "table_border_color": "#35423a", "table_even_background_fill": "#1c2420", "table_odd_background_fill": "#232d27", } super().set( **palette, **{f"{key}_dark": value for key, value in palette.items()}, color_accent="#ef8158", block_title_text_weight="600", block_shadow="none", block_shadow_dark="none", button_primary_shadow="none", button_primary_shadow_dark="none", button_large_padding="11px", ) orange_red_theme = OrangeRedTheme() # ============================================================ # Backend: Turbo is the default; legacy preserves the old Space features. # Select QWEN_BACKEND=legacy in Space Variables, then restart to load only it. # The existing qwenimage/ directory is required only by the legacy backend. # ============================================================ BACKEND = os.environ.get("QWEN_BACKEND", "turbo").strip().lower() if BACKEND not in {"turbo", "legacy"}: raise ValueError("QWEN_BACKEND must be 'turbo' or 'legacy'.") IS_TURBO = BACKEND == "turbo" DEFAULT_STEPS = 6 if IS_TURBO else 4 DEFAULT_CFG = 1.0 DEFAULT_NEGATIVE = ( "worst quality, low quality, bad anatomy, bad hands, text, error, missing fingers, " "extra digit, fewer digits, cropped, jpeg artifacts, signature, watermark, username, blurry, " "overexposed, blown highlights, clipped whites, washed out, harsh lighting" ) DEFAULT_NEGATIVE_TEXT = "" if IS_TURBO else DEFAULT_NEGATIVE BASE_MODEL_ID = os.environ.get("BASE_MODEL_ID", "Qwen/Qwen-Image-2.1") TURBO_REPO = os.environ.get("TURBO_REPO", "Viggle/Qwen-Image-2.1-viggle-turbo") TURBO_FILE = os.environ.get( "TURBO_FILE", "Qwen-Image-2.1-viggle-turbo-v0.2.1-6step-lora-r256.safetensors" ) TURBO_ADAPTER = "viggle-turbo-required" DMD2_REPO = "linoyts/Qwen-Image-2.1-DMD2-2steps" DMD2_FILE = "pytorch_lora_weights_v1_5.safetensors" DMD2_ADAPTER = "qwen-dmd2-required" DMD2_SIGMAS = (1.0, 0.5) AIO_REPO_ID = os.environ.get("AIO_REPO_ID", "prithivMLmods/Qwen-Image-Edit-Rapid-AIO-V19") MODEL_LABEL = "Qwen Image 2.1 · Viggle Turbo" if IS_TURBO else "Qwen Edit 2511 · Rapid AIO" HF_TOKEN = os.environ.get("HF_TOKEN") device = torch.device("cuda" if torch.cuda.is_available() else "cpu") dtype = torch.bfloat16 ATTENTION_BACKEND = "sdpa" OP_QWEN, OP_FACE, OP_MOSS = "Qwen Edit", "Face Swap", "MOSS Edit (i2i)" OP_OUTPAINT = "Qwen Outpaint" OP_DETAIL = "Detail Enhancer" OP_RELIGHT, OP_CAMERA = "Relight", "Camera Angle" OPERATIONS = [OP_QWEN, OP_FACE, OP_MOSS, OP_OUTPAINT, OP_DETAIL, OP_RELIGHT, OP_CAMERA] SINGLE_SOURCE_OPERATIONS = (OP_OUTPAINT, OP_DETAIL, OP_RELIGHT, OP_CAMERA) QWEN_SHARED_MODES = (OP_QWEN, OP_RELIGHT, OP_CAMERA) PUBLIC_TITLE = "Qwen 2.1 Turbo Studio | Edit, Face Swap, MOSS, Outpaint, Detail, Relight, Camera Angle" QWEN_TURBO, QWEN_BASE = "Turbo (6 steps)", "Base (30 steps, no Viggle)" QWEN_DMD2 = "DMD2 v1.5 (2 steps)" QWEN_MODES = (QWEN_TURBO, QWEN_DMD2, QWEN_BASE) # Camera Angle: the Multiple Angles author's native recipe (see camera_backend). CAMERA_STEPS, CAMERA_MIN_STEPS, CAMERA_MAX_STEPS = 40, 10, 50 CAMERA_STRENGTH = 0.5 QWEN_MODE_KEYS = {OP_QWEN: "qwen_mode", OP_RELIGHT: "qwen_mode", OP_CAMERA: "qwen_mode", OP_FACE: "face_mode", OP_OUTPAINT: "outpaint_mode", OP_DETAIL: "detail_mode"} DMD2_DEMO = "https://huggingface.co/spaces/linoyts/qwen-image-2-1-realtime" FACE_TURBO, FACE_BASE = "Turbo (6 steps)", "Base (30 steps)" OUTPAINT_TURBO, OUTPAINT_BASE = "Turbo (6 steps)", "Base (25 steps)" from detail_backend import MODE_TURBO as DETAIL_TURBO, MODE_BASE as DETAIL_BASE _ACTIVE_OPERATION = ContextVar("studio_operation", default=OP_QWEN) _CATALOG_WRITE_TOKEN = ContextVar("catalog_write_token", default=None) def operation_scoped(fn, *, write_token=False): """Bind one callback's catalogue without sharing mode/credentials across sessions.""" @functools.wraps(fn) def wrapped(operation, *args, **kwargs): mode_token = _ACTIVE_OPERATION.set(operation) credential = args[0] if write_token else None auth_token = _CATALOG_WRITE_TOKEN.set(credential) try: return fn(*(args[1:] if write_token else args), **kwargs) finally: _CATALOG_WRITE_TOKEN.reset(auth_token) _ACTIVE_OPERATION.reset(mode_token) parameters = [inspect.Parameter("operation", inspect.Parameter.POSITIONAL_OR_KEYWORD)] if write_token: parameters.append(inspect.Parameter("catalog_write_token", inspect.Parameter.POSITIONAL_OR_KEYWORD)) wrapped.__signature__ = inspect.signature(fn).replace(parameters=parameters + list(inspect.signature(fn).parameters.values())) return wrapped def turbo_sigmas(steps): """Viggle's raw schedule: extra steps subdivide only the highest-noise segment.""" steps = int(steps) if not 4 <= steps <= 8: raise ValueError("Turbo supports 4–8 steps here; 6 is the recommended default.") if steps == 4: return [1.0, 0.75, 0.5, 0.25] return [1.0 - 0.125 * i / (steps - 4) for i in range(steps - 4)] + [0.875, 0.75, 0.5, 0.25] def _use_sdpa_attention(): global ATTENTION_BACKEND if not IS_TURBO: from qwenimage.transformer_qwenimage import QwenDoubleStreamAttnProcessor2_0 pipe.transformer.set_attn_processor(QwenDoubleStreamAttnProcessor2_0()) ATTENTION_BACKEND = "sdpa" def _is_flash_attention_kernel_error(exc): message = "".join(traceback.format_exception(type(exc), exc, exc.__traceback__)).lower() return any(key in message for key in ("flash-attn", "flash_attn", "no kernel image is available")) if IS_TURBO: from diffusers import QwenImage21Pipeline, FlowMatchEulerDiscreteScheduler pipe = QwenImage21Pipeline.from_pretrained(BASE_MODEL_ID, dtype=dtype, token=HF_TOKEN) BASE_SCHEDULER_CONFIG = dict(pipe.scheduler.config) # Never fuse this adapter into bf16 weights or disable it when optional LoRAs are cleared. pipe.load_lora_weights(TURBO_REPO, weight_name=TURBO_FILE, adapter_name=TURBO_ADAPTER, token=HF_TOKEN) pipe.set_adapters([TURBO_ADAPTER], adapter_weights=[1.0]) pipe.scheduler = FlowMatchEulerDiscreteScheduler.from_config( pipe.scheduler.config, shift_terminal=None ) pipe.to(device) pipe.vae.disable_tiling() # Same Conv3d -> matmul optimization used by the official Viggle Space. # It avoids the very slow bf16 vision-patch Conv3d kernel on ZeroGPU. _patch_embed = pipe.text_encoder.model.visual.patch_embed def _patch_embed_forward(hidden_states): proj = _patch_embed.proj weight = proj.weight.reshape(proj.weight.shape[0], -1) result = hidden_states.to(weight.dtype).flatten(1) @ weight.T return result if proj.bias is None else result + proj.bias _patch_embed.forward = _patch_embed_forward else: try: from qwenimage.pipeline_qwenimage_edit_plus import QwenImageEditPlusPipeline from qwenimage.transformer_qwenimage import QwenImageTransformer2DModel except ImportError as error: raise RuntimeError( "Legacy mode requires the qwenimage/ folder from your original Space. " "Restore that folder or set QWEN_BACKEND=turbo." ) from error pipe = QwenImageEditPlusPipeline.from_pretrained( "Qwen/Qwen-Image-Edit-2511", transformer=QwenImageTransformer2DModel.from_pretrained( AIO_REPO_ID, torch_dtype=dtype, device_map="cuda" ), torch_dtype=dtype, ).to(device) _use_sdpa_attention() if os.environ.get("ENABLE_FA3", "").strip().lower() in {"1", "true", "yes", "on"}: try: from qwenimage.qwen_fa3_processor import QwenDoubleStreamAttnProcessorFA3 pipe.transformer.set_attn_processor(QwenDoubleStreamAttnProcessorFA3()) ATTENTION_BACKEND = "fa3" except Exception as error: print(f"FA3 unavailable; keeping SDPA: {error}") _use_sdpa_attention() print(f"Backend: {MODEL_LABEL}; device={device}; torch={torch.__version__}") MAX_SEED = np.iinfo(np.int32).max # ============================================================ # VAE tiling toggle (UI-controlled; OFF by default) # ============================================================ def _apply_vae_tiling(enabled: bool): """ Toggle VAE tiling on the global pipeline. This does NOT require a Space restart; it applies to the next pipe(...) call. Note: this is global process state, so concurrent users could flip it between runs. """ if IS_TURBO: # Never tile reference encoding. Decode-only tiling is applied around pipe(...). pipe.vae.disable_tiling() return try: if enabled: if hasattr(pipe, "enable_vae_tiling"): pipe.enable_vae_tiling() print("✅ VAE tiling ENABLED (per UI).") elif hasattr(pipe, "vae") and hasattr(pipe.vae, "enable_tiling"): pipe.vae.enable_tiling() print("✅ VAE tiling ENABLED via pipe.vae.enable_tiling() (per UI).") else: print("⚠️ No enable_vae_tiling()/vae.enable_tiling() found; cannot enable.") else: if hasattr(pipe, "disable_vae_tiling"): pipe.disable_vae_tiling() print("🛑 VAE tiling DISABLED (per UI).") elif hasattr(pipe, "vae") and hasattr(pipe.vae, "disable_tiling"): pipe.vae.disable_tiling() print("🛑 VAE tiling DISABLED via pipe.vae.disable_tiling() (per UI).") else: # If no disable method exists, we leave current state unchanged. print("⚠️ No disable_vae_tiling()/vae.disable_tiling() found; leaving current state unchanged.") except Exception as e: print(f"⚠️ VAE tiling toggle failed: {e}") @contextmanager def decode_tiling(enabled): """Keep reference encoding untiled; allow optional tiling only during decode.""" if not IS_TURBO or not enabled: yield return original_decode = pipe.vae.decode def tiled_decode(*args, **kwargs): pipe.vae.enable_tiling() try: return original_decode(*args, **kwargs) finally: pipe.vae.disable_tiling() pipe.vae.decode = tiled_decode try: yield finally: pipe.vae.decode = original_decode pipe.vae.disable_tiling() # ============================================================ # Derived conditioning (Transformers): Depth # ============================================================ # Depth uses Depth Anything V2 Small (Transformers-compatible): # https://huggingface.co/depth-anything/Depth-Anything-V2-Small-hf DEPTH_MODEL_ID = "depth-anything/Depth-Anything-V2-Small-hf" # Lazy cache keyed by device string ("cpu" / "cuda") _DEPTH_CACHE = {} def _derived_device(use_gpu: bool) -> torch.device: return torch.device("cuda" if (use_gpu and torch.cuda.is_available()) else "cpu") def _load_depth_models(dev: torch.device): key = str(dev) if key in _DEPTH_CACHE: return _DEPTH_CACHE[key] proc = AutoImageProcessor.from_pretrained(DEPTH_MODEL_ID) model = AutoModelForDepthEstimation.from_pretrained(DEPTH_MODEL_ID).to(dev) model.eval() _DEPTH_CACHE[key] = (proc, model) return _DEPTH_CACHE[key] @torch.inference_mode() def make_depth_map(img: Image.Image, *, use_gpu: bool) -> Image.Image: dev = _derived_device(use_gpu) proc, model = _load_depth_models(dev) w, h = img.size inputs = proc(images=img.convert("RGB"), return_tensors="pt").to(dev) outputs = model(**inputs) predicted = outputs.predicted_depth # [B, H, W] depth = torch.nn.functional.interpolate( predicted.unsqueeze(1), size=(h, w), mode="bicubic", align_corners=False, ).squeeze(1)[0] depth = depth - depth.min() depth = depth / (depth.max() + 1e-8) depth = (depth * 255.0).clamp(0, 255).to(torch.uint8).cpu().numpy() return Image.fromarray(depth).convert("RGB") # ============================================================ # LoRA adapters + presets # ============================================================ NONE_LORA = "None" # The bundled catalogues. Kept here rather than in a private repo by choice; note that every # name below is visible to anyone who opens this file on the Hub. ADAPTER_SPECS = { "Consistance": { "type": "single", "repo": "Pr0f3ssi0n4ln00b/QIE_2511_Consistency_Lora", "weights": "qe2511_consis_alpha_patched.safetensors", "adapter_name": "Consistency", "strength": 0.6 }, "Semirealistic-photo-detailer": { "type": "single", "repo": "rzgar/Qwen-Image-Edit-semi-realistic-detailer", "weights": "Qwen-Image-Edit-Anime-Semi-Realistic-Detailer-v1.safetensors", "adapter_name": "semirealistic", "strength": 1.0 }, "AnyPose": { "type": "package", "requires_two_images": True, "image2_label": "Upload Pose Reference (Image 2)", "parts": [ { "repo": "lilylilith/AnyPose", "weights": "2511-AnyPose-base-000006250.safetensors", "adapter_name": "anypose-base", "strength": 0.7 }, { "repo": "lilylilith/AnyPose", "weights": "2511-AnyPose-helper-00006000.safetensors", "adapter_name": "anypose-helper", "strength": 0.7 } ] }, "Any2Real_2601": { "type": "single", "repo": "lrzjason/Anything2Real_2601", "weights": "anything2real_2601_A_final_patched.safetensors", "adapter_name": "photoreal", "strength": 1.0 }, "Hyperrealistic-Portrait": { "type": "single", "repo": "prithivMLmods/Qwen-Image-Edit-2511-Hyper-Realistic-Portrait", "weights": "HRP_20.safetensors", "adapter_name": "HRPortrait", "strength": 1.0 }, "Ultrarealistic-Portrait": { "type": "single", "repo": "prithivMLmods/Qwen-Image-Edit-2511-Ultra-Realistic-Portrait", "weights": "URP_20.safetensors", "adapter_name": "URPortrait", "strength": 1.0 }, "BFS-Best-FaceSwap": { "type": "single", "requires_two_images": True, "image2_label": "Upload Head/Face Donor (Image 2)", "repo": "Alissonerdx/BFS-Best-Face-Swap", "weights": "bfs_head_v5_2511_original.safetensors", "adapter_name": "BFS-Best-Faceswap", "strength": 1.0, "needs_alpha_fix": True }, "BFS-Best-FaceSwap-merge": { "type": "single", "requires_two_images": True, "image2_label": "Upload Head/Face Donor (Image 2)", "repo": "Alissonerdx/BFS-Best-Face-Swap", "weights": "bfs_head_v5_2511_merged_version_rank_32_fp32.safetensors", "adapter_name": "BFS-Best-Faceswap-merge", "strength": 1.1, "needs_alpha_fix": True }, "F2P": { "type": "single", "repo": "DiffSynth-Studio/Qwen-Image-Edit-F2P", "weights": "edit_0928_lora_step40000.safetensors", "adapter_name": "F2P", "strength": 1.0 }, "Multiple-Angles": { "type": "single", "repo": "dx8152/Qwen-Edit-2509-Multiple-angles", "weights": "镜头转换.safetensors", "adapter_name": "multiple-angles", "strength": 1.0 }, "Light-Restoration": { "type": "single", "repo": "dx8152/Qwen-Image-Edit-2509-Light_restoration", "weights": "移除光影.safetensors", "adapter_name": "light-restoration", "strength": 1.0 }, "Relight": { "type": "single", "repo": "dx8152/Qwen-Image-Edit-2509-Relight", "weights": "Qwen-Edit-Relight.safetensors", "adapter_name": "relight", "strength": 1.0 }, "Multi-Angle-Lighting": { "type": "single", "repo": "dx8152/Qwen-Edit-2509-Multi-Angle-Lighting", "weights": "多角度灯光-251116.safetensors", "adapter_name": "multi-angle-lighting", "strength": 1.0 }, "Edit-Skin": { "type": "single", "repo": "tlennon-ie/qwen-edit-skin", "weights": "qwen-edit-skin_1.1_000002750.safetensors", "adapter_name": "edit-skin", "strength": 1.0 }, "Next-Scene": { "type": "single", "repo": "lovis93/next-scene-qwen-image-lora-2509", "weights": "next-scene_lora-v2-3000.safetensors", "adapter_name": "next-scene", "strength": 1.0 }, "Flat-Log": { "type": "single", "repo": "tlennon-ie/QwenEdit2509-FlatLogColor", "weights": "QwenEdit2509-FlatLogColor.safetensors", "adapter_name": "flat-log", "strength": 1.0 }, "Upscale-Image": { "type": "single", "repo": "vafipas663/Qwen-Edit-2509-Upscale-LoRA", "weights": "qwen-edit-enhance_64-v3_000001000.safetensors", "adapter_name": "upscale-image", "strength": 1.0 }, "Upscale2K": { "type": "single", "repo": "valiantcat/Qwen-Image-Edit-2509-Upscale2K", "weights": "qwen_image_edit_2509_upscale.safetensors", "adapter_name": "upscale-2k", "strength": 1.0, "target_long_edge": 2048 }, "Photo-to-Anime": { "repo": "autoweeb/Qwen-Image-Edit-2509-Photo-to-Anime", "weights": "Qwen-Image-Edit-2509-Photo-to-Anime_000001000.safetensors", "adapter_name": "photo-to-anime" }, "Anime-V2": { "repo": "prithivMLmods/Qwen-Image-Edit-2511-Anime", "weights": "Qwen-Image-Edit-2511-Anime-2000.safetensors", "adapter_name": "anime-v2" }, "Light-Migration": { "repo": "dx8152/Qwen-Edit-2509-Light-Migration", "weights": "参考色调.safetensors", "adapter_name": "light-migration" }, "Style-Transfer": { "repo": "zooeyy/Style-Transfer", "weights": "Style Transfer-Alpha-V0.1.safetensors", "adapter_name": "style-transfer" }, "Manga-Tone": { "repo": "nappa114514/Qwen-Image-Edit-2509-Manga-Tone", "weights": "tone001.safetensors", "adapter_name": "manga-tone" }, "Anything2Real": { "repo": "lrzjason/Anything2Real_2601", "weights": "anything2real_2601.safetensors", "adapter_name": "anything2real" }, "Fal-Multiple-Angles": { "repo": "fal/Qwen-Image-Edit-2511-Multiple-Angles-LoRA", "weights": "qwen-image-edit-2511-multiple-angles-lora.safetensors", "adapter_name": "fal-multiple-angles" }, "Polaroid-Photo": { "repo": "prithivMLmods/Qwen-Image-Edit-2511-Polaroid-Photo", "weights": "Qwen-Image-Edit-2511-Polaroid-Photo.safetensors", "adapter_name": "polaroid-photo" }, "Unblur-Anything": { "repo": "prithivMLmods/Qwen-Image-Edit-2511-Unblur-Upscale", "weights": "Qwen-Image-Edit-Unblur-Upscale_15.safetensors", "adapter_name": "unblur-anything" }, "Midnight-Noir-Eyes-Spotlight": { "repo": "prithivMLmods/Qwen-Image-Edit-2511-Midnight-Noir-Eyes-Spotlight", "weights": "Qwen-Image-Edit-2511-Midnight-Noir-Eyes-Spotlight.safetensors", "adapter_name": "midnight-noir-eyes-spotlight" }, "Hyper-Realistic-Portrait": { "repo": "prithivMLmods/Qwen-Image-Edit-2511-Hyper-Realistic-Portrait", "weights": "HRP_20.safetensors", "adapter_name": "hyper-realistic-portrait" }, "Ultra-Realistic-Portrait": { "repo": "prithivMLmods/Qwen-Image-Edit-2511-Ultra-Realistic-Portrait", "weights": "URP_20.safetensors", "adapter_name": "ultra-realistic-portrait" }, "Pixar-Inspired-3D": { "repo": "prithivMLmods/Qwen-Image-Edit-2511-Pixar-Inspired-3D", "weights": "PI3_20.safetensors", "adapter_name": "pi3" }, "Noir-Comic-Book": { "repo": "prithivMLmods/Qwen-Image-Edit-2511-Noir-Comic-Book-Panel", "weights": "Noir-Comic-Book-Panel_20.safetensors", "adapter_name": "ncb" }, "Any-light": { "repo": "lilylilith/QIE-2511-MP-AnyLight", "weights": "QIE-2511-AnyLight_.safetensors", "adapter_name": "any-light" }, "Studio-DeLight": { "repo": "prithivMLmods/QIE-2511-Studio-DeLight", "weights": "QIE-2511-Studio-DeLight-5000.safetensors", "adapter_name": "studio-delight" } } # Adapters that read their second reference as an instruction rather than as picture data: # for those the extra references are safer kept conditioning-only. CONDITIONING_ONLY = { "BFS-Best-FaceSwap", "BFS-Best-FaceSwap-merge", "AnyPose" } # The prompt each bundled style fills in when the box is empty. LORA_PRESET_PROMPTS = { "Any2Real_2601": "change the picture 1 to realistic photograph", "Semirealistic-photo-detailer": "transform the image to semi-realistic image", "AnyPose": "Make the person in image 1 do the exact same pose of the person in image 2. Changing the style and background of the image of the person in image 1 is undesirable, so don't do it. The new pose should be pixel accurate to the pose we are trying to copy. The position of the arms and head and legs should be the same as the pose we are trying to copy. Change the field of view and angle to match exactly image 2. Head tilt and eye gaze pose should match the person in image 2.", "Hyperrealistic-Portrait": "Transform the image into an ultra-realistic photorealistic portrait with strict identity preservation, facing straight to the camera. Enhance pore-level skin textures, realistic moisture effects, and natural wet hair clumping against the skin. Apply cool-toned soft-box lighting with subtle highlights and shadows, maintain realistic green-hazel eye catchlights without synthetic gloss, and preserve soft natural lip texture. Use shallow depth of field with a clean bokeh background, an 85mm macro photographic look, and raw photo grading without retouching to maintain realism and original details.", "Ultrarealistic-Portrait": "Transform the image into an ultra-realistic glamour portrait while strictly preserving the subject’s identity. Apply a close-up composition with a slight head tilt and a hand near the face, enhance cinematic directional lighting with dramatic fashion-style highlights, and refine makeup details including glowing skin, glossy lips, luminous highlighter, and defined eyes. Increase skin realism with detailed epidermal textures such as micropores, microhairs, subtle oil sheen, natural highlights, soft wrinkles, and subsurface scattering. Maintain a luxury fashion-magazine look in a 9:16 aspect ratio, preserving realism, facial structure, and original details without over-smoothing or retouching.", "Upscale2K": "Upscale this picture to 4K resolution.", "BFS-Best-FaceSwap": "head_swap: start with Picture 1 as the base image, keeping its lighting, environment, and background. remove the head from Picture 1 completely and replace it with the head from Picture 2, strictly preserving the hair, eye color, and nose structure of Picture 2. copy the eye direction, head rotation, and micro-expressions from Picture 1. high quality, sharp details, 4k", "BFS-Best-FaceSwap-merge": "head_swap: start with Picture 1 as the base image, keeping its lighting, environment, and background. remove the head from Picture 1 completely and replace it with the head from Picture 2, strictly preserving the hair, eye color, and nose structure of Picture 2. copy the eye direction, head rotation, and micro-expressions from Picture 1. high quality, sharp details, 4k" } # ============================================================ # Fast (step-distilled) LoRAs # ============================================================ # Lightning adapters from lightx2v. They cut the step count down to 4-8. The Rapid AIO checkpoint # already carries a distillation of its own, so these are optional - reach for one when a style # adapter fights the merge and the output goes soft at 4 steps. NO_FAST_LORA = "None (the AIO merge is already distilled)" FAST_LORAS = { "\u26a1 2511 Lightning \u00b7 4 steps (bf16, 850 MB)": { "repo": "lightx2v/Qwen-Image-Edit-2511-Lightning", "weights": "Qwen-Image-Edit-2511-Lightning-4steps-V1.0-bf16.safetensors", "adapter_name": "fast-2511-4-bf16", "steps": 4, }, "\u26a1 2511 Lightning \u00b7 8 steps (bf16, 850 MB)": { "repo": "lightx2v/Qwen-Image-Edit-2511-Lightning", "weights": "Qwen-Image-Edit-2511-Lightning-8steps-V1.0-bf16.safetensors", "adapter_name": "fast-2511-8-bf16", "steps": 8, }, "\u26a1 2511 Lightning \u00b7 4 steps (fp32, 1.7 GB)": { "repo": "lightx2v/Qwen-Image-Edit-2511-Lightning", "weights": "Qwen-Image-Edit-2511-Lightning-4steps-V1.0-fp32.safetensors", "adapter_name": "fast-2511-4-fp32", "steps": 4, }, "\u26a1 2511 Lightning \u00b7 8 steps (fp32, 1.7 GB)": { "repo": "lightx2v/Qwen-Image-Edit-2511-Lightning", "weights": "Qwen-Image-Edit-2511-Lightning-8steps-V1.0-fp32.safetensors", "adapter_name": "fast-2511-8-fp32", "steps": 8, }, "\u26a1 2509 Lightning \u00b7 4 steps (bf16)": { "repo": "lightx2v/Qwen-Image-Lightning", "weights": "Qwen-Image-Edit-2509/Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors", "adapter_name": "fast-2509-4-bf16", "steps": 4, }, "\u26a1 2509 Lightning \u00b7 8 steps (bf16)": { "repo": "lightx2v/Qwen-Image-Lightning", "weights": "Qwen-Image-Edit-2509/Qwen-Image-Edit-2509-Lightning-8steps-V1.0-bf16.safetensors", "adapter_name": "fast-2509-8-bf16", "steps": 8, }, "\u26a1 Edit v1 Lightning \u00b7 4 steps (bf16)": { "repo": "lightx2v/Qwen-Image-Lightning", "weights": "Qwen-Image-Edit-Lightning-4steps-V1.0-bf16.safetensors", "adapter_name": "fast-edit1-4-bf16", "steps": 4, }, "\u26a1 Edit v1 Lightning \u00b7 8 steps (bf16)": { "repo": "lightx2v/Qwen-Image-Lightning", "weights": "Qwen-Image-Edit-Lightning-8steps-V1.0-bf16.safetensors", "adapter_name": "fast-edit1-8-bf16", "steps": 8, }, } FAST_LORA_CHOICES = [NO_FAST_LORA] + list(FAST_LORAS.keys()) # ------------------------------------------------------------------------------------------------ # Minor-safety check # ------------------------------------------------------------------------------------------------ # One absolute line, checked before anything else runs: no request that asks to make a person a # child. Everything else in this Space is a matter of taste and of the visitor's own responsibility; # this is not, and it is the one thing that ends an account rather than earning a warning label. # # Deliberately blunt. A word list plus an age test will refuse some innocent sentences - a lens # called "child" or a period drama - and that is the right trade: a false refusal costs one prompt, # a miss costs everything. The check runs inside the generating function rather than on a button, so # an API or MCP call cannot walk around it. _MINOR_WORDS = ( r"child(?:ren|ish|like)?", r"kid|kids", r"toddler", r"infant", r"baby|babies", r"pre[- ]?teen", r"teen(?:s|age|ager|aged)?", r"underage", r"minors?", r"school ?girl", r"school ?boy", r"schoolkid", r"kindergarten", r"elementary school", r"middle school", r"grade school", r"primary school", r"pupil", r"loli(?:ta|con)?", r"shota(?:con)?", r"jailbait", r"little (?:girl|boy)", r"young(?:er)? (?:girl|boy|child)", r"small child", r"prepubescent", r"pubescent", r"adolescent", r"juvenile", ) _MINOR_RE = re.compile(r"\b(?:" + "|".join(_MINOR_WORDS) + r")\b", re.IGNORECASE) # "7 years old", "aged 12", "12yo", "12 y/o" - anything under eighteen. _AGE_RE = re.compile( r"\b(?:aged\s*)?(\d{1,2})\s*(?:years?[- ]old|yo\b|y/o\b|yrs?[- ]old)|" r"\baged?\s+(\d{1,2})\b", re.IGNORECASE, ) def check_prompt(text): """Refuse a request that asks for a minor. Raises; never returns False.""" text = str(text or "") hit = _MINOR_RE.search(text) if not hit: for match in _AGE_RE.finditer(text): age = next((int(g) for g in match.groups() if g), None) if age is not None and age < 18: hit = match break if hit: print(f"[refused] minor-safety check matched {hit.group(0)!r}", flush=True) raise gr.Error( "This request was refused: it asks for a minor, or for someone to be made younger or " "child-like. That is not allowed here under any framing, and the check is deliberately " "broad - if your prompt was innocent, reword it without those words." ) # ============================================================ # CivitAI: downloading, searching # ============================================================ CIVITAI_HOSTS = ("civitai.com", "civitai.red", "civitai.green", "civitai.work") # Which host answers the search. `.red` is a mirror of the same API and carries entries the main # domain hides, so it is asked first and `.com` is the fallback. Set CIVITAI_API_HOST to pin one. # Adult entries are returned to an authenticated caller only, whichever host answers: without # CIVITAI_TOKEN the X / XXX levels are simply absent from the results. CIVITAI_API_HOSTS = [h for h in (os.environ.get("CIVITAI_API_HOST", "").strip(), "civitai.red", "civitai.com") if h] CIVITAI_DOWNLOAD_RE = re.compile(r"/api/download/models/(\d+)") def is_direct_link(text): text = (text or "").strip().strip('"').strip("'") if not text.startswith(("http://", "https://")): return False host = (urllib.parse.urlparse(text).hostname or "").lower() return not host.endswith("huggingface.co") def _civitai_alternatives(url): """The same download through each CivitAI domain in turn. They mirror one another, and one of them will sometimes answer a datacentre address with a Cloudflare challenge while another does not - which is what a Space is, so this is not a rare case.""" yield url host = (urllib.parse.urlparse(url).hostname or "").lower() if any(host.endswith(known) for known in CIVITAI_HOSTS): for other in CIVITAI_HOSTS: if not host.endswith(other): yield url.replace(host, other, 1) def download_direct_lora(url): """Fetch a `.safetensors` from a plain link and return the local path. Cached by URL.""" url = url.strip().strip('"').strip("'") host = (urllib.parse.urlparse(url).hostname or "").lower() request_url = url token = os.environ.get("CIVITAI_TOKEN", "").strip() if token and any(host.endswith(known) for known in CIVITAI_HOSTS) and "token=" not in url: request_url = url + ("&" if "?" in url else "?") + f"token={token}" cache_dir = os.path.join(tempfile.gettempdir(), "url-loras") os.makedirs(cache_dir, exist_ok=True) cached = os.path.join(cache_dir, hashlib.sha256(url.encode()).hexdigest()[:16] + ".safetensors") if os.path.exists(cached) and os.path.getsize(cached) > 1_000_000: return cached response, last = None, None for candidate in _civitai_alternatives(url): candidate_host = (urllib.parse.urlparse(candidate).hostname or "").lower() attempt_url = candidate if token and any(candidate_host.endswith(k) for k in CIVITAI_HOSTS) and "token=" not in candidate: attempt_url = candidate + ("&" if "?" in candidate else "?") + f"token={token}" try: attempt = requests.get(attempt_url, stream=True, timeout=180, headers={"User-Agent": "Mozilla/5.0"}) attempt.raise_for_status() except Exception as failure: # Not quoting the exception: requests puts the URL in its message, and the URL carries # the token. last = f"{type(failure).__name__} from {candidate_host}" print(f"[lora] {last}; trying another CivitAI domain") continue if "text/html" in (attempt.headers.get("content-type") or "").lower(): last = f"a web page instead of a file from {candidate_host}" print(f"[lora] {last}; trying another CivitAI domain") continue response = attempt break if response is None: raise gr.Error( f"Could not fetch that link ({last}). CivitAI sometimes puts a Cloudflare challenge in " "front of a datacentre address, and a gated model needs CIVITAI_TOKEN under Settings → " "Variables and secrets. Downloading the file yourself and uploading it always works." ) written = 0 with open(cached, "wb") as handle: for chunk in response.iter_content(chunk_size=1 << 20): if chunk: handle.write(chunk) written += len(chunk) if written < 1_000_000: os.remove(cached) raise gr.Error("That link returned only a few kilobytes - a login or error page, not weights.") with open(cached, "rb") as handle: length = struct.unpack("**{base}** · {size:.0f} MB · {downloads} downloads · by {creator}") if words: line += f" · triggers: {', '.join(words[:5])}" lines.append(line + "") if not choices: return "Found models, but none with a `.safetensors` file.", gr.update(choices=[], value=None), {} body = '
\n\n' + " \n".join(lines[:40]) + "\n\n
" return body, gr.update(choices=choices, value=choices[0]), mapping CIVITAI_DOWNLOAD_RE = re.compile(r"/api/download/models/(\d+)") _CIVITAI_DETAILS: dict = {} def civitai_details(version_id: str, file_id: str = ""): """`(label, trigger words)` for a download link, from the public model-versions endpoint. The number in a download URL is the *model version* id, so one lookup gives the title, the version, the file behind `fileId`, and the words the adapter was trained on. Cached in-process.""" key = (version_id, file_id) if key in _CIVITAI_DETAILS: return _CIVITAI_DETAILS[key] headers = {"User-Agent": "Mozilla/5.0"} token = os.environ.get("CIVITAI_TOKEN", "").strip() if token: headers["Authorization"] = f"Bearer {token}" data = None for host in CIVITAI_API_HOSTS: try: response = requests.get(f"https://{host}/api/v1/model-versions/{version_id}", headers=headers, timeout=20) response.raise_for_status() data = response.json() break except Exception: continue if not data: return f"CivitAI {version_id} (name unavailable)", [] model_name = (data.get("model") or {}).get("name") or f"model {data.get('modelId', '?')}" label = f"{model_name} · {data.get('name') or ''}".strip(" ·") if file_id: for entry in data.get("files") or []: if str(entry.get("id")) == str(file_id): label += f" · {entry.get('name', '')}" break result = (label, [word for word in (data.get("trainedWords") or []) if word]) _CIVITAI_DETAILS[key] = result return result def describe_lora(reference: str): """A readable line for whatever is in a slot: a CivitAI link becomes its real title.""" reference = (reference or "").strip() if not reference: return "", [] match = CIVITAI_DOWNLOAD_RE.search(reference) if match: file_id = reference.split("fileId=", 1)[1].split("&")[0] if "fileId=" in reference else "" return civitai_details(match.group(1), file_id) if reference.startswith(("http://", "https://")): return os.path.basename(reference.split("?")[0]) or reference, [] return reference, [] def identify_loras(*references): """Name every filled slot. A link is looked up; anything else is shown as typed.""" lines = [] for index, reference in enumerate(references, start=1): reference = (reference or "").strip() if not reference: continue label, words = describe_lora(reference) line = f"**{index}.** {label}" if words: line += f" \ntrigger words: {', '.join(words[:8])}" lines.append(line) return " \n".join(lines) if lines else "Nothing in the slots yet." def put_in_slot(label, mapping, slot): """Write the chosen result's link into one lora repo box, leaving the others alone.""" updates = [gr.update() for _ in range(3)] url = (mapping or {}).get(label) if not url: return [*updates, "Search and pick a file first."] index = int(str(slot).split()[-1]) - 1 updates[index] = gr.update(value=url) return [*updates, f"**Put into {slot}** — {label}"] # Track what is currently loaded in memory (adapter_name values) LOADED_ADAPTERS = {TURBO_ADAPTER} if IS_TURBO else set() LORA_PREFETCHED = {} # Maps a user LoRA reference to the adapter name it was loaded under. USER_ADAPTER_NAMES = {} _HF_URL_RE = re.compile( r"^https?://huggingface\.co/(?P[^/]+/[^/]+)/(?:blob|resolve)/[^/]+/(?P.+?)(?:\?.*)?$" ) def _parse_user_lora_reference(reference: str): """`owner/repo`, `owner/repo/file.safetensors`, or a Hugging Face file URL -> `(repo, weight_name)`. The file name is resolved from the repo listing when only a repo was given.""" reference = str(reference or "").strip().rstrip("/") match = _HF_URL_RE.match(reference) if match: return match.group("repo"), urllib.parse.unquote(match.group("path")) if reference.startswith("http"): raise gr.Error(f"That address is not a recognisable Hugging Face file URL: `{reference}`") parts = [part for part in reference.split("/") if part] if len(parts) >= 3 and parts[-1].endswith(".safetensors"): return "/".join(parts[:2]), "/".join(parts[2:]) if len(parts) != 2: raise gr.Error( f"`{reference}` is not an `owner/repo`, an `owner/repo/file.safetensors`, or a Hugging Face URL." ) from huggingface_hub import list_repo_files try: files = [name for name in list_repo_files(reference) if name.endswith(".safetensors")] except Exception as error: raise gr.Error(f"Cannot read `{reference}`: {error}") if not files: raise gr.Error(f"`{reference}` holds no `.safetensors` file.") if len(files) > 1: listed = ", ".join(files[:8]) + (" …" if len(files) > 8 else "") raise gr.Error( f"`{reference}` holds several files. Write `{reference}/name.safetensors`. Available: {listed}" ) return reference, files[0] def _load_local_lora(path: str, adapter_name: str): """An uploaded `.safetensors`, with the same key repair the bundled adapters get.""" folder = os.path.dirname(path) or "." if IS_TURBO: load_turbo_lora_weights(path, adapter_name) return try: pipe.load_lora_weights(folder, weight_name=os.path.basename(path), adapter_name=adapter_name) return except Exception as first_error: print(f"[user lora] normal load failed ({first_error}); repairing keys") sd = safetensors_load_file(path) sd = _inject_missing_alpha_keys(sd) sd, _ = _filter_to_diffusers_lora_keys(sd) sd = _duplicate_stripped_prefix_keys(sd) if not sd: raise gr.Error(f"No usable LoRA keys in `{os.path.basename(path)}`.") pipe.load_lora_weights(sd, adapter_name=adapter_name) def _ensure_user_lora(source: str, slot: int, uploaded: bool) -> str: """Load a user LoRA once and return the adapter name to activate.""" key = f"{slot}:{source}" adapter_name = USER_ADAPTER_NAMES.get(key) if adapter_name and adapter_name in LOADED_ADAPTERS: return adapter_name # Keep at most one custom adapter per slot; avoid unlimited VRAM growth across uploads. for previous_key, previous_name in list(USER_ADAPTER_NAMES.items()): if previous_key.startswith(f"{slot}:") and previous_key != key: if previous_name in LOADED_ADAPTERS: pipe.delete_adapters(previous_name) LOADED_ADAPTERS.discard(previous_name) USER_ADAPTER_NAMES.pop(previous_key, None) digest = hashlib.sha256(source.encode("utf-8")).hexdigest()[:16] adapter_name = f"user-lora-{slot + 1}-{digest}" if uploaded: _load_local_lora(source, adapter_name) else: repo, weight_name = _parse_user_lora_reference(source) _load_lora_weights_with_fallback( repo=repo, weight_name=weight_name, adapter_name=adapter_name, needs_alpha_fix=True ) LOADED_ADAPTERS.add(adapter_name) USER_ADAPTER_NAMES[key] = adapter_name print(f"[user lora] slot {slot + 1} loaded: {source}") return adapter_name def _ensure_fast_lora(name: str) -> str: spec = FAST_LORAS[name] adapter_name = spec["adapter_name"] if adapter_name not in LOADED_ADAPTERS: print(f"--- Downloading and loading fast LoRA: {name} ---") _load_lora_weights_with_fallback( repo=spec["repo"], weight_name=spec["weights"], adapter_name=adapter_name, needs_alpha_fix=True, ) LOADED_ADAPTERS.add(adapter_name) return adapter_name def _resolve_user_slot(file_obj, text): """An uploaded file wins over a typed reference. Returns `(source, uploaded)`.""" if file_obj: path = file_obj if isinstance(file_obj, str) else getattr(file_obj, "name", None) if path: return path, True if text and str(text).strip(): text = str(text).strip() # A prefetched link arrives here as a local path, and a local file is loaded the same way an # uploaded one is. return (text, True) if os.path.exists(text) else (text, False) return None, False # ============================================================ # Helpers: resolution # ============================================================ # We prefer *area-based* sizing (≈ megapixels) over long-edge sizing. # This aligns better with Qwen-Image-Edit's internal assumptions and reduces FOV drift. def _round_to_multiple(x: int, m: int) -> int: return max(m, (int(x) // m) * m) def compute_canvas_dimensions_from_area( image: Image.Image, target_area: int, multiple_of: int, ) -> tuple[int, int]: """Compute (width, height) that matches image aspect ratio and approximates target_area. The result is floored to be divisible by multiple_of (typically vae_scale_factor*2). """ w, h = image.size aspect = w / h if h else 1.0 if IS_TURBO: from diffusers.pipelines.qwenimage21.pipeline_qwenimage21 import calculate_dimensions width, height, _ = calculate_dimensions(int(target_area), float(aspect)) multiple_of = math.lcm(32, int(multiple_of)) else: from qwenimage.pipeline_qwenimage_edit_plus import calculate_dimensions width, height = calculate_dimensions(int(target_area), float(aspect)) width = _round_to_multiple(int(width), int(multiple_of)) height = _round_to_multiple(int(height), int(multiple_of)) return width, height def get_target_area_for_lora( image: Image.Image, lora_adapter: str, user_target_megapixels: float, ) -> int: """Return target pixel area for the canvas. Priority: 1) Adapter spec: target_area (pixels) or target_megapixels 2) Adapter spec: target_long_edge (legacy) -> converted to area using image aspect 3) User slider target megapixels """ spec = ADAPTER_SPECS.get(lora_adapter, {}) if "target_area" in spec: try: return int(spec["target_area"]) except Exception: pass if "target_megapixels" in spec: try: mp = float(spec["target_megapixels"]) return int(mp * 1024 * 1024) except Exception: pass # Legacy support (e.g. Upscale2K) if "target_long_edge" in spec: try: long_edge = int(spec["target_long_edge"]) w, h = image.size if w >= h: new_w = long_edge new_h = int(round(long_edge * (h / w))) else: new_h = long_edge new_w = int(round(long_edge * (w / h))) return int(new_w * new_h) except Exception: pass # User default try: mp = float(user_target_megapixels) except Exception: mp = 1.0 # Treat 0 MP as "match input area" if mp <= 0: w, h = image.size return int(w * h) return int(mp * 1024 * 1024) # ============================================================ # Helpers: multi-input routing + gallery normalization # ============================================================ def lora_requires_two_images(lora_adapter: str) -> bool: return bool(ADAPTER_SPECS.get(lora_adapter, {}).get("requires_two_images", False)) def image2_label_for_lora(lora_adapter: str) -> str: return str(ADAPTER_SPECS.get(lora_adapter, {}).get("image2_label", "Upload Reference (Image 2)")) def _to_pil_rgb(x) -> Optional[Image.Image]: """ Accepts PIL / numpy / (image, caption) tuples from gr.Gallery and returns PIL RGB. Gradio Gallery commonly yields tuples like (image, caption). """ if x is None: return None # Gallery often returns (image, caption) if isinstance(x, tuple) and len(x) >= 1: x = x[0] if x is None: return None if isinstance(x, Image.Image): return x.copy() if IS_TURBO and x.mode == "RGBA" else x.convert("RGB") if isinstance(x, np.ndarray): return Image.fromarray(x).convert("RGB") # Best-effort fallback try: return Image.fromarray(np.array(x)).convert("RGB") except Exception: return None def build_labeled_images( img1: Image.Image, img2: Optional[Image.Image], extra_imgs: Optional[list[Image.Image]], ) -> dict[str, Image.Image]: """ Creates labels image_1, image_2, image_3... based on what is actually uploaded: - img1 is always image_1 - img2 becomes image_2 only if present - extras start immediately after the last present base box The pipeline receives images in this exact order. """ labeled: dict[str, Image.Image] = {} idx = 1 labeled[f"image_{idx}"] = img1 idx += 1 if img2 is not None: labeled[f"image_{idx}"] = img2 idx += 1 if extra_imgs: for im in extra_imgs: if im is None: continue labeled[f"image_{idx}"] = im idx += 1 return labeled def _append_to_gallery(existing, new_img) -> list[Image.Image]: """Append new_img to an existing gallery list.""" items: list[Image.Image] = [] if existing: for item in existing: pil = _to_pil_rgb(item) if pil is not None: items.append(pil) if new_img is not None: pil = _to_pil_rgb(new_img) if pil is not None: items.append(pil) return items def protect_highlights(image: Image.Image, strength: float = 0.35, threshold: float = 0.82) -> Image.Image: """Apply a gentle shoulder curve to bright pixels to reduce clipped highlights.""" try: amount = max(0.0, min(1.0, float(strength))) except Exception: amount = 0.0 if amount <= 0: return image alpha = image.getchannel("A") if image.mode == "RGBA" else None arr = np.asarray(image.convert("RGB")).astype(np.float32) / 255.0 luminance = ( arr[:, :, 0] * 0.2126 + arr[:, :, 1] * 0.7152 + arr[:, :, 2] * 0.0722 ) knee = max(0.01, 1.0 - float(threshold)) mask = np.clip((luminance - float(threshold)) / knee, 0.0, 1.0) mask = mask * mask * (3.0 - 2.0 * mask) compressed_luminance = float(threshold) + (luminance - float(threshold)) * (1.0 - amount * 0.72 * mask) ratio = np.divide( compressed_luminance, np.maximum(luminance, 1e-6), out=np.ones_like(luminance), where=luminance > 1e-6, ) corrected = np.clip(arr * ratio[:, :, None], 0.0, 1.0) result = Image.fromarray((corrected * 255.0 + 0.5).astype(np.uint8), mode="RGB") if alpha is not None: result.putalpha(alpha) return result # ============================================================ # Helpers: BFS alpha key fix # ============================================================ def _inject_missing_alpha_keys(state_dict: dict) -> dict: """ Diffusers' Qwen LoRA converter expects '.alpha' keys. BFS safetensors omits them. We inject alpha = rank (neutral scaling). IMPORTANT: diffusers may strip 'diffusion_model.' before lookup, so we inject BOTH: - diffusion_model.xxx.alpha - xxx.alpha """ bases = {} for k, v in state_dict.items(): if not isinstance(v, torch.Tensor): continue if k.endswith(".lora_down.weight") and v.ndim >= 1: base = k[: -len(".lora_down.weight")] rank = int(v.shape[0]) bases[base] = rank for base, rank in bases.items(): alpha_tensor = torch.tensor(float(rank), dtype=torch.float32) full_alpha = f"{base}.alpha" if full_alpha not in state_dict: state_dict[full_alpha] = alpha_tensor if base.startswith("diffusion_model."): stripped_base = base[len("diffusion_model.") :] stripped_alpha = f"{stripped_base}.alpha" if stripped_alpha not in state_dict: state_dict[stripped_alpha] = alpha_tensor return state_dict def _filter_to_diffusers_lora_keys(state_dict: dict) -> tuple[dict, dict]: """Return (filtered_state_dict, stats). Some ComfyUI/Qwen safetensors (especially "merged" variants) include non-LoRA delta/patch keys like `*.diff` and `*.diff_b` alongside real LoRA tensors. Diffusers' internal Qwen LoRA converter is strict: any leftover keys cause an error (`state_dict should be empty...`). This helper keeps only the keys Diffusers can consume as a LoRA: - `*.lora_up.weight` - `*.lora_down.weight` - (rare) `*.lora_mid.weight` - alpha keys: `*.alpha` (or `*.lora_alpha` which we normalize to `*.alpha`) It also drops known patch keys (`*.diff`, `*.diff_b`) and everything else. """ keep_suffixes = ( ".lora_up.weight", ".lora_down.weight", ".lora_mid.weight", ".alpha", ".lora_alpha", ) dropped_patch = 0 dropped_other = 0 kept = 0 normalized_alpha = 0 out: dict[str, torch.Tensor] = {} for k, v in state_dict.items(): if not isinstance(v, torch.Tensor): # Ignore non-tensor entries if any. dropped_other += 1 continue # Drop ComfyUI "delta" keys that Diffusers' LoRA loader will never consume. if k.endswith(".diff") or k.endswith(".diff_b"): dropped_patch += 1 continue if not k.endswith(keep_suffixes): dropped_other += 1 continue if k.endswith(".lora_alpha"): # Normalize common alt name to what Diffusers expects. base = k[: -len(".lora_alpha")] k2 = f"{base}.alpha" out[k2] = v.float() if v.dtype != torch.float32 else v normalized_alpha += 1 kept += 1 continue out[k] = v kept += 1 stats = { "kept": kept, "dropped_patch": dropped_patch, "dropped_other": dropped_other, "normalized_alpha": normalized_alpha, } return out, stats def _duplicate_stripped_prefix_keys(state_dict: dict, prefix: str = "diffusion_model.") -> dict: """Ensure both prefixed and unprefixed variants exist for LoRA-related keys. Diffusers' Qwen LoRA conversion may strip `diffusion_model.` when looking up modules. Some exports only include prefixed keys. To be maximally compatible, we duplicate LoRA keys (and alpha) in stripped form when missing. """ out = dict(state_dict) for k, v in list(state_dict.items()): if not k.startswith(prefix): continue stripped = k[len(prefix) :] if stripped not in out: out[stripped] = v return out def _load_lora_weights_with_fallback(repo: str, weight_name: str, adapter_name: str, needs_alpha_fix: bool = False): """ Normal path: pipe.load_lora_weights(repo, weight_name=..., adapter_name=...) BFS fallback: download safetensors, inject missing alpha keys, then load from dict. """ cached = LORA_PREFETCHED.get((repo, weight_name)) load_repo = os.path.dirname(cached) if cached else repo load_name = os.path.basename(cached) if cached else weight_name try: pipe.load_lora_weights(load_repo, weight_name=load_name, adapter_name=adapter_name) return except (KeyError, ValueError) as e: # KeyError: missing required alpha keys (common in BFS) # ValueError: Diffusers Qwen converter found leftover keys (e.g. .diff/.diff_b) if not needs_alpha_fix: raise print( "⚠️ LoRA load failed (will try safe dict fallback). " f"Adapter={adapter_name!r} file={weight_name!r} error={type(e).__name__}: {e}" ) local_path = hf_hub_download(repo_id=repo, filename=weight_name) sd = safetensors_load_file(local_path) # 1) Inject required `.alpha` keys (neutral scaling alpha=rank). sd = _inject_missing_alpha_keys(sd) # 2) Keep only LoRA + alpha keys; drop ComfyUI patch/delta keys. sd, stats = _filter_to_diffusers_lora_keys(sd) # 3) Duplicate stripped keys (remove `diffusion_model.`) for compatibility. sd = _duplicate_stripped_prefix_keys(sd) print( "🧹 LoRA dict cleanup stats: " f"kept={stats['kept']} dropped_patch={stats['dropped_patch']} " f"dropped_other={stats['dropped_other']} normalized_alpha={stats['normalized_alpha']}" ) pipe.load_lora_weights(sd, adapter_name=adapter_name) return # ============================================================ # LoRA loader: single/package + strengths # ============================================================ def _ensure_loaded_and_get_active_adapters(selected_lora: str): spec = ADAPTER_SPECS.get(selected_lora) if not spec: raise gr.Error(f"Configuration not found for: {selected_lora}") adapter_names = [] adapter_weights = [] if spec.get("type") == "package": parts = spec.get("parts", []) if not parts: raise gr.Error(f"Package spec has no parts: {selected_lora}") for part in parts: repo = part["repo"] weights = part["weights"] adapter_name = part["adapter_name"] strength = float(part.get("strength", 1.0)) needs_alpha_fix = bool(part.get("needs_alpha_fix", False)) if adapter_name not in LOADED_ADAPTERS: print(f"--- Downloading and Loading Adapter Part: {selected_lora} / {adapter_name} ---") try: _load_lora_weights_with_fallback( repo=repo, weight_name=weights, adapter_name=adapter_name, needs_alpha_fix=needs_alpha_fix, ) LOADED_ADAPTERS.add(adapter_name) except Exception as e: raise gr.Error(f"Failed to load adapter part {selected_lora}/{adapter_name}: {e}") else: print(f"--- Adapter part already loaded: {selected_lora} / {adapter_name} ---") adapter_names.append(adapter_name) adapter_weights.append(strength) else: repo = spec["repo"] weights = spec["weights"] adapter_name = spec["adapter_name"] strength = float(spec.get("strength", 1.0)) needs_alpha_fix = bool(spec.get("needs_alpha_fix", False)) if adapter_name not in LOADED_ADAPTERS: print(f"--- Downloading and Loading Adapter: {selected_lora} ---") try: _load_lora_weights_with_fallback( repo=repo, weight_name=weights, adapter_name=adapter_name, needs_alpha_fix=needs_alpha_fix, ) LOADED_ADAPTERS.add(adapter_name) except Exception as e: raise gr.Error(f"Failed to load adapter {selected_lora}: {e}") else: print(f"--- Adapter {selected_lora} is already loaded. ---") adapter_names = [adapter_name] adapter_weights = [strength] return adapter_names, adapter_weights # ============================================================ # UI handlers # ============================================================ def on_lora_change_ui(selected_lora, current_prompt, current_extras_condition_only): # Preset prompt (fill only if empty) if selected_lora != NONE_LORA: preset = LORA_PRESET_PROMPTS.get(selected_lora, "") if preset and (current_prompt is None or str(current_prompt).strip() == ""): prompt_update = gr.update(value=preset) else: prompt_update = gr.update(value=current_prompt) else: prompt_update = gr.update(value=current_prompt) # Image2 visibility/label if lora_requires_two_images(selected_lora): img2_update = gr.update(visible=True, label=image2_label_for_lora(selected_lora)) else: img2_update = gr.update(visible=True, label="Upload Reference (Image 2)") # Extra references routing default: # Some adapters read their second reference as an instruction rather than as picture data, and # for those the extra references are safer kept conditioning-only. Which ones comes from the # catalogue, not from a name written here. if selected_lora in CONDITIONING_ONLY: extras_update = gr.update(value=True) else: extras_update = gr.update(value=current_extras_condition_only) return prompt_update, img2_update, extras_update # ============================================================ # UI helpers: output routing + derived conditioning # ============================================================ def set_output_as_image1(last): if last is None: raise gr.Error("No output available yet.") return gr.update(value=last) def set_output_as_image2(last): if last is None: raise gr.Error("No output available yet.") return gr.update(value=last, visible=True) def set_output_as_extra(last, existing_extra): if last is None: raise gr.Error("No output available yet.") return _append_to_gallery(existing_extra, last) # GPU depth shares the pipeline's xlarge allocation. CPU depth bypasses this call. @spaces.GPU(duration=60, size="xlarge") def _depth_on_gpu(base): return make_depth_map(base, use_gpu=True) def add_derived_ref(img1, existing_extra, derived_type, derived_use_gpu): if img1 is None: raise gr.Error("Please upload Image 1 first.") if derived_type == "None": return gr.update(value=existing_extra), gr.update(visible=False, value=None) base = img1.convert("RGB") if derived_type == "Depth (Depth Anything V2 Small)": derived = _depth_on_gpu(base) if derived_use_gpu else make_depth_map(base, use_gpu=False) else: raise gr.Error(f"Unknown derived type: {derived_type}") new_gallery = _append_to_gallery(existing_extra, derived) return gr.update(value=new_gallery), gr.update(visible=True, value=derived) # ============================================================ # Auto-Describe (Qwen-VL) # ============================================================ # The pipeline's text encoder is a full Qwen-VL chat model, so captioning reuses # weights that are already loaded. Face Swap, Detail, Relight and Camera use fixed # presets, so the button appears only where the prompt is free text. DESCRIBE_OPERATIONS = (OP_QWEN, OP_MOSS, OP_OUTPAINT) DESCRIBE_HINT = ("**Paid · GPU:** Qwen-VL writes a prompt from your uploaded photo. " "Uses your ZeroGPU quota on xlarge (2×): about 10-20 s of GPU, roughly 20-40 quota seconds.") # Shares the pipeline's xlarge allocation; a caption is ~220 tokens at most. @spaces.GPU(duration=45, size="xlarge") def _describe_on_gpu(image, scene_only): import describe_backend processor = getattr(pipe, "processor", None) if processor is None or not hasattr(pipe.text_encoder, "generate"): raise gr.Error("Auto-Describe needs the pipeline's Qwen-VL processor and text encoder.") return describe_backend.describe(pipe.text_encoder, processor, image, scene_only=scene_only) def auto_describe(operation, image1, image2, current_prompt): import describe_backend try: image, label = describe_backend.source_image(image1, image2) except ValueError as error: raise gr.Error(str(error)) from error scene_only = operation == OP_OUTPAINT try: description = _describe_on_gpu(describe_backend.prepare_image(image), scene_only) except ValueError as error: raise gr.Error(str(error)) from error preset = restore_outpaint_prompt() if scene_only else None note = (f"**Auto-Describe (Paid · GPU):** prompt written from {label} by Qwen-VL using ZeroGPU quota. " "Edit it freely, or restore the previous prompt.") return (describe_backend.compose(description, preset), current_prompt, gr.update(visible=True), note) def restore_described_prompt(previous): return previous or "", gr.update(visible=False), DESCRIBE_HINT # ============================================================ # Inference # ============================================================ # ============================================================ # GPU reservation # ============================================================ # Placement, canvas, references and adapter application contribute to runtime. # LoRA downloads occur before this allocation. PLACEMENT_ALLOWANCE = 30 SECONDS_PER_STEP_AT_1MP = 3.2 MIN_GPU_SECONDS, MAX_GPU_SECONDS = (90 if IS_TURBO else 60), 400 def estimate_gpu_seconds(steps, target_megapixels, guidance_scale, lora_adapter, fast_lora, num_user_loras=0, vae_tiling=False, decoder_vae="qwen", num_references=1): # An allocation estimate, not a measured benchmark or the account's charged quota. # Downloads are done before GPU allocation. This is the general, full-budget path. megapixels = max(0.1, float(target_megapixels or 1.0)) total = ( PLACEMENT_ALLOWANCE + int(steps) * SECONDS_PER_STEP_AT_1MP * megapixels * (2.0 if float(guidance_scale) > 1.0 else 1.0) + 7 * max(0, int(num_references) - 1) + 5 * int(num_user_loras) + (15 if vae_tiling else 0) + (20 if not IS_TURBO and decoder_vae == "wan2x" else 0) ) return max(MIN_GPU_SECONDS, min(MAX_GPU_SECONDS, math.ceil(total))) def get_infer_duration(*args, **kwargs): bound = inspect.signature(infer).bind_partial(*args, **kwargs) bound.apply_defaults() return request_gpu_seconds(bound.arguments) def is_dmd2_request(data): if data.get("operation") == OP_CAMERA: # Two-step DMD2 mostly kept the original view; Camera uses the native sampler. return False mode_key = QWEN_MODE_KEYS.get(data.get("operation", OP_QWEN)) return IS_TURBO and mode_key is not None and data.get(mode_key) == QWEN_DMD2 def _ensure_dmd2_adapter(prepared): if DMD2_ADAPTER not in pipe.get_list_adapters().get("transformer", []): # Rank equals alpha. Load tensors without the newer PEFT metadata # fields the Studio's pinned runtime can't parse. weights = safetensors_load_file(prepared["dmd2_path"], device="cpu") pipe.load_lora_weights(weights, adapter_name=DMD2_ADAPTER) return DMD2_ADAPTER def _with_qwen_sampling_state(fn): """Restore the shared native model even when preparation or sampling fails.""" @functools.wraps(fn) def wrapped(*args, **kwargs): bound = inspect.signature(fn).bind(*args, **kwargs) bound.apply_defaults() if not IS_TURBO or bound.arguments.get("operation") != OP_QWEN: return fn(*args, **kwargs) mode = bound.arguments.get("qwen_mode", QWEN_TURBO) if mode not in QWEN_MODES: raise gr.Error("Choose Viggle Turbo, DMD2, or Base for Qwen Image Edit.") scheduler_options = {} if mode == QWEN_BASE else {"shift_terminal": None} if mode == QWEN_DMD2: scheduler_options.update(use_dynamic_shifting=False, shift=1.0) original_scheduler = pipe.scheduler try: pipe.enable_lora() pipe.scheduler = FlowMatchEulerDiscreteScheduler.from_config( BASE_SCHEDULER_CONFIG, **scheduler_options) return fn(*args, **kwargs) finally: pipe.scheduler = original_scheduler pipe.vae.disable_tiling() pipe.enable_lora() pipe.set_adapters([TURBO_ADAPTER], adapter_weights=[1.0]) return wrapped # The wrapper below calls this on ZeroGPU's xlarge slice, as the upstream demo does. @_with_qwen_sampling_state def infer( input_image_1, input_image_2, input_images_extra, # gallery multi-image box prompt, lora_adapter, seed, randomize_seed, guidance_scale, steps, target_megapixels, extras_condition_only, pad_to_canvas, vae_tiling, # VAE tiling toggle resolution_multiple, vae_ref_megapixels, decoder_vae, keep_decoder_2x, highlight_protection, highlight_protection_strength, fast_lora=NO_FAST_LORA, fast_lora_strength=1.0, user_lora_1_file=None, user_lora_1_ref="", user_lora_1_scale=0.0, user_lora_2_file=None, user_lora_2_ref="", user_lora_2_scale=0.0, user_lora_3_file=None, user_lora_3_ref="", user_lora_3_scale=0.0, negative_prompt_text=DEFAULT_NEGATIVE_TEXT, aspect_ratio="Match Image 1", custom_width=1024, custom_height=1024, operation=OP_QWEN, face_mode=FACE_TURBO, face_strength=1.0, outpaint_mode=OUTPAINT_TURBO, outpaint_left=25, outpaint_right=25, outpaint_top=25, outpaint_bottom=25, outpaint_feather=32, detail_mode=DETAIL_TURBO, detail_strength=1.0, qwen_mode=QWEN_TURBO, relight_preset="Soft studio", relight_direction="Left", relight_color="#FFFFFF", relight_strength=1.0, camera_azimuth=90, camera_elevation=0, camera_closeup=False, camera_strength=CAMERA_STRENGTH, _prepared_data=None, progress=gr.Progress(track_tqdm=True), ): use_dmd2 = is_dmd2_request(locals()) if use_dmd2: steps, guidance_scale, negative_prompt_text = len(DMD2_SIGMAS), DEFAULT_CFG, "" active_negative_prompt, guidance_scale, guidance_passes = guidance_values( {"negative_prompt_text": negative_prompt_text, "guidance_scale": guidance_scale}, default=4.0 if operation == OP_MOSS else DEFAULT_CFG, min_cfg=0 if operation == OP_MOSS else 1, max_cfg=20 if operation == OP_MOSS else 10) negative_prompt_text = active_negative_prompt or "" if operation in (OP_FACE, OP_MOSS, *SINGLE_SOURCE_OPERATIONS): data = dict(locals()) data.pop("_prepared_data", None) data.update(_prepared_data or {}) if operation == OP_MOSS: import moss_backend # Qwen stays on the 96GB xlarge GPU. MOSS loads/discards one stage at a # time; moving Qwen to CPU here would duplicate its host snapshot. result, seed, _ = moss_backend.generate(data, progress=progress) else: if operation == OP_OUTPAINT: import outpaint_backend as edit_backend elif operation == OP_DETAIL: import detail_backend as edit_backend elif operation == OP_RELIGHT: import relight_backend as edit_backend elif operation == OP_CAMERA: import camera_backend as edit_backend else: import bfs_backend as edit_backend user_names, user_weights = [], [] for index in range(1, 4): scale = float(data.get(f"user_lora_{index}_scale") or 0) source, uploaded = _resolve_user_slot(data.get(f"user_lora_{index}_file"), data.get(f"user_lora_{index}_ref")) if source and scale: user_names.append(_ensure_user_lora(source, index - 1, uploaded)) user_weights.append(scale) data["width"], data["height"] = request_canvas(data) dmd2_adapter = _ensure_dmd2_adapter(data) if use_dmd2 else None result = edit_backend.generate(pipe, data, turbo_adapter=TURBO_ADAPTER, base_scheduler_config=BASE_SCHEDULER_CONFIG, user_adapters=user_names, user_weights=user_weights, dmd2_adapter=dmd2_adapter) seed = int(data["seed"]) # Outpaint's native canvas and restored original pixels are final, even # when an old profile supplies a fixed ratio or highlight correction. if operation == OP_FACE: result = crop_output_to_aspect(result, aspect_ratio) if operation not in SINGLE_SOURCE_OPERATIONS: if highlight_protection: result = protect_highlights(result, strength=float(highlight_protection_strength)) return result, seed, result use_viggle = IS_TURBO and qwen_mode == QWEN_TURBO gc.collect() if torch.cuda.is_available(): torch.cuda.empty_cache() check_prompt(prompt) if input_image_1 is None and not IS_TURBO: raise gr.Error("Please upload Image 1.") # Style adapter + optional fast adapter + up to three of the user's own, # activated together in one call. adapter_names: list[str] = [TURBO_ADAPTER] if use_viggle else [] if use_dmd2: adapter_names.append(_ensure_dmd2_adapter(_prepared_data)) adapter_weights: list[float] = [1.0] * len(adapter_names) if not IS_TURBO and lora_adapter != NONE_LORA: names, weights = _ensure_loaded_and_get_active_adapters(lora_adapter) adapter_names += names adapter_weights += weights if not IS_TURBO and fast_lora and fast_lora != NO_FAST_LORA and fast_lora in FAST_LORAS: try: progress(0.02, desc=f"Loading {fast_lora}...") adapter_names.append(_ensure_fast_lora(fast_lora)) adapter_weights.append(float(fast_lora_strength)) except Exception as error: raise gr.Error(f"Failed to load the fast LoRA: {error}") user_slots = [ (user_lora_1_file, user_lora_1_ref, user_lora_1_scale), (user_lora_2_file, user_lora_2_ref, user_lora_2_scale), (user_lora_3_file, user_lora_3_ref, user_lora_3_scale), ] for slot, (file_obj, ref_text, scale) in enumerate(user_slots): try: scale = float(scale) except Exception: scale = 0.0 if scale == 0: continue source, uploaded = _resolve_user_slot(file_obj, ref_text) if not source: continue progress(0.03, desc=f"Loading your lora {slot + 1}...") adapter_names.append(_ensure_user_lora(source, slot, uploaded)) adapter_weights.append(scale) # PEFT expects unique adapter names. Repeated catalogue selections combine strengths. combined = {} for name, weight in zip(adapter_names, adapter_weights): combined[name] = combined.get(name, 0.0) + weight adapter_names, adapter_weights = list(combined), list(combined.values()) if adapter_names: pipe.set_adapters(adapter_names, adapter_weights=adapter_weights) elif IS_TURBO: # Native Base without optional adapters has no active LoRA at all. # The request guard re-enables PEFT before restoring Turbo afterwards. pipe.disable_lora() else: try: pipe.set_adapters([], adapter_weights=[]) except Exception: if LOADED_ADAPTERS: pipe.set_adapters(list(LOADED_ADAPTERS), adapter_weights=[0.0] * len(LOADED_ADAPTERS)) if randomize_seed: seed = random.randint(0, MAX_SEED) generator = torch.Generator(device=device).manual_seed(seed) true_cfg_scale = float(guidance_scale) img1 = _to_pil_rgb(input_image_1) img2 = _to_pil_rgb(input_image_2) # Normalize extra images (Gallery) to PIL RGB (handles tuples from Gallery) extra_imgs: list[Image.Image] = [] if input_images_extra: for item in input_images_extra: pil = _to_pil_rgb(item) if pil is not None: extra_imgs.append(pil) # Enforce existing 2-image LoRA behavior (image_1 + image_2 required) if lora_requires_two_images(lora_adapter) and img2 is None: raise gr.Error("This LoRA needs two images. Please upload Image 2 as well.") # Ordered references; no empty placeholder enters the new pipeline. labeled = build_labeled_images(img1, img2, extra_imgs) if img1 is not None else {} pipe_images = [im for im in (img1, img2, *extra_imgs) if im is not None] base_ref_count = int(img1 is not None) + int(img2 is not None) width, height = resolve_canvas( img1 or img2 or (extra_imgs[0] if extra_imgs else None), lora_adapter, target_megapixels, resolution_multiple, aspect_ratio, custom_width, custom_height, bool(pipe_images), ) vae_image_indices = list(range(base_ref_count)) if extras_condition_only and extra_imgs else None try: print( "[DEBUG][infer] submitting request | " f"lora_adapter={lora_adapter!r} seed={seed} prompt={prompt!r}" ) print(f"[DEBUG][infer] canvas={width}x{height} (~{(width*height)/1_048_576:.3f} MP) vae_tiling={bool(vae_tiling)}") # ✅ Apply UI toggle per-request (OFF by default) # Lattice multiple passed to pipeline too (anti-drift / valid size grid) res_mult = int(resolution_multiple) if resolution_multiple is not None else int(pipe.vae_scale_factor * 2) # Optional: override VAE sizing for *extra* references (beyond Image 1 / Image 2) # Interpreted as megapixels; 0 disables override (uses canvas). try: mp_ref = float(vae_ref_megapixels) except Exception: mp_ref = 0.0 vae_ref_area = int(mp_ref * 1024 * 1024) if mp_ref and mp_ref > 0 else None # Extras start index depends on whether Image 2 exists base_ref_count = 2 if img2 is not None else 1 _apply_vae_tiling(bool(vae_tiling)) if IS_TURBO: # These are exactly the supported QwenImage21Pipeline parameters. # Legacy latent-routing / decoder kwargs must never reach this pipeline. if pad_to_canvas and pipe_images: pipe_images = [pad_reference(im, width, height) for im in pipe_images] # CFG keeps separate positive/negative caches. Bound their combined # reference footprint using the native 1024-area, /32 resize. prefix_tokens = 0 for reference in pipe_images: ratio = reference.width / reference.height ref_width = max(32, round(math.sqrt(1024**2 * ratio) / 32) * 32) ref_height = max(32, round(math.sqrt(1024**2 / ratio) / 32) * 32) prefix_tokens += (ref_width // 16) * (ref_height // 16) sigmas = list(DMD2_SIGMAS) if use_dmd2 else turbo_sigmas(steps) if use_viggle else None pipe_kwargs = dict( image=pipe_images or None, prompt=prompt, negative_prompt=active_negative_prompt, height=height, width=width, num_inference_steps=int(steps), sigmas=sigmas, generator=generator, true_cfg_scale=true_cfg_scale, output_resolution=1024, use_kv_cache=prefix_tokens * 32 * 2 * 4096 * 2 * guidance_passes <= 30e9, ) else: pipe_kwargs = dict( image=pipe_images if len(pipe_images) > 1 else pipe_images[0], prompt=prompt, negative_prompt=active_negative_prompt, height=height, width=width, num_inference_steps=int(steps), generator=generator, true_cfg_scale=true_cfg_scale, vae_image_indices=vae_image_indices, pad_to_canvas=bool(pad_to_canvas), resolution_multiple=res_mult, vae_ref_area=vae_ref_area, vae_ref_start_index=base_ref_count, decoder_vae=str(decoder_vae).lower(), keep_decoder_2x=bool(keep_decoder_2x), ) with decode_tiling(bool(vae_tiling)): try: result = pipe(**pipe_kwargs).images[0] except RuntimeError as error: if ATTENTION_BACKEND == "fa3" and _is_flash_attention_kernel_error(error): _use_sdpa_attention() # Preserve the selected seed if a failed attention kernel consumed RNG state. generator.manual_seed(seed) result = pipe(**pipe_kwargs).images[0] else: raise result = crop_output_to_aspect(result, aspect_ratio) if bool(highlight_protection): result = protect_highlights(result, strength=float(highlight_protection_strength)) return result, seed, result finally: gc.collect() if torch.cuda.is_available(): torch.cuda.empty_cache() # ============================================================ # Shared validation, portable LoRA downloads, canvas and profiles # ============================================================ def pad_reference(image, width, height): """Optional letterboxing, with no aspect-ratio distortion.""" # Match the target aspect, not its large output dimensions; the pipeline resizes to 1024². ref_width = max(32, round(math.sqrt(1024 ** 2 * width / height) / 32) * 32) ref_height = max(32, round(ref_width * height / width / 32) * 32) mode = "RGBA" if image.mode == "RGBA" else "RGB" fill = (255, 255, 255, 255) if mode == "RGBA" else (255, 255, 255) return ImageOps.pad(image.convert(mode), (ref_width, ref_height), method=Image.Resampling.LANCZOS, color=fill) FIXED_OUTPUT_RATIOS = { "1:1": (1, 1), "16:9": (16, 9), "9:16": (9, 16), "4:3": (4, 3), "3:4": (3, 4), "3:2": (3, 2), "2:3": (2, 3), "4:5": (4, 5), "5:4": (5, 4), "21:9": (7, 3), "9:21": (3, 7), } def exact_output_dimensions(width, height, aspect_ratio): """Largest exact fixed-ratio rectangle inside the generated image.""" width, height = int(width), int(height) if width <= 0 or height <= 0: raise ValueError("Output image dimensions must be positive.") ratio = FIXED_OUTPUT_RATIOS.get(str(aspect_ratio)) if ratio is None: return width, height ratio_w, ratio_h = ratio unit = min(width // ratio_w, height // ratio_h) if unit < 1: raise ValueError("Output image is too small for the selected aspect ratio.") return ratio_w * unit, ratio_h * unit def crop_output_to_aspect(image, aspect_ratio): """Center-crop fixed presets while preserving pixels and the image mode.""" if image is None: raise ValueError("The model returned no output image.") width, height = image.size crop_width, crop_height = exact_output_dimensions(width, height, aspect_ratio) if (crop_width, crop_height) == (width, height): return image left = (width - crop_width) // 2 top = (height - crop_height) // 2 return image.crop((left, top, left + crop_width, top + crop_height)) def output_size_text(width, height, aspect_ratio): """Describe actual output dimensions, never an unfulfilled requested ratio.""" width, height = int(width), int(height) if width <= 0 or height <= 0: raise ValueError("Output image dimensions must be positive.") requested = FIXED_OUTPUT_RATIOS.get(str(aspect_ratio)) if requested and width * requested[1] == height * requested[0]: label = str(aspect_ratio) else: divisor = math.gcd(width, height) label = f"{width // divisor}:{height // divisor}" return f"**Output:** {width} × {height} px · {label}" def describe_output(image, aspect_ratio, operation=OP_QWEN): if operation in SINGLE_SOURCE_OPERATIONS: aspect_ratio = "Match Image 1" return output_size_text(image.width, image.height, aspect_ratio) if image is not None else "" COMPARE_VIEW_RESULT = "Result" COMPARE_VIEW_SLIDER = "Before / After" def comparison_before(source, result): """Fit the source onto the result's canvas so both slider layers line up.""" if source is None or result is None: return None if not isinstance(source, Image.Image): source = Image.fromarray(source) source = ImageOps.exif_transpose(source) if source.mode in ("RGBA", "LA") or (source.mode == "P" and "transparency" in source.info): rgba = source.convert("RGBA") flat = Image.new("RGB", rgba.size, (255, 255, 255)) flat.paste(rgba, mask=rgba.getchannel("A")) source = flat else: source = source.convert("RGB") size = (result.width, result.height) if source.size == size: return source if abs(source.width / source.height - result.width / result.height) <= 0.01: return source.resize(size, Image.LANCZOS) # Different framing (custom aspect ratio, camera reframing): letterbox, never crop. return ImageOps.pad(source, size, method=Image.LANCZOS, color=(128, 128, 128)) def comparison_view(result, source, outpaint_source, operation, view): """Before/After pair for the result column; hidden when there is no source image.""" # Outpaint compares against the expanded canvas preview, where gray marks the new area. original = outpaint_source if operation == OP_OUTPAINT and outpaint_source is not None else source if result is not None and not isinstance(result, Image.Image): result = Image.fromarray(result) before = comparison_before(original, result) if before is None: return (gr.update(value=COMPARE_VIEW_RESULT, visible=False), gr.update(visible=True), gr.update(value=None, visible=False)) show_slider = view == COMPARE_VIEW_SLIDER return (gr.update(visible=True), gr.update(visible=not show_slider), gr.update(value=(before, result.convert("RGB")), visible=show_slider)) def switch_result_view(view): show_slider = view == COMPARE_VIEW_SLIDER return gr.update(visible=not show_slider), gr.update(visible=show_slider) def resolve_canvas(image, lora_adapter, target_megapixels, resolution_multiple, aspect_ratio="Match Image 1", custom_width=1024, custom_height=1024, has_references=True): multiple = int(resolution_multiple or 32) if multiple <= 0: raise gr.Error("Resolution multiple must be positive.") if IS_TURBO: multiple = math.lcm(32, multiple) base = image if image is not None else Image.new("RGB", (1024, 1024)) area = get_target_area_for_lora(base, lora_adapter, float(target_megapixels or 0)) if not IS_TURBO and aspect_ratio == "Match Image 1": # Keep the original helper + floor-to-lattice behavior for existing legacy profiles. return compute_canvas_dimensions_from_area(base, area, multiple) ratio = base.width / base.height if aspect_ratio == "Custom": width, height = int(custom_width), int(custom_height) if width < 256 or height < 256 or width > 8192 or height > 8192: raise gr.Error("Custom sides must be between 256 and 8192 pixels.") ratio, area = width / height, width * height elif aspect_ratio and aspect_ratio != "Match Image 1": try: left, right = map(float, str(aspect_ratio).split(":")) ratio = left / right except (ValueError, ZeroDivisionError): raise gr.Error("Choose a valid output aspect ratio.") if not math.isfinite(ratio) or ratio <= 0: raise gr.Error("Choose a valid output aspect ratio.") if IS_TURBO: cap = 1536 ** 2 if has_references else 2048 ** 2 area = min(max(256 ** 2, int(area)), cap) else: area = max(multiple ** 2, int(area)) width = max(multiple, round(math.sqrt(area * ratio) / multiple) * multiple) height = max(multiple, round(math.sqrt(area / ratio) / multiple) * multiple) # Same nearest-32 bucket rounding as upstream; e.g. 1760x1344 may slightly exceed 1536². return width, height def request_images(data): if data.get("operation") in SINGLE_SOURCE_OPERATIONS: image = _to_pil_rgb(data.get("input_image_1")) return [image] if image is not None else [] images = [] for value in (data.get("input_image_1"), data.get("input_image_2")): image = _to_pil_rgb(value) if image is not None: images.append(image) for value in data.get("input_images_extra") or []: image = _to_pil_rgb(value) if image is not None: images.append(image) return images def request_canvas(data): if data.get("operation") == OP_RELIGHT: import relight_backend return relight_backend.request_canvas(data) if data.get("operation") == OP_CAMERA: import camera_backend return camera_backend.request_canvas(data) if data.get("operation") == OP_DETAIL: import detail_backend return detail_backend.request_canvas(data) if data.get("operation") == OP_OUTPAINT: import outpaint_backend return outpaint_backend.request_canvas(data) if data.get("operation") == OP_MOSS: import moss_backend return moss_backend.request_canvas(data) images = request_images(data) return resolve_canvas( images[0] if images else None, data.get("lora_adapter", NONE_LORA), data.get("target_megapixels", 1.0), data.get("resolution_multiple", 32), data.get("aspect_ratio", "Match Image 1"), data.get("custom_width", 1024), data.get("custom_height", 1024), bool(images), ) def request_gpu_seconds(data, worker_samples=None): data = normalize_guidance_request(data) if data.get("operation") == OP_RELIGHT: import relight_backend return relight_backend.estimate_seconds(data) if data.get("operation") == OP_CAMERA: import camera_backend return camera_backend.estimate_seconds(data) if data.get("operation") == OP_DETAIL: import detail_backend return detail_backend.estimate_seconds(data) if data.get("operation") == OP_OUTPAINT: import outpaint_backend return outpaint_backend.estimate_seconds(data) if data.get("operation") == OP_MOSS: import moss_backend return moss_backend.estimate_gpu_seconds(data) if data.get("operation") == OP_FACE: import bfs_backend prepared = dict(data) prepared["width"], prepared["height"] = request_canvas(data) return bfs_backend.estimate_seconds(prepared) width, height = request_canvas(data) num_user = sum( bool(data.get(f"user_lora_{i}_file") or str(data.get(f"user_lora_{i}_ref") or "").strip()) and float(data.get(f"user_lora_{i}_scale") or 0) != 0 for i in range(1, 4) ) refs = request_images(data) mode = data.get("qwen_mode", QWEN_TURBO) default_sampler = mode == QWEN_DMD2 or (mode == QWEN_TURBO and data.get("steps", DEFAULT_STEPS) == 6) # These two ordinary recipes completed in under 8 s end to end on the # same 1 MP portrait. Leave room for worker placement and cold DMD2 loads. if (IS_TURBO and data.get("operation", OP_QWEN) == OP_QWEN and default_sampler and width * height <= 1.05 * 1024 ** 2 and max(width, height) <= 1600 and len(refs) <= 1 and all(max(image.size) <= 2048 for image in refs) and not data.get("input_images_extra") and not num_user and data.get("lora_adapter") in (None, NONE_LORA) and data.get("fast_lora") in (None, "", NO_FAST_LORA) and data["guidance_scale"] == 1 and not data.get("vae_tiling") and len(str(data.get("prompt") or "")) <= 1024 and not data.get("pad_to_canvas") and not data.get("highlight_protection")): seconds = 50 if mode == QWEN_DMD2 else 55 if worker_samples is None: worker_samples = _qwen_worker_samples(data) if worker_samples: seconds = max(seconds, math.ceil(max(worker_samples) * 1.5 + 15)) return min(MAX_GPU_SECONDS, seconds) return estimate_gpu_seconds( data.get("steps", DEFAULT_STEPS), width * height / 1024 ** 2, data.get("guidance_scale", DEFAULT_CFG), data.get("lora_adapter", NONE_LORA), data.get("fast_lora", NO_FAST_LORA), num_user, data.get("vae_tiling", False), data.get("decoder_vae", "qwen"), len(refs), ) def _turbo_lora_canonical_keys(header): """Plan a native 2.1 load after checking every low-rank pair's dimensions. Comfy/AI Toolkit fuse SwiGLU as [gate_layer; proj] along the output dimension. Their B matrix is split in that order; both halves reuse A. Prefixes describe export formats, so compatibility comes from the actual target modules and shapes, never from a prefix or a catalog model label. """ if not isinstance(header, dict): raise ValueError("invalid safetensors header object") pairs, target_owners = {}, {} kohya_names = None def resolve_name(name): nonlocal kohya_names for prefix in ("base_model.model.", "model.diffusion_model.", "diffusion_model.", "transformer."): if name.startswith(prefix): name = name[len(prefix):] for prefix in ("lora_unet_", "lora_transformer_", "lycoris_"): if name.startswith(prefix): # Enumerate real names instead of replacing every underscore: # img_mlp, transformer_blocks and to_out.0 must stay distinct. if kohya_names is None: kohya_names = {} for native, module in pipe.transformer.named_modules(): weight = getattr(module, "weight", None) if weight is not None and len(weight.shape) == 2: kohya_names[native.replace(".", "_")] = native if native.endswith(".img_mlp.gate_layer"): fused = native[:-len("gate_layer")] + "gate_up" kohya_names[fused.replace(".", "_")] = fused encoded = name[len(prefix):] if encoded not in kohya_names: raise ValueError(f"unknown Qwen Image 2.1 LoRA module: {name}") name = kohya_names[encoded] break return name for key, value in header.items(): if key == "__metadata__": continue match = re.fullmatch(r"(.+)\.lora_([AB])(?:\.default)?\.weight", key) if match: raw_name, side = match.groups() else: match = re.fullmatch(r"(.+)\.lora_(down|up)\.weight", key) if match: raw_name, side = match[1], {"down": "A", "up": "B"}[match[2]] else: match = re.fullmatch(r"(.+)\.(?:alpha|lora_alpha)", key) if not match: raise ValueError(f"unsupported LoRA tensor: {key}; use 2.1 A/B or down/up weights") raw_name, side = match[1], "alpha" module_name = resolve_name(raw_name) shape = tuple(value["shape"]) if side == "alpha": if shape not in ((), (1,)): raise ValueError(f"LoRA alpha must be a scalar: {module_name}") elif (len(shape) != 2 or any(not isinstance(size, int) or isinstance(size, bool) or size <= 0 for size in shape)): raise ValueError(f"unsupported tensor shape for {module_name}") pair = pairs.setdefault(module_name, {}) if side in pair: raise ValueError(f"duplicate normalized LoRA tensor: {module_name}.{side}") pair[side] = (key, shape) if not pairs: raise ValueError("no LoRA tensors found") plan = {} for module_name, pair in sorted(pairs.items()): if "A" not in pair or "B" not in pair or pair["A"][1][0] != pair["B"][1][1]: raise ValueError(f"missing or mismatched LoRA pair: {module_name}") if module_name.endswith(".img_mlp.gate_up"): prefix = module_name[:-len("gate_up")] native_names = (prefix + "gate_layer", prefix + "proj") else: native_names = (module_name,) targets, row_start, in_features = [], 0, None for native in native_names: try: base_shape = tuple(pipe.transformer.get_submodule(native).weight.shape) except (AttributeError, KeyError, IndexError) as error: raise ValueError(f"unknown Qwen Image 2.1 module: {native}; old-model LoRAs require legacy mode") from error if len(base_shape) != 2 or (in_features is not None and in_features != base_shape[1]): raise ValueError(f"unsupported target dimensions for {native}") if native in target_owners: raise ValueError(f"overlapping LoRA targets: {module_name} and {target_owners[native]}") target_owners[native] = module_name in_features = base_shape[1] targets.append((native, row_start, row_start + base_shape[0])) row_start += base_shape[0] if pair["A"][1][1] != in_features or pair["B"][1][0] != row_start: raise ValueError(f"incompatible dimensions for {module_name}; 2509/2511 LoRAs require legacy mode") plan[module_name] = { "a": pair["A"][0], "b": pair["B"][0], "alpha": pair.get("alpha", (None,))[0], "rank": pair["A"][1][0], "shapes": (pair["A"][1], pair["B"][1]), "targets": tuple(targets), } return plan def validate_turbo_lora(path): """Validate native/Comfy/Kohya 2.1 shapes on CPU before requesting a GPU.""" try: if "qwen-image-2.1-viggle-turbo" in str(path).lower(): raise ValueError("Viggle Turbo is already built in; do not stack a second distillation adapter") with open(path, "rb") as handle: size_bytes = handle.read(8) if len(size_bytes) != 8: raise ValueError("missing safetensors header") size = struct.unpack(" 1 for module_name, start, stop in pair["targets"]: native_state[f"transformer.{module_name}.lora_A.weight"] = a native_state[f"transformer.{module_name}.lora_B.weight"] = b[start:stop].contiguous() if fused else b # Canonical names and folded alpha bypass Diffusers' older Qwen converter. # The selected speed adapter and optional user strengths are activated separately. pipe.load_lora_weights(native_state, adapter_name=adapter_name) def normalize_guidance_request(data): """Apply the same negative-prompt rule to UI, direct API and GPU budgets.""" out = dict(data) # Camera Angle has one recipe for UI, API and restored profiles: the camera # author's native sampler, CFG 1 and no negative prompt. The old two-step # DMD2 recipe mostly kept the original view. Steps outside 10-50 (old 2/6 # step values and API defaults) use the recommended 40. if out.get("operation") == OP_CAMERA: out.update(qwen_mode=QWEN_BASE, guidance_scale=DEFAULT_CFG, negative_prompt_text="") try: camera_steps = float(out.get("steps", CAMERA_STEPS)) except (TypeError, ValueError, OverflowError): camera_steps = float(CAMERA_STEPS) if (not math.isfinite(camera_steps) or not camera_steps.is_integer() or not CAMERA_MIN_STEPS <= camera_steps <= CAMERA_MAX_STEPS): camera_steps = float(CAMERA_STEPS) out["steps"] = int(camera_steps) return out if is_dmd2_request(out): out.update(steps=len(DMD2_SIGMAS), guidance_scale=DEFAULT_CFG, negative_prompt_text="") return out try: moss = out.get("operation") == OP_MOSS negative, cfg, _ = guidance_values(out, default=4.0 if moss else DEFAULT_CFG, min_cfg=0 if moss else 1, max_cfg=20 if moss else 10) except ValueError as error: raise gr.Error(str(error)) from error out.update(negative_prompt_text=negative or "", guidance_scale=cfg) return out def normalize_profile(payload): if not isinstance(payload, dict): raise gr.Error("A settings file must contain a JSON object.") data = dict(payload) operation = data.get("operation", OP_QWEN) if operation not in OPERATIONS: raise gr.Error("This profile names an unsupported operation.") data["operation"] = operation # Before schema 4 the camera strength default was 1. With the native sampler # that often turned real photos into plain studio renders. if (operation == OP_CAMERA and int(data.get("schema_version", 0) or 0) < 4 and data.get("camera_strength", 1.0) == 1.0): data["camera_strength"] = CAMERA_STRENGTH # In schema 1/2 native Qwen ignored its prefilled legacy negative at CFG 1. # Do not turn that old hidden default into an active exclusion on import. old_schema = int(data.get("schema_version", 0) or 0) < 3 if (IS_TURBO and operation != OP_MOSS and old_schema and float(data.get("guidance_scale", 1.0)) == 1.0 and data.get("negative_prompt_text") == DEFAULT_NEGATIVE): data["negative_prompt_text"] = "" data = normalize_guidance_request(data) data["schema_version"] = 4 mode = data.get("qwen_mode", QWEN_TURBO) data["qwen_mode"] = mode if mode in QWEN_MODES else ( QWEN_BASE if str(mode).startswith("Base") else QWEN_TURBO) for key, turbo, base in (("face_mode", FACE_TURBO, FACE_BASE), ("outpaint_mode", OUTPAINT_TURBO, OUTPAINT_BASE), ("detail_mode", DETAIL_TURBO, DETAIL_BASE)): mode = data.get(key) data[key] = QWEN_DMD2 if mode == QWEN_DMD2 else base if str(mode).startswith("Base") else turbo data["face_strength"] = max(0.0, min(1.5, float(data.get("face_strength", 1.0)))) detail_strength_value = float(data.get("detail_strength", 1.0)) if not math.isfinite(detail_strength_value): raise gr.Error("Qwen Detail Enhancer strength must be a finite number.") data["detail_strength"] = max(0.0, min(1.5, detail_strength_value)) for key, default, maximum in [(f"outpaint_{side}", 25, 100) for side in ("left", "right", "top", "bottom")] + [("outpaint_feather", 32, 128)]: value = float(data.get(key, default)) if not math.isfinite(value): raise gr.Error("Outpaint expansion and feather values must be finite numbers.") data[key] = max(0, min(maximum, value)) # Older Simple profiles could keep the only user description in the helper box. if (data.get("ui_mode", "Simple") != "Pro" and not str(data.get("prompt") or "").strip() and isinstance(data.get("pb_idea"), str)): data["prompt"] = data["pb_idea"] if "pb_writer" in data: data["pb_writer"] = resolve_writer(data["pb_writer"], DEFAULT_QWEN_SPACE) if operation != OP_QWEN: if not IS_TURBO: raise gr.Error("Image editing operations require the shared Turbo studio backend.") limits = sampling_limits(operation, data["face_mode"], data["outpaint_mode"], data["detail_mode"], data["qwen_mode"]) data["steps"] = max(limits[0], min(limits[1], int(data.get("steps", limits[2])))) data.update(lora_adapter=NONE_LORA, fast_lora=NO_FAST_LORA, decoder_vae="qwen", keep_decoder_2x=False, extras_condition_only=False, vae_ref_megapixels=0.0, resolution_multiple=32) if operation in SINGLE_SOURCE_OPERATIONS: megapixels = float(data.get("target_megapixels", 1.0)) if not math.isfinite(megapixels): raise gr.Error("Image editing resolution must be a finite number.") data.update(target_megapixels=max(.5, min(4.0 if operation == OP_DETAIL else 2.0, megapixels)), aspect_ratio="Match Image 1", pad_to_canvas=False, highlight_protection=False, prompt=ensure_operation_prompt(operation, data.get("prompt", ""))) return data, "" if not IS_TURBO: if payload.get("backend") == "turbo": for i in range(1, 4): data[f"user_lora_{i}_scale"] = 0.0 data.update(steps=DEFAULT_STEPS, resolution_multiple=32, extras_condition_only=True, pad_to_canvas=True, vae_tiling=False, vae_ref_megapixels=0.0, highlight_protection=True, decoder_vae="qwen", keep_decoder_2x=False) return data, "Adapted for legacy: custom 2.1 LoRAs are inactive; their links are kept." return data, "" changed = [] fixed = { "lora_adapter": NONE_LORA, "fast_lora": NO_FAST_LORA, "decoder_vae": "qwen", "keep_decoder_2x": False, "extras_condition_only": False, "vae_ref_megapixels": 0.0, } for key, value in fixed.items(): if key in data and data[key] != value: changed.append(key) data[key] = value old_profile = payload.get("backend") != "turbo" if old_profile: # Keep links for the user; disable legacy custom weights until deliberately selected. for i in range(1, 4): key = f"user_lora_{i}_scale" if float(data.get(key) or 0) != 0: changed.append(key) data[key] = 0.0 data["qwen_mode"] = QWEN_TURBO data["steps"] = DEFAULT_STEPS data["pad_to_canvas"] = False data["highlight_protection"] = False data["vae_tiling"] = False else: minimum, maximum, default = sampling_limits(OP_QWEN, qwen_mode=data["qwen_mode"]) data["steps"] = max(minimum, min(maximum, int(data.get("steps", default)))) if data.get("resolution_multiple", 32) not in (32, 64, 128): data["resolution_multiple"] = 32 changed.append("resolution_multiple") if old_profile or changed: note = ("Adapted for Qwen Image 2.1: native decoder, all references encoded. " "Old LoRA selections are inactive; custom links are kept. The saved profile file is unchanged.") else: note = "" return data, note def validate_request(data): data = normalize_guidance_request(data) operation = data.get("operation", OP_QWEN) if operation not in OPERATIONS: raise gr.Error("Choose a supported operation.") if operation != OP_QWEN: if not IS_TURBO: raise gr.Error("Image editing operations require QWEN_BACKEND=turbo.") if data.get("input_image_1") is None: raise gr.Error("Upload Image 1 before using this image editing mode.") if operation == OP_FACE: if data.get("input_image_2") is None: raise gr.Error("Face Swap needs Image 1 (target/body) and Image 2 (reference face).") if data.get("input_images_extra"): raise gr.Error("Face Swap uses two images. Remove extra references or choose another operation.") base = str(data.get("face_mode", "")).startswith("Base") if not base and not is_dmd2_request(data): turbo_sigmas(data.get("steps", 6)) elif base and not 4 <= int(data.get("steps", 30)) <= 50: raise gr.Error("Base face swap supports 4-50 steps; 30 is the default.") elif operation == OP_OUTPAINT: mode = data.get("outpaint_mode", OUTPAINT_TURBO) if mode not in (OUTPAINT_TURBO, QWEN_DMD2, OUTPAINT_BASE): raise gr.Error("Choose Turbo, DMD2, or Base for Outpaint.") minimum, maximum, _ = sampling_limits(operation, outpaint_mode=mode) if not minimum <= int(data.get("steps", 25 if mode == OUTPAINT_BASE else 6)) <= maximum: raise gr.Error(f"Outpaint {mode} supports {minimum}-{maximum} steps.") feather = float(data.get("outpaint_feather", 32)) if not math.isfinite(feather) or not 0 <= feather <= 128: raise gr.Error("Outpaint edge blending must be between 0 and 128 pixels.") elif operation == OP_DETAIL: import detail_backend detail_backend.request_canvas(data) elif operation == OP_RELIGHT: import relight_backend relight_backend.request_canvas(data) elif operation == OP_CAMERA: import camera_backend camera_backend.request_canvas(data) else: if len(request_images(data)) > 4: raise gr.Error("MOSS accepts at most four reference images in total.") if not str(data.get("prompt") or "").strip(): raise gr.Error("Describe the image edit first.") if not 1 <= int(data.get("steps", 30)) <= 60: raise gr.Error("MOSS supports 1-60 steps here; 30 is the default.") check_prompt(data.get("prompt") or "") request_canvas(data) return check_prompt(data.get("prompt")) if not str(data.get("prompt") or "").strip(): raise gr.Error("Write a prompt first.") images = request_images(data) if not IS_TURBO and data.get("input_image_1") is None: raise gr.Error("Please upload Image 1.") if IS_TURBO: mode = data.get("qwen_mode", QWEN_TURBO) if mode not in QWEN_MODES: raise gr.Error("Choose Viggle Turbo, DMD2, or Base for Qwen Image Edit.") if mode == QWEN_TURBO: turbo_sigmas(data["steps"]) elif mode == QWEN_BASE: steps_value = float(data.get("steps", 30)) if not math.isfinite(steps_value) or not steps_value.is_integer() or not 4 <= steps_value <= 50: raise gr.Error("Qwen Base supports 4-50 whole steps; 30 is the default.") if len(images) > 10: raise gr.Error("Use at most 10 references; 1-3 are recommended for Qwen Image Edit.") if data.get("lora_adapter") not in (None, NONE_LORA): raise gr.Error("The selected old style LoRA requires QWEN_BACKEND=legacy.") if data.get("fast_lora") not in (None, "", NO_FAST_LORA): raise gr.Error("Old Lightning adapters require legacy mode. Choose Qwen Turbo or Base with its model selector.") if data.get("decoder_vae", "qwen") != "qwen" or data.get("keep_decoder_2x"): raise gr.Error("The WAN decoder is available only in legacy mode.") if data.get("extras_condition_only") or float(data.get("vae_ref_megapixels") or 0) != 0: raise gr.Error("Conditioning-only routing and separate reference VAE sizes require legacy mode.") if lora_requires_two_images(data.get("lora_adapter")) and data.get("input_image_2") is None: raise gr.Error("This LoRA needs Image 2 as well.") request_canvas(data) # Validate dimensions before any download/GPU allocation. def prepare_lora_files(data): """Fetch only active adapters on CPU. Do not mutate UI text or profile references.""" for i in range(1, 4): if float(data.get(f"user_lora_{i}_scale") or 0) <= 0: continue source, uploaded = _resolve_user_slot(data.get(f"user_lora_{i}_file"), data.get(f"user_lora_{i}_ref")) if not source: continue if not uploaded: if is_direct_link(source): source = download_direct_lora(source) else: repo, weight_name = _parse_user_lora_reference(source) source = hf_hub_download(repo_id=repo, filename=weight_name, token=HF_TOKEN) if IS_TURBO: validate_turbo_lora(source) data[f"user_lora_{i}_file"] = source if IS_TURBO: return specs = [] style = ADAPTER_SPECS.get(data.get("lora_adapter"), {}) specs.extend(style.get("parts", []) if style.get("type") == "package" else ([style] if style else [])) fast = FAST_LORAS.get(data.get("fast_lora")) if fast: specs.append(fast) for spec in specs: key = spec["repo"], spec["weights"] if key not in LORA_PREFETCHED: LORA_PREFETCHED[key] = hf_hub_download(repo_id=key[0], filename=key[1], token=HF_TOKEN) # Completed worker timings are separate from the scheduler's protective allowance. # Only anonymous configuration hashes and durations are persisted. import threading as _timing_threading _QWEN_TIMING_LOCK = _timing_threading.RLock() def _qwen_timing_key(data): try: data = normalize_guidance_request(data) images = request_images(data) width, height = request_canvas(data) loras = [] for slot in range(1, 4): scale = float(data.get(f"user_lora_{slot}_scale") or 0) source, uploaded = _resolve_user_slot(data.get(f"user_lora_{slot}_file"), data.get(f"user_lora_{slot}_ref")) if source and scale: loras.append([str(source), scale]) try: from spaces.zero.config import get_config hardware = str(get_config().get("model", "unknown")) except Exception: hardware = "unknown" settings = { "schema": "studio-worker-v2", "operation": data.get("operation", OP_QWEN), "face": [data.get("face_mode"), data.get("face_strength")], "outpaint": [data.get(name) for name in ( "outpaint_mode", "outpaint_left", "outpaint_right", "outpaint_top", "outpaint_bottom", "outpaint_feather")] if data.get("operation") == OP_OUTPAINT else None, "detail": [data.get("detail_mode", DETAIL_TURBO), data.get("detail_strength", 1.0)] if data.get("operation") == OP_DETAIL else None, "qwen_mode": data.get("qwen_mode", QWEN_TURBO) if data.get("operation", OP_QWEN) in QWEN_SHARED_MODES else None, "relight": [data.get(key) for key in ("relight_preset", "relight_direction", "relight_color", "relight_strength")] if data.get("operation") == OP_RELIGHT else None, "camera": [data.get(key) for key in ("camera_azimuth", "camera_elevation", "camera_closeup", "camera_strength")] if data.get("operation") == OP_CAMERA else None, "model": "OpenMOSS/MOSS-Image" if data.get("operation") == OP_MOSS else (BASE_MODEL_ID if IS_TURBO else AIO_REPO_ID), "turbo": [TURBO_REPO, TURBO_FILE] if IS_TURBO else None, "hardware": hardware, "attention": ATTENTION_BACKEND, "canvas": [width, height], "steps": int(data.get("steps", DEFAULT_STEPS)), "references": [list(image.size) for image in images], "cfg": float(data.get("guidance_scale", DEFAULT_CFG)), "style": None if IS_TURBO else data.get("lora_adapter"), "fast": None if IS_TURBO else [data.get("fast_lora"), data.get("fast_lora_strength")], "loras": loras, "options": [data.get(name) for name in ( "extras_condition_only", "pad_to_canvas", "vae_tiling", "resolution_multiple", "vae_ref_megapixels", "decoder_vae", "keep_decoder_2x", "highlight_protection", "highlight_protection_strength", "aspect_ratio")], "prompt_size": (len(str(data.get("prompt") or "")) + 127) // 128, "negative_size": (len(str(data.get("negative_prompt_text") or "")) + 127) // 128 if float(data.get("guidance_scale", DEFAULT_CFG)) > 1 else 0, } return hashlib.sha256(json.dumps(settings, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()).hexdigest() except Exception: return None def _qwen_timing_history(record=None): try: directory = os.path.join(PROFILES_DIR, ".timings") os.makedirs(directory, exist_ok=True) path = os.path.join(directory, "qwen-worker-timings-v1.json") with _QWEN_TIMING_LOCK, open(path, "a+", encoding="utf-8") as stream: try: import fcntl except ImportError: fcntl = None if fcntl is not None: fcntl.flock(stream.fileno(), fcntl.LOCK_EX if record is not None else fcntl.LOCK_SH) stream.seek(0) try: rows = json.load(stream) if not isinstance(rows, list): rows = [] except (ValueError, TypeError): rows = [] if record is not None: rows = (rows + [record])[-200:] stream.seek(0) stream.truncate() json.dump(rows, stream) stream.flush() return rows except (OSError, ValueError, TypeError): return [] def _qwen_record_timing(key, seconds): # A read-only or full cache must never discard a successfully generated image. try: elapsed = float(seconds) if key and math.isfinite(elapsed) and elapsed > 0: _qwen_timing_history({"key": key, "seconds": elapsed}) except Exception: pass def _qwen_worker_samples(data): key = _qwen_timing_key(data) samples = [] if not key: return samples for row in _qwen_timing_history(): try: elapsed = float(row["seconds"]) if row["key"] == key and math.isfinite(elapsed) and elapsed > 0: samples.append(elapsed) except (KeyError, TypeError, ValueError, OverflowError): continue return sorted(samples[-20:]) def _qwen_observed_runtime(samples): if not samples: return None low = samples[max(0, math.ceil(.1 * len(samples)) - 1)] high = samples[math.ceil(.9 * len(samples)) - 1] return max(1, math.floor(low)), max(1, math.ceil(high)), len(samples) def reservation_text(seconds): # Hugging Face lists xlarge at twice the daily quota cost of large. return (f"GPU reservation: **{seconds} s** on xlarge (2×) · " f"**{2 * seconds} quota seconds** at the published rate") @functools.wraps(infer) def _timed_infer(*args, **kwargs): import time started = time.perf_counter() result = infer(*args, **kwargs) return result, time.perf_counter() - started _gpu_infer = spaces.GPU(duration=get_infer_duration, size="xlarge")(_timed_infer) def with_auto_prompt_lora(data): """Choose one general catalogue adapter on CPU for this request only.""" operation = data.get("operation", OP_QWEN) if (not IS_TURBO or operation not in (OP_QWEN, OP_MOSS, OP_FACE, OP_OUTPAINT, OP_DETAIL) or data.get("lora_adapter") not in (None, "", NONE_LORA) or any(data.get(f"user_lora_{i}_file") or str(data.get(f"user_lora_{i}_ref") or "").strip() for i in range(1, 4)) or not requests_nudity(data.get("prompt"))): return data, "" if operation == OP_MOSS: name = "MOSS Image – Better Nudes v3.0" source = "https://civitai.red/api/download/models/3453190?fileId=3353880" else: name = "NSFW Qwen by TheseAlpacas v2" # Same SHA-256 as the Qwen catalogue's Civitai file 3244894. source = "Oliver577/NSFW-Qwen-by-TheseAlpacas-V2/NSFW Qwen by TheseAlpacas V2.safetensors" return dict(data, user_lora_1_ref=source, user_lora_1_scale=1.0), name def prepare_generation_weights(data): if data.get("operation") == OP_MOSS: import moss_backend data["_prepared_data"] = moss_backend.prepare(data) elif data.get("operation") in (OP_FACE, *SINGLE_SOURCE_OPERATIONS): if data.get("operation") == OP_OUTPAINT: import outpaint_backend as edit_backend elif data.get("operation") == OP_DETAIL: import detail_backend as edit_backend elif data.get("operation") == OP_RELIGHT: import relight_backend as edit_backend elif data.get("operation") == OP_CAMERA: import camera_backend as edit_backend else: import bfs_backend as edit_backend edit_data = dict(data) edit_data["width"], edit_data["height"] = request_canvas(data) prepared = edit_backend.prepare(edit_data, token=HF_TOKEN) prepare_lora_files(prepared) data["_prepared_data"] = prepared else: prepare_lora_files(data) if is_dmd2_request(data): data["_prepared_data"] = { **(data.get("_prepared_data") or {}), "dmd2_path": hf_hub_download(repo_id=DMD2_REPO, filename=DMD2_FILE, token=HF_TOKEN), } @functools.wraps(infer) def run_inference(*args, **kwargs): bound = inspect.signature(infer).bind(*args, **kwargs) bound.apply_defaults() original = normalize_guidance_request(bound.arguments) validate_request(original) data, auto_name = with_auto_prompt_lora(original) # Compute from sources before downloads replace them with worker-local paths. timing_key = _qwen_timing_key(data) try: prepare_generation_weights(data) except Exception: if not auto_name: raise # Only CPU preparation can fall back. Never repeat a GPU allocation. data = original timing_key = _qwen_timing_key(data) prepare_generation_weights(data) print(f"[auto-lora] {auto_name} unavailable; using original request", flush=True) auto_name = "" # Only this call allocates GPU time. Image generation is local to this Space. result, worker_seconds = _gpu_infer(**data) if auto_name: print(f"[auto-lora] completed {data['operation']} with {auto_name} at strength 1.0", flush=True) _qwen_record_timing(timing_key, worker_seconds) return result # ============================================================ # UI # ============================================================ # ============================================================ # Prompt building and enhancement # ============================================================ # Two paths. The builder is pure string work: it wraps the instruction you typed # in the edit language this model responds to, plus the clause that keeps the # person in the photo the same person. Instant, no GPU, nothing to refuse. # # The model path calls the user's Qwen3.8 writing Space once, combining # prompt preparation with compatible LoRA selection and strengths. EDIT_KINDS = { "(keep as written)": "", "relight the scene": "relight the scene", "change the camera angle": "render the same subject from a different camera angle", "change the outfit": "change the outfit", "change the background": "replace the background", "add something to the scene": "add to the scene", "remove something": "remove from the scene", "change the pose": "change the pose", "change the expression": "change the facial expression", "restyle the image": "restyle the image", "sharpen and add detail": "sharpen the image and recover fine detail", } EDIT_ANGLES = { "(keep as written)": "", "extreme close-up": "framed as an extreme close-up", "close-up": "framed as a close-up", "medium shot": "framed as a medium shot", "full body": "framed as a full-body shot", "from below": "seen from a low angle", "from above": "seen from a high angle", "from behind": "seen from behind", "three-quarter view": "seen in three-quarter view", "profile": "seen in profile", } EDIT_LIGHTING = { "(keep as written)": "", "soft natural light": "lit by soft natural light with gentle falloff", "golden hour": "lit by warm golden-hour light with a soft rim", "hard key light": "lit by a hard key light with deep shadows", "candle / firelight": "lit by flickering warm candlelight", "neon night": "lit by neon light with wet reflections at night", "overcast daylight": "lit by flat overcast daylight", "studio softbox": "lit by a clean studio softbox on a plain backdrop", "single lamp in a dark room": "lit by one warm lamp in an otherwise dark room", "moonlight": "lit by cool moonlight through a window", } EDIT_LOOKS = { "(keep as written)": "", "photorealistic": "photorealistic, natural skin texture and pores", "film photo": "shot on film, fine grain, muted colours", "editorial studio": "editorial studio photography, clean and sharp", "candid phone photo": "a candid phone snapshot, slightly imperfect", "cinematic still": "a cinematic still, shallow depth of field", "illustration": "a clean digital illustration", "anime": "anime style, crisp lineart", } IDENTITY_TAIL = ( "Keep the same person, face, hair and body proportions as the input image, " "and keep everything else in the frame unchanged" ) def _strip_built(text): """Remove sentences a previous Build added, so pressing it again rewrites rather than stacks.""" known = {IDENTITY_TAIL.lower().rstrip(".")} for table, lead in ((EDIT_ANGLES, ""), (EDIT_LIGHTING, ""), (EDIT_LOOKS, "render it as ")): for value in table.values(): if value: known.add((lead + value).lower().rstrip(".")) for angle in EDIT_ANGLES.values(): for light in EDIT_LIGHTING.values(): joined = ", ".join(part for part in (angle, light) if part) if joined: known.add(("the subject is " + joined).lower().rstrip(".")) kept = [] for sentence in re.split(r"(?<=\.)\s+", (text or "").strip()): if sentence.strip().lower().rstrip(".") not in known: kept.append(sentence.strip()) return " ".join(kept).strip() def build_edit_prompt(prompt, kind, angle, lighting, look, keep_identity=True): """Wrap the typed instruction in edit language. No model, no network - it only ever adds to your own words, and it replaces what it added last time.""" body = _strip_built(prompt).strip().rstrip(".,;") if not body and not EDIT_KINDS.get(kind): raise gr.Error("Write what to change first, or pick an edit type.") lead = EDIT_KINDS.get(kind, "") if lead and body: sentence = f"{lead[0].upper() + lead[1:]}: {body}." elif lead: sentence = lead[0].upper() + lead[1:] + "." else: sentence = body[0].upper() + body[1:] + "." parts = [sentence] detail = ", ".join( part for part in (EDIT_ANGLES.get(angle, ""), EDIT_LIGHTING.get(lighting, "")) if part ) if detail: parts.append("The subject is " + detail + ".") if EDIT_LOOKS.get(look): parts.append("Render it as " + EDIT_LOOKS[look] + ".") if keep_identity: parts.append(IDENTITY_TAIL + ".") return " ".join(parts) # ============================================================ # Named profiles # ============================================================ # Everything typed rather than uploaded, stored under a name inside the Space. # `/data` is used when the Space has persistent storage attached, so profiles # survive a restart; otherwise they live for as long as the Space runs. import time if os.path.isdir("/data") and os.access("/data", os.W_OK): PROFILES_DIR = os.path.join("/data", "qie-profiles") else: PROFILES_DIR = os.path.join(tempfile.gettempdir(), "qie-profiles") os.makedirs(PROFILES_DIR, exist_ok=True) # Embed after PROFILES_DIR and the original ADAPTER_SPECS/LORA_PRESET_PROMPTS. # This catalogue stores references and metadata only; it never downloads weights. import threading import html from datetime import datetime, timezone LORA_LIBRARY_MODELS = ["qwen-image-2.1", "qwen-edit-2511", "qwen-edit-2509"] LORA_LIBRARY_DIR = os.path.join(PROFILES_DIR, "lora-library") from moss_catalog import MossCatalog MOSS_CATALOG = MossCatalog(cache_dir=os.path.join(PROFILES_DIR, "moss-lora-library")) LORA_LIBRARY_FILE = os.path.join(LORA_LIBRARY_DIR, "catalog.json") _LORA_LIBRARY_LOCK = threading.RLock() _LORA_LIBRARY_VERSION = 1 # Curated from model cards and safetensors headers, verified 2026-09-25. # These are editing adapters; their Turbo output quality remains experimental. _LORA_LIBRARY_QWEN21_SEEDS = [ { "id": "seed-qwen21-anime-consistency", "name": "Anime Consistency", "source": "WarmBloodAban/Qwen-Image-2.1-LoRAs/Qwen2.1_Anime_consistency.safetensors", "model": "qwen-image-2.1", "trigger": "", "strength": 0.7, "author": "WarmBloodAban", "added_at": "2026-09-25T00:00:00.000000Z", "published_at": "2026-09-20T22:48:04.000Z", "builtin": True, "modes": ["edit"], "kind": "adapter", "description": "Experimental anime character consistency for image editing, model sheets and facial expressions.", }, { "id": "seed-qwen21-natural-exposure", "name": "Natural Exposure", "source": "prithivMLmods/Qwen-Image-2.1-Natural-Exposure-LoRA/Qwen-Image-2.1-Natural-Exposure-LoRA-4000.safetensors", "model": "qwen-image-2.1", "trigger": "Transform the image with balanced neutral exposure", "strength": 1.0, "author": "prithivMLmods", "added_at": "2026-09-25T00:00:00.000000Z", "published_at": "2026-09-23T06:52:09.000Z", "builtin": True, "modes": ["edit"], "kind": "adapter", "description": "Experimental balanced, neutral exposure editing while preserving natural colors, detail and image consistency.", }, ] # Explicit catalogue provenance, never guessed from a custom filename or URL. # The 2511 tags identify entries carried by the original 2511 app; they do not # assert a newly verified training base or guarantee model output quality. _LORA_LIBRARY_STYLE_MODELS = { "Consistance": "qwen-edit-2511", "Semirealistic-photo-detailer": "qwen-edit-2511", "AnyPose": "qwen-edit-2511", "Any2Real_2601": "qwen-edit-2511", "Hyperrealistic-Portrait": "qwen-edit-2511", "Ultrarealistic-Portrait": "qwen-edit-2511", "BFS-Best-FaceSwap": "qwen-edit-2511", "BFS-Best-FaceSwap-merge": "qwen-edit-2511", "F2P": "qwen-edit-2509", "Multiple-Angles": "qwen-edit-2509", "Light-Restoration": "qwen-edit-2509", "Relight": "qwen-edit-2509", "Multi-Angle-Lighting": "qwen-edit-2509", "Edit-Skin": "qwen-edit-2511", "Next-Scene": "qwen-edit-2509", "Flat-Log": "qwen-edit-2509", "Upscale-Image": "qwen-edit-2509", "Upscale2K": "qwen-edit-2509", "Photo-to-Anime": "qwen-edit-2509", "Anime-V2": "qwen-edit-2511", "Light-Migration": "qwen-edit-2509", "Style-Transfer": "qwen-edit-2511", "Manga-Tone": "qwen-edit-2509", "Anything2Real": "qwen-edit-2511", "Fal-Multiple-Angles": "qwen-edit-2511", "Polaroid-Photo": "qwen-edit-2511", "Unblur-Anything": "qwen-edit-2511", "Midnight-Noir-Eyes-Spotlight": "qwen-edit-2511", "Hyper-Realistic-Portrait": "qwen-edit-2511", "Ultra-Realistic-Portrait": "qwen-edit-2511", "Pixar-Inspired-3D": "qwen-edit-2511", "Noir-Comic-Book": "qwen-edit-2511", "Any-light": "qwen-edit-2511", "Studio-DeLight": "qwen-edit-2511", } def _lora_library_now(): return datetime.now(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z") def _lora_library_model(value): aliases = { "qwen-image-2.1": "qwen-image-2.1", "qwen image 2.1": "qwen-image-2.1", "qwen 2.1": "qwen-image-2.1", "qwen2.1": "qwen-image-2.1", "qwen/qwen-image-2.1": "qwen-image-2.1", "qwen-edit-2511": "qwen-edit-2511", "qwen-image-edit-2511": "qwen-edit-2511", "qwen image edit 2511": "qwen-edit-2511", "qwen/qwen-image-edit-2511": "qwen-edit-2511", "qwen-edit-2509": "qwen-edit-2509", "qwen-image-edit-2509": "qwen-edit-2509", "qwen image edit 2509": "qwen-edit-2509", "qwen/qwen-image-edit-2509": "qwen-edit-2509", } model = aliases.get(str(value or "").strip().lower()) if model is None: raise gr.Error("Choose an explicit model tag: qwen-image-2.1, qwen-edit-2511, or qwen-edit-2509.") return model def _lora_library_source(value): source = str(value or "").strip().strip("\"'") if not source or len(source) > 4096 or any(ord(char) < 32 for char in source): raise gr.Error("Provide a valid LoRA URL or owner/repo[/file.safetensors] reference.") parsed = urllib.parse.urlparse(source) if parsed.scheme: if parsed.scheme not in ("http", "https") or not parsed.hostname or parsed.username or parsed.password: raise gr.Error("Use an HTTP(S) download URL without embedded login credentials, or a Hugging Face reference.") return source parts = source.split("/") if (len(parts) < 2 or not re.fullmatch(r"[A-Za-z0-9_.-]+", parts[0]) or not re.fullmatch(r"[A-Za-z0-9_.-]+", parts[1]) or any(part in ("", ".", "..") for part in parts) or "\\" in source or (len(parts) > 2 and not source.lower().endswith(".safetensors"))): raise gr.Error("Store a LoRA URL or owner/repo[/file.safetensors], not a local file path.") return source def _lora_library_timestamp(value): if value in (None, ""): return _lora_library_now() try: if isinstance(value, (int, float)) and not isinstance(value, bool): stamp = datetime.fromtimestamp(value, timezone.utc) else: stamp = datetime.fromisoformat(str(value).replace("Z", "+00:00")) if stamp.tzinfo is None: stamp = stamp.replace(tzinfo=timezone.utc) return stamp.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z") except (TypeError, ValueError, OverflowError) as error: raise gr.Error("An entry's added_at must be an ISO date or Unix timestamp.") from error def _lora_library_clean_item(raw, default_model=None, fallback_name=""): if isinstance(raw, str): raw = {"source": raw, "name": fallback_name} if not isinstance(raw, dict): raise gr.Error("Every library entry must be an object or a source reference.") model = _lora_library_model(raw.get("model") or raw.get("base_model") or raw.get("baseModel") or default_model) source = raw.get("source") or raw.get("reference") or raw.get("url") or raw.get("download_url") if not source: source = raw.get("repo") or raw.get("repo_id") weight = raw.get("weights") or raw.get("weight_name") or raw.get("filename") if source and weight: source = str(source).rstrip("/") + "/" + str(weight).lstrip("/") source = _lora_library_source(source) name = str(raw.get("name") or raw.get("title") or fallback_name or "").strip() if not name or len(name) > 160: raise gr.Error("Give each library entry a name of 1–160 characters.") try: strength = float(raw.get("strength", raw.get("scale", raw.get("default_strength", 1.0)))) if not math.isfinite(strength) or not 0 <= strength <= 2: raise ValueError except (TypeError, ValueError): raise gr.Error("Default LoRA strength must be between 0 and 2.") trigger = raw.get("trigger", raw.get("trigger_words", raw.get("trainedWords", ""))) if isinstance(trigger, list): trigger = ", ".join(str(word).strip() for word in trigger if str(word).strip()) trigger = str(trigger or "").strip() author = str(raw.get("author") or "").strip() if len(trigger) > 2000 or len(author) > 160: raise gr.Error("Use at most 2,000 characters for triggers and 160 for the author.") modes = raw.get("modes", ["edit", "t2i"]) if isinstance(modes, str): modes = [modes] if isinstance(modes, list): modes = ["t2i" if mode == "text-to-image" else mode for mode in modes] if not isinstance(modes, list) or not modes or any(mode not in ("edit", "t2i") for mode in modes): raise gr.Error("Library modes must contain edit, text-to-image, or both.") digest = hashlib.sha256((model + "\n" + source).encode("utf-8")).hexdigest()[:24] return {"id": "custom-" + digest, "name": name, "source": source, "model": model, "trigger": trigger, "strength": strength, "author": author, "modes": list(dict.fromkeys(modes)), "kind": "adapter", "added_at": _lora_library_timestamp(raw.get("added_at", raw.get("created_at")))} def _lora_library_decode(payload, default_model=None): if isinstance(payload, dict): if "items" in payload: if payload.get("version", 1) != _LORA_LIBRARY_VERSION: raise gr.Error("This library file uses an unsupported version.") payload = payload["items"] elif "loras" in payload: payload = payload["loras"] elif any(key in payload for key in ("source", "reference", "url", "repo", "repo_id")): payload = [payload] if isinstance(payload, dict): records = [(name, item) for name, item in payload.items() if name not in {"version", "schema_version", "exported_at", "metadata"}] elif isinstance(payload, list): records = [("", item) for item in payload] else: raise gr.Error("Import a {version, items} library, a list of entries, or a name-to-entry mapping.") if len(records) > 2000: raise gr.Error("Import at most 2,000 library entries at once.") result = {} for name, raw in records: item = _lora_library_clean_item(raw, default_model, str(name)) if item["id"] in result: item["added_at"] = result[item["id"]]["added_at"] result[item["id"]] = item return list(result.values()) @contextmanager def _lora_library_transaction(): # Threads share the RLock; flock also serializes multiple Linux workers. with _LORA_LIBRARY_LOCK: os.makedirs(LORA_LIBRARY_DIR, exist_ok=True) with open(os.path.join(LORA_LIBRARY_DIR, "catalog.lock"), "a", encoding="utf-8") as lock_file: try: import fcntl except ImportError: fcntl = None if fcntl is not None: fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX) try: yield finally: if fcntl is not None: fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN) def _lora_library_read(): if not os.path.exists(LORA_LIBRARY_FILE): return [] try: with open(LORA_LIBRARY_FILE, encoding="utf-8") as handle: return _lora_library_decode(json.load(handle)) except (OSError, ValueError) as error: raise gr.Error("The saved LoRA library could not be read. Its existing file has been left intact.") from error def _lora_library_write(items): path = None try: with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=LORA_LIBRARY_DIR, prefix="catalog-", suffix=".tmp", delete=False) as handle: path = handle.name json.dump({"version": _LORA_LIBRARY_VERSION, "items": items}, handle, ensure_ascii=False, indent=2) handle.flush() os.fsync(handle.fileno()) os.replace(path, LORA_LIBRARY_FILE) finally: if path and os.path.exists(path): os.remove(path) def _lora_library_builtins(): entries = [dict(entry, modes=list(entry["modes"])) for entry in _LORA_LIBRARY_QWEN21_SEEDS] for name, spec in ADAPTER_SPECS.items(): model = _LORA_LIBRARY_STYLE_MODELS.get(name) if model is None: continue # New styles need an explicit tag, never filename guessing. parts = spec.get("parts", []) if spec.get("type") == "package" else [spec] sources = [part["repo"] + "/" + part["weights"] for part in parts] if not sources: continue entries.append({ "id": "builtin-style-" + hashlib.sha256(name.encode("utf-8")).hexdigest()[:16], "name": name, "source": sources[0], "sources": sources, "model": model, "trigger": "", "strength": float(spec.get("strength", 1.0)), "author": parts[0]["repo"].split("/")[0], "added_at": "", "builtin": True, "style_name": name, "package": len(parts) > 1, "modes": ["edit"], "kind": "style", }) return entries def lora_library_compatible(entry): """Metadata filter only; actual tensor compatibility is checked before GPU use.""" if _ACTIVE_OPERATION.get() == OP_MOSS: return isinstance(entry, dict) and entry.get("model") == "moss-image" models = {"qwen-image-2.1"} if IS_TURBO else {"qwen-edit-2511", "qwen-edit-2509"} return isinstance(entry, dict) and entry.get("model") in models def lora_library_entries(query=""): """Current backend's candidate pool, newest first; includes style/package metadata.""" return _lora_library_entries(query) def lora_library_get(entry_id): """Resolve an exact saved ID, rechecking current-backend compatibility.""" return _lora_library_find(entry_id) def _lora_library_find(entry_id): entry = next((entry for entry in _lora_library_entries() if entry["id"] == entry_id), None) if entry is None: raise gr.Error("Select an entry compatible with the current backend. Refresh the library if it changed.") return entry def lora_library_describe(entry_id): if not entry_id: return "Add or import a LoRA with an explicit model tag to start your library." entry = _lora_library_find(entry_id) esc = lambda value: html.escape(str(value)).replace("`", "`") lines = [f"**{esc(entry['name'])}** · `{entry['model']}`", "Bundled editing style (read-only)." if entry.get("style_name") else f"Default strength: {entry['strength']:g} · added {esc(entry['added_at'])}"] if entry.get("description"): lines.append(esc(entry["description"])) lines.append("Use: " + ", ".join("text-to-image" if mode == "t2i" else mode for mode in entry.get("modes", ["edit", "t2i"]))) if entry.get("author"): lines.append("Author: " + esc(entry["author"])) lines.extend("Source: `" + esc(source) + "`" for source in entry.get("sources", [entry["source"]])) if entry.get("trigger"): lines.append("Triggers: " + esc(entry["trigger"])) if entry.get("package"): lines.append("Applying this selects the whole bundled package in Editing style.") if not entry.get("builtin"): lines.append("The model tag is declared metadata; weight compatibility is checked before generation.") return " \n".join(lines) def lora_library_apply(entry_id, slot, current_prompt): """Outputs: ref1,file1,scale1,ref2,file2,scale2,ref3,file3,scale3,style,prompt,status.""" entry = _lora_library_find(entry_id) updates = [gr.update() for _ in range(11)] if entry.get("style_name"): updates[9] = gr.update(value=entry["style_name"]) preset = LORA_PRESET_PROMPTS.get(entry["style_name"], "") if preset and not str(current_prompt or "").strip(): updates[10] = gr.update(value=preset) return [*updates, f"Selected bundled style {entry['name']}. Custom slots are unchanged."] match = re.search(r"([123])$", str(slot).strip()) if not match: raise gr.Error("Choose custom slot 1, 2, or 3.") index = int(match.group(1)) - 1 updates[index * 3:index * 3 + 3] = [gr.update(value=entry["source"]), gr.update(value=None), gr.update(value=entry["strength"])] prompt = str(current_prompt or "") words = [word.strip() for word in entry.get("trigger", "").split(",") if word.strip()] additions = [word for word in words if word.casefold() not in prompt.casefold()] if additions: prompt = prompt.rstrip(", ") + (", " if prompt.strip() else "") + ", ".join(dict.fromkeys(additions)) prompt = ensure_operation_prompt(_ACTIVE_OPERATION.get(), prompt) if prompt != str(current_prompt or ""): updates[10] = gr.update(value=prompt) return [*updates, f"Applied {entry['name']} to custom slot {index + 1} at strength {entry['strength']:g}."] # Embed AFTER the local LoRA-library helpers and BEFORE building the Gradio UI. # Overrides their public callbacks without changing call signatures. # Wire a separate "Sync shared library" button to: # lora_library_sync(query, selected_id) -> [library_picker, library_status] # Optionally use the same callback on demo.load for a read-only initial sync. # Keep the prompt-helper Refresh callback local: it calls lora_library_entries(). # No function here runs a network request at import. Only Add/Delete/Import write. import copy as _library_copy import time as _library_time REMOTE_LORA_BUCKET = os.environ.get("LORA_LIBRARY_BUCKET", "amisima/qwen2.1-lora").strip().strip("/") REMOTE_LORA_FILE = os.environ.get("LORA_LIBRARY_FILE", "library.json").strip().strip("/") REMOTE_LORA_DEFAULT_MODEL = "qwen-image-2.1" # Explicit default for this user's dedicated bucket. _REMOTE_LORA_KEY = hashlib.sha256((REMOTE_LORA_BUCKET + "/" + REMOTE_LORA_FILE).encode()).hexdigest()[:16] _REMOTE_LORA_CACHE = os.path.join(LORA_LIBRARY_DIR, "remote-" + _REMOTE_LORA_KEY + ".json") _REMOTE_LORA_PENDING = os.path.join(LORA_LIBRARY_DIR, "pending-" + _REMOTE_LORA_KEY + ".json") _REMOTE_LORA_NOTICE = "Shared library not synced yet; local entries are available." def _bucket_token(): return (os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_HUB_TOKEN") or "").strip() def _bucket_path(): if (not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", REMOTE_LORA_BUCKET) or any(part in ("", ".", "..") for part in REMOTE_LORA_FILE.split("/")) or "\\" in REMOTE_LORA_FILE): raise ValueError("Check LORA_LIBRARY_BUCKET and LORA_LIBRARY_FILE in the Space settings.") return f"buckets/{REMOTE_LORA_BUCKET}/{REMOTE_LORA_FILE}" def _bucket_local_json(path, default): if not os.path.exists(path): return _library_copy.deepcopy(default) with open(path, encoding="utf-8") as handle: return json.load(handle) def _bucket_local_write(path, value): temporary = None try: with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=LORA_LIBRARY_DIR, prefix="shared-", suffix=".tmp", delete=False) as handle: temporary = handle.name json.dump(value, handle, ensure_ascii=False, indent=2) handle.flush() os.fsync(handle.fileno()) os.replace(temporary, path) finally: if temporary and os.path.exists(temporary): os.remove(temporary) def _bucket_rows(payload): if isinstance(payload, list): return None, payload if isinstance(payload, dict): key = "normal" if "normal" in payload else "items" if "items" in payload else None if key and isinstance(payload[key], list): return key, payload[key] raise ValueError("The shared library must contain a normal/items list, or be a list of entries.") def _bucket_entry(raw): if not isinstance(raw, dict) or raw.get("high") or raw.get("low"): return None # Preserve paired video records remotely; never apply them as image LoRAs. item = dict(raw) item.setdefault("added_at", item.get("added") or "1970-01-01T00:00:00Z") # The old browser-owner key identifies deletion ownership, not the author. item.setdefault("author", "") try: clean = _lora_library_clean_item(item, REMOTE_LORA_DEFAULT_MODEL) except Exception: return None clean["remote"] = True if raw.get("page"): clean["page"] = raw["page"] return clean def _bucket_parsed(payload): _, rows = _bucket_rows(payload) return [entry for raw in rows if (entry := _bucket_entry(raw)) is not None] def _bucket_get_json(url): # Public reads do not carry the Space owner's token. Use it only when the # same Hugging Face endpoint requires authentication (e.g. a private bucket). headers = {"Accept": "application/json"} response = requests.get(url, headers=headers, params={"cb": str(_library_time.time_ns())}, timeout=(10, 30), stream=True) if response.status_code in (401, 403) and _bucket_token(): response.close() headers["Authorization"] = "Bearer " + _bucket_token() response = requests.get(url, headers=headers, params={"cb": str(_library_time.time_ns())}, timeout=(10, 30), stream=True) try: if response.status_code == 404: return None if response.status_code != 200: raise RuntimeError(f"Hugging Face read returned HTTP {response.status_code}.") content = bytearray() for chunk in response.iter_content(65536): content.extend(chunk) if len(content) > 4 * 1024 * 1024: raise ValueError("The shared catalogue exceeds the 4 MB JSON limit.") return json.loads(content) finally: response.close() def _bucket_read_remote(): _bucket_path() url = f"https://huggingface.co/buckets/{REMOTE_LORA_BUCKET}/resolve/{urllib.parse.quote(REMOTE_LORA_FILE, safe='/')}" payload = _bucket_get_json(url) if payload is None: # A missing file is an empty catalogue only after the bucket itself has # been read successfully. A read/auth failure must never justify a write. metadata = _bucket_get_json(f"https://huggingface.co/api/buckets/{REMOTE_LORA_BUCKET}") if not isinstance(metadata, dict) or metadata.get("repoType") != "bucket": raise RuntimeError("The configured storage bucket could not be read.") payload = {"normal": []} _bucket_rows(payload) return payload def _bucket_write_remote(payload): token = _bucket_token() if not token: raise RuntimeError("HF_TOKEN with bucket write access is not configured.") from huggingface_hub import HfFileSystem content = json.dumps(payload, ensure_ascii=False, indent=2, allow_nan=False).encode("utf-8") if len(content) > 4 * 1024 * 1024: raise ValueError("The shared catalogue would exceed the 4 MB JSON limit; nothing was written.") with HfFileSystem(token=token).open(_bucket_path(), "wb") as handle: handle.write(content) def _bucket_pending(): value = _bucket_local_json(_REMOTE_LORA_PENDING, {"upserts": {}, "deleted": []}) if not isinstance(value, dict) or not isinstance(value.get("upserts"), dict) or not isinstance(value.get("deleted"), list): raise ValueError("The locally pending library changes could not be read.") return value def _bucket_apply(payload, upserts, deleted): """Merge entry changes while preserving unknown root/entry metadata.""" result = _library_copy.deepcopy(payload) key, rows = _bucket_rows(result) additions = dict(upserts) output = [] for raw in rows: parsed = _bucket_entry(raw) item_id = parsed["id"] if parsed else None if item_id in deleted: continue if item_id in additions: changed = additions.pop(item_id) raw = {**raw, **changed, "url": changed["source"], "added": changed["added_at"]} raw.pop("remote", None) output.append(raw) for changed in additions.values(): output.append({**changed, "url": changed["source"], "added": changed["added_at"]}) output[-1].pop("remote", None) if key is None: return output result[key] = output return result def _bucket_commit(upserts=(), deleted=()): """Called only by explicit Add/Delete/Import actions, never by refresh.""" global _REMOTE_LORA_NOTICE with _lora_library_transaction(): local = {entry["id"]: entry for entry in _lora_library_read()} pending = _bucket_pending() for entry in upserts: entry = dict(entry) previous = local.get(entry["id"]) or pending["upserts"].get(entry["id"]) if previous: entry["added_at"] = previous["added_at"] local[entry["id"]] = entry pending["upserts"][entry["id"]] = entry pending["deleted"] = [key for key in pending["deleted"] if key != entry["id"]] for item_id in deleted: local.pop(item_id, None) pending["upserts"].pop(item_id, None) if item_id not in pending["deleted"]: pending["deleted"].append(item_id) _lora_library_write(list(local.values())) _bucket_local_write(_REMOTE_LORA_PENDING, pending) if not _bucket_token(): _REMOTE_LORA_NOTICE = "Saved locally. Add HF_TOKEN with bucket write access to save future changes to the shared library." return try: fresh = _bucket_read_remote() # Must succeed immediately before every write. remote_ids = {entry["id"] for entry in _bucket_parsed(fresh)} changes = {key: entry for key, entry in local.items() if key not in remote_ids} changes.update(pending["upserts"]) merged = _bucket_apply(fresh, changes, set(pending["deleted"])) _bucket_write_remote(merged) verified = _bucket_read_remote() if verified != merged: raise RuntimeError("The shared file changed or could not be verified after saving; no retry was made.") _bucket_local_write(_REMOTE_LORA_CACHE, verified) synced_ids = {entry["id"] for entry in _bucket_parsed(verified)} # The verified cache is the readable backup for synced rows. Keeping # another local copy would resurrect an entry deleted by another app. _lora_library_write([entry for entry in local.values() if entry["id"] not in synced_ids]) _bucket_local_write(_REMOTE_LORA_PENDING, {"upserts": {}, "deleted": []}) _REMOTE_LORA_NOTICE = f"Saved to {REMOTE_LORA_BUCKET}/{REMOTE_LORA_FILE}." except Exception as error: # Never print response URLs or tokens; local edits remain usable and # pending until another explicit write action can safely merge them. _REMOTE_LORA_NOTICE = f"Saved locally; shared save was not confirmed ({type(error).__name__}). No retry was made." def _lora_library_entries(query=""): if _ACTIVE_OPERATION.get() == OP_MOSS: return MOSS_CATALOG.entries(query) with _lora_library_transaction(): local = _lora_library_read() cached = _bucket_local_json(_REMOTE_LORA_CACHE, {"normal": []}) remote = _bucket_parsed(cached) pending = _bucket_pending() # Shared rows win over old local copies; pending explicit local edits win # until a verified write completes. Other local custom rows are preserved. entries = {entry["id"]: entry for entry in local} entries.update({entry["id"]: entry for entry in remote}) entries.update(pending["upserts"]) for item_id in pending["deleted"]: entries.pop(item_id, None) builtins = _lora_library_builtins() if any(lora_library_compatible(entry) for entry in remote): builtins = [entry for entry in builtins if entry.get("style_name")] values = list(entries.values()) + builtins terms = str(query or "").casefold().split() values = [entry for entry in values if lora_library_compatible(entry) and all(term in " ".join(str(entry.get(key, "")) for key in ("name", "source", "model", "trigger", "author")).casefold() for term in terms)] return sorted(values, key=lambda entry: (entry.get("added_at", ""), entry["name"].casefold(), entry["id"]), reverse=True) def lora_library_refresh(query="", selected_id=None): if _ACTIVE_OPERATION.get() == OP_MOSS: return MOSS_CATALOG.refresh(query, selected_id) entries = _lora_library_entries(query) selected = selected_id if any(entry["id"] == selected_id for entry in entries) else (entries[0]["id"] if entries else None) choices = [(f"{entry['name']} · {entry['model']}" + (" · bundled" if entry.get("builtin") else ""), entry["id"]) for entry in entries] return gr.update(choices=choices, value=selected), f"{len(entries)} compatible entries · newest added first. {_REMOTE_LORA_NOTICE}" def lora_library_sync(query="", selected_id=None): global _REMOTE_LORA_NOTICE if _ACTIVE_OPERATION.get() == OP_MOSS: return MOSS_CATALOG.sync(query, selected_id) try: with _lora_library_transaction(): fresh = _bucket_read_remote() _bucket_local_write(_REMOTE_LORA_CACHE, fresh) count = len(_bucket_parsed(fresh)) _REMOTE_LORA_NOTICE = f"Synced {count} shared entries from {REMOTE_LORA_BUCKET}. Local pending changes are kept; refresh never writes." except Exception as error: _REMOTE_LORA_NOTICE = f"Shared refresh failed ({type(error).__name__}); using the last cache and local entries." return lora_library_refresh(query, selected_id) def lora_library_add(name, source, model, trigger="", strength=1.0, author="", query=""): if _ACTIVE_OPERATION.get() == OP_MOSS: return MOSS_CATALOG.add(name, source, model, trigger, strength, author, query, write_token=_CATALOG_WRITE_TOKEN.get()) entry = _lora_library_clean_item({"name": name, "source": source, "model": model, "trigger": trigger, "strength": strength, "author": author}) previous = next((item for item in _lora_library_entries() if item["id"] == entry["id"]), None) if previous: entry["added_at"] = previous["added_at"] entry["modes"] = previous.get("modes", entry["modes"]) _bucket_commit([entry]) return lora_library_refresh(query, entry["id"]) def lora_library_delete(entry_id, query=""): if _ACTIVE_OPERATION.get() == OP_MOSS: return MOSS_CATALOG.delete(entry_id, query, write_token=_CATALOG_WRITE_TOKEN.get()) entry = _lora_library_find(entry_id) if entry.get("builtin"): raise gr.Error("Bundled fallback entries are read-only.") _bucket_commit(deleted=[entry_id]) return lora_library_refresh(query) def lora_library_import(path, default_model=None, query=""): if _ACTIVE_OPERATION.get() == OP_MOSS: return MOSS_CATALOG.import_file(path, default_model or "moss-image", query, write_token=_CATALOG_WRITE_TOKEN.get()) path = path if isinstance(path, str) else getattr(path, "name", "") if not path or os.path.getsize(path) > 4 * 1024 * 1024: raise gr.Error("Choose a library JSON file smaller than 4 MB.") with open(path, encoding="utf-8") as handle: payload = json.load(handle) if isinstance(payload, dict) and "normal" in payload: incoming = [] for raw in payload["normal"]: if not isinstance(raw, dict) or raw.get("high") or raw.get("low"): continue row = dict(raw) row.setdefault("added_at", row.get("added")) clean = _lora_library_clean_item(row, default_model or REMOTE_LORA_DEFAULT_MODEL) # Keep optional page/owner/other import metadata in the stored row; # only the normalized fields participate in applying an adapter. incoming.append({**row, **clean}) else: incoming = _lora_library_decode(payload, default_model) _bucket_commit(incoming) return lora_library_refresh(query) def lora_library_export(): if _ACTIVE_OPERATION.get() == OP_MOSS: return MOSS_CATALOG.export() # Export the cached shared payload plus pending/local custom entries without # dropping unknown fields or writing anything back to the bucket. with _lora_library_transaction(): payload = _bucket_local_json(_REMOTE_LORA_CACHE, {"normal": []}) pending = _bucket_pending() remote_ids = {entry["id"] for entry in _bucket_parsed(payload)} upserts = {entry["id"]: entry for entry in _lora_library_read() if entry["id"] not in remote_ids} upserts.update(pending["upserts"]) payload = _bucket_apply(payload, upserts, set(pending["deleted"])) with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", prefix="qwen-shared-library-", suffix=".json", delete=False) as handle: json.dump(payload, handle, ensure_ascii=False, indent=2) path = handle.name return gr.update(value=path, visible=True) # Hugging Face bucket writes have no compare-and-swap guard in this integration. # Fresh reads reduce accidental clobbering, but simultaneous writers in separate # apps can still race. Local locks serialize this app only; no auto-retry is used. NO_PROFILE = "— no saved profile —" SETTINGS_KEYS = [ "prompt", "lora_adapter", "fast_lora", "fast_lora_strength", "seed", "randomize_seed", "guidance_scale", "steps", "target_megapixels", "resolution_multiple", "vae_ref_megapixels", "decoder_vae", "keep_decoder_2x", "highlight_protection", "highlight_protection_strength", "extras_condition_only", "pad_to_canvas", "vae_tiling", "user_lora_1_ref", "user_lora_1_scale", "user_lora_2_ref", "user_lora_2_scale", "user_lora_3_ref", "user_lora_3_scale", "negative_prompt_text", "aspect_ratio", "custom_width", "custom_height", "pb_kind", "pb_angle", "pb_lighting", "pb_look", "pb_identity", "pb_use_model", "derived_type", "derived_use_gpu", "ui_mode", "pb_idea", "pb_writer", "pb_suggest_loras", "pb_use_images", "operation", "face_mode", "face_strength", "outpaint_mode", "outpaint_left", "outpaint_right", "outpaint_top", "outpaint_bottom", "outpaint_feather", "detail_mode", "detail_strength", "qwen_mode", "relight_preset", "relight_direction", "relight_color", "relight_strength", "camera_azimuth", "camera_elevation", "camera_closeup", "camera_strength", ] def profile_update(key, payload): if payload.get(key) is None: return gr.update() return gr.update(value=payload[key]) def _profile_file(name): safe = re.sub(r"[^A-Za-z0-9 ._-]", "_", (name or "").strip())[:64].strip() or "profile" return os.path.join(PROFILES_DIR, f"{safe}.json") def list_profiles(): if not os.path.isdir(PROFILES_DIR): return [] return [entry[:-5] for entry in sorted(os.listdir(PROFILES_DIR)) if entry.endswith(".json")] def save_profile(name, *values): if not (name or "").strip(): return gr.update(), "Give the profile a name first." payload = {"saved": time.strftime("%Y-%m-%d %H:%M:%S"), "schema_version": 4, "backend": BACKEND} payload.update(dict(zip(SETTINGS_KEYS, values))) payload = normalize_guidance_request(payload) if "pb_writer" in payload: payload["pb_writer"] = resolve_writer(payload["pb_writer"], DEFAULT_QWEN_SPACE) try: with open(_profile_file(name), "w", encoding="utf-8") as handle: json.dump(payload, handle, ensure_ascii=False, indent=2, default=str) except Exception as error: return gr.update(), f"Could not save: `{type(error).__name__}: {error}`" saved = os.path.basename(_profile_file(name))[:-5] return gr.update(choices=[NO_PROFILE, *list_profiles()], value=saved), f"Saved **{saved}**." def load_profile(name): blank = [gr.update() for _ in SETTINGS_KEYS] if not name or name == NO_PROFILE: return [*blank, gr.update(), ""] path = _profile_file(name) if not os.path.exists(path): return [*blank, gr.update(), f"No profile named **{name}**."] try: with open(path, encoding="utf-8") as handle: payload = json.load(handle) except Exception as error: return [*blank, gr.update(), f"Could not read it: `{type(error).__name__}: {error}`"] payload, note = normalize_profile(payload) updates = [ profile_update(key, payload) for key in SETTINGS_KEYS ] stamp = payload.get("saved", "") return [*updates, gr.update(value=name), f"Loaded **{name}**{f' (saved {stamp})' if stamp else ''}. {note}"] def refresh_profiles(current=None): """Re-read the folder. The dropdown's choices are built once at start-up, so a profile saved in another tab (or after this page was opened) would otherwise stay invisible until a restart.""" names = list_profiles() value = current if current in names else NO_PROFILE return gr.update(choices=[NO_PROFILE, *names], value=value) def delete_profile(name): if not name or name == NO_PROFILE: return gr.update(), "Pick a profile first." try: os.remove(_profile_file(name)) except FileNotFoundError: return gr.update(choices=[NO_PROFILE, *list_profiles()], value=NO_PROFILE), f"No profile named **{name}**." except Exception as error: return gr.update(), f"Could not delete: `{type(error).__name__}: {error}`" return gr.update(choices=[NO_PROFILE, *list_profiles()], value=NO_PROFILE), f"Deleted **{name}**." def export_settings(*values): payload = {"saved": time.strftime("%Y-%m-%d %H:%M:%S"), "schema_version": 4, "backend": BACKEND} payload.update(dict(zip(SETTINGS_KEYS, values))) payload = normalize_guidance_request(payload) if "pb_writer" in payload: payload["pb_writer"] = resolve_writer(payload["pb_writer"], DEFAULT_QWEN_SPACE) directory = os.path.join(tempfile.gettempdir(), "qie-settings") os.makedirs(directory, exist_ok=True) path = os.path.join(directory, f"qie-settings-{int(time.time())}.json") with open(path, "w", encoding="utf-8") as handle: json.dump(payload, handle, ensure_ascii=False, indent=2, default=str) return gr.update(value=path, visible=True) def import_settings(path): if not path: return [gr.update() for _ in SETTINGS_KEYS] try: with open(path, encoding="utf-8") as handle: payload = json.load(handle) except Exception as error: raise gr.Error(f"That settings file cannot be read: `{type(error).__name__}: {error}`") payload, note = normalize_profile(payload) if note: gr.Info(note) return [ profile_update(key, payload) for key in SETTINGS_KEYS ] # ============================================================ # UI helpers # ============================================================ """Shared remote prompt-writer selection; no model weights or credentials here.""" import os ORIGINAL_WRITER = "amisima/Qwen3.8-27B-Uncensored-Demo" def assistant_choices(qwen_space): return [("Qwen3.8 - Original", resolve_writer(qwen_space)), (ECONOMY_LABEL, ECONOMY_SPACE)] def _space_id(writer): value = str(writer or "").strip() for prefix in ("https://huggingface.co/spaces/", "http://huggingface.co/spaces/"): if value.lower().startswith(prefix): value = value[len(prefix):].strip("/") break return value def _retired_writer(writer): """Recognize old saved choices and overrides only to migrate them away.""" value = _space_id(writer).lower() configured = _space_id(os.environ.get("QWEN_FABLE_SPACE", "")).lower() return "fable" in value or bool(configured and value == configured) def supports_images(writer): # The prompt assistant accepts images; never silently strip attachments. return True def resolve_writer(writer, default=ORIGINAL_WRITER): value = _space_id(writer) if not value or _retired_writer(value): value = _space_id(default) if not value or _retired_writer(value): value = ORIGINAL_WRITER return value def prepare_request(writer, message, image=None): target = resolve_writer(writer) return target, message, image def _reply_text(result): if result is None: return "" if isinstance(result, str): return result.strip() if isinstance(result, dict): if result.get("role") in ("user", "system", "tool"): return "" if (result.get("metadata") or {}).get("title"): return "" return _reply_text(result.get("content", result.get("text", ""))) if isinstance(result, (tuple, list)): if result and all(isinstance(item, dict) and "role" in item for item in result): for item in reversed(result): if item.get("role") == "assistant": text = _reply_text(item) if text: return text return "" if result and all(isinstance(item, (tuple, list)) and len(item) == 2 for item in result): return _reply_text(result[-1][1]) if result and all(isinstance(item, dict) and item.get("type") == "text" for item in result): return "\n".join(_reply_text(item) for item in result).strip() for item in reversed(result): text = _reply_text(item) if text: return text return "" def writer_result(result): """Reject incomplete JSON/prompt output, supporting existing Gradio chat APIs.""" if isinstance(result, (tuple, list)) and len(result) == 1: return writer_result(result[0]) if isinstance(result, dict) and result.get("protocol") == "h3-writer-v1": if result.get("finish_reason") != "stop": raise ValueError( "The writer returned an incomplete answer " f"({result.get('finish_reason', 'unknown')}; " f"{result.get('generated_tokens', '?')}/{result.get('max_new_tokens', '?')} tokens). " "No automatic retry was submitted." ) text = str(result.get("text") or "").strip() else: def cut_off(value): if isinstance(value, dict): title = str((value.get("metadata") or {}).get("title", "")).lower() return "cut off" in title or "truncated" in title or cut_off(value.get("content")) return isinstance(value, (tuple, list)) and any(cut_off(item) for item in value) if cut_off(result): raise ValueError("The writer reported a truncated answer. No automatic retry was submitted.") text = _reply_text(result) if not text: raise ValueError("The writer returned no final answer. No automatic retry was submitted.") return text # Qwen prompt + LoRA preparation. Embed after library helpers and prompt builder. # Reuses the user's shared video-Space writer selection/result protocol. import copy DEFAULT_QWEN_SPACE = resolve_writer(os.environ.get("EXPANDER_SPACE", ORIGINAL_WRITER)) QWEN_WRITER_CHOICES = assistant_choices(DEFAULT_QWEN_SPACE) _QWEN_PICK_STOP = set("a an the and or of to in on at for with from this that image photo picture edit generate create same keep subject person woman man scene background quality detailed realistic natural model qwen lora nsfw sfw safetensors version style".split()) def _qwen_words(value): return {word for word in re.findall(r"[\w]+", str(value or "").casefold()) if len(word) > 2 and word not in _QWEN_PICK_STOP and not word.isdigit()} def _qwen_triggers(entry): raw = entry.get("trigger", "") if isinstance(raw, (list, tuple)): raw = ", ".join(map(str, raw)) return list(dict.fromkeys(word.strip() for word in re.split(r"[,\n]+", str(raw)) if word.strip())) def _qwen_pool(has_references=False): pool, seen = [], set() use_mode = "i2i" if _ACTIVE_OPERATION.get() == OP_MOSS else ("edit" if has_references else "t2i") if _ACTIVE_OPERATION.get() == OP_MOSS and not has_references: return [] for item in lora_library_entries(): if (not lora_library_compatible(item) or item.get("package") or item.get("style_name") or (item.get("modes") and use_mode not in item["modes"])): continue # A custom slot cannot reproduce a bundled style's special image routing. spec = ADAPTER_SPECS.get(item.get("style_name"), {}) if spec.get("requires_two_images") or any(key in spec for key in ("target_area", "target_megapixels", "target_long_edge")): continue source = str(item.get("source") or "").strip() if not source or source in seen or not item.get("id"): continue seen.add(source) pool.append(dict(item)) return pool def _qwen_clean_prompt(prompt, state): text = str(prompt or "") record = (state or {}).get("prompt_record") or {} rendered, base = record.get("rendered", ""), record.get("base", "") # Only remove our exact insertion; user-written trigger words are never replaced. if rendered and text.startswith(rendered): return base + text[len(rendered):] return text def _qwen_ranked(basis, pool): wanted, lower = _qwen_words(basis), str(basis or "").casefold() ranked = [] for item in pool: score = len(wanted & _qwen_words(item.get("name"))) for trigger in _qwen_triggers(item): if re.search(r"(?{name}' if page_url.startswith(("http://", "https://")) else name strength = (state.get("selected_strengths") or {}).get(item["id"]) applied = f" · strength {float(strength):g}" if item["id"] in selected and strength is not None else "" rows.append(("✓ " if item["id"] in selected else "") + link + applied) return gr.update(choices=choices, value=selected, visible=bool(page)), "
".join(rows) def _qwen_slot_rows(values): return [[str(values[i] or ""), values[i + 1], float(values[i + 2] or 0)] for i in range(0, 9, 3)] def _qwen_owned_slots(state, slots): owned = {} for key, record in (state.get("owned_slots") or {}).items(): try: index = int(key) row = slots[index] if (0 <= index < 3 and not row[1] and row[0] == record.get("source") and abs(row[2] - float(record.get("strength", row[2]))) < 1e-8): owned[index] = record except (ValueError, TypeError, IndexError): continue return owned def _qwen_apply(prompt, state, slots, current_style, selected_ids, strengths=None, slot_strengths=None): state = copy.deepcopy(state) slots = copy.deepcopy(slots) owned = _qwen_owned_slots(state, slots) page = {item["id"]: item for item in state.get("page", [])} chosen = list(dict.fromkeys(selected_ids or [])) if len(chosen) > 3 or any(key not in page for key in chosen): raise gr.Error("Choose up to three LoRAs from the displayed suggestions.") # Recheck local catalogue membership and backend metadata at application time. valid = {item["id"]: item for item in _qwen_pool(bool(state.get("has_references")))} if any(key not in valid for key in chosen): raise gr.Error("A selected LoRA is no longer available for this backend. Press Refresh.") for index, record in owned.items(): if record.get("id") not in chosen: slots[index] = ["", None, 0.0] owned = {index: record for index, record in owned.items() if record.get("id") in chosen} strengths, slot_strengths = strengths or {}, slot_strengths or {} for index, strength in slot_strengths.items(): if slots[index][0] or slots[index][1]: slots[index][2] = strength current_sources = {row[0]: index for index, row in enumerate(slots) if row[0] and not row[1]} applied, overflow = [], [] for key in chosen: item = valid[key] source = item["source"] index = current_sources.get(source) if index is None: index = next((i for i, row in enumerate(slots) if not row[0].strip() and not row[1]), None) if index is None: overflow.append(item["name"]) continue value = float(strengths.get(key, item.get("strength", .7))) minimum, maximum = (0.0, 4.0) if _ACTIVE_OPERATION.get() == OP_MOSS else (.2, 1.3) value = round(max(minimum, min(maximum, value)), 2) slots[index] = [source, None, value] owned[index] = {"id": key, "source": source, "strength": value} current_sources[source] = index elif index in owned: if key in strengths: slots[index][2] = strengths[key] owned[index] = {"id": key, "source": source, "strength": slots[index][2]} # A pre-existing manual source is retained, not claimed by the assistant. applied.append(item) # Keep ownership strength records synchronized with valid model changes. for index, record in owned.items(): record["strength"] = slots[index][2] clean = _qwen_clean_prompt(prompt, state) if _ACTIVE_OPERATION.get() in (OP_FACE, OP_OUTPAINT, OP_DETAIL): clean = ensure_operation_prompt(_ACTIVE_OPERATION.get(), clean) missing = [] for item in applied: for word in _qwen_triggers(item): if word not in missing and not re.search(r"(? 4: raise gr.Error("The prompt assistant accepts up to four reference images.") from gradio_client import Client, handle_file from concurrent.futures import TimeoutError as FutureTimeout import httpx target = resolve_writer(writer, DEFAULT_QWEN_SPACE) token = str(user_token or "").strip() or False visitor = _qwen_caller_token(request) class VisitorClient(Client): def add_zero_gpu_headers(self, headers): outgoing = dict(headers) outgoing.pop("x-ip-token", None) if visitor: outgoing["x-ip-token"] = visitor return outgoing client = None job = None try: kwargs = dict(verbose=False, httpx_kwargs={"timeout": httpx.Timeout(60, connect=30, write=60, pool=30)}) parameters = inspect.signature(Client.__init__).parameters token_key = "token" if "token" in parameters else "hf_token" client = VisitorClient(target, **{token_key: token}, **kwargs) # A queued generation can remain quiet; the outer job timeout owns its limit. client.httpx_kwargs["timeout"] = httpx.Timeout(None, connect=30, write=60, pool=30) with tempfile.TemporaryDirectory(prefix="qwen-prompt-") as directory: files = [] for index, original in enumerate(images): image = ImageOps.exif_transpose(original).copy() if image.mode == "RGBA": flattened = Image.new("RGB", image.size, "white") flattened.paste(image, mask=image.getchannel("A")) image = flattened else: image = image.convert("RGB") edge = 768 if is_economy(target) else 1024 image.thumbnail((edge, edge), Image.Resampling.LANCZOS) path = os.path.join(directory, f"reference-{index + 1}.png") image.save(path, format="PNG") files.append(handle_file(path)) # One verified endpoint; never retry or switch writers after submission. job = client.submit(message={"text": message, "files": files}, max_new_tokens=ECONOMY_TOKENS if is_economy(target) else 1024, temperature=0 if is_economy(target) else .6, api_name="/write_prompt") result = job.result(timeout=360) if isinstance(result, (list, tuple)) and len(result) == 1: result = result[0] if not isinstance(result, dict) or result.get("protocol") != "h3-writer-v1": raise ValueError("The writer returned an unexpected response format.") return writer_result(result) except FutureTimeout as error: if job is not None: try: job.cancel() except Exception: pass raise gr.Error("The writing request timed out. Your prompt and slots are unchanged. No retry was submitted.") from error except Exception as error: # Errors may contain credential-bearing request URLs. Show a redacted summary. detail = str(error) if token: detail = detail.replace(token, "[redacted]") detail = re.sub(r"(?i)([?&](?:token|access_token|key)=)[^\s&]+", r"\1[redacted]", detail) raise gr.Error("The writer could not finish. Your prompt and slots are unchanged; no retry was submitted. " + detail[:500]) from error finally: if client is not None and hasattr(client, "close"): try: client.close() except Exception: pass def _qwen_parse_setup(reply, page, slots): text = str(reply or "").strip() if text.startswith("```"): text = re.sub(r"^```(?:json)?\s*|\s*```$", "", text, flags=re.I).strip() result = json.loads(text) if (not isinstance(result, dict) or not isinstance(result.get("prompt"), str) or ("picks" in result and not isinstance(result["picks"], list)) or ("strengths" in result and not isinstance(result["strengths"], list))): raise ValueError("The writer must return a prompt and LoRA selections as JSON.") prompt = " ".join(result["prompt"].split()).strip() if len(prompt) < 30 or len(prompt) > 3000: raise ValueError("The writer returned no usable image prompt.") allowed = {entry["id"] for entry in page} picks, strengths = [], {} for entry in result.get("picks", []): if not isinstance(entry, dict) or entry.get("id") not in allowed: raise ValueError("The writer selected a LoRA outside the supplied catalogue.") value = float(entry["strength"]) if not math.isfinite(value) or not .2 <= value <= 1.3: raise ValueError("The writer returned an invalid LoRA strength.") if entry["id"] not in picks: picks.append(entry["id"]) strengths[entry["id"]] = round(value, 2) if len(picks) > 3: raise ValueError("The writer selected more than three LoRAs.") tuning = {} for entry in result.get("strengths", []): if not isinstance(entry, dict) or type(entry.get("slot")) is not int or not 1 <= entry["slot"] <= 3: raise ValueError("The writer returned an invalid existing slot.") index, value = entry["slot"] - 1, float(entry["strength"]) if not math.isfinite(value) or not .2 <= value <= 1.3: raise ValueError("The writer returned an invalid slot strength.") if not str(slots[index][0] or "").strip() and not slots[index][1]: # A writer may echo an example slot despite there being no adapter. # Tuning never selects an adapter: ignore this harmless extra record. continue tuning[index] = round(value, 2) # A prompt-only reply must not silently clear previously selected adapters. # An explicit empty picks array remains an intentional empty selection. return prompt, picks if "picks" in result else None, strengths, tuning def prepare_prompt_setup(idea, current_prompt, writer, auto_loras, use_images, image1, image2, extras, kind, angle, lighting, look, keep_identity, use_model, writer_token, state, u1r, u1f, u1s, u2r, u2f, u2s, u3r, u3f, u3s, current_style, ui_mode, request: gr.Request, progress=gr.Progress()): operation = _ACTIVE_OPERATION.get() if operation != OP_QWEN and image1 is None: raise gr.Error("Upload Image 1 before preparing an image edit.") if operation == OP_FACE: if image2 is None: raise gr.Error("Upload the target/body in Image 1 and the reference face in Image 2.") keep_identity = False # The identity is deliberately replaced with Image 2. elif operation in SINGLE_SOURCE_OPERATIONS: # Other editing modes can leave hidden references in this session. image2, extras = None, None # Simple has one editable prompt; a restored advanced idea must not override it. source = idea if ui_mode == "Pro" and str(idea or "").strip() else current_prompt if operation in (OP_OUTPAINT, OP_DETAIL): source = ensure_operation_prompt(operation, source) if is_economy(writer): original = str(source or "").strip() references = [value for value in [image1, image2, *(extras or [])] if value is not None] images = [] if use_images and use_model: for value in references: image = _to_pil_rgb(value) if image is None: raise gr.Error("A reference could not be read. Upload it again.") images.append(image) if not original and not images: raise gr.Error("Write your idea or share a reference image first.") check_prompt(original) caption = "" controls = "" if images: progress(.15, desc="Describing the reference images on CPU.") caption = _qwen_remote_setup(writer, economy_instruction(kind="image"), images, writer_token, request) details = [table.get(value, "") for table, value in ( (EDIT_KINDS, kind), (EDIT_ANGLES, angle), (EDIT_LIGHTING, lighting), (EDIT_LOOKS, look) )] if keep_identity: details.append(IDENTITY_TAIL) controls = ". ".join(value for value in details if value) prepared = ensure_operation_prompt(operation, economy_prompt(caption, original, controls)) check_prompt(prepared) # No catalogue lookup, parser, selection refresh or adapter mutation on this path. return [prepared, *[gr.update() for _ in range(12)], state, economy_status(bool(images))] state = copy.deepcopy(state) if isinstance(state, dict) else {} original = str(source or "").strip() or _qwen_clean_prompt(current_prompt, state).strip() if not original: raise gr.Error("Write your idea first.") check_prompt(original) references = [value for value in [image1, image2, *(extras or [])] if value is not None] state["has_references"] = bool(references) images = [] if use_images: for value in references: if value is None: continue image = _to_pil_rgb(value) if image is None: raise gr.Error("A reference could not be read. Upload it again.") images.append(image) if len(images) > 4: raise gr.Error("The prompt assistant accepts up to four reference images. Remove extras or turn off image sharing.") built = build_edit_prompt(original, kind, angle, lighting, look, bool(keep_identity and state["has_references"])) if operation == OP_FACE: built += " Image 1 is the target/body image. Replace its face with the identity from Image 2, the reference face. Preserve Image 1's body, pose, clothing, background, lighting and framing." elif operation == OP_OUTPAINT: built += " Extend the scene naturally into the new outer canvas, matching the source lighting, perspective and texture. Preserve the original image content." elif operation == OP_DETAIL: built += " Improve clarity and fine detail in Image 1 while preserving its composition, identity, lighting and visual style. Do not invent new objects or change the framing." built = ensure_operation_prompt(operation, built) slots = _qwen_slot_rows([u1r, u1f, u1s, u2r, u2f, u2s, u3r, u3f, u3s]) state = _qwen_page(original, state) if not use_model: result = _qwen_apply(built, state, slots, current_style, state.get("selected_ids", [])) result[-1] = "Prompt built locally. No AI request; existing LoRAs retained." return result # Give the writer a useful compatible pool even when the idea is not English. # Display Refresh remains local and relevance-ranked; AI may see up to 24 entries. pool = _qwen_pool(bool(state.get("has_references"))) if auto_loras else [] by_id = {item["id"]: item for item in pool} candidates_order = ([by_id[key] for key in state.get("selected_ids", []) if key in by_id] + _qwen_ranked(original, pool) + pool) page, page_seen = [], set() for item in candidates_order: if item["id"] not in page_seen: page.append(item) page_seen.add(item["id"]) if len(page) == 24: break existing = [{"slot": i + 1, "name": os.path.basename(str(row[1] or row[0]).split("?")[0])[:120], "strength": row[2]} for i, row in enumerate(slots) if row[0].strip() or row[1]] existing_slot_ids = [entry["slot"] for entry in existing] candidates = [{"id": item["id"], "name": item["name"], "triggers": _qwen_triggers(item), "default_strength": item.get("strength", .7)} for item in page] message = ( f"Operation: {operation}. " "Prepare an IMAGE generation/editing prompt, not a video. Return exactly one JSON object, no markdown. " "Schema: {\"prompt\":\"...\",\"picks\":[],\"strengths\":[]}. " "Each optional picks item is {\"id\":\"supplied-candidate-id\",\"strength\":0.7,\"why\":\"brief reason\"}. " "Each optional strengths item has an integer slot from EXISTING SLOT IDS and its numeric strength. " "The prompt must be one English paragraph, 70–110 words. Preserve the user's requested content, counts, " "composition and exclusions. Keep quoted image text exactly in its original language. " "Do not invent people, references, extra actions, motion sequences, sound or dialogue. " + (f"There are {len(images)} reference images, in upload order. Refer to images only by those positions. " "Describe the requested changes while preserving unaffected details. " if images else ("This will edit reference images that were NOT shared with you. Preserve requested identity and unaffected details, " "but do not invent visual observations; follow only the user description. " if state["has_references"] else "There are no reference images: write a self-contained text-to-image prompt; do not claim to see a person or image. ")) + ("Preserve the same person's identity from the reference. " if keep_identity and state["has_references"] else "") + ("Begin the prompt with the exact required BFS trigger head_swap: and preserve its spelling. " if operation == OP_FACE else "") + ("Keep the exact outpainting trigger at the beginning of USER IDEA AND CONTROLS. Describe only the newly expanded scene around Image 1; preserve its original content. " if operation == OP_OUTPAINT else "") + ("Keep the exact trigger Enhance this image. Describe enhancement of Image 1 only, preserving its composition, identity and visual style. Avoid sharpening language for illustrations unless requested. " if operation == OP_DETAIL else "") + "Choose at most three genuinely relevant candidate IDs; an empty picks list is correct when none help. " "Never invent adapters, URLs, IDs or trigger words. Existing manual adapters must stay; tune only their numbered strengths. " "New adapter choices belong only in picks. Never put a new pick or an empty slot in strengths. " + ("There are no existing adapters: strengths MUST be an empty array. " if not existing_slot_ids else "Only the listed existing slot IDs may appear in strengths; omit slots whose strength should stay unchanged. ") + "Every strength must be from 0.2 to 1.3; reduce overlapping effects and protect requested identity. " + ("LoRA selection and tuning are disabled: return empty picks and strengths arrays. " if not auto_loras else "") + "\nUSER IDEA AND CONTROLS: " + built + "\nEXISTING SLOT IDS: " + json.dumps(existing_slot_ids) + "\nEXISTING SLOTS: " + json.dumps(existing, ensure_ascii=False) + "\nCANDIDATES: " + json.dumps(candidates, ensure_ascii=False) ) if len(message) > 24000: raise gr.Error("The idea and adapter descriptions are too long. Shorten the idea before preparing it.") progress(.15, desc="Preparing prompt, LoRA choices and strengths in one writing request…") reply = _qwen_remote_setup(writer, message, images, writer_token, request) try: prompt, picks, strengths, tuning = _qwen_parse_setup(reply, page, slots) check_prompt(prompt) except Exception as error: raise gr.Error("The writer returned an incomplete or invalid setup. Your prompt and slots are unchanged; no retry was sent. " + str(error)[:350]) from error if picks is None: picks = state.get("selected_ids", []) if not auto_loras: picks, strengths, tuning = state.get("selected_ids", []), {}, {} if auto_loras: state["page"] = page # AI picks may come from beyond the five displayed rows. prompt = ensure_operation_prompt(operation, prompt) result = _qwen_apply(prompt, state, slots, current_style, picks, strengths, tuning) # English output makes local Refresh useful for Bulgarian/transliterated ideas too. basis = (original + "\n" + _qwen_clean_prompt(result[0], result[-2])).strip() shown = _qwen_page(basis, result[-2]) result[11], result[12] = _qwen_picker_view(shown) result[13] = shown result[-1] = "Prepared the prompt and LoRA settings in one AI request. " + result[-1] return result def refresh_prompt_loras(idea, prompt, state): state = copy.deepcopy(state) if isinstance(state, dict) else {} idea_text = str(idea or "").strip() prompt_text = _qwen_clean_prompt(prompt, state).strip() basis = (idea_text + "\n" + prompt_text).strip() if idea_text and prompt_text else idea_text or prompt_text state = _qwen_page(basis, state, advance=True) picker, links = _qwen_picker_view(state) note = ("Next relevant suggestions; selected LoRAs retained. Refresh uses no AI or GPU and loops through the list." if state["page"] else "No relevant compatible LoRAs in your library yet. Add them in Pro; no AI or GPU was used.") return [picker, links, state, note] def apply_prompt_lora_picks(selected_ids, prompt, state, u1r, u1f, u1s, u2r, u2f, u2s, u3r, u3f, u3s, current_style): state = copy.deepcopy(state) if isinstance(state, dict) else {} # Match the video picker: a fourth tick replaces the oldest automatic pick. # _qwen_apply still preserves manually edited or uploaded slots. selected_ids = list(dict.fromkeys(selected_ids or [])) if len(selected_ids) > 3: available = {item["id"] for item in state.get("page", [])} if any(key not in available for key in selected_ids): raise gr.Error("Choose LoRAs from the displayed suggestions.") previous = state.get("selected_ids", []) retained = [key for key in previous if key in selected_ids] added = [key for key in selected_ids if key not in previous] selected_ids = (retained + added)[-3:] slots = _qwen_slot_rows([u1r, u1f, u1s, u2r, u2f, u2s, u3r, u3f, u3s]) result = _qwen_apply(prompt, state, slots, current_style, selected_ids) result[-1] += " Selection updated locally; no AI or GPU call." return result # Local context synchronization for the prompt/LoRA picker. # Wire each reference component's .change to sync_prompt_reference_mode with # [image1, image2, extras, idea, prompt, state, *helper_slots, current_style] # and the same 15 helper_outputs as Prepare. No network/model work is performed. def _qwen_has_references(image1, image2, extras): for value in [image1, image2, *(extras or [])]: if isinstance(value, (tuple, list)): value = value[0] if value else None if value is not None: return True return False def pick_prompt_loras_cpu(prompt, image1, image2, extras, state, u1r, u1f, u1s, u2r, u2f, u2s, u3r, u3f, u3s, current_style, request: gr.Request = None): """Apply strong catalogue matches and rank related matches for the signed-in owner.""" def unchanged(note): return [*[gr.update() for _ in range(14)], note] state = copy.deepcopy(state) if isinstance(state, dict) else {} basis = _qwen_clean_prompt(prompt, state).strip() if not basis: return unchanged("Write or paste a prompt to pick LoRAs.") slots = _qwen_slot_rows([u1r, u1f, u1s, u2r, u2f, u2s, u3r, u3f, u3s]) free_slots = sum(not ref.strip() and not uploaded for ref, uploaded, _ in slots) if not free_slots: return unchanged("All three LoRA slots are occupied. Clear a slot to add another.") operation = _ACTIVE_OPERATION.get() # A first click after startup may arrive before the operation's initial catalogue sync. cache_path = MOSS_CATALOG.cache_file if operation == OP_MOSS else _REMOTE_LORA_CACHE if not os.path.isfile(cache_path): lora_library_sync() # The dedicated edit operations have no text-to-image path, even before an upload. has_references = operation != OP_QWEN or _qwen_has_references(image1, image2, extras) pool = _qwen_pool(has_references) by_id = {item["id"]: item for item in pool} active_refs = {ref for ref, uploaded, _ in slots if ref and not uploaded} selected = [key for key in state.get("selected_ids", []) if key in by_id and by_id[key]["source"] in active_refs] occupied_sources = {_active_lora_key(ref) for ref, _, _ in slots if ref.strip()} ranked = rank_prompt_loras(basis, pool) added, strengths = [], {} for item in ranked: source = _active_lora_key(item["source"]) strength = float(item.get("strength", .7)) if source in occupied_sources or strength <= 0: continue key = item["id"] added.append(key) strengths[key] = strength occupied_sources.add(source) if len(added) == min(2, free_slots): break candidates = [item for item in rank_prompt_loras(basis, pool, include_suggestions=True) if _active_lora_key(item["source"]) not in occupied_sources][:5] semantic = rerank_loras(basis, candidates, request=request) if not added and candidates else None if semantic: first = semantic[0]["id"] candidates = [semantic[0], *(item for item in candidates if item["id"] != first)] suggested = [item["id"] for item in candidates] if not added: if not suggested: return unchanged("No compatible LoRA matches this prompt. Current LoRAs kept.") state.update(has_references=has_references, basis=basis, cursor=0, selected_ids=selected, page=[by_id[key] for key in [*selected, *suggested]]) picker, links = _qwen_picker_view(state) note = "Possible matches are shown below. Tick a LoRA to use it." if semantic: note = "CPU Heretic suggestion is first. Tick a LoRA to use it." elif semantic == []: note = "CPU Heretic found no clear match. You can tick a related LoRA below." return [*[gr.update() for _ in range(11)], picker, links, state, note] selected.extend(added) page_ids = dict.fromkeys([*selected, *suggested]) # A stale picker-owned entry must not cause an occupied slot to be cleared here. owned = {str(index): record for index, record in _qwen_owned_slots(state, slots).items() if record.get("id") in selected} state.update(has_references=has_references, basis=basis, cursor=0, page=[by_id[key] for key in page_ids], owned_slots=owned) result = _qwen_apply(prompt, state, slots, current_style, selected, strengths=strengths) for index, (ref, uploaded, _) in enumerate(slots): if ref.strip() or uploaded: start = 1 + 3 * index result[start:start + 3] = [gr.update() for _ in range(3)] result[-1] = f"Added {len(added)} LoRA{'s' if len(added) != 1 else ''} from your prompt on CPU." if suggested: result[-1] += " Related suggestions are available in the list below." return result def sync_prompt_reference_mode(image1, image2, extras, idea, prompt, state, u1r, u1f, u1s, u2r, u2f, u2s, u3r, u3f, u3s, current_style): state = copy.deepcopy(state) if isinstance(state, dict) else {} if _ACTIVE_OPERATION.get() in SINGLE_SOURCE_OPERATIONS: image2, extras = None, None has_references = _qwen_has_references(image1, image2, extras) if has_references == bool(state.get("has_references")): # Image replacement within the same mode must not rewrite a user's prompt, # slots, or picker, or cause another component-change callback cascade. return [gr.update() for _ in range(15)] state["has_references"] = has_references clean = _qwen_clean_prompt(prompt, state).strip() basis = (str(idea or "").strip() + "\n" + clean).strip() state = _qwen_page(basis, state) slots = _qwen_slot_rows([u1r, u1f, u1s, u2r, u2f, u2s, u3r, u3f, u3s]) # _qwen_page removes incompatible selected IDs. _qwen_apply clears only their # unchanged assistant-owned slots and exact owned trigger suffix; manual slot # edits/uploads remain untouched. result = _qwen_apply(prompt, state, slots, current_style, state.get("selected_ids", [])) result[-1] = ("LoRA suggestions updated for " + ("image editing" if has_references else "text to image") + ". Incompatible automatic selections removed; manual slots preserved. No AI or GPU used.") return result def reset_prompt_assistant(image1=None, image2=None, extras=None): # Call after successful profile/settings loading. Outputs, in order: # assistant_state, pb_picks, pb_links, pb_status. # Retain only current reference presence; profile-loaded slots are manual. return [{"has_references": _qwen_has_references(image1, image2, extras)}, gr.update(choices=[], value=[], visible=False), "", ""] def load_profile_ui(name, image1, image2, extras): result = load_profile(name) if "value" not in result[-2]: return [*result, *[gr.update() for _ in range(7)]] return [*result, *reset_prompt_assistant(image1, image2, extras), *[gr.update(value=None) for _ in range(3)]] def import_settings_ui(path, image1, image2, extras): result = import_settings(path) if not path: return [*result, *[gr.update() for _ in range(7)]] return [*result, *reset_prompt_assistant(image1, image2, extras), *[gr.update(value=None) for _ in range(3)]] def on_fast_lora_change(name, current_steps): """A fast adapter has a step count it was distilled for; move the slider there.""" spec = FAST_LORAS.get(name) if not spec: return gr.update(), gr.update(visible=False) return gr.update(value=spec["steps"]), gr.update(visible=True) def gpu_estimate_text(*args): try: bound = inspect.signature(infer).bind_partial(*args) bound.apply_defaults() data, _ = with_auto_prompt_lora(normalize_guidance_request(bound.arguments)) samples = _qwen_worker_samples(data) seconds = request_gpu_seconds(data, worker_samples=samples) refs = request_images(data) width, height = request_canvas(data) out_width, out_height = ((width, height) if data.get("operation") in (OP_MOSS, *SINGLE_SOURCE_OPERATIONS) else exact_output_dimensions(width, height, data.get("aspect_ratio"))) observed = _qwen_observed_runtime(samples) if observed: low, high, count = observed duration = f"~{low} s" if low == high else f"~{low}-{high} s" qualifier = "Early estimate" if count < 3 else "Estimated generation time" headline = f"**{qualifier}: {duration} per image**" note = f"Based on {count} comparable completed runs. Queueing, startup and downloads can add time." else: headline = "**Generation time: not yet measured for these settings**" note = "A matching completed run will give a useful estimate." return ( f"{reservation_text(seconds)}\n\n{headline}\n\n" "
Generation details\n\n" f"{int(data.get('steps', DEFAULT_STEPS))} steps · {out_width}×{out_height} · {len(refs)} reference(s)\n\n" f"{note} This is a timing estimate, not a quota charge.\n\n" "The reservation includes a startup margin. The full allowance must be available at the start. " "Adapter downloads happen before allocation.\n\n
" ) except Exception: return "⏱️ **Generation time:** check the image and size settings." def sampling_limits(operation, face_mode=FACE_TURBO, outpaint_mode=OUTPAINT_TURBO, detail_mode=DETAIL_TURBO, qwen_mode=QWEN_TURBO): if is_dmd2_request(locals()): return (len(DMD2_SIGMAS),) * 3 if operation == OP_MOSS: return 1, 60, 30 if operation == OP_FACE: return (4, 50, 30) if str(face_mode).startswith("Base") else (4, 8, 6) if operation == OP_OUTPAINT: return (4, 50, 25) if str(outpaint_mode).startswith("Base") else (4, 8, 6) if operation == OP_DETAIL: return (8, 50, 25) if str(detail_mode).startswith("Base") else (4, 8, 6) if operation == OP_CAMERA: return CAMERA_MIN_STEPS, CAMERA_MAX_STEPS, CAMERA_STEPS if IS_TURBO: return (4, 50, 30) if qwen_mode == QWEN_BASE else (4, 8, DEFAULT_STEPS) return 1, 50, DEFAULT_STEPS def operation_visuals(operation, face_mode, outpaint_mode=OUTPAINT_TURBO, detail_mode=DETAIL_TURBO, qwen_mode=QWEN_TURBO): moss, face, outpaint = operation == OP_MOSS, operation == OP_FACE, operation == OP_OUTPAINT detail = operation == OP_DETAIL relight, camera = operation == OP_RELIGHT, operation == OP_CAMERA single = operation in SINGLE_SOURCE_OPERATIONS dmd2 = is_dmd2_request(locals()) minimum, maximum, _ = sampling_limits(operation, face_mode, outpaint_mode, detail_mode, qwen_mode) note = ("Upload a photo, tap a lighting look and a light position, then Generate." if relight else "**Camera Angle — fixed 17 Nov 2026** · the camera author's recipe: 40 steps, camera strength 0.5. Upload a photo, tap a camera around the subject and choose its height. Side and back views turn best. Unseen sides are invented, and the background can be simplified; try another seed for a different take." if camera else "Image 1 is the target/body. Image 2 supplies the face identity. Turbo is the default; Base is available below." if face else "Expand any side of your image. The gray preview shows the new area to fill. A prompt is optional; the original interior is preserved." if outpaint else "**MOSS Edit fixed · 13 Nov 2026** — corrected input/output sizing and cropping during image preparation.\n\n" "Upload Image 1 and describe your edit. Images 2-4 are optional references." if moss else "Enhance a photo or illustration with Elusarca's Qwen Detail Enhancer. Start at 1 MP; creative enhancement can change fine details." if detail else f"DMD2 creates from text or edits reference images in two steps at the selected output size. " f"[⚡ Realtime 512 px preview]({DMD2_DEMO}) opens the author's demo." if dmd2 else "Edit reference images, or leave images empty to create from text. Base uses 30 steps without Viggle; optional LoRAs still work." if IS_TURBO and qwen_mode == QWEN_BASE else "Edit reference images, or leave images empty to create from text. Turbo defaults: 6 steps, CFG 1.") if dmd2 and operation not in (OP_QWEN, OP_CAMERA): note += " DMD2 is an experimental two-step option. The result can differ from Viggle or Base." model = "moss-image" if moss else ("qwen-image-2.1" if IS_TURBO else "qwen-edit-2511") return [ gr.update(label="Image 1 - target / body" if face else "Source image (required)" if single else "Image 1 - image to edit (required)" if moss else "Image 1 (optional)" if IS_TURBO else "Image 1"), gr.update(label="Image 2 - reference face (required)" if face else "Image 2 - optional reference", visible=not single), gr.update(visible=face), note, gr.update(label="Inference Steps (fixed at 2)" if dmd2 else f"Inference Steps ({minimum}-{maximum} for this mode)", interactive=not dmd2), gr.update(label="CFG", interactive=not (dmd2 or camera), **({"value": DEFAULT_CFG} if dmd2 or camera else {})), gr.update(label="Negative prompt (unavailable in DMD2)" if dmd2 else "Negative prompt (not used by Camera Angle)" if camera else "Negative prompt (optional)", interactive=not (dmd2 or camera)), f"Shared library: **{MOSS_CATALOG.bucket if moss else REMOTE_LORA_BUCKET}**", gr.update(choices=["moss-image"] if moss else LORA_LIBRARY_MODELS, value=model), gr.update(visible=moss), gr.update(label="Additional reference images (up to 4 total)" if moss else "Additional reference images", visible=not face and not single), gr.update(visible=not IS_TURBO and operation == OP_QWEN), gr.update(visible=not moss and not face and not single), gr.update(visible=not moss), gr.update(value="MOSS Image" if moss else "Qwen Image 2.1" if IS_TURBO else QIE_BASE_MODELS[0]), gr.update(visible=not moss), ("DMD2 uses two steps and fixed CFG 1." if dmd2 else "Camera Angle uses the camera author's recipe: native Qwen without a speed LoRA, 40 steps and CFG 1. " "10-50 steps are allowed; fewer steps are faster but can turn less." if camera else ("MOSS defaults: 30 steps and CFG 4. " if moss else "Qwen Face Swap defaults: Turbo 6 steps or Base 30 steps, CFG 1. " if face else "Outpaint defaults: Turbo 6 steps or Base 25 steps, CFG 1. The original interior is restored after generation. " if outpaint else "Qwen Detail Enhancer: Turbo 6 steps is economical; Base 25 steps follows the author's recipe. Default CFG 1. The Turbo combination is experimental. " if detail else "Relight offers Viggle 6 steps, DMD2 2 steps, or Base 30 steps. " if relight else "Qwen Base defaults to 30 steps, CFG 1 and no Viggle. Optional LoRAs remain available. " if IS_TURBO and qwen_mode == QWEN_BASE else "Turbo defaults to CFG 1. " if IS_TURBO else "CFG above 1 uses negative prompts. ") + "Adding a negative prompt raises CFG 1 to 1.1 automatically. CFG above 1 uses extra GPU work."), "Match Image 1 and 0 MP save the original dimensions within MOSS's 4 MP / 4096 px limit. The model edits at up to 1024 px on the long side. Other ratios fit the full source into the canvas." if moss else "Outpaint expansion sets the output shape. Choose 0.5-2 MP; the preview shows the exact saved canvas, with no aspect-ratio crop." if outpaint else "Qwen Detail Enhancer keeps the source shape, rounded to 32 pixels, with up to 4x enlargement. Start at 1 MP; 4 MP follows the author's larger recipe. No aspect-ratio crop is applied." if detail else "Keeps the source image shape, rounded to 32 pixels. Choose 0.5-2 MP; the default is 1 MP." if relight or camera else "The shared Qwen canvas uses multiples of 32 and caps editing at 1536² area. Fixed output ratios are cropped exactly.", "Three independent MOSS LoRA slots. Use a repository/file, HF bucket file, direct download URL or upload. Strength 0 disables a slot. Qwen adapters are incompatible." if moss else USER_LORA_HELP, gr.update(visible=not face and not single), gr.update(visible=outpaint), gr.update(visible=not single), gr.update(visible=not single), gr.update(visible=not single), gr.update(visible=not single), gr.update(visible=not single), gr.update(visible=not single), gr.update(label="Describe the expanded scene (optional)" if outpaint else "Detail enhancement instructions (optional)" if detail else "Extra lighting instructions (optional)" if relight else "What do you want to create or change?", visible=not camera, placeholder="Leave the preset, or describe what should continue beyond the edges" if outpaint else "Use the preset or describe the details to improve" if detail else "Optional: add a mood or describe the lighting" if relight else "Describe your image or the changes you want"), gr.update(visible=detail), gr.update(visible=IS_TURBO and operation in (OP_QWEN, OP_RELIGHT), label="Relight model" if relight else "Camera Angle model (native Base, 40 steps)" if camera else "Qwen Image Edit model"), gr.update(visible=face), gr.update(visible=outpaint), gr.update(visible=detail), gr.update(visible=relight), gr.update(visible=camera), gr.update(visible=not (relight or camera)), gr.update(visible=not (relight or camera)), gr.update(value="Generate lighting" if relight else "Generate angle" if camera else "Generate"), gr.update(visible=not (relight or camera)), gr.update(visible=not (relight or camera)), ] def reset_operation(operation, prompt, state, image1, image2, extras, negative_prompt_text=""): starting_qwen_mode = QWEN_BASE if operation == OP_CAMERA else QWEN_TURBO minimum, maximum, default = sampling_limits(operation, qwen_mode=starting_qwen_mode) clean = _qwen_clean_prompt(prompt, state) preset = restore_face_prompt() outpaint_preset = restore_outpaint_prompt() detail_preset = restore_detail_prompt() if operation == OP_FACE: clean = preset elif operation == OP_OUTPAINT: clean = outpaint_preset elif operation == OP_DETAIL: clean = detail_preset elif operation in (OP_RELIGHT, OP_CAMERA): clean = "" elif clean.strip() in (preset.strip(), outpaint_preset.strip(), detail_preset.strip()): clean = "" refs = None if operation in (OP_FACE, *SINGLE_SOURCE_OPERATIONS) else extras return [gr.update(value=default), gr.update(value=DEFAULT_CFG if operation == OP_CAMERA else guidance_values({"negative_prompt_text": negative_prompt_text}, default=4.0 if operation == OP_MOSS else DEFAULT_CFG)[1]), gr.update(value=0.0 if operation == OP_MOSS else 1.0), gr.update(value=FACE_TURBO), gr.update(value=NONE_LORA), gr.update(value=NO_FAST_LORA), gr.update(value=False), gr.update(value=0.0), gr.update(value="qwen"), gr.update(value=False), gr.update(value=False), gr.update(value=False), gr.update(value=operation in (OP_FACE, OP_DETAIL)), clean, *[value for _ in range(3) for value in ("", None, 0.0)], *reset_prompt_assistant(image1, None if operation in SINGLE_SOURCE_OPERATIONS else image2, refs), gr.update(value=None) if operation in (OP_FACE, *SINGLE_SOURCE_OPERATIONS) else gr.update(), gr.update(value=OUTPAINT_TURBO), *[gr.update(value=25) for _ in range(4)], gr.update(value=32), gr.update(value=DETAIL_TURBO), gr.update(value=1.0), gr.update(value=starting_qwen_mode), gr.update(value="Match Image 1") if operation == OP_MOSS or operation in SINGLE_SOURCE_OPERATIONS else gr.update(), gr.update(value="Soft studio"), gr.update(value="Left"), gr.update(value="#FFFFFF"), gr.update(value=1.0), gr.update(value=90), gr.update(value=0), gr.update(value=False), gr.update(value=CAMERA_STRENGTH), ] def restore_face_prompt(): from bfs_backend import FACE_SWAP_PROMPT return FACE_SWAP_PROMPT def restore_outpaint_prompt(): from outpaint_backend import OUTPAINT_PROMPT return OUTPAINT_PROMPT def restore_detail_prompt(): from detail_backend import DETAIL_PROMPT return DETAIL_PROMPT def apply_detail_preset(preset): from detail_backend import DETAIL_PRESETS return DETAIL_PRESETS[preset] def apply_relight_preset(preset): from relight_backend import PRESETS selected = PRESETS[preset] return selected["direction"], selected["color"] def ensure_operation_prompt(operation, text): if operation == OP_FACE: from bfs_backend import prompt_with_trigger return prompt_with_trigger(text) if operation == OP_OUTPAINT: from outpaint_backend import prompt_with_trigger return prompt_with_trigger(text) if operation == OP_DETAIL: from detail_backend import prompt_with_trigger return prompt_with_trigger(text) return text def reset_face_sampling(face_mode): minimum, maximum, default = sampling_limits(OP_FACE, face_mode) return gr.update(value=default) def reset_outpaint_sampling(outpaint_mode): _, _, default = sampling_limits(OP_OUTPAINT, outpaint_mode=outpaint_mode) return gr.update(value=default) def reset_detail_sampling(detail_mode): _, _, default = sampling_limits(OP_DETAIL, detail_mode=detail_mode) return gr.update(value=default) def reset_qwen_sampling(qwen_mode): _, _, default = sampling_limits(OP_QWEN, qwen_mode=qwen_mode) return gr.update(value=default) def qwen_sampling_notes(operation, qwen_mode): if operation not in QWEN_SHARED_MODES: return (gr.update(),) * 4 updates = operation_visuals(operation, FACE_TURBO, qwen_mode=qwen_mode) return updates[3], updates[16], updates[5], updates[6] def specialist_sampling_notes(operation, face_mode, outpaint_mode, detail_mode): if operation not in (OP_FACE, OP_OUTPAINT, OP_DETAIL): return (gr.update(),) * 4 updates = operation_visuals(operation, face_mode, outpaint_mode, detail_mode) return updates[3], updates[16], updates[5], updates[6] def update_negative_guidance(negative_prompt_text, guidance_scale): if not str(negative_prompt_text or "").strip() and math.isclose(float(guidance_scale), 1.1, abs_tol=1e-9): return gr.update(value=1.0) _, cfg, _ = guidance_values({"negative_prompt_text": negative_prompt_text, "guidance_scale": guidance_scale}) return gr.update(value=cfg) # Quick "Target pixel" picker. It only drives the existing target_megapixels # slider, which stays the source of truth for generation and profiles. TWO_MP_OPERATIONS = (OP_FACE, OP_OUTPAINT, OP_RELIGHT, OP_CAMERA) def target_pixel_limit(operation): return 2 if operation in TWO_MP_OPERATIONS else 4 def target_pixel_choices(operation): return [(f"{n} MP", float(n)) for n in range(1, target_pixel_limit(operation) + 1)] def target_pixel_info(operation): if operation in TWO_MP_OPERATIONS: return "This mode supports up to 2 MP." if operation == OP_QWEN: return "Editing with images is capped near 2.25 MP; 3-4 MP apply to text-to-image." return "Higher MP uses more GPU time." def target_pixel_update(operation, megapixels): limit = target_pixel_limit(operation) try: mp = float(megapixels) except (TypeError, ValueError): mp = float("nan") value = None if math.isfinite(mp) and abs(mp - round(mp)) < 1e-6 and 1 <= round(mp) <= limit: value = float(round(mp)) return gr.update(choices=target_pixel_choices(operation), value=value, info=target_pixel_info(operation)) def target_pixel_clamp(operation, megapixels): try: mp = float(megapixels) except (TypeError, ValueError): return gr.update() limit = target_pixel_limit(operation) return gr.update(value=float(limit)) if math.isfinite(mp) and mp > limit else gr.update() def sampling_label(operation, face_mode, outpaint_mode=OUTPAINT_TURBO, detail_mode=DETAIL_TURBO, qwen_mode=QWEN_TURBO): minimum, maximum, _ = sampling_limits(operation, face_mode, outpaint_mode, detail_mode, qwen_mode) dmd2 = is_dmd2_request(locals()) return gr.update(label="Inference Steps (fixed at 2)" if dmd2 else f"Inference Steps ({minimum}-{maximum} for this mode)", interactive=not dmd2) def outpaint_preview(operation, image, left, right, top, bottom, target_megapixels): if operation != OP_OUTPAINT or image is None: return None, "Upload a source image to preview the expanded canvas." if operation == OP_OUTPAINT else "" import outpaint_backend try: canvas, (width, height) = outpaint_backend.preview(dict( input_image_1=image, outpaint_left=left, outpaint_right=right, outpaint_top=top, outpaint_bottom=bottom, target_megapixels=target_megapixels)) return canvas, f"**Output canvas: {width} × {height} px.** Gray areas will be filled; the source is scaled to fit this canvas." except (ValueError, TypeError, gr.Error) as error: return None, str(error) def on_operation_style_change(operation, selected_lora, current_prompt, current_extras_condition_only): if operation != OP_QWEN: return gr.update(), gr.update(), gr.update() return on_lora_change_ui(selected_lora, current_prompt, current_extras_condition_only) def _active_lora_text(value): """Render catalog/user labels as text, without Markdown or automatic links.""" value = html.escape(" ".join(str(value or "").split()))[:240] value = re.sub(r"([\\`*_{}\[\]()#+.!|>~\-])", r"\\\1", value) return value.replace(":", ":").replace("/", "/") def _active_lora_key(source): from moss_catalog import _source, _source_key try: return _source_key(_source(source)) except Exception: return str(source or "").strip() def _active_lora_filename(source): # Basenames work for both Windows uploads and Linux Space cache paths. path = urllib.parse.urlparse(str(source or "").replace("\\", "/")).path name = urllib.parse.unquote(path.rstrip("/").rsplit("/", 1)[-1]) name = re.sub(r"\.(?:safetensors|pt|bin)$", "", name, flags=re.I) return name.replace("_", " ") or "Custom LoRA" def active_lora_summary(face_mode=FACE_TURBO, face_strength=1.0, outpaint_mode=OUTPAINT_TURBO, detail_mode=DETAIL_TURBO, detail_strength=1.0, lora_adapter=NONE_LORA, fast_lora=NO_FAST_LORA, fast_lora_strength=1.0, u1r="", u1f=None, u1s=0, u2r="", u2f=None, u2s=0, u3r="", u3f=None, u3s=0, qwen_mode=QWEN_TURBO, camera_strength=CAMERA_STRENGTH): """Describe the current selection from local metadata only; never fetch weights.""" operation = _ACTIVE_OPERATION.get() rows = [] def add(label, name, author, strength): try: strength = float(strength or 0) except (ValueError, TypeError): return if not math.isfinite(strength) or strength == 0: return author = " · " + _active_lora_text(author) if author else "" rows.append(f"- **{label}: {_active_lora_text(name)}**{author} · strength **{strength:g}**") dmd2 = is_dmd2_request(locals()) use_turbo = IS_TURBO and operation != OP_MOSS and not dmd2 if operation in QWEN_SHARED_MODES: use_turbo = use_turbo and qwen_mode == QWEN_TURBO and operation != OP_CAMERA if operation == OP_FACE: add("Built in", "BFS Head v1.1", "Alissonerdx", face_strength) use_turbo = use_turbo and not str(face_mode).startswith("Base") elif operation == OP_OUTPAINT: add("Built in", "Qwen Outpaint v2", "ausboss", 1) use_turbo = use_turbo and not str(outpaint_mode).startswith("Base") elif operation == OP_DETAIL: add("Built in", "Elusarca Qwen Detail Enhancer v1", "reverentelusarca", detail_strength) use_turbo = use_turbo and not str(detail_mode).startswith("Base") elif operation == OP_MOSS: add("Built in", "Moss Image Edit", "chinoll", 1) elif operation == OP_CAMERA: add("Built in", "Qwen 2.1 Multiple Angles v2", "akhaliq", camera_strength) if dmd2: add("Built in", "Qwen Image 2.1 DMD2 v1.5", "linoyts", 1) if use_turbo: add("Built in", "Qwen 2.1 Viggle Turbo v0.2.1", "Viggle", 1) if not IS_TURBO and operation == OP_QWEN: spec = ADAPTER_SPECS.get(lora_adapter, {}) for part in spec.get("parts", [spec]): if part: add("Style", part.get("adapter_name", lora_adapter), str(part.get("repo", "")).split("/")[0], part.get("strength", 1)) if fast_lora in FAST_LORAS: add("Fast", fast_lora, str(FAST_LORAS[fast_lora].get("repo", "")).split("/")[0], fast_lora_strength) slots = [(u1r,u1f,u1s), (u2r,u2f,u2s), (u3r,u3f,u3s)] entries = _lora_library_entries() if any(ref and not upload for ref,upload,_ in slots) else [] lookup = {} for entry in entries: sources = [entry.get(key) for key in ("source", "original_download_url", "download_url", "url", "reference")] sources.extend(entry.get("sources", []) if isinstance(entry.get("sources"), list) else []) for source in sources: if isinstance(source, str) and source: lookup.setdefault(_active_lora_key(source), entry) for index, (reference, uploaded, strength) in enumerate(slots, 1): source, is_upload = _resolve_user_slot(uploaded, reference) if not source: continue entry = {} if is_upload else lookup.get(_active_lora_key(source), {}) add(f"Slot {index}", entry.get("name") or _active_lora_filename(source), entry.get("author", ""), strength) return "**Active LoRAs**\n\n" + ("\n".join(rows) if rows else "No LoRAs enabled.") def refresh_active_loras(query="", selected_id=None, idea="", prompt="", state=None, ui_mode="Simple"): picker, status = lora_library_sync(query, selected_id) count = len(_lora_library_entries()) note = "Using the saved list; refresh was unavailable." if "failed" in status.lower() else "LoRAs refreshed." suggestions, links, state, _ = refresh_prompt_loras(idea if ui_mode == "Pro" else "", prompt, state) note = f"{note} **{count} available.** Next group of suggestions; selected LoRAs and strengths kept." return picker, status, suggestions, links, state, note DARK_THEME_JS = """() => { document.documentElement.classList.add("dark"); document.documentElement.style.colorScheme = "dark"; document.body.classList.add("dark"); document.querySelectorAll("gradio-app, .gradio-container").forEach( element => element.classList.add("dark") ); }""" css = r""" /* Image Studio — local system fonts, accessible controls and no remote assets. */ :root, .dark { color-scheme: dark; --studio-bg: #131815; --studio-surface: #1c2420; --studio-panel: #232d27; --studio-field: #171f1a; --studio-ink: #edf2ed; --studio-muted: #b0bdb2; --studio-border: #35423a; --studio-border-strong: #617468; --studio-accent: #ef8158; --studio-accent-hover: #fa946f; --studio-accent-soft: #38281f; --studio-accent-border: #80513c; --studio-shadow: 0 8px 30px rgb(0 0 0 / 12%); --studio-focus: 0 0 0 3px rgb(239 129 88 / 30%); --studio-radius: 20px; } body { background: var(--studio-bg) !important; } .gradio-container { color-scheme: dark; --font: "Segoe UI", -apple-system, BlinkMacSystemFont, Arial, sans-serif; --font-mono: "Cascadia Code", "SFMono-Regular", Consolas, monospace; --body-background-fill: var(--studio-bg); --body-text-color: var(--studio-ink); --body-text-color-subdued: var(--studio-muted); --background-fill-primary: var(--studio-surface); --background-fill-secondary: var(--studio-panel); --block-background-fill: var(--studio-surface); --block-border-color: var(--studio-border); --block-border-width: 1px; --block-radius: 12px; --block-shadow: none; --block-label-background-fill: var(--studio-surface); --block-label-text-color: var(--studio-ink); --block-title-background-fill: var(--studio-panel); --block-title-border-color: var(--studio-border-strong); --block-title-text-color: var(--studio-ink); --block-info-text-color: var(--studio-muted); --accordion-text-color: var(--studio-ink); --border-color-primary: var(--studio-border); --border-color-accent: var(--studio-accent-border); --input-background-fill: var(--studio-field); --input-background-fill-focus: var(--studio-field); --input-border-color: var(--studio-border-strong); --input-border-color-focus: var(--studio-accent); --input-placeholder-color: var(--studio-muted); --input-shadow: none; --input-shadow-focus: var(--studio-focus); --input-text-size: 15px; --input-text-color: var(--studio-ink); --button-primary-background-fill: var(--studio-accent); --button-primary-background-fill-hover: var(--studio-accent-hover); --button-primary-border-color: var(--studio-accent); --button-primary-border-color-hover: var(--studio-accent-hover); --button-primary-text-color: #20150f; --button-primary-text-color-hover: #20150f; --button-primary-shadow: none; --button-primary-shadow-hover: none; --button-secondary-background-fill: var(--studio-surface); --button-secondary-background-fill-hover: var(--studio-panel); --button-secondary-border-color: var(--studio-border-strong); --button-secondary-border-color-hover: var(--studio-accent-border); --button-secondary-text-color: var(--studio-ink); --button-secondary-text-color-hover: var(--studio-ink); --button-secondary-shadow: none; --button-secondary-shadow-hover: none; --checkbox-background-color: var(--studio-field); --checkbox-background-color-selected: var(--studio-accent); --checkbox-border-color: var(--studio-border-strong); --checkbox-border-color-selected: var(--studio-accent); --checkbox-label-background-fill: var(--studio-surface); --checkbox-label-background-fill-hover: var(--studio-panel); --checkbox-label-background-fill-selected: var(--studio-accent-soft); --checkbox-label-border-color: var(--studio-border); --checkbox-label-border-color-selected: var(--studio-accent-border); --checkbox-label-text-color: var(--studio-ink); --checkbox-label-text-color-selected: var(--studio-ink); --slider-color: var(--studio-accent); --color-accent: var(--studio-accent); --color-accent-soft: var(--studio-accent-soft); --code-background-fill: var(--studio-field); --link-text-color: var(--studio-accent); --link-text-color-hover: var(--studio-accent-hover); --panel-background-fill: var(--studio-panel); --panel-border-color: var(--studio-border); max-width: 1440px !important; padding: 26px 32px 40px !important; color: var(--studio-ink) !important; background: var(--studio-bg) !important; font-family: var(--font) !important; font-size: 15px !important; line-height: 1.5 !important; } .dark .gradio-container, .gradio-container.dark { --button-primary-text-color: #20150f; --button-primary-text-color-hover: #20150f; } #col-container { width: 100%; max-width: 1360px; margin: 0 auto !important; gap: 18px !important; } #col-container .prose { color: var(--studio-ink); font-size: 14px; line-height: 1.55; } #col-container .prose h3 { margin: 0 0 8px; color: var(--studio-ink); font-size: 16px; font-weight: 650; line-height: 1.4; letter-spacing: -.015em; } #col-container .prose p { overflow-wrap: anywhere; } #col-container .prose :not(pre) > code { background: var(--studio-field); color: var(--studio-ink); border: 1px solid var(--studio-border-strong); border-radius: 5px; padding: 2px 5px; white-space: normal; overflow-wrap: anywhere; } #col-container .md code, #col-container .md pre, #col-container .info-text code { color: var(--studio-ink); } #col-container .prose pre { background: var(--studio-field); color: var(--studio-ink); border: 1px solid var(--studio-border); border-radius: 8px; } /* Leave native focus, disabled and loading semantics intact. */ #col-container button { min-height: 44px; border-radius: 11px; font-family: inherit; font-weight: 600; transition: background-color 140ms ease, border-color 140ms ease, box-shadow 140ms ease; } #col-container button:focus-visible, #col-container a:focus-visible, #col-container input:focus-visible, #col-container textarea:focus-visible, #col-container [role="tab"]:focus-visible { outline: 2px solid var(--studio-accent) !important; outline-offset: 3px; } #col-container input[type="text"], #col-container input[type="password"], #col-container input[type="number"], #col-container select { min-height: 44px; } /* Slider values and reset buttons share a native 24px clipping wrapper. */ #col-container .head:has(> .tab-like-container) { align-items: center; gap: 10px; } #col-container .head:has(> .tab-like-container) > label { flex: 1 1 150px; min-width: 0; max-width: 100%; } #col-container .head:has(> .tab-like-container) [data-testid="block-info"] { max-width: 100%; white-space: normal; overflow-wrap: anywhere; } #col-container .tab-like-container:has(input[type="number"]) { box-sizing: border-box; height: 46px; min-height: 46px; flex-shrink: 0; max-width: 100%; border-radius: 8px; background: var(--studio-field); } #col-container .tab-like-container input[type="number"] { box-sizing: border-box; height: 44px; min-height: 44px; width: calc(12ch + 32px); min-width: 0; padding: 8px 10px; color: var(--studio-ink); font-size: 15px; line-height: 1.2; font-variant-numeric: tabular-nums; } #col-container .tab-like-container .reset-button { box-sizing: border-box; height: 44px; min-height: 44px; min-width: 44px; flex: 0 0 44px; padding: 0 10px; border-radius: 0 7px 7px 0; } #col-container label.block:has(> input[type="number"]) { height: auto; min-width: 0; } #col-container label.block > input[type="number"] { box-sizing: border-box; height: 44px; min-height: 44px; line-height: 1.4; color: var(--studio-ink); } #col-container input[type="range"] { min-height: 36px; cursor: pointer; } #col-container label:has(> input[type="checkbox"]), #col-container label:has(> input[type="radio"]) { min-height: 44px; cursor: pointer; align-items: center; } #col-container .gr-accordion > button.label-wrap { display: flex; align-items: center; gap: 12px; min-height: 48px; width: 100%; min-width: 0; padding-top: 12px; padding-bottom: 12px; text-align: left; color: var(--studio-ink) !important; } #col-container .gr-accordion > button.label-wrap:hover { background: var(--studio-panel); } #col-container .gr-accordion > button.label-wrap > span:first-child { min-width: 0; overflow-wrap: anywhere; } /* A square arrow stays inside its header when a closed section rotates it. */ #col-container .gr-accordion > button.label-wrap > .icon { display: inline-flex; flex: 0 0 20px; width: 20px; height: 20px; align-items: center; justify-content: center; line-height: 20px; color: inherit; } #col-container span[data-testid="block-info"] { background: var(--studio-panel) !important; color: var(--studio-ink) !important; border-color: var(--studio-border-strong) !important; } #col-container label[data-testid="block-label"] { background: var(--studio-surface) !important; color: var(--studio-ink) !important; border-color: var(--studio-border-strong) !important; } /* Compact identity header; the actual operation controls carry the navigation. */ #studio-header { padding: 0 !important; border: 0 !important; background: transparent !important; } .studio-header { display: flex; align-items: center; justify-content: space-between; gap: 24px; padding: 2px 2px 12px; } .studio-brand { display: flex; align-items: center; gap: 13px; min-width: 0; } .studio-brand-mark { display: grid; flex: 0 0 52px; width: 52px; height: 52px; place-items: center; border: 1px solid var(--studio-accent-border); border-radius: 16px; background: var(--studio-accent-soft); color: var(--studio-accent); } .studio-brand-mark svg { display: block; } .studio-eyebrow { margin: 0 0 1px; color: var(--studio-muted); font-size: 11px; font-weight: 700; line-height: 1.45; letter-spacing: .11em; text-transform: uppercase; } .studio-brand-copy h1 { margin: 0 !important; color: var(--studio-ink) !important; font-size: 26px !important; font-weight: 680 !important; line-height: 1.2 !important; letter-spacing: -.04em; } .studio-header-description { margin: 0 !important; color: var(--studio-ink); font-size: 13px; font-weight: 550; line-height: 1.55; text-align: right; } .studio-header-description span { color: var(--studio-muted); font-weight: 400; } /* Native Gradio Radio labels are retained, including keyboard navigation. */ #studio-operation { padding: 12px !important; border: 1px solid var(--studio-border) !important; border-radius: 17px !important; background: var(--studio-panel) !important; box-shadow: none !important; } #studio-operation > .wrap { display: grid !important; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 6px !important; } #studio-operation > .wrap > label, .studio-model > .wrap > label, #ui-mode > .wrap > label { position: relative; display: flex !important; align-items: center !important; justify-content: center; min-height: 48px; margin: 0 !important; padding: 10px 14px !important; border: 1px solid transparent !important; border-radius: 11px !important; background: transparent !important; color: var(--studio-muted) !important; box-shadow: none !important; font-size: 14px !important; font-weight: 600 !important; line-height: 1.35; text-align: center; transition: background-color 140ms ease, border-color 140ms ease, box-shadow 140ms ease; } #studio-operation > .wrap > label:hover, .studio-model > .wrap > label:hover, #ui-mode > .wrap > label:hover { background: var(--studio-surface) !important; color: var(--studio-ink) !important; } #studio-operation > .wrap > label.selected, #studio-operation > .wrap > label:has(input:checked) { border-color: var(--studio-accent-border) !important; background: var(--studio-surface) !important; color: var(--studio-accent) !important; box-shadow: 0 2px 5px rgb(24 40 29 / 6%) !important; } #studio-operation > .wrap > label input, .studio-model > .wrap > label input, #ui-mode > .wrap > label input { position: absolute !important; width: 1px !important; height: 1px !important; margin: 0 !important; opacity: 0; } #studio-operation > .wrap > label:has(input:focus-visible), .studio-model > .wrap > label:has(input:focus-visible), #ui-mode > .wrap > label:has(input:focus-visible) { outline: 2px solid var(--studio-accent); outline-offset: 2px; } #studio-operation > .wrap > label span, .studio-model > .wrap > label span, #ui-mode > .wrap > label span { color: inherit !important; font-size: inherit !important; font-weight: inherit !important; white-space: normal; } #operation-note { margin-top: -6px !important; padding: 0 4px !important; border: 0 !important; background: transparent !important; } #operation-note .prose, #operation-note p { margin: 0 !important; color: var(--studio-muted) !important; font-size: 13px !important; } .studio-model { width: fit-content !important; max-width: 100%; padding: 0 !important; border: 0 !important; background: transparent !important; } .studio-model > .wrap, #ui-mode > .wrap { display: flex !important; gap: 4px !important; width: fit-content; max-width: 100%; padding: 4px; border: 1px solid var(--studio-border); border-radius: 13px; background: var(--studio-panel); } .studio-model > .wrap > label, #ui-mode > .wrap > label { flex: 1 1 auto; min-height: 44px; padding: 9px 17px !important; font-size: 13px !important; } .studio-model > .wrap > label.selected, .studio-model > .wrap > label:has(input:checked), #ui-mode > .wrap > label.selected, #ui-mode > .wrap > label:has(input:checked) { border-color: var(--studio-border-strong) !important; background: var(--studio-surface) !important; color: var(--studio-ink) !important; box-shadow: 0 1px 4px rgb(24 40 29 / 5%) !important; } #target-pixel > .wrap { display: grid !important; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px !important; } #target-pixel > .wrap > label { display: flex !important; align-items: center !important; justify-content: center; min-height: 40px; margin: 0 !important; border: 1px solid var(--studio-border) !important; border-radius: 8px !important; font-weight: 600 !important; } #target-pixel > .wrap > label.selected, #target-pixel > .wrap > label:has(input:checked) { border-color: var(--studio-accent-border) !important; color: var(--studio-accent) !important; } /* Work surfaces: one coherent input card and a persistent result beside it. */ #studio-workspace { gap: 22px !important; align-items: flex-start !important; } #input-col { min-width: min(100%, 380px) !important; padding: 20px !important; gap: 16px !important; border: 1px solid var(--studio-border) !important; border-radius: var(--studio-radius) !important; background: var(--studio-surface) !important; box-shadow: var(--studio-shadow) !important; } #reference-images { gap: 12px !important; } #reference-images > .block { min-width: 170px !important; } #reference-one, #reference-two { overflow: hidden; border: 1px solid var(--studio-border-strong) !important; border-radius: 13px !important; background: var(--studio-panel) !important; box-shadow: none !important; } #reference-one .upload-container, #reference-two .upload-container { background: var(--studio-panel) !important; } #reference-one button, #reference-two button, #studio-result button { min-width: 44px; min-height: 44px; } #studio-prompt { border-radius: 13px !important; box-shadow: none !important; } #studio-prompt textarea { min-height: 126px !important; padding: 13px 14px !important; border-radius: 9px !important; font-size: 15px !important; line-height: 1.65 !important; } #prompt-helper { padding: 15px !important; gap: 7px !important; border: 1px solid var(--studio-border) !important; border-radius: 13px !important; background: var(--studio-panel) !important; box-shadow: none !important; } #prompt-helper .prose h3, #prompt-helper .prose p { margin: 0 !important; } #prompt-helper .prose p { color: var(--studio-muted); font-size: 13px; } #enhance-btn { min-height: 46px !important; margin-top: 5px; border-color: var(--studio-border-strong) !important; background: var(--studio-surface) !important; color: var(--studio-ink) !important; box-shadow: none !important; } #enhance-btn:hover { border-color: var(--studio-accent-border) !important; background: var(--studio-accent-soft) !important; } #active-loras { padding: 15px !important; border: 1px solid var(--studio-border) !important; border-radius: 13px !important; background: var(--studio-surface) !important; } #active-loras .prose > p:first-child { margin: 0 0 10px !important; color: var(--studio-ink); font-size: 14px; letter-spacing: -.01em; } #active-loras .prose > p:only-child { margin-bottom: 0 !important; } #active-loras ul { display: grid; gap: 8px; margin: 0 !important; padding: 0 !important; list-style: none !important; } #active-loras li { position: relative; margin: 0 !important; padding: 12px 13px 12px 19px !important; border: 1px solid var(--studio-border); border-radius: 9px; background: var(--studio-panel); color: var(--studio-muted); font-size: 12px; line-height: 1.6; overflow-wrap: anywhere; } #active-loras li::before { position: absolute; top: 14px; bottom: 14px; left: 8px; width: 3px; border-radius: 3px; background: var(--studio-accent); content: ""; } #active-loras li > strong:first-child, #active-loras li > p > strong:first-child { display: block; margin-bottom: 3px; color: var(--studio-ink); font-size: 13px; font-weight: 650; } #active-loras li strong { color: var(--studio-ink); } #active-loras li p { margin: 0 !important; } #lora-picks .wrap { gap: 8px !important; } #lora-picks label:has(input) { width: 100%; padding: 11px 12px !important; border-radius: 10px !important; line-height: 1.4; } #lora-links .prose { font-size: 12px; line-height: 1.65; } #lora-refresh { min-height: 44px !important; font-size: 13px !important; } #lora-status .prose { color: var(--studio-ink); font-size: 14px; } #result-dimensions .prose { color: var(--studio-muted); font-size: 12px; } .gpu-estimate { padding: 11px 13px !important; border: 1px solid var(--studio-border) !important; border-radius: 11px !important; background: var(--studio-panel) !important; color: var(--studio-muted); } .gpu-estimate .prose, .gpu-estimate p { margin: 0 !important; color: var(--studio-muted); font-size: 12px !important; line-height: 1.5; } .gpu-estimate strong { color: var(--studio-ink); font-weight: 600; } .gpu-estimate sub { font-size: 11px; } #run-btn { position: relative !important; top: auto !important; min-height: 56px !important; margin: 0 !important; border: 1px solid var(--studio-accent) !important; border-radius: 13px !important; background: var(--studio-accent) !important; color: var(--button-primary-text-color) !important; box-shadow: 0 4px 10px rgb(207 71 28 / 14%) !important; font-size: 16px !important; font-weight: 700 !important; letter-spacing: .005em; } #run-btn:hover:not(:disabled) { border-color: var(--studio-accent-hover) !important; background: var(--studio-accent-hover) !important; box-shadow: 0 6px 16px rgb(207 71 28 / 20%) !important; } #out-col { position: sticky; top: 20px; align-self: flex-start !important; min-width: min(100%, 380px) !important; padding: 20px !important; gap: 12px !important; border: 1px solid var(--studio-border) !important; border-radius: var(--studio-radius) !important; background: var(--studio-surface) !important; box-shadow: var(--studio-shadow) !important; } #studio-result { overflow: hidden; border: 1px solid var(--studio-border) !important; border-radius: 13px !important; background: var(--studio-panel) !important; box-shadow: none !important; } #studio-result .image-container, #studio-result .empty { background: var(--studio-panel) !important; } /* Before / After comparison: same frame as the result, toggled by a segmented control. */ #studio-compare { overflow: hidden; border: 1px solid var(--studio-border) !important; border-radius: 13px !important; background: var(--studio-panel) !important; box-shadow: none !important; } #studio-compare button { min-width: 44px; min-height: 44px; } #result-view .wrap { display: flex !important; gap: 0 !important; padding: 3px !important; border: 1px solid var(--studio-border) !important; border-radius: 999px !important; background: var(--studio-panel) !important; } #result-view label { flex: 1 1 0; justify-content: center; min-height: 36px; margin: 0 !important; border: 0 !important; border-radius: 999px !important; background: transparent !important; box-shadow: none !important; cursor: pointer; } #result-view label input { position: absolute; opacity: 0; pointer-events: none; } #result-view label.selected, #result-view label:has(input:checked) { background: var(--studio-accent) !important; color: #fff !important; } #result-view label:has(input:focus-visible) { outline: 2px solid var(--studio-accent); outline-offset: 2px; } /* Auto-Describe sits directly under the prompt it writes. */ #auto-describe { gap: 6px !important; padding: 0 !important; border: 0 !important; background: transparent !important; box-shadow: none !important; } #auto-describe .block, #auto-describe .form, #auto-describe .styler, #auto-describe-row { border: 0 !important; background: transparent !important; box-shadow: none !important; } #auto-describe-row { flex-wrap: wrap; gap: 8px !important; } #auto-describe-row button { flex: 0 1 auto !important; min-width: 0 !important; min-height: 36px; } #auto-describe-status .prose p { margin: 0 !important; font-size: 0.85em; opacity: 0.8; } #result-dimensions .prose p { margin: 0 !important; } /* Secondary controls remain plainly visible and preserve Simple / Pro behavior. */ #more-settings { margin-top: 6px; padding: 22px !important; gap: 16px !important; border: 1px solid var(--studio-border) !important; border-radius: var(--studio-radius) !important; background: var(--studio-surface) !important; box-shadow: var(--studio-shadow) !important; } #settings-heading .prose h3 { margin: 0 !important; font-size: 18px !important; font-weight: 650; letter-spacing: -.025em; } #ui-mode { width: fit-content !important; padding: 0 !important; border: 0 !important; background: transparent !important; } #ui-mode > .wrap > label { min-width: 108px; } #image-settings { border: 1px solid var(--studio-border) !important; border-radius: 13px !important; background: var(--studio-surface) !important; } #more-settings .tab-wrapper { height: auto; min-height: 52px; } #more-settings .tab-container { height: 44px; min-height: 44px; gap: 5px; border-bottom-color: var(--studio-border); } #more-settings .tab-container > button { padding: 10px 15px; color: var(--studio-muted); font-size: 13px; } #more-settings .tab-container > button.selected, #more-settings .tab-container > button[aria-selected="true"] { border-color: var(--studio-accent-border); background: var(--studio-accent-soft); color: var(--studio-accent); } .panel { padding: 16px !important; border: 1px solid var(--studio-border) !important; border-radius: 13px !important; background: var(--studio-panel) !important; box-shadow: none !important; } .route-row { gap: 10px !important; } .route-row button { min-height: 46px !important; font-size: 13px !important; } .search-results { max-height: 320px; overflow-y: auto; padding: 12px 14px; border: 1px solid var(--studio-border); border-radius: 12px; background: var(--studio-panel); color: var(--studio-ink); font-size: 13px; } .consent-note { padding: 11px 13px; border: 1px solid var(--studio-accent-border); border-radius: 11px; background: var(--studio-accent-soft); color: var(--studio-ink); font-size: 13px; } @media (max-width: 1100px) { .gradio-container { padding: 22px 22px 32px !important; } #studio-operation > .wrap { grid-template-columns: repeat(3, minmax(0, 1fr)); } #studio-workspace { gap: 16px !important; } #input-col, #out-col { padding: 16px !important; } } @media (max-width: 860px) { #studio-workspace { flex-direction: column !important; } #input-col, #out-col { width: 100% !important; min-width: 0 !important; } #out-col { position: static; } #studio-result, #studio-compare { height: min(560px, 72vw) !important; min-height: 300px !important; } } @media (max-width: 580px) { .gradio-container { padding: 17px 12px 28px !important; } #col-container { gap: 15px !important; } .studio-header { gap: 12px; padding-bottom: 7px; } .studio-brand { gap: 11px; } .studio-brand-mark { flex-basis: 46px; width: 46px; height: 46px; border-radius: 14px; } .studio-brand-copy h1 { font-size: 24px !important; } .studio-header-description { display: none; } #studio-operation { padding: 9px !important; border-radius: 14px !important; } #studio-operation > .wrap { grid-template-columns: repeat(2, minmax(0, 1fr)); } #studio-operation > .wrap > label { min-height: 48px; padding: 10px 8px !important; font-size: 13px !important; } #studio-operation > .wrap > label:last-child:nth-child(odd) { grid-column: 1 / -1; } .studio-model { width: 100% !important; } .studio-model > .wrap { width: 100%; } .studio-model > .wrap > label { min-width: 0; padding: 9px 10px !important; } #input-col, #out-col, #more-settings { padding: 14px !important; border-radius: 16px !important; } #reference-images { flex-direction: column !important; } #reference-images > .block { width: 100% !important; min-width: 0 !important; } #studio-prompt textarea { font-size: 16px !important; } #more-settings .tab-container > button { padding: 10px 12px; } } @media (prefers-reduced-motion: reduce) { #col-container *, #col-container *::before, #col-container *::after { scroll-behavior: auto !important; transition: none !important; } } """ STUDIO_HEADER = """
Qwen 2.1 + MOSS

Image Studio

Edit. Relight. Change the angle.
Turbo, DMD2 or Base. Your images, your settings.

""" HERO = f"""

{MODEL_LABEL}

{"Create or edit images with Viggle Turbo v0.2.1. Six steps by default." if IS_TURBO else "Your original Rapid AIO editor with its legacy adapters and decoder."}

3 custom LoRA slotsmultiple references Qwen prompt & LoRA helperSimple / Prodepth mapsnamed profilescanvas sizes
""" INTRO = """**Built with Qwen · Distillation by Viggle.** Turbo uses Qwen Image 2.1, Viggle v0.2.1, the official six-step schedule and CFG 1. Keep optional LoRAs specific to **Qwen Image 2.1**. Native Diffusers/PEFT and supported ComfyUI exports are checked and prepared before generation. The older 2509/2511 LoRAs and WAN decoder use a different architecture. To use the original model, keep your original `qwenimage/` folder and set the Space variable **QWEN_BACKEND=legacy**, then restart. Only the selected model is loaded. Switch back with **QWEN_BACKEND=turbo**. See the included setup notes for dependencies. Profiles remain readable in both modes; incompatible values are adapted visibly on import. """ FAST_HELP = ("Viggle Turbo is already active at strength 1.0. Its six-step schedule is built in; " "old Lightning adapters are available in legacy mode." if IS_TURBO else "Optional 2509/2511 Lightning adapters. The AIO model is already distilled; start with None.") USER_LORA_HELP = """Three independently weighted adapters. Use an `owner/repo`, `owner/repo/file.safetensors`, Hugging Face file URL, direct download link, or upload. Strength 0 disables a slot. Downloads happen before GPU allocation and the saved links stay portable. """ + (" **Turbo requires Qwen Image 2.1 LoRAs. Supported Diffusers/PEFT and ComfyUI formats are validated before GPU allocation.**" if IS_TURBO else "") # gradio 6.0 takes `theme` and `css` on launch(), not here - passing them to the constructor # only earns a warning and the styling is dropped. with gr.Blocks(title=PUBLIC_TITLE) as demo: with gr.Column(elem_id="col-container"): gr.HTML(STUDIO_HEADER, elem_id="studio-header") operation = gr.Radio([("Qwen Face Swap", value) if value == OP_FACE else ("Qwen Detail Enhancer", value) if value == OP_DETAIL else ("Camera Angle — BETA TEST", value) if value == OP_CAMERA else (value, value) for value in OPERATIONS] if IS_TURBO else [OP_QWEN], value=OP_QWEN, label="Operation", elem_id="studio-operation") operation_note = gr.Markdown("Edit reference images, or leave images empty to create from text. Turbo defaults: 6 steps, CFG 1.", elem_id="operation-note") qwen_mode = gr.Radio([("Viggle Turbo (6 steps)", QWEN_TURBO), QWEN_DMD2, ("Native Base (Edit / Relight 30 steps, Camera 40)", QWEN_BASE)], value=QWEN_TURBO, label="Qwen Image Edit model", visible=IS_TURBO, elem_classes="studio-model") face_mode = gr.Radio([("Viggle Turbo (6 steps)", FACE_TURBO), QWEN_DMD2, ("Base (30 steps, no Viggle)", FACE_BASE)], value=FACE_TURBO, label="Qwen Face Swap model", visible=False, elem_classes="studio-model") outpaint_mode = gr.Radio([("Viggle Turbo (6 steps)", OUTPAINT_TURBO), QWEN_DMD2, ("Base (25 steps, no Viggle)", OUTPAINT_BASE)], value=OUTPAINT_TURBO, label="Qwen Outpaint model", visible=False, elem_classes="studio-model") detail_mode = gr.Radio([(DETAIL_TURBO, DETAIL_TURBO), QWEN_DMD2, ("Base (25 steps, no Viggle)", DETAIL_BASE)], value=DETAIL_TURBO, label="Qwen Detail Enhancer model", visible=False, elem_classes="studio-model") pro_controls = [] assistant_state = gr.State({}) with gr.Row(equal_height=False, elem_id="studio-workspace"): with gr.Column(scale=5, elem_id="input-col"): with gr.Row(elem_id="reference-images"): input_image_1 = gr.Image(label="Image 1 (optional)" if IS_TURBO else "Image 1", type="pil", image_mode="RGBA" if IS_TURBO else "RGB", height=260, elem_id="reference-one") input_image_2 = gr.Image(label="Image 2 - optional reference", type="pil", image_mode="RGBA" if IS_TURBO else "RGB", height=260, elem_id="reference-two") with gr.Accordion("Qwen Face Swap settings", open=False, visible=False) as face_controls: face_strength = gr.Slider(0, 1.5, value=1, step=0.05, label="BFS Head v1.1 strength") face_prompt_button = gr.Button("Restore Qwen Face Swap prompt", size="sm") with gr.Group(visible=False) as outpaint_controls: gr.Markdown("### Expand the canvas\nEach percentage adds that much of the source width or height on that side.") with gr.Row(): outpaint_left = gr.Slider(0, 100, value=25, step=1, label="Expand left (%)") outpaint_right = gr.Slider(0, 100, value=25, step=1, label="Expand right (%)") with gr.Row(): outpaint_top = gr.Slider(0, 100, value=25, step=1, label="Expand top (%)") outpaint_bottom = gr.Slider(0, 100, value=25, step=1, label="Expand bottom (%)") outpaint_canvas = gr.Image(label="Expanded canvas preview", interactive=False, type="pil", format="png", height=240) outpaint_dimensions = gr.Markdown("Upload a source image to preview the expanded canvas.") with gr.Accordion("Outpaint detail settings", open=False): outpaint_feather = gr.Slider(0, 128, value=32, step=1, label="Blend along the original edge (pixels)", info="Softens the join inside the source edge. Set 0 to preserve every source pixel after resizing.") outpaint_prompt_button = gr.Button("Restore Outpaint prompt", size="sm") with gr.Accordion("Qwen Detail Enhancer settings", open=False, visible=False) as detail_controls: from detail_backend import DETAIL_PRESETS detail_strength = gr.Slider(0, 1.5, value=1, step=.05, label="Elusarca Qwen Detail Enhancer strength", info="The built-in enhancement adapter is separate from your three optional LoRA slots.") detail_preset = gr.Radio(list(DETAIL_PRESETS), value="Generic (original workflow)", label="Enhancement prompt preset") detail_prompt_button = gr.Button("Restore Qwen Detail Enhancer prompt", size="sm") with gr.Group(visible=False) as relight_controls: from relight_backend import PRESETS as RELIGHT_PRESETS from visual_controls import ( RELIGHT_HTML, RELIGHT_CSS, RELIGHT_JS, CAMERA_HTML, CAMERA_CSS, CAMERA_JS, relight_widget_value, camera_widget_value, read_relight_widget, read_camera_widget, ) relight_visual = gr.HTML(value=relight_widget_value(), html_template=RELIGHT_HTML, css_template=RELIGHT_CSS, js_on_load=RELIGHT_JS, elem_id="relight-visual", apply_default_css=False) relight_preset = gr.Dropdown(list(RELIGHT_PRESETS), value="Soft studio", label="Lighting style", visible=False) relight_direction = gr.Dropdown(["Left", "Right", "Front", "Above", "Behind"], value="Left", label="Light from", visible=False) relight_color = gr.ColorPicker(value="#FFFFFF", label="Light colour", visible=False) with gr.Group(visible=False) as relight_pro: relight_strength = gr.Slider(0, 1, value=1, step=.05, label="Blend with original", info="1 uses the full relight. Lower values mix the original image; shifted details may create double edges.") pro_controls.append(relight_pro) with gr.Group(visible=False) as camera_controls: from camera_backend import AZIMUTH_CHOICES, ELEVATION_CHOICES camera_visual = gr.HTML(value=camera_widget_value(), html_template=CAMERA_HTML, css_template=CAMERA_CSS, js_on_load=CAMERA_JS, elem_id="camera-visual", apply_default_css=False) camera_azimuth = gr.Dropdown(AZIMUTH_CHOICES, value=90, label="View from", visible=False) camera_elevation = gr.Dropdown(ELEVATION_CHOICES, value=0, label="Camera height", visible=False) camera_closeup = gr.Checkbox(False, label="Close-up", visible=False) with gr.Group(visible=False) as camera_pro: camera_strength = gr.Slider(0.3, 1.5, value=CAMERA_STRENGTH, step=.05, label="Camera LoRA strength", info="0.5 is recommended. Higher can turn further but often turns a photo into a plain studio render.") pro_controls.append(camera_pro) prompt = gr.Textbox(label="What do you want to create or change?", lines=4, placeholder="Describe your image or the changes you want", elem_id="studio-prompt") with gr.Group(visible=operation.value in DESCRIBE_OPERATIONS, elem_id="auto-describe") as describe_group: with gr.Row(elem_id="auto-describe-row"): describe_button = gr.Button("🔍 Auto-Describe Image 1 (Paid · GPU)", size="sm", variant="secondary", elem_id="auto-describe-btn") describe_undo = gr.Button("↩ Restore previous prompt", size="sm", variant="secondary", visible=False, elem_id="auto-describe-undo") describe_status = gr.Markdown(DESCRIBE_HINT, elem_id="auto-describe-status") previous_prompt = gr.State(None) target_pixel = gr.Radio(target_pixel_choices(OP_QWEN), value=1.0, label="Target pixel", info=target_pixel_info(OP_QWEN), elem_id="target-pixel") with gr.Accordion("Negative prompt (optional)", open=False): negative_prompt_text = gr.Textbox(label="Negative prompt (optional)", value=DEFAULT_NEGATIVE_TEXT, lines=2, placeholder="Describe what to avoid", interactive=True) gr.Markdown("Adding text raises CFG from 1 to 1.1 automatically. CFG above 1 uses extra GPU work.") with gr.Group(elem_id="prompt-helper") as prompt_helper_group: gr.Markdown("### Prompt Improvement") gr.Markdown("Refine your description in one click.") pb_button = gr.Button("Improve Prompt", variant="secondary", elem_id="enhance-btn") cpu_pick_button = gr.Button("Pick LoRAs from prompt (Free · CPU)", size="sm", variant="secondary", elem_id="pick-loras-cpu") active_loras = gr.Markdown(active_lora_summary(), elem_id="active-loras") with gr.Group() as lora_suggestions_group: if all(os.environ.get(name) for name in ( "OAUTH_CLIENT_ID", "OAUTH_CLIENT_SECRET", "OAUTH_SCOPES", "OPENID_PROVIDER_URL", )): gr.Markdown("**Heretic · Free CPU** for related LoRA suggestions after owner sign-in.") gr.LoginButton("Sign in with Hugging Face", size="sm") else: gr.Markdown("**Heretic · Free CPU** · Hugging Face sign-in is temporarily unavailable.") pb_status = gr.Markdown("", elem_id="lora-status") pb_picks = gr.CheckboxGroup(choices=[], value=[], label="LoRAs - tick to use (up to 3)", visible=False, elem_id="lora-picks") pb_links = gr.Markdown("", elem_id="lora-links") pb_refresh = gr.Button("Refresh LoRAs - next group", size="sm", elem_id="lora-refresh") active_lora_refresh_button, active_lora_status = pb_refresh, pb_status estimate = gr.Markdown("**Generation time:** not measured yet.", elem_classes="gpu-estimate") run_button = gr.Button("Generate", variant="primary", elem_id="run-btn") with gr.Column(scale=6, elem_id="out-col"): result_view = gr.Radio( [COMPARE_VIEW_RESULT, COMPARE_VIEW_SLIDER], value=COMPARE_VIEW_RESULT, show_label=False, container=False, visible=False, elem_id="result-view") output_image = gr.Image(label="Result", interactive=False, format="png", height=560, elem_id="studio-result") compare_slider = gr.ImageSlider( label="Before / After - drag the handle to compare", type="pil", format="png", interactive=False, visible=False, height=560, max_height=560, buttons=["download", "fullscreen"], elem_id="studio-compare") output_dimensions = gr.Markdown("", elem_id="result-dimensions") last_output = gr.State(value=None) with gr.Group(elem_id="more-settings"): gr.Markdown("### More Settings", elem_id="settings-heading") ui_mode = gr.Radio(["Simple", "Pro"], value="Simple", label="Controls", elem_id="ui-mode") with gr.Accordion("Image settings", open=False, elem_id="image-settings"): with gr.Accordion("About this studio", open=False) as qwen_about: gr.Markdown(INTRO) with gr.Group() as helper_settings_scope: with gr.Accordion("Prompt Improvement settings", open=False, visible=False) as helper_pro: pb_writer = gr.Dropdown(assistant_choices(DEFAULT_QWEN_SPACE), value=DEFAULT_QWEN_SPACE, label="Prompt helper") with gr.Row(): pb_suggest_loras = gr.Checkbox(True, label="Suggest LoRAs and set strengths") pb_use_images = gr.Checkbox(True, label="Use reference images in the helper") gr.Markdown(ECONOMY_NOTE) pb_idea = gr.Textbox(label="Separate helper instructions (optional)", lines=2, placeholder="Leave empty to use the main description") with gr.Accordion("Prompt controls", open=False): with gr.Row(): pb_kind = gr.Dropdown(list(EDIT_KINDS), value="(keep as written)", label="Edit type") pb_angle = gr.Dropdown(list(EDIT_ANGLES), value="(keep as written)", label="Framing / angle") with gr.Row(): pb_lighting = gr.Dropdown(list(EDIT_LIGHTING), value="(keep as written)", label="Lighting") pb_look = gr.Dropdown(list(EDIT_LOOKS), value="(keep as written)", label="Look") pb_identity = gr.Checkbox(True, label="Preserve identity when editing people") pb_use_model = gr.Checkbox(True, label="Use Qwen (off = local text builder)") writer_token = gr.Textbox(label="Your HF token (optional)", type="password", info="Used only for your prompt helper request; never saved in profiles.") gr.Markdown("Prepare uses one request for the prompt, LoRAs and strengths. Refresh only changes suggestions; it uses no AI or GPU.") pro_controls.append(helper_pro) aspect_ratio = gr.Dropdown( ["Match Image 1", "1:1", "4:3", "3:4", "16:9", "9:16", "3:2", "2:3", "4:5", "5:4", "21:9", "9:21", "Custom"], value="Match Image 1", label="Output aspect ratio", info="Sets the saved image shape. Qwen fixed ratios use a small center crop. MOSS fits the full source. Custom dimensions are in Pro.") with gr.Group(visible=False) as style_pro: lora_choices = [NONE_LORA] + list(ADAPTER_SPECS.keys()) lora_adapter = gr.Dropdown( label="🎨 Editing style (bundled lora)", choices=[NONE_LORA] if IS_TURBO else lora_choices, value=NONE_LORA, interactive=not IS_TURBO, info="Legacy styles require QWEN_BACKEND=legacy." if IS_TURBO else "Selecting a style fills a matching prompt when the prompt box is empty.", ) if not IS_TURBO: pro_controls.append(style_pro) with gr.Accordion("LoRA library", open=False, visible=False) as library_settings: library_header = gr.Markdown(f"Shared library: **{REMOTE_LORA_BUCKET}**") library_query = gr.Textbox(label="Search library", placeholder="Name, author or trigger") library_sync_button = gr.Button("🔄 Sync library", size="sm") library_picker = gr.Dropdown(choices=lora_library_refresh()[0]["choices"], label="LoRA", value=None) library_details = gr.Markdown("") with gr.Row(): library_slot = gr.Dropdown(["my lora 1", "my lora 2", "my lora 3"], value="my lora 1", label="Apply to slot") library_apply = gr.Button("Apply LoRA", variant="secondary") library_status = gr.Markdown("") with gr.Group(visible=False) as library_pro: with gr.Accordion("Add, import or export LoRAs", open=False): library_name = gr.Textbox(label="Name") library_source = gr.Textbox(label="HF reference or download URL", placeholder="owner/repo/file.safetensors") library_model = gr.Dropdown(LORA_LIBRARY_MODELS, value="qwen-image-2.1" if IS_TURBO else "qwen-edit-2511", label="Model") library_trigger = gr.Textbox(label="Trigger words") library_strength = gr.Slider(0, 4, value=1, step=0.05, label="Default strength (MOSS: 0-4; Qwen: 0-2)") library_author = gr.Textbox(label="Author (optional)") library_write_token = gr.Textbox(type="password", label="HF write token (catalogue owner only)", info="Needed only to save, delete or import shared MOSS entries. Never saved in profiles.", visible=False) with gr.Row(): library_save = gr.Button("Save / update entry") library_delete = gr.Button("Delete selected entry") library_import = gr.File(label="Import library JSON", file_types=[".json"], type="filepath") library_export = gr.Button("Export library JSON") library_download = gr.File(label="Library JSON", visible=False, interactive=False) pro_controls.append(library_pro) pro_controls.append(library_settings) with gr.Accordion("Additional reference images", open=False) as extra_references_group: input_images_extra = gr.Gallery( label="Extra references", type="pil", height=240, columns=4, rows=2, interactive=True, ) with gr.Group(visible=False) as advanced_pro: with gr.Group(elem_classes="panel", visible=not IS_TURBO) as fast_adapter_group: gr.Markdown("### ⚡ Fast lora (step distillation)") gr.Markdown(FAST_HELP) fast_lora = gr.Dropdown( label="Fast adapter", choices=[("Viggle Turbo (built in)", NO_FAST_LORA)] if IS_TURBO else FAST_LORA_CHOICES, value=NO_FAST_LORA, interactive=not IS_TURBO, ) fast_lora_strength = gr.Slider( label="Fast lora strength", minimum=0.0, maximum=2.0, step=0.05, value=1.0, visible=False, ) with gr.Tabs(): with gr.Tab("⭐ My lora"): user_lora_help = gr.Markdown(USER_LORA_HELP) with gr.Accordion("🔍 Search CivitAI", open=False): with gr.Row(): search_query = gr.Textbox(label="Search", placeholder="e.g. relight, anime", scale=3) search_base = gr.Dropdown(["Qwen Image 2.1"] if IS_TURBO else QIE_BASE_MODELS, value="Qwen Image 2.1" if IS_TURBO else QIE_BASE_MODELS[0], label="Base model", allow_custom_value=True, scale=2) with gr.Row(): search_nsfw = gr.Checkbox(value=False, label="Include NSFW results") search_btn = gr.Button("🔍 Search", variant="secondary", elem_id="search-btn") search_pick = gr.Dropdown(choices=[], label="Pick a file") with gr.Row(): search_slot = gr.Dropdown([f"my lora {i}" for i in range(1, 4)], value="my lora 1", label="Into slot", scale=2) search_put_btn = gr.Button("⬇️ Put it in", variant="primary", scale=1, elem_id="search-put") # Below the picker on purpose: a wall of results above it would push the # controls off the screen. search_results = gr.Markdown("No search yet.") search_state = gr.State({}) with gr.Group(): user_lora_1_ref = gr.Textbox(label="my lora 1", placeholder="owner/repo") user_lora_1_file = gr.File(label="…or upload", file_types=[".safetensors"], type="filepath") user_lora_1_scale = gr.Slider(label="my lora 1 strength", minimum=0.0, maximum=4.0, step=0.05, value=0.0) with gr.Group(): user_lora_2_ref = gr.Textbox(label="my lora 2", placeholder="owner/repo") user_lora_2_file = gr.File(label="…or upload", file_types=[".safetensors"], type="filepath") user_lora_2_scale = gr.Slider(label="my lora 2 strength", minimum=0.0, maximum=4.0, step=0.05, value=0.0) with gr.Group(): user_lora_3_ref = gr.Textbox(label="my lora 3", placeholder="owner/repo") user_lora_3_file = gr.File(label="…or upload", file_types=[".safetensors"], type="filepath") user_lora_3_scale = gr.Slider(label="my lora 3 strength", minimum=0.0, maximum=4.0, step=0.05, value=0.0) lora_identify_btn = gr.Button("🔎 name my links", variant="secondary", elem_id="lora-identify") lora_names = gr.Markdown("Nothing in the slots yet.") with gr.Tab("⚙️ Sampling"): seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0) randomize_seed = gr.Checkbox(label="🎲 Randomize seed", value=True) guidance_scale = gr.Slider(label="CFG", minimum=1.0, maximum=10.0, step=0.1, value=DEFAULT_CFG, interactive=True) # Static bounds cover all modes. Gradio validates queued # inputs before a concurrent mode-update has reached the # session; narrowing these bounds can reject a valid 30. # Model-specific limits are checked before GPU allocation. steps = gr.Slider(label="Inference Steps (4-8 for Turbo)" if IS_TURBO else "Inference Steps (1-50)", minimum=1, maximum=60, step=1, value=DEFAULT_STEPS) sampling_note = gr.Markdown("Default CFG 1. Negative prompts automatically use at least CFG 1.1; CFG above 1 uses extra GPU work.") with gr.Tab("🖼️ Canvas"): with gr.Row() as custom_canvas_controls: custom_width = gr.Number(label="Custom width", value=1024, minimum=256, maximum=8192, precision=0) custom_height = gr.Number(label="Custom height", value=1024, minimum=256, maximum=8192, precision=0) canvas_note = gr.Markdown("Qwen uses multiples of 32. Editing is capped at 1536 squared area; text to image at 2048 squared area.") target_megapixels = gr.Slider( label="Target Megapixels (canvas, 0 = match input area)", minimum=0.0, maximum=4.0 if IS_TURBO else 6.0, step=0.1, value=1.0, ) resolution_multiple = gr.Dropdown( label="Resolution lattice multiple (anti-drift)", choices=[32, 64, 128] if IS_TURBO else [32, 56, 112], value=32, interactive=True, ) vae_ref_megapixels = gr.Slider( label="Extra refs VAE megapixels override (0 = use canvas)", minimum=0.0, maximum=6.0, step=0.1, value=0.0, interactive=not IS_TURBO, ) extras_condition_only = gr.Checkbox( label="Extras conditioning-only (legacy)", value=not IS_TURBO, interactive=not IS_TURBO, ) pad_to_canvas = gr.Checkbox( label="Pad images to canvas aspect", value=not IS_TURBO, ) vae_tiling = gr.Checkbox(label="Decode tiling (experimental, lower VRAM)" if IS_TURBO else "VAE tiling (lower VRAM, slower)", value=False) with gr.Tab("🎚️ Output quality"): decoder_vae = gr.Dropdown( label="Decoder VAE", choices=["qwen"] if IS_TURBO else ["qwen", "wan2x"], value="qwen", interactive=not IS_TURBO, ) keep_decoder_2x = gr.Checkbox(label="Keep 2× output (legacy wan2x only)", value=False, interactive=not IS_TURBO) highlight_protection = gr.Checkbox( label="Highlight protection (reduce overexposure)", value=not IS_TURBO, ) highlight_protection_strength = gr.Slider( label="Highlight protection strength", minimum=0.0, maximum=1.0, step=0.05, value=0.35, ) with gr.Tab("🧭 Depth conditioning") as depth_controls: derived_type = gr.Dropdown( label="Derived Type (from Image 1)", choices=["None", "Depth (Depth Anything V2 Small)"], value="None", ) derived_use_gpu = gr.Checkbox(label="Use GPU for derived model", value=False) add_derived_btn = gr.Button("➕ Add derived ref to Extras (conditioning-only recommended)") with gr.Tab("💾 Profiles"): gr.Markdown( "Profiles keep the prompt, the style, the fast adapter, every slider, your lora " "references — everything typed rather than uploaded. " "Uploaded files and images are not stored." ) with gr.Row(): profile_picker = gr.Dropdown( label="Saved profiles", choices=[NO_PROFILE, *list_profiles()], value=NO_PROFILE, scale=3, ) profile_load = gr.Button("📂 load", variant="secondary", scale=1, elem_id="profile-load") profile_refresh = gr.Button("🔄", variant="secondary", scale=1, min_width=60, elem_id="profile-refresh") with gr.Row(): profile_name = gr.Textbox( label="Save as", placeholder="e.g. relight, my lora 0.8", max_lines=1, scale=3 ) profile_save = gr.Button("💾 save", variant="primary", scale=1, elem_id="profile-save") profile_delete = gr.Button("🗑️ delete the selected profile", variant="secondary", elem_id="profile-delete") profile_status = gr.Markdown("") with gr.Accordion("Take it with you (.json file)", open=False): settings_export_btn = gr.Button("⬇️ export the current settings to .json", size="sm") settings_download = gr.File(label="Your settings", visible=False, interactive=False) settings_upload = gr.File( label="📤 import a settings .json", file_types=[".json"], type="filepath" ) pro_controls.append(advanced_pro) with gr.Row(): estimate_btn = gr.Button("🔄", variant="secondary", scale=1, min_width=60, elem_id="estimate-btn") with gr.Row(elem_classes="route-row"): btn_out_to_img1 = gr.Button("⬅️ Output → Image 1", variant="secondary") btn_out_to_img2 = gr.Button("⬅️ Output → Image 2", variant="secondary") btn_out_to_extra = gr.Button("➕ Output → Extra Ref", variant="secondary") derived_preview = gr.Image( label="Derived Conditioning Preview", interactive=False, format="png", height=200, visible=False, ) with gr.Accordion("💡 Tips", open=False): gr.Markdown( "- The reservation is an estimate, not a guaranteed runtime or your charged quota; xlarge has a quota multiplier.\n" "- LoRA files are downloaded before GPU allocation.\n" "- Turbo uses six steps and CFG 1 by default. Legacy CFG > 1 uses two passes.\n" "- route the output back into Image 1 to keep iterating on the same edit.\n" "- save a set-up you like as a profile — it comes back from the dropdown next visit." ) # On LoRA selection: preset prompt + toggle Image 2 lora_adapter.change( fn=on_operation_style_change, inputs=[operation, lora_adapter, prompt, extras_condition_only], outputs=[prompt, input_image_2, extras_condition_only], ) fast_lora.change( fn=on_fast_lora_change, inputs=[fast_lora, steps], outputs=[steps, fast_lora_strength], ) # Stable input ordering also drives both the visible and allocated duration estimate. active_lora_inputs = [operation, face_mode, face_strength, outpaint_mode, detail_mode, detail_strength, lora_adapter, fast_lora, fast_lora_strength, user_lora_1_ref, user_lora_1_file, user_lora_1_scale, user_lora_2_ref, user_lora_2_file, user_lora_2_scale, user_lora_3_ref, user_lora_3_file, user_lora_3_scale, qwen_mode, camera_strength] active_lora_callback = operation_scoped(active_lora_summary) inference_inputs = [ input_image_1, input_image_2, input_images_extra, prompt, lora_adapter, seed, randomize_seed, guidance_scale, steps, target_megapixels, extras_condition_only, pad_to_canvas, vae_tiling, resolution_multiple, vae_ref_megapixels, decoder_vae, keep_decoder_2x, highlight_protection, highlight_protection_strength, fast_lora, fast_lora_strength, user_lora_1_file, user_lora_1_ref, user_lora_1_scale, user_lora_2_file, user_lora_2_ref, user_lora_2_scale, user_lora_3_file, user_lora_3_ref, user_lora_3_scale, negative_prompt_text, aspect_ratio, custom_width, custom_height, operation, face_mode, face_strength, outpaint_mode, outpaint_left, outpaint_right, outpaint_top, outpaint_bottom, outpaint_feather, detail_mode, detail_strength, qwen_mode, relight_preset, relight_direction, relight_color, relight_strength, camera_azimuth, camera_elevation, camera_closeup, camera_strength, ] # Initial page config and subsequent callbacks use the actual component values. estimate.value = gpu_estimate_text(*(component.value for component in inference_inputs)) run_button.click( fn=run_inference, inputs=inference_inputs, outputs=[output_image, seed, last_output], concurrency_id="qwen-model", concurrency_limit=1, api_name="generate", ).then(describe_output, [last_output, aspect_ratio, operation], output_dimensions, queue=False).then( comparison_view, [last_output, input_image_1, outpaint_canvas, operation, result_view], [result_view, output_image, compare_slider], queue=False, show_progress="hidden", api_name=False, ).then( gpu_estimate_text, inference_inputs, estimate, show_progress="hidden", api_name=False, ) result_view.change(switch_result_view, result_view, [output_image, compare_slider], queue=False, show_progress="hidden", api_name=False) # Auto-Describe shares the model with generation, so it shares its queue slot too. describe_button.click(auto_describe, [operation, input_image_1, input_image_2, prompt], [prompt, previous_prompt, describe_undo, describe_status], concurrency_id="qwen-model", concurrency_limit=1, api_name="describe_image") describe_undo.click(restore_described_prompt, previous_prompt, [prompt, describe_undo, describe_status], queue=False, api_name=False) operation.change(lambda value: gr.update(visible=value in DESCRIBE_OPERATIONS), operation, describe_group, queue=False, show_progress="hidden", api_name=False) # Output routing buttons btn_out_to_img1.click(fn=set_output_as_image1, inputs=[last_output], outputs=[input_image_1]) btn_out_to_img2.click(fn=set_output_as_image2, inputs=[last_output], outputs=[input_image_2]) btn_out_to_extra.click(fn=set_output_as_extra, inputs=[last_output, input_images_extra], outputs=[input_images_extra]) # Derived conditioning: append pose/depth map as extra ref (UI shows preview) add_derived_btn.click( fn=add_derived_ref, inputs=[input_image_1, input_images_extra, derived_type, derived_use_gpu], outputs=[input_images_extra, derived_preview], concurrency_id="qwen-model", concurrency_limit=1, ) # ------------------------------------------------------------------ # Profiles and the live cost readout # ------------------------------------------------------------------ _USER_REFS = [user_lora_1_ref, user_lora_2_ref, user_lora_3_ref] lora_identify_btn.click(identify_loras, _USER_REFS, lora_names) for _field in _USER_REFS: _field.submit(identify_loras, _USER_REFS, lora_names) search_btn.click(civitai_search, [search_query, search_base, search_nsfw], [search_results, search_pick, search_state]) search_query.submit(civitai_search, [search_query, search_base, search_nsfw], [search_results, search_pick, search_state]) search_put_btn.click(put_in_slot, [search_pick, search_state, search_slot], [user_lora_1_ref, user_lora_2_ref, user_lora_3_ref, search_results]) settings_fields = [ prompt, lora_adapter, fast_lora, fast_lora_strength, seed, randomize_seed, guidance_scale, steps, target_megapixels, resolution_multiple, vae_ref_megapixels, decoder_vae, keep_decoder_2x, highlight_protection, highlight_protection_strength, extras_condition_only, pad_to_canvas, vae_tiling, user_lora_1_ref, user_lora_1_scale, user_lora_2_ref, user_lora_2_scale, user_lora_3_ref, user_lora_3_scale, negative_prompt_text, aspect_ratio, custom_width, custom_height, pb_kind, pb_angle, pb_lighting, pb_look, pb_identity, pb_use_model, derived_type, derived_use_gpu, ui_mode, pb_idea, pb_writer, pb_suggest_loras, pb_use_images, operation, face_mode, face_strength, outpaint_mode, outpaint_left, outpaint_right, outpaint_top, outpaint_bottom, outpaint_feather, detail_mode, detail_strength, qwen_mode, relight_preset, relight_direction, relight_color, relight_strength, camera_azimuth, camera_elevation, camera_closeup, camera_strength, ] profile_save.click(save_profile, [profile_name, *settings_fields], [profile_picker, profile_status]) profile_aux = [assistant_state, pb_picks, pb_links, pb_status, user_lora_1_file, user_lora_2_file, user_lora_3_file] profile_load.click(load_profile_ui, [profile_picker, input_image_1, input_image_2, input_images_extra], [*settings_fields, profile_name, profile_status, *profile_aux]).then( active_lora_callback, active_lora_inputs, active_loras, queue=False, api_name=False) profile_delete.click(delete_profile, profile_picker, [profile_picker, profile_status]) profile_refresh.click(refresh_profiles, profile_picker, profile_picker) # Repopulate on every page open, so profiles saved elsewhere show up without a restart. demo.load(refresh_profiles, profile_picker, profile_picker) settings_export_btn.click(export_settings, settings_fields, settings_download) settings_upload.upload(import_settings_ui, [settings_upload, input_image_1, input_image_2, input_images_extra], [*settings_fields, *profile_aux]).then( active_lora_callback, active_lora_inputs, active_loras, queue=False, api_name=False) helper_slots = [user_lora_1_ref, user_lora_1_file, user_lora_1_scale, user_lora_2_ref, user_lora_2_file, user_lora_2_scale, user_lora_3_ref, user_lora_3_file, user_lora_3_scale] helper_outputs = [prompt, *helper_slots, lora_adapter, pb_picks, pb_links, assistant_state, pb_status] cpu_pick_button.click(operation_scoped(pick_prompt_loras_cpu), [operation, prompt, input_image_1, input_image_2, input_images_extra, assistant_state, *helper_slots, lora_adapter], helper_outputs, api_name="pick_loras_cpu", concurrency_id="prompt-helper", concurrency_limit=1).then( active_lora_callback, active_lora_inputs, active_loras, queue=False, api_name=False) pb_button.click(operation_scoped(prepare_prompt_setup), [operation, pb_idea, prompt, pb_writer, pb_suggest_loras, pb_use_images, input_image_1, input_image_2, input_images_extra, pb_kind, pb_angle, pb_lighting, pb_look, pb_identity, pb_use_model, writer_token, assistant_state, *helper_slots, lora_adapter, ui_mode], helper_outputs, concurrency_id="prompt-helper", concurrency_limit=1).then( active_lora_callback, active_lora_inputs, active_loras, queue=False, api_name=False) for reference_control in (input_image_1, input_image_2, input_images_extra): reference_control.change(operation_scoped(sync_prompt_reference_mode), [operation, input_image_1, input_image_2, input_images_extra, pb_idea, prompt, assistant_state, *helper_slots, lora_adapter], helper_outputs, concurrency_id="prompt-helper", concurrency_limit=1) # .input responds to user picks; programmatic Prepare/Refresh updates don't reapply them. pb_picks.input(operation_scoped(apply_prompt_lora_picks), [operation, pb_picks, prompt, assistant_state, *helper_slots, lora_adapter], helper_outputs, concurrency_id="prompt-helper", concurrency_limit=1, trigger_mode="always_last").then( active_lora_callback, active_lora_inputs, active_loras, queue=False, api_name=False) ui_mode_event = ui_mode.change(lambda mode: [gr.update(visible=mode == "Pro") for _ in pro_controls], ui_mode, pro_controls, queue=False) library_query.change(operation_scoped(lora_library_refresh), [operation, library_query, library_picker], [library_picker, library_status]) library_sync_button.click(operation_scoped(lora_library_sync), [operation, library_query, library_picker], [library_picker, library_status]).then( active_lora_callback, active_lora_inputs, active_loras, queue=False, api_name=False) library_picker.change(operation_scoped(lora_library_describe), [operation, library_picker], library_details) library_apply.click(operation_scoped(lora_library_apply), [operation, library_picker, library_slot, prompt], [*helper_slots, lora_adapter, prompt, library_status]).then( active_lora_callback, active_lora_inputs, active_loras, queue=False, api_name=False) library_save.click(operation_scoped(lora_library_add, write_token=True), [operation, library_write_token, library_name, library_source, library_model, library_trigger, library_strength, library_author, library_query], [library_picker, library_status]) library_delete.click(operation_scoped(lora_library_delete, write_token=True), [operation, library_write_token, library_picker, library_query], [library_picker, library_status]) library_import.upload(operation_scoped(lora_library_import, write_token=True), [operation, library_write_token, library_import, library_model, library_query], [library_picker, library_status]) library_export.click(operation_scoped(lora_library_export), operation, library_download) demo.load(operation_scoped(lora_library_sync), [operation, library_query, library_picker], [library_picker, library_status]).then( active_lora_callback, active_lora_inputs, active_loras, queue=False, api_name=False) active_lora_refresh_button.click(operation_scoped(refresh_active_loras), [operation, library_query, library_picker, pb_idea, prompt, assistant_state, ui_mode], [library_picker, library_status, pb_picks, pb_links, assistant_state, active_lora_status], concurrency_id="prompt-helper", concurrency_limit=1, api_name="refresh_loras").then( active_lora_callback, active_lora_inputs, active_loras, queue=False, api_name=False) for control in active_lora_inputs: control.change(active_lora_callback, active_lora_inputs, active_loras, queue=False, trigger_mode="always_last", show_progress="hidden", api_name=False) # Cache metadata can change without changing any chosen slot. library_status.change(active_lora_callback, active_lora_inputs, active_loras, queue=False, trigger_mode="always_last", show_progress="hidden", api_name=False) demo.load(active_lora_callback, active_lora_inputs, active_loras, queue=False, api_name="active_lora_summary") mode_visual_outputs = [input_image_1, input_image_2, face_controls, operation_note, steps, guidance_scale, negative_prompt_text, library_header, library_model, library_write_token, extra_references_group, fast_adapter_group, pad_to_canvas, vae_tiling, search_base, qwen_about, sampling_note, canvas_note, user_lora_help, btn_out_to_extra, outpaint_controls, aspect_ratio, custom_canvas_controls, btn_out_to_img2, depth_controls, highlight_protection, highlight_protection_strength, prompt, detail_controls, qwen_mode, face_mode, outpaint_mode, detail_mode, relight_controls, camera_controls, prompt_helper_group, cpu_pick_button, run_button, lora_suggestions_group, helper_settings_scope] ui_mode_event.then(operation_visuals, [operation, face_mode, outpaint_mode, detail_mode, qwen_mode], mode_visual_outputs, queue=False, api_name=False) demo.load(operation_visuals, [operation, face_mode, outpaint_mode, detail_mode, qwen_mode], mode_visual_outputs, queue=False, api_name=False) operation.change(operation_visuals, [operation, face_mode, outpaint_mode, detail_mode, qwen_mode], mode_visual_outputs, queue=False).then( operation_scoped(lora_library_sync), [operation, library_query, library_picker], [library_picker, library_status]).then( active_lora_callback, active_lora_inputs, active_loras, queue=False, api_name=False) operation.input(reset_operation, [operation, prompt, assistant_state, input_image_1, input_image_2, input_images_extra, negative_prompt_text], [steps, guidance_scale, target_megapixels, face_mode, lora_adapter, fast_lora, extras_condition_only, vae_ref_megapixels, decoder_vae, keep_decoder_2x, highlight_protection, pad_to_canvas, vae_tiling, prompt, *helper_slots, assistant_state, pb_picks, pb_links, pb_status, input_images_extra, outpaint_mode, outpaint_left, outpaint_right, outpaint_top, outpaint_bottom, outpaint_feather, detail_mode, detail_strength, qwen_mode, aspect_ratio, relight_preset, relight_direction, relight_color, relight_strength, camera_azimuth, camera_elevation, camera_closeup, camera_strength], concurrency_id="prompt-helper", concurrency_limit=1).then( operation_visuals, [operation, face_mode, outpaint_mode, detail_mode, qwen_mode], mode_visual_outputs, queue=False).then( active_lora_callback, active_lora_inputs, active_loras, queue=False, api_name=False) face_mode.input(reset_face_sampling, face_mode, steps, queue=False) face_prompt_button.click(restore_face_prompt, None, prompt, queue=False) outpaint_mode.input(reset_outpaint_sampling, outpaint_mode, steps, queue=False) outpaint_prompt_button.click(restore_outpaint_prompt, None, prompt, queue=False) detail_mode.input(reset_detail_sampling, detail_mode, steps, queue=False) qwen_mode.input(reset_qwen_sampling, qwen_mode, steps, queue=False) qwen_mode.change(qwen_sampling_notes, [operation, qwen_mode], [operation_note, sampling_note, guidance_scale, negative_prompt_text], queue=False) gr.on([face_mode.change, outpaint_mode.change, detail_mode.change], specialist_sampling_notes, [operation, face_mode, outpaint_mode, detail_mode], [operation_note, sampling_note, guidance_scale, negative_prompt_text], queue=False) detail_prompt_button.click(restore_detail_prompt, None, prompt, queue=False) detail_preset.input(apply_detail_preset, detail_preset, prompt, queue=False) relight_preset.input(apply_relight_preset, relight_preset, [relight_direction, relight_color], queue=False) relight_visual.input(fn=None, inputs=relight_visual, outputs=[relight_preset, relight_direction, relight_color], js="(value) => { const d = JSON.parse(value); return [d.preset, d.direction, d.color]; }", queue=False, show_progress="hidden", api_name=False) camera_visual.input(fn=None, inputs=camera_visual, outputs=[camera_azimuth, camera_elevation, camera_closeup], js="(value) => { const d = JSON.parse(value); return [d.azimuth, d.elevation, d.closeup]; }", queue=False, show_progress="hidden", api_name=False) # Hidden controls remain the source for generation/profiles. Programmatic # updates repaint the diagrams; only a user input event writes back. These # mappings are local so slow server echoes cannot overwrite later clicks. gr.on([relight_preset.change, relight_direction.change, relight_color.change], fn=None, inputs=[relight_preset, relight_direction, relight_color], outputs=relight_visual, js="(preset, direction, color) => JSON.stringify({preset, direction, color})", queue=False, show_progress="hidden", api_name=False, trigger_mode="always_last") gr.on([camera_azimuth.change, camera_elevation.change, camera_closeup.change], fn=None, inputs=[camera_azimuth, camera_elevation, camera_closeup], outputs=camera_visual, js="(azimuth, elevation, closeup) => JSON.stringify({azimuth, elevation, closeup})", queue=False, show_progress="hidden", api_name=False, trigger_mode="always_last") prompt.blur(ensure_operation_prompt, [operation, prompt], prompt, queue=False) negative_prompt_text.input(update_negative_guidance, [negative_prompt_text, guidance_scale], guidance_scale, queue=False, trigger_mode="always_last") # Resetting Turbo/Base must not send another full layout update with stale # operation inputs after the new operation has already hidden its controls. face_mode.change(sampling_label, [operation, face_mode, outpaint_mode, detail_mode, qwen_mode], steps, queue=False) outpaint_mode.change(sampling_label, [operation, face_mode, outpaint_mode, detail_mode, qwen_mode], steps, queue=False) detail_mode.change(sampling_label, [operation, face_mode, outpaint_mode, detail_mode, qwen_mode], steps, queue=False) qwen_mode.change(sampling_label, [operation, face_mode, outpaint_mode, detail_mode, qwen_mode], steps, queue=False) target_pixel.input(lambda value: gr.update(value=float(value)) if value is not None else gr.update(), target_pixel, target_megapixels, queue=False, show_progress="hidden", api_name=False) operation.change(target_pixel_clamp, [operation, target_megapixels], target_megapixels, queue=False, show_progress="hidden", api_name=False) gr.on([operation.change, target_megapixels.change, demo.load], target_pixel_update, [operation, target_megapixels], target_pixel, queue=False, show_progress="hidden", api_name=False, trigger_mode="always_last") preview_inputs = [operation, input_image_1, outpaint_left, outpaint_right, outpaint_top, outpaint_bottom, target_megapixels] for control in preview_inputs: # .change includes profile/reset values as well as user changes. The # CPU preview is cheap, and always_last avoids queuing every drag step. control.change(outpaint_preview, preview_inputs, [outpaint_canvas, outpaint_dimensions], queue=False, show_progress="hidden", api_name=False, trigger_mode="always_last") estimate_inputs = inference_inputs for control in estimate_inputs: # .change also sees values restored by profiles and sampler resets. control.change(gpu_estimate_text, estimate_inputs, estimate, trigger_mode="always_last", show_progress="hidden") # The button stays for a manual refresh. estimate_btn.click(gpu_estimate_text, estimate_inputs, estimate, show_progress="hidden") demo.load(gpu_estimate_text, estimate_inputs, estimate, show_progress="hidden") if __name__ == "__main__": demo.queue(max_size=30).launch( theme=orange_red_theme, css=css, js=DARK_THEME_JS, mcp_server=True, ssr_mode=False, show_error=True, )