"""Pinned Multiple-Angles v2 on the studio's shared Qwen Image 2.1 pipeline. Preparation is CPU-only. The caller owns the shared pipeline lock and GPU lease; this module attaches one small camera adapter, never another base model. The default recipe is the camera author's native sampler (no speed adapter, 40 steps, CFG 1). Live tests on 17 Nov 2026 showed that the two-step DMD2 combination mostly kept the original view (a head turn instead of a camera move). The native sampler moved the camera to true side and back views. At adapter strength 1 real photos often became isolated studio renders, so the default strength is 0.5, which kept the rotation and more of the scene. """ import json import math import os import random import struct from bfs_backend import DMD2_SCHEDULER, DMD2_SIGMAS, MODE_DMD2, select_speed_adapter, specialist_guidance CAMERA_REPO = "akhaliq/Qwen-Image-2.1-Multiple-Angles-LoRA" CAMERA_FILE = "checkpoints_v2/angles_v2_full_qwen21_multiple_angles_v2_qwen21_multiple_angles_v2_000001500.safetensors" CAMERA_REVISION = "175b29b6eb41307473eebc363fca8fc198216b60" CAMERA_SHA256 = "548c57977c3f1c09c2c9e5f4e83e930cbc6f719c878a576ab8666ce29fef39b6" CAMERA_FILE_SIZE = 318819792 CAMERA_ADAPTER = "qwen21-multiple-angles-v2-1500" MODE_TURBO = "Turbo (6 steps)" MODE_BASE = "Base (30 steps, no Viggle)" DEFAULT_MODE = MODE_BASE DEFAULT_STEPS, MIN_STEPS, MAX_STEPS = 40, 10, 50 DEFAULT_STRENGTH, MIN_STRENGTH, MAX_STRENGTH = 0.5, 0.3, 1.5 REFERENCE_RESOLUTION = 1024 MAX_SEED = 2**31 - 1 # These are the trained captions, not numeric instructions interpreted by Qwen. AZIMUTH_LABELS = { 0: "front view", 30: "front-right view", 60: "front-right quarter view", 90: "right side view", 120: "back-right quarter view", 150: "back-right view", 180: "back view", 210: "back-left view", 240: "back-left quarter view", 270: "left side view", 300: "front-left quarter view", 330: "front-left view", } ELEVATION_LABELS = { 0: "eye-level shot", 30: "elevated shot", 60: "high-angle shot", 90: "top-down shot", } AZIMUTH_CHOICES = [(f"{angle}\N{DEGREE SIGN} — {label}", angle) for angle, label in AZIMUTH_LABELS.items()] ELEVATION_CHOICES = [(f"{angle}\N{DEGREE SIGN} — {label}", angle) for angle, label in ELEVATION_LABELS.items()] 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 angle_settings(data): azimuth = _number(data.get("camera_azimuth", 90), "Camera azimuth", 0, 330, integer=True) elevation = _number(data.get("camera_elevation", 0), "Camera elevation", 0, 90, integer=True) if azimuth not in AZIMUTH_LABELS: raise ValueError("Choose a Camera azimuth in 30-degree increments from 0 to 330.") if elevation not in ELEVATION_LABELS: raise ValueError("Choose Camera elevation 0, 30, 60, or 90 degrees.") closeup = data.get("camera_closeup", False) if not isinstance(closeup, bool): raise ValueError("Camera close-up must be true or false.") return azimuth, elevation, closeup def _caption(azimuth, elevation, closeup): return f" {AZIMUTH_LABELS[azimuth]}, {ELEVATION_LABELS[elevation]}" + (" close-up" if closeup else "") def canonical_prompt(data): """Return only the author's deterministic caption for the selected pose.""" return _caption(*angle_settings(data)) def render_view(data): """Return the pose actually rendered and whether the photo is mirrored. Live tests showed that the adapter follows right-side captions, while some subjects ignored left-side captions and still turned right. A left view is therefore the mirror image of the matching right view of the mirrored photo. """ azimuth, elevation, closeup = angle_settings(data) if 180 < azimuth < 360: return 360 - azimuth, elevation, closeup, True return azimuth, elevation, closeup, False def render_prompt(data): """Caption sent to the model: the requested pose, or its mirrored right side.""" return _caption(*render_view(data)[:3]) def is_base(data): mode = data.get("qwen_mode", DEFAULT_MODE) if mode not in (MODE_TURBO, MODE_DMD2, MODE_BASE): raise ValueError("Choose Turbo, DMD2, or Base for Camera Angle.") return mode == MODE_BASE def is_dmd2(data): return data.get("qwen_mode", DEFAULT_MODE) == MODE_DMD2 def _settings(data): base, dmd2 = is_base(data), is_dmd2(data) steps = (len(DMD2_SIGMAS) if dmd2 else _number(data.get("steps", DEFAULT_STEPS if base else 6), "Camera Angle steps", MIN_STEPS if base else 4, MAX_STEPS if base else 8, integer=True)) strength = _number(data.get("camera_strength", DEFAULT_STRENGTH), "Camera strength", MIN_STRENGTH, MAX_STRENGTH) megapixels = _number(data.get("target_megapixels", 1.0), "Camera megapixels", .5, 2) angle_settings(data) specialist_guidance(data, dmd2) return steps, strength, megapixels def source_image(data): """Read one image, honor EXIF, and composite transparency onto white.""" from PIL import Image, ImageOps value = data.get("input_image_1") if value is None: raise ValueError("Camera Angle needs Image 1 (the subject to view from a new angle).") try: if isinstance(value, Image.Image): image = ImageOps.exif_transpose(value).copy() else: if isinstance(value, dict): value = value.get("path") or value.get("name") with Image.open(value) as opened: image = ImageOps.exif_transpose(opened).copy() if image.width < 1 or image.height < 1: raise ValueError("empty source") if image.mode in ("RGBA", "LA", "P"): image = image.convert("RGBA") background = Image.new("RGBA", image.size, (255, 255, 255, 255)) background.alpha_composite(image) image = background return image.convert("RGB") except (TypeError, OSError, ValueError, AttributeError) as error: raise ValueError("Camera Angle could not read Image 1; choose a valid, nonempty image.") from error def _dimensions(area, ratio): width = max(32, int(round(math.sqrt(area * ratio) / 32)) * 32) height = max(32, int(round(math.sqrt(area / ratio) / 32)) * 32) if min(width, height) < 256 or max(width, height) > 8192: raise ValueError("Camera Angle image sides must stay within 256-8192 pixels; use a less extreme aspect ratio.") return width, height def reference_size(width, height): return _dimensions(REFERENCE_RESOLUTION**2, width / height) def request_canvas(data): """Keep Image 1's aspect ratio at the chosen area, rounded to native /32.""" _, _, megapixels = _settings(data) source = source_image(data) reference_size(*source.size) return _dimensions(megapixels * 1024**2, source.width / source.height) def _expected_shapes(): """Exact rank-64 checkpoint schema, verified from the pinned public header.""" modules = {"attn.to_q": (4096, 4096), "attn.to_k": (4096, 4096), "attn.to_v": (4096, 4096), "attn.to_out.0": (4096, 4096), "img_mlp.gate_up": (24576, 4096), "img_mlp.out": (4096, 12288)} shapes = {} for block in range(32): for name, (rows, columns) in modules.items(): prefix = f"diffusion_model.transformer_blocks.{block}.{name}" shapes[f"{prefix}.lora_A.weight"] = (64, columns) shapes[f"{prefix}.lora_B.weight"] = (rows, 64) return shapes def _validate_header(header, payload_size): expected = _expected_shapes() if not isinstance(header, dict) or set(header) - {"__metadata__"} != set(expected): raise ValueError("Camera Angle v2 requires its complete 384-tensor rank-64 checkpoint.") spans = [] for key, shape in expected.items(): entry = header[key] if (not isinstance(entry, dict) or entry.get("dtype") != "F16" or entry.get("shape") != list(shape) or any(type(dimension) is not int for dimension in entry["shape"])): raise ValueError(f"Camera Angle v2 has an incompatible tensor: {key}.") offsets = entry.get("data_offsets") if (not isinstance(offsets, list) or len(offsets) != 2 or any(type(value) is not int for value in offsets) or offsets[0] < 0 or offsets[1] - offsets[0] != math.prod(shape) * 2): raise ValueError(f"Camera Angle v2 has invalid tensor offsets: {key}.") spans.append(tuple(offsets)) cursor = 0 for start, end in sorted(spans): if start != cursor: raise ValueError("Camera Angle v2 has overlapping or missing tensor data.") cursor = end if cursor != payload_size: raise ValueError("Camera Angle v2 tensor data is truncated or has an unexpected size.") def validate_camera_lora(path): """Validate the complete pinned safetensors schema on CPU without torch.""" try: if os.path.getsize(path) != CAMERA_FILE_SIZE: raise ValueError("Camera Angle v2 download is incomplete or is the wrong checkpoint.") with open(path, "rb") as handle: size_bytes = handle.read(8) if len(size_bytes) != 8: raise ValueError("Camera Angle v2 is missing its safetensors header.") header_size = struct.unpack("