StereoGenBench-Temporal / benchmark.py
stereo-dataset's picture
Add calibrated synthetic trajectories and long stereo takes; redraw the dataset overview
91a4bc3 verified
Raw History Blame Contribute Delete
4.11 kB
"""Assemble a registered edit and evaluate a frame-aligned right-eye prediction."""
import argparse
import hashlib
import json
from pathlib import Path
import numpy as np
ROOT = Path(__file__).resolve().parent
def registry(name):
return json.loads((ROOT / "metadata" / (name + ".json")).read_text(encoding="utf-8"))
def assemble(edit, eye, sources, cache):
frames = {}
for key in dict.fromkeys(shot["recording"] for shot in edit["shots"]):
src = sources[key]
media = src.get("media") or src["rgb"]
path = ROOT / media
if media.startswith("local/"):
path = cache / (key + ".npz")
if not path.is_file():
raise FileNotFoundError(f"{path} is missing. See the dataset card for media preparation.")
with np.load(path, allow_pickle=False) as data:
frames[key] = data[eye]
pieces = [frames[s["recording"]][s["start"]:s["start"] + s["frames"]] for s in edit["shots"]]
result = np.concatenate(pieces)
for index, amount in edit.get("rgb_additions", {}).items():
frame = result[int(index)]
frame[:] = np.clip(frame.astype(np.int16) + amount, 0, 255)
if hashlib.sha256(result).hexdigest() != edit[eye + "_rgb_sha256"]:
raise ValueError(f"Decoded RGB checksum failed for {edit['id']} / {eye}")
return result
def score(edit, prediction, target):
if prediction.shape != target.shape or prediction.dtype != np.uint8:
raise ValueError(f"Expected a frame-aligned RGB uint8 array of shape {target.shape}")
absolute = np.abs(prediction.astype(np.int16) - target)
per_frame = absolute.mean(axis=(1, 2, 3))
post = [t for c in edit["cuts"] for t in range(c, min(c + 4, len(target)))]
identifiers = {key:edit[key] for key in ("pair","family","layout") if key in edit}
common = edit["common_boundary4"]
return dict(edit=edit["id"], **identifiers, whole_mae=float(per_frame.mean()),
postcut4_mae=float(per_frame[post].mean()) if post else None,
common_boundary4_mae=float(per_frame[common].mean()) if common else None)
def lookup(tag):
edits = registry("edits")
if tag in edits:
return edits[tag], registry("recordings")
synthetic = registry("synthetic_edits")
sources = registry("synthetic_sources")
if tag in synthetic:
return synthetic[tag], sources
if tag not in sources:
raise KeyError(tag)
src = sources[tag]
edit = dict(id=tag, family=src["family"], layout=src.get("variant","continuous"),
shots=[dict(recording=tag, start=0, frames=src["frames"])],
cuts=src["cuts"], common_boundary4=[],
left_rgb_sha256=src["array_sha256"]["left"], right_rgb_sha256=src["array_sha256"]["right"])
return edit, sources
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--cache", type=Path, default=ROOT / "local/freiburg")
commands = parser.add_subparsers(dest="command", required=True)
export = commands.add_parser("export", help="Write an edit as a time × height × width × RGB uint8 array")
export.add_argument("edit")
export.add_argument("output", type=Path)
export.add_argument("--eye", choices=["left", "right"], default="left")
evaluate = commands.add_parser("score", help="Score a predicted right-eye RGB array")
evaluate.add_argument("edit")
evaluate.add_argument("prediction", type=Path)
args = parser.parse_args()
try:
edit, sources = lookup(args.edit)
except KeyError:
parser.error(f"Unknown ID {args.edit}. See the real and synthetic indices on the dataset card.")
if args.command == "export":
result = assemble(edit, args.eye, sources, args.cache)
with args.output.open("xb") as stream:
np.save(stream, result, allow_pickle=False)
else:
target = assemble(edit, "right", sources, args.cache)
print(json.dumps(score(edit, np.load(args.prediction, mmap_mode="r", allow_pickle=False), target), indent=2))
if __name__ == "__main__":
main()