"""Placed-light relighting on the application's existing Qwen Image 2.1 pipe. Preparation, lighting validation and prompt construction are CPU-only. No task LoRA, extra base model or remote inference is needed. The caller holds the shared pipeline lock and owns the one GPU lease used by ``generate``. """ import json import math import random import re from bfs_backend import ( DMD2_SCHEDULER, DMD2_SIGMAS, MODE_DMD2, select_speed_adapter, specialist_guidance, turbo_sigmas, ) MODE_TURBO = "Turbo (6 steps)" MODE_BASE = "Base (30 steps, no Viggle)" MAX_SEED = 2**31 - 1 MAX_LIGHTS = 3 DEFAULT_COLOR = "#FFFFFF" DEFAULT_PRESET = "Soft studio" DEFAULT_DIRECTION = "Left" DEFAULT_STRENGTH = 1.0 PRESETS = { "Soft studio": { "color": DEFAULT_COLOR, "direction": "Left", "diffusion": 0.9, "instruction": "Use a large soft studio key light with smooth, natural shadow transitions.", }, "Warm sunset": { "color": "#FFBC73", "direction": "Right", "diffusion": 0.35, "instruction": "Create sunset-style directional highlights and soft ambient fill, using the specified light colours.", }, "Cool moonlight": { "color": "#9EBBFF", "direction": "Above", "diffusion": 0.55, "instruction": "Create a restrained moonlit atmosphere with deep, readable shadows, using the specified light colours.", }, "Neon pink + blue": { "color": "#FF60C8", "direction": "Left", "diffusion": 0.4, "instruction": "Create a neon-lit atmosphere with clear colour separation and controlled highlights.", "fill_color": "#4E8CFF", }, "Rim light": { "color": "#D6E6FF", "direction": "Behind", "diffusion": 0.25, "instruction": "Emphasize a luminous edge around the subject while retaining readable detail in the shadows.", }, } DIRECTIONS = ("Left", "Right", "Front", "Above", "Behind") _POSITIONS = { "Left": (0.0, 0.35, 0.75), "Right": (1.0, 0.35, 0.75), "Front": (0.5, 0.5, 1.0), "Above": (0.5, 0.0, 0.5), "Behind": (0.5, 0.35, -1.0), } RELIGHT_INSTRUCTION = ( "Relight the input image using the lighting setup below. Replace the original illumination " "with the requested lights. Change the illumination, " "shading, highlights, shadows and reflected light consistently with the scene. " "Preserve the subject's identity, facial expression, pose, framing, background " "geometry, materials and fine details as closely as possible. Do not add lamps " "or visible light-source objects." ) def _number(value, label, low, high, *, integer=False): if isinstance(value, bool): raise ValueError(f"{label} must be a number between {low} and {high}.") 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 _mode(data): mode = data.get("qwen_mode", data.get("relight_mode", MODE_TURBO)) if mode not in (MODE_TURBO, MODE_DMD2, MODE_BASE): raise ValueError("Choose Turbo, DMD2, or Base for Relight.") return mode def is_base(data): return _mode(data) == MODE_BASE def is_dmd2(data): return _mode(data) == MODE_DMD2 def _color(value): if not isinstance(value, str) or not re.fullmatch(r"#[0-9a-fA-F]{6}", value): raise ValueError("Light colour must be a six-digit hex colour, such as #FFD6A3.") return value.upper() def validate_lights(value): """Normalize 1-3 screen-space lights; never silently ignore malformed input. x/y are 0..1, with (0,0) at the image's top left. z is -1..1, where positive faces the camera and negative is behind the subject. Coordinates describe semantic light directions, not calibrated physical 3D positions. """ if isinstance(value, str): if len(value) > 8192: raise ValueError("The Relight light setup is too large.") try: value = json.loads(value) except (TypeError, ValueError) as error: raise ValueError("Relight lights must be a JSON list of placed lights.") from error if not isinstance(value, (list, tuple)) or not 1 <= len(value) <= MAX_LIGHTS: raise ValueError(f"Place between 1 and {MAX_LIGHTS} lights.") lights = [] for index, light in enumerate(value, 1): if not isinstance(light, dict): raise ValueError(f"Light {index} must include x/y position and colour.") if set(light) - {"x", "y", "z", "color", "intensity"}: raise ValueError(f"Light {index} has unsupported settings.") lights.append({ "x": _number(light.get("x"), f"Light {index} horizontal position", 0, 1), "y": _number(light.get("y"), f"Light {index} vertical position", 0, 1), "z": _number(light.get("z", 1.0), f"Light {index} depth", -1, 1), "color": _color(light.get("color", DEFAULT_COLOR)), "intensity": _number(light.get("intensity", 1.0), f"Light {index} intensity", 0, 2), }) if not any(light["intensity"] > 0 for light in lights): raise ValueError("Give at least one light a positive intensity.") return lights def lights_from_data(data): preset = _preset(data) raw = data.get("relight_lights") if raw is not None and not (isinstance(raw, str) and not raw.strip()): return validate_lights(raw) direction = data.get("relight_direction", preset["direction"]) if direction not in DIRECTIONS: raise ValueError("Choose Left, Right, Front, Above, or Behind for the light.") x, y, z = _POSITIONS[direction] lights = [{ "x": x, "y": y, "z": z, "color": data.get("relight_color", preset["color"]), "intensity": data.get("relight_brightness", 1.0), }] if "fill_color" in preset: lights.append({"x": 1 - x if x != 0.5 else 0.9, "y": y, "z": 0.75, "color": preset["fill_color"], "intensity": 0.8}) return validate_lights(lights) def _preset(data): name = data.get("relight_preset", DEFAULT_PRESET) if not isinstance(name, str) or name not in PRESETS: raise ValueError("Choose one of the Relight lighting presets.") return PRESETS[name] def _color_description(color): """Give the text encoder a colour name as well as the precise UI value.""" import colorsys red, green, blue = (int(color[i:i + 2], 16) / 255 for i in (1, 3, 5)) hue, saturation, value = colorsys.rgb_to_hsv(red, green, blue) if saturation < 0.12: return "neutral white" if value >= 0.65 else "neutral grey" names = ("red", "orange", "yellow", "yellow-green", "green", "green-cyan", "cyan", "cyan-blue", "blue", "violet", "magenta", "rose") name = names[int((hue * 12 + 0.5) % 12)] return ("pale " if saturation < 0.4 else "") + name def build_prompt(data): """Translate placed lights into image-relative instructions on CPU.""" lights = lights_from_data(data) preset = _preset(data) diffusion = _number(data.get("relight_diffusion", preset["diffusion"]), "Light softness", 0, 1) softness = ("Use soft, diffused shadows." if diffusion > 0.65 else "Use crisp, directional shadows." if diffusion < 0.35 else "Use moderately soft shadows.") extra = data.get("_relight_extra_prompt", data.get("prompt", "")) if extra is None: extra = "" if not isinstance(extra, str) or len(extra) > 4000: raise ValueError("Additional Relight instructions must be text of at most 4000 characters.") descriptions = [] for index, light in enumerate(lights, 1): if light["intensity"] == 0: continue horizontal = "the viewer's left" if light["x"] < 0.4 else "the viewer's right" if light["x"] > 0.6 else "the horizontal centre" vertical = "above" if light["y"] < 0.4 else "below" if light["y"] > 0.6 else "near eye level" depth = "behind the subject, creating rim/back lighting" if light["z"] < -0.25 else ( "in front of the subject, toward the camera" if light["z"] > 0.25 else "beside the subject") power = "subtle" if light["intensity"] < 0.6 else "moderate" if light["intensity"] <= 1.2 else "strong" descriptions.append( f"Light {index}: {power} {_color_description(light['color'])} light ({light['color']}), " f"from {horizontal}, {vertical}, {depth}; image-plane position " f"{light['x'] * 100:.1f}% from the left and {light['y'] * 100:.1f}% from the top, " f"relative intensity {light['intensity']:.2f}." ) # A manually moved rim preset must not instruct both frontal and back light. moved_rim = (data.get("relight_preset") == "Rim light" and data.get("relight_direction", preset["direction"]) != "Behind") style = "" if _custom_lights(data) or moved_rim else preset["instruction"] + " " return RELIGHT_INSTRUCTION + "\n" + style + softness + "\n" + "\n".join(descriptions) + ( "\nAdditional lighting instructions: " + extra.strip() if extra.strip() else "") def _custom_lights(data): if "_relight_custom_lights" in data: return bool(data["_relight_custom_lights"]) raw = data.get("relight_lights") return raw is not None and not (isinstance(raw, str) and not raw.strip()) def _settings(data): base, dmd2 = is_base(data), is_dmd2(data) steps = (len(DMD2_SIGMAS) if dmd2 else _number( data.get("steps", 30 if base else 6), "Relight steps", 4, 50 if base else 8, integer=True)) megapixels = _number(data.get("target_megapixels", 1.0), "Relight megapixels", 0.5, 2) strength = _number(data.get("relight_strength", DEFAULT_STRENGTH), "Relight amount", 0, 1) specialist_guidance(data, dmd2) return steps, megapixels, strength def source_image(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("Relight needs Image 1 (the picture to relight).") if isinstance(value, Image.Image): image = ImageOps.exif_transpose(value).copy() else: if isinstance(value, dict): value = value.get("path") or value.get("name") try: with Image.open(value) as opened: image = ImageOps.exif_transpose(opened).copy() except (TypeError, OSError, ValueError, AttributeError) as error: raise ValueError("Relight could not read Image 1.") from error if image.width < 1 or image.height < 1: raise ValueError("Relight needs a nonempty image.") if image.mode in ("RGBA", "LA", "P"): rgba = image.convert("RGBA") image = Image.new("RGBA", rgba.size, (255, 255, 255, 255)) image.alpha_composite(rgba) return image.convert("RGB") def _native_dimensions(resolution, ratio): width = math.sqrt(resolution * resolution * ratio) height = width / ratio return round(width / 32) * 32, round(height / 32) * 32 def _geometry(source, megapixels): resolution = int(round(math.sqrt(megapixels * 1024**2))) width, height = _native_dimensions(resolution, source.width / source.height) # The native pipe resizes references using this same positive resolution. # Find its /32 fixed point so blending never aligns a different canvas. for _ in range(64): if min(width, height) < 256 or max(width, height) > 8192: raise ValueError("Relight image sides must be within 256-8192 pixels; use a less extreme aspect ratio.") next_size = _native_dimensions(resolution, width / height) if next_size == (width, height): return width, height, resolution width, height = next_size raise ValueError("Relight could not match the native reference and output canvas.") def request_canvas(data): _, megapixels, _ = _settings(data) width, height, _ = _geometry(source_image(data), megapixels) return width, height def prepare(data, token=None): """Validate and create one exact-size RGB reference; no downloads or GPU.""" from PIL import Image out = dict(data) steps, megapixels, strength = _settings(out) lights = lights_from_data(out) prompt = build_prompt(out) negative, cfg, _ = specialist_guidance(out, is_dmd2(out)) source = source_image(out) width, height, resolution = _geometry(source, megapixels) seed = random.randint(0, MAX_SEED) if out.get("randomize_seed", True) else _number( out.get("seed", 0), "Seed", 0, MAX_SEED, integer=True) out.update( input_image_1=source, image1=source, input_image_2=None, image2=None, input_images_extra=None, qwen_mode=_mode(out), relight_mode=_mode(out), relight_lights=lights, relight_strength=strength, target_megapixels=megapixels, steps=steps, width=width, height=height, seed=seed, randomize_seed=False, negative_prompt_text=negative or "", guidance_scale=cfg, _relight_extra_prompt=out.get("_relight_extra_prompt", out.get("prompt", "")), _relight_custom_lights=_custom_lights(out), prompt=prompt, _relight_resolution=resolution, _relight_reference=source.resize((width, height), Image.Resampling.LANCZOS), ) return out def estimate_seconds(data): """Conservative shared-model estimate, including CFG and optional adapters.""" steps, _, _ = _settings(data) width, height = request_canvas(data) _, _, passes = specialist_guidance(data, is_dmd2(data)) area = width * height per_step = 5.6e-6 * (1.2 * area / 16**2)**1.363 optional = 0 for slot in range(1, 4): if data.get(f"user_lora_{slot}_file") or data.get(f"user_lora_{slot}_ref"): weight = _number(data.get(f"user_lora_{slot}_scale") or 0, "Optional LoRA strength", -10, 10) optional += weight != 0 return int(min(300, max(20, math.ceil((8 + 2e-6 * area + steps * per_step * passes + 4 * optional) * 1.2 + 3)))) def blend_result(result, reference, strength=1.0): """Mix exact-size canvases in linear light; never crop, warp or align.""" from PIL import Image strength = _number(strength, "Relight amount", 0, 1) if not isinstance(result, Image.Image) or not isinstance(reference, Image.Image) or result.size != reference.size: raise ValueError("Relight returned an unexpected canvas size; no blending was applied.") if strength == 1: return result.convert("RGB") if strength == 0: return reference.convert("RGB").copy() import numpy as np def to_linear(image): values = np.asarray(image.convert("RGB"), dtype=np.float32) / 255 return np.where(values <= 0.04045, values / 12.92, ((values + 0.055) / 1.055)**2.4) mixed = (1 - strength) * to_linear(reference) + strength * to_linear(result) srgb = np.where(mixed <= 0.0031308, mixed * 12.92, 1.055 * mixed**(1 / 2.4) - 0.055) return Image.fromarray((srgb * 255).round().clip(0, 255).astype(np.uint8)) def generate(pipe, data, *, turbo_adapter, base_scheduler_config, user_adapters=(), user_weights=(), kv_budget_gb=30.0, dmd2_adapter=None): """Run under the caller's shared lease/lock and restore default adapters.""" 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 (turbo_adapter, dmd2_adapter) for name in user_adapters): raise ValueError("Built-in 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) prompt = build_prompt(data) base, dmd2 = is_base(data), is_dmd2(data) speed = 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("_relight_reference") resolution = data.get("_relight_resolution") if reference is None or resolution is None: raise ValueError("Prepare the Relight reference before entering the GPU worker.") width, height = request_canvas(data) if reference.size != (width, height) or _native_dimensions(resolution, width / height) != reference.size: raise ValueError("Relight reference and output canvas must match exactly.") seed = _number(data.get("seed"), "Seed", 0, MAX_SEED, integer=True) budget = _number(kv_budget_gb, "KV-cache budget", 0, 1024) names = ([speed] if speed else []) + list(user_adapters) weights = ([1.0] if speed else []) + list(user_weights) combined = {} for name, weight in zip(names, weights): if not isinstance(name, str) or not name: raise ValueError("Optional adapter names must be nonempty text.") weight = _number(weight, "LoRA strength", -10, 10) combined[name] = combined.get(name, 0.0) + weight prefix_tokens = (width // 16) * (height // 16) original_scheduler = pipe.scheduler try: pipe.enable_lora() if combined: pipe.set_adapters(list(combined), adapter_weights=list(combined.values())) else: pipe.disable_lora() pipe.scheduler = FlowMatchEulerDiscreteScheduler.from_config(base_scheduler_config, **scheduler_options) pipe.vae.disable_tiling() with torch.inference_mode(): latents = pipe( prompt=prompt, image=[reference], width=width, height=height, output_resolution=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))) return blend_result(result, reference, strength) finally: pipe.scheduler = original_scheduler pipe.vae.disable_tiling() pipe.enable_lora() pipe.set_adapters([turbo_adapter], adapter_weights=[1.0])