Download project/scripts/cache_cave_surface.py from xiaojie06/CaveWorld3D: direct link, hf CLI and curl.
- Browser
- Download file 4.35 kB
-
https://huggingface.co/xiaojie06/CaveWorld3D/resolve/main/project/scripts/cache_cave_surface.py
- Command line
-
hf download hf://xiaojie06/CaveWorld3D/project/scripts/cache_cave_surface.py
-
curl -L -o cache_cave_surface.py https://huggingface.co/xiaojie06/CaveWorld3D/resolve/main/project/scripts/cache_cave_surface.py
4.35 kB
| """Generate frozen, image-only conditioning predictions for source-disjoint field training.""" | |
| import argparse | |
| from collections import Counter | |
| import hashlib | |
| from pathlib import Path | |
| import random | |
| import cv2 | |
| import numpy as np | |
| import torch | |
| from cave_lens_model import network, restore, read_rgb | |
| from cave_surface_model import predictions | |
| from evaluate_cave_lens import frame, paired_rows | |
| from inventory_cave_outpaint import read, write | |
| from train_cave_lens import aperture | |
| def seed(key): | |
| return int(hashlib.sha256(key.encode()).hexdigest()[:12], 16) | |
| def roster(parent, lens, split): | |
| idx = read(lens / "corpus/index.json") | |
| cameras = [ | |
| dict(r, task="camera", uid="camera_" + r["case"]) | |
| for r in read(parent / "evidence/cases.json") | |
| ] | |
| pairs = [ | |
| dict(r, task="registered", uid="pair_" + r["case"]) for r in paired_rows(lens) | |
| ] | |
| frames = [] | |
| for n, r in enumerate(idx["frames"]): | |
| frames.append(dict(r, task="aperture", uid="view_" + str(n))) | |
| if r["source"].startswith("IMG_"): | |
| frames.append(dict(r, task="aperture", uid="offset_" + str(n))) | |
| rows = [ | |
| r for r in cameras + pairs + frames if split == "all61" or r["role"] == "train" | |
| ] | |
| assert len({r["uid"] for r in rows}) == len(rows) | |
| return rows | |
| def observation(parent, lens, row, max_edge=576): | |
| if row["task"] == "aperture": | |
| t = read_rgb(lens / "corpus" / row["file"]) | |
| k = aperture(*t.shape[:2], random.Random(seed(row["uid"]))) | |
| g = t.copy() | |
| v = ~k | |
| else: | |
| ref = frame(parent, lens, row) | |
| g, k, t, v = (ref[s] for s in ("guide", "known", "truth", "mask")) | |
| g = g.copy() | |
| g[~k] = 0 | |
| h, w = k.shape | |
| if max(h, w) > max_edge: | |
| size = ( | |
| max(8, round(w * max_edge / max(h, w))), | |
| max(8, round(h * max_edge / max(h, w))), | |
| ) | |
| frac = cv2.resize(k.astype("f4"), size, interpolation=cv2.INTER_AREA) | |
| g = ( | |
| np.rint( | |
| cv2.resize(g.astype("f4"), size, interpolation=cv2.INTER_AREA) | |
| / np.maximum(frac[..., None], 1e-5) | |
| ) | |
| .clip(0, 255) | |
| .astype("u1") | |
| ) | |
| k = frac > 0.99 | |
| g[~k] = 0 | |
| t = cv2.resize(t, size, interpolation=cv2.INTER_AREA) | |
| v = cv2.resize(v.astype("f4"), size, interpolation=cv2.INTER_AREA) > 0.99 | |
| return g, k, t, v & ~k | |
| def load_backbones(lens, split): | |
| field = network(lens / "upstream/big-lama.pt") | |
| base = network(lens / "upstream/big-lama.pt") | |
| restore(field, lens / "weights" / split / "epoch-7.safetensors") | |
| return field, base | |
| def main(parent, lens, work, split): | |
| cv2.setNumThreads(1) | |
| torch.set_num_threads(2) | |
| field, base = load_backbones(lens, split) | |
| rows = roster(parent, lens, split) | |
| dst = work / "cache" / split | |
| dst.mkdir(exist_ok=True, parents=True) | |
| usable = [] | |
| rejected = [] | |
| for i, row in enumerate(rows): | |
| name = dst / (row["uid"] + ".npz") | |
| if name.is_file(): | |
| usable.append(row) | |
| continue | |
| g, k, _, _ = observation(parent, lens, row) | |
| if not k.any() or k.all(): | |
| rejected.append( | |
| dict( | |
| uid=row["uid"], source=row["source"], known_fraction=float(k.mean()) | |
| ) | |
| ) | |
| continue | |
| p, b, c = predictions(field, base, g, k) | |
| partial = name.with_suffix(".part.npz") | |
| np.savez_compressed(partial, primary=p, alternate=b, official=c) | |
| partial.replace(name) | |
| usable.append(row) | |
| if i % 120 == 0: | |
| print("cache", split, i, len(rows), flush=True) | |
| assert {r["source"] for r in rows} == {r["source"] for r in usable} | |
| write(dst / "roster.json", usable) | |
| write( | |
| dst / "ready.json", | |
| dict( | |
| rows=len(usable), | |
| sources=len({r["source"] for r in usable}), | |
| tasks=Counter(r["task"] for r in usable), | |
| scenes=Counter(r["scene"] for r in usable), | |
| rejected=rejected, | |
| ), | |
| ) | |
| if __name__ == "__main__": | |
| arg = argparse.ArgumentParser(description=__doc__) | |
| for key in ("parent", "lens", "work"): | |
| arg.add_argument(key, type=Path) | |
| arg.add_argument("split", choices=["heldout", "all61"]) | |
| main(**vars(arg.parse_args())) | |