diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..14a4b2e1469f170d325a0370ff9df6b3b8abeb6a 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +loras/hyper-realistic-portrait-before.jpg filter=lfs diff=lfs merge=lfs -text +loras/style-transfer-before.jpg filter=lfs diff=lfs merge=lfs -text +loras/ultra-realistic-portrait-before.jpg filter=lfs diff=lfs merge=lfs -text +loras/upscaler-before.jpg filter=lfs diff=lfs merge=lfs -text diff --git a/README.md b/README.md index 23be781a75920dd4b59893e4721c4dcbec235673..e660d7fb2d75071e73ebe476b02ac27b5165dc11 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,18 @@ --- -title: SeeMeeS Qwen Image Editor -emoji: πŸ–Ό -colorFrom: purple -colorTo: red +title: Qdpie-Qwen-Image-Editor-No-Packs +emoji: πŸŽƒ +colorFrom: blue +colorTo: blue sdk: gradio +sdk_version: 6.26.0 app_file: app.py -pinned: false +pinned: true +license: apache-2.0 +short_description: Modified Qwen Image Editor with LoRAs --- -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file +Copy of the August Qdpie editor with the prompt-pack menu and pack files removed. The original folder is unchanged. Upload this directory as its own Space. + +Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference + +Special thanks to [prithivMLmods / Qwen-Image-Edit-2511-LoRAs-Fast](https://huggingface.co/spaces/prithivMLmods/Qwen-Image-Edit-2511-LoRAs-Fast). diff --git a/app.py b/app.py index 652dc459175b17dc4acd2394b8b8ad1edd2394a5..a2965d29eb5f4a04facbf8a23a5956b412172a39 100644 --- a/app.py +++ b/app.py @@ -1,154 +1,725 @@ +import os +import gc import gradio as gr import numpy as np +import spaces +import torch import random +import base64 +import json +import html as html_lib +from io import BytesIO +from PIL import Image -# import spaces #[uncomment to use ZeroGPU] -from diffusers import DiffusionPipeline -import torch +MAX_SEED = np.iinfo(np.int32).max +LANCZOS = getattr(Image, "Resampling", Image).LANCZOS -device = "cuda" if torch.cuda.is_available() else "cpu" -model_repo_id = "stabilityai/sdxl-turbo" # Replace to the model you would like to use +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") +print("CUDA_VISIBLE_DEVICES=", os.environ.get("CUDA_VISIBLE_DEVICES")) +print("torch.__version__ =", torch.__version__) +print("torch.version.cuda =", torch.version.cuda) +print("cuda available:", torch.cuda.is_available()) +print("cuda device count:", torch.cuda.device_count()) if torch.cuda.is_available(): - torch_dtype = torch.float16 -else: - torch_dtype = torch.float32 + print("current device:", torch.cuda.current_device()) + print("device name:", torch.cuda.get_device_name(torch.cuda.current_device())) -pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype) -pipe = pipe.to(device) +print("Using device:", device) + +from diffusers import FlowMatchEulerDiscreteScheduler +from qwenimage.pipeline_qwenimage_edit_plus import QwenImageEditPlusPipeline +from qwenimage.transformer_qwenimage import QwenImageTransformer2DModel +from qwenimage.qwen_fa3_processor import QwenDoubleStreamAttnProcessorFA3 + +dtype = torch.bfloat16 + +# --------------------------------------------------------------------------- +# Model load strategy (keeps cold-start near the ~20GB Rapid path, not ~58GB): +# 1) Load Rapid-AIO-V19 transformer (~20GB FP8) β€” this is the diffusion brain. +# 2) Load Qwen-Image-Edit-2511 pipeline shell (text_encoder, VAE, processor…) +# while NEVER downloading the base BF16 transformer/* weights (~40GB). +# Passing transformer= alone is usually enough for diffusers to skip that +# component, but a factory rebuild / cache miss can still pull the whole +# Qwen/Qwen-Image-Edit-2511 repo (~57.7GB on the Hub). snapshot_download with +# ignore_patterns makes the skip explicit and log-friendly. +# --------------------------------------------------------------------------- +from huggingface_hub import snapshot_download + +print("=== [1/2] Loading Rapid transformer (prithivMLmods/Qwen-Image-Edit-Rapid-AIO-V19, ~20GB) ===") +_transformer = QwenImageTransformer2DModel.from_pretrained( + "prithivMLmods/Qwen-Image-Edit-Rapid-AIO-V19", + torch_dtype=dtype, + device_map="cuda" if torch.cuda.is_available() else None, +) + +print("=== [2/2] Loading Qwen-Image-Edit-2511 shell (skip base transformer/* weights) ===") +_base_dir = snapshot_download( + "Qwen/Qwen-Image-Edit-2511", + # Keep transformer/config.json if present for schema, but never the multi-GB weights. + ignore_patterns=[ + "transformer/*.safetensors", + "transformer/*.bin", + "transformer/*.pt", + "transformer/*.pth", + "transformer/*.index.json", + "transformer/**/*.safetensors", + "transformer/**/*.bin", + ], +) +import warnings +with warnings.catch_warnings(): + # Local qwenimage.transformer_qwenimage is API-compatible with the official + # diffusers class; type-check warning is noisy but harmless. + warnings.filterwarnings( + "ignore", + message=r".*Expected types for transformer.*", + ) + pipe = QwenImageEditPlusPipeline.from_pretrained( + _base_dir, + transformer=_transformer, + torch_dtype=dtype, + ).to(device) +print("=== Pipeline ready (Rapid transformer + base text_encoder/VAE) ===") + +try: + _attn_proc = QwenDoubleStreamAttnProcessorFA3() + pipe.transformer.set_attn_processor(_attn_proc) + _backend = getattr(_attn_proc, "_attention_backend", "unknown") + if _backend == "fa3": + print("Attention backend: Flash Attention 3") + else: + print(f"Attention backend: {_backend} (FA3 unavailable on this GPU β€” expected on Blackwell)") +except Exception as e: + print(f"Warning: Could not set attention processor: {e}") + +ADAPTER_SPECS = { + "Multiple-Angles": { + "repo": "dx8152/Qwen-Edit-2509-Multiple-angles", + "weights": "ι•œε€΄θ½¬ζ’.safetensors", + "adapter_name": "multiple-angles", + }, + "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", + }, + "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", + }, + "Manga-Tone": { + "repo": "nappa114514/Qwen-Image-Edit-2509-Manga-Tone", + "weights": "tone001.safetensors", + "adapter_name": "manga-tone", + }, + "Noir-Comic-Book": { + "repo": "prithivMLmods/Qwen-Image-Edit-2511-Noir-Comic-Book-Panel", + "weights": "Noir-Comic-Book-Panel_20.safetensors", + "adapter_name": "ncb", + }, + "Pixar-Inspired-3D": { + "repo": "prithivMLmods/Qwen-Image-Edit-2511-Pixar-Inspired-3D", + "weights": "PI3_20.safetensors", + "adapter_name": "pi3", + }, + "Polaroid-Photo": { + "repo": "prithivMLmods/Qwen-Image-Edit-2511-Polaroid-Photo", + "weights": "Qwen-Image-Edit-2511-Polaroid-Photo.safetensors", + "adapter_name": "polaroid-photo", + }, + "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", + }, + "Anything2Real": { + "repo": "lrzjason/Anything2Real_2601", + "weights": "anything2real_2601.safetensors", + "adapter_name": "anything2real", + }, + "Style-Transfer": { + "repo": "zooeyy/Style-Transfer", + "weights": "Style Transfer-Alpha-V0.1.safetensors", + "adapter_name": "style-transfer", + }, + "Upscaler": { + "repo": "starsfriday/Qwen-Image-Edit-2511-Upscale2K", + "weights": "qwen_image_edit_2511_upscale.safetensors", + "adapter_name": "upscale-2k", + }, + "Unblur-Anything": { + "repo": "prithivMLmods/Qwen-Image-Edit-2511-Unblur-Upscale", + "weights": "Qwen-Image-Edit-Unblur-Upscale_15.safetensors", + "adapter_name": "unblur-anything", + }, + "Light-Migration": { + "repo": "dx8152/Qwen-Edit-2509-Light-Migration", + "weights": "参考色调.safetensors", + "adapter_name": "light-migration", + }, + "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", + }, + "Cinematic-FlatLog": { + "repo": "prithivMLmods/QIE-2511-Cinematic-FlatLog-Control", + "weights": "QIE-2511-Cinematic-FlatLog-Control-3200.safetensors", + "adapter_name": "flat-log", + }, + "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", + }, +} + + +LOADED_ADAPTERS: set = set() +ADAPTER_NAMES = list(ADAPTER_SPECS.keys()) + +LORA_DISPLAY_ORDER = ["Multiple-Angles", "Fal-Multiple-Angles", "Photo-to-Anime", "Anime-V2", "Manga-Tone", "Noir-Comic-Book", "Pixar-Inspired-3D", "Polaroid-Photo", "Hyper-Realistic-Portrait", "Ultra-Realistic-Portrait", "Anything2Real", "Style-Transfer", "Upscaler", "Unblur-Anything", "Light-Migration", "Any-light", "Studio-DeLight", "Cinematic-FlatLog", "Midnight-Noir-Eyes-Spotlight"] +LORA_HELP = {"none": "A LoRA is a specialized skill pack for the editor (style, camera, lighting, upscale, etc.). Pick one that matches your goal, then write a prompt that asks for that kind of change. Use LoRA Prompts chips for starter text that matches each adapter. Prompt and LoRA work together β€” the menu only selects the skill pack.", "Multiple-Angles": "Camera / viewpoint LoRA. Best for rotating or shifting perspective (e.g. rotate 45 degrees right, top-down view). Use with Camera quick prompts.", "Fal-Multiple-Angles": "Another multi-angle camera LoRA (2511-oriented). Viewpoint changes driven by the prompt (e.g. front-right quarter view). Try if Multiple-Angles is weak.", "Photo-to-Anime": "Turns photos toward anime illustration. Pair with prompts like transform into anime.", "Anime-V2": "Alternate anime conversion LoRA with a different look than Photo-to-Anime.", "Manga-Tone": "Manga / comic tone rendering. Prompt e.g. paint with manga tone.", "Noir-Comic-Book": "Noir comic-book panel look. Prompt e.g. transform into a noir comic book style.", "Pixar-Inspired-3D": "Stylized 3D / Pixar-like rendering. Prompt e.g. transform into Pixar-inspired 3D.", "Polaroid-Photo": "Polaroid / instant photo aesthetic. Use polaroid snapshot language in the prompt.", "Hyper-Realistic-Portrait": "Hyper-real face / portrait detail. Best on faces.", "Ultra-Realistic-Portrait": "Realism portrait LoRA with a different look than Hyper-Realistic.", "Anything2Real": "Steers toward realistic photograph look. Prompt e.g. change to a realistic photograph.", "Style-Transfer": "Style from a reference image. Use 2 images: #1 content, #2 style.", "Upscaler": "Detail / resolution enhancement. Prompt e.g. upscale to 4K; larger output size helps.", "Unblur-Anything": "Sharpen / deblur soft images. Prompt e.g. unblur and upscale.", "Light-Migration": "Relight using a reference. Usually 2 images: subject + lighting reference.", "Any-light": "Lighting control. Often works with a lighting reference and a clear lighting prompt.", "Studio-DeLight": "Neutral / studio even lighting. Prompt e.g. neutral uniform lighting.", "Cinematic-FlatLog": "Cinematic flat / log color grade. Prompt e.g. cinematic flat log.", "Midnight-Noir-Eyes-Spotlight": "Dramatic noir spotlight look. Prompt for midnight noir eyes spotlight style."} + +# Starter prompts when a LoRA is selected (creator-aligned). Edit freely. +# Applied on menu change if the prompt box is empty or still holds the previous default. +LORA_DEFAULT_PROMPTS = { + "none": "", + "Multiple-Angles": "Rotate the camera 45 degrees to the right.", + "Fal-Multiple-Angles": "Front-right quarter view.", + "Photo-to-Anime": "Transform into anime.", + "Anime-V2": "Transform into anime (while preserving the background and remaining elements maintaining realism and original details.)", + "Manga-Tone": "Paint with manga tone.", + "Noir-Comic-Book": "Transform into a noir comic book style.", + "Pixar-Inspired-3D": "Transform it into Pixar-inspired 3D.", + "Polaroid-Photo": "cinematic polaroid with soft grain subtle vignette gentle lighting white frame handwritten photographed preserving realistic texture and details.", + "Hyper-Realistic-Portrait": "Transform into a hyper-realistic face portrait.", + "Ultra-Realistic-Portrait": "Ultra-realistic portrait.", + "Anything2Real": "Change the picture to realistic photograph.", + "Style-Transfer": "Convert Image 1 to the style of Image 2.", + "Upscaler": "Upscale this picture to 4K resolution.", + "Unblur-Anything": "Unblur and upscale.", + "Light-Migration": "Refer to the color tone, remove the original lighting from Image 1, and relight Image 1 based on the lighting and color tone of Image 2.", + "Any-light": "Apply the lighting from image 2 to image 1.", + "Studio-DeLight": "Neutral uniform lighting. Preserve identity and composition.", + "Cinematic-FlatLog": "Transform into a cinematic flat log.", + "Midnight-Noir-Eyes-Spotlight": "Transform into Midnight Noir Eyes Spotlight.", +} + +# Demo thumbs live on disk under loras/ (not embedded) so app.py stays small / HF-editable. +# Gradio serves them via allowed_paths + /gradio_api/file=... +import json as _json +from pathlib import Path + +_LORA_DIR = Path(__file__).resolve().parent / "loras" +_DEMO_EXTS = (".jpg", ".jpeg", ".png", ".webp") + + +def _gradio_file_url(path: Path) -> str: + """URL Gradio uses for files under allowed_paths (absolute path is most reliable).""" + return f"/gradio_api/file={path.resolve()}" + + +def _find_demo(slug: str, kind: str): + """kind is 'before' or 'after'. Returns Gradio file URL or None.""" + for ext in _DEMO_EXTS: + candidate = _LORA_DIR / f"{slug}-{kind}{ext}" + if candidate.is_file(): + return _gradio_file_url(candidate) + return None + + +def _build_demo_maps(): + before, after = {}, {} + for name in LORA_DISPLAY_ORDER: + slug = name.lower() + b = _find_demo(slug, "before") + a = _find_demo(slug, "after") + if b: + before[slug] = b + if a: + after[slug] = a + gen_b = _find_demo("generic", "before") or "" + gen_a = _find_demo("generic", "after") or "" + return before, after, gen_b, gen_a + + +LORA_DEMO_BEFORE, LORA_DEMO_AFTER, LORA_DEMO_GENERIC_BEFORE, LORA_DEMO_GENERIC_AFTER = _build_demo_maps() +LORA_HELP_JS = _json.dumps(LORA_HELP, ensure_ascii=False) +LORA_DEFAULT_PROMPTS_JS = _json.dumps(LORA_DEFAULT_PROMPTS, ensure_ascii=False) +LORA_DEMO_BEFORE_JS = _json.dumps(LORA_DEMO_BEFORE) +LORA_DEMO_AFTER_JS = _json.dumps(LORA_DEMO_AFTER) +LORA_DEMO_GENERIC_BEFORE_JS = _json.dumps(LORA_DEMO_GENERIC_BEFORE) +LORA_DEMO_GENERIC_AFTER_JS = _json.dumps(LORA_DEMO_GENERIC_AFTER) +print( + f"LoRA demos from disk: {len(LORA_DEMO_BEFORE)} before, {len(LORA_DEMO_AFTER)} after " + f"(dir={_LORA_DIR})" +) + + + + +EXAMPLES_CONFIG = [ + {"images": ["examples/B.jpg"], "prompt": "Transform into anime.", "lora": "Photo-to-Anime"}, + {"images": ["examples/HRP.jpg"], "prompt": "Transform into a hyper-realistic face portrait.", "lora": "Hyper-Realistic-Portrait"}, + {"images": ["examples/A.jpeg"], "prompt": "Rotate the camera 45 degrees to the right.", "lora": "Multiple-Angles"}, + {"images": ["examples/U.jpg"], "prompt": "Upscale this picture to 4K resolution.", "lora": "Upscaler"}, + {"images": ["examples/L1.jpg", "examples/L2.jpg"], "prompt": "Apply the lighting from image 2 to image 1.", "lora": "Any-light"}, + {"images": ["examples/PP1.jpg"], "prompt": "cinematic polaroid with soft grain subtle vignette gentle lighting white frame handwritten photographed preserving realistic texture and details.", "lora": "Polaroid-Photo"}, + {"images": ["examples/Z1.jpg"], "prompt": "Front-right quarter view.", "lora": "Fal-Multiple-Angles"}, + {"images": ["examples/URP.jpg"], "prompt": "Transform into a cinematic flat log.", "lora": "Cinematic-FlatLog"}, + {"images": ["examples/SL.jpg"], "prompt": "Neutral uniform lighting. Preserve identity and composition.", "lora": "Studio-DeLight"}, + {"images": ["examples/PI.jpg"], "prompt": "Transform it into Pixar-inspired 3D.", "lora": "Pixar-Inspired-3D"}, + {"images": ["examples/MT.jpg"], "prompt": "Paint with manga tone.", "lora": "Manga-Tone"}, + {"images": ["examples/NCB.jpg"], "prompt": "Transform into a noir comic book style.", "lora": "Noir-Comic-Book"}, + {"images": ["examples/URP.jpg"], "prompt": "Ultra-realistic portrait.", "lora": "Ultra-Realistic-Portrait"}, + {"images": ["examples/MN.jpg"], "prompt": "Transform into Midnight Noir Eyes Spotlight.", "lora": "Midnight-Noir-Eyes-Spotlight"}, + {"images": ["examples/ST1.jpg", "examples/ST2.jpg"], "prompt": "Convert Image 1 to the style of Image 2.", "lora": "Style-Transfer"}, + {"images": ["examples/R1.jpg"], "prompt": "Change the picture to realistic photograph.", "lora": "Anything2Real"}, + {"images": ["examples/UA.jpeg"], "prompt": "Unblur and upscale.", "lora": "Unblur-Anything"}, + {"images": ["examples/L1.jpg", "examples/L2.jpg"], "prompt": "Refer to the color tone, remove the original lighting from Image 1, and relight Image 1 based on the lighting and color tone of Image 2.", "lora": "Light-Migration"}, + {"images": ["examples/P1.jpg"], "prompt": "Transform into anime (while preserving the background and remaining elements maintaining realism and original details.)", "lora": "Anime-V2"}, +] + + +def make_thumb_b64(path, max_dim=220): + if not os.path.exists(path): + return "" + try: + img = Image.open(path).convert("RGB") + img.thumbnail((max_dim, max_dim), LANCZOS) + buf = BytesIO() + img.save(buf, format="JPEG", quality=65) + return f"data:image/jpeg;base64,{base64.b64encode(buf.getvalue()).decode()}" + except Exception as e: + print(f"Thumbnail error for {path}: {e}") + return "" + + +def encode_full_image(path): + if not os.path.exists(path): + return "" + try: + with open(path, "rb") as f: + data = f.read() + ext = path.rsplit(".", 1)[-1].lower() + mime = {"jpg": "image/jpeg", "jpeg": "image/jpeg", "png": "image/png", "webp": "image/webp"}.get(ext, "image/jpeg") + return f"data:{mime};base64,{base64.b64encode(data).decode()}" + except Exception as e: + print(f"Encode error for {path}: {e}") + return "" + + +def build_example_cards_html(): + cards = "" + for i, ex in enumerate(EXAMPLES_CONFIG): + thumbs_html = "" + for path in ex["images"]: + thumb = make_thumb_b64(path) + if thumb: + thumbs_html += f'' + else: + thumbs_html += '
Preview
' + n = len(ex["images"]) + img_badge = f'{n} image{"s" if n > 1 else ""}' + lora_badge = html_lib.escape(ex["lora"]) + prompt_short = html_lib.escape(ex["prompt"][:85]) + if len(ex["prompt"]) > 85: + prompt_short += "…" + cards += f'''
+
{thumbs_html}
+
+ {img_badge} + {lora_badge} +
+
{prompt_short}
+
''' + return cards + + +def load_example_data(idx_str): + try: + idx = int(float(idx_str)) if idx_str and idx_str.strip() else -1 + except (ValueError, TypeError): + idx = -1 + if idx < 0 or idx >= len(EXAMPLES_CONFIG): + return json.dumps({"images": [], "prompt": "", "lora": "", "names": [], "status": "error"}) + ex = EXAMPLES_CONFIG[idx] + b64_list, names = [], [] + for path in ex["images"]: + b64 = encode_full_image(path) + if b64: + b64_list.append(b64) + names.append(os.path.basename(path)) + return json.dumps({"images": b64_list, "prompt": ex["prompt"], "lora": ex["lora"], "names": names, "status": "ok"}) + + +print("Example gallery strip disabled (UI uses LoRA demos + chips instead).") +EXAMPLE_CARDS_HTML = "" + + +def b64_to_pil_list(b64_json_str): + if not b64_json_str or b64_json_str.strip() in ("", "[]"): + return [] + try: + b64_list = json.loads(b64_json_str) + except Exception: + return [] + pil_images = [] + for b64_str in b64_list: + if not b64_str or not isinstance(b64_str, str): + continue + try: + if b64_str.startswith("data:image"): + _, data = b64_str.split(",", 1) + else: + data = b64_str + image_data = base64.b64decode(data) + pil_images.append(Image.open(BytesIO(image_data)).convert("RGB")) + except Exception as e: + print(f"Error decoding image: {e}") + return pil_images + + +# Long-side base sizes (normal = 1024, the previous default). +# "original" uses source pixels (long side capped at MAX_SOURCE_SIDE). +IMAGE_SIZE_BASE = { + "x-small": 512, # thumbnail + "small": 768, + "normal": 1024, + "large": 1280, + "x-large": 1536, +} +MAX_SOURCE_SIDE = 4000 + + +def _round8(n: int) -> int: + return max(8, (int(n) // 8) * 8) -MAX_SEED = np.iinfo(np.int32).max -MAX_IMAGE_SIZE = 1024 +def _cap_source_dims(w: int, h: int): + """Scale source so the long side is at most MAX_SOURCE_SIDE.""" + long_side = max(w, h) + if long_side <= MAX_SOURCE_SIDE or long_side <= 0: + return w, h + scale = MAX_SOURCE_SIDE / float(long_side) + return max(1, int(round(w * scale))), max(1, int(round(h * scale))) -# @spaces.GPU #[uncomment to use ZeroGPU] + +def update_dimensions_on_upload(image, aspect="original", size="normal"): + """Compute generation width/height from source image, aspect preset, and size mode.""" + if image is None: + base = IMAGE_SIZE_BASE.get(size, 1024) if size != "original" else 1024 + return base, base + + w, h = image.size + + if size == "original": + # Exact source pixels (//8), long side capped at 4000. + # Non-original ratios: same long side, forced shape (F decision). + cw, ch = _cap_source_dims(w, h) + long_side = max(cw, ch) + if aspect == "square": + target_width = target_height = long_side + elif aspect == "wide": + target_width = long_side + target_height = int(long_side * 9 / 16) + elif aspect == "portrait": + target_height = long_side + target_width = int(long_side * 9 / 16) + else: + target_width, target_height = cw, ch + return _round8(target_width), _round8(target_height) + + base = IMAGE_SIZE_BASE.get(size, 1024) + # Scale fixed aspect presets from their normal (1024-class) dimensions. + scale = base / 1024.0 + + if aspect == "square": + target_width = target_height = base + elif aspect == "wide": + # 16:9 at normal β‰ˆ 1344Γ—768 + target_width = int(1344 * scale) + target_height = int(768 * scale) + elif aspect == "portrait": + # 9:16 at normal β‰ˆ 768Γ—1344 + target_width = int(768 * scale) + target_height = int(1344 * scale) + else: # "original" β€” maintain aspect ratio, long side = base + if w > h: + target_width = base + target_height = int(target_width * h / w) + else: + target_height = base + target_width = int(target_height * w / h) + + return _round8(target_width), _round8(target_height) + + +@spaces.GPU(size="xlarge") def infer( + images_b64_json, prompt, - negative_prompt, + lora_adapter, seed, randomize_seed, - width, - height, guidance_scale, - num_inference_steps, + steps, + aspect_ratio, + image_size, progress=gr.Progress(track_tqdm=True), ): + gc.collect() + torch.cuda.empty_cache() + + pil_images = b64_to_pil_list(images_b64_json) + if not pil_images: + raise gr.Error("Please upload at least one image to edit.") + if not prompt or prompt.strip() == "": + raise gr.Error("Please enter an edit prompt.") + + if not lora_adapter or lora_adapter == "none": + print("--- No LoRA selected; running base model ---") + try: + pipe.disable_lora() + except Exception: + try: + pipe.set_adapters([]) + except Exception as e: + print(f"Warning: could not clear adapters: {e}") + else: + spec = ADAPTER_SPECS.get(lora_adapter) + if not spec: + raise gr.Error(f"Configuration not found for: {lora_adapter}") + + adapter_name = spec["adapter_name"] + if adapter_name not in LOADED_ADAPTERS: + print(f"--- Downloading and Loading Adapter: {lora_adapter} ---") + try: + pipe.load_lora_weights(spec["repo"], weight_name=spec["weights"], adapter_name=adapter_name) + LOADED_ADAPTERS.add(adapter_name) + except Exception as e: + raise gr.Error(f"Failed to load adapter {lora_adapter}: {e}") + else: + print(f"--- Adapter {lora_adapter} already loaded. ---") + + pipe.set_adapters([adapter_name], adapter_weights=[1.0]) + if randomize_seed: seed = random.randint(0, MAX_SEED) - generator = torch.Generator().manual_seed(seed) + generator = torch.Generator(device=device).manual_seed(seed) + width, height = update_dimensions_on_upload(pil_images[0], aspect_ratio, image_size) - image = pipe( + # true_cfg_scale <= 1 disables classifier-free guidance; negative_prompt is then ignored + # and diffusers logs a warning. Only pass it when CFG is actually enabled (guidance > 1). + pipe_kwargs = dict( + image=pil_images, prompt=prompt, - negative_prompt=negative_prompt, - guidance_scale=guidance_scale, - num_inference_steps=num_inference_steps, - width=width, height=height, + width=width, + num_inference_steps=steps, generator=generator, - ).images[0] + true_cfg_scale=guidance_scale, + ) + if guidance_scale is not None and float(guidance_scale) > 1.0: + pipe_kwargs["negative_prompt"] = ( + "worst quality, low quality, bad anatomy, bad hands, text, error, missing fingers, " + "extra digit, fewer digits, cropped, jpeg artifacts, signature, watermark, username, blurry" + ) - return image, seed + try: + result_image = pipe(**pipe_kwargs).images[0] + return result_image, seed + except Exception as e: + raise e + finally: + gc.collect() + torch.cuda.empty_cache() -examples = [ - "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", - "An astronaut riding a green horse", - "A delicious ceviche cheesecake slice", -] +# ── UI assets (CSS / JS / HTML live under ui/ so app.py stays small) ────────── +_UI_DIR = Path(__file__).resolve().parent / "ui" -css = """ -#col-container { - margin: 0 auto; - max-width: 640px; -} -""" - -with gr.Blocks(css=css) as demo: - with gr.Column(elem_id="col-container"): - gr.Markdown(" # Text-to-Image Gradio Template") - - with gr.Row(): - prompt = gr.Text( - label="Prompt", - show_label=False, - max_lines=1, - placeholder="Enter your prompt", - container=False, - ) - - run_button = gr.Button("Run", scale=0, variant="primary") - - result = gr.Image(label="Result", show_label=False) - - with gr.Accordion("Advanced Settings", open=False): - negative_prompt = gr.Text( - label="Negative prompt", - max_lines=1, - placeholder="Enter a negative prompt", - visible=False, - ) - - seed = gr.Slider( - label="Seed", - minimum=0, - maximum=MAX_SEED, - step=1, - value=0, - ) - - randomize_seed = gr.Checkbox(label="Randomize seed", value=True) - - with gr.Row(): - width = gr.Slider( - label="Width", - minimum=256, - maximum=MAX_IMAGE_SIZE, - step=32, - value=1024, # Replace with defaults that work for your model - ) - - height = gr.Slider( - label="Height", - minimum=256, - maximum=MAX_IMAGE_SIZE, - step=32, - value=1024, # Replace with defaults that work for your model - ) - - with gr.Row(): - guidance_scale = gr.Slider( - label="Guidance scale", - minimum=0.0, - maximum=10.0, - step=0.1, - value=0.0, # Replace with defaults that work for your model - ) - - num_inference_steps = gr.Slider( - label="Number of inference steps", - minimum=1, - maximum=50, - step=1, - value=2, # Replace with defaults that work for your model - ) - - gr.Examples(examples=examples, inputs=[prompt]) - gr.on( - triggers=[run_button.click, prompt.submit], - fn=infer, - inputs=[ - prompt, - negative_prompt, - seed, - randomize_seed, - width, - height, - guidance_scale, - num_inference_steps, + +def _load_ui(name: str) -> str: + return (_UI_DIR / name).read_text(encoding="utf-8") + + +def _fill_ui(template: str, mapping: dict) -> str: + out = template + for key, val in mapping.items(): + out = out.replace(f"__{key}__", val) + return out + + +css = _load_ui("app.css") + "\n" + _load_ui("app_phone.css") +gallery_js = _load_ui("gallery.js") +wire_outputs_js = _load_ui("wire_outputs.js") +boot_js = _load_ui("boot.js") + + +# ── SVG assets (same family/style as the FireRed-Image-Edit app, recolored via CSS) ── +FIRE_LOGO_SVG = '' + +DOWNLOAD_SVG = '' + +UPLOAD_SVG = '' + +REMOVE_SVG = '' + +CLEAR_SVG = '' + +GITHUB_SVG = '' + +LORA_OPTIONS_HTML = "\n".join( + [''] + + [ + f'' + for name in LORA_DISPLAY_ORDER + ] +) + + +# ── Gradio app ───────────────────────────────────────────────────────────────── +with gr.Blocks() as demo: + + hidden_images_b64 = gr.Textbox(value="[]", elem_id="hidden-images-b64", elem_classes="hidden-input", container=False) + prompt = gr.Textbox(value="", elem_id="prompt-gradio-input", elem_classes="hidden-input", container=False) + lora_adapter = gr.Dropdown(choices=["none"] + list(LORA_DISPLAY_ORDER), value="none", elem_id="gradio-lora", elem_classes="hidden-input", container=False) + seed = gr.Slider(minimum=0, maximum=MAX_SEED, step=1, value=0, elem_id="gradio-seed", elem_classes="hidden-input", container=False) + randomize_seed = gr.Checkbox(value=True, elem_id="gradio-randomize", elem_classes="hidden-input", container=False) + guidance_scale = gr.Slider(minimum=1.0, maximum=10.0, step=0.1, value=1.0, elem_id="gradio-guidance", elem_classes="hidden-input", container=False) + steps = gr.Slider(minimum=1, maximum=50, step=1, value=4, elem_id="gradio-steps", elem_classes="hidden-input", container=False) + result = gr.Image(elem_id="gradio-result", elem_classes="hidden-input", container=False, format="png") + + example_idx = gr.Textbox(value="", elem_id="example-idx-input", elem_classes="hidden-input", container=False) + example_result = gr.Textbox(value="", elem_id="example-result-data", elem_classes="hidden-input", container=False) + example_load_btn = gr.Button("Load Example", elem_id="example-load-btn") + + aspect_ratio = gr.Dropdown( + choices=[ + ("Original (maintain aspect ratio)", "original"), + ("Square (1:1)", "square"), + ("Wide (16:9)", "wide"), + ("Portrait (9:16)", "portrait"), + ], + value="original", + elem_id="gradio-aspect", + elem_classes="hidden-input", + container=False, + ) + image_size = gr.Dropdown( + choices=[ + ("Original (source pixels)", "original"), + ("X-Small (thumbnail)", "x-small"), + ("Small", "small"), + ("Normal", "normal"), + ("Large", "large"), + ("X-Large", "x-large"), ], + value="normal", + elem_id="gradio-size", + elem_classes="hidden-input", + container=False, + ) + _shell_fill = { + "FIRE_LOGO_SVG": FIRE_LOGO_SVG, + "GITHUB_SVG": GITHUB_SVG, + "UPLOAD_SVG": UPLOAD_SVG, + "REMOVE_SVG": REMOVE_SVG, + "CLEAR_SVG": CLEAR_SVG, + "DOWNLOAD_SVG": DOWNLOAD_SVG, + "LORA_OPTIONS_HTML": LORA_OPTIONS_HTML, + } + shell_desktop_html = _fill_ui(_load_ui("shell.html"), _shell_fill) + shell_phone_html = _fill_ui(_load_ui("shell_phone.html"), _shell_fill) + # Both skins in DOM briefly; boot.js removes the unused one so element IDs stay unique. + # Phone stack: upload β†’ output β†’ prompts β†’ prompt β†’ menus β†’ LoRA β†’ advanced β†’ Edit β†’ footer + dual_shell_html = ( + '
' + f'
{shell_desktop_html}
' + f'' + "
" + ) + gr.HTML(dual_shell_html) + + # LoRA help + demo thumbs: Gradio 6 won't run scripts inside gr.HTML, so use demo.load. + lora_demo_js = _fill_ui( + _load_ui("lora_demo.js"), + { + "LORA_HELP_JS": LORA_HELP_JS, + "LORA_DEFAULT_PROMPTS_JS": LORA_DEFAULT_PROMPTS_JS, + "LORA_DEMO_BEFORE_JS": LORA_DEMO_BEFORE_JS, + "LORA_DEMO_AFTER_JS": LORA_DEMO_AFTER_JS, + "LORA_DEMO_GENERIC_BEFORE_JS": LORA_DEMO_GENERIC_BEFORE_JS, + "LORA_DEMO_GENERIC_AFTER_JS": LORA_DEMO_GENERIC_AFTER_JS, + }, + ) + + + run_btn = gr.Button("Run", elem_id="gradio-run-btn") + + # boot first: pick skin before gallery/lora_demo bind to IDs + demo.load(fn=None, js=boot_js) + demo.load(fn=None, js=lora_demo_js) + demo.load(fn=None, js=gallery_js) + demo.load(fn=None, js=wire_outputs_js) + + run_btn.click( + fn=infer, + inputs=[hidden_images_b64, prompt, lora_adapter, seed, randomize_seed, guidance_scale, steps, aspect_ratio, image_size], outputs=[result, seed], + js=r"""(imgs, p, la, s, rs, gs, st, ar, sz) => { + const images = window.__uploadedImages || []; + const b64Array = images.map(img => img.b64); + const imgsJson = JSON.stringify(b64Array); + const promptEl = document.getElementById('custom-prompt-input'); + const loraEl = document.getElementById('custom-lora-select'); + const aspectEl = document.getElementById('custom-aspect-select'); + const sizeEl = document.getElementById('custom-size-select'); + const promptVal = promptEl ? promptEl.value : p; + const loraVal = loraEl ? loraEl.value : la; + const aspectVal = aspectEl ? aspectEl.value : (ar || 'original'); + const sizeVal = sizeEl ? sizeEl.value : (sz || 'normal'); + return [imgsJson, promptVal, loraVal, s, rs, gs, st, aspectVal, sizeVal]; + }""", + ) + + example_load_btn.click( + fn=load_example_data, + inputs=[example_idx], + outputs=[example_result], + queue=False, ) if __name__ == "__main__": - demo.launch() + _app_root = Path(__file__).resolve().parent + demo.queue(max_size=50).launch( + css=css, + mcp_server=True, + ssr_mode=False, + show_error=True, + # Absolute paths so /gradio_api/file= demo thumbs work on Spaces + allowed_paths=[ + str(_app_root / "examples"), + str(_app_root / "loras"), + ], + ) \ No newline at end of file diff --git a/loras/README.md b/loras/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3a3942069dd1cec35dd1ba090047ec0174a5ee3f --- /dev/null +++ b/loras/README.md @@ -0,0 +1,20 @@ +# LoRA demo images + +All demo thumbs live in this folder only: `loras/` + +## Naming +- Before: `{slug}-before.jpg` (slug = LoRA name lowercased) +- After: `{slug}-after.jpg` (you create these in the Space) +- Fallback: `generic-before.svg`, `generic-after.svg` + +Examples: `photo-to-anime-before.jpg`, `multiple-angles-after.jpg` + +## Serve the prototype from the project root +```bash +# After changing ui/ or this folder, rebuild: +python3 scripts/build_example_index.py +python3 -m http.server 8765 +``` +Then open http://localhost:8765/example-index.html + +The prototype mirrors live `ui/` (Prompt Packs). It does not run the model. diff --git a/loras/anime-v2-after.jpg b/loras/anime-v2-after.jpg new file mode 100644 index 0000000000000000000000000000000000000000..88c58a57a324713e13468634baab1b6e480b48c1 Binary files /dev/null and b/loras/anime-v2-after.jpg differ diff --git a/loras/anime-v2-before.jpg b/loras/anime-v2-before.jpg new file mode 100644 index 0000000000000000000000000000000000000000..ab25825ed250e1fb5fe84759c85fe2ae74b4afb1 Binary files /dev/null and b/loras/anime-v2-before.jpg differ diff --git a/loras/any-light-after.jpg b/loras/any-light-after.jpg new file mode 100644 index 0000000000000000000000000000000000000000..cf6fccef266a3108687a6fbfa2da027e86ee3754 Binary files /dev/null and b/loras/any-light-after.jpg differ diff --git a/loras/any-light-before.jpg b/loras/any-light-before.jpg new file mode 100644 index 0000000000000000000000000000000000000000..9cf4b7b5ed7ea396a267083955a703969b7b1498 Binary files /dev/null and b/loras/any-light-before.jpg differ diff --git a/loras/anything2real-after.jpg b/loras/anything2real-after.jpg new file mode 100644 index 0000000000000000000000000000000000000000..39645f1760cfedd0333331385f978835600a5aeb Binary files /dev/null and b/loras/anything2real-after.jpg differ diff --git a/loras/anything2real-before.jpg b/loras/anything2real-before.jpg new file mode 100644 index 0000000000000000000000000000000000000000..30474ab7f7d4c9517c60564e734aa0825282237e Binary files /dev/null and b/loras/anything2real-before.jpg differ diff --git a/loras/cinematic-flatlog-after.jpg b/loras/cinematic-flatlog-after.jpg new file mode 100644 index 0000000000000000000000000000000000000000..fb74b06cb590d3143153c3e7a35e5d7dca1ba3b2 Binary files /dev/null and b/loras/cinematic-flatlog-after.jpg differ diff --git a/loras/cinematic-flatlog-before.jpg b/loras/cinematic-flatlog-before.jpg new file mode 100644 index 0000000000000000000000000000000000000000..edbcc336b7b897923cb7db5bb54d35745ae097b9 Binary files /dev/null and b/loras/cinematic-flatlog-before.jpg differ diff --git a/loras/fal-multiple-angles-after.jpg b/loras/fal-multiple-angles-after.jpg new file mode 100644 index 0000000000000000000000000000000000000000..9e06de5131a3a2558f75f6f58e29334a1ab47be9 Binary files /dev/null and b/loras/fal-multiple-angles-after.jpg differ diff --git a/loras/fal-multiple-angles-before.jpg b/loras/fal-multiple-angles-before.jpg new file mode 100644 index 0000000000000000000000000000000000000000..fabe537f7d4019f29c94fdaf6f4f2d68750f86ee Binary files /dev/null and b/loras/fal-multiple-angles-before.jpg differ diff --git a/loras/generic-after.jpg b/loras/generic-after.jpg new file mode 100644 index 0000000000000000000000000000000000000000..00a69e27d83c82540efe810a2cc9b4fb7979e999 Binary files /dev/null and b/loras/generic-after.jpg differ diff --git a/loras/generic-before.jpg b/loras/generic-before.jpg new file mode 100644 index 0000000000000000000000000000000000000000..81538eb37f3a10359c3a4ff15cec3e207583f2c7 Binary files /dev/null and b/loras/generic-before.jpg differ diff --git a/loras/hyper-realistic-portrait-after.jpg b/loras/hyper-realistic-portrait-after.jpg new file mode 100644 index 0000000000000000000000000000000000000000..32715460f5e92336fb84db4e3b53cfd7d814901b Binary files /dev/null and b/loras/hyper-realistic-portrait-after.jpg differ diff --git a/loras/hyper-realistic-portrait-before.jpg b/loras/hyper-realistic-portrait-before.jpg new file mode 100644 index 0000000000000000000000000000000000000000..a6ec7a3d92840689a01aa9764d1e0c4b39467af4 --- /dev/null +++ b/loras/hyper-realistic-portrait-before.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:49ab7c5188fdc2521ba4d391043df1063d42942342316acb4fc97b4968b85bf8 +size 106604 diff --git a/loras/light-migration-after.jpg b/loras/light-migration-after.jpg new file mode 100644 index 0000000000000000000000000000000000000000..266ab36da53f582f5dff09a07a17f24d6e9c2bb2 Binary files /dev/null and b/loras/light-migration-after.jpg differ diff --git a/loras/light-migration-before.jpg b/loras/light-migration-before.jpg new file mode 100644 index 0000000000000000000000000000000000000000..c2e8d75d4b35cd187e821cceb2d4e4acffcd9b4d Binary files /dev/null and b/loras/light-migration-before.jpg differ diff --git a/loras/manga-tone-after.jpg b/loras/manga-tone-after.jpg new file mode 100644 index 0000000000000000000000000000000000000000..1063db0611d95aed44ec3c5f0ab00d2b1b3163fc Binary files /dev/null and b/loras/manga-tone-after.jpg differ diff --git a/loras/manga-tone-before.jpg b/loras/manga-tone-before.jpg new file mode 100644 index 0000000000000000000000000000000000000000..87104c9d4d16426fb814d90051dc1c02ef7ba1fa Binary files /dev/null and b/loras/manga-tone-before.jpg differ diff --git a/loras/midnight-noir-eyes-spotlight-after.jpg b/loras/midnight-noir-eyes-spotlight-after.jpg new file mode 100644 index 0000000000000000000000000000000000000000..98b0570d60da502863b3e80525facbe8423e979a Binary files /dev/null and b/loras/midnight-noir-eyes-spotlight-after.jpg differ diff --git a/loras/midnight-noir-eyes-spotlight-before.jpg b/loras/midnight-noir-eyes-spotlight-before.jpg new file mode 100644 index 0000000000000000000000000000000000000000..f823614ec38b9734f721f6b66b05854f9978e5cb Binary files /dev/null and b/loras/midnight-noir-eyes-spotlight-before.jpg differ diff --git a/loras/multiple-angles-after.jpg b/loras/multiple-angles-after.jpg new file mode 100644 index 0000000000000000000000000000000000000000..dda1b09a9a61f24af6750390f4dbbfb327b0edeb Binary files /dev/null and b/loras/multiple-angles-after.jpg differ diff --git a/loras/multiple-angles-before.jpg b/loras/multiple-angles-before.jpg new file mode 100644 index 0000000000000000000000000000000000000000..87104c9d4d16426fb814d90051dc1c02ef7ba1fa Binary files /dev/null and b/loras/multiple-angles-before.jpg differ diff --git a/loras/noir-comic-book-after.jpg b/loras/noir-comic-book-after.jpg new file mode 100644 index 0000000000000000000000000000000000000000..fae0b8e56e4609fa181efddf790375e4f7cbec48 Binary files /dev/null and b/loras/noir-comic-book-after.jpg differ diff --git a/loras/noir-comic-book-before.jpg b/loras/noir-comic-book-before.jpg new file mode 100644 index 0000000000000000000000000000000000000000..fabe537f7d4019f29c94fdaf6f4f2d68750f86ee Binary files /dev/null and b/loras/noir-comic-book-before.jpg differ diff --git a/loras/photo-to-anime-after.jpg b/loras/photo-to-anime-after.jpg new file mode 100644 index 0000000000000000000000000000000000000000..83523da2a7585754a7e1828de25586b5607aec56 Binary files /dev/null and b/loras/photo-to-anime-after.jpg differ diff --git a/loras/photo-to-anime-before.jpg b/loras/photo-to-anime-before.jpg new file mode 100644 index 0000000000000000000000000000000000000000..bfcc3e678a46c4c5c3e004bf45769dc997237f92 Binary files /dev/null and b/loras/photo-to-anime-before.jpg differ diff --git a/loras/pixar-inspired-3d-after.jpg b/loras/pixar-inspired-3d-after.jpg new file mode 100644 index 0000000000000000000000000000000000000000..60349702d191888905307c08815b28d1d4d0d9fa Binary files /dev/null and b/loras/pixar-inspired-3d-after.jpg differ diff --git a/loras/pixar-inspired-3d-before.jpg b/loras/pixar-inspired-3d-before.jpg new file mode 100644 index 0000000000000000000000000000000000000000..9a45a97203ad7c9048082426f5bdf114c86cea92 Binary files /dev/null and b/loras/pixar-inspired-3d-before.jpg differ diff --git a/loras/polaroid-photo-after.jpg b/loras/polaroid-photo-after.jpg new file mode 100644 index 0000000000000000000000000000000000000000..81eff925494938acc66a93f45c4794a7165a492e Binary files /dev/null and b/loras/polaroid-photo-after.jpg differ diff --git a/loras/polaroid-photo-before.jpg b/loras/polaroid-photo-before.jpg new file mode 100644 index 0000000000000000000000000000000000000000..c372c6671aa4f21759a967ad40415393c063f1ba Binary files /dev/null and b/loras/polaroid-photo-before.jpg differ diff --git a/loras/studio-delight-after.jpg b/loras/studio-delight-after.jpg new file mode 100644 index 0000000000000000000000000000000000000000..862457e41e56f9725a06ba5dfcfbfcedb34a148f Binary files /dev/null and b/loras/studio-delight-after.jpg differ diff --git a/loras/studio-delight-before.jpg b/loras/studio-delight-before.jpg new file mode 100644 index 0000000000000000000000000000000000000000..1edc6f2e7ce089b6f9e3c3a2ef113ceb2a7cb5d7 Binary files /dev/null and b/loras/studio-delight-before.jpg differ diff --git a/loras/style-transfer-after.jpg b/loras/style-transfer-after.jpg new file mode 100644 index 0000000000000000000000000000000000000000..336b22cf2a87220e2e7938f5c9ae065944f9d0b3 Binary files /dev/null and b/loras/style-transfer-after.jpg differ diff --git a/loras/style-transfer-before.jpg b/loras/style-transfer-before.jpg new file mode 100644 index 0000000000000000000000000000000000000000..5cc0448e3cc7bef8d7ff9708fc5eb4eae8b8500c --- /dev/null +++ b/loras/style-transfer-before.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0119dfb23b5692ee7880aa71e5a70fb6f2b2ffe77018bbd88783aa32d72fcbd9 +size 112340 diff --git a/loras/ultra-realistic-portrait-after.jpg b/loras/ultra-realistic-portrait-after.jpg new file mode 100644 index 0000000000000000000000000000000000000000..c03e00ecf91b7cbea8097fa69458802139f58432 Binary files /dev/null and b/loras/ultra-realistic-portrait-after.jpg differ diff --git a/loras/ultra-realistic-portrait-before.jpg b/loras/ultra-realistic-portrait-before.jpg new file mode 100644 index 0000000000000000000000000000000000000000..a6ec7a3d92840689a01aa9764d1e0c4b39467af4 --- /dev/null +++ b/loras/ultra-realistic-portrait-before.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:49ab7c5188fdc2521ba4d391043df1063d42942342316acb4fc97b4968b85bf8 +size 106604 diff --git a/loras/unblur-anything-after.jpg b/loras/unblur-anything-after.jpg new file mode 100644 index 0000000000000000000000000000000000000000..9c7c02839a4afcbcad5f933be30aec915c6901b7 Binary files /dev/null and b/loras/unblur-anything-after.jpg differ diff --git a/loras/unblur-anything-before.jpg b/loras/unblur-anything-before.jpg new file mode 100644 index 0000000000000000000000000000000000000000..8c990e75de468ffdb5434c6e18240077334e80e3 Binary files /dev/null and b/loras/unblur-anything-before.jpg differ diff --git a/loras/upscaler-after.jpg b/loras/upscaler-after.jpg new file mode 100644 index 0000000000000000000000000000000000000000..7ac67828a9587c1601bde27581ee14333b7f2787 Binary files /dev/null and b/loras/upscaler-after.jpg differ diff --git a/loras/upscaler-before.jpg b/loras/upscaler-before.jpg new file mode 100644 index 0000000000000000000000000000000000000000..a6ec7a3d92840689a01aa9764d1e0c4b39467af4 --- /dev/null +++ b/loras/upscaler-before.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:49ab7c5188fdc2521ba4d391043df1063d42942342316acb4fc97b4968b85bf8 +size 106604 diff --git a/pre-requirements.txt b/pre-requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..0a7531aeb5f4984577d9f9a6f6ce87890025bf8c --- /dev/null +++ b/pre-requirements.txt @@ -0,0 +1 @@ +pip==26.1.2 \ No newline at end of file diff --git a/qwenimage/__init__.py b/qwenimage/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/qwenimage/pipeline_qwenimage_edit_plus.py b/qwenimage/pipeline_qwenimage_edit_plus.py new file mode 100644 index 0000000000000000000000000000000000000000..38320ae9c9b27da12d96a2e77059dc00a0ba43c5 --- /dev/null +++ b/qwenimage/pipeline_qwenimage_edit_plus.py @@ -0,0 +1,891 @@ +# Copyright 2025 Qwen-Image Team and The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import inspect +import math +from typing import Any, Callable, Dict, List, Optional, Union + +import numpy as np +import torch +from transformers import Qwen2_5_VLForConditionalGeneration, Qwen2Tokenizer, Qwen2VLProcessor + +from diffusers.image_processor import PipelineImageInput, VaeImageProcessor +from diffusers.loaders import QwenImageLoraLoaderMixin +from diffusers.models import AutoencoderKLQwenImage, QwenImageTransformer2DModel +from diffusers.schedulers import FlowMatchEulerDiscreteScheduler +from diffusers.utils import is_torch_xla_available, logging, replace_example_docstring +from diffusers.utils.torch_utils import randn_tensor +from diffusers.pipelines.pipeline_utils import DiffusionPipeline +from diffusers.pipelines.qwenimage.pipeline_output import QwenImagePipelineOutput + + +if is_torch_xla_available(): + import torch_xla.core.xla_model as xm + + XLA_AVAILABLE = True +else: + XLA_AVAILABLE = False + + +logger = logging.get_logger(__name__) # pylint: disable=invalid-name + +EXAMPLE_DOC_STRING = """ + Examples: + ```py + >>> import torch + >>> from PIL import Image + >>> from diffusers import QwenImageEditPlusPipeline + >>> from diffusers.utils import load_image + + >>> pipe = QwenImageEditPlusPipeline.from_pretrained("Qwen/Qwen-Image-Edit-2509", torch_dtype=torch.bfloat16) + >>> pipe.to("cuda") + >>> image = load_image( + ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/yarn-art-pikachu.png" + ... ).convert("RGB") + >>> prompt = ( + ... "Make Pikachu hold a sign that says 'Qwen Edit is awesome', yarn art style, detailed, vibrant colors" + ... ) + >>> # Depending on the variant being used, the pipeline call will slightly vary. + >>> # Refer to the pipeline documentation for more details. + >>> image = pipe(image, prompt, num_inference_steps=50).images[0] + >>> image.save("qwenimage_edit_plus.png") + ``` +""" + +CONDITION_IMAGE_SIZE = 384 * 384 +VAE_IMAGE_SIZE = 1024 * 1024 + + +# Copied from diffusers.pipelines.qwenimage.pipeline_qwenimage.calculate_shift +def calculate_shift( + image_seq_len, + base_seq_len: int = 256, + max_seq_len: int = 4096, + base_shift: float = 0.5, + max_shift: float = 1.15, +): + m = (max_shift - base_shift) / (max_seq_len - base_seq_len) + b = base_shift - m * base_seq_len + mu = image_seq_len * m + b + return mu + + +# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps +def retrieve_timesteps( + scheduler, + num_inference_steps: Optional[int] = None, + device: Optional[Union[str, torch.device]] = None, + timesteps: Optional[List[int]] = None, + sigmas: Optional[List[float]] = None, + **kwargs, +): + r""" + Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles + custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`. + + Args: + scheduler (`SchedulerMixin`): + The scheduler to get timesteps from. + num_inference_steps (`int`): + The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps` + must be `None`. + device (`str` or `torch.device`, *optional*): + The device to which the timesteps should be moved to. If `None`, the timesteps are not moved. + timesteps (`List[int]`, *optional*): + Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed, + `num_inference_steps` and `sigmas` must be `None`. + sigmas (`List[float]`, *optional*): + Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed, + `num_inference_steps` and `timesteps` must be `None`. + + Returns: + `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the + second element is the number of inference steps. + """ + if timesteps is not None and sigmas is not None: + raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values") + if timesteps is not None: + accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys()) + if not accepts_timesteps: + raise ValueError( + f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom" + f" timestep schedules. Please check whether you are using the correct scheduler." + ) + scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs) + timesteps = scheduler.timesteps + num_inference_steps = len(timesteps) + elif sigmas is not None: + accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys()) + if not accept_sigmas: + raise ValueError( + f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom" + f" sigmas schedules. Please check whether you are using the correct scheduler." + ) + scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs) + timesteps = scheduler.timesteps + num_inference_steps = len(timesteps) + else: + scheduler.set_timesteps(num_inference_steps, device=device, **kwargs) + timesteps = scheduler.timesteps + return timesteps, num_inference_steps + + +# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents +def retrieve_latents( + encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample" +): + if hasattr(encoder_output, "latent_dist") and sample_mode == "sample": + return encoder_output.latent_dist.sample(generator) + elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax": + return encoder_output.latent_dist.mode() + elif hasattr(encoder_output, "latents"): + return encoder_output.latents + else: + raise AttributeError("Could not access latents of provided encoder_output") + + +def calculate_dimensions(target_area, ratio): + width = math.sqrt(target_area * ratio) + height = width / ratio + + width = round(width / 32) * 32 + height = round(height / 32) * 32 + + return width, height + + +class QwenImageEditPlusPipeline(DiffusionPipeline, QwenImageLoraLoaderMixin): + r""" + The Qwen-Image-Edit pipeline for image editing. + + Args: + transformer ([`QwenImageTransformer2DModel`]): + Conditional Transformer (MMDiT) architecture to denoise the encoded image latents. + scheduler ([`FlowMatchEulerDiscreteScheduler`]): + A scheduler to be used in combination with `transformer` to denoise the encoded image latents. + vae ([`AutoencoderKL`]): + Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations. + text_encoder ([`Qwen2.5-VL-7B-Instruct`]): + [Qwen2.5-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct), specifically the + [Qwen2.5-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct) variant. + tokenizer (`QwenTokenizer`): + Tokenizer of class + [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer). + """ + + model_cpu_offload_seq = "text_encoder->transformer->vae" + _callback_tensor_inputs = ["latents", "prompt_embeds"] + + def __init__( + self, + scheduler: FlowMatchEulerDiscreteScheduler, + vae: AutoencoderKLQwenImage, + text_encoder: Qwen2_5_VLForConditionalGeneration, + tokenizer: Qwen2Tokenizer, + processor: Qwen2VLProcessor, + transformer: QwenImageTransformer2DModel, + ): + super().__init__() + + self.register_modules( + vae=vae, + text_encoder=text_encoder, + tokenizer=tokenizer, + processor=processor, + transformer=transformer, + scheduler=scheduler, + ) + self.vae_scale_factor = 2 ** len(self.vae.temperal_downsample) if getattr(self, "vae", None) else 8 + self.latent_channels = self.vae.config.z_dim if getattr(self, "vae", None) else 16 + # QwenImage latents are turned into 2x2 patches and packed. This means the latent width and height has to be divisible + # by the patch size. So the vae scale factor is multiplied by the patch size to account for this + self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor * 2) + self.tokenizer_max_length = 1024 + + self.prompt_template_encode = "<|im_start|>system\nDescribe the key features of the input image (color, shape, size, texture, objects, background), then explain how the user's text instruction should alter or modify the image. Generate a new image that meets the user's requirements while maintaining consistency with the original input where appropriate.<|im_end|>\n<|im_start|>user\n{}<|im_end|>\n<|im_start|>assistant\n" + self.prompt_template_encode_start_idx = 64 + self.default_sample_size = 128 + + # Copied from diffusers.pipelines.qwenimage.pipeline_qwenimage.QwenImagePipeline._extract_masked_hidden + def _extract_masked_hidden(self, hidden_states: torch.Tensor, mask: torch.Tensor): + bool_mask = mask.bool() + valid_lengths = bool_mask.sum(dim=1) + selected = hidden_states[bool_mask] + split_result = torch.split(selected, valid_lengths.tolist(), dim=0) + + return split_result + + def _get_qwen_prompt_embeds( + self, + prompt: Union[str, List[str]] = None, + image: Optional[torch.Tensor] = None, + device: Optional[torch.device] = None, + dtype: Optional[torch.dtype] = None, + ): + device = device or self._execution_device + dtype = dtype or self.text_encoder.dtype + + prompt = [prompt] if isinstance(prompt, str) else prompt + img_prompt_template = "Picture {}: <|vision_start|><|image_pad|><|vision_end|>" + if isinstance(image, list): + base_img_prompt = "" + for i, img in enumerate(image): + base_img_prompt += img_prompt_template.format(i + 1) + elif image is not None: + base_img_prompt = img_prompt_template.format(1) + else: + base_img_prompt = "" + + template = self.prompt_template_encode + + drop_idx = self.prompt_template_encode_start_idx + txt = [template.format(base_img_prompt + e) for e in prompt] + + model_inputs = self.processor( + text=txt, + images=image, + padding=True, + return_tensors="pt", + ).to(device) + + outputs = self.text_encoder( + input_ids=model_inputs.input_ids, + attention_mask=model_inputs.attention_mask, + pixel_values=model_inputs.pixel_values, + image_grid_thw=model_inputs.image_grid_thw, + output_hidden_states=True, + ) + + hidden_states = outputs.hidden_states[-1] + split_hidden_states = self._extract_masked_hidden(hidden_states, model_inputs.attention_mask) + split_hidden_states = [e[drop_idx:] for e in split_hidden_states] + attn_mask_list = [torch.ones(e.size(0), dtype=torch.long, device=e.device) for e in split_hidden_states] + max_seq_len = max([e.size(0) for e in split_hidden_states]) + prompt_embeds = torch.stack( + [torch.cat([u, u.new_zeros(max_seq_len - u.size(0), u.size(1))]) for u in split_hidden_states] + ) + encoder_attention_mask = torch.stack( + [torch.cat([u, u.new_zeros(max_seq_len - u.size(0))]) for u in attn_mask_list] + ) + + prompt_embeds = prompt_embeds.to(dtype=dtype, device=device) + + return prompt_embeds, encoder_attention_mask + + # Copied from diffusers.pipelines.qwenimage.pipeline_qwenimage_edit.QwenImageEditPipeline.encode_prompt + def encode_prompt( + self, + prompt: Union[str, List[str]], + image: Optional[torch.Tensor] = None, + device: Optional[torch.device] = None, + num_images_per_prompt: int = 1, + prompt_embeds: Optional[torch.Tensor] = None, + prompt_embeds_mask: Optional[torch.Tensor] = None, + max_sequence_length: int = 1024, + ): + r""" + + Args: + prompt (`str` or `List[str]`, *optional*): + prompt to be encoded + image (`torch.Tensor`, *optional*): + image to be encoded + device: (`torch.device`): + torch device + num_images_per_prompt (`int`): + number of images that should be generated per prompt + prompt_embeds (`torch.Tensor`, *optional*): + Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not + provided, text embeddings will be generated from `prompt` input argument. + """ + device = device or self._execution_device + + prompt = [prompt] if isinstance(prompt, str) else prompt + batch_size = len(prompt) if prompt_embeds is None else prompt_embeds.shape[0] + + if prompt_embeds is None: + prompt_embeds, prompt_embeds_mask = self._get_qwen_prompt_embeds(prompt, image, device) + + _, seq_len, _ = prompt_embeds.shape + prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1) + prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1) + prompt_embeds_mask = prompt_embeds_mask.repeat(1, num_images_per_prompt, 1) + prompt_embeds_mask = prompt_embeds_mask.view(batch_size * num_images_per_prompt, seq_len) + + return prompt_embeds, prompt_embeds_mask + + # Copied from diffusers.pipelines.qwenimage.pipeline_qwenimage_edit.QwenImageEditPipeline.check_inputs + def check_inputs( + self, + prompt, + height, + width, + negative_prompt=None, + prompt_embeds=None, + negative_prompt_embeds=None, + prompt_embeds_mask=None, + negative_prompt_embeds_mask=None, + callback_on_step_end_tensor_inputs=None, + max_sequence_length=None, + ): + if height % (self.vae_scale_factor * 2) != 0 or width % (self.vae_scale_factor * 2) != 0: + logger.warning( + f"`height` and `width` have to be divisible by {self.vae_scale_factor * 2} but are {height} and {width}. Dimensions will be resized accordingly" + ) + + if callback_on_step_end_tensor_inputs is not None and not all( + k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs + ): + raise ValueError( + f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}" + ) + + if prompt is not None and prompt_embeds is not None: + raise ValueError( + f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to" + " only forward one of the two." + ) + elif prompt is None and prompt_embeds is None: + raise ValueError( + "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined." + ) + elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)): + raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}") + + if negative_prompt is not None and negative_prompt_embeds is not None: + raise ValueError( + f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:" + f" {negative_prompt_embeds}. Please make sure to only forward one of the two." + ) + + if prompt_embeds is not None and prompt_embeds_mask is None: + raise ValueError( + "If `prompt_embeds` are provided, `prompt_embeds_mask` also have to be passed. Make sure to generate `prompt_embeds_mask` from the same text encoder that was used to generate `prompt_embeds`." + ) + if negative_prompt_embeds is not None and negative_prompt_embeds_mask is None: + raise ValueError( + "If `negative_prompt_embeds` are provided, `negative_prompt_embeds_mask` also have to be passed. Make sure to generate `negative_prompt_embeds_mask` from the same text encoder that was used to generate `negative_prompt_embeds`." + ) + + if max_sequence_length is not None and max_sequence_length > 1024: + raise ValueError(f"`max_sequence_length` cannot be greater than 1024 but is {max_sequence_length}") + + @staticmethod + # Copied from diffusers.pipelines.qwenimage.pipeline_qwenimage.QwenImagePipeline._pack_latents + def _pack_latents(latents, batch_size, num_channels_latents, height, width): + latents = latents.view(batch_size, num_channels_latents, height // 2, 2, width // 2, 2) + latents = latents.permute(0, 2, 4, 1, 3, 5) + latents = latents.reshape(batch_size, (height // 2) * (width // 2), num_channels_latents * 4) + + return latents + + @staticmethod + # Copied from diffusers.pipelines.qwenimage.pipeline_qwenimage.QwenImagePipeline._unpack_latents + def _unpack_latents(latents, height, width, vae_scale_factor): + batch_size, num_patches, channels = latents.shape + + # VAE applies 8x compression on images but we must also account for packing which requires + # latent height and width to be divisible by 2. + height = 2 * (int(height) // (vae_scale_factor * 2)) + width = 2 * (int(width) // (vae_scale_factor * 2)) + + latents = latents.view(batch_size, height // 2, width // 2, channels // 4, 2, 2) + latents = latents.permute(0, 3, 1, 4, 2, 5) + + latents = latents.reshape(batch_size, channels // (2 * 2), 1, height, width) + + return latents + + # Copied from diffusers.pipelines.qwenimage.pipeline_qwenimage_edit.QwenImageEditPipeline._encode_vae_image + def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator): + if isinstance(generator, list): + image_latents = [ + retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i], sample_mode="argmax") + for i in range(image.shape[0]) + ] + image_latents = torch.cat(image_latents, dim=0) + else: + image_latents = retrieve_latents(self.vae.encode(image), generator=generator, sample_mode="argmax") + latents_mean = ( + torch.tensor(self.vae.config.latents_mean) + .view(1, self.latent_channels, 1, 1, 1) + .to(image_latents.device, image_latents.dtype) + ) + latents_std = ( + torch.tensor(self.vae.config.latents_std) + .view(1, self.latent_channels, 1, 1, 1) + .to(image_latents.device, image_latents.dtype) + ) + image_latents = (image_latents - latents_mean) / latents_std + + return image_latents + + def prepare_latents( + self, + images, + batch_size, + num_channels_latents, + height, + width, + dtype, + device, + generator, + latents=None, + ): + # VAE applies 8x compression on images but we must also account for packing which requires + # latent height and width to be divisible by 2. + height = 2 * (int(height) // (self.vae_scale_factor * 2)) + width = 2 * (int(width) // (self.vae_scale_factor * 2)) + + shape = (batch_size, 1, num_channels_latents, height, width) + + image_latents = None + if images is not None: + if not isinstance(images, list): + images = [images] + all_image_latents = [] + for image in images: + image = image.to(device=device, dtype=dtype) + if image.shape[1] != self.latent_channels: + image_latents = self._encode_vae_image(image=image, generator=generator) + else: + image_latents = image + if batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] == 0: + # expand init_latents for batch_size + additional_image_per_prompt = batch_size // image_latents.shape[0] + image_latents = torch.cat([image_latents] * additional_image_per_prompt, dim=0) + elif batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] != 0: + raise ValueError( + f"Cannot duplicate `image` of batch size {image_latents.shape[0]} to {batch_size} text prompts." + ) + else: + image_latents = torch.cat([image_latents], dim=0) + + image_latent_height, image_latent_width = image_latents.shape[3:] + image_latents = self._pack_latents( + image_latents, batch_size, num_channels_latents, image_latent_height, image_latent_width + ) + all_image_latents.append(image_latents) + image_latents = torch.cat(all_image_latents, dim=1) + + if isinstance(generator, list) and len(generator) != batch_size: + raise ValueError( + f"You have passed a list of generators of length {len(generator)}, but requested an effective batch" + f" size of {batch_size}. Make sure the batch size matches the length of the generators." + ) + if latents is None: + latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype) + latents = self._pack_latents(latents, batch_size, num_channels_latents, height, width) + else: + latents = latents.to(device=device, dtype=dtype) + + return latents, image_latents + + @property + def guidance_scale(self): + return self._guidance_scale + + @property + def attention_kwargs(self): + return self._attention_kwargs + + @property + def num_timesteps(self): + return self._num_timesteps + + @property + def current_timestep(self): + return self._current_timestep + + @property + def interrupt(self): + return self._interrupt + + @torch.no_grad() + @replace_example_docstring(EXAMPLE_DOC_STRING) + def __call__( + self, + image: Optional[PipelineImageInput] = None, + prompt: Union[str, List[str]] = None, + negative_prompt: Union[str, List[str]] = None, + true_cfg_scale: float = 4.0, + height: Optional[int] = None, + width: Optional[int] = None, + num_inference_steps: int = 50, + sigmas: Optional[List[float]] = None, + guidance_scale: Optional[float] = None, + num_images_per_prompt: int = 1, + generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, + latents: Optional[torch.Tensor] = None, + prompt_embeds: Optional[torch.Tensor] = None, + prompt_embeds_mask: Optional[torch.Tensor] = None, + negative_prompt_embeds: Optional[torch.Tensor] = None, + negative_prompt_embeds_mask: Optional[torch.Tensor] = None, + output_type: Optional[str] = "pil", + return_dict: bool = True, + attention_kwargs: Optional[Dict[str, Any]] = None, + callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None, + callback_on_step_end_tensor_inputs: List[str] = ["latents"], + max_sequence_length: int = 512, + ): + r""" + Function invoked when calling the pipeline for generation. + + Args: + image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`): + `Image`, numpy array or tensor representing an image batch to be used as the starting point. For both + numpy array and pytorch tensor, the expected value range is between `[0, 1]` If it's a tensor or a list + or tensors, the expected shape should be `(B, C, H, W)` or `(C, H, W)`. If it is a numpy array or a + list of arrays, the expected shape should be `(B, H, W, C)` or `(H, W, C)` It can also accept image + latents as `image`, but if passing latents directly it is not encoded again. + prompt (`str` or `List[str]`, *optional*): + The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`. + instead. + negative_prompt (`str` or `List[str]`, *optional*): + The prompt or prompts not to guide the image generation. If not defined, one has to pass + `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `true_cfg_scale` is + not greater than `1`). + true_cfg_scale (`float`, *optional*, defaults to 1.0): + true_cfg_scale (`float`, *optional*, defaults to 1.0): Guidance scale as defined in [Classifier-Free + Diffusion Guidance](https://huggingface.co/papers/2207.12598). `true_cfg_scale` is defined as `w` of + equation 2. of [Imagen Paper](https://huggingface.co/papers/2205.11487). Classifier-free guidance is + enabled by setting `true_cfg_scale > 1` and a provided `negative_prompt`. Higher guidance scale + encourages to generate images that are closely linked to the text `prompt`, usually at the expense of + lower image quality. + height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor): + The height in pixels of the generated image. This is set to 1024 by default for the best results. + width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor): + The width in pixels of the generated image. This is set to 1024 by default for the best results. + num_inference_steps (`int`, *optional*, defaults to 50): + The number of denoising steps. More denoising steps usually lead to a higher quality image at the + expense of slower inference. + sigmas (`List[float]`, *optional*): + Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in + their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed + will be used. + guidance_scale (`float`, *optional*, defaults to None): + A guidance scale value for guidance distilled models. Unlike the traditional classifier-free guidance + where the guidance scale is applied during inference through noise prediction rescaling, guidance + distilled models take the guidance scale directly as an input parameter during forward pass. Guidance + scale is enabled by setting `guidance_scale > 1`. Higher guidance scale encourages to generate images + that are closely linked to the text `prompt`, usually at the expense of lower image quality. This + parameter in the pipeline is there to support future guidance-distilled models when they come up. It is + ignored when not using guidance distilled models. To enable traditional classifier-free guidance, + please pass `true_cfg_scale > 1.0` and `negative_prompt` (even an empty negative prompt like " " should + enable classifier-free guidance computations). + num_images_per_prompt (`int`, *optional*, defaults to 1): + The number of images to generate per prompt. + generator (`torch.Generator` or `List[torch.Generator]`, *optional*): + One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html) + to make generation deterministic. + latents (`torch.Tensor`, *optional*): + Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image + generation. Can be used to tweak the same generation with different prompts. If not provided, a latents + tensor will be generated by sampling using the supplied random `generator`. + prompt_embeds (`torch.Tensor`, *optional*): + Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not + provided, text embeddings will be generated from `prompt` input argument. + negative_prompt_embeds (`torch.Tensor`, *optional*): + Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt + weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input + argument. + output_type (`str`, *optional*, defaults to `"pil"`): + The output format of the generate image. Choose between + [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`. + return_dict (`bool`, *optional*, defaults to `True`): + Whether or not to return a [`~pipelines.qwenimage.QwenImagePipelineOutput`] instead of a plain tuple. + attention_kwargs (`dict`, *optional*): + A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under + `self.processor` in + [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). + callback_on_step_end (`Callable`, *optional*): + A function that calls at the end of each denoising steps during the inference. The function is called + with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, + callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by + `callback_on_step_end_tensor_inputs`. + callback_on_step_end_tensor_inputs (`List`, *optional*): + The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list + will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the + `._callback_tensor_inputs` attribute of your pipeline class. + max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`. + + Examples: + + Returns: + [`~pipelines.qwenimage.QwenImagePipelineOutput`] or `tuple`: + [`~pipelines.qwenimage.QwenImagePipelineOutput`] if `return_dict` is True, otherwise a `tuple`. When + returning a tuple, the first element is a list with the generated images. + """ + image_size = image[-1].size if isinstance(image, list) else image.size + calculated_width, calculated_height = calculate_dimensions(1024 * 1024, image_size[0] / image_size[1]) + height = height or calculated_height + width = width or calculated_width + + multiple_of = self.vae_scale_factor * 2 + width = width // multiple_of * multiple_of + height = height // multiple_of * multiple_of + + # 1. Check inputs. Raise error if not correct + self.check_inputs( + prompt, + height, + width, + negative_prompt=negative_prompt, + prompt_embeds=prompt_embeds, + negative_prompt_embeds=negative_prompt_embeds, + prompt_embeds_mask=prompt_embeds_mask, + negative_prompt_embeds_mask=negative_prompt_embeds_mask, + callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs, + max_sequence_length=max_sequence_length, + ) + + self._guidance_scale = guidance_scale + self._attention_kwargs = attention_kwargs + self._current_timestep = None + self._interrupt = False + + # 2. Define call parameters + if prompt is not None and isinstance(prompt, str): + batch_size = 1 + elif prompt is not None and isinstance(prompt, list): + batch_size = len(prompt) + else: + batch_size = prompt_embeds.shape[0] + + device = self._execution_device + # 3. Preprocess image + if image is not None and not (isinstance(image, torch.Tensor) and image.size(1) == self.latent_channels): + if not isinstance(image, list): + image = [image] + condition_image_sizes = [] + condition_images = [] + vae_image_sizes = [] + vae_images = [] + for img in image: + image_width, image_height = img.size + condition_width, condition_height = calculate_dimensions( + CONDITION_IMAGE_SIZE, image_width / image_height + ) + vae_width, vae_height = calculate_dimensions(VAE_IMAGE_SIZE, image_width / image_height) + condition_image_sizes.append((condition_width, condition_height)) + vae_image_sizes.append((vae_width, vae_height)) + condition_images.append(self.image_processor.resize(img, condition_height, condition_width)) + vae_images.append(self.image_processor.preprocess(img, vae_height, vae_width).unsqueeze(2)) + + has_neg_prompt = negative_prompt is not None or ( + negative_prompt_embeds is not None and negative_prompt_embeds_mask is not None + ) + + if true_cfg_scale > 1 and not has_neg_prompt: + logger.warning( + f"true_cfg_scale is passed as {true_cfg_scale}, but classifier-free guidance is not enabled since no negative_prompt is provided." + ) + elif true_cfg_scale <= 1 and has_neg_prompt: + logger.warning( + " negative_prompt is passed but classifier-free guidance is not enabled since true_cfg_scale <= 1" + ) + + do_true_cfg = true_cfg_scale > 1 and has_neg_prompt + prompt_embeds, prompt_embeds_mask = self.encode_prompt( + image=condition_images, + prompt=prompt, + prompt_embeds=prompt_embeds, + prompt_embeds_mask=prompt_embeds_mask, + device=device, + num_images_per_prompt=num_images_per_prompt, + max_sequence_length=max_sequence_length, + ) + if do_true_cfg: + negative_prompt_embeds, negative_prompt_embeds_mask = self.encode_prompt( + image=condition_images, + prompt=negative_prompt, + prompt_embeds=negative_prompt_embeds, + prompt_embeds_mask=negative_prompt_embeds_mask, + device=device, + num_images_per_prompt=num_images_per_prompt, + max_sequence_length=max_sequence_length, + ) + + # 4. Prepare latent variables + num_channels_latents = self.transformer.config.in_channels // 4 + latents, image_latents = self.prepare_latents( + vae_images, + batch_size * num_images_per_prompt, + num_channels_latents, + height, + width, + prompt_embeds.dtype, + device, + generator, + latents, + ) + img_shapes = [ + [ + (1, height // self.vae_scale_factor // 2, width // self.vae_scale_factor // 2), + *[ + (1, vae_height // self.vae_scale_factor // 2, vae_width // self.vae_scale_factor // 2) + for vae_width, vae_height in vae_image_sizes + ], + ] + ] * batch_size + + # 5. Prepare timesteps + sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) if sigmas is None else sigmas + image_seq_len = latents.shape[1] + mu = calculate_shift( + image_seq_len, + self.scheduler.config.get("base_image_seq_len", 256), + self.scheduler.config.get("max_image_seq_len", 4096), + self.scheduler.config.get("base_shift", 0.5), + self.scheduler.config.get("max_shift", 1.15), + ) + timesteps, num_inference_steps = retrieve_timesteps( + self.scheduler, + num_inference_steps, + device, + sigmas=sigmas, + mu=mu, + ) + num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0) + self._num_timesteps = len(timesteps) + + # handle guidance + if self.transformer.config.guidance_embeds and guidance_scale is None: + raise ValueError("guidance_scale is required for guidance-distilled model.") + elif self.transformer.config.guidance_embeds: + guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32) + guidance = guidance.expand(latents.shape[0]) + elif not self.transformer.config.guidance_embeds and guidance_scale is not None: + logger.warning( + f"guidance_scale is passed as {guidance_scale}, but ignored since the model is not guidance-distilled." + ) + guidance = None + elif not self.transformer.config.guidance_embeds and guidance_scale is None: + guidance = None + + if self.attention_kwargs is None: + self._attention_kwargs = {} + + txt_seq_lens = prompt_embeds_mask.sum(dim=1).tolist() if prompt_embeds_mask is not None else None + + image_rotary_emb = self.transformer.pos_embed(img_shapes, txt_seq_lens, device=latents.device) + if do_true_cfg: + negative_txt_seq_lens = ( + negative_prompt_embeds_mask.sum(dim=1).tolist() + if negative_prompt_embeds_mask is not None + else None + ) + uncond_image_rotary_emb = self.transformer.pos_embed( + img_shapes, negative_txt_seq_lens, device=latents.device + ) + else: + uncond_image_rotary_emb = None + + # 6. Denoising loop + self.scheduler.set_begin_index(0) + with self.progress_bar(total=num_inference_steps) as progress_bar: + for i, t in enumerate(timesteps): + if self.interrupt: + continue + + self._current_timestep = t + + latent_model_input = latents + if image_latents is not None: + latent_model_input = torch.cat([latents, image_latents], dim=1) + + # broadcast to batch dimension in a way that's compatible with ONNX/Core ML + timestep = t.expand(latents.shape[0]).to(latents.dtype) + with self.transformer.cache_context("cond"): + noise_pred = self.transformer( + hidden_states=latent_model_input, + timestep=timestep / 1000, + guidance=guidance, + encoder_hidden_states_mask=prompt_embeds_mask, + encoder_hidden_states=prompt_embeds, + image_rotary_emb=image_rotary_emb, + attention_kwargs=self.attention_kwargs, + return_dict=False, + )[0] + noise_pred = noise_pred[:, : latents.size(1)] + + if do_true_cfg: + with self.transformer.cache_context("uncond"): + neg_noise_pred = self.transformer( + hidden_states=latent_model_input, + timestep=timestep / 1000, + guidance=guidance, + encoder_hidden_states_mask=negative_prompt_embeds_mask, + encoder_hidden_states=negative_prompt_embeds, + image_rotary_emb=uncond_image_rotary_emb, + attention_kwargs=self.attention_kwargs, + return_dict=False, + )[0] + neg_noise_pred = neg_noise_pred[:, : latents.size(1)] + comb_pred = neg_noise_pred + true_cfg_scale * (noise_pred - neg_noise_pred) + + cond_norm = torch.norm(noise_pred, dim=-1, keepdim=True) + noise_norm = torch.norm(comb_pred, dim=-1, keepdim=True) + noise_pred = comb_pred * (cond_norm / noise_norm) + + # compute the previous noisy sample x_t -> x_t-1 + latents_dtype = latents.dtype + latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0] + + if latents.dtype != latents_dtype: + if torch.backends.mps.is_available(): + # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272 + latents = latents.to(latents_dtype) + + if callback_on_step_end is not None: + callback_kwargs = {} + for k in callback_on_step_end_tensor_inputs: + callback_kwargs[k] = locals()[k] + callback_outputs = callback_on_step_end(self, i, t, callback_kwargs) + + latents = callback_outputs.pop("latents", latents) + prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds) + + # call the callback, if provided + if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): + progress_bar.update() + + if XLA_AVAILABLE: + xm.mark_step() + + self._current_timestep = None + if output_type == "latent": + image = latents + else: + latents = self._unpack_latents(latents, height, width, self.vae_scale_factor) + latents = latents.to(self.vae.dtype) + latents_mean = ( + torch.tensor(self.vae.config.latents_mean) + .view(1, self.vae.config.z_dim, 1, 1, 1) + .to(latents.device, latents.dtype) + ) + latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to( + latents.device, latents.dtype + ) + latents = latents / latents_std + latents_mean + image = self.vae.decode(latents, return_dict=False)[0][:, :, 0] + image = self.image_processor.postprocess(image, output_type=output_type) + + # Offload all models + self.maybe_free_model_hooks() + + if not return_dict: + return (image,) + + return QwenImagePipelineOutput(images=image) diff --git a/qwenimage/qwen_fa3_processor.py b/qwenimage/qwen_fa3_processor.py new file mode 100644 index 0000000000000000000000000000000000000000..e825febec89ce9a6d51c4f1d7e2528656734069d --- /dev/null +++ b/qwenimage/qwen_fa3_processor.py @@ -0,0 +1,233 @@ +""" +Paired with a good language model. Thanks! + +FA3 is currently broken on Blackwell (sm_100) GPUs; this module detects that +at import time and falls back to PyTorch scaled-dot-product attention (SDPA) +automatically. The public class name / call signature are unchanged. +""" + +import torch +import torch.nn.functional as F +from typing import Optional, Tuple +from diffusers.models.transformers.transformer_qwenimage import apply_rotary_emb_qwen + + +# --------------------------------------------------------------------------- +# FA3 availability check +# --------------------------------------------------------------------------- + +def _is_blackwell() -> bool: + """Return True when the current default CUDA device is an sm_100 (Blackwell) GPU.""" + if not torch.cuda.is_available(): + return False + cap = torch.cuda.get_device_capability() + # Blackwell β†’ compute capability 10.x (sm_100) + return cap[0] >= 10 + + +_fa3_available: bool = False +_fa3_unavailable_reason: str = "" +_flash_attn_func = None + +if _is_blackwell(): + _fa3_unavailable_reason = ( + "FlashAttention-3 is not yet supported on Blackwell (sm_100) GPUs. " + "Falling back to scaled-dot-product attention (SDPA)." + ) +else: + try: + from kernels import get_kernel + _k = get_kernel("kernels-community/vllm-flash-attn3") + _flash_attn_func = _k.flash_attn_func + _fa3_available = True + except Exception as e: + _fa3_unavailable_reason = ( + "FlashAttention-3 via Hugging Face `kernels` is unavailable. " + f"Tried `get_kernel('kernels-community/vllm-flash-attn3')` and failed with:\n{e}\n" + "Falling back to scaled-dot-product attention (SDPA)." + ) + + +# --------------------------------------------------------------------------- +# FA3 custom op (registered only when the kernel loaded successfully) +# --------------------------------------------------------------------------- + +if _fa3_available: + @torch.library.custom_op("flash::flash_attn_func", mutates_args=()) + def flash_attn_func( + q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, causal: bool = False + ) -> torch.Tensor: + # _flash_attn_func returns (output, softmax_lse); we only need output. + output, _lse = _flash_attn_func(q, k, v, causal=causal) + return output + + @flash_attn_func.register_fake + def _flash_attn_func_fake(q, k, v, causal=False): + # output shape mirrors q: (batch, seq_len, num_heads, head_dim) + return torch.empty_like(q).contiguous() + +else: + # Provide a stub so call-sites that import the symbol don't break at + # module load; the processor will route around it at runtime. + def flash_attn_func( + q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, causal: bool = False + ) -> torch.Tensor: + raise RuntimeError(_fa3_unavailable_reason) + + +# --------------------------------------------------------------------------- +# SDPA fallback helper +# --------------------------------------------------------------------------- + +def _sdpa_attention( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + causal: bool = False, +) -> torch.Tensor: + """ + Scaled dot-product attention using torch.nn.functional.scaled_dot_product_attention. + + Input / output layout: (B, S, H, D_h) β€” same as the FA3 kernel. + """ + # SDPA expects (B, H, S, D_h) + q = q.transpose(1, 2) + k = k.transpose(1, 2) + v = v.transpose(1, 2) + + out = F.scaled_dot_product_attention(q, k, v, is_causal=causal) + + # Back to (B, S, H, D_h) + return out.transpose(1, 2) + + +# --------------------------------------------------------------------------- +# Attention processor +# --------------------------------------------------------------------------- + +class QwenDoubleStreamAttnProcessorFA3: + """ + Attention processor for the Qwen double-stream architecture. + + Preferred backend: vLLM FlashAttention-3 via Hugging Face ``kernels``. + Automatic fallback: PyTorch ``scaled_dot_product_attention`` (SDPA) when + FA3 is unavailable β€” e.g. on Blackwell (sm_100) GPUs where FA3 is not yet + supported, or when the ``kernels`` package is absent. + + Notes / limitations + ------------------- + - Arbitrary attention masks are not supported on the FA3 path. Pass + ``attention_mask=None`` (the default) to stay on the fast path. + - On the SDPA path, ``attention_mask`` is likewise ignored; add explicit + support here if you need it. + - ``encoder_hidden_states`` (text stream) is required. + """ + + _attention_backend: str # set in __init__ after capability detection + + def __init__(self): + if _fa3_available: + self._attention_backend = "fa3" + else: + import warnings + warnings.warn( + f"QwenDoubleStreamAttnProcessorFA3: {_fa3_unavailable_reason}", + stacklevel=2, + ) + self._attention_backend = "sdpa" + + def _attend( + self, + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + causal: bool = False, + ) -> torch.Tensor: + """Dispatch to FA3 or SDPA depending on what is available.""" + if self._attention_backend == "fa3": + return flash_attn_func(q, k, v, causal=causal) + return _sdpa_attention(q, k, v, causal=causal) + + @torch.no_grad() + def __call__( + self, + attn, + hidden_states: torch.FloatTensor, # (B, S_img, D_model) + encoder_hidden_states: torch.FloatTensor = None, # (B, S_txt, D_model) + encoder_hidden_states_mask: torch.FloatTensor = None, # unused + attention_mask: Optional[torch.FloatTensor] = None, # unsupported on FA3 path + image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, + ) -> Tuple[torch.FloatTensor, torch.FloatTensor]: + + if encoder_hidden_states is None: + raise ValueError( + "QwenDoubleStreamAttnProcessorFA3 requires encoder_hidden_states (text stream)." + ) + if attention_mask is not None and self._attention_backend == "fa3": + raise NotImplementedError( + "attention_mask is not supported on the FA3 path. " + "Either drop the mask or let the processor fall back to SDPA." + ) + + B, S_img, _ = hidden_states.shape + S_txt = encoder_hidden_states.shape[1] + + # ---- QKV projections ---- + img_q = attn.to_q(hidden_states) + img_k = attn.to_k(hidden_states) + img_v = attn.to_v(hidden_states) + + txt_q = attn.add_q_proj(encoder_hidden_states) + txt_k = attn.add_k_proj(encoder_hidden_states) + txt_v = attn.add_v_proj(encoder_hidden_states) + + # ---- Reshape to (B, S, H, D_h) ---- + H = attn.heads + img_q = img_q.unflatten(-1, (H, -1)) + img_k = img_k.unflatten(-1, (H, -1)) + img_v = img_v.unflatten(-1, (H, -1)) + + txt_q = txt_q.unflatten(-1, (H, -1)) + txt_k = txt_k.unflatten(-1, (H, -1)) + txt_v = txt_v.unflatten(-1, (H, -1)) + + # ---- Q/K normalization ---- + if getattr(attn, "norm_q", None) is not None: + img_q = attn.norm_q(img_q) + if getattr(attn, "norm_k", None) is not None: + img_k = attn.norm_k(img_k) + if getattr(attn, "norm_added_q", None) is not None: + txt_q = attn.norm_added_q(txt_q) + if getattr(attn, "norm_added_k", None) is not None: + txt_k = attn.norm_added_k(txt_k) + + # ---- RoPE (Qwen variant) ---- + if image_rotary_emb is not None: + img_freqs, txt_freqs = image_rotary_emb + img_q = apply_rotary_emb_qwen(img_q, img_freqs, use_real=False) + img_k = apply_rotary_emb_qwen(img_k, img_freqs, use_real=False) + txt_q = apply_rotary_emb_qwen(txt_q, txt_freqs, use_real=False) + txt_k = apply_rotary_emb_qwen(txt_k, txt_freqs, use_real=False) + + # ---- Joint attention over [text, image] along sequence axis ---- + q = torch.cat([txt_q, img_q], dim=1) # (B, S_txt + S_img, H, D_h) + k = torch.cat([txt_k, img_k], dim=1) + v = torch.cat([txt_v, img_v], dim=1) + + out = self._attend(q, k, v, causal=False) # (B, S_total, H, D_h) + + # ---- Back to (B, S, D_model) ---- + out = out.flatten(2, 3).to(q.dtype) + + # ---- Split text / image segments ---- + txt_attn_out = out[:, :S_txt, :] + img_attn_out = out[:, S_txt:, :] + + # ---- Output projections ---- + img_attn_out = attn.to_out[0](img_attn_out) + if len(attn.to_out) > 1: + img_attn_out = attn.to_out[1](img_attn_out) # dropout if present + + txt_attn_out = attn.to_add_out(txt_attn_out) + + return img_attn_out, txt_attn_out \ No newline at end of file diff --git a/qwenimage/transformer_qwenimage.py b/qwenimage/transformer_qwenimage.py new file mode 100644 index 0000000000000000000000000000000000000000..8b86c5edfa1ffd2d718c5f9689648143a4e7fde2 --- /dev/null +++ b/qwenimage/transformer_qwenimage.py @@ -0,0 +1,642 @@ +# Copyright 2025 Qwen-Image Team, The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import functools +import math +from typing import Any, Dict, List, Optional, Tuple, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from diffusers.configuration_utils import ConfigMixin, register_to_config +from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin +from diffusers.utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers +from diffusers.utils.torch_utils import maybe_allow_in_graph +from diffusers.models.attention import FeedForward, AttentionMixin +from diffusers.models.attention_dispatch import dispatch_attention_fn +from diffusers.models.attention_processor import Attention +from diffusers.models.cache_utils import CacheMixin +from diffusers.models.embeddings import TimestepEmbedding, Timesteps +from diffusers.models.modeling_outputs import Transformer2DModelOutput +from diffusers.models.modeling_utils import ModelMixin +from diffusers.models.normalization import AdaLayerNormContinuous, RMSNorm + + +logger = logging.get_logger(__name__) # pylint: disable=invalid-name + + +def get_timestep_embedding( + timesteps: torch.Tensor, + embedding_dim: int, + flip_sin_to_cos: bool = False, + downscale_freq_shift: float = 1, + scale: float = 1, + max_period: int = 10000, +) -> torch.Tensor: + """ + This matches the implementation in Denoising Diffusion Probabilistic Models: Create sinusoidal timestep embeddings. + + Args + timesteps (torch.Tensor): + a 1-D Tensor of N indices, one per batch element. These may be fractional. + embedding_dim (int): + the dimension of the output. + flip_sin_to_cos (bool): + Whether the embedding order should be `cos, sin` (if True) or `sin, cos` (if False) + downscale_freq_shift (float): + Controls the delta between frequencies between dimensions + scale (float): + Scaling factor applied to the embeddings. + max_period (int): + Controls the maximum frequency of the embeddings + Returns + torch.Tensor: an [N x dim] Tensor of positional embeddings. + """ + assert len(timesteps.shape) == 1, "Timesteps should be a 1d-array" + + half_dim = embedding_dim // 2 + exponent = -math.log(max_period) * torch.arange( + start=0, end=half_dim, dtype=torch.float32, device=timesteps.device + ) + exponent = exponent / (half_dim - downscale_freq_shift) + + emb = torch.exp(exponent).to(timesteps.dtype) + emb = timesteps[:, None].float() * emb[None, :] + + # scale embeddings + emb = scale * emb + + # concat sine and cosine embeddings + emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=-1) + + # flip sine and cosine embeddings + if flip_sin_to_cos: + emb = torch.cat([emb[:, half_dim:], emb[:, :half_dim]], dim=-1) + + # zero pad + if embedding_dim % 2 == 1: + emb = torch.nn.functional.pad(emb, (0, 1, 0, 0)) + return emb + + +def apply_rotary_emb_qwen( + x: torch.Tensor, + freqs_cis: Union[torch.Tensor, Tuple[torch.Tensor]], + use_real: bool = True, + use_real_unbind_dim: int = -1, +) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Apply rotary embeddings to input tensors using the given frequency tensor. This function applies rotary embeddings + to the given query or key 'x' tensors using the provided frequency tensor 'freqs_cis'. The input tensors are + reshaped as complex numbers, and the frequency tensor is reshaped for broadcasting compatibility. The resulting + tensors contain rotary embeddings and are returned as real tensors. + + Args: + x (`torch.Tensor`): + Query or key tensor to apply rotary embeddings. [B, S, H, D] xk (torch.Tensor): Key tensor to apply + freqs_cis (`Tuple[torch.Tensor]`): Precomputed frequency tensor for complex exponentials. ([S, D], [S, D],) + + Returns: + Tuple[torch.Tensor, torch.Tensor]: Tuple of modified query tensor and key tensor with rotary embeddings. + """ + if use_real: + cos, sin = freqs_cis # [S, D] + cos = cos[None, None] + sin = sin[None, None] + cos, sin = cos.to(x.device), sin.to(x.device) + + if use_real_unbind_dim == -1: + # Used for flux, cogvideox, hunyuan-dit + x_real, x_imag = x.reshape(*x.shape[:-1], -1, 2).unbind(-1) # [B, S, H, D//2] + x_rotated = torch.stack([-x_imag, x_real], dim=-1).flatten(3) + elif use_real_unbind_dim == -2: + # Used for Stable Audio, OmniGen, CogView4 and Cosmos + x_real, x_imag = x.reshape(*x.shape[:-1], 2, -1).unbind(-2) # [B, S, H, D//2] + x_rotated = torch.cat([-x_imag, x_real], dim=-1) + else: + raise ValueError(f"`use_real_unbind_dim={use_real_unbind_dim}` but should be -1 or -2.") + + out = (x.float() * cos + x_rotated.float() * sin).to(x.dtype) + + return out + else: + x_rotated = torch.view_as_complex(x.float().reshape(*x.shape[:-1], -1, 2)) + freqs_cis = freqs_cis.unsqueeze(1) + x_out = torch.view_as_real(x_rotated * freqs_cis).flatten(3) + + return x_out.type_as(x) + + +class QwenTimestepProjEmbeddings(nn.Module): + def __init__(self, embedding_dim): + super().__init__() + + self.time_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0, scale=1000) + self.timestep_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim) + + def forward(self, timestep, hidden_states): + timesteps_proj = self.time_proj(timestep) + timesteps_emb = self.timestep_embedder(timesteps_proj.to(dtype=hidden_states.dtype)) # (N, D) + + conditioning = timesteps_emb + + return conditioning + + +class QwenEmbedRope(nn.Module): + def __init__(self, theta: int, axes_dim: List[int], scale_rope=False): + super().__init__() + self.theta = theta + self.axes_dim = axes_dim + pos_index = torch.arange(4096) + neg_index = torch.arange(4096).flip(0) * -1 - 1 + self.pos_freqs = torch.cat( + [ + self.rope_params(pos_index, self.axes_dim[0], self.theta), + self.rope_params(pos_index, self.axes_dim[1], self.theta), + self.rope_params(pos_index, self.axes_dim[2], self.theta), + ], + dim=1, + ) + self.neg_freqs = torch.cat( + [ + self.rope_params(neg_index, self.axes_dim[0], self.theta), + self.rope_params(neg_index, self.axes_dim[1], self.theta), + self.rope_params(neg_index, self.axes_dim[2], self.theta), + ], + dim=1, + ) + self.rope_cache = {} + + # DO NOT USING REGISTER BUFFER HERE, IT WILL CAUSE COMPLEX NUMBERS LOSE ITS IMAGINARY PART + self.scale_rope = scale_rope + + def rope_params(self, index, dim, theta=10000): + """ + Args: + index: [0, 1, 2, 3] 1D Tensor representing the position index of the token + """ + assert dim % 2 == 0 + freqs = torch.outer(index, 1.0 / torch.pow(theta, torch.arange(0, dim, 2).to(torch.float32).div(dim))) + freqs = torch.polar(torch.ones_like(freqs), freqs) + return freqs + + def forward(self, video_fhw, txt_seq_lens, device): + """ + Args: video_fhw: [frame, height, width] a list of 3 integers representing the shape of the video Args: + txt_length: [bs] a list of 1 integers representing the length of the text + """ + if self.pos_freqs.device != device: + self.pos_freqs = self.pos_freqs.to(device) + self.neg_freqs = self.neg_freqs.to(device) + + if isinstance(video_fhw, list): + video_fhw = video_fhw[0] + if not isinstance(video_fhw, list): + video_fhw = [video_fhw] + + vid_freqs = [] + max_vid_index = 0 + for idx, fhw in enumerate(video_fhw): + frame, height, width = fhw + rope_key = f"{idx}_{height}_{width}" + + if not torch.compiler.is_compiling(): + if rope_key not in self.rope_cache: + self.rope_cache[rope_key] = self._compute_video_freqs(frame, height, width, idx) + video_freq = self.rope_cache[rope_key] + else: + video_freq = self._compute_video_freqs(frame, height, width, idx) + video_freq = video_freq.to(device) + vid_freqs.append(video_freq) + + if self.scale_rope: + max_vid_index = max(height // 2, width // 2, max_vid_index) + else: + max_vid_index = max(height, width, max_vid_index) + + max_len = max(txt_seq_lens) + txt_freqs = self.pos_freqs[max_vid_index : max_vid_index + max_len, ...] + vid_freqs = torch.cat(vid_freqs, dim=0) + + return vid_freqs, txt_freqs + + @functools.lru_cache(maxsize=None) + def _compute_video_freqs(self, frame, height, width, idx=0): + seq_lens = frame * height * width + freqs_pos = self.pos_freqs.split([x // 2 for x in self.axes_dim], dim=1) + freqs_neg = self.neg_freqs.split([x // 2 for x in self.axes_dim], dim=1) + + freqs_frame = freqs_pos[0][idx : idx + frame].view(frame, 1, 1, -1).expand(frame, height, width, -1) + if self.scale_rope: + freqs_height = torch.cat([freqs_neg[1][-(height - height // 2) :], freqs_pos[1][: height // 2]], dim=0) + freqs_height = freqs_height.view(1, height, 1, -1).expand(frame, height, width, -1) + freqs_width = torch.cat([freqs_neg[2][-(width - width // 2) :], freqs_pos[2][: width // 2]], dim=0) + freqs_width = freqs_width.view(1, 1, width, -1).expand(frame, height, width, -1) + else: + freqs_height = freqs_pos[1][:height].view(1, height, 1, -1).expand(frame, height, width, -1) + freqs_width = freqs_pos[2][:width].view(1, 1, width, -1).expand(frame, height, width, -1) + + freqs = torch.cat([freqs_frame, freqs_height, freqs_width], dim=-1).reshape(seq_lens, -1) + return freqs.clone().contiguous() + + +class QwenDoubleStreamAttnProcessor2_0: + """ + Attention processor for Qwen double-stream architecture, matching DoubleStreamLayerMegatron logic. This processor + implements joint attention computation where text and image streams are processed together. + """ + + _attention_backend = None + + def __init__(self): + if not hasattr(F, "scaled_dot_product_attention"): + raise ImportError( + "QwenDoubleStreamAttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0." + ) + + def __call__( + self, + attn: Attention, + hidden_states: torch.FloatTensor, # Image stream + encoder_hidden_states: torch.FloatTensor = None, # Text stream + encoder_hidden_states_mask: torch.FloatTensor = None, + attention_mask: Optional[torch.FloatTensor] = None, + image_rotary_emb: Optional[torch.Tensor] = None, + ) -> torch.FloatTensor: + if encoder_hidden_states is None: + raise ValueError("QwenDoubleStreamAttnProcessor2_0 requires encoder_hidden_states (text stream)") + + seq_txt = encoder_hidden_states.shape[1] + + # Compute QKV for image stream (sample projections) + img_query = attn.to_q(hidden_states) + img_key = attn.to_k(hidden_states) + img_value = attn.to_v(hidden_states) + + # Compute QKV for text stream (context projections) + txt_query = attn.add_q_proj(encoder_hidden_states) + txt_key = attn.add_k_proj(encoder_hidden_states) + txt_value = attn.add_v_proj(encoder_hidden_states) + + # Reshape for multi-head attention + img_query = img_query.unflatten(-1, (attn.heads, -1)) + img_key = img_key.unflatten(-1, (attn.heads, -1)) + img_value = img_value.unflatten(-1, (attn.heads, -1)) + + txt_query = txt_query.unflatten(-1, (attn.heads, -1)) + txt_key = txt_key.unflatten(-1, (attn.heads, -1)) + txt_value = txt_value.unflatten(-1, (attn.heads, -1)) + + # Apply QK normalization + if attn.norm_q is not None: + img_query = attn.norm_q(img_query) + if attn.norm_k is not None: + img_key = attn.norm_k(img_key) + if attn.norm_added_q is not None: + txt_query = attn.norm_added_q(txt_query) + if attn.norm_added_k is not None: + txt_key = attn.norm_added_k(txt_key) + + # Apply RoPE + if image_rotary_emb is not None: + img_freqs, txt_freqs = image_rotary_emb + img_query = apply_rotary_emb_qwen(img_query, img_freqs, use_real=False) + img_key = apply_rotary_emb_qwen(img_key, img_freqs, use_real=False) + txt_query = apply_rotary_emb_qwen(txt_query, txt_freqs, use_real=False) + txt_key = apply_rotary_emb_qwen(txt_key, txt_freqs, use_real=False) + + # Concatenate for joint attention + # Order: [text, image] + joint_query = torch.cat([txt_query, img_query], dim=1) + joint_key = torch.cat([txt_key, img_key], dim=1) + joint_value = torch.cat([txt_value, img_value], dim=1) + + # Compute joint attention + joint_hidden_states = dispatch_attention_fn( + joint_query, + joint_key, + joint_value, + attn_mask=attention_mask, + dropout_p=0.0, + is_causal=False, + backend=self._attention_backend, + ) + + # Reshape back + joint_hidden_states = joint_hidden_states.flatten(2, 3) + joint_hidden_states = joint_hidden_states.to(joint_query.dtype) + + # Split attention outputs back + txt_attn_output = joint_hidden_states[:, :seq_txt, :] # Text part + img_attn_output = joint_hidden_states[:, seq_txt:, :] # Image part + + # Apply output projections + img_attn_output = attn.to_out[0](img_attn_output) + if len(attn.to_out) > 1: + img_attn_output = attn.to_out[1](img_attn_output) # dropout + + txt_attn_output = attn.to_add_out(txt_attn_output) + + return img_attn_output, txt_attn_output + + +@maybe_allow_in_graph +class QwenImageTransformerBlock(nn.Module): + def __init__( + self, dim: int, num_attention_heads: int, attention_head_dim: int, qk_norm: str = "rms_norm", eps: float = 1e-6 + ): + super().__init__() + + self.dim = dim + self.num_attention_heads = num_attention_heads + self.attention_head_dim = attention_head_dim + + # Image processing modules + self.img_mod = nn.Sequential( + nn.SiLU(), + nn.Linear(dim, 6 * dim, bias=True), # For scale, shift, gate for norm1 and norm2 + ) + self.img_norm1 = nn.LayerNorm(dim, elementwise_affine=False, eps=eps) + self.attn = Attention( + query_dim=dim, + cross_attention_dim=None, # Enable cross attention for joint computation + added_kv_proj_dim=dim, # Enable added KV projections for text stream + dim_head=attention_head_dim, + heads=num_attention_heads, + out_dim=dim, + context_pre_only=False, + bias=True, + processor=QwenDoubleStreamAttnProcessor2_0(), + qk_norm=qk_norm, + eps=eps, + ) + self.img_norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=eps) + self.img_mlp = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate") + + # Text processing modules + self.txt_mod = nn.Sequential( + nn.SiLU(), + nn.Linear(dim, 6 * dim, bias=True), # For scale, shift, gate for norm1 and norm2 + ) + self.txt_norm1 = nn.LayerNorm(dim, elementwise_affine=False, eps=eps) + # Text doesn't need separate attention - it's handled by img_attn joint computation + self.txt_norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=eps) + self.txt_mlp = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate") + + def _modulate(self, x, mod_params): + """Apply modulation to input tensor""" + shift, scale, gate = mod_params.chunk(3, dim=-1) + return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1), gate.unsqueeze(1) + + def forward( + self, + hidden_states: torch.Tensor, + encoder_hidden_states: torch.Tensor, + encoder_hidden_states_mask: torch.Tensor, + temb: torch.Tensor, + image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, + joint_attention_kwargs: Optional[Dict[str, Any]] = None, + ) -> Tuple[torch.Tensor, torch.Tensor]: + # Get modulation parameters for both streams + img_mod_params = self.img_mod(temb) # [B, 6*dim] + txt_mod_params = self.txt_mod(temb) # [B, 6*dim] + + # Split modulation parameters for norm1 and norm2 + img_mod1, img_mod2 = img_mod_params.chunk(2, dim=-1) # Each [B, 3*dim] + txt_mod1, txt_mod2 = txt_mod_params.chunk(2, dim=-1) # Each [B, 3*dim] + + # Process image stream - norm1 + modulation + img_normed = self.img_norm1(hidden_states) + img_modulated, img_gate1 = self._modulate(img_normed, img_mod1) + + # Process text stream - norm1 + modulation + txt_normed = self.txt_norm1(encoder_hidden_states) + txt_modulated, txt_gate1 = self._modulate(txt_normed, txt_mod1) + + # Use QwenAttnProcessor2_0 for joint attention computation + # This directly implements the DoubleStreamLayerMegatron logic: + # 1. Computes QKV for both streams + # 2. Applies QK normalization and RoPE + # 3. Concatenates and runs joint attention + # 4. Splits results back to separate streams + joint_attention_kwargs = joint_attention_kwargs or {} + attn_output = self.attn( + hidden_states=img_modulated, # Image stream (will be processed as "sample") + encoder_hidden_states=txt_modulated, # Text stream (will be processed as "context") + encoder_hidden_states_mask=encoder_hidden_states_mask, + image_rotary_emb=image_rotary_emb, + **joint_attention_kwargs, + ) + + # QwenAttnProcessor2_0 returns (img_output, txt_output) when encoder_hidden_states is provided + img_attn_output, txt_attn_output = attn_output + + # Apply attention gates and add residual (like in Megatron) + hidden_states = hidden_states + img_gate1 * img_attn_output + encoder_hidden_states = encoder_hidden_states + txt_gate1 * txt_attn_output + + # Process image stream - norm2 + MLP + img_normed2 = self.img_norm2(hidden_states) + img_modulated2, img_gate2 = self._modulate(img_normed2, img_mod2) + img_mlp_output = self.img_mlp(img_modulated2) + hidden_states = hidden_states + img_gate2 * img_mlp_output + + # Process text stream - norm2 + MLP + txt_normed2 = self.txt_norm2(encoder_hidden_states) + txt_modulated2, txt_gate2 = self._modulate(txt_normed2, txt_mod2) + txt_mlp_output = self.txt_mlp(txt_modulated2) + encoder_hidden_states = encoder_hidden_states + txt_gate2 * txt_mlp_output + + # Clip to prevent overflow for fp16 + if encoder_hidden_states.dtype == torch.float16: + encoder_hidden_states = encoder_hidden_states.clip(-65504, 65504) + if hidden_states.dtype == torch.float16: + hidden_states = hidden_states.clip(-65504, 65504) + + return encoder_hidden_states, hidden_states + + +class QwenImageTransformer2DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin, CacheMixin, AttentionMixin): + """ + The Transformer model introduced in Qwen. + + Args: + patch_size (`int`, defaults to `2`): + Patch size to turn the input data into small patches. + in_channels (`int`, defaults to `64`): + The number of channels in the input. + out_channels (`int`, *optional*, defaults to `None`): + The number of channels in the output. If not specified, it defaults to `in_channels`. + num_layers (`int`, defaults to `60`): + The number of layers of dual stream DiT blocks to use. + attention_head_dim (`int`, defaults to `128`): + The number of dimensions to use for each attention head. + num_attention_heads (`int`, defaults to `24`): + The number of attention heads to use. + joint_attention_dim (`int`, defaults to `3584`): + The number of dimensions to use for the joint attention (embedding/channel dimension of + `encoder_hidden_states`). + guidance_embeds (`bool`, defaults to `False`): + Whether to use guidance embeddings for guidance-distilled variant of the model. + axes_dims_rope (`Tuple[int]`, defaults to `(16, 56, 56)`): + The dimensions to use for the rotary positional embeddings. + """ + + _supports_gradient_checkpointing = True + _no_split_modules = ["QwenImageTransformerBlock"] + _skip_layerwise_casting_patterns = ["pos_embed", "norm"] + _repeated_blocks = ["QwenImageTransformerBlock"] + + @register_to_config + def __init__( + self, + patch_size: int = 2, + in_channels: int = 64, + out_channels: Optional[int] = 16, + num_layers: int = 60, + attention_head_dim: int = 128, + num_attention_heads: int = 24, + joint_attention_dim: int = 3584, + guidance_embeds: bool = False, # TODO: this should probably be removed + axes_dims_rope: Tuple[int, int, int] = (16, 56, 56), + ): + super().__init__() + self.out_channels = out_channels or in_channels + self.inner_dim = num_attention_heads * attention_head_dim + + self.pos_embed = QwenEmbedRope(theta=10000, axes_dim=list(axes_dims_rope), scale_rope=True) + + self.time_text_embed = QwenTimestepProjEmbeddings(embedding_dim=self.inner_dim) + + self.txt_norm = RMSNorm(joint_attention_dim, eps=1e-6) + + self.img_in = nn.Linear(in_channels, self.inner_dim) + self.txt_in = nn.Linear(joint_attention_dim, self.inner_dim) + + self.transformer_blocks = nn.ModuleList( + [ + QwenImageTransformerBlock( + dim=self.inner_dim, + num_attention_heads=num_attention_heads, + attention_head_dim=attention_head_dim, + ) + for _ in range(num_layers) + ] + ) + + self.norm_out = AdaLayerNormContinuous(self.inner_dim, self.inner_dim, elementwise_affine=False, eps=1e-6) + self.proj_out = nn.Linear(self.inner_dim, patch_size * patch_size * self.out_channels, bias=True) + + self.gradient_checkpointing = False + + def forward( + self, + hidden_states: torch.Tensor, + encoder_hidden_states: torch.Tensor = None, + encoder_hidden_states_mask: torch.Tensor = None, + timestep: torch.LongTensor = None, + image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, + guidance: torch.Tensor = None, # TODO: this should probably be removed + attention_kwargs: Optional[Dict[str, Any]] = None, + return_dict: bool = True, + ) -> Union[torch.Tensor, Transformer2DModelOutput]: + """ + The [`QwenTransformer2DModel`] forward method. + + Args: + hidden_states (`torch.Tensor` of shape `(batch_size, image_sequence_length, in_channels)`): + Input `hidden_states`. + encoder_hidden_states (`torch.Tensor` of shape `(batch_size, text_sequence_length, joint_attention_dim)`): + Conditional embeddings (embeddings computed from the input conditions such as prompts) to use. + encoder_hidden_states_mask (`torch.Tensor` of shape `(batch_size, text_sequence_length)`): + Mask of the input conditions. + timestep ( `torch.LongTensor`): + Used to indicate denoising step. + attention_kwargs (`dict`, *optional*): + A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under + `self.processor` in + [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). + return_dict (`bool`, *optional*, defaults to `True`): + Whether or not to return a [`~models.transformer_2d.Transformer2DModelOutput`] instead of a plain + tuple. + + Returns: + If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a + `tuple` where the first element is the sample tensor. + """ + if attention_kwargs is not None: + attention_kwargs = attention_kwargs.copy() + lora_scale = attention_kwargs.pop("scale", 1.0) + else: + lora_scale = 1.0 + + if USE_PEFT_BACKEND: + # weight the lora layers by setting `lora_scale` for each PEFT layer + scale_lora_layers(self, lora_scale) + else: + if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None: + logger.warning( + "Passing `scale` via `joint_attention_kwargs` when not using the PEFT backend is ineffective." + ) + + hidden_states = self.img_in(hidden_states) + + timestep = timestep.to(hidden_states.dtype) + encoder_hidden_states = self.txt_norm(encoder_hidden_states) + encoder_hidden_states = self.txt_in(encoder_hidden_states) + + if guidance is not None: + guidance = guidance.to(hidden_states.dtype) * 1000 + + temb = ( + self.time_text_embed(timestep, hidden_states) + if guidance is None + else self.time_text_embed(timestep, guidance, hidden_states) + ) + + for index_block, block in enumerate(self.transformer_blocks): + if torch.is_grad_enabled() and self.gradient_checkpointing: + encoder_hidden_states, hidden_states = self._gradient_checkpointing_func( + block, + hidden_states, + encoder_hidden_states, + encoder_hidden_states_mask, + temb, + image_rotary_emb, + ) + + else: + encoder_hidden_states, hidden_states = block( + hidden_states=hidden_states, + encoder_hidden_states=encoder_hidden_states, + encoder_hidden_states_mask=encoder_hidden_states_mask, + temb=temb, + image_rotary_emb=image_rotary_emb, + joint_attention_kwargs=attention_kwargs, + ) + + # Use only the image part (hidden_states) from the dual-stream blocks + hidden_states = self.norm_out(hidden_states, temb) + output = self.proj_out(hidden_states) + + if USE_PEFT_BACKEND: + # remove `lora_scale` from each PEFT layer + unscale_lora_layers(self, lora_scale) + + if not return_dict: + return (output,) + + return Transformer2DModelOutput(sample=output) diff --git a/requirements.txt b/requirements.txt index 73d01db64bd054c7d21fd0bd79b3af087c468809..3e0f498fd42a949cc0351daf7000b70c3e81326c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,10 @@ -accelerate -diffusers -invisible_watermark -torch -transformers -xformers \ No newline at end of file +--extra-index-url https://download.pytorch.org/whl/cu130 +torch==2.11.0 +torchvision==0.26.0 +transformers==5.14.1 +accelerate==1.14.0 +diffusers==0.39.0 +peft==0.19.1 +av==17.1.0 +huggingface-hub==1.24.0 +kernels==0.16.0 diff --git a/ui/app.css b/ui/app.css new file mode 100644 index 0000000000000000000000000000000000000000..9f06fd7caec84d3975e0bfcf330c138d7aa35892 --- /dev/null +++ b/ui/app.css @@ -0,0 +1,700 @@ +@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&display=swap'); +*{box-sizing:border-box;margin:0;padding:0} +body,.gradio-container{ + background:#0f0f13!important;font-family:'Inter',system-ui,-apple-system,sans-serif!important; + font-size:14px!important;color:#e4e4e7!important;min-height:100vh; +} +.dark body,.dark .gradio-container{background:#0f0f13!important;color:#e4e4e7!important} +footer{display:none!important} +.hidden-input{display:none!important;height:0!important;overflow:hidden!important;margin:0!important;padding:0!important} + +#example-load-btn{ + position:absolute!important;left:-9999px!important;top:-9999px!important; + width:1px!important;height:1px!important;opacity:0.01!important; + pointer-events:none!important;overflow:hidden!important; +} +#gradio-run-btn{ + position:absolute;left:-9999px;top:-9999px;width:1px;height:1px; + opacity:0.01;pointer-events:none;overflow:hidden; +} + +/* ── App shell ── */ +.app-shell{ + background:#18181b;border:1px solid #27272a;border-radius:16px; + margin:12px auto;max-width:1440px;overflow:hidden; + box-shadow:0 25px 50px -12px rgba(0,0,0,.6),0 0 0 1px rgba(255,255,255,.03); +} + +/* ── Header ── */ +.app-header{ + background:linear-gradient(135deg,#18181b,#1e1e24);border-bottom:1px solid #27272a; + padding:14px 24px;display:flex;align-items:center;justify-content:space-between; + flex-wrap:wrap;gap:12px; +} +.app-header-left{display:flex;align-items:center;gap:12px} +.app-logo{ + width:38px;height:38px;background:linear-gradient(135deg,#1E90FF,#47A3FF,#7CB8FF); + border-radius:11px;display:flex;align-items:center;justify-content:center; + box-shadow:0 4px 12px rgba(30,144,255,.35);flex-shrink:0; +} +.app-logo svg{width:20px;height:20px;fill:#fff;flex-shrink:0} +.app-title{ + font-size:18px;font-weight:800;background:linear-gradient(135deg,#e4e4e7,#a1a1aa); + -webkit-background-clip:text;-webkit-text-fill-color:transparent;letter-spacing:-.3px; +} +.app-badge{ + font-size:11px;font-weight:700;padding:3px 10px;border-radius:20px; + background:rgba(30,144,255,.15);color:#47A3FF;border:1px solid rgba(30,144,255,.25);letter-spacing:.3px; +} +.app-badge.fast{background:rgba(34,197,94,.12);color:#4ade80;border:1px solid rgba(34,197,94,.25)} + +/* ── GitHub button ── */ +.gh-btn{ + display:inline-flex!important;align-items:center!important;gap:7px!important; + padding:7px 16px!important;border-radius:8px!important;text-decoration:none!important; + font-family:'Inter',sans-serif!important;font-size:13px!important;font-weight:700!important; + letter-spacing:.1px!important;background:#1E90FF!important; + color:#ffffff!important;-webkit-text-fill-color:#ffffff!important; + border:1px solid rgba(255,255,255,.18)!important; + box-shadow:0 2px 10px rgba(30,144,255,.45),0 1px 0 rgba(255,255,255,.1) inset!important; + transition:transform .15s ease,box-shadow .15s ease,background .15s ease!important; + cursor:pointer!important;flex-shrink:0!important; +} +.gh-btn:hover{ + background:#47A3FF!important;color:#ffffff!important;-webkit-text-fill-color:#ffffff!important; + transform:translateY(-1px)!important; + box-shadow:0 5px 18px rgba(30,144,255,.6),0 1px 0 rgba(255,255,255,.12) inset!important; +} +.gh-btn:active{ + background:#1873CC!important;transform:translateY(0)!important; + box-shadow:0 1px 5px rgba(30,144,255,.35)!important; +} +.gh-btn svg{fill:#ffffff!important;flex-shrink:0;width:15px!important;height:15px!important} +.gh-btn span{color:#ffffff!important;-webkit-text-fill-color:#ffffff!important} + +@media (prefers-color-scheme: light){ + .gh-btn{background:#1E90FF!important;color:#ffffff!important;-webkit-text-fill-color:#ffffff!important;border-color:rgba(255,255,255,.18)!important} + .gh-btn:hover{background:#47A3FF!important} + .gh-btn svg{fill:#ffffff!important} + .gh-btn span{color:#ffffff!important;-webkit-text-fill-color:#ffffff!important} +} + +/* ── Toolbar row (left actions | right Output label) ~60% / 40% ── */ +.app-toolbar-row{ + display:flex;align-items:stretch;background:#18181b;border-bottom:1px solid #27272a; +} +.app-toolbar{ + flex:0 0 60%;width:60%;max-width:60%;min-width:0;padding:8px 16px; + display:flex;flex-direction:column;gap:6px;align-items:stretch;justify-content:center; + border-right:1px solid #27272a;box-sizing:border-box; +} +.app-toolbar-actions{display:flex;gap:4px;align-items:center;flex-wrap:wrap} +.upload-hint{ + font-size:13px;color:#a1a1aa;line-height:1.5;padding:0 2px; +} +.upload-hint b{color:#7CB8FF;font-weight:600} + +.output-toolbar{ + flex:0 0 40%;width:40%;max-width:40%;min-width:0;padding:8px 20px; + display:flex;align-items:center;justify-content:space-between;gap:10px; + box-sizing:border-box; +} +.output-toolbar-left{display:flex;align-items:center;gap:10px;min-width:0} +.output-toolbar .out-title-label{ + font-size:13px;font-weight:700;color:#ffffff!important; + -webkit-text-fill-color:#ffffff!important;text-transform:uppercase;letter-spacing:.8px; +} +.out-pred-dims,.size-pred-dims{ + font-family:'JetBrains Mono',monospace;font-size:11px;font-weight:500; + color:#47A3FF;white-space:nowrap; +} +.out-pred-dims[hidden],.size-pred-dims[hidden]{display:none!important} +.size-pred-dims{ + margin-top:8px;color:#a1a1aa;font-size:12px; +} +.tb-sep{width:1px;height:28px;background:#27272a;margin:0 8px} +.modern-tb-btn{ + display:inline-flex;align-items:center;justify-content:center;gap:6px; + min-width:32px;height:34px;background:transparent;border:1px solid transparent; + border-radius:8px;cursor:pointer;font-size:13px;font-weight:600;padding:0 12px; + font-family:'Inter',sans-serif;color:#ffffff!important;-webkit-text-fill-color:#ffffff!important; + transition:all .15s ease; +} +.modern-tb-btn:hover{background:rgba(30,144,255,.15);border-color:rgba(30,144,255,.3)} +.modern-tb-btn:active,.modern-tb-btn.active{background:rgba(30,144,255,.25);border-color:rgba(30,144,255,.45)} +.modern-tb-btn .tb-label{font-size:13px;color:#ffffff!important;-webkit-text-fill-color:#ffffff!important;font-weight:600} +.modern-tb-btn .tb-svg{width:15px;height:15px;flex-shrink:0;color:#ffffff!important} +.modern-tb-btn .tb-svg, +.modern-tb-btn .tb-svg *{stroke:#ffffff!important;fill:none!important} +.tb-info{font-family:'JetBrains Mono',monospace;font-size:12px;color:#71717a;padding:0 8px;display:flex;align-items:center} + +body:not(.dark) .modern-tb-btn,body:not(.dark) .modern-tb-btn *{color:#ffffff!important;-webkit-text-fill-color:#ffffff!important} +body:not(.dark) .modern-tb-btn .tb-svg,body:not(.dark) .modern-tb-btn .tb-svg *{stroke:#ffffff!important} +.dark .modern-tb-btn,.dark .modern-tb-btn *{color:#ffffff!important;-webkit-text-fill-color:#ffffff!important} +.dark .modern-tb-btn .tb-svg,.dark .modern-tb-btn .tb-svg *{stroke:#ffffff!important} +.gradio-container .modern-tb-btn,.gradio-container .modern-tb-btn *{color:#ffffff!important;-webkit-text-fill-color:#ffffff!important} +.gradio-container .modern-tb-btn .tb-svg,.gradio-container .modern-tb-btn .tb-svg *{stroke:#ffffff!important} + +/* ── Main layout: upload ~60% | editor/output ~40% ── */ +.app-main-row{display:flex;gap:0;flex:1;overflow:visible} +.app-main-left{ + flex:0 0 60%;width:60%;max-width:60%;display:flex;flex-direction:column;min-width:0; + border-right:1px solid #27272a;position:relative;z-index:1;box-sizing:border-box; +} +.app-main-right{ + flex:0 0 40%;width:40%;max-width:40%;display:flex;flex-direction:column;min-width:0; + background:#18181b;position:relative;z-index:5;box-sizing:border-box; +} + +/* ── Drop zone ── */ +#gallery-drop-zone{position:relative;background:#09090b;min-height:440px;height:440px;max-height:440px;overflow:auto} +.app-main-right{display:flex!important;flex-direction:column!important;overflow-y:auto;min-height:0} +.app-main-right .output-frame{ + flex:0 0 440px;height:440px;min-height:440px;max-height:440px; + display:flex;flex-direction:column; +} +.app-main-right .output-frame .out-body{flex:1 1 auto;min-height:0;height:100%} +.app-main-right .output-frame .out-body img{ + max-width:100%;max-height:100%;width:auto;height:auto;object-fit:contain; +} +.app-main-right .panel-card, +.app-main-right .lora-selector-card, +.app-main-right .settings-group, +.app-main-right > div[style*="padding"]{flex-shrink:0} +.settings-group-title{color:#a1a1aa!important} +#gallery-drop-zone.drag-over{outline:2px solid #1E90FF;outline-offset:-2px;background:rgba(30,144,255,.04)} + +.upload-prompt-modern{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);z-index:20} +.upload-click-area{ + display:flex;flex-direction:column;align-items:center;justify-content:center; + cursor:pointer;padding:36px 52px;border:2px dashed #3f3f46;border-radius:16px; + background:rgba(30,144,255,.03);transition:all .2s ease;gap:8px; +} +.upload-click-area:hover{background:rgba(30,144,255,.08);border-color:#1E90FF;transform:scale(1.03)} +.upload-click-area:active{background:rgba(30,144,255,.12);transform:scale(.98)} +.upload-click-area svg{width:80px;height:80px} +.upload-main-text{color:#71717a;font-size:14px;font-weight:500;margin-top:4px} +.upload-sub-text{color:#52525b;font-size:12px;text-align:center;max-width:280px;line-height:1.5} + +/* ── Gallery: max 2 images, equal columns, aspect-aware height with cap ── */ +.image-gallery-grid{ + display:grid;grid-template-columns:1fr 1fr;gap:14px;padding:16px; + align-content:start;align-items:stretch; +} +.gallery-thumb{ + position:relative;border-radius:10px;overflow:hidden; + cursor:pointer;border:2px solid #27272a;transition:all .2s ease;background:#18181b; + display:flex;flex-direction:column;min-width:0; +} +.gallery-thumb:hover{border-color:#3f3f46;transform:translateY(-2px);box-shadow:0 4px 12px rgba(0,0,0,.4)} +.gallery-thumb.selected{border-color:#1E90FF!important;box-shadow:0 0 0 3px rgba(30,144,255,.2)} +.gallery-thumb-media{ + width:100%;min-height:200px;height:clamp(200px,28vw,360px); + max-height:360px;display:flex;align-items:center;justify-content:center; + background:#09090b;overflow:hidden;flex:1 1 auto; +} +.gallery-thumb-media img{ + max-width:100%;max-height:100%;width:auto;height:auto; + object-fit:contain;display:block; +} +.gallery-thumb-dims{ + font-family:'JetBrains Mono',monospace;font-size:11px;font-weight:500; + color:#71717a;text-align:center;padding:6px 8px;line-height:1.2; + border-top:1px solid #27272a;background:#18181b;min-height:28px; + display:flex;align-items:center;justify-content:center;flex-shrink:0; +} +.thumb-badge{ + position:absolute;top:8px;left:8px;background:#1E90FF;color:#fff;z-index:2; + padding:2px 8px;border-radius:4px;font-family:'JetBrains Mono',monospace;font-size:11px;font-weight:600; +} +.thumb-remove{ + position:absolute;top:8px;right:8px;width:26px;height:26px;background:rgba(0,0,0,.75);z-index:2; + color:#fff;border:1px solid rgba(255,255,255,.15);border-radius:50%;cursor:pointer; + display:none;align-items:center;justify-content:center;font-size:12px;transition:all .15s;line-height:1; +} +.gallery-thumb:hover .thumb-remove{display:flex} +.thumb-remove:hover{background:#1E90FF;border-color:#1E90FF} +.gallery-add-card{ + border-radius:10px;border:2px dashed #3f3f46; + height:100%;min-height:clamp(228px, calc(28vw + 28px), 388px); + display:flex;flex-direction:column;align-items:center;justify-content:center; + cursor:pointer;transition:all .2s ease;background:rgba(30,144,255,.03);gap:4px; +} +.gallery-add-card:hover{border-color:#1E90FF;background:rgba(30,144,255,.08)} +.gallery-add-card .add-icon{font-size:32px;color:#71717a;font-weight:300} +.gallery-add-card .add-text{font-size:13px;color:#71717a;font-weight:500} + +/* ── Hint bar ── */ +.hint-bar{ + background:rgba(30,144,255,.06);border-top:1px solid #27272a;border-bottom:1px solid #27272a; + padding:10px 20px;font-size:13px;color:#a1a1aa;line-height:1.7; +} +.hint-bar b{color:#7CB8FF;font-weight:600} +.hint-bar kbd{ + display:inline-block;padding:1px 6px;background:#27272a;border:1px solid #3f3f46; + border-radius:4px;font-family:'JetBrains Mono',monospace;font-size:11px;color:#a1a1aa; +} + +/* ── Quick Prompts master bar + per-group toolbars ── */ +.prompts-toolbar{ + display:flex;align-items:center;justify-content:space-between;gap:12px; + padding:12px 16px;border-top:1px solid #27272a;border-bottom:1px solid #27272a; + background:#18181b;flex-wrap:wrap; +} +.prompts-toolbar-left{display:flex;flex-direction:column;gap:2px;min-width:0} +.prompts-toolbar-title{ + font-size:15px;font-weight:700;color:#ffffff!important;-webkit-text-fill-color:#ffffff!important; + letter-spacing:.4px;line-height:1.3; +} +.prompts-toolbar-hint{ + font-size:12px;font-weight:500;color:#71717a;text-transform:none;letter-spacing:0; +} +.prompts-toolbar-right{display:flex;gap:6px;align-items:center;flex-shrink:0;margin-left:auto} +.prompts-tb-btn{ + height:36px!important;padding:0 14px!important; +} +.prompts-tb-btn .tb-label{font-size:14px!important;font-weight:600!important} + +.chip-panel{ + border-bottom:1px solid #27272a;background:#121214; +} +.chip-panel-toolbar{ + width:100%;display:flex;align-items:center;gap:10px; + padding:12px 16px;margin:0;border:none;background:transparent; + cursor:pointer;text-align:left;font-family:'Inter',sans-serif; + color:#e4e4e7;transition:background .15s ease; +} +.chip-panel-toolbar:hover{background:rgba(30,144,255,.06)} +.chip-panel-toolbar:focus-visible{outline:2px solid rgba(30,144,255,.5);outline-offset:-2px} +.chip-panel-title{ + font-size:14px;font-weight:700;color:#ffffff!important;-webkit-text-fill-color:#ffffff!important; + letter-spacing:.2px;flex:1 1 auto;min-width:0; +} +.chip-panel-hint{ + font-size:12px;font-weight:500;color:#71717a;flex:1 1 auto; +} +.chip-panel-hint[hidden]{display:none!important} +.chip-panel-chevron{ + font-size:10px;color:#71717a;transition:transform .15s ease;flex-shrink:0; + margin-left:auto; +} +.chip-panel.open .chip-panel-chevron{transform:rotate(180deg);color:#7CB8FF} +.chip-panel.open .chip-panel-toolbar{background:rgba(30,144,255,.04);border-bottom:1px solid #27272a} +.chip-panel-body{padding:10px 16px 14px} +.chip-panel-body[hidden]{display:none!important} +.section-hint{ + font-weight:500!important;text-transform:none!important;letter-spacing:0!important; + color:#71717a!important;font-size:12px!important; +} + +/* ── Suggestions ── */ +.suggestions-section{border-top:1px solid #27272a;padding:12px 16px} +.suggestions-title,.examples-title{ + font-size:12px;font-weight:600;color:#71717a;text-transform:uppercase; + letter-spacing:.8px;margin-bottom:10px; +} +.suggestions-wrap{display:flex;flex-wrap:wrap;gap:6px} +.suggestion-chip{ + display:inline-flex;align-items:center;gap:4px;padding:5px 12px; + background:rgba(30,144,255,.08);border:1px solid rgba(30,144,255,.2);border-radius:20px; + color:#7CB8FF;font-size:12px;font-weight:500;font-family:'Inter',sans-serif; + cursor:pointer;transition:all .15s;white-space:nowrap; +} +.suggestion-chip:hover{background:rgba(30,144,255,.15);border-color:rgba(30,144,255,.35);color:#47A3FF;transform:translateY(-1px)} +.suggestion-chip.active{ + background:rgba(30,144,255,.28)!important;border-color:rgba(30,144,255,.55)!important; + color:#ffffff!important;box-shadow:0 0 0 1px rgba(30,144,255,.35); +} +.suggestion-chip.active:hover{color:#ffffff!important} +.camera-chip{border-style:dashed} +.left-stack{border-top:1px solid #27272a;padding:12px 16px} +.left-stack .section-title{ + font-size:12px;font-weight:600;color:#71717a;text-transform:uppercase; + letter-spacing:.8px;margin-bottom:10px; +} +.lora-help-text{ + margin-top:8px;padding:10px 12px;border-radius:8px; + background:rgba(30,144,255,.06);border:1px solid rgba(30,144,255,.18); + font-size:12px;line-height:1.45;color:#a1a1aa; +} +.lora-help-text b{color:#e4e4e7;font-weight:600} +.lora-demo-row{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:10px} +.lora-demo-card{background:#09090b;border:1px solid #27272a;border-radius:10px;overflow:hidden} +.lora-demo-card .demo-label{ + font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.6px; + color:#71717a;padding:6px 8px;border-bottom:1px solid #27272a; + font-family:'JetBrains Mono',monospace; +} +.lora-demo-card .demo-label.before{color:#7CB8FF} +.lora-demo-card .demo-label.after{color:#4ade80} +.lora-demo-card img,#lora-demo-before,#lora-demo-after{ + width:100%;height:200px;object-fit:contain;display:block;background:#0a0a0c; +} +.lora-demo-caption{margin-top:8px;font-size:11px;color:#71717a;line-height:1.4} +.lora-demo-caption b{color:#a1a1aa;font-weight:600} +#lora-demo-status{margin-top:6px;font-size:11px;color:#7CB8FF;font-family:'JetBrains Mono',monospace} + +/* ── Examples (hidden; removed from main UI) ── */ +.examples-section{border-top:1px solid #27272a;padding:12px 16px;display:none} +.examples-scroll{display:flex;gap:10px;overflow-x:auto;padding-bottom:8px} +.examples-scroll::-webkit-scrollbar{height:6px} +.examples-scroll::-webkit-scrollbar-track{background:#09090b;border-radius:3px} +.examples-scroll::-webkit-scrollbar-thumb{background:#27272a;border-radius:3px} +.examples-scroll::-webkit-scrollbar-thumb:hover{background:#3f3f46} +.example-card{ + flex-shrink:0;width:220px;background:#09090b;border:1px solid #27272a; + border-radius:10px;overflow:hidden;cursor:pointer;transition:all .2s ease; +} +.example-card:hover{border-color:#1E90FF;transform:translateY(-2px);box-shadow:0 4px 12px rgba(30,144,255,.15)} +.example-card.loading{opacity:.5;pointer-events:none} +.example-thumbs{display:flex;height:110px;overflow:hidden;background:#18181b} +.example-thumbs img{flex:1;object-fit:cover;min-width:0;border-bottom:1px solid #27272a} +.example-thumb-placeholder{ + flex:1;display:flex;align-items:center;justify-content:center; + background:#18181b;color:#3f3f46;font-size:11px;min-width:0; +} +.example-meta{padding:6px 10px 2px;display:flex;align-items:center;gap:5px;flex-wrap:wrap} +.example-badge{ + display:inline-flex;padding:2px 7px;background:rgba(30,144,255,.1);border-radius:4px; + font-size:10px;font-weight:600;color:#47A3FF;font-family:'JetBrains Mono',monospace;white-space:nowrap; +} +.example-lora-badge{ + display:inline-flex;padding:2px 7px;background:rgba(255,255,255,.06);border-radius:4px; + font-size:10px;font-weight:600;color:#a1a1aa;font-family:'JetBrains Mono',monospace; + white-space:nowrap;border:1px solid #27272a;max-width:130px;overflow:hidden;text-overflow:ellipsis; +} +.example-prompt-text{ + padding:4px 10px 8px;font-size:11px;color:#a1a1aa;line-height:1.4; + display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden; +} + +/* ── Right panel ── */ +.panel-card{border-bottom:1px solid #27272a} +.panel-card-title{ + padding:12px 20px;font-size:12px;font-weight:600;color:#71717a; + text-transform:uppercase;letter-spacing:.8px;border-bottom:1px solid rgba(39,39,42,.6); +} +.panel-card-body{padding:16px 20px;display:flex;flex-direction:column;gap:8px} +.modern-label{font-size:13px;font-weight:500;color:#a1a1aa;margin-bottom:4px;display:block} +.modern-textarea{ + width:100%;background:#09090b;border:1px solid #27272a;border-radius:8px; + padding:10px 14px;font-family:'Inter',sans-serif;font-size:14px;color:#e4e4e7; + resize:vertical;outline:none;min-height:42px;transition:border-color .2s; +} +/* Slightly taller than default (about +1 row) */ +#custom-prompt-input.modern-textarea{ + min-height:96px; + line-height:1.45; +} +.prompt-packs-hint, +#prompt-pack-desc{ + margin:0 0 10px;padding:10px 12px;font-size:12px;color:#a1a1aa;line-height:1.5; + background:rgba(30,144,255,.06);border:1px solid rgba(30,144,255,.18);border-radius:8px; + min-height:2.8em; +} +.prompt-packs-hint code, +#prompt-pack-desc code{ + font-family:'JetBrains Mono',monospace;font-size:11px;color:#a1a1aa; + background:#09090b;border:1px solid #27272a;border-radius:4px;padding:0 4px; +} +.prompt-pack-menu .lora-select-label{margin-bottom:8px} +.modern-textarea:focus{border-color:#1E90FF;box-shadow:0 0 0 3px rgba(30,144,255,.15)} +.modern-textarea::placeholder{color:#3f3f46} +.modern-textarea.error-flash{ + border-color:#ef4444!important;box-shadow:0 0 0 3px rgba(239,68,68,.2)!important;animation:shake .4s ease; +} +@keyframes shake{0%,100%{transform:translateX(0)}20%,60%{transform:translateX(-4px)}40%,80%{transform:translateX(4px)}} + +/* ── LoRA selector ── */ +.lora-selector-card{border-bottom:1px solid #27272a!important;background:#0f0f13!important} +.lora-selector-body{padding:14px 20px!important;background:#0f0f13!important} +/* LoRA menu title block */ +.lora-menu-heading{margin-bottom:8px} +.lora-select-label{ + font-size:12px!important;font-weight:600!important; + color:#71717a!important;-webkit-text-fill-color:#71717a!important; + text-transform:uppercase!important;letter-spacing:.8px!important; + margin-bottom:0!important;display:flex!important;align-items:center!important; + flex-wrap:wrap!important;gap:6px!important;font-family:'Inter',sans-serif!important; +} +.lora-menu-title{font:inherit;color:inherit;-webkit-text-fill-color:inherit} +.lora-select-label::before{ + content:'';display:inline-block;width:8px;height:8px; + background:#1E90FF;border-radius:50%;flex-shrink:0; +} +.lora-native-select{ + width:100%!important;background:#09090b!important; + border:1px solid #3f3f46!important;border-radius:8px!important; + padding:9px 36px 9px 14px!important; + font-family:'Inter',sans-serif!important; + font-size:13px!important;font-weight:600!important; + color:#e4e4e7!important;-webkit-text-fill-color:#e4e4e7!important; + outline:none!important;appearance:none!important;-webkit-appearance:none!important; + background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%231E90FF' d='M6 8L1 3h10z'/%3E%3C/svg%3E")!important; + background-repeat:no-repeat!important;background-position:right 12px center!important; + cursor:pointer!important;transition:border-color .2s!important;color-scheme:dark!important; +} +.lora-native-select:focus{border-color:#1E90FF!important;box-shadow:0 0 0 3px rgba(30,144,255,.15)!important} +.lora-native-select option{background:#18181b!important;color:#e4e4e7!important} + +/* ── Help tooltip on select labels ── */ +.select-help{ + position:relative;display:inline-flex;align-items:center;justify-content:center; + width:16px;height:16px;border-radius:50%;margin-left:2px;flex-shrink:0;z-index:20; + background:rgba(30,144,255,.15);border:1px solid rgba(30,144,255,.3); + color:#47A3FF!important;-webkit-text-fill-color:#47A3FF!important; + font-size:11px!important;font-weight:700!important;font-family:'Inter',sans-serif!important; + text-transform:none!important;letter-spacing:0!important;cursor:help; + line-height:1;user-select:none; +} +.select-help:hover{ + z-index:10050;background:rgba(30,144,255,.28);border-color:rgba(30,144,255,.5); + color:#7CB8FF!important;-webkit-text-fill-color:#7CB8FF!important; +} +.select-help .select-tooltip{ + visibility:hidden;opacity:0;position:absolute;left:50%;bottom:calc(100% + 10px); + transform:translateX(-50%);width:240px;padding:10px 12px;border-radius:8px; + background:#18181b;border:1px solid #3f3f46;color:#e4e4e7;font-size:12px;font-weight:500; + font-family:'Inter',sans-serif;text-transform:none;letter-spacing:0;line-height:1.45; + text-align:left;white-space:normal;box-shadow:0 8px 24px rgba(0,0,0,.55);z-index:10050; + pointer-events:none;transition:opacity .15s ease,visibility .15s ease; +} +.select-help .select-tooltip::after{ + content:'';position:absolute;top:100%;left:50%;transform:translateX(-50%); + border:6px solid transparent;border-top-color:#3f3f46; +} +.select-help:hover .select-tooltip{visibility:visible;opacity:1} +/* Keep advanced-slider tips inside the right panel (open to the right) */ +.slider-row .select-help .select-tooltip{ + left:calc(100% + 10px);right:auto;top:50%;bottom:auto; + transform:translateY(-50%);width:220px; +} +.slider-row .select-help .select-tooltip::after{ + top:50%;left:-6px;right:auto;bottom:auto;transform:translateY(-50%); + border:6px solid transparent;border-right-color:#3f3f46;border-top-color:transparent; +} + +@media (prefers-color-scheme: light){ + .lora-selector-card{background:#0f0f13!important} + .lora-selector-body{background:#0f0f13!important} + .lora-select-label{color:#71717a!important;-webkit-text-fill-color:#71717a!important} + .lora-native-select{ + background:#09090b!important;color:#e4e4e7!important; + -webkit-text-fill-color:#e4e4e7!important; + border-color:#3f3f46!important;color-scheme:dark!important; + } + .lora-native-select option{background:#18181b!important;color:#e4e4e7!important} +} + +/* ── Toast ── */ +.toast-notification{ + position:fixed;top:24px;left:50%;transform:translateX(-50%) translateY(-120%); + z-index:9999;padding:10px 24px;border-radius:10px;font-family:'Inter',sans-serif; + font-size:14px;font-weight:600;display:flex;align-items:center;gap:8px; + box-shadow:0 8px 24px rgba(0,0,0,.5); + transition:transform .35s cubic-bezier(.34,1.56,.64,1),opacity .35s ease;opacity:0;pointer-events:none; +} +.toast-notification.visible{transform:translateX(-50%) translateY(0);opacity:1;pointer-events:auto} +.toast-notification.error{background:linear-gradient(135deg,#dc2626,#b91c1c);color:#fff;border:1px solid rgba(255,255,255,.15)} +.toast-notification.warning{background:linear-gradient(135deg,#d97706,#b45309);color:#fff;border:1px solid rgba(255,255,255,.15)} +.toast-notification.info{background:linear-gradient(135deg,#2563eb,#1d4ed8);color:#fff;border:1px solid rgba(255,255,255,.15)} +.toast-notification .toast-icon{font-size:16px;line-height:1} +.toast-notification .toast-text{line-height:1.3} + +/* ── Run button ── */ +.btn-run{ + display:flex;align-items:center;justify-content:center;gap:8px;width:100%; + background:linear-gradient(135deg,#1E90FF,#1873CC);border:none;border-radius:10px; + padding:12px 24px;cursor:pointer;font-size:15px;font-weight:600;font-family:'Inter',sans-serif; + color:#ffffff!important;-webkit-text-fill-color:#ffffff!important;transition:all .2s ease;letter-spacing:-.2px; + box-shadow:0 4px 16px rgba(30,144,255,.3),inset 0 1px 0 rgba(255,255,255,.1); +} +.btn-run:hover{ + background:linear-gradient(135deg,#47A3FF,#1E90FF);transform:translateY(-1px); + box-shadow:0 6px 24px rgba(30,144,255,.45),inset 0 1px 0 rgba(255,255,255,.15); +} +.btn-run:active{transform:translateY(0);box-shadow:0 2px 8px rgba(30,144,255,.3)} +.btn-run svg{width:18px;height:18px;fill:#ffffff!important} +.btn-run svg path{fill:#ffffff!important} +#custom-run-btn,#custom-run-btn *,#custom-run-btn span,#custom-run-btn svg, +#custom-run-btn svg path,#run-btn-label,.btn-run,.btn-run *{ + color:#ffffff!important;-webkit-text-fill-color:#ffffff!important;fill:#ffffff!important; +} +body:not(.dark) .btn-run,body:not(.dark) .btn-run *,body:not(.dark) #custom-run-btn, +body:not(.dark) #custom-run-btn *{color:#ffffff!important;-webkit-text-fill-color:#ffffff!important;fill:#ffffff!important} +.dark .btn-run,.dark .btn-run *,.dark #custom-run-btn,.dark #custom-run-btn *{ + color:#ffffff!important;-webkit-text-fill-color:#ffffff!important;fill:#ffffff!important; +} +.gradio-container .btn-run,.gradio-container .btn-run *,.gradio-container #custom-run-btn, +.gradio-container #custom-run-btn *{color:#ffffff!important;-webkit-text-fill-color:#ffffff!important;fill:#ffffff!important} + +/* ── Output ── */ +.output-frame{border-bottom:1px solid #27272a;display:flex;flex-direction:column;position:relative} +.output-frame .out-body{ + flex:1;background:#09090b;display:flex;align-items:center;justify-content:center; + overflow:hidden;min-height:120px;position:relative; +} +.output-frame .out-body img{max-width:100%;max-height:460px;image-rendering:auto} +.output-frame .out-placeholder{color:#3f3f46;font-size:13px;text-align:center;padding:20px} +.out-download-btn{ + display:none;align-items:center;justify-content:center;background:rgba(30,144,255,.1); + border:1px solid rgba(30,144,255,.2);border-radius:6px;cursor:pointer;padding:3px 10px; + font-size:11px;font-weight:500;color:#7CB8FF!important;gap:4px;height:24px;transition:all .15s; +} +.out-download-btn:hover{background:rgba(30,144,255,.2);border-color:rgba(30,144,255,.35);color:#ffffff!important} +.out-download-btn.visible{display:inline-flex} +.out-download-btn svg{width:12px;height:12px;fill:#7CB8FF} +.out-download-btn:hover svg{fill:#ffffff} + +/* ── Loader ── */ +.modern-loader{ + display:none;position:absolute;top:0;left:0;right:0;bottom:0;background:rgba(9,9,11,.92); + z-index:15;flex-direction:column;align-items:center;justify-content:center;gap:16px;backdrop-filter:blur(4px); +} +.modern-loader.active{display:flex} +.modern-loader .loader-spinner{ + width:36px;height:36px;border:3px solid #27272a;border-top-color:#1E90FF; + border-radius:50%;animation:spin .8s linear infinite; +} +@keyframes spin{to{transform:rotate(360deg)}} +.modern-loader .loader-text{font-size:13px;color:#a1a1aa;font-weight:500} +.loader-bar-track{width:200px;height:4px;background:#27272a;border-radius:2px;overflow:hidden} +.loader-bar-fill{ + height:100%;background:linear-gradient(90deg,#1E90FF,#47A3FF,#1E90FF); + background-size:200% 100%;animation:shimmer 1.5s ease-in-out infinite;border-radius:2px; +} +@keyframes shimmer{0%{background-position:200% 0}100%{background-position:-200% 0}} + +/* ── Settings (collapsible) ── */ +.settings-group{ + border:1px solid #27272a;border-radius:10px;margin:12px 16px;padding:0; + overflow:visible;position:relative;z-index:6; +} +.settings-group-title{ + font-size:12px;font-weight:600;color:#71717a;text-transform:uppercase;letter-spacing:.8px; + padding:10px 16px;background:rgba(24,24,27,.5);cursor:pointer;user-select:none; + display:flex;align-items:center;justify-content:space-between;gap:8px; + transition:color .15s ease,background .15s ease;border-radius:9px; +} +.settings-group-title:hover{color:#a1a1aa;background:rgba(30,144,255,.06)} +.settings-group.open .settings-group-title{border-bottom:1px solid #27272a;border-radius:9px 9px 0 0} +.settings-chevron{ + font-size:10px;color:#71717a;transition:transform .2s ease;line-height:1;flex-shrink:0; +} +.settings-group.open .settings-chevron{transform:rotate(180deg);color:#47A3FF} +.settings-group-body{ + display:none;padding:14px 16px;flex-direction:column;gap:12px; + overflow:visible;position:relative;z-index:7;border-radius:0 0 9px 9px; +} +.settings-group.open .settings-group-body{display:flex} +.slider-row{display:flex;align-items:center;gap:10px;min-height:28px;position:relative;z-index:1} +.slider-row:hover{z-index:30} +.slider-row label{ + font-size:13px;font-weight:500;color:#a1a1aa;min-width:88px;flex-shrink:0; + display:inline-flex;align-items:center;gap:5px;position:relative; +} +.slider-row .select-help{text-transform:none;letter-spacing:0;position:relative} +.slider-row input[type="range"]{ + flex:1;-webkit-appearance:none;appearance:none;height:6px;background:#27272a; + border-radius:3px;outline:none;min-width:0; +} +.slider-row input[type="range"]::-webkit-slider-thumb{ + -webkit-appearance:none;width:16px;height:16px;background:linear-gradient(135deg,#1E90FF,#1873CC); + border-radius:50%;cursor:pointer;box-shadow:0 2px 6px rgba(30,144,255,.4);transition:transform .15s; +} +.slider-row input[type="range"]::-webkit-slider-thumb:hover{transform:scale(1.2)} +.slider-row input[type="range"]::-moz-range-thumb{ + width:16px;height:16px;background:linear-gradient(135deg,#1E90FF,#1873CC); + border-radius:50%;cursor:pointer;border:none;box-shadow:0 2px 6px rgba(30,144,255,.4); +} +.slider-row .slider-val{ + min-width:52px;text-align:right;font-family:'JetBrains Mono',monospace;font-size:12px; + font-weight:500;padding:3px 8px;background:#09090b;border:1px solid #27272a; + border-radius:6px;color:#a1a1aa;flex-shrink:0; +} +.checkbox-row{display:flex;align-items:center;gap:8px;font-size:13px;color:#a1a1aa} +.checkbox-row input[type="checkbox"]{accent-color:#1E90FF;width:16px;height:16px;cursor:pointer} +.checkbox-row label{color:#a1a1aa;font-size:13px;cursor:pointer} + +/* ── Status bar ── */ +.app-statusbar{ + background:#18181b;border-top:1px solid #27272a;padding:6px 20px; + display:flex;gap:12px;height:34px;align-items:center;font-size:12px; +} +.app-statusbar .sb-section{ + padding:0 12px;flex:1;display:flex;align-items:center;font-family:'JetBrains Mono',monospace; + font-size:12px;color:#52525b;overflow:hidden;white-space:nowrap; +} +.app-statusbar .sb-section.sb-fixed{ + flex:0 0 auto;min-width:90px;text-align:center;justify-content:center; + padding:3px 12px;background:rgba(30,144,255,.08);border-radius:6px;color:#47A3FF;font-weight:500; +} + +/* ── Footer note ── */ +.exp-note{ + padding:10px 20px;font-size:12px;color:#52525b; + border-top:1px solid #27272a;text-align:center;font-weight:500; + background:#18181b;font-family:'Inter',sans-serif; +} +.exp-note a{color:#47A3FF;text-decoration:none} +.exp-note a:hover{text-decoration:underline} + +/* ── Dark overrides ── */ +.dark .app-shell{background:#18181b} +.dark .upload-prompt-modern{background:transparent} +.dark .panel-card{background:#18181b} +.dark .settings-group{background:#18181b} +.dark .output-toolbar .out-title-label{color:#ffffff!important;-webkit-text-fill-color:#ffffff!important} +.dark .out-download-btn{color:#7CB8FF!important} +.dark .out-download-btn:hover{color:#ffffff!important} + +/* ── Scrollbars ── */ +::-webkit-scrollbar{width:8px;height:8px} +::-webkit-scrollbar-track{background:#09090b} +::-webkit-scrollbar-thumb{background:#27272a;border-radius:4px} +::-webkit-scrollbar-thumb:hover{background:#3f3f46} + +/* + * Legacy narrow-layout hacks for the DESKTOP shell only. + * When dual-skin phone is active (html[data-ui-skin=phone]), these MUST NOT run β€” + * they reordered the old single shell and looked like the β€œpre-update” phone UI. + * Real phone/embed layout lives in shell_phone.html + app_phone.css. + */ +@media(max-width:860px){ + html:not([data-ui-skin="phone"]) .app-toolbar-row{flex-direction:column} + html:not([data-ui-skin="phone"]) .app-toolbar{flex:1 1 auto;width:100%;max-width:100%;border-right:none;border-bottom:1px solid #27272a} + html:not([data-ui-skin="phone"]) .output-toolbar{flex:1 1 auto;width:100%;max-width:100%} + html:not([data-ui-skin="phone"]) .app-main-row{ + display:flex;flex-direction:column; + } + html:not([data-ui-skin="phone"]) .app-main-left, + html:not([data-ui-skin="phone"]) .app-main-right{ + display:contents; + width:100%;max-width:100%;border:none; + } + html:not([data-ui-skin="phone"]) #gallery-drop-zone{order:1;width:100%;min-height:260px;height:min(52vw,320px);max-height:320px} + html:not([data-ui-skin="phone"]) .app-main-right .output-frame, + html:not([data-ui-skin="phone"]) .output-frame{ + order:2;width:100%; + flex:0 0 auto!important;height:min(52vw,320px)!important; + min-height:220px!important;max-height:320px!important; + } + html:not([data-ui-skin="phone"]) #prompts-toolbar{order:3;width:100%} + html:not([data-ui-skin="phone"]) #panel-style{order:4;width:100%} + html:not([data-ui-skin="phone"]) #panel-camera{order:5;width:100%} + html:not([data-ui-skin="phone"]) #panel-lora{order:6;width:100%} + html:not([data-ui-skin="phone"]) .panel-prompt{order:7;width:100%} + html:not([data-ui-skin="phone"]) .lora-controls-stack{order:8;width:100%;border-top:1px solid #27272a} + html:not([data-ui-skin="phone"]) .panel-aspect{order:9;width:100%} + html:not([data-ui-skin="phone"]) .panel-size{order:10;width:100%} + html:not([data-ui-skin="phone"]) #advanced-settings{order:11;width:100%} + html:not([data-ui-skin="phone"]) .run-btn-wrap{ + order:20;width:100%; + position:sticky;bottom:0;z-index:40; + background:rgba(24,24,27,.96);border-top:1px solid #27272a; + padding:12px 16px 14px!important; + box-shadow:0 -6px 20px rgba(0,0,0,.35); + } + html:not([data-ui-skin="phone"]) .image-gallery-grid{grid-template-columns:1fr 1fr;gap:10px;padding:12px} + html:not([data-ui-skin="phone"]) .gallery-thumb-media{min-height:140px;height:clamp(140px,36vw,220px);max-height:220px} +} diff --git a/ui/app_phone.css b/ui/app_phone.css new file mode 100644 index 0000000000000000000000000000000000000000..eb7cf92d8c4fba26b8f28c7c7e9a1a976a952c43 --- /dev/null +++ b/ui/app_phone.css @@ -0,0 +1,288 @@ +/* Phone / narrow layout skin β€” activated when html[data-ui-skin="phone"] + Desktop shell is removed from the DOM by boot.js so IDs stay unique. */ + +/* Do not lock zoom: avoid touch-action/manipulation globals and maximum-scale tricks. + overflow-x only on shell, not html β€” html overflow can interfere with pinch-zoom on some browsers. */ +html[data-ui-skin="phone"] .gradio-container { + overflow-x: clip; +} +html[data-ui-skin="phone"] body { + /* allow page zoom; keep horizontal spill contained without trapping gestures */ + overflow-x: visible; +} + +html[data-ui-skin="phone"] .app-shell-phone, +html[data-ui-skin="phone"] #skin-phone .app-shell { + margin: 0 !important; + max-width: none !important; + border-radius: 0 !important; + border-left: none !important; + border-right: none !important; + min-height: 100dvh; +} + +/* App chrome header (logo/GitHub) is omitted from shell_phone.html */ + +/* Single-column stack */ +html[data-ui-skin="phone"] .phone-stack { + display: flex; + flex-direction: column; + width: 100%; + min-width: 0; + /* clear fixed Edit bar so last fields stay reachable */ + padding-bottom: calc(72px + env(safe-area-inset-bottom, 0px)); +} +html[data-ui-skin="phone"] .phone-block { + width: 100%; + box-sizing: border-box; + border-bottom: 1px solid #27272a; + background: #18181b; +} + +/* Upload: toolbar as section header + full-height gallery */ +html[data-ui-skin="phone"] .phone-upload .app-toolbar { + width: 100% !important; + max-width: 100% !important; + flex: none !important; + padding: 8px 12px !important; + border-right: none !important; + border-bottom: 1px solid #27272a; + display: flex; + flex-direction: column; + gap: 6px; + box-sizing: border-box; +} +/* Keep upload block size; only shrink the empty-state placeholder so it doesn’t scroll inside */ +html[data-ui-skin="phone"] .phone-upload #gallery-drop-zone { + width: 100% !important; + min-height: 168px !important; + height: min(38vw, 220px) !important; + max-height: 240px !important; + aspect-ratio: auto !important; + position: relative; + background: #09090b; + overflow: hidden !important; +} +/* Placeholder scale ~midway between full desktop and the previous tiny 0.52 */ +html[data-ui-skin="phone"] .phone-upload #gallery-drop-zone .upload-prompt-modern { + transform: translate(-50%, -50%) scale(0.72); + transform-origin: center center; + max-width: 92%; + pointer-events: none; +} +html[data-ui-skin="phone"] .phone-upload #gallery-drop-zone .upload-click-area { + pointer-events: auto; + padding: 12px 16px !important; + gap: 4px; + border-radius: 12px; +} +html[data-ui-skin="phone"] .phone-upload #gallery-drop-zone .upload-click-area svg { + width: 56px !important; + height: 56px !important; +} +html[data-ui-skin="phone"] .phone-upload #gallery-drop-zone .upload-main-text { + font-size: 13px !important; + margin-top: 4px !important; +} +html[data-ui-skin="phone"] .phone-upload #gallery-drop-zone .upload-sub-text { + font-size: 11px !important; + max-width: 14rem !important; + line-height: 1.35 !important; + padding: 0 6px; +} +/* Gallery with images: allow internal scroll without changing the outer block size */ +html[data-ui-skin="phone"] .phone-upload #gallery-drop-zone:has(.image-gallery-grid[style*="display: grid"]), +html[data-ui-skin="phone"] .phone-upload #gallery-drop-zone:has(.image-gallery-grid:not([style*="display: none"])) { + overflow: auto !important; +} + +/* Output right after upload */ +html[data-ui-skin="phone"] .phone-output .output-toolbar { + width: 100% !important; + max-width: 100% !important; + flex: none !important; + padding: 8px 12px !important; + border-bottom: 1px solid #27272a; + display: flex; + align-items: center; + justify-content: space-between; + box-sizing: border-box; +} +/* Same footprint as upload block for side-by-side compare when scrolling */ +html[data-ui-skin="phone"] .phone-output .output-frame { + width: 100% !important; + flex: none !important; + min-height: 168px !important; + height: min(38vw, 220px) !important; + max-height: 240px !important; + aspect-ratio: auto !important; + display: flex; + flex-direction: column; + background: #09090b; + overflow: hidden; +} +html[data-ui-skin="phone"] .phone-output .output-frame .out-body { + flex: 1 1 auto; + min-height: 0; + height: 100%; + position: relative; + display: flex; + align-items: center; + justify-content: center; +} +html[data-ui-skin="phone"] .phone-output .out-body img, +html[data-ui-skin="phone"] .phone-output .modern-out-img { + max-width: 100%; + max-height: 100%; + width: auto; + height: auto; + object-fit: contain; +} + +/* Quick prompts β€” whole block capped; open panels scroll inside so N open tables + don’t keep growing the page past the fixed Edit bar */ +html[data-ui-skin="phone"] .phone-prompts { + max-height: min(42vh, 320px); + display: flex; + flex-direction: column; + min-height: 0; + overflow-x: hidden; + overflow-y: auto; + -webkit-overflow-scrolling: touch; +} +html[data-ui-skin="phone"] .phone-prompts .prompts-toolbar { + width: 100%; + padding: 8px 12px; + box-sizing: border-box; + flex: 0 0 auto; + position: sticky; + top: 0; + z-index: 2; + background: #18181b; +} +html[data-ui-skin="phone"] .phone-prompts .chip-panel { + width: 100%; + border-top: 1px solid #27272a; + flex: 0 0 auto; +} +html[data-ui-skin="phone"] .phone-prompts .chip-panel-body { + max-height: min(22vh, 160px); + overflow-y: auto; + -webkit-overflow-scrolling: touch; + overscroll-behavior: contain; +} + +/* Prompt β€” 16px inputs reduce iOS focus zoom */ +html[data-ui-skin="phone"] .phone-prompt .panel-card { + border: none !important; + background: transparent !important; +} +html[data-ui-skin="phone"] .phone-prompt .panel-card-body { + padding: 12px 14px !important; +} +html[data-ui-skin="phone"] .phone-prompt .modern-textarea { + min-height: 110px; + font-size: 16px !important; +} + +/* Menus: pack + aspect + size */ +html[data-ui-skin="phone"] .phone-menus { + padding: 0 0 4px; +} +html[data-ui-skin="phone"] .phone-menus .prompt-pack-menu, +html[data-ui-skin="phone"] .phone-menus .lora-selector-card { + border: none !important; + border-bottom: 1px solid #27272a !important; + background: transparent !important; + margin: 0 !important; +} +html[data-ui-skin="phone"] .phone-menus .prompt-pack-menu, +html[data-ui-skin="phone"] .phone-menus .lora-selector-body { + padding: 12px 14px !important; +} +html[data-ui-skin="phone"] .phone-menus .lora-native-select, +html[data-ui-skin="phone"] .phone-lora .lora-native-select { + font-size: 16px !important; /* iOS zoom guard */ +} + +/* LoRA */ +html[data-ui-skin="phone"] .phone-lora { + padding: 12px 14px 16px; +} +html[data-ui-skin="phone"] .phone-lora .left-stack { + border-top: none; + padding: 0; +} +/* Demos hidden until a LoRA is selected (class toggled in lora_demo.js) */ +html[data-ui-skin="phone"]:not(.has-lora-selected) #lora-demo-row, +html[data-ui-skin="phone"]:not(.has-lora-selected) #lora-demo-status, +html[data-ui-skin="phone"]:not(.has-lora-selected) .lora-demo-caption { + display: none !important; +} + +/* Advanced + run */ +html[data-ui-skin="phone"] .phone-advanced .settings-group { + border: none !important; + border-radius: 0 !important; + margin: 0 !important; +} +/* + * Fixed Edit bar. On HF, transform/filter on Gradio ancestors break position:fixed + * (bar sticks to a nested box, not the screen). boot.js ports .phone-run to + * document.body (.phone-run--ported) so fixed = real viewport β€” same as embeds. + */ +html[data-ui-skin="phone"] .phone-run, +html[data-ui-skin="phone"] body > .phone-run, +body > .phone-run.phone-run--ported { + position: fixed !important; + left: 0 !important; + right: 0 !important; + bottom: 0 !important; + top: auto !important; + z-index: 2147483000 !important; /* above typical HF/Gradio chrome */ + width: 100% !important; + max-width: 100vw !important; + box-sizing: border-box !important; + padding: 10px 14px !important; + margin: 0 !important; + background: rgba(24, 24, 27, 0.97) !important; + border-top: 1px solid #27272a !important; + box-shadow: 0 -8px 28px rgba(0, 0, 0, 0.5) !important; + transform: none !important; + filter: none !important; + contain: none !important; +} +html[data-ui-skin="phone"] .phone-run .run-btn-wrap { + padding: 0 !important; +} +html[data-ui-skin="phone"] .phone-run .btn-run { + width: 100%; + min-height: 48px; + font-size: 15px; +} +html[data-ui-skin="phone"] .phone-footer { + padding-bottom: 8px; +} + +html[data-ui-skin="phone"] .phone-footer .exp-note { + padding: 10px 14px; + font-size: 11px; +} +html[data-ui-skin="phone"] .phone-footer .app-statusbar { + padding: 6px 12px; + height: auto; + min-height: 34px; + flex-wrap: wrap; +} + +@supports (padding: env(safe-area-inset-bottom)) { + html[data-ui-skin="phone"] .phone-run, + html[data-ui-skin="phone"] body > .phone-run, + body > .phone-run.phone-run--ported { + padding-bottom: calc(10px + env(safe-area-inset-bottom)) !important; + } +} + +/* Hide unused skin before boot removes it (avoid flash of both) */ +#skin-phone[hidden] { display: none !important; } +#skin-desktop[hidden] { display: none !important; } diff --git a/ui/boot.js b/ui/boot.js new file mode 100644 index 0000000000000000000000000000000000000000..62c09ea4e933b891b07358b3c36cc841b8ccc335 --- /dev/null +++ b/ui/boot.js @@ -0,0 +1,158 @@ +() => { + /** + * Dual-skin boot: pick desktop vs phone layout, keep a single set of IDs in the DOM. + * + * Rules (first match wins for force flags): + * ?ui=phone | ?ui=mobile β†’ phone + * ?ui=desktop | ?ui=pc β†’ desktop + * Mobile / phone UA β†’ phone (HF embeds often report a WIDE iframe width) + * max-width ≀ 768px β†’ phone + * else β†’ desktop + * + * Unused skin is removed so getElementById stays unambiguous for gallery.js. + */ + function wantPhoneUI() { + try { + var q = new URLSearchParams(window.location.search || ""); + var force = (q.get("ui") || "").toLowerCase(); + if (force === "phone" || force === "mobile") return true; + if (force === "desktop" || force === "pc") return false; + } catch (e) {} + + // Real phones/tablets in portrait-ish embeds: don't trust iframe CSS width alone + try { + var ua = navigator.userAgent || ""; + if (/Android.+Mobile|iPhone|iPod|webOS|BlackBerry|IEMobile|Opera Mini/i.test(ua)) { + return true; + } + // iPad / Android tablet β€” treat as phone layout (single column) + if (/iPad|Android(?!.*Mobile)|Tablet/i.test(ua)) { + return true; + } + if (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1) { + return true; // iPadOS desktop UA + } + } catch (e2) {} + + try { + if (window.matchMedia("(max-width: 768px)").matches) return true; + // Very short + narrow-ish viewport (mobile browser chrome) + if (window.matchMedia("(max-width: 900px) and (max-height: 900px) and (pointer: coarse)").matches) { + return true; + } + } catch (e3) { + if ((window.innerWidth || 1024) <= 768) return true; + } + return false; + } + + /** + * Gradio / Spaces often inject maximum-scale=1 or user-scalable=no, which kills + * pinch-zoom. Restore a viewport that allows zoom (a11y + your request). + */ + function ensureZoomableViewport() { + try { + var allow = + "width=device-width, initial-scale=1, viewport-fit=cover, " + + "minimum-scale=0.5, maximum-scale=5, user-scalable=yes"; + var metas = document.querySelectorAll('meta[name="viewport"]'); + if (!metas || !metas.length) { + var m = document.createElement("meta"); + m.setAttribute("name", "viewport"); + m.setAttribute("content", allow); + (document.head || document.documentElement).appendChild(m); + return; + } + for (var i = 0; i < metas.length; i++) { + metas[i].setAttribute("content", allow); + } + } catch (e) {} + } + + /** + * HF / Gradio wrap the app in transformed/overflow ancestors, so position:fixed + * on .phone-run is relative to that box (often off-screen). Moving the bar to + * document.body makes fixed = real viewport. Embeds often don't have those + * ancestors β€” which is why floating Edit already worked there. + */ + function pinPhoneRunBar() { + try { + if (window.__qwenUiSkin !== "phone") return; + var bar = document.querySelector(".phone-run"); + if (!bar || !document.body) return; + if (bar.parentNode === document.body) { + bar.classList.add("phone-run--ported"); + return; + } + // Marker so we can leave a spacer if needed (stack already has padding-bottom) + bar.setAttribute("data-ported", "1"); + bar.classList.add("phone-run--ported"); + document.body.appendChild(bar); + } catch (e) {} + } + + function activate() { + var phone = wantPhoneUI(); + var desktop = document.getElementById("skin-desktop"); + var phoneEl = document.getElementById("skin-phone"); + + // Skins not in DOM yet + if (!desktop && !phoneEl) return false; + + // Always allow pinch/zoom β€” do not lock scale on phone or desktop + ensureZoomableViewport(); + + if (phone) { + if (desktop && desktop.parentNode) desktop.parentNode.removeChild(desktop); + if (phoneEl) { + phoneEl.hidden = false; + phoneEl.removeAttribute("hidden"); + phoneEl.style.display = ""; + } + document.documentElement.setAttribute("data-ui-skin", "phone"); + try { document.body && document.body.setAttribute("data-ui-skin", "phone"); } catch (e4) {} + window.__qwenUiSkin = "phone"; + pinPhoneRunBar(); + // DOM may still be settling on HF + setTimeout(pinPhoneRunBar, 100); + setTimeout(pinPhoneRunBar, 500); + setTimeout(pinPhoneRunBar, 1500); + } else { + // If we previously ported the bar, remove orphan + try { + var orphan = document.querySelector("body > .phone-run"); + if (orphan) orphan.parentNode.removeChild(orphan); + } catch (e6) {} + if (phoneEl && phoneEl.parentNode) phoneEl.parentNode.removeChild(phoneEl); + if (desktop) { + desktop.hidden = false; + desktop.removeAttribute("hidden"); + desktop.style.display = ""; + } + document.documentElement.setAttribute("data-ui-skin", "desktop"); + try { document.body && document.body.setAttribute("data-ui-skin", "desktop"); } catch (e5) {} + window.__qwenUiSkin = "desktop"; + } + return true; + } + + // Expose for gallery.js / lora_demo.js if boot load order is flaky + window.__qwenActivateUiSkin = activate; + window.__qwenWantPhoneUI = wantPhoneUI; + window.__qwenEnsureZoomableViewport = ensureZoomableViewport; + window.__qwenPinPhoneRunBar = pinPhoneRunBar; + + function tryActivate(n) { + // Fix zoom even before skins appear (Gradio may set a locked viewport early) + ensureZoomableViewport(); + if (activate()) { + // Gradio sometimes rewrites viewport after load β€” re-assert zoom a few times + setTimeout(ensureZoomableViewport, 200); + setTimeout(ensureZoomableViewport, 1000); + setTimeout(ensureZoomableViewport, 3000); + return; + } + if (n < 60) setTimeout(function () { tryActivate(n + 1); }, 50); + } + tryActivate(0); +} diff --git a/ui/gallery.js b/ui/gallery.js new file mode 100644 index 0000000000000000000000000000000000000000..0703ee5317b29f60dfd29567cd7418357f07d354 --- /dev/null +++ b/ui/gallery.js @@ -0,0 +1,736 @@ +() => { +function init() { + if (window.__qwenInitDone) return; + + // Dual-skin: ensure boot ran (HF load order can race). Removes unused shell. + if (typeof window.__qwenActivateUiSkin === 'function' && !window.__qwenUiSkin) { + window.__qwenActivateUiSkin(); + } + if (!window.__qwenUiSkin) { + const dual = document.getElementById('skin-desktop') || document.getElementById('skin-phone'); + if (dual) { setTimeout(init, 50); return; } + } + + const galleryGrid = document.getElementById('image-gallery-grid'); + const dropZone = document.getElementById('gallery-drop-zone'); + const uploadPrompt = document.getElementById('upload-prompt'); + const uploadClick = document.getElementById('upload-click-area'); + const fileInput = document.getElementById('custom-file-input'); + const btnUpload = document.getElementById('tb-upload'); + const btnRemove = document.getElementById('tb-remove'); + const btnClear = document.getElementById('tb-clear'); + const promptInput = document.getElementById('custom-prompt-input'); + const loraSelect = document.getElementById('custom-lora-select'); + const packSelect = document.getElementById('custom-prompt-pack-select'); + const aspectSelect = document.getElementById('custom-aspect-select'); + const sizeSelect = document.getElementById('custom-size-select'); + const runBtnEl = document.getElementById('custom-run-btn'); + const imgCountTb = document.getElementById('tb-image-count'); + const imgCountSb = document.getElementById('sb-image-count'); + + if (!galleryGrid || !fileInput || !dropZone) { setTimeout(init, 250); return; } + window.__qwenInitDone = true; + // HF: re-pin floating Edit after UI is live (transform ancestors break fixed) + if (typeof window.__qwenPinPhoneRunBar === 'function') { + window.__qwenPinPhoneRunBar(); + setTimeout(window.__qwenPinPhoneRunBar, 300); + } + + window.__toggleAdvancedSettings = function() { + const group = document.getElementById('advanced-settings'); + const toggle = document.getElementById('advanced-settings-toggle'); + if (!group) return; + const open = group.classList.toggle('open'); + if (toggle) toggle.setAttribute('aria-expanded', open ? 'true' : 'false'); + }; + + let images = []; + window.__uploadedImages = images; + let selectedIdx = -1; + let toastTimer = null; + + const IMAGE_SIZE_BASE = {'x-small':512,'small':768,'normal':1024,'large':1280,'x-large':1536}; + const MAX_SOURCE_SIDE = 4000; + const SIZE_LABELS = { + original: 'Original (source pixels)', + 'x-small': 'X-Small (thumbnail)', + small: 'Small', + normal: 'Normal', + large: 'Large', + 'x-large': 'X-Large', + }; + + function round8(n) { return Math.max(8, Math.floor(Number(n) / 8) * 8); } + function capSourceDims(w, h) { + const longSide = Math.max(w, h); + if (!longSide || longSide <= MAX_SOURCE_SIDE) return [w, h]; + const s = MAX_SOURCE_SIDE / longSide; + return [Math.max(1, Math.round(w * s)), Math.max(1, Math.round(h * s))]; + } + function computeOutputDims(srcW, srcH, aspect, size) { + if (!srcW || !srcH) return null; + if (size === 'original') { + let [w, h] = capSourceDims(srcW, srcH); + const longSide = Math.max(w, h); + if (aspect === 'square') return [round8(longSide), round8(longSide)]; + if (aspect === 'wide') return [round8(longSide), round8(longSide * 9 / 16)]; + if (aspect === 'portrait') return [round8(longSide * 9 / 16), round8(longSide)]; + return [round8(w), round8(h)]; + } + const base = IMAGE_SIZE_BASE[size] || 1024; + const scale = base / 1024; + if (aspect === 'square') return [round8(base), round8(base)]; + if (aspect === 'wide') return [round8(1344 * scale), round8(768 * scale)]; + if (aspect === 'portrait') return [round8(768 * scale), round8(1344 * scale)]; + if (srcW >= srcH) { + const tw = base; + return [round8(tw), round8(tw * srcH / srcW)]; + } + const th = base; + return [round8(th * srcW / srcH), round8(th)]; + } + function formatDims(w, h) { return w + ' \u00d7 ' + h; } + function getAspect() { return aspectSelect ? aspectSelect.value : 'original'; } + function getSize() { return sizeSelect ? sizeSelect.value : 'normal'; } + + function updatePredictedSizeUI() { + const outEl = document.getElementById('output-pred-dims'); + const sizeEl = document.getElementById('size-pred-dims'); + const first = images.length ? images[0] : null; + const srcW = first && first.w ? first.w : 0; + const srcH = first && first.h ? first.h : 0; + const hasSrc = srcW > 0 && srcH > 0; + const aspect = getAspect(); + const size = getSize(); + + // Dynamic size-menu labels (show predicted WΓ—H when image #1 is known) + if (sizeSelect) { + Array.from(sizeSelect.options).forEach(opt => { + const key = opt.value; + const baseLabel = SIZE_LABELS[key] || key; + if (!hasSrc) { + if (key === 'original') opt.textContent = baseLabel; + else if (key === 'x-small') opt.textContent = 'X-Small (thumbnail \u00b7 512)'; + else if (key === 'small') opt.textContent = 'Small (768)'; + else if (key === 'normal') opt.textContent = 'Normal (1024)'; + else if (key === 'large') opt.textContent = 'Large (1280)'; + else if (key === 'x-large') opt.textContent = 'X-Large (1536)'; + else opt.textContent = baseLabel; + return; + } + const dims = computeOutputDims(srcW, srcH, aspect, key); + if (dims) opt.textContent = baseLabel + ' \u2014 ' + formatDims(dims[0], dims[1]); + else opt.textContent = baseLabel; + }); + } + + if (!hasSrc) { + if (outEl) { outEl.hidden = true; outEl.textContent = ''; } + if (sizeEl) { sizeEl.hidden = true; sizeEl.textContent = ''; } + return; + } + const pred = computeOutputDims(srcW, srcH, aspect, size); + if (!pred) return; + const txt = formatDims(pred[0], pred[1]); + if (outEl) { outEl.hidden = false; outEl.textContent = txt; } + if (sizeEl) { + sizeEl.hidden = false; + sizeEl.textContent = 'Predicted output: ' + txt + + (size === 'original' && Math.max(srcW, srcH) > MAX_SOURCE_SIDE + ? ' (source capped at ' + MAX_SOURCE_SIDE + ' long side)' + : ''); + } + } + + /* ── Force dark + blue styles on elements that browsers may override ── */ + function enforceDarkStyles() { + document.querySelectorAll('.lora-selector-card').forEach(el => { + el.style.setProperty('background','#0f0f13','important'); + }); + document.querySelectorAll('.lora-selector-body').forEach(el => { + el.style.setProperty('background','#0f0f13','important'); + }); + document.querySelectorAll('.lora-select-label').forEach(el => { + el.style.setProperty('color','#71717a','important'); + el.style.setProperty('-webkit-text-fill-color','#71717a','important'); + }); + [ + document.getElementById('custom-lora-select'), + document.getElementById('custom-aspect-select'), + document.getElementById('custom-size-select'), + ].forEach(sel => { + if (!sel) return; + sel.style.setProperty('background-color','#09090b','important'); + sel.style.setProperty('color','#e4e4e7','important'); + sel.style.setProperty('-webkit-text-fill-color','#e4e4e7','important'); + sel.style.setProperty('border-color','#3f3f46','important'); + }); + + const ghBtn = document.querySelector('.gh-btn'); + if (ghBtn) { + ghBtn.style.setProperty('background','#1E90FF','important'); + ghBtn.style.setProperty('color','#ffffff','important'); + ghBtn.style.setProperty('-webkit-text-fill-color','#ffffff','important'); + ghBtn.style.setProperty('border-color','rgba(255,255,255,.18)','important'); + ghBtn.style.setProperty('box-shadow','0 2px 10px rgba(30,144,255,.45)','important'); + const svg = ghBtn.querySelector('svg'); + if (svg) svg.style.setProperty('fill','#ffffff','important'); + const span = ghBtn.querySelector('span'); + if (span) { + span.style.setProperty('color','#ffffff','important'); + span.style.setProperty('-webkit-text-fill-color','#ffffff','important'); + } + } + + const shell = document.querySelector('.app-shell'); + const header = document.querySelector('.app-header'); + const toolbar = document.querySelector('.app-toolbar'); + if (shell) shell.style.setProperty('background','#18181b','important'); + if (header) header.style.setProperty('background','#18181b','important'); + if (toolbar) toolbar.style.setProperty('background','#18181b','important'); + } + + enforceDarkStyles(); + setInterval(enforceDarkStyles, 1000); + + const ghBtn = document.querySelector('.gh-btn'); + if (ghBtn) { + ghBtn.addEventListener('mouseenter', () => { + ghBtn.style.setProperty('background','#47A3FF','important'); + ghBtn.style.setProperty('color','#ffffff','important'); + ghBtn.style.setProperty('-webkit-text-fill-color','#ffffff','important'); + ghBtn.style.setProperty('transform','translateY(-1px)','important'); + ghBtn.style.setProperty('box-shadow','0 5px 18px rgba(30,144,255,.6)','important'); + }); + ghBtn.addEventListener('mouseleave', () => { + ghBtn.style.setProperty('background','#1E90FF','important'); + ghBtn.style.setProperty('color','#ffffff','important'); + ghBtn.style.setProperty('-webkit-text-fill-color','#ffffff','important'); + ghBtn.style.setProperty('transform','translateY(0)','important'); + ghBtn.style.setProperty('box-shadow','0 2px 10px rgba(30,144,255,.45)','important'); + }); + ghBtn.addEventListener('mousedown', () => { + ghBtn.style.setProperty('background','#1873CC','important'); + ghBtn.style.setProperty('transform','translateY(0)','important'); + }); + ghBtn.addEventListener('mouseup', () => { + ghBtn.style.setProperty('background','#47A3FF','important'); + }); + } + + function showToast(message, type) { + let toast = document.getElementById('app-toast'); + if (!toast) { + toast = document.createElement('div'); + toast.id = 'app-toast'; + toast.className = 'toast-notification'; + toast.innerHTML = ''; + document.body.appendChild(toast); + } + const icon = toast.querySelector('.toast-icon'); + const text = toast.querySelector('.toast-text'); + toast.className = 'toast-notification ' + (type || 'error'); + icon.textContent = type === 'warning' ? '\u26A0' : type === 'info' ? '\u2139' : '\u2717'; + text.textContent = message; + if (toastTimer) clearTimeout(toastTimer); + void toast.offsetWidth; + toast.classList.add('visible'); + toastTimer = setTimeout(() => toast.classList.remove('visible'), 3500); + } + window.__showToast = showToast; + + function flashPromptError() { + if (!promptInput) return; + promptInput.classList.add('error-flash'); + promptInput.focus(); + setTimeout(() => promptInput.classList.remove('error-flash'), 800); + } + + function setGradioValue(containerId, value) { + const container = document.getElementById(containerId); + if (!container) return; + container.querySelectorAll('input, textarea').forEach(el => { + if (el.type === 'file' || el.type === 'range' || el.type === 'checkbox') return; + const proto = el.tagName === 'TEXTAREA' ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype; + const ns = Object.getOwnPropertyDescriptor(proto, 'value'); + if (ns && ns.set) { + ns.set.call(el, value); + el.dispatchEvent(new Event('input', {bubbles:true, composed:true})); + el.dispatchEvent(new Event('change', {bubbles:true, composed:true})); + } + }); + } + window.__setGradioValue = setGradioValue; + + function syncImagesToGradio() { + window.__uploadedImages = images; + const b64Array = images.map(img => img.b64); + setGradioValue('hidden-images-b64', JSON.stringify(b64Array)); + updateCounts(); + } + function syncPromptToGradio() { + if (promptInput) setGradioValue('prompt-gradio-input', promptInput.value); + } + function syncLoraToGradio() { + if (!loraSelect) return; + const container = document.getElementById('gradio-lora'); + if (!container) return; + container.querySelectorAll('input').forEach(el => { + const ns = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value'); + if (ns && ns.set) { + ns.set.call(el, loraSelect.value); + el.dispatchEvent(new Event('input', {bubbles:true, composed:true})); + el.dispatchEvent(new Event('change', {bubbles:true, composed:true})); + } + }); + } + function syncPromptPackToGradio() { + if (!packSelect) return; + const container = document.getElementById('gradio-prompt-pack'); + if (!container) return; + container.querySelectorAll('input').forEach(el => { + const ns = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value'); + if (ns && ns.set) { + ns.set.call(el, packSelect.value); + el.dispatchEvent(new Event('input', {bubbles:true, composed:true})); + el.dispatchEvent(new Event('change', {bubbles:true, composed:true})); + } + }); + } + function syncAspectToGradio() { + if (!aspectSelect) return; + const container = document.getElementById('gradio-aspect'); + if (!container) return; + container.querySelectorAll('input').forEach(el => { + const ns = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value'); + if (ns && ns.set) { + ns.set.call(el, aspectSelect.value); + el.dispatchEvent(new Event('input', {bubbles:true, composed:true})); + el.dispatchEvent(new Event('change', {bubbles:true, composed:true})); + } + }); + } + function syncSizeToGradio() { + if (!sizeSelect) return; + const container = document.getElementById('gradio-size'); + if (!container) return; + container.querySelectorAll('input').forEach(el => { + const ns = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value'); + if (ns && ns.set) { + ns.set.call(el, sizeSelect.value); + el.dispatchEvent(new Event('input', {bubbles:true, composed:true})); + el.dispatchEvent(new Event('change', {bubbles:true, composed:true})); + } + }); + } + + const MAX_IMAGES = 2; + + function updateCounts() { + const n = images.length; + const txt = n > 0 ? n + ' image' + (n > 1 ? 's' : '') + ' (max ' + MAX_IMAGES + ')' : 'No images'; + if (imgCountTb) imgCountTb.textContent = n > 0 ? n + ' image' + (n > 1 ? 's' : '') : 'No images'; + if (imgCountSb) imgCountSb.textContent = n > 0 ? n + ' / ' + MAX_IMAGES + ' images' : 'No images uploaded'; + } + + function addImage(b64, name) { + if (images.length >= MAX_IMAGES) { + showToast('Maximum ' + MAX_IMAGES + ' images. Remove one to add another.', 'warning'); + return false; + } + const entry = {id: Date.now() + Math.random(), b64, name, w: 0, h: 0}; + images.push(entry); + renderGallery(); syncImagesToGradio(); updatePredictedSizeUI(); + const probe = new Image(); + probe.onload = () => { + entry.w = probe.naturalWidth || 0; + entry.h = probe.naturalHeight || 0; + renderGallery(); + updatePredictedSizeUI(); + }; + probe.onerror = () => { updatePredictedSizeUI(); }; + probe.src = b64; + return true; + } + window.__addImage = addImage; + + function removeImage(idx) { + images.splice(idx, 1); + if (selectedIdx === idx) selectedIdx = -1; + else if (selectedIdx > idx) selectedIdx--; + renderGallery(); syncImagesToGradio(); updatePredictedSizeUI(); + } + + function clearAll() { + images = []; window.__uploadedImages = images; selectedIdx = -1; + renderGallery(); syncImagesToGradio(); updatePredictedSizeUI(); + } + window.__clearAll = clearAll; + + function renderGallery() { + if (images.length === 0) { + galleryGrid.innerHTML = ''; galleryGrid.style.display = 'none'; + if (uploadPrompt) uploadPrompt.style.display = ''; + updatePredictedSizeUI(); + updateCounts(); + return; + } + if (uploadPrompt) uploadPrompt.style.display = 'none'; + galleryGrid.style.display = 'grid'; + let html = ''; + images.forEach((img, i) => { + const sel = i === selectedIdx ? ' selected' : ''; + const dimTxt = (img.w && img.h) ? formatDims(img.w, img.h) : '\u2026'; + const role = i === 0 ? 'Main' : 'Ref'; + html += ''; + }); + if (images.length < MAX_IMAGES) { + html += ''; + } + galleryGrid.innerHTML = html; + galleryGrid.querySelectorAll('.gallery-thumb').forEach(thumb => { + thumb.addEventListener('click', (e) => { + if (e.target.closest('.thumb-remove')) return; + selectedIdx = (selectedIdx === parseInt(thumb.dataset.idx)) ? -1 : parseInt(thumb.dataset.idx); + renderGallery(); + }); + }); + galleryGrid.querySelectorAll('.thumb-remove').forEach(btn => { + btn.addEventListener('click', (e) => { e.stopPropagation(); removeImage(parseInt(btn.dataset.remove)); }); + }); + const addCard = document.getElementById('gallery-add-card'); + if (addCard) addCard.addEventListener('click', () => fileInput.click()); + updateCounts(); + } + + function processFiles(files) { + const list = Array.from(files).filter(f => f && f.type && f.type.startsWith('image/')); + if (!list.length) return; + let skipped = 0; + list.forEach(file => { + if (images.length >= MAX_IMAGES) { skipped++; return; } + const reader = new FileReader(); + reader.onload = (e) => addImage(e.target.result, file.name); + reader.readAsDataURL(file); + }); + if (skipped > 0) { + showToast('Maximum ' + MAX_IMAGES + ' images. Extra file(s) were not added.', 'warning'); + } + } + + fileInput.addEventListener('change', (e) => { processFiles(e.target.files); e.target.value = ''; }); + if (uploadClick) uploadClick.addEventListener('click', () => fileInput.click()); + if (btnUpload) btnUpload.addEventListener('click', () => fileInput.click()); + if (btnRemove) btnRemove.addEventListener('click', () => { if (selectedIdx >= 0) removeImage(selectedIdx); }); + if (btnClear) btnClear.addEventListener('click', clearAll); + + dropZone.addEventListener('dragover', (e) => { e.preventDefault(); dropZone.classList.add('drag-over'); }); + dropZone.addEventListener('dragleave', (e) => { e.preventDefault(); dropZone.classList.remove('drag-over'); }); + dropZone.addEventListener('drop', (e) => { + e.preventDefault(); dropZone.classList.remove('drag-over'); + if (e.dataTransfer.files.length) processFiles(e.dataTransfer.files); + }); + + if (promptInput) promptInput.addEventListener('input', syncPromptToGradio); + if (loraSelect) loraSelect.addEventListener('change', () => { + // Original path: sync Gradio; lora_demo.js also listens and updates before/after demos + syncLoraToGradio(); + if (window.__setLoraDemos) window.__setLoraDemos(loraSelect.value); + }); + if (window.__setLoraDemos) setTimeout(() => window.__setLoraDemos(loraSelect ? loraSelect.value : 'none'), 300); + + function updatePromptPackDescription() { + const descEl = document.getElementById('prompt-pack-desc'); + if (!descEl || !packSelect) return; + const opt = packSelect.options[packSelect.selectedIndex]; + const raw = (opt && opt.getAttribute('data-description')) || ''; + const fallbackNone = + 'Prompt Packs add variety the base model struggles with in specific areas. Choose a pack in the menu below, or trigger one in the prompt (e.g. [[pack]]).'; + descEl.textContent = raw.trim() || ( + !packSelect.value || packSelect.value === 'none' + ? fallbackNone + : ('Pack "' + packSelect.value + '" will apply on Run (menu overrides prompt tags).') + ); + } + if (packSelect) { + packSelect.addEventListener('change', () => { + syncPromptPackToGradio(); + updatePromptPackDescription(); + }); + updatePromptPackDescription(); + } + + if (aspectSelect) aspectSelect.addEventListener('change', () => { syncAspectToGradio(); updatePredictedSizeUI(); }); + if (sizeSelect) sizeSelect.addEventListener('change', () => { syncSizeToGradio(); updatePredictedSizeUI(); }); + updatePredictedSizeUI(); + + + /* ── Toggle quick-prompt chips (amend / remove) ── */ + const activeChips = new Map(); + const CAMERA_MUTEX_GROUPS = [ + ['45-right', '45-left'], + ['front-right', 'front-left', 'back-right', 'back-left'], + ['profile-right', 'profile-left'], + ['zoom-in', 'zoom-out'], + ['top-down', 'low-angle'], + ]; + function normalizeSpaces(s) { + return (s || '').replace(/[ \t]+/g, ' ').replace(/\n{3,}/g, '\n\n').trim(); + } + function appendPhrase(phrase) { + if (!promptInput) return; + let cur = promptInput.value || ''; + const p = (phrase || '').trim(); + if (!p) return; + if (!cur.trim()) promptInput.value = p; + else { + const needsSpace = !/\s$/.test(cur); + promptInput.value = cur + (needsSpace ? ' ' : '') + p; + } + syncPromptToGradio(); + } + function removePhrase(phrase) { + if (!promptInput) return; + const p = (phrase || '').trim(); + if (!p) return; + const re = new RegExp('\\s*' + p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\s*', 'g'); + promptInput.value = normalizeSpaces((promptInput.value || '').replace(re, ' ')); + syncPromptToGradio(); + } + function cameraMutexPeers(chipId) { + for (const group of CAMERA_MUTEX_GROUPS) { + if (group.includes(chipId)) return group.filter(id => id !== chipId); + } + return []; + } + function deactivateChipById(chipId) { + const btn = document.querySelector('.suggestion-chip[data-chip-id="' + chipId + '"]'); + if (!btn || !btn.classList.contains('active')) return; + const phrase = activeChips.get(chipId) || btn.getAttribute('data-prompt') || ''; + if (phrase) removePhrase(phrase); + btn.classList.remove('active'); + activeChips.delete(chipId); + } + function wireChips(root, opts) { + opts = opts || {}; + if (!root) return; + root.querySelectorAll('.suggestion-chip[data-prompt]').forEach(btn => { + btn.addEventListener('click', () => { + const id = btn.getAttribute('data-chip-id') || btn.textContent.trim(); + const phrase = btn.getAttribute('data-prompt') || ''; + if (btn.classList.contains('active')) { + removePhrase(phrase); + btn.classList.remove('active'); + activeChips.delete(id); + showToast('Removed from prompt', 'info'); + } else { + if (opts.cameraMutex) cameraMutexPeers(id).forEach(deactivateChipById); + appendPhrase(phrase); + btn.classList.add('active'); + activeChips.set(id, phrase); + showToast('Added to prompt', 'info'); + } + }); + }); + } + wireChips(document.getElementById('style-chips')); + wireChips(document.getElementById('camera-chips'), { cameraMutex: true }); + wireChips(document.getElementById('lora-chips')); + + /* ── Per-panel chip toolbars + master Open/Close + Clear Prompts ── */ + const CHIP_HINT = '(click to add Β· again to remove)'; + const chipPanels = Array.from(document.querySelectorAll('.chip-panel[data-panel]')); + const btnOpenPrompts = document.getElementById('tb-open-prompts'); + const btnOpenPromptsLabel = document.getElementById('tb-open-prompts-label'); + const btnClearPrompts = document.getElementById('tb-clear-prompts'); + + function setPanelOpen(panel, open) { + if (!panel) return; + const toggle = panel.querySelector('.chip-panel-toolbar'); + const body = panel.querySelector('.chip-panel-body'); + const hint = panel.querySelector('.chip-panel-hint'); + panel.classList.toggle('open', open); + if (body) body.hidden = !open; + if (toggle) { + toggle.setAttribute('aria-expanded', open ? 'true' : 'false'); + // Closed: full hint as native tooltip. Open: clear title so visible hint is the instruction. + toggle.title = open ? '' : CHIP_HINT; + } + if (hint) hint.hidden = !open; + } + function isPanelOpen(panel) { + return panel && panel.classList.contains('open'); + } + function anyPanelOpen() { + return chipPanels.some(isPanelOpen); + } + function allPanelsOpen() { + return chipPanels.length > 0 && chipPanels.every(isPanelOpen); + } + function syncMasterOpenButton() { + const open = allPanelsOpen(); + if (btnOpenPrompts) { + btnOpenPrompts.setAttribute('aria-expanded', open ? 'true' : 'false'); + btnOpenPrompts.classList.toggle('active', open || anyPanelOpen()); + } + if (btnOpenPromptsLabel) { + const phone = window.__qwenUiSkin === 'phone'; + btnOpenPromptsLabel.textContent = open + ? (phone ? 'Close' : 'Close Prompts') + : (phone ? 'Open' : 'Open Prompts'); + } + } + function setAllPanelsOpen(open) { + chipPanels.forEach(p => setPanelOpen(p, open)); + syncMasterOpenButton(); + } + chipPanels.forEach(panel => { + const toggle = panel.querySelector('.chip-panel-toolbar'); + if (!toggle) return; + setPanelOpen(panel, false); // start closed; title bar always visible + toggle.addEventListener('click', () => { + setPanelOpen(panel, !isPanelOpen(panel)); + syncMasterOpenButton(); + }); + }); + if (btnOpenPrompts) { + btnOpenPrompts.addEventListener('click', () => { + // If all open β†’ close all; otherwise open all + setAllPanelsOpen(!allPanelsOpen()); + }); + } + syncMasterOpenButton(); + + function clearPromptsOnly() { + if (promptInput) { + promptInput.value = ''; + syncPromptToGradio(); + } + document.querySelectorAll('.suggestion-chip.active').forEach(btn => btn.classList.remove('active')); + activeChips.clear(); + showToast('Prompt cleared', 'info'); + } + if (btnClearPrompts) btnClearPrompts.addEventListener('click', clearPromptsOnly); + window.__clearPrompts = clearPromptsOnly; + window.__setPromptsOpen = setAllPanelsOpen; + window.__setPanelOpen = setPanelOpen; + + window.__setPrompt = function(text) { if (promptInput) { promptInput.value = text; syncPromptToGradio(); } }; + window.__setLora = function(lora) { + if (loraSelect) { + loraSelect.value = lora || 'none'; + loraSelect.dispatchEvent(new Event('change', {bubbles:true})); + syncLoraToGradio(); + if (window.__setLoraDemos) window.__setLoraDemos(loraSelect.value); + } + }; + window.__setAspect = function(aspect) { + if (aspectSelect) { + aspectSelect.value = aspect; + aspectSelect.dispatchEvent(new Event('change', {bubbles:true})); + syncAspectToGradio(); + } + }; + window.__setSize = function(size) { + if (sizeSelect) { + sizeSelect.value = size; + sizeSelect.dispatchEvent(new Event('change', {bubbles:true})); + syncSizeToGradio(); + } + }; + + document.querySelectorAll('.example-card[data-idx]').forEach(card => { + card.addEventListener('click', () => { + const idx = card.getAttribute('data-idx'); + document.querySelectorAll('.example-card.loading').forEach(c => c.classList.remove('loading')); + card.classList.add('loading'); + showToast('Loading example\u2026', 'info'); + setGradioValue('example-result-data', ''); + setGradioValue('example-idx-input', idx); + setTimeout(() => { + const btn = document.getElementById('example-load-btn'); + if (btn) { const b = btn.querySelector('button'); if (b) b.click(); else btn.click(); } + }, 150); + setTimeout(() => card.classList.remove('loading'), 12000); + }); + }); + + function syncSlider(customId, gradioId) { + const slider = document.getElementById(customId); + const valSpan = document.getElementById(customId + '-val'); + if (!slider) return; + slider.addEventListener('input', () => { + if (valSpan) valSpan.textContent = slider.value; + const container = document.getElementById(gradioId); + if (!container) return; + container.querySelectorAll('input[type="range"],input[type="number"]').forEach(el => { + const ns = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value'); + if (ns && ns.set) { + ns.set.call(el, slider.value); + el.dispatchEvent(new Event('input', {bubbles:true, composed:true})); + el.dispatchEvent(new Event('change', {bubbles:true, composed:true})); + } + }); + }); + } + syncSlider('custom-seed', 'gradio-seed'); + syncSlider('custom-guidance', 'gradio-guidance'); + syncSlider('custom-steps', 'gradio-steps'); + + const randCheck = document.getElementById('custom-randomize'); + if (randCheck) { + randCheck.addEventListener('change', () => { + const container = document.getElementById('gradio-randomize'); + if (!container) return; + const cb = container.querySelector('input[type="checkbox"]'); + if (cb && cb.checked !== randCheck.checked) cb.click(); + }); + } + + function showLoader() { + const l = document.getElementById('output-loader'); + if (l) l.classList.add('active'); + const sb = document.querySelector('.sb-fixed'); + if (sb) sb.textContent = 'Processing\u2026'; + } + function hideLoader() { + const l = document.getElementById('output-loader'); + if (l) l.classList.remove('active'); + const sb = document.querySelector('.sb-fixed'); + if (sb) sb.textContent = 'Done'; + } + window.__showLoader = showLoader; + window.__hideLoader = hideLoader; + + function validateBeforeRun() { + const promptVal = promptInput ? promptInput.value.trim() : ''; + const hasImages = images.length > 0; + if (!hasImages && !promptVal) { showToast('Please upload an image and enter a prompt', 'error'); flashPromptError(); return false; } + if (!hasImages) { showToast('Please upload at least one image', 'error'); return false; } + if (!promptVal) { showToast('Please enter an edit prompt', 'warning'); flashPromptError(); return false; } + return true; + } + + window.__clickGradioRunBtn = function() { + if (!validateBeforeRun()) return; + syncPromptToGradio(); syncImagesToGradio(); syncLoraToGradio(); syncPromptPackToGradio(); syncAspectToGradio(); syncSizeToGradio(); showLoader(); + setTimeout(() => { + const gradioBtn = document.getElementById('gradio-run-btn'); + if (!gradioBtn) return; + const btn = gradioBtn.querySelector('button'); + if (btn) btn.click(); else gradioBtn.click(); + }, 200); + }; + + if (runBtnEl) runBtnEl.addEventListener('click', () => window.__clickGradioRunBtn()); + + renderGallery(); + updateCounts(); +} +init(); +} diff --git a/ui/lora_demo.js b/ui/lora_demo.js new file mode 100644 index 0000000000000000000000000000000000000000..019f10ea2bdbc3b7561535a7b638d90d98cc4e5c --- /dev/null +++ b/ui/lora_demo.js @@ -0,0 +1,93 @@ +() => { + window.__LORA_HELP = __LORA_HELP_JS__; + window.__LORA_DEFAULT_PROMPTS = __LORA_DEFAULT_PROMPTS_JS__; + window.__LORA_DEMO_BEFORE = __LORA_DEMO_BEFORE_JS__; + window.__LORA_DEMO_AFTER = __LORA_DEMO_AFTER_JS__; + window.__LORA_DEMO_GENERIC_BEFORE = __LORA_DEMO_GENERIC_BEFORE_JS__; + window.__LORA_DEMO_GENERIC_AFTER = __LORA_DEMO_GENERIC_AFTER_JS__; + + + + window.__setLoraDemos = function(val, opts) { + opts = opts || {}; + var before = document.getElementById('lora-demo-before'); + var after = document.getElementById('lora-demo-after'); + var nameEl = document.getElementById('lora-demo-name'); + var status = document.getElementById('lora-demo-status'); + var tip = document.getElementById('lora-help-tooltip'); + var box = document.getElementById('lora-help-text'); + var help = window.__LORA_HELP || {}; + var v = val || 'none'; + var text = help[v] || help['none'] || ''; + // Phone skin CSS hides demos until a LoRA is selected + try { + document.documentElement.classList.toggle('has-lora-selected', !!(v && v !== 'none')); + } catch (e) {} + if (nameEl) nameEl.textContent = (v === 'none') ? 'Choose a LoRA…' : v; + if (tip) tip.textContent = text; + if (box) { + if (v === 'none') box.textContent = text; + else box.innerHTML = '' + String(v).replace(/ β€” ' + String(text).replace(/ + + +
+
+ + Qwen-Image-Edit + 2511 + 4-Step Fast +
+ + + __GITHUB_SVG__ + GitHub + +
+ + +
+
+
+ + + +
+ No images +
+
+ Upload: Max 2 images  ·  + #1 Main / #2 Reference +
+
+
+
+ Output + +
+ + __DOWNLOAD_SVG__ Save + +
+
+ + +
+ + +
+ + + + +
+
+
Quick Prompts
+
+
+ + +
+
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+
+
+ Editing Style / LoRA + ? + A LoRA is a specialized skill pack for the editor. Pick one that matches your goal, then write a matching prompt. + +
+
+ +
A LoRA is a specialized skill pack for the editor (style, camera, lighting, upscale, etc.). Pick one that matches your goal, then write a prompt that asks for that kind of change.
+
+
+
Before
+ Before demo +
+
+
After
+ After demo +
+
+
+
Demo for Choose a LoRA…
+
+ +
+ + +
+ +
+
+
+
+
Processing image…
+
+
+
Result will appear here
+
+
+ +
+
Edit Instruction
+
+ + +
+
+ +
+
+
+ Output Dimensions / Ratio + ? + Sets the output shape. Original keeps the source proportions; Square is 1:1; Wide is 16:9 landscape; Portrait is 9:16 vertical. This only changes the frame ratio, not overall resolution. + +
+ +
+
+ +
+
+
+ Output Image Size + ? + Controls output resolution. Original uses source pixels (long side max 4000). Ladder: X-Small 512, Small 768, Normal 1024, Large 1280, X-Large 1536 on the long side. Larger images use more GPU memory and take longer. + +
+ + +
+
+ +
+ +
+
+ + + 0 +
+
+ + +
+
+ + + 1.0 +
+
+ + + 4 +
+
+
+ +
+ +
+ +
+
+ +
+ Experimental Space for + Qwen-Image-Edit-2511 + · LoRAs loaded lazily on first use +
+ +
+
No images uploaded
+
Ready
+
+ + diff --git a/ui/shell_phone.html b/ui/shell_phone.html new file mode 100644 index 0000000000000000000000000000000000000000..fe457809590b2b0e94064892886db3c775612286 --- /dev/null +++ b/ui/shell_phone.html @@ -0,0 +1,311 @@ +
+ + +
+ +
+
+
+ + + +
+ No images +
+
+ Upload: Max 2 images  ·  + #1 Main / #2 Reference +
+
+ +
+ +
+
+
+ Output + +
+ + __DOWNLOAD_SVG__ Save + +
+
+
+
+
+
Processing image…
+
+
+
Result will appear here
+
+
+
+ +
+
+
+
Prompts
+
+
+ + +
+
+ +
+ + +
+ +
+ + +
+ +
+ + +
+
+ +
+
+
Prompt
+
+ + + + +
+
+
+ +
+
+
+
+ Aspect + ? + Sets the output shape. Original keeps the source proportions; Square is 1:1; Wide is 16:9 landscape; Portrait is 9:16 vertical. This only changes the frame ratio, not overall resolution. + +
+ +
+
+
+
+
+ Size + ? + Controls output resolution. Original uses source pixels (long side max 4000). Ladder: X-Small 512, Small 768, Normal 1024, Large 1280, X-Large 1536 on the long side. Larger images use more GPU memory and take longer. + +
+ + +
+
+
+ +
+
+
+
+ LoRA + ? + A LoRA is a specialized skill pack for the editor. Pick one that matches your goal, then write a matching prompt. + +
+
+ +
A LoRA is a specialized skill pack for the editor (style, camera, lighting, upscale, etc.). Pick one that matches your goal, then write a prompt that asks for that kind of change.
+
+
+
Before
+ Before demo +
+
+
After
+ After demo +
+
+
+
Demo for Choose a LoRA…
+
+
+ +
+
+ +
+
+ + + 0 +
+
+ + +
+
+ + + 1.0 +
+
+ + + 4 +
+
+
+
+ +
+
+ +
+
+ + + +
+
diff --git a/ui/wire_outputs.js b/ui/wire_outputs.js new file mode 100644 index 0000000000000000000000000000000000000000..b40bd44d87968af34ca432a1a52417d7dd53399e --- /dev/null +++ b/ui/wire_outputs.js @@ -0,0 +1,97 @@ +() => { +function watchOutputs() { + const resultContainer = document.getElementById('gradio-result'); + const outBody = document.getElementById('output-image-container'); + const outPh = document.getElementById('output-placeholder'); + const dlBtn = document.getElementById('dl-btn-output'); + + if (!resultContainer || !outBody) { setTimeout(watchOutputs, 500); return; } + + if (dlBtn) { + dlBtn.addEventListener('click', (e) => { + e.stopPropagation(); + const img = outBody.querySelector('img.modern-out-img'); + if (img && img.src) { + const a = document.createElement('a'); + a.href = img.src; a.download = 'qwen_edit_output.png'; + document.body.appendChild(a); a.click(); document.body.removeChild(a); + } + }); + } + + function syncImage() { + const resultImg = resultContainer.querySelector('img'); + if (resultImg && resultImg.src) { + if (outPh) outPh.style.display = 'none'; + let existing = outBody.querySelector('img.modern-out-img'); + if (!existing) { + existing = document.createElement('img'); + existing.className = 'modern-out-img'; + outBody.appendChild(existing); + } + if (existing.src !== resultImg.src) { + existing.src = resultImg.src; + if (dlBtn) dlBtn.classList.add('visible'); + if (window.__hideLoader) window.__hideLoader(); + } + } + } + const observer = new MutationObserver(syncImage); + observer.observe(resultContainer, {childList:true, subtree:true, attributes:true, attributeFilter:['src']}); + setInterval(syncImage, 800); +} +watchOutputs(); + +function watchSeed() { + const seedContainer = document.getElementById('gradio-seed'); + const seedSlider = document.getElementById('custom-seed'); + const seedVal = document.getElementById('custom-seed-val'); + if (!seedContainer || !seedSlider) { setTimeout(watchSeed, 500); return; } + function sync() { + const el = seedContainer.querySelector('input[type="range"],input[type="number"]'); + if (el && el.value) { seedSlider.value = el.value; if (seedVal) seedVal.textContent = el.value; } + } + const obs = new MutationObserver(sync); + obs.observe(seedContainer, {childList:true, subtree:true, attributes:true, attributeFilter:['value']}); + setInterval(sync, 1000); +} +watchSeed(); + +function watchExampleResults() { + const container = document.getElementById('example-result-data'); + if (!container) { setTimeout(watchExampleResults, 500); return; } + let lastProcessed = ''; + + function checkResult() { + const el = container.querySelector('textarea') || container.querySelector('input'); + if (!el) return; + const val = el.value; + if (!val || val === lastProcessed || val.length < 20) return; + try { + const data = JSON.parse(val); + if (data.status === 'ok' && data.images && data.images.length > 0) { + lastProcessed = val; + if (window.__clearAll) window.__clearAll(); + if (window.__setPrompt && data.prompt) window.__setPrompt(data.prompt); + if (window.__setLora && data.lora) window.__setLora(data.lora); + data.images.forEach((b64, i) => { + if (b64 && window.__addImage) { + const name = (data.names && data.names[i]) ? data.names[i] : ('example_'+(i+1)+'.jpg'); + window.__addImage(b64, name); + } + }); + document.querySelectorAll('.example-card.loading').forEach(c => c.classList.remove('loading')); + if (window.__showToast) window.__showToast('Example loaded \u2014 ' + data.images.length + ' image(s)', 'info'); + } else if (data.status === 'error') { + document.querySelectorAll('.example-card.loading').forEach(c => c.classList.remove('loading')); + if (window.__showToast) window.__showToast('Could not load example images', 'error'); + } + } catch(e) { console.error('Example parse error:', e); } + } + + const obs = new MutationObserver(checkResult); + obs.observe(container, {childList:true, subtree:true, characterData:true, attributes:true}); + setInterval(checkResult, 500); +} +watchExampleResults(); +}