bardofcodes's picture
Add files using upload-large-folder tool
4cf20ea verified
"""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)