"""Build source-conditioned appearance inputs in the target camera, with supervision kept separate.""" from collections import defaultdict from pathlib import Path import sys import time import cv2 import numpy as np from PIL import Image, ImageOps import torch from dual_cave_records import read, write, root_assets from train_cave_fidelity import get_rows, manifests, open_fidelity from train_dual_cave_metrics import artifact W = np.array([0.2126, 0.7152, 0.0722], "f4") def photograph(path): with Image.open(path) as im: img = ImageOps.exif_transpose(im).convert("RGB") img.thumbnail((760, 760), Image.Resampling.LANCZOS) return np.array(img) def smooth(a, sigma): return cv2.GaussianBlur(a, (0, 0), sigma, borderType=cv2.BORDER_REFLECT101) def profile(ref): """Estimate conditional colour and detail strength using only the observed source photograph.""" h, w = ref.shape[:2] scale = min(1, 704 / max(h, w)) ref = ( cv2.resize( ref, (max(1, round(w * scale)), max(1, round(h * scale))), interpolation=cv2.INTER_AREA, ).astype("f4") / 255 ) low = smooth(ref, 4) y = low @ W energy = smooth(np.abs(ref @ W - smooth(ref @ W, 1.3)), 3) chroma = low - y[..., None] axis = np.linspace(0.025, 0.975, 16, dtype="f4") lookup = [] for t in axis: m = np.abs(y - t) < 0.065 if m.sum() < 48: continue lookup.append( [ float(t), float(np.quantile(energy[m], 0.65)), *np.median(chroma[m], axis=0).tolist(), ] ) if not lookup: lookup = [[0.5, 0.006, 0, 0, 0]] q = np.array(lookup, "f4") lut = np.stack( [np.interp(axis, q[:, 0], q[:, i]) for i in range(1, 5)], axis=1 ).astype("f4") quant = np.quantile(y, np.linspace(0.05, 0.95, 11)).astype("f4") feat = np.concatenate( [ np.quantile(ref.reshape(-1, 3), [0.10, 0.50, 0.90], axis=0).flatten(), ref.mean((0, 1)), ref.std((0, 1)), quant[[0, 2, 5, 8, 10]], np.array( [ (y < 0.2).mean(), (y > 0.7).mean(), energy.mean() * 10, np.quantile(energy, 0.85) * 10, ] ), ] ).astype("f4") return dict(axis=axis, lut=lut, q=quant, features=feat) def make_inputs(stack, current, source, branch): primary = stack[1] if branch == "single" else stack[2] anchor = current.astype("f4") / 255 donor = primary.astype("f4") / 255 low = smooth(anchor, 5) y = low @ W detail = donor - smooth(donor, 1.3) energy = smooth(np.abs(detail @ W), 3) axis, lut = source["axis"], source["lut"] desired = np.interp(y, axis, lut[:, 0]).astype("f4") gain = np.clip(np.sqrt((desired + 0.008) / (energy + 0.008)), 0.7, 1.65) texture = np.clip(donor + (gain - 1)[..., None] * detail, 0, 1) levels = np.linspace(0.05, 0.95, 11) target = np.quantile(y[::3, ::3], levels) target, ids = np.unique(target, return_index=True) rel = np.interp(y, target, source["q"][ids]).astype("f4") delta = np.clip(rel - y, -0.13, 0.13) chrom = np.stack([np.interp(y, axis, lut[:, k]) for k in (1, 2, 3)], -1).astype( "f4" ) color = np.clip( anchor + 0.70 * delta[..., None] + 0.40 * np.clip(chrom - (low - y[..., None]), -0.10, 0.10), 0, 1, ) return np.stack( [ current, stack[1], stack[2], stack[3], stack[4], np.rint(texture * 255).astype("u1"), np.rint(color * 255).astype("u1"), ] ) class Sources: def __init__(self, root, branch): self.root = root self.branch = branch self.field = Path(read(root / "previous.json")["parent"]) self.paired = Path(read(self.field / "previous.json")["parent"]) self.paths, self.cfg = root_assets(self.paired) self.cache = {} if branch == "single": self.single = { v["name"]: v["photo"] for v in read(self.paired / "panos/requests.json") } self.formal = { v["name"].replace("/", "_"): v["photo"] for v in read(self.paths["light"] / "formal_requests.json") } self.blind = { v["name"]: v["photo"] for v in read(self.paths["light"] / "blind_requests.json") } if branch == "mapped": from prepare_dual_mapped import MappedInputs from refit_photographic_field import training_views m = MappedInputs(self.paths, self.cfg) q = next( v for v in training_views( m.mat / "survey/face", m.mat / "field/face", m.mat / "dense/face" )[0] if v["role"] == "query" ) def get(v): a = ( v["rgb"].detach().cpu().numpy() if torch.is_tensor(v["rgb"]) else v["rgb"] ) return ( a if a.dtype == np.uint8 else np.rint(np.clip(a, 0, 1) * 255).astype("u1") ) self.frozen = profile(get(q)) self.mapped = {} refs = defaultdict(list) for v in m.old: refs[v["source"]].append(v) for v in m.dense + m.dev: C = v["C"] q = min( refs[v["source"]], key=lambda a: abs( np.degrees( np.arccos(np.clip(float(C[:3, 2] @ a["C"][:3, 2]), -1, 1)) ) - 65 ), ) k = (q["source"], q["frame"]) if k not in self.cache: self.cache[k] = profile(get(q)) self.mapped[v["source"], str(v["frame"])] = self.cache[k] del m def __call__(self, r): g = r["group"] k = r["key"] if self.branch == "mapped": return ( self.mapped[r["source"], k] if r["split"] in ("train", "development") else self.frozen ) path = r.get("query") if not path and self.branch == "voyager": case = g.rsplit("_seed", 1)[0] path = next( d / case / "ref_image.png" for d in ( self.paths["controls"] / "cases", self.field / "windows/cases", self.paired / "voyager/wide/cases", ) if (d / case / "ref_image.png").is_file() ) if not path and self.branch == "single": name = g.removeprefix("full_sensor_") if name in self.single: path = self.single[name] elif g == "blind": path = self.blind[k] elif g == "fresh_rock_angles": path = self.formal["face_seed_143"] else: path = self.formal[g] path = str(path) if path not in self.cache: self.cache[path] = profile(photograph(path)) return self.cache[path] def populate(root, branch, stage): cv2.setNumThreads(2) field = Path(read(root / "previous.json")["parent"]) model, strength = open_fidelity(field, branch) src = Sources(root, branch) old = manifests(field, branch, stage) newroot = root / "observations" extra = ( newroot / "extra" / branch / ("fit.json" if stage == "fit" else "audit.json") ) outfile = root / "cache" / branch records = [] def prepare(path, index, historic): for start in range(0, len(index), 16): batch = index[start : start + 16] for v in get_rows(path, branch, batch): out = outfile / v["file"] # Include every original camera even when no LPIPS tile is available. record = { k: v[k] for k in ("file", "group", "key", "source", "split", "outside") } record.update(historical=historic, fps=v.get("fps")) if not out.is_file(): st = v["stack"] ref = src(v) current = artifact(model, v, "bands", strength) stack = make_inputs(st, current, ref, branch) out.parent.mkdir(parents=True, exist_ok=True) np.savez_compressed( out, stack=stack, features=ref["features"], truth=v["truth"], mask=v["mask"], fixed=v["fixed"] if v["fixed"] is not None else st[4], preserve=v["preserve"] if v["preserve"] is not None else np.empty(0, bool), ) records.append(record) print(branch, stage, "paired", len(records), flush=True) prepare(field, old, True) write(outfile / (stage + "-historical.json"), records) while not extra.is_file(): time.sleep(5) prepare(newroot, read(extra), False) if len({v["file"] for v in records}) != len(records): raise ValueError("duplicate camera files") write(outfile / (stage + ".json"), records) if __name__ == "__main__": populate(Path(sys.argv[1]), sys.argv[2], sys.argv[3])