DROID-Sim / package /tools /migrate_render_contracts.py
shutzang's picture
Add files using upload-large-folder tool
e24a893 verified
Raw History Blame Contribute Delete
10.5 kB
"""Recover explicit portable cameras from retained render evidence, without deleting it.
Only adds render/scene.json. Missing or ambiguous evidence is reported, not guessed.
"""
import argparse
import json
from pathlib import Path
import subprocess
import numpy as np
from PIL import Image
from package_trajectories import digest, write_json
from render_kernels import load_camera, load_foreground_intrinsics
def read(path):
try:
return json.loads(path.read_text())
except (ValueError, OSError):
return {}
def walk(value):
yield value
if isinstance(value, dict):
for x in value.values():
yield from walk(x)
elif isinstance(value, list):
for x in value:
yield from walk(x)
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--dataset', type=Path, default=Path(__file__).resolve().parents[2] / 'batch_1st_scene')
p.add_argument('--search-roots', type=Path, nargs='*', default=[])
p.add_argument('--report', type=Path, required=True)
p.add_argument('--scenes', type=int, nargs='*')
a = p.parse_args()
indexed = []
if a.search_roots:
result = subprocess.run(['rg', '--files', '-uuu', '-g', '*gravity*.json', *map(str, a.search_roots)],
text=True, capture_output=True, check=False)
if result.returncode not in (0, 1):
raise RuntimeError(result.stderr)
indexed = [Path(line) for line in result.stdout.splitlines()]
rows = []
for scene in sorted(a.dataset.iterdir()):
if not scene.is_dir() or not scene.name[:4].isdigit():
continue
if a.scenes and int(scene.name[:4]) not in a.scenes:
continue
row = dict(scene=scene.name)
try:
backups = list((scene / 'backup').glob('layered_render_repro_*'))
if len(backups) > 1:
accepted_hash = digest(scene / 'layered_composite.png')
backups = [b for b in backups if (b / 'layered_composite.png').exists()
and digest(b / 'layered_composite.png') == accepted_hash]
assert len(backups) == 1, f'Expected one accepted render package, found {len(backups)}'
backup = backups[0]
documents = {p.name: read(p) for p in backup.glob('*.json')}
request = documents.get('foreground_request.json', {})
render_request = documents.get('render_request.json', {})
manifest = documents.get('shadow_layered_manifest.json', {})
width, height = Image.open(scene / 'image.png').size
cam_path = scene / 'background/aligned_target_vggt/cameras_target_vggt.npz'
ply = scene / 'background/aligned_target_vggt/background_aligned_target_vggt.ply'
if not cam_path.exists() or not ply.exists():
raise ValueError('No canonical GS alignment; retained background source: ' + str(manifest.get('background_source')))
wb, kb, _, _, frame, _ = load_camera(cam_path, 0, width, height)
fg_camera_path = scene / 'reconstruction/vggt/camera.json'
local_inputs = render_request.get('inputs_relative_to_scene_root', {})
if local_inputs.get('foreground_camera_json'):
fg_camera_path = scene / local_inputs['foreground_camera_json']
kf, _ = load_foreground_intrinsics(fg_camera_path, width, height)
fg_npz = backup / 'foreground_layer.npz'
if not fg_npz.is_file():
source_run = documents.get('layered_repro_package_manifest.json', {}).get('source_layered_run')
if source_run:
source_run = Path(source_run)
# A relocated cache is evidence only if its rendered layers match the
# retained accepted package, not merely because its directory exists.
source_npz = source_run / 'foreground_layer.npz'
if source_npz.is_file() and all(
(source_run / f).is_file() and (backup / f).is_file()
and digest(source_run / f) == digest(backup / f)
for f in ('foreground_render.png', 'layered_composite.png')
):
fg_npz = source_npz
gravity_path = None
gravity = None
legacy_same_frame = bool(local_inputs.get('gravity_json') and (backup / 'render_layered_scene.py').exists())
if fg_npz.is_file():
with np.load(fg_npz, allow_pickle=False) as f:
wf = f['w2c'].astype(np.float64)
kf = f['intrinsics'].astype(np.float64)
camera_source = str(fg_npz)
gravity = np.linalg.inv(wf) @ wb
else:
declared = request.get('gravity_transform') or render_request.get('gravity_transform')
if local_inputs.get('gravity_json'):
declared = str(scene / local_inputs['gravity_json'])
if declared and not Path(declared).is_file() and scene.name + '/' in declared:
relocated = scene / declared.split(scene.name + '/', 1)[1]
if relocated.is_file():
declared = str(relocated)
expected_hashes = set()
for value in walk(documents):
if isinstance(value, dict) and isinstance(value.get('path'), str) and 'gravity' in Path(value['path']).name:
if value.get('sha256'):
expected_hashes.add(value['sha256'])
candidates = ([Path(declared)] if declared else []) + list(scene.rglob('*gravity*.json'))
candidates += [p for p in indexed if scene.name in str(p)]
candidates = list(dict.fromkeys(p for p in candidates if p.is_file()))
usable = []
for candidate in candidates:
d = read(candidate)
if 'transform_gravity_from_background' not in d:
continue
g = np.asarray(d['transform_gravity_from_background'], dtype=np.float64)
if g.shape != (4, 4) or not np.isfinite(g).all():
continue
usable.append((candidate, g, digest(candidate)))
matched = [x for x in usable if x[2] in expected_hashes]
if not matched and declared:
matched = [x for x in usable if x[0] == Path(declared)]
if not matched:
raise ValueError(f'Cannot identify authoritative gravity; {len(usable)} candidates, {len(expected_hashes)} reference hashes')
gravity_path, gravity, _ = matched[0]
assert all(np.allclose(x[1], gravity, atol=1e-8) for x in matched), 'Conflicting authoritative gravity transforms'
wf = wb @ np.linalg.inv(gravity)
camera_source = str(gravity_path)
if request.get('foreground_camera_override_json'):
raise ValueError('Foreground camera override needs explicit migration')
if legacy_same_frame:
# Archived core render script uses w2c_gravity for BOTH assets.
# Keep that semantics only where the actual archived script proves it.
code = (backup / 'render_layered_scene.py').read_text()
if 'gaussians,\n w2c_gravity,' not in code:
raise ValueError('Legacy renderer background frame requires inspection')
wb = wf.copy()
gravity = np.eye(4)
if not np.allclose(kf, kb, atol=1e-4, rtol=1e-5):
raise ValueError('Foreground and background intrinsics differ; cannot claim one camera')
assert np.isfinite(wf).all() and np.allclose(wf[3], [0, 0, 0, 1])
bg_request = documents.get('background_request.json', {})
gauge = bg_request.get('render_gauge_world_units_per_normalized_unit')
if gauge is None:
with np.load(cam_path, allow_pickle=False) as f:
if 'render_gauge_world_units_per_normalized_unit' in f:
gauge = float(f['render_gauge_world_units_per_normalized_unit'])
# Legacy renderer uses world-space Gaussian rasterization without gauge.
mode = 'world' if legacy_same_frame else 'camera_gauge_sh0'
if mode != 'world' and (gauge is None or float(gauge) <= 0):
raise ValueError('Missing numerical Gaussian gauge')
contract = dict(format='droid_sim_render_v1', foreground='fully_refined_foreground.glb',
background=str(ply.relative_to(scene)), target_image='image.png',
image_size_wh=[width, height], frame_index=frame,
intrinsic=kf.tolist(), world_to_camera_foreground=wf.tolist(),
world_to_camera_background=wb.tolist(),
transform_foreground_from_background=gravity.tolist(),
background_renderer=mode, background_gauge=gauge,
compositing_policy='foreground_alpha_priority_over_real_gs',
background_color=[0.96, 0.96, 0.96],
same_camera=True, metric_scale_verified=False,
canonical_foreground_sha256=digest(scene / 'fully_refined_foreground.glb'),
accepted_composite_sha256=digest(scene / 'layered_composite.png'),
migration=dict(camera_source=camera_source, validated_by_rerender=False))
(scene / 'render').mkdir(exist_ok=True)
write_json(scene / 'render/scene.json', contract)
row.update(status='contract_recovered_pending_render_test', camera_source=camera_source, background_renderer=mode)
except Exception as e:
row.update(status='needs_recovery', error=f'{type(e).__name__}: {e}')
rows.append(row)
print(scene.name[:4], row['status'], row.get('error', ''), flush=True)
a.report.parent.mkdir(parents=True, exist_ok=True)
write_json(a.report, dict(total=len(rows), recovered=sum(x['status'].startswith('contract_') for x in rows), scenes=rows))
if __name__ == '__main__':
main()