File size: 4,105 Bytes
3088257
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91a4bc3
 
 
3088257
 
 
 
 
 
 
91a4bc3
 
 
3088257
 
 
 
 
 
 
 
 
 
 
91a4bc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3088257
 
 
 
 
 
 
 
 
 
 
 
 
 
91a4bc3
 
 
 
3088257
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
"""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()