"""Elusarca Detail Enhancer on the studio's existing Qwen Image 2.1 pipeline. Prepare the pinned adapter and single reference before the GPU allocation. The caller serializes generation with every other shared-pipeline operation. Base uses the original 25-step recipe; Turbo is an optional experimental blend. """ import math import random import re from bfs_backend import DMD2_SCHEDULER, DMD2_SIGMAS, MODE_DMD2, select_speed_adapter, specialist_guidance DETAIL_REPO = "reverentelusarca/elusarcas-qwen-2.1-detail-enhancer-lora" DETAIL_FILE = "elusarcas-qwen2-1-detailer-v1.safetensors" DETAIL_REVISION = "aedadc6b65a15e6b261c0ec61a4587c3e7119514" DETAIL_ADAPTER = "elusarca-detail-enhancer-v1" MODE_BASE = "Base (25 steps)" MODE_TURBO = "Turbo (6 steps, experimental)" DETAIL_TRIGGER = "Enhance this image" DETAIL_PROMPT = ( "Enhance this image to high resolution while preserving the original composition, lighting, and " "atmosphere. Image can be illustration or real photo, keep the original input style." ) DETAIL_DETAILED_PROMPT = ( "Enhance this image to high resolution with rich fine details. Sharpen textures and surfaces, add " "natural microdetails, and improve clarity and definition across the image while preserving the " "original composition, lighting, atmosphere, and visual style. The input may be an illustration or " "a real photograph; preserve the original style." ) DETAIL_ILLUSTRATION_PROMPT = DETAIL_DETAILED_PROMPT.replace("Sharpen textures and surfaces, add", "Add") DETAIL_PRESETS = { "Generic (original workflow)": DETAIL_PROMPT, "Rich detail (photos / portraits)": DETAIL_DETAILED_PROMPT, "Illustration (no sharpening)": DETAIL_ILLUSTRATION_PROMPT, } REFERENCE_RESOLUTION = 1024 MAX_SEED = 2**31 - 1 def prompt_with_trigger(text): text = str(text or "").strip() or DETAIL_PROMPT # Keep the author's trigger, while retaining editable detailed instructions. if not re.search(r"(? 8192: raise ValueError("Detail Enhancer image sides must stay within 32-8192 pixels; use a less extreme aspect ratio.") return width, height def prepare(data, token=None): from huggingface_hub import hf_hub_download from PIL import Image out = dict(data) negative, cfg, _ = specialist_guidance(out, is_dmd2(out)) out.update(negative_prompt_text=negative or "", guidance_scale=cfg) steps, strength, _ = _settings(out) width, height = request_canvas(out) source = source_image(out) seed = (random.randint(0, MAX_SEED) if out.get("randomize_seed") else _number(out.get("seed", 0), "Seed", 0, MAX_SEED, integer=True)) out.update(input_image_1=source, input_image_2=None, input_images_extra=None, _detail_reference=source.resize(reference_size(*source.size), Image.Resampling.LANCZOS), width=width, height=height, steps=steps, detail_strength=strength, seed=seed, randomize_seed=False, prompt=prompt_with_trigger(out.get("prompt"))) out["_detail_path"] = hf_hub_download(repo_id=DETAIL_REPO, filename=DETAIL_FILE, revision=DETAIL_REVISION, token=token) return out def estimate_seconds(data): """Use the upstream eager-model formula, plus adapter and decode allowances.""" steps, _, _ = _settings(data) _, _, passes = specialist_guidance(data, is_dmd2(data)) width, height = request_canvas(data) per_step = 2.26 * ((width * height / 256.0) / 16524.0)**1.22 * 1.3 optional = sum(bool(data.get(f"user_lora_{i}_file") or data.get(f"user_lora_{i}_ref")) and float(data.get(f"user_lora_{i}_scale") or 0) != 0 for i in range(1, 4)) return int(min(400, max(30, math.ceil((12 + steps * per_step * passes + optional * 4) * 1.2 + 5)))) def ensure_detail(pipe, path): if getattr(pipe, "_shared_detail_v1_loaded", False): return from bfs_backend import convert_bfs_state_dict from safetensors.torch import load_file state = load_file(path, device="cpu") if len(state) != 384: raise ValueError("Detail Enhancer v1 must contain all 384 adapter tensors.") try: converted = convert_bfs_state_dict(state, pipe.transformer) except ValueError as error: raise ValueError(str(error).replace("BFS", "Detail Enhancer")) from error if len(converted) != 448: raise ValueError("Detail Enhancer v1 must address all 224 native Qwen projections.") pipe.load_lora_weights(converted, adapter_name=DETAIL_ADAPTER) pipe._shared_detail_v1_loaded = True def generate(pipe, data, *, turbo_adapter, base_scheduler_config, user_adapters=(), user_weights=(), kv_budget_gb=30.0, dmd2_adapter=None): """Apply required/optional adapters only for this shared, serialized request.""" import torch from diffusers import FlowMatchEulerDiscreteScheduler from bfs_backend import decode_latents, turbo_sigmas if len(user_adapters) != len(user_weights): raise ValueError("Optional adapter names and weights must have the same length.") if any(name in (DETAIL_ADAPTER, turbo_adapter, dmd2_adapter) for name in user_adapters): raise ValueError("Built-in Detail Enhancer and speed adapters cannot occupy an optional slot.") if base_scheduler_config is None: raise ValueError("The original Qwen base scheduler configuration is required.") steps, strength, _ = _settings(data) base, dmd2 = is_base(data), is_dmd2(data) speed_adapter = select_speed_adapter(base, dmd2, turbo_adapter, dmd2_adapter) sigmas = list(DMD2_SIGMAS) if dmd2 else None if base else turbo_sigmas(steps) scheduler_options = DMD2_SCHEDULER if dmd2 else {} if base else {"shift_terminal": None} negative, cfg, passes = specialist_guidance(data, dmd2) reference = data.get("_detail_reference") if reference is None or not data.get("_detail_path"): raise ValueError("Prepare the Detail Enhancer reference before entering the GPU worker.") width, height = request_canvas(data) seed = _number(data.get("seed"), "Seed", 0, MAX_SEED, integer=True) budget = _number(kv_budget_gb, "KV-cache budget", 0, 1024) prefix_tokens = (reference.width // 16) * (reference.height // 16) names = [DETAIL_ADAPTER] + ([speed_adapter] if speed_adapter else []) + list(user_adapters) weights = [strength] + ([1.0] if speed_adapter else []) + list(user_weights) combined = {} for name, weight in zip(names, weights): weight = float(weight) if not math.isfinite(weight): raise ValueError("LoRA strengths must be finite.") combined[name] = combined.get(name, 0.0) + weight original_scheduler = pipe.scheduler try: ensure_detail(pipe, data["_detail_path"]) pipe.set_adapters(list(combined), adapter_weights=list(combined.values())) pipe.scheduler = FlowMatchEulerDiscreteScheduler.from_config( base_scheduler_config, **scheduler_options) pipe.vae.disable_tiling() with torch.inference_mode(): latents = pipe(prompt=prompt_with_trigger(data.get("prompt")), image=[reference], width=width, height=height, output_resolution=REFERENCE_RESOLUTION, num_inference_steps=steps, sigmas=sigmas, true_cfg_scale=cfg, negative_prompt=negative, use_kv_cache=prefix_tokens * 32 * 2 * 4096 * 2 * passes <= budget * 1e9, generator=torch.Generator(device="cuda").manual_seed(seed), output_type="latent").images result = decode_latents(pipe, latents, height, width, bool(data.get("vae_tiling", True))) if result.size != (width, height): raise ValueError("Detail Enhancer returned an unexpected output size.") return result.convert("RGB") finally: pipe.scheduler = original_scheduler pipe.vae.disable_tiling() pipe.set_adapters([turbo_adapter], adapter_weights=[1.0])