Download projects/spatial-0/scripts/run_multiview_memory.py from KineJIng/kinejing-open-source: direct link, hf CLI and curl.
- Browser
- Download file 6.98 kB
-
https://huggingface.co/datasets/KineJIng/kinejing-open-source/resolve/main/projects/spatial-0/scripts/run_multiview_memory.py
- Command line
-
hf download hf://datasets/KineJIng/kinejing-open-source/projects/spatial-0/scripts/run_multiview_memory.py
-
curl -L -o run_multiview_memory.py https://huggingface.co/datasets/KineJIng/kinejing-open-source/resolve/main/projects/spatial-0/scripts/run_multiview_memory.py
6.98 kB
| """Local multi-reference experiment from measured reconstruction cameras; no public upload.""" | |
| import argparse | |
| import hashlib | |
| import importlib.util | |
| import json | |
| import os | |
| from pathlib import Path | |
| import sys | |
| import time | |
| ROOT = Path(__file__).resolve().parents[1] | |
| COMFY = ROOT.parent / "tools/ComfyUI" | |
| ADAPTER = COMFY / "custom_nodes/ComfyUI_HYWorld2" | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("reconstruction", type=Path) | |
| parser.add_argument("output", type=Path) | |
| parser.add_argument("--anchor", type=int, default=5) | |
| parser.add_argument("--geometry-conditioning", action="store_true") | |
| args = parser.parse_args() | |
| os.environ["HF_HUB_OFFLINE"] = "1" | |
| sys.path[:0] = [str(COMFY), str(ADAPTER)] | |
| import numpy as np | |
| import torch | |
| from PIL import Image | |
| spec = importlib.util.spec_from_file_location("kw_stereo", ADAPTER / "nodes/world_stereo.py") | |
| module = importlib.util.module_from_spec(spec) | |
| spec.loader.exec_module(module) | |
| with args.reconstruction.open("rb") as stream: | |
| checksum = hashlib.file_digest(stream, "sha256").hexdigest() | |
| with np.load(args.reconstruction) as data: | |
| images = torch.from_numpy(data["image"].copy()).float() / 255 | |
| w2cs = torch.eye(4).repeat(len(images), 1, 1) | |
| w2cs[:, :3, :] = torch.from_numpy(data["extrinsics"].copy()).float() | |
| intrinsics = torch.from_numpy(data["intrinsics"].copy()).float() | |
| if not 0 <= args.anchor < len(images): | |
| parser.error("Anchor outside reconstruction") | |
| if args.geometry_conditioning: | |
| from export_nerfstudio import build_initial_points | |
| from geometry_conditioning import prepare_geometry_inputs | |
| from functools import partial | |
| points, colors, threshold = build_initial_points(data, 40., 600000) | |
| valid_depth = data["depth"][args.anchor] | |
| valid_depth = valid_depth[np.isfinite(valid_depth) & (valid_depth > 0)] | |
| if not len(valid_depth): | |
| raise ValueError("No valid anchor depth") | |
| median_depth = float(np.median(valid_depth)) | |
| else: | |
| median_depth = 2. | |
| if not 0 <= args.anchor < len(images): | |
| parser.error("Anchor outside reconstruction") | |
| if not torch.isfinite(w2cs).all(): | |
| raise ValueError("Nonfinite camera matrices") | |
| c2ws = torch.linalg.inv(w2cs) | |
| trajectory, = module.VNCCS_CameraTrajectoryBuilder().build( | |
| preset="stereo_orbit", num_frames=9, radius=1., speed=.28, elevation_deg=0., | |
| median_depth=median_depth, fov_deg=70., image_width=768, image_height=448) | |
| from geometry_conditioning import anchor_trajectory | |
| trajectory["c2ws"] = anchor_trajectory(trajectory["c2ws"]) | |
| targets = c2ws[args.anchor] @ trajectory["c2ws"][::4] | |
| # Nearest camera heuristic, not upstream occlusion-aware retrieval. | |
| distance = torch.cdist(targets[1:, :3, 3], c2ws[:, :3, 3]) | |
| angle = 1 - (targets[1:, :3, 2] @ c2ws[:, :3, 2].T).clamp(-1, 1) | |
| scale = distance.median().clamp_min(1e-4) | |
| choices = (distance / scale + angle).argmin(dim=1).tolist() | |
| selected, indices = [args.anchor], [0] | |
| for position, candidate in enumerate(choices): | |
| if candidate not in selected and position not in indices: | |
| selected.append(candidate) | |
| indices.append(position) | |
| if len(selected) == 3: | |
| break | |
| if len(selected) < 2 and args.geometry_conditioning: | |
| # Nearby trajectories can select the anchor at every target. Keep that | |
| # honest: full-cloud conditioning is multi-view, memory may be one-view. | |
| print("Geometry contains all input views; reference memory selected only the anchor.") | |
| elif len(selected) < 2: | |
| raise RuntimeError("No distinct useful reference camera found; refusing to label single-view as multi-view") | |
| args.output.mkdir(parents=True, exist_ok=False) | |
| report = {"status": "running", "input_sha256": checksum, "anchor": args.anchor, | |
| "geometry_conditioning": args.geometry_conditioning, "trajectory_median_depth": median_depth, | |
| "trajectory_anchor_normalized": True, | |
| "reference_frames": selected, "reference_indices": indices, | |
| "reference_memory_view_count": len(selected), | |
| "retrieval": "nearest normalized camera distance plus viewing-direction penalty", | |
| "quality_status": "not_evaluated", "scope": "Experimental; input poses and depth scale unverified"} | |
| started = time.perf_counter() | |
| (args.output / "run.json").write_text(json.dumps(report, indent=2), encoding="utf-8") | |
| original_prepare = module._prepare_pipeline_inputs | |
| if args.geometry_conditioning: | |
| module._prepare_pipeline_inputs = partial( | |
| prepare_geometry_inputs, module, torch.from_numpy(points), | |
| torch.from_numpy(colors).float()/255., args.output / "conditioning") | |
| try: | |
| with torch.inference_mode(): | |
| model, = module.VNCCS_LoadWorldStereoLightModel().load_model("Memory DMD Light INT4") | |
| output, poses, intrs = module.VNCCS_WorldStereoGenerate().generate( | |
| model, images[args.anchor:args.anchor+1], trajectory, | |
| prompt="A photorealistic continuation of the same scene. Preserve visible objects, materials and layout.", | |
| num_inference_steps=4, guidance_scale=1., seed=20260905, | |
| latent_condition_mode="first_frame_only", render_vae_mode="keyframes", | |
| conditioning_frame_mode="keyframes", vae_memory_mode="tiled+sliced", | |
| crop_generated_edges=False, worldmirror_sequence_mode="prepend_source_highres", | |
| base_camera_poses=c2ws[args.anchor:args.anchor+1], | |
| base_camera_intrinsics=intrinsics[args.anchor:args.anchor+1], | |
| enable_reference_memory=True, reference_images=images[selected], | |
| reference_camera_poses=c2ws[selected], reference_indices=torch.tensor(indices)) | |
| for index, frame in enumerate(output): | |
| Image.fromarray((frame.float().cpu().numpy().clip(0, 1)*255).astype(np.uint8)).save(args.output / f"frame-{index:04d}.png") | |
| bundle = {"frame_count": len(output), "pose_convention": "camera_to_world", | |
| "provenance": ["observed"] + ["generated"]*(len(output)-1), | |
| "camera_poses": poses.cpu().tolist(), "camera_intrinsics": intrs.cpu().tolist()} | |
| (args.output / "cameras.json").write_text(json.dumps(bundle), encoding="utf-8") | |
| report["status"] = "completed" | |
| except Exception as error: | |
| report.update(status="failed", error=f"{type(error).__name__}: {error}") | |
| raise | |
| finally: | |
| module._prepare_pipeline_inputs = original_prepare | |
| report["elapsed_seconds"] = time.perf_counter() - started | |
| (args.output / "run.json").write_text(json.dumps(report, indent=2), encoding="utf-8") | |
| if __name__ == "__main__": | |
| main() | |