File size: 5,051 Bytes
82fef95
 
 
4cf20ea
 
 
 
82fef95
 
 
 
4cf20ea
82fef95
 
 
 
4cf20ea
82fef95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cf20ea
 
 
 
82fef95
 
 
 
 
 
 
 
 
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
"""Lightweight loader for the SuperFit primitive-assembly release.

Reads ``manifest.jsonl`` at the repository root and provides helpers to filter
rows and resolve artifact paths. Manifest discovery has no dependency on
PyTorch or the SuperFit package. Loading pickle artifacts may require SuperFit,
PyTorch, NumPy, and related runtime dependencies because serialized tensors and
primitive-expression objects can be embedded in the pickle payloads.

Example::

    from pathlib import Path
    from load_release import ReleaseIndex

    root = Path(".")  # clone root of the Hugging Face dataset repo
    index = ReleaseIndex(root)
    rows = index.filter(source_dataset="toys4k", method="superfrustum", category="airplane")
    print(index.artifact_path(rows[0], "primitive_assembly"))
"""

from __future__ import annotations

import json
import pickle
from pathlib import Path
from typing import Any, Iterator, Literal

ArtifactKind = Literal[
    "primitive_assembly",
    "primitive_assembly_eval",
    "primitive_assembly_error",
    "primitive_assembly_textured",
]


class ReleaseIndex:
    """In-memory index over ``manifest.jsonl``."""

    def __init__(self, root: str | Path, manifest_name: str = "manifest.jsonl") -> None:
        self.root = Path(root).resolve()
        manifest_path = self.root / manifest_name
        if not manifest_path.is_file():
            raise FileNotFoundError(
                f"Manifest not found: {manifest_path}. "
                "Run `python scripts/build_manifest.py` from the dataset root."
            )
        self.rows: list[dict[str, Any]] = []
        with manifest_path.open() as fh:
            for line in fh:
                line = line.strip()
                if line:
                    self.rows.append(json.loads(line))

    def __len__(self) -> int:
        return len(self.rows)

    def __iter__(self) -> Iterator[dict[str, Any]]:
        return iter(self.rows)

    def filter(
        self,
        *,
        source_dataset: str | None = None,
        method: str | None = None,
        object_id: str | None = None,
        category: str | None = None,
        has_eval: bool | None = None,
        has_textured: bool | None = None,
        has_error: bool | None = None,
    ) -> list[dict[str, Any]]:
        """Return manifest rows matching all supplied criteria."""
        out: list[dict[str, Any]] = []
        for row in self.rows:
            if source_dataset is not None and row["source_dataset"] != source_dataset:
                continue
            if method is not None and row["method"] != method:
                continue
            if object_id is not None and row["object_id"] != object_id:
                continue
            if category is not None and row.get("category") != category:
                continue
            if has_eval is not None and row.get("has_primitive_assembly_eval") != has_eval:
                continue
            if has_textured is not None and row.get("has_primitive_assembly_textured") != has_textured:
                continue
            if has_error is not None and row.get("has_primitive_assembly_error") != has_error:
                continue
            out.append(row)
        return out

    def get(
        self,
        source_dataset: str,
        method: str,
        object_id: str,
    ) -> dict[str, Any]:
        """Return the unique row for an instance, or raise ``KeyError``."""
        matches = self.filter(
            source_dataset=source_dataset,
            method=method,
            object_id=object_id,
        )
        if not matches:
            raise KeyError(f"No entry for {source_dataset}/{method}/{object_id}")
        if len(matches) > 1:
            raise KeyError(f"Ambiguous entry for {source_dataset}/{method}/{object_id}")
        return matches[0]

    def artifact_path(self, row: dict[str, Any], kind: ArtifactKind) -> Path:
        """Resolve a manifest path column to an absolute filesystem path."""
        key = f"{kind}_path"
        rel = row.get(key)
        if not rel:
            raise FileNotFoundError(
                f"Artifact '{kind}' not listed for {row['instance_dir']}"
            )
        path = self.root / rel
        if not path.is_file():
            raise FileNotFoundError(f"Missing file: {path}")
        return path

    def load(self, row: dict[str, Any], kind: ArtifactKind = "primitive_assembly") -> Any:
        """Load a pickle artifact for a manifest row."""
        return load_pickle(self.artifact_path(row, kind))


def load_pickle(path: str | Path) -> Any:
    """Load a pickle file. Only unpickle artifacts you trust.

    Primitive-assembly pickles may require the SuperFit runtime to be installed.
    """
    with Path(path).open("rb") as fh:
        return pickle.load(fh)


def load_metadata(root: str | Path, name: str = "metadata.json") -> dict[str, Any]:
    """Load the dataset summary JSON written by ``scripts/build_manifest.py``."""
    path = Path(root).resolve() / name
    with path.open() as fh:
        return json.load(fh)