SUPRA-Tex: 3D Generation with Super-Aligned Texture
Gate single-view observations on image/geometry depth agreement
chensjtuef148d7d4d77
diff --git a/docs/frontend.md b/docs/frontend.mdindex a73a4e0..fa2dced 100644--- a/docs/frontend.md+++ b/docs/frontend.md@@ -43,7 +43,13 @@ checkpoint revision. Runtime and dependency paths must be local directories.For the same options on `infer.py`, use `--material-revision` instead of`--revision` (which selects the completion model there).Use a fresh output directory. The handoff contains `condition_rgba.png`,-`condition_rgb.png`, `camera.json`, `albedo.png`, and `mra.png`.+`condition_rgb.png`, `camera.json`, `image_depth.npy`, `albedo.png`, and `mra.png`.+`image_depth.npy` is the MoGe-2 camera-z depth on the condition pixel grid+(NaN where invalid). Single-view completion uses it to exclude source pixels+whose depth disagrees with the generated geometry near depth edges, and it skips+this gate when the depth is missing or degenerate. Pass `--no-image-depth` to+omit it; `--record-material-provenance` omits it because dual-view completion+does not support the gate.For an existing non-opaque foreground RGBA, omit `--with-rmbg` during preparationand replace `--rmbg-model` with `--use-input-alpha` in the frontend command.@@ -127,7 +133,7 @@ Individual foreground, camera, and FireRed stages remain available:python -m supratex.frontend.preprocess --input input.png --rmbg-model /models/rmbg2 \--output-dir workpython -m supratex.frontend.camera --image work/condition_rgb.png --model /models/moge2 \- --output work/camera.json+ --output work/camera.json --depth-output work/image_depth.npypython -m supratex.frontend.firered --base-model /models/firered-base \--condition work/condition_rgb.png --weights full_transformer.safetensors \--spec joint_contract.json --checkpoint-manifest checkpoint_complete.json --output work/materialdiff --git a/supratex/frontend/camera.py b/supratex/frontend/camera.pyindex 87bbd2f..f08b13d 100644--- a/supratex/frontend/camera.py+++ b/supratex/frontend/camera.py@@ -29,10 +29,41 @@ def camera_from_intrinsics(intrinsics: np.ndarray, width: int, height: int, *, r"moge_resolution_level": int(resolution_level)}+def _image_depth(result: dict, width: int, height: int) -> np.ndarray:+ """Copy MoGe camera-z, rejecting outputs that changed the source pixel grid."""+ value = result.get("depth")+ if value is None:+ raise ValueError("MoGe did not return an image depth map")+ depth = value.detach().float().cpu().numpy()+ if depth.shape == (1, height, width):+ depth = depth[0]+ if depth.shape != (height, width):+ raise ValueError("MoGe depth must preserve the input image pixel grid")+ valid = np.isfinite(depth) & (depth > 0)+ mask = result.get("mask")+ if mask is not None:+ mask = mask.detach().cpu().numpy()+ if mask.shape == (1, height, width):+ mask = mask[0]+ if mask.shape != depth.shape:+ raise ValueError("MoGe valid mask must match the image depth grid")+ valid &= np.isfinite(mask) & (mask > 0)+ return np.where(valid, depth, np.nan).astype(np.float32)++def estimate(image: Path, model_path: Path, module_name: str = "moge.model.v2", resolution_level: int = 9,- device: str = "cuda") -> dict:+ device: str = "cuda", *, depth_output: Path | None = None) -> dict:+ """Estimate the camera and optionally save depth on the unchanged input pixel grid.++ Invalid model pixels become NaN. No crop, resize, or second model call is+ involved; the texture loader resizes this map with the same image frame.+ """if not 0 <= resolution_level <= 9:raise ValueError("resolution_level must be in [0, 9]")+ if depth_output is not None:+ depth_output = Path(depth_output)+ if depth_output.exists():+ raise FileExistsError(f"image depth output must be new: {depth_output}")module = importlib.import_module(module_name)model_cls = getattr(module, "MoGeModel", None)if model_cls is None:@@ -49,8 +80,14 @@ def estimate(image: Path, model_path: Path, module_name: str = "moge.model.v2",tensor = torch.from_numpy(np.asarray(rgb, dtype=np.float32) / 255.0).permute(2, 0, 1).to(device)with torch.inference_mode():result = model.infer(tensor, resolution_level=resolution_level, force_projection=True, apply_mask=True)- return camera_from_intrinsics(result["intrinsics"].squeeze().float().cpu().numpy(), width, height,- resolution_level=resolution_level)+ camera = camera_from_intrinsics(result["intrinsics"].squeeze().float().cpu().numpy(), width, height,+ resolution_level=resolution_level)+ if depth_output is not None:+ depth = _image_depth(result, width, height)+ depth_output.parent.mkdir(parents=True, exist_ok=True)+ with depth_output.open("xb") as stream:+ np.save(stream, depth, allow_pickle=False)+ return camerafinally:model.cpu()del tensor, result, model@@ -67,9 +104,11 @@ def main() -> None:help="MoGe-2 detail level from 0 (fastest) to 9 (highest).")parser.add_argument("--device", default="cuda")parser.add_argument("--output", type=Path, required=True)+ parser.add_argument("--depth-output", type=Path, help="save image-aligned camera-z as .npy; invalid pixels become NaN")args = parser.parse_args()args.output.parent.mkdir(parents=True, exist_ok=True)- args.output.write_text(json.dumps(estimate(args.image, args.model, args.module, args.resolution_level, args.device), indent=2) + "\n")+ args.output.write_text(json.dumps(estimate(args.image, args.model, args.module, args.resolution_level, args.device,+ depth_output=args.depth_output), indent=2) + "\n")if __name__ == "__main__":diff --git a/supratex/frontend/pipeline.py b/supratex/frontend/pipeline.pyindex 444dc14..c6169c8 100644--- a/supratex/frontend/pipeline.py+++ b/supratex/frontend/pipeline.py@@ -111,7 +111,7 @@ def run(input_image: Path, output: Path, *, moge_model: str | Path,geometry_scale_search: bool = False, geometry_target_padding: int = 3, geometry_max_iterations: int = 2,geometry_seed: int = 42, record_material_provenance: bool = False,attention: str = "auto", low_vram: bool | None = None,- parallel_frontend: bool = False) -> dict[str, str]:+ parallel_frontend: bool = False, export_image_depth: bool = True) -> dict[str, str]:"""Build the condition, canonical camera, and material-map handoff in one directory."""if record_material_provenance and firered_manifest is not None:raise ValueError("material provenance does not support a custom FireRed manifest; "@@ -168,7 +168,11 @@ def run(input_image: Path, output: Path, *, moge_model: str | Path,finally:if estimator is not None:estimator.close()- camera = estimate(rgb, moge_model, moge_module, resolution_level, device)+ # Depth gating is single-view only; a dual-view front packet must omit it.+ export_image_depth = export_image_depth and not record_material_provenance+ depth_path = output / "image_depth.npy"+ camera = estimate(rgb, moge_model, moge_module, resolution_level, device,+ **({"depth_output": depth_path} if export_image_depth else {}))camera["foreground_source"] = foreground_sourcecamera_path = output / "camera.json"camera_path.write_text(json.dumps(camera, indent=2) + "\n", encoding="utf-8")@@ -222,6 +226,8 @@ def run(input_image: Path, output: Path, *, moge_model: str | Path,result = {"condition_rgba": str(rgba), "condition_rgb": str(rgb), "camera": str(camera_path),"albedo": str(final_albedo), "mra": str(final_mra), "foreground_source": foreground_source,"material_backend": material_backend}+ if export_image_depth:+ result["image_depth"] = str(depth_path)if geometry_result:result.update(geometry=str(geometry_path), geometry_receipt=geometry_result["receipt"])return result@@ -261,6 +267,8 @@ def main() -> None:parser.add_argument("--material-checkpoint-manifest", type=Path)parser.add_argument("--key", default="input")parser.add_argument("--record-material-provenance", action="store_true", help="write material bindings for optional dual-view inference")+ parser.add_argument("--no-image-depth", action="store_true",+ help="omit the optional image_depth.npy filtering input (implied by --record-material-provenance)")parser.add_argument("--device", default="cuda")parser.add_argument("--attention", choices=("auto", "flash_attn_3", "flash_attn", "sdpa", "xformers"), default="auto")parser.add_argument("--low-vram", action=argparse.BooleanOptionalAction, default=None,@@ -284,6 +292,7 @@ def main() -> None:rmbg_model=args.rmbg_model, use_input_alpha=args.use_input_alpha, device=args.device,moge_module=args.moge_module, resolution_level=args.resolution_level, key=args.key,record_material_provenance=args.record_material_provenance,+ export_image_depth=not args.no_image_depth,attention=args.attention, low_vram=args.low_vram), indent=2))diff --git a/supratex/inference/image_depth.py b/supratex/inference/image_depth.pynew file mode 100644index 0000000..181aa97--- /dev/null+++ b/supratex/inference/image_depth.py@@ -0,0 +1,115 @@+"""Conservative image/geometry depth consistency for source-pixel admission.++An auxiliary depth map supplies evidence about image-to-surface correspondence;+it is not ground truth. Invalid or degenerate fits leave the existing admission+rules unchanged and report why the additional gate was disabled.+"""+from __future__ import annotations++import math++import numpy as np++IMAGE_DEPTH_GAP = 0.02+IMAGE_DEPTH_HIGHPASS = 41+IMAGE_DEPTH_BOUNDARY_RADIUS = 16+MIN_FIT_PIXELS = 1000+++def image_depth_disagreement(depth: np.ndarray, image_depth: np.ndarray,+ gap: float = IMAGE_DEPTH_GAP,+ highpass: int = IMAGE_DEPTH_HIGHPASS,+ boundary_radius: int = IMAGE_DEPTH_BOUNDARY_RADIUS,+ stats: dict | None = None) -> np.ndarray:+ """Return suspicious source pixels, using camera-z depths on the same grid.++ ``gap`` is an absolute canonical length (unit object cube). ``highpass``+ and ``boundary_radius`` are pixels of the observation grid, normally 1024.+ The latter is a square/Chebyshev radius. Pixels without two finite positive+ depths are never rejected. A source pixel is rejected only when its local+ residual exceeds ``gap`` near a depth edge in the fitted image-depth map.+ ``stats`` receives JSON-safe fit diagnostics, including disabled reasons.+ """+ from scipy.ndimage import maximum_filter, median_filter, minimum_filter++ depth = np.asarray(depth)+ image_depth = np.asarray(image_depth)+ if depth.ndim != 2 or image_depth.shape != depth.shape:+ raise ValueError("geometry and image depths must be matching 2D maps")+ if not math.isfinite(gap) or gap <= 0:+ raise ValueError("image-depth gap must be finite and positive")+ if not isinstance(highpass, int) or highpass < 1 or highpass % 2 != 1:+ raise ValueError("image-depth highpass must be a positive odd size")+ if not isinstance(boundary_radius, int) or boundary_radius < 0:+ raise ValueError("image-depth boundary radius must be nonnegative")++ valid_image = np.isfinite(image_depth) & (image_depth > 0)+ both = np.isfinite(depth) & (depth > 0) & valid_image+ reject = np.zeros(depth.shape, dtype=bool)+ report = {"status": "disabled", "reason": "insufficient_valid_depth",+ "valid_pixels": int(both.sum()), "gap": float(gap),+ "highpass": highpass, "boundary_radius": boundary_radius,+ "rejected_pixels": 0}++ def disabled(reason: str) -> np.ndarray:+ report["reason"] = reason+ if stats is not None:+ stats.update(report)+ return reject++ if report["valid_pixels"] < MIN_FIT_PIXELS:+ return disabled("insufficient_valid_depth")+ x, y = image_depth[both].astype(np.float64), depth[both].astype(np.float64)+ keep = np.ones(x.size, dtype=bool)+ for iteration in range(3):+ count = int(keep.sum())+ if count < MIN_FIT_PIXELS:+ return disabled("insufficient_fit_inliers")+ xx, yy = x[keep], y[keep]+ # Center the fit to avoid an ill-conditioned [large-depth, 1] matrix.+ # A single depth layer cannot identify both scale and offset.+ xmean, ymean = float(xx.mean()), float(yy.mean())+ span = float(np.ptp(xx))+ if span <= 1e-6 * max(float(np.max(np.abs(xx))), 1.0):+ return disabled("degenerate_image_depth_span")+ dx, dy = xx - xmean, yy - ymean+ variance = float(np.mean(dx * dx))+ if variance <= np.finfo(np.float64).eps * max(xmean * xmean, 1.0):+ return disabled("degenerate_image_depth_variance")+ a = float(np.mean(dx * dy) / variance)+ b = ymean - a * xmean+ if not math.isfinite(a) or not math.isfinite(b) or a <= 0:+ return disabled("invalid_affine_fit")+ residual = np.abs(y - (a * x + b))+ if not np.isfinite(residual).all():+ return disabled("nonfinite_affine_residual")+ report.update(fit_iterations=iteration + 1, fit_pixels=count,+ scale=a, offset=b,+ median_absolute_residual=float(np.median(residual)))+ if iteration < 2:+ # Include percentile ties. Strict '<' can discard every pixel of+ # an exactly aligned plane, or all of one of two depth layers.+ threshold = float(np.percentile(residual, 80))+ tolerance = 64 * np.finfo(np.float64).eps * max(float(np.max(np.abs(y))), 1.0)+ keep = residual <= threshold + tolerance++ fitted = np.full(depth.shape, np.nan, dtype=np.float32)+ fitted[valid_image] = (a * image_depth[valid_image].astype(np.float64) + b).astype(np.float32)+ if not np.isfinite(fitted[both]).all() or not (fitted[both] > 0).all():+ return disabled("invalid_fitted_depth")+ full = np.zeros(depth.shape, dtype=np.float32)+ full[both] = depth[both] - fitted[both]+ smooth = median_filter(full, size=highpass)+ maximum = maximum_filter(np.where(valid_image, fitted, -np.inf), size=3,+ mode="constant", cval=-np.inf)+ minimum = minimum_filter(np.where(valid_image, fitted, np.inf), size=3,+ mode="constant", cval=np.inf)+ with np.errstate(invalid="ignore"):+ boundary = valid_image & np.isfinite(maximum) & np.isfinite(minimum) & ((maximum - minimum) > gap)+ near = maximum_filter(boundary, size=2 * boundary_radius + 1, mode="constant", cval=0)+ reject[both] = (np.abs((full - smooth)[both]) > gap) & near[both]+ report.update(status="applied", reason=None, rejected_pixels=int(reject.sum()),+ boundary_pixels=int(boundary.sum()))+ if stats is not None:+ stats.update(report)+ return rejectdiff --git a/supratex/inference/native_observation.py b/supratex/inference/native_observation.pyindex e3a9118..24a2faf 100644--- a/supratex/inference/native_observation.py+++ b/supratex/inference/native_observation.py@@ -11,6 +11,8 @@ from typing import Anyimport numpy as npimport torch+from .image_depth import image_depth_disagreement+RESOLUTION = 1024LATENT_RESOLUTION = 64@@ -233,10 +235,16 @@ def _admitted_pixels(depth: np.ndarray, missed: np.ndarray, focal: tuple[float,def pixel_first_occupied(camera: dict[str, Any], occupancy: np.ndarray, trusted: torch.Tensor, depth_edge_rtol: float = 0.04,- stats: dict | None = None) -> torch.Tensor:- """Map trusted camera pixels to their first occupied volume cell."""+ stats: dict | None = None, image_depth: np.ndarray | None = None,+ admitted_out: dict | None = None) -> torch.Tensor:+ """Map trusted pixels to first occupied cells, optionally excluding depth conflicts.++ ``admitted_out['pixels']`` is the complementary image-depth-conflict mask+ for reprojection, not the union of all observation admission rules.+ """if "extrinsic" in camera:- return pixel_first_occupied_cv(camera, occupancy, trusted, depth_edge_rtol, stats=stats)+ return pixel_first_occupied_cv(camera, occupancy, trusted, depth_edge_rtol, stats=stats,+ image_depth=image_depth, admitted_out=admitted_out)if trusted.shape != (RESOLUTION, RESOLUTION):raise ValueError("trusted alpha mask must be 1024 by 1024")if "camera_angle_x" not in camera or "distance" not in camera:@@ -261,6 +269,12 @@ def pixel_first_occupied(camera: dict[str, Any], occupancy: np.ndarray, trusted:admitted = _admitted_pixels(depth, missed, (focal, focal), depth_edge_rtol, stats=stats)retained = hit_mask.copy()retained[hit_mask] &= admitted[y[hit_mask], x[hit_mask]]+ if image_depth is not None:+ mismatch = _image_depth_mask(camera, occupancy, image_depth, stats, admitted_out)+ rejected = retained & mismatch[y, x]+ retained &= ~mismatch[y, x]+ if stats is not None:+ stats.update(rejected_image_depth=int(rejected.sum()), admitted=int(retained.sum()))hit = owners[retained]if not hit.size:raise RuntimeError("observation admission removed every first-hit observation")@@ -292,6 +306,54 @@ def camera_rays(camera: dict[str, Any], ys: np.ndarray, xs: np.ndarray) -> tuplereturn eye, directions, rotation+def first_hit_depth(camera: dict[str, Any], occupancy: np.ndarray) -> np.ndarray:+ """Return full-grid first-hit camera-z for canonical and complete CV cameras.++ The canonical camera looks down world -z; its positive view depth is+ ``eye_z - world_z``. CV cameras instead use the z component after their+ world-to-camera rotation. Neither convention uses Euclidean ray length.+ """+ ys, xs = np.mgrid[0:RESOLUTION, 0:RESOLUTION]+ ys, xs = ys.ravel(), xs.ravel()+ if "extrinsic" in camera:+ eye, directions, rotation = camera_rays(camera, ys, xs)+ else:+ angle = float(camera["camera_angle_x"])+ distance = float(camera["distance"]) * float(camera.get("mesh_scale", 1.0))+ if not math.isfinite(angle) or not 0 < angle < math.pi or not math.isfinite(distance) or distance <= 0:+ raise ValueError("canonical camera requires a finite FOV in (0, pi) and positive effective distance")+ # Keep the arithmetic order of the canonical admission ray builder.+ focal = 16.0 / math.tan(angle / 2.0) * RESOLUTION / 32.0+ eye = np.array([0., 0., distance], dtype=np.float64)+ directions = np.column_stack(((xs + .5 - RESOLUTION / 2) / focal,+ -(ys + .5 - RESOLUTION / 2) / focal,+ -np.ones(xs.size))).astype(np.float64)+ rotation = np.diag([1., -1., -1.])+ owners, reasons, _ = _dda_batch_kernel()(eye, directions, occupancy, -.5, .5, RESOLUTION)+ hits = reasons == 0+ centers = (owners[hits].astype(np.float64) + .5) / RESOLUTION - .5+ values = ((centers - eye) @ rotation.T)[:, 2]+ if not np.isfinite(values).all() or not (values > 0).all():+ raise RuntimeError("first-hit owners must lie in front of the camera")+ result = np.full((RESOLUTION, RESOLUTION), np.nan, dtype=np.float32)+ result[ys[hits], xs[hits]] = values.astype(np.float32)+ return result+++def _image_depth_mask(camera: dict[str, Any], occupancy: np.ndarray, image_depth: np.ndarray,+ stats: dict | None, admitted_out: dict | None) -> np.ndarray:+ if np.asarray(image_depth).shape != (RESOLUTION, RESOLUTION):+ raise ValueError("image depth must be an observation-resolution map")+ diagnostic: dict[str, Any] = {}+ mismatch = image_depth_disagreement(first_hit_depth(camera, occupancy), image_depth, stats=diagnostic)+ if stats is not None:+ stats["image_depth"] = diagnostic+ if admitted_out is not None:+ admitted_out["pixels"] = ~mismatch+ admitted_out["image_depth"] = diagnostic+ return mismatch++def pixel_hits_cv(camera: dict[str, Any], occupancy: np.ndarray, mask: np.ndarray) -> np.ndarray:"""Return the raw first-hit silhouette, without trusted-mask depth filtering."""if mask.shape != (RESOLUTION, RESOLUTION) or mask.dtype != np.bool_:@@ -305,7 +367,8 @@ def pixel_hits_cv(camera: dict[str, Any], occupancy: np.ndarray, mask: np.ndarradef pixel_first_occupied_cv(camera: dict[str, Any], occupancy: np.ndarray, trusted: torch.Tensor,- depth_edge_rtol: float = .04, stats: dict | None = None) -> torch.Tensor:+ depth_edge_rtol: float = .04, stats: dict | None = None,+ image_depth: np.ndarray | None = None, admitted_out: dict | None = None) -> torch.Tensor:"""Apply the production first-hit admission rules to a full CV camera."""if trusted.shape != (RESOLUTION, RESOLUTION) or trusted.dtype != torch.bool:raise ValueError("trusted alpha must be a boolean observation-resolution image")@@ -330,6 +393,12 @@ def pixel_first_occupied_cv(camera: dict[str, Any], occupancy: np.ndarray, trustintrinsic = np.asarray(camera.get("projection_intrinsic", camera.get("intrinsic")), dtype=np.float64)focal = (float(intrinsic[0, 0]) * RESOLUTION, float(intrinsic[1, 1]) * RESOLUTION)retained = hits & _admitted_pixels(depth, missed, focal, depth_edge_rtol, stats=stats)[ys, xs]+ if image_depth is not None:+ mismatch = _image_depth_mask(camera, occupancy, image_depth, stats, admitted_out)+ rejected = retained & mismatch[ys, xs]+ retained &= ~mismatch[ys, xs]+ if stats is not None:+ stats.update(rejected_image_depth=int(rejected.sum()), admitted=int(retained.sum()))kept = owners[retained].astype(np.int64, copy=False)if not kept.size:raise RuntimeError("observation admission removed every first-hit observation")diff --git a/supratex/inference/pipeline.py b/supratex/inference/pipeline.pyindex 379e6e2..1ca1c7f 100644--- a/supratex/inference/pipeline.py+++ b/supratex/inference/pipeline.py@@ -196,6 +196,17 @@ def _load_case(input_dir: str | Path, torch: Any, image: Any, remove_floaters: braise ValueError("camera.json must be valid JSON") from errorif "camera_angle_x" not in camera or "distance" not in camera:raise ValueError("camera.json must provide canonical camera_angle_x and distance")+ image_depth = None+ if (root / "image_depth.npy").is_file():+ import numpy as np+ raw = np.load(root / "image_depth.npy", allow_pickle=False)+ if raw.shape != rgba.size[::-1]:+ raise ValueError("image_depth.npy must match the condition_rgba.png pixel grid")+ if raw.dtype.kind not in "fiu":+ raise ValueError("image_depth.npy must contain numeric camera-z depths")+ raw = raw.astype(np.float32)+ raw[~np.isfinite(raw) | (raw <= 0)] = np.nan+ image_depth = np.asarray(image.fromarray(raw).resize((RESOLUTION, RESOLUTION), image.Resampling.NEAREST), dtype=np.float32)if remove_floaters:import numpy as npfrom .geometry_cleanup import remove_floaters as clean@@ -203,7 +214,8 @@ def _load_case(input_dir: str | Path, torch: Any, image: Any, remove_floaters: bvertices, faces = vertices.contiguous(), faces.contiguous()print(f"Floaters: removed {report['removed_components']} of {report['components']} components "f"({report['removed_faces']} of {report['faces']} faces)", flush=True)- return {"vertices": vertices, "faces": faces, "rgba": rgba, "albedo": albedo, "mra": mra, "camera": camera}+ return {"vertices": vertices, "faces": faces, "rgba": rgba, "albedo": albedo, "mra": mra, "camera": camera,+ "image_depth": image_depth}def _runtime() -> dict[str, Any]:@@ -266,7 +278,8 @@ def _alignment_report(uv: Any, alpha: Any, admission: Mapping[str, int], np: Anyrejected = [f"missed geometry {admission['trusted_rays'] - admission['first_hits']}",f"depth edge {admission['rejected_depth_edge']}"]rejected += [f"{label} {admission[key]}" for key, label in (("rejected_silhouette", "silhouette margin"),- ("rejected_grazing", "grazing")) if admission[key]]+ ("rejected_grazing", "grazing"),+ ("rejected_image_depth", "image-depth mismatch")) if admission.get(key)]print(f"Observation: silhouette IoU {report['silhouette_iou']:.3f} "f"(geometry inside image {report['geometry_inside_image']:.3f}, image covered {report['image_covered_by_geometry']:.3f}); "f"admitted {admission['admitted']} of {admission['trusted_rays']} trusted pixels ({', '.join(rejected)})", flush=True)@@ -276,7 +289,20 @@ def _alignment_report(uv: Any, alpha: Any, admission: Mapping[str, int], np: Anyreturn report-def _partial(surface: Any, shape: Any, case: Mapping[str, Any], external: Any, projection: Any, encoder: Any, normalization: Mapping[str, Any], runtime: Mapping[str, Any], device: str) -> Any:+def _source_footprint_safe(keep: Any, grid: Any, runtime: Mapping[str, Any], device: str) -> Any:+ """Reject material samples with nonzero weight in a depth-mismatch pixel.++ Use the actual material-sampling grid and interpolation conventions, rather+ than a separately rounded CPU projection of voxel centres.+ """+ torch, F, np = runtime["torch"], runtime["F"], runtime["np"]+ unsafe = torch.from_numpy(np.asarray(~keep, dtype=np.float32)).to(device)[None, None]+ contribution = F.grid_sample(unsafe, grid, mode="bilinear", align_corners=False,+ padding_mode="border")[0, 0, 0]+ return contribution <= 1e-6+++def _partial(surface: Any, shape: Any, case: dict[str, Any], external: Any, projection: Any, encoder: Any, normalization: Mapping[str, Any], runtime: Mapping[str, Any], device: str) -> Any:torch, F, np, image, image_filter, sparse = runtime["torch"], runtime["F"], runtime["np"], runtime["Image"], runtime["ImageFilter"], runtime["sparse"]coords = surface.coords[:, 1:].long(); points = (coords.float() + .5) / RESOLUTION - .5camera = (torch.cat((points, torch.ones_like(points[:, :1])), dim=1) @ external.T)[:, :3]@@ -289,10 +315,31 @@ def _partial(surface: Any, shape: Any, case: Mapping[str, Any], external: Any, pmask = image.fromarray(np.where(alpha >= 254, 255, 0).astype(np.uint8)).resize((RESOLUTION, RESOLUTION), image.Resampling.NEAREST).filter(image_filter.MinFilter(5))trusted = torch.from_numpy(np.asarray(mask, dtype=np.uint8).copy() == 255)bits, ordered, order = native_observation.build_occupancy_index(coords)- admission: dict[str, int] = {}- owners = native_observation.pixel_first_occupied(dict(case["camera"]), bits, trusted, stats=admission)+ admission: dict[str, Any] = {}+ admitted: dict[str, Any] = {}+ if case.get("image_depth") is None:+ owners = native_observation.pixel_first_occupied(dict(case["camera"]), bits, trusted, stats=admission)+ else:+ owners = native_observation.pixel_first_occupied(dict(case["camera"]), bits, trusted, stats=admission,+ image_depth=case["image_depth"], admitted_out=admitted)_alignment_report(uv, alpha, admission, np, image, image_filter)+ if admission.get("image_depth"):+ diagnostic = admission["image_depth"]+ detail = f" ({diagnostic['reason']})" if diagnostic.get("reason") else ""+ print(f"Image depth gate: {diagnostic['status']}{detail}; "+ f"{diagnostic['valid_pixels']} paired depth pixels, "+ f"{diagnostic['rejected_pixels']} mismatch pixels", flush=True)visible = native_observation.owner_rows(coords, owners, ordered, order)+ if "pixels" in admitted:+ keep = np.asarray(admitted["pixels"], dtype=bool)+ case["observation_keep"] = keep+ safe = _source_footprint_safe(keep, grid, runtime, device)+ admission["rejected_image_depth_footprint_owners"] = int((visible & ~safe).sum())+ visible &= safe+ admission["observed_voxels"] = int(visible.sum())+ case["observation_admission"] = admission+ print(f"Observation image depth: excluded {admission['rejected_image_depth_footprint_owners']} "+ f"additional voxel samples crossing the mismatch mask; {admission['observed_voxels']} observed voxels", flush=True)if not bool(visible.any()): raise RuntimeError("the trusted alpha gate leaves no observed material surface")with torch.no_grad():return native_observation.encode_partial(encoder, coords, visible, sampled(case["albedo"]), sampled(case["mra"]), shape.coords[:, 1:], dict(normalization), sparse, device)@@ -441,6 +488,8 @@ def _run_completion_low_vram(*, case: Mapping[str, Any], back_case: Mapping[str,representation = runtime["MeshWithVoxel"](case["vertices"], case["faces"], [-.5, -.5, -.5], 1. / RESOLUTION, decoded_cpu.coords[:, 1:].int(), decoded_cpu.feats.float().clamp(0, 1), torch.Size([1, 6, RESOLUTION, RESOLUTION, RESOLUTION]), layout=LAYOUT)del decoded_cpu_export(Path(output), representation, texture_size, decimation_target, texture_format, runtime, gutter=gutter, low_vram=True)+ if back_case is None and case.get("observation_keep") is not None:+ return {"observation_keep": case["observation_keep"], "observation_admission": case.get("observation_admission", {})}return dual_stats@@ -456,6 +505,9 @@ def _run_completion(*, input_dir: str | Path, output: str | Path, model_config:runtime = _runtime(); torch, models = runtime["torch"], runtime["models"]if not torch.cuda.is_available(): raise RuntimeError("CUDA is unavailable")case = _load_case(input_dir, torch, runtime["Image"], remove_floaters); ckpts = _completion_vae_root(trellis_root)+ if back_case is not None and (case.get("image_depth") is not None or back_case.get("image_depth") is not None):+ raise ValueError("image_depth.npy consistency gating currently supports single-view completion only; "+ "remove it or prepare the front view with --no-image-depth")if os.environ.get("SUPRATEX_LOW_VRAM", "0") == "1":return _run_completion_low_vram(case=case, back_case=back_case, ckpts=ckpts, config=config,dataset=dataset, checkpoint_path=checkpoint_path, partial_stats=partial_stats,@@ -499,6 +551,8 @@ def _run_completion(*, input_dir: str | Path, output: str | Path, model_config:if decoded.feats.shape[1] != 6: raise RuntimeError("material decoder must emit six PBR channels")representation = runtime["MeshWithVoxel"](case["vertices"].to(device), case["faces"].to(device), [-.5, -.5, -.5], 1. / RESOLUTION, decoded.coords[:, 1:].int(), decoded.feats.float().clamp(0, 1), torch.Size([1, 6, RESOLUTION, RESOLUTION, RESOLUTION]), layout=LAYOUT)_export(Path(output), representation, texture_size, decimation_target, texture_format, runtime, gutter=gutter)+ if back_case is None and case.get("observation_keep") is not None:+ return {"observation_keep": case["observation_keep"], "observation_admission": case.get("observation_admission", {})}return dual_stats@@ -566,7 +620,7 @@ def _run_front_reprojection(arguments: dict[str, Any], work_dir: str | Path | Nowrite_json(work / "receipt.json", receipt)try:native = work / "preds/mesh.glb"- _run_completion(**{**arguments, "input_dir": source, "output": native, "gutter": False})+ completion = _run_completion(**{**arguments, "input_dir": source, "output": native, "gutter": False})# Reprojection runs in separate CUDA workers; release cached blocks first.import gcimport torch@@ -576,7 +630,13 @@ def _run_front_reprojection(arguments: dict[str, Any], work_dir: str | Path | Nowrite_json(work / "receipt.json", receipt)from .reprojection import run_front_viewtry:- final = run_front_view(native, source, work / "reproject")+ keep = (completion or {}).get("observation_keep")+ if keep is None:+ final = run_front_view(native, source, work / "reproject")+ else:+ receipt["image_depth_admission"] = completion.get("observation_admission", {})+ receipt["reprojection_excluded_source_pixels"] = int((~keep).sum())+ final = run_front_view(native, source, work / "reproject", keep=keep)except Exception as error:_publish_unrefined(native, output, arguments["gutter"], error)receipt.update(status="valid", stage="complete", refine="skipped",@@ -606,6 +666,10 @@ def run_completion(*, input_dir: str | Path, output: str | Path, model_config: scheckpoint=checkpoint, trellis_root=trellis_root, seed=seed, device=device,texture_size=texture_size, decimation_target=decimation_target,texture_format=texture_format, gutter=gutter, remove_floaters=remove_floaters)+ if back_view_dir is not None and any((Path(root) / "image_depth.npy").is_file()+ for root in (input_dir, back_view_dir)):+ raise ValueError("image_depth.npy consistency gating currently supports single-view completion only; "+ "remove it or prepare the front view with --no-image-depth")# Dual-view refines both views itself, so --refine needs no separate pass there.if refine and back_view_dir is None:_run_front_reprojection(arguments, work_dir)diff --git a/supratex/inference/reprojection/__init__.py b/supratex/inference/reprojection/__init__.pyindex c39e054..bfbe511 100644--- a/supratex/inference/reprojection/__init__.py+++ b/supratex/inference/reprojection/__init__.py@@ -30,7 +30,7 @@ __all__ = ["run_dual_view", "run_front_view", "validate_dual_view"]PROFILE = "supratex.dual_view.reproject_continuous"-def _prepare_inputs(source: Path, destination: Path, camera: dict[str, Any]) -> dict[str, Any]:+def _prepare_inputs(source: Path, destination: Path, camera: dict[str, Any], keep: Any = None) -> dict[str, Any]:"""Align observation alpha and RGB once, preserving native albedo/MRA maps."""from PIL import Image@@ -45,6 +45,11 @@ def _prepare_inputs(source: Path, destination: Path, camera: dict[str, Any]) ->resized = rgb.convert("RGB").resize((1024, 1024), Image.Resampling.LANCZOS)alpha = rgba.convert("RGBA").getchannel("A").point(lambda value: 255 if value >= 254 else 0)alpha = alpha.resize((1024, 1024), Image.Resampling.NEAREST)+ if keep is not None:+ import numpy as np+ # Apply at the actual projection grid. A 1024 -> small source ->+ # 1024 round trip could otherwise resurrect thin rejected strips.+ alpha = Image.fromarray(np.where(keep, np.asarray(alpha), 0).astype(np.uint8))resized.save(destination / "condition_rgb.png")aligned = resized.copy()aligned.putalpha(alpha)@@ -75,13 +80,14 @@ def _command(module: str, arguments: list[str], log: Path) -> None:raise RuntimeError(f"reprojection worker failed with exit code {result}; see {log}")-def _run_side(baseline: Path, source: Path, output: Path, camera: dict[str, Any]) -> Path:+def _run_side(baseline: Path, source: Path, output: Path, camera: dict[str, Any], keep: Any = None) -> Path:"""Publish one view only after the projection and continuous candidates pass."""output.mkdir(parents=True)baseline_binding = bind_file(baseline)code = {path.name: bind_file(path) for path in Path(__file__).parent.glob("*.py")}inputs = output / "inputs_1024"- source_bindings = _prepare_inputs(source, inputs, camera)+ source_bindings = (_prepare_inputs(source, inputs, camera) if keep is None else+ _prepare_inputs(source, inputs, camera, keep=keep))input_bindings = {path.name: bind_file(path) for path in inputs.iterdir() if path.is_file()}renderer = Path(__file__).with_name("_renderer.py").resolve()project, continuous = output / "project", output / "continuous"@@ -185,13 +191,17 @@ def _validate_side(output: Path) -> dict[str, Any]:return receipt-def run_front_view(native_glb: Path, input_dir: Path, output_dir: Path) -> Path:+def run_front_view(native_glb: Path, input_dir: Path, output_dir: Path, keep: Any = None) -> Path:"""Reproject the single reference view onto a single-view result.This is the front half of dual-view texturing with the canonical referencecamera from ``camera.json``. Inputs are staged under ``output_dir`` so theirbindings stay valid; a missing ``condition_rgb.png`` is derived from theRGBA observation with black premultiplication, as the frontend writes it.+ Optional ``keep`` excludes source pixels identified as image/geometry depth+ mismatches. It changes only staged projection trust, not source RGB, source+ files, or the final mesh's opacity. Other observation-admission filters are+ not passed through this mask."""import numpy as npfrom PIL import Image@@ -201,6 +211,10 @@ def run_front_view(native_glb: Path, input_dir: Path, output_dir: Path) -> Path:if output.exists():raise FileExistsError(f"front reprojection requires a new destination: {output}")camera = read_json(source / "camera.json")+ if keep is not None:+ keep = np.asarray(keep)+ if keep.shape != (1024, 1024) or keep.dtype != np.bool_:+ raise ValueError("reprojection keep must be a boolean 1024 by 1024 source-image mask")try:camera = {"camera_angle_x": float(camera["camera_angle_x"]), "distance": float(camera["distance"]),"mesh_scale": float(camera.get("mesh_scale", 1.0))}@@ -216,6 +230,8 @@ def run_front_view(native_glb: Path, input_dir: Path, output_dir: Path) -> Path:with Image.open(source / "condition_rgba.png") as image:rgba = np.asarray(image.convert("RGBA"), dtype=np.float32) / 255.Image.fromarray((np.clip(rgba[..., :3] * rgba[..., 3:4], 0, 1) * 255).astype(np.uint8)).save(staged / "condition_rgb.png")+ if keep is not None:+ return _run_side(native, staged, output / "front", camera, keep=keep)return _run_side(native, staged, output / "front", camera)