File size: 3,849 Bytes
10ed3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Small v1.1 reader; no model, GPU, raw data, or media decoding required."""
import json
from pathlib import Path, PurePosixPath

import torch

PROFILE = "pt/tensor_bundle/v1"
LAYOUT = {
    "intrinsic": ("camera/camera.pt", "intrinsic"),
    "keypoints_xyz": ("annotation/keypoints/keypoints.pt", "xyz"),
    "mano": ("annotation/mano/mano.pt", "motion"),
}


def safe_path(root, reference):
    """Resolve a canonical, view-relative POSIX reference without traversal."""
    if not isinstance(reference, str) or not reference or any(x in reference for x in ("\\", ":", "<", ">")):
        raise ValueError(f"Invalid relative reference: {reference!r}")
    path = PurePosixPath(reference)
    if path.is_absolute() or ".." in path.parts or path.as_posix() != reference or reference == ".":
        raise ValueError(f"Reference must stay inside view: {reference}")
    result = Path(root).joinpath(*path.parts)
    if not result.resolve().is_relative_to(Path(root).resolve()):
        raise ValueError(f"Reference escapes its input tree: {reference}")
    return result


def exact_tensor(a, b):
    """Compare dtype, shape and contiguous bytes, including NaN payload bits."""
    return (a.dtype == b.dtype and a.shape == b.shape and
            torch.equal(a.contiguous().view(torch.uint8), b.contiguous().view(torch.uint8)))


class ViewReader:
    def __init__(self, view):
        self.view = Path(view)
        self.meta = json.loads((self.view / "metainfo.json").read_text())
        if self.meta["schema_version"] != "hand-warehouse/1.1":
            raise ValueError("ViewReader expects a v1.1 view")
        self.cache = {}

    def tensor(self, reference, keys=None):
        path = safe_path(self.view, reference)
        if keys is not None and (not isinstance(keys, list) or not keys or
                                 any(not isinstance(k, str) or not k for k in keys)):
            raise ValueError("Dictionary keys must be a nonempty list of nonempty strings")
        if reference not in self.cache:
            self.cache[reference] = torch.load(path, map_location="cpu", weights_only=True)
        value = self.cache[reference]
        for key in keys or []:
            value = value[key]
        if not isinstance(value, torch.Tensor) or value.device.type != "cpu":
            raise TypeError(f"Reference is not a CPU tensor: {reference} {keys}")
        return value

    def numeric(self, name):
        if name not in LAYOUT:
            raise ValueError(f"Unsupported FreiHAND numerical component: {name}")
        component = self.meta["components"][name]
        reference, entry = LAYOUT[name]
        if component["data_ref"] != reference or component["valid_ref"] != reference:
            raise ValueError("Numerical data and valid must use the registered bundle path")
        if component["data_key"] != [entry, "data"] or component["valid_key"] != [entry, "valid"]:
            raise ValueError("Numerical data and valid must use the registered same-entry keys")
        for key in ("storage", "valid_storage"):
            if component[key]["profile"] != PROFILE:
                raise ValueError("Numerical fields must declare the bundle profile")
        data = self.tensor(component["data_ref"], component["data_key"])
        valid = self.tensor(component["valid_ref"], component["valid_key"])
        bundle = self.cache[reference]
        if type(bundle) is not dict or set(bundle) != {entry} or type(bundle[entry]) is not dict or set(bundle[entry]) != {"data", "valid"}:
            raise ValueError("Unexpected bundle fields")
        if valid.dtype != torch.bool:
            raise TypeError("valid must be bool")
        return data, valid

    def validity(self, name):
        component = self.meta["components"][name]
        return self.tensor(component["valid_ref"], component.get("valid_key"))