"""Collapse the requested surfaces into the smallest set of diffusion passes. Each pass costs 10-45 s, so passes are the expensive unit and the goal is to run as few as possible without diluting any prompt. Two surfaces share a pass when they share both a material and a plane kind. Material, because the prompt and the numeric tuning are per-material -- mixing wood and marble into one prompt degrades both. Plane kind, because the wording differs between a floor and a wall even for the same material, so a marble floor and a marble wall stay separate despite the identical tuning. Groups are made disjoint on the way out. Wall components are already disjoint upstream, but the guarantee is cheap to enforce here and it means a later pass can never overwrite an earlier one's work at a shared corner. """ from __future__ import annotations import numpy as np from services.refine.profiles import normalize_material_type, normalize_surface_kind def group_surfaces_by_material( surfaces: list[dict], masks_by_id: dict[int, np.ndarray], ) -> list[dict]: """Return one entry per diffusion pass, in request order. `surfaces` entries carry segmentIds, materialType and surfaceKind. `masks_by_id` maps a bundle segment id to its uint8 surface mask. Segment ids with no mask are skipped, and a group left with no pixels is dropped -- a stale id from the client should not fail the whole request. """ if not surfaces or not masks_by_id: return [] shape = next(iter(masks_by_id.values())).shape[:2] ordered_keys: list[tuple[str, str]] = [] accumulated: dict[tuple[str, str], dict] = {} for surface in surfaces: material = normalize_material_type(surface.get("materialType")) kind = normalize_surface_kind(surface.get("surfaceKind")) key = (material, kind) if key not in accumulated: ordered_keys.append(key) accumulated[key] = { "materialType": material, "surfaceKind": kind, "materialDescription": str(surface.get("materialDescription") or ""), "segmentIds": [], "mask": np.zeros(shape, dtype=np.uint8), } group = accumulated[key] if not group["materialDescription"] and surface.get("materialDescription"): group["materialDescription"] = str(surface["materialDescription"]) for segment_id in surface.get("segmentIds") or []: mask = masks_by_id.get(int(segment_id)) if mask is None: continue group["segmentIds"].append(int(segment_id)) group["mask"] = np.maximum(group["mask"], (mask > 0).astype(np.uint8)) groups: list[dict] = [] claimed = np.zeros(shape, dtype=bool) for key in ordered_keys: group = accumulated[key] group["mask"][claimed] = 0 if not group["mask"].any(): continue claimed |= group["mask"].astype(bool) group["pixels"] = int(group["mask"].sum()) groups.append(group) return groups