File size: 5,091 Bytes
bc88015
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Recording-selective Hub access; metadata never triggers volume acquisition."""

from __future__ import annotations

import json
from pathlib import Path


class MissingComponentError(LookupError):
    """A requested component is unavailable, rather than an empty measurement."""


class BenchmarkClient:
    """Read a pinned release or local assembly with a per-file download budget.

    Tables retain native XYZ voxel coordinates. Physical XYZ fields are null if
    calibration is unknown. Volumes return CZYX, without intensity normalization.
    Local assemblies support the same API as remote commits. Remote callers must
    explicitly select a revision; this prevents silent changes in experiments.
    """

    def __init__(
        self,
        repo_id="pytc/trackingBench",
        *,
        revision=None,
        root=None,
        cache_dir=None,
        max_download_bytes=128 * 1024**2,
    ):
        if root is None and revision is None:
            raise ValueError("Pin a Hub commit/tag with revision, or supply root")
        self.repo_id = repo_id
        self.revision = revision
        self.root = Path(root) if root is not None else None
        self.cache_dir = cache_dir
        self.max_download_bytes = max_download_bytes
        self.manifest = json.loads(self._file("metadata/client_manifest.json").read_text())

    def _file(self, path):
        logical = Path(path)
        if logical.is_absolute() or ".." in logical.parts:
            raise ValueError("Manifest paths must stay within the repository")
        if self.root is not None:
            return self.root / logical
        from huggingface_hub import HfApi, hf_hub_download

        info = next(
            iter(
                HfApi().get_paths_info(
                    self.repo_id, [path], repo_type="dataset", revision=self.revision
                )
            ),
            None,
        )
        if info is None or getattr(info, "size", None) is None:
            raise MissingComponentError(path)
        if info.size > self.max_download_bytes:
            raise ValueError(f"{path} exceeds the {self.max_download_bytes}-byte file budget")
        return Path(
            hf_hub_download(
                self.repo_id,
                path,
                repo_type="dataset",
                revision=self.revision,
                cache_dir=self.cache_dir,
            )
        )

    def list_recordings(self, **filters):
        import pandas as pd

        df = pd.read_parquet(self._file(self.manifest["recordings"]))
        for key, value in filters.items():
            df = df.loc[df[key] == value]
        return df.reset_index(drop=True)

    def _component(self, recording_id, component):
        import pandas as pd

        entry = self.manifest["components"].get(recording_id)
        if entry is None:
            raise MissingComponentError(f"Unknown recording: {recording_id}")
        path = entry.get(component)
        if path is None:
            raise MissingComponentError(f"{component} unavailable for {recording_id}")
        return pd.read_parquet(self._file(path))

    def load_detections(self, recording_id):
        return self._component(recording_id, "detections")

    def load_tracks(self, recording_id, label_source=None):
        df = self._component(recording_id, "tracks")
        if label_source is not None:
            df = df.loc[df.annotation_type == label_source].reset_index(drop=True)
        return df

    def load_reference_cloud(self, recording_id):
        return self._component(recording_id, "anatomy")

    def load_posture(self, recording_id):
        return self._component(recording_id, "posture")

    def load_corruptions(self, recording_id):
        return self._component(recording_id, "perturbations")

    def get_split(self, protocol, partition):
        if protocol not in {"tracking_gt", "anatomical_verification", "anatomical_consistency"}:
            raise ValueError(f"Unknown protocol: {protocol}")
        if partition not in {"train", "validation", "test", "development", "quarantine"}:
            raise ValueError(f"Unknown partition: {partition}")
        return self.manifest["splits"][protocol].get(partition, [])

    def load_volume(self, recording_id, frame, channels=None):
        """Download only the small declared imaging pilot and return one CZYX frame.

        Frames outside the hosted pilot raise MissingComponentError with upstream
        resolution details. Original multi-GB recordings are never auto-downloaded.
        """
        import h5py
        import numpy as np

        entry = self.manifest["components"].get(recording_id, {})
        volume = entry.get("volume")
        if volume is None or frame not in volume["frames"]:
            raise MissingComponentError(
                f"No hosted frame {frame} for {recording_id}; consult metadata/upstream_assets.json"
            )
        with h5py.File(self._file(volume["path"]), "r") as h:
            data = h[f"frames/{frame}"][()]
        return data if channels is None else np.take(data, channels, axis=0)