kinejing-open-source / projects /spatial-0 /scripts /run_frozen_completion.py
zoah111's picture
Publish reviewed KineJing technical release (dataset, batch 13/16)
6da4e64 verified
Raw History Blame Contribute Delete
6.81 kB
"""Local frozen observed-scene conditioning experiment. No downloads or publishing."""
import argparse
from functools import partial
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import subprocess
import sys
import time
import numpy as np
from PIL import Image
from plyfile import PlyData
import torch
from geometry_conditioning import anchor_trajectory
from frozen_conditioning import prepare_frozen_inputs, load_conditions
ROOT = Path(__file__).resolve().parents[1]
COMFY = ROOT.parent/"tools/ComfyUI"
ADAPTER = COMFY/"custom_nodes/ComfyUI_HYWorld2"
def digest(path):
with path.open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("scene", type=Path)
parser.add_argument("priors", type=Path)
parser.add_argument("images", type=Path)
parser.add_argument("output", type=Path)
parser.add_argument("--anchor", type=int, default=17)
parser.add_argument("--parallax", type=float, default=.15, help="Fraction of visible splat median depth")
parser.add_argument("--generate", action="store_true")
args = parser.parse_args()
if not 0 < args.parallax <= .5:
parser.error("parallax must be >0 and <=.5")
os.environ["HF_HUB_OFFLINE"] = "1"
sys.path[:0] = [str(COMFY), str(ADAPTER)]
spec = importlib.util.spec_from_file_location("kw_frozen_stereo", ADAPTER/"nodes/world_stereo.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
with np.load(args.priors, allow_pickle=False) as priors:
if not 0 <= args.anchor < len(priors["c2w"]):
parser.error("Invalid anchor")
base, intr = priors["c2w"][args.anchor].copy(), priors["intrinsics"][args.anchor].copy()
image_path = args.images/str(priors["frame_names"][args.anchor])
if digest(image_path) != str(priors["image_sha256"][args.anchor]):
raise ValueError("Anchor fingerprint mismatch")
with Image.open(image_path) as image:
source = np.asarray(image.convert("RGB")).copy()
scene_hash = digest(args.scene)
vertices = PlyData.read(args.scene)["vertex"].data
points = np.column_stack([vertices[n] for n in ("x", "y", "z")])
camera_points = (points-base[:3, 3]) @ base[:3, :3]
z = camera_points[:, 2]
projected = camera_points @ intr.T
uv = projected[:, :2]/np.maximum(z[:, None], 1e-8)
valid = np.isfinite(camera_points).all(axis=1) & (z > 0) & (vertices["opacity"] > -2.2)
valid &= (uv[:, 0] >= 0) & (uv[:, 0] < source.shape[1]) & (uv[:, 1] >= 0) & (uv[:, 1] < source.shape[0])
if valid.sum() < 100:
raise ValueError("Too little visible observed geometry for this anchor")
median_depth = float(np.median(z[valid]))
width, height = 768, 448
trajectory, = module.VNCCS_CameraTrajectoryBuilder().build(preset="stereo_orbit", num_frames=9,
radius=1., speed=args.parallax*median_depth, median_depth=median_depth,
elevation_deg=0., fov_deg=70., image_width=width, image_height=height)
trajectory["c2ws"] = anchor_trajectory(trajectory["c2ws"])
base_t = torch.from_numpy(base).float()
absolute = base_t @ trajectory["c2ws"]
keys = torch.arange(0, len(absolute), 4)
render_intr = intr.copy()
render_intr[0] *= width/source.shape[1]
render_intr[1] *= height/source.shape[0]
args.output.mkdir(parents=True, exist_ok=False)
np.savez_compressed(args.output/"conditioning-cameras.npz", c2w=absolute[keys].numpy(),
intrinsics=np.repeat(render_intr[None], len(keys), axis=0))
report = {"status": "preparing", "scene_sha256": scene_hash, "anchor_image_sha256": digest(image_path),
"camera_priors_sha256": digest(args.priors), "anchor": args.anchor, "parallax_fraction": args.parallax,
"median_visible_splat_depth": median_depth, "scope": "Frozen observed scene; generated hypotheses not fused or verified"}
started = time.perf_counter()
original = module._prepare_pipeline_inputs
try:
for mode in ("rgb", "alpha"):
command = [sys.executable, str(ROOT/"scripts/render_frozen_brush.py"), str(args.scene),
str(args.output/"conditioning-cameras.npz"), str(args.output/mode), "--width", str(width), "--height", str(height)]
if mode == "alpha":
command.append("--white-alpha")
subprocess.run(command, check=True)
report["status"] = "prepared"
load_conditions(args.output, absolute[keys].numpy(),
np.repeat(render_intr[None], len(keys), axis=0), width, height)
if args.generate:
module._prepare_pipeline_inputs = partial(prepare_frozen_inputs, module, args.output)
with torch.inference_mode():
model, = module.VNCCS_LoadWorldStereoLightModel().load_model("Memory DMD Light INT4")
output, poses, intrs = module.VNCCS_WorldStereoGenerate().generate(
model, torch.from_numpy(source).float()[None]/255., 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=base_t[None], base_camera_intrinsics=torch.from_numpy(intr).float()[None],
enable_reference_memory=True)
for i, frame in enumerate(output):
Image.fromarray((frame.float().cpu().numpy().clip(0, 1)*255).astype(np.uint8)).save(args.output/f"frame-{i:04d}.png")
(args.output/"cameras.json").write_text(json.dumps({"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()}), encoding="utf-8")
report["status"] = "completed"
if digest(args.scene) != scene_hash:
raise RuntimeError("Observed scene changed during completion")
except Exception as error:
report.update(status="failed", error=f"{type(error).__name__}: {error}")
raise
finally:
module._prepare_pipeline_inputs = original
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()