"""Outpaint v2 on the application's existing native Qwen Image 2.1 pipeline. ``prepare`` builds the canvas and downloads only the pinned 152 MiB adapter, outside the GPU lease. ``generate`` runs under the caller's shared pipeline lock. No additional model, segmentation model, or latent noise mask is used. """ import math import random import re from bfs_backend import DMD2_SCHEDULER, DMD2_SIGMAS, MODE_DMD2, select_speed_adapter, specialist_guidance OUTPAINT_REPO = "ausboss/Qwen-Image-2.1-Outpaint-LoRA" OUTPAINT_FILE = "qwen-image-2.1-outpaint-v2.safetensors" OUTPAINT_REVISION = "dca5bdc7eb328f6021f330140f64b00a820ae5cd" OUTPAINT_ADAPTER = "qwen-outpaint-v2" OUTPAINT_PROMPT = ( "Outpaint the image: replace the solid gray areas with a seamless continuation of the scene, " "keeping the existing picture unchanged." ) MODE_TURBO = "Turbo (6 steps)" MODE_BASE = "Base (25 steps)" GRAY = (128, 128, 128) MAX_SEED = 2**31 - 1 SIDES = ("left", "right", "top", "bottom") def prompt_with_trigger(text): """Put the author's exact instruction first, once, including after editing.""" text = str(text or "").strip() text = re.sub(re.escape(OUTPAINT_PROMPT), "", text, flags=re.IGNORECASE).strip() return OUTPAINT_PROMPT + (" " + text if text else "") def _number(value, label, low, high, *, integer=False): try: number = float(value) except (TypeError, ValueError, OverflowError) as error: raise ValueError(f"{label} must be a number between {low} and {high}.") from error if not math.isfinite(number) or not low <= number <= high or (integer and not number.is_integer()): raise ValueError(f"{label} must be {'a whole number ' if integer else ''}between {low} and {high}.") return int(number) if integer else number def is_base(data): mode = data.get("outpaint_mode", MODE_TURBO) if mode not in (MODE_BASE, MODE_TURBO, MODE_DMD2): raise ValueError("Choose Turbo, DMD2, or Base for Outpaint.") return mode == MODE_BASE def is_dmd2(data): return data.get("outpaint_mode") == MODE_DMD2 def turbo_sigmas(steps): steps = _number(steps, "Outpaint Turbo steps", 4, 8, integer=True) if steps == 4: return [1.0, 0.75, 0.5, 0.25] return [1.0 - 0.125 * i / (steps - 4) for i in range(steps - 4)] + [0.875, 0.75, 0.5, 0.25] def _settings(data): base = is_base(data) dmd2 = is_dmd2(data) specialist_guidance(data, dmd2) pads = {side: _number(data.get(f"outpaint_{side}", 25), f"{side.title()} extension", 0, 100) for side in SIDES} if not any(pads.values()): raise ValueError("Extend at least one side to outpaint the image.") mp = _number(data.get("target_megapixels", 1.0), "Outpaint target megapixels", 0.5, 2.0) feather = _number(data.get("outpaint_feather", 32), "Outpaint edge blend", 0, 256, integer=True) steps = (len(DMD2_SIGMAS) if dmd2 else _number(data.get("steps", 25 if base else 6), "Outpaint steps", 4, 50 if base else 8, integer=True)) return pads, mp, feather, steps def _source(data): from PIL import Image, ImageOps value = data.get("input_image_1") if value is None: value = data.get("image1") if value is None: raise ValueError("Outpaint needs Image 1 (the picture to extend).") if isinstance(value, Image.Image): image = ImageOps.exif_transpose(value).convert("RGB") else: if isinstance(value, dict): value = value.get("path") or value.get("name") if not value: raise ValueError("Outpaint needs Image 1 (the picture to extend).") try: with Image.open(value) as opened: image = ImageOps.exif_transpose(opened).convert("RGB") except (TypeError, OSError, ValueError) as error: raise ValueError("Outpaint could not read Image 1.") from error if image.width < 1 or image.height < 1: raise ValueError("Outpaint needs a nonempty image.") return image def _native_dimensions(resolution, ratio): """The pinned native pipeline's calculate_dimensions, without a GPU import.""" width = math.sqrt(resolution * resolution * ratio) height = width / ratio return round(width / 32) * 32, round(height / 32) * 32 def _geometry(image, pads, mp): resolution = int(round(math.sqrt(mp * 1024 * 1024))) virtual_width = image.width * (1 + (pads["left"] + pads["right"]) / 100) virtual_height = image.height * (1 + (pads["top"] + pads["bottom"]) / 100) width, height = _native_dimensions(resolution, virtual_width / virtual_height) # Unlike the author's Comfy node, native Diffusers does not accept resolution # zero. A fixed point keeps its positive-resolution reference resize at the # exact output size, preventing the known area from shifting under stitching. for _ in range(64): if min(width, height) < 256 or max(width, height) > 8192: raise ValueError("Outpaint canvas sides must be between 256 and 8192 pixels; use a less extreme aspect ratio.") next_size = _native_dimensions(resolution, width / height) if next_size == (width, height): break width, height = next_size else: raise ValueError("Outpaint could not align this canvas to the native reference resolution.") # Account for /32 rounding in each axis. A zero-extension side stays flush; # percentages remain relative to the resized source rather than the canvas. picture_width = max(1, round(width / (1 + (pads["left"] + pads["right"]) / 100))) picture_height = max(1, round(height / (1 + (pads["top"] + pads["bottom"]) / 100))) horizontal = pads["left"] + pads["right"] vertical = pads["top"] + pads["bottom"] x = round((width - picture_width) * pads["left"] / horizontal) if horizontal else 0 y = round((height - picture_height) * pads["top"] / vertical) if vertical else 0 if (picture_width, picture_height) == (width, height): raise ValueError("The requested extension is less than one output pixel; increase it.") return width, height, resolution, (x, y, picture_width, picture_height) def request_canvas(data): """Return the exact /32 output dimensions; perform no model import/download.""" pads, mp, _, _ = _settings(data) width, height, _, _ = _geometry(_source(data), pads, mp) return width, height def build_canvas(data): """Return (gray canvas, resized source, (x, y, w, h), native resolution).""" from PIL import Image pads, mp, _, _ = _settings(data) source = _source(data) width, height, resolution, box = _geometry(source, pads, mp) x, y, picture_width, picture_height = box picture = source.resize((picture_width, picture_height), Image.Resampling.LANCZOS) canvas = Image.new("RGB", (width, height), GRAY) canvas.paste(picture, (x, y)) return canvas, picture, box, resolution def preview(data): canvas, _, _, _ = build_canvas(data) return canvas, canvas.size def prepare(data, token=None): """Validate, normalize, and download the pinned adapter before GPU allocation.""" from huggingface_hub import hf_hub_download out = dict(data) dmd2 = is_dmd2(out) negative, cfg, _ = specialist_guidance(out, dmd2) out.update(negative_prompt_text=negative or "", guidance_scale=cfg) pads, mp, feather, steps = _settings(out) source = _source(out) out["input_image_1"] = out["image1"] = source canvas, picture, box, resolution = build_canvas(out) out.update({f"outpaint_{side}": value for side, value in pads.items()}) out.update(outpaint_mode=MODE_DMD2 if dmd2 else MODE_BASE if is_base(out) else MODE_TURBO, target_megapixels=mp, outpaint_feather=feather, steps=steps, width=canvas.width, height=canvas.height, prompt=prompt_with_trigger(out.get("prompt"))) if out.get("randomize_seed", True): out["seed"] = random.randint(0, MAX_SEED) else: out["seed"] = _number(out.get("seed", 0), "Seed", 0, MAX_SEED, integer=True) out["randomize_seed"] = False out["_outpaint_canvas"] = canvas out["_outpaint_source"] = picture out["_outpaint_box"] = box out["_outpaint_resolution"] = resolution out["_outpaint_path"] = hf_hub_download( repo_id=OUTPAINT_REPO, filename=OUTPAINT_FILE, revision=OUTPAINT_REVISION, token=token, ) return out def estimate_seconds(data): """One-reference estimate; optional LoRAs and output area consume the budget.""" _, _, _, steps = _settings(data) _, _, passes = specialist_guidance(data, is_dmd2(data)) width, height = request_canvas(data) area = width * height prefix_and_target = 1.2 * area / 16**2 per_step = 5.6e-6 * prefix_and_target**1.363 active = sum(bool(data.get(f"user_lora_{slot}_file") or data.get(f"user_lora_{slot}_ref")) and float(data.get(f"user_lora_{slot}_scale") or 0) != 0 for slot in range(1, 4)) # Include initial adapter attachment and decode overhead, not only denoising. return int(min(300, max(20, math.ceil((8 + 2e-6 * area + steps * per_step * passes + 4 * active) * 1.2 + 3)))) def ensure_outpaint(pipe, path): """Attach v2 once, using the shared native Qwen Comfy projection converter.""" if getattr(pipe, "_shared_outpaint_v2_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("Outpaint v2 must contain all 384 adapter tensors.") try: state = convert_bfs_state_dict(state, pipe.transformer) except ValueError as error: raise ValueError(str(error).replace("BFS", "Outpaint")) from error if len(state) != 448: raise ValueError("Outpaint v2 must address all 224 native Qwen projections.") pipe.load_lora_weights(state, adapter_name=OUTPAINT_ADAPTER) pipe._shared_outpaint_v2_loaded = True def composite_original(result, picture, box, feather=32): """Restore resized source pixels; blend only inward from expanded edges. Feather zero preserves every source pixel. With feather 32, pixels at least 32 px from new content are exact; the inside edge strip mixes generated and source pixels to hide a seam. Edges flush with the canvas are never faded. """ import numpy as np from PIL import Image feather = _number(feather, "Outpaint edge blend", 0, 256, integer=True) x, y, width, height = box if picture.size != (width, height) or min(x, y) < 0 or x + width > result.width or y + height > result.height: raise ValueError("The Outpaint source placement does not fit the generated canvas.") out = result.convert("RGB").copy() picture = picture.convert("RGB") if not feather: out.paste(picture, (x, y)) return out horizontal = np.full(width, float(feather), dtype=np.float32) vertical = np.full(height, float(feather), dtype=np.float32) if x: horizontal = np.minimum(horizontal, np.arange(width)) if x + width < out.width: horizontal = np.minimum(horizontal, np.arange(width - 1, -1, -1)) if y: vertical = np.minimum(vertical, np.arange(height)) if y + height < out.height: vertical = np.minimum(vertical, np.arange(height - 1, -1, -1)) alpha = (np.minimum(vertical[:, None], horizontal[None, :]) / feather)[..., None] generated = np.asarray(out.crop((x, y, x + width, y + height)), dtype=np.float32) blended = generated * (1 - alpha) + np.asarray(picture, dtype=np.float32) * alpha out.paste(Image.fromarray(blended.round().clip(0, 255).astype(np.uint8)), (x, y)) return out def generate(pipe, data, *, turbo_adapter, base_scheduler_config, user_adapters=(), user_weights=(), kv_budget_gb=30.0, dmd2_adapter=None): """Generate inside the caller's shared lease/lock, then restore Turbo state.""" import torch from diffusers import FlowMatchEulerDiscreteScheduler from bfs_backend import decode_latents if len(user_adapters) != len(user_weights): raise ValueError("Optional adapter names and weights must have the same length.") if any(name in (OUTPAINT_ADAPTER, turbo_adapter, dmd2_adapter) for name in user_adapters): raise ValueError("Built-in Outpaint and speed adapters cannot occupy an optional slot.") if base_scheduler_config is None: raise ValueError("The original Qwen base scheduler configuration is required.") _, _, feather, steps = _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) canvas = data.get("_outpaint_canvas") if canvas is None or any(key not in data for key in ("_outpaint_source", "_outpaint_box", "_outpaint_resolution", "_outpaint_path")): raise ValueError("Prepare the Outpaint canvas before entering the GPU worker.") width, height = canvas.size resolution = data["_outpaint_resolution"] if _native_dimensions(resolution, width / height) != canvas.size: raise ValueError("Outpaint reference and output dimensions must match exactly.") seed = _number(data.get("seed"), "Seed", 0, MAX_SEED, integer=True) budget = _number(kv_budget_gb, "KV-cache budget", 0, 1024) prefix_tokens = (width // 16) * (height // 16) use_kv_cache = prefix_tokens * 32 * 2 * 4096 * 2 * passes <= budget * 1e9 names = [OUTPAINT_ADAPTER] + ([speed_adapter] if speed_adapter else []) + list(user_adapters) weights = [1.0] + ([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_outpaint(pipe, data["_outpaint_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=[canvas], width=width, height=height, output_resolution=resolution, num_inference_steps=steps, sigmas=sigmas, true_cfg_scale=cfg, negative_prompt=negative, use_kv_cache=use_kv_cache, 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 != canvas.size: raise ValueError("Outpaint returned an unexpected canvas size; original pixels were not composited.") return composite_original(result, data["_outpaint_source"], data["_outpaint_box"], feather) finally: pipe.scheduler = original_scheduler pipe.vae.disable_tiling() pipe.set_adapters([turbo_adapter], adapter_weights=[1.0])