epishelf 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. epishelf/__init__.py +59 -0
  2. epishelf/_typing.py +55 -0
  3. epishelf/acquire.py +98 -0
  4. epishelf/agibot.py +119 -0
  5. epishelf/archive.py +182 -0
  6. epishelf/brcd.py +789 -0
  7. epishelf/calvin.py +135 -0
  8. epishelf/catalog/__init__.py +223 -0
  9. epishelf/catalog/_papers.py +27 -0
  10. epishelf/catalog/abc130k.py +35 -0
  11. epishelf/catalog/agibot.py +28 -0
  12. epishelf/catalog/behavior.py +21 -0
  13. epishelf/catalog/bimanual_yam.py +31 -0
  14. epishelf/catalog/calvin.py +39 -0
  15. epishelf/catalog/cortex.py +61 -0
  16. epishelf/catalog/domino.py +25 -0
  17. epishelf/catalog/droid.py +97 -0
  18. epishelf/catalog/egocentric100k.py +23 -0
  19. epishelf/catalog/egosuite.py +21 -0
  20. epishelf/catalog/evidence.py +285 -0
  21. epishelf/catalog/hifi_umi_2k.py +56 -0
  22. epishelf/catalog/hiw500.py +52 -0
  23. epishelf/catalog/hy_embodied.py +36 -0
  24. epishelf/catalog/interndata_a1.py +56 -0
  25. epishelf/catalog/libero.py +123 -0
  26. epishelf/catalog/libero_plus.py +29 -0
  27. epishelf/catalog/maintained.py +91 -0
  28. epishelf/catalog/manifests/agibot.json +329 -0
  29. epishelf/catalog/manifests/hifi_umi_2k.json +404 -0
  30. epishelf/catalog/manifests/interndata_a1.json +1495 -0
  31. epishelf/catalog/manifests/robocoin.json +164 -0
  32. epishelf/catalog/manifests/so100.json +1231 -0
  33. epishelf/catalog/manifests/unifolm_wbt.json +75 -0
  34. epishelf/catalog/maniskill.py +32 -0
  35. epishelf/catalog/model.py +687 -0
  36. epishelf/catalog/molmoact.py +56 -0
  37. epishelf/catalog/oxe.py +40 -0
  38. epishelf/catalog/pusht.py +20 -0
  39. epishelf/catalog/realomin.py +20 -0
  40. epishelf/catalog/recipes/__init__.py +9 -0
  41. epishelf/catalog/recipes/molmoact2.py +137 -0
  42. epishelf/catalog/recipes/vlact.py +228 -0
  43. epishelf/catalog/rlbench.py +24 -0
  44. epishelf/catalog/robocasa.py +37 -0
  45. epishelf/catalog/robocasa365.py +57 -0
  46. epishelf/catalog/robocasa_gr1.py +41 -0
  47. epishelf/catalog/robocerebra.py +28 -0
  48. epishelf/catalog/robochallenge.py +62 -0
  49. epishelf/catalog/robocoin.py +29 -0
  50. epishelf/catalog/robodojo.py +194 -0
  51. epishelf/catalog/robotwin2.py +78 -0
  52. epishelf/catalog/so100.py +28 -0
  53. epishelf/catalog/unifolm_wbt.py +37 -0
  54. epishelf/catalog/vla_arena.py +38 -0
  55. epishelf/cli.py +331 -0
  56. epishelf/collate.py +66 -0
  57. epishelf/collections.py +394 -0
  58. epishelf/columnar.py +179 -0
  59. epishelf/composed.py +237 -0
  60. epishelf/convert/__init__.py +440 -0
  61. epishelf/convert/run.py +391 -0
  62. epishelf/convert/unit.py +699 -0
  63. epishelf/core.py +378 -0
  64. epishelf/cortex.py +218 -0
  65. epishelf/dataset.py +529 -0
  66. epishelf/derived.py +78 -0
  67. epishelf/flat.py +110 -0
  68. epishelf/fsio.py +93 -0
  69. epishelf/hdf5.py +139 -0
  70. epishelf/layers.py +678 -0
  71. epishelf/lerobot.py +512 -0
  72. epishelf/media/__init__.py +18 -0
  73. epishelf/media/blobs.py +160 -0
  74. epishelf/media/decode.py +56 -0
  75. epishelf/media/encode.py +222 -0
  76. epishelf/media/image.py +23 -0
  77. epishelf/media/reader.py +263 -0
  78. epishelf/multifile.py +121 -0
  79. epishelf/overlays.py +80 -0
  80. epishelf/preparation.py +328 -0
  81. epishelf/preparers.py +492 -0
  82. epishelf/py.typed +0 -0
  83. epishelf/rangeio.py +86 -0
  84. epishelf/resources.py +290 -0
  85. epishelf/robochallenge.py +406 -0
  86. epishelf/robotwin.py +230 -0
  87. epishelf/sampling.py +270 -0
  88. epishelf/semantics.py +177 -0
  89. epishelf/time.py +96 -0
  90. epishelf/validation.py +79 -0
  91. epishelf/views.py +407 -0
  92. epishelf-0.1.0.dist-info/METADATA +225 -0
  93. epishelf-0.1.0.dist-info/RECORD +96 -0
  94. epishelf-0.1.0.dist-info/WHEEL +4 -0
  95. epishelf-0.1.0.dist-info/entry_points.txt +2 -0
  96. epishelf-0.1.0.dist-info/licenses/LICENSE +202 -0
epishelf/__init__.py ADDED
@@ -0,0 +1,59 @@
1
+ """Robot dataset readers, a catalog of pinned releases, and episode collections."""
2
+
3
+ from .catalog import families, load, prepare, recipes, release, select
4
+ from .collate import collate_samples
5
+ from .collections import Collection, Collections, EpisodeKey
6
+ from .core import (
7
+ DataError,
8
+ Episode,
9
+ EvidenceRef,
10
+ MissingSourceError,
11
+ Reader,
12
+ Record,
13
+ RecordStream,
14
+ Sample,
15
+ Stream,
16
+ StreamSpec,
17
+ )
18
+ from .dataset import RobotDataset
19
+ from .derived import resize
20
+ from .layers import Layer, write_layer
21
+ from .resources import ResourceLimits, configure_resources, resource_stats
22
+ from .sampling import EpochSampler, Mixture
23
+ from .time import Alignment, ClockMap, TimeIndex
24
+
25
+ __version__ = "0.1.0"
26
+ __all__ = [
27
+ "Alignment",
28
+ "ClockMap",
29
+ "Collection",
30
+ "Collections",
31
+ "DataError",
32
+ "Episode",
33
+ "EpisodeKey",
34
+ "EpochSampler",
35
+ "EvidenceRef",
36
+ "Layer",
37
+ "MissingSourceError",
38
+ "Mixture",
39
+ "Reader",
40
+ "Record",
41
+ "RecordStream",
42
+ "RobotDataset",
43
+ "ResourceLimits",
44
+ "Sample",
45
+ "Stream",
46
+ "StreamSpec",
47
+ "TimeIndex",
48
+ "collate_samples",
49
+ "configure_resources",
50
+ "families",
51
+ "load",
52
+ "prepare",
53
+ "recipes",
54
+ "release",
55
+ "resize",
56
+ "resource_stats",
57
+ "select",
58
+ "write_layer",
59
+ ]
epishelf/_typing.py ADDED
@@ -0,0 +1,55 @@
1
+ """Names for shapes that recur in annotations. Imported only for type checking (`if TYPE_CHECKING:`)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from collections.abc import Callable, Iterable, Mapping, Sequence
7
+ from typing import Any, BinaryIO, NotRequired, Protocol, SupportsIndex, TypeAlias, TypedDict
8
+
9
+ import numpy as np
10
+ import numpy.typing as npt
11
+
12
+ from .core import Episode
13
+ from .media.blobs import BlobMedia, _Handle
14
+
15
+ PathLike: TypeAlias = "os.PathLike[str] | str"
16
+ JSON: TypeAlias = Any # a JSON-decoded value: dict, list, str, int, float, bool or None
17
+ Row: TypeAlias = "dict[str, JSON]" # one episode's metadata row, with its `id`
18
+ Spec: TypeAlias = "dict[str, Any]" # a dataset's `spec`: its keys vary by producer (see RobotDataset)
19
+ Payload: TypeAlias = Any # one decoded sample: an ndarray, a Record, an image, a Python value from a table
20
+ Option: TypeAlias = Any # a reader option, forwarded to a reader chosen at run time
21
+
22
+ Int64Array: TypeAlias = "npt.NDArray[np.int64]"
23
+ Indices: TypeAlias = "Iterable[SupportsIndex] | npt.NDArray[np.integer]" # positions, checked by `indices_of`
24
+ Lengths: TypeAlias = "Sequence[int] | npt.NDArray[np.integer]" # one count per episode
25
+ Flags: TypeAlias = "Sequence[bool] | npt.NDArray[np.bool_]" # one flag per episode
26
+ Samples: TypeAlias = "Sequence[Payload] | np.ndarray" # samples in request order; fixed shapes may be one ndarray
27
+ Media: TypeAlias = "os.PathLike[str] | str | BlobMedia" # a video or image file, or a Blob Pack member
28
+ MediaFile: TypeAlias = "BinaryIO | _Handle" # an open video or image: a file, or a Blob Pack member
29
+ Encoded: TypeAlias = "tuple[Media, Sequence[float] | npt.NDArray[np.floating], float]" # (video, seconds, tolerance)
30
+
31
+ ReadOne: TypeAlias = "Callable[[int], Payload]"
32
+ ReadMany: TypeAlias = "Callable[..., Samples]" # (checked int64 indices[, size=(height, width)]) -> samples
33
+ BatchReader: TypeAlias = "Callable[[dict[str, Int64Array]], Mapping[str, Samples]]" # {stream: indices} -> samples
34
+ FlatRead: TypeAlias = "Callable[[Int64Array, Int64Array], Samples]" # (episode positions, steps) -> samples
35
+
36
+
37
+ class StreamIndexEntry(TypedDict):
38
+ """One stream of a reader's `stream_index`: per-episode lengths (None for a record stream) and, for a layer's
39
+ stream, which episodes have it. `RobotDataset._stream_index` makes the lengths int64 arrays."""
40
+
41
+ record: bool
42
+ clock: str
43
+ lengths: Lengths | None
44
+ present: NotRequired[Flags]
45
+
46
+
47
+ StreamIndex: TypeAlias = "dict[str, StreamIndexEntry]"
48
+
49
+
50
+ class Episodes(Protocol):
51
+ """What views, collections and conversion read: a `Reader`, a `RobotDataset` or a plain sequence of episodes."""
52
+
53
+ def __len__(self) -> int: ...
54
+
55
+ def __getitem__(self, index: int, /) -> Episode: ...
epishelf/acquire.py ADDED
@@ -0,0 +1,98 @@
1
+ """Explicit bounded acquisition; never called by sample access."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ from collections.abc import Iterable
7
+ from pathlib import Path
8
+ from typing import TYPE_CHECKING, TypeGuard
9
+
10
+ from .core import DataError
11
+ from .fsio import atomic_json, safe_target
12
+
13
+ if TYPE_CHECKING:
14
+ from huggingface_hub.hf_api import RepoFile, RepoFolder
15
+
16
+ from ._typing import JSON
17
+
18
+ ACQUISITION = "epishelf-acquisition.json" # the files fetched by download_files, with their hashes
19
+
20
+
21
+ def _is_file(item: RepoFile | RepoFolder) -> TypeGuard[RepoFile]:
22
+ """A file, not a folder: only files have a size and a blob ID (checked by attribute, not class)."""
23
+ return hasattr(item, "size") and hasattr(item, "blob_id")
24
+
25
+
26
+ def hub_files(repo_id: str, revision: str, names: Iterable[str]) -> dict[str, RepoFile]:
27
+ """Size and content-hash entries of named files at a pinned Hub revision, keyed by path; absent files are left
28
+ out. Asks for exactly these paths: a repository listing (`repo_info().siblings`) stops at 100,000 files."""
29
+ from huggingface_hub import HfApi
30
+
31
+ names = list(dict.fromkeys(names))
32
+ entries = {}
33
+ for start in range(0, len(names), 500):
34
+ for item in HfApi().get_paths_info(
35
+ repo_id, names[start : start + 500], repo_type="dataset", revision=revision
36
+ ):
37
+ if _is_file(item):
38
+ entries[item.path] = item
39
+ return entries
40
+
41
+
42
+ def hub_folder(repo_id: str, revision: str, folder: str) -> dict[str, RepoFile]:
43
+ """Every file under a folder at a pinned Hub revision, keyed by path (a recursive listing of that folder)."""
44
+ from huggingface_hub import HfApi
45
+
46
+ return {
47
+ item.path: item
48
+ for item in HfApi().list_repo_tree(
49
+ repo_id, path_in_repo=folder.rstrip("/"), recursive=True, repo_type="dataset", revision=revision
50
+ )
51
+ if _is_file(item)
52
+ }
53
+
54
+
55
+ def download_files(
56
+ repo_id: str, revision: str, files: Iterable[str], destination: Path, *, max_bytes: int
57
+ ) -> dict[str, JSON]:
58
+ """Download an explicit pinned file set, verified by Hub's content hash."""
59
+ from huggingface_hub import hf_hub_download
60
+
61
+ if len(revision) != 40 or any(c not in "0123456789abcdef" for c in revision):
62
+ raise ValueError("Use an immutable 40-character Hub commit")
63
+ files = tuple(dict.fromkeys(files))
64
+ if not files or max_bytes <= 0:
65
+ raise ValueError("Explicit files and positive max_bytes are required")
66
+ for name in files:
67
+ safe_target(destination, name)
68
+ entries = hub_files(repo_id, revision, files)
69
+ if set(files) - entries.keys():
70
+ raise FileNotFoundError(sorted(set(files) - entries.keys()))
71
+ sizes = [entries[n].size for n in files]
72
+ if any(s is None for s in sizes):
73
+ raise DataError("Upstream file sizes are unknown")
74
+ if sum(sizes) > max_bytes:
75
+ raise DataError(f"Selection is {sum(sizes)} bytes, exceeding {max_bytes}")
76
+ hashes = {}
77
+ for name in files:
78
+ path = Path(hf_hub_download(repo_id, name, repo_type="dataset", revision=revision, local_dir=destination))
79
+ entry = entries[name]
80
+ digest = hashlib.sha256() if entry.lfs else hashlib.sha1()
81
+ if not entry.lfs:
82
+ digest.update(f"blob {entry.size}\0".encode())
83
+ with path.open("rb") as handle:
84
+ for block in iter(lambda: handle.read(1024 * 1024), b""):
85
+ digest.update(block)
86
+ expected = entry.lfs.sha256 if entry.lfs else entry.blob_id
87
+ if path.stat().st_size != entry.size or digest.hexdigest() != expected:
88
+ raise DataError(f"Integrity check failed: {name}")
89
+ hashes[name] = digest.hexdigest()
90
+ manifest = {
91
+ "repo_id": repo_id,
92
+ "revision": revision,
93
+ "files": hashes,
94
+ "coverage": "partial",
95
+ "selected_bytes": sum(sizes),
96
+ }
97
+ atomic_json(Path(destination) / ACQUISITION, manifest)
98
+ return manifest
epishelf/agibot.py ADDED
@@ -0,0 +1,119 @@
1
+ """Official AgiBot World 2026 LeRobot datasets and their source-declared annotation layers (preparers.py selects
2
+ episodes from the archives)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from dataclasses import replace
7
+ from pathlib import Path
8
+ from typing import TYPE_CHECKING
9
+
10
+ import numpy as np
11
+
12
+ from .core import DataError, Record, RecordStream
13
+ from .lerobot import LeRobotReader
14
+
15
+ if TYPE_CHECKING:
16
+ from collections.abc import Sequence
17
+
18
+ from ._typing import Indices, Option, PathLike, Payload, Row
19
+ from .core import Episode, Stream, StreamSpec
20
+
21
+
22
+ class Agibot2026Reader(LeRobotReader):
23
+ def __init__(self, root: PathLike, **options: Option) -> None:
24
+ if Path(root).is_file():
25
+ raise DataError("Prepare selected archive-local episodes before opening an AgiBot tar")
26
+ super().__init__(root, **options)
27
+ if self.v3:
28
+ raise DataError("The AgiBot World 2026 profile requires a v2 dataset")
29
+
30
+ def _native_depth_format(self, key: str) -> str | None:
31
+ feature = self.info["features"][key]
32
+ info = feature.get("video_info", {})
33
+ if info.get("video.is_depth_map"):
34
+ pixel_format = info.get("video.pix_fmt")
35
+ if pixel_format not in {"gray16be", "gray16le"}:
36
+ raise DataError(f"{key}: unverified AgiBot depth encoding {pixel_format!r}")
37
+ return pixel_format
38
+ return None
39
+
40
+ def _read(self, row: Row, key: str, index: int) -> Payload:
41
+ if self._native_depth_format(key):
42
+ return self._read_many(row, key, [index])[0]
43
+ return super()._read(row, key, index)
44
+
45
+ def _rgb_video(self, key: str) -> bool: # declared depth is read natively; other non-RGB maps stay rejected
46
+ return self._native_depth_format(key) is None and super()._rgb_video(key)
47
+
48
+ def _read_many(self, row: Row, key: str, indices: Indices, size: Sequence[int] | None = None) -> list[Payload]:
49
+ indices = [int(i) for i in indices]
50
+ pixel_format = self._native_depth_format(key)
51
+ if pixel_format is None:
52
+ return super()._read_many(row, key, indices, size)
53
+ timestamps = self._video_times(row, key, indices)
54
+ frames = self.video.frames_played_at(self._path(row, key), timestamps, pixel_format=pixel_format)
55
+ return [pixels.astype(np.uint16)[..., None] for pixels in frames]
56
+
57
+ def _stream_spec(self, key: str, spec: StreamSpec) -> StreamSpec:
58
+ if not self._native_depth_format(key):
59
+ return spec
60
+ height, width = self.info["features"][key]["shape"][:2]
61
+ return replace(
62
+ spec,
63
+ kind="depth",
64
+ dtype="uint16",
65
+ shape=(height, width, 1),
66
+ semantics={**spec.semantics, "normalization": "native gray16 depth counts; physical units unknown"},
67
+ )
68
+
69
+ def __getitem__(self, index: int) -> Episode:
70
+ episode = super().__getitem__(index)
71
+ streams: dict[str, Stream] = dict(episode.streams)
72
+ row = episode.metadata["source_episode"]
73
+ eid, length = str(row["episode_index"]), int(row["length"])
74
+ layers = {
75
+ "annotation.instructions": (
76
+ self.info.get("instruction_segments", {}).get(eid, []),
77
+ "start_frame_index",
78
+ "end_frame_index",
79
+ "instruction_segments",
80
+ ),
81
+ "annotation.keyframes": (
82
+ self.info.get("key_frame", {}).get(eid, {}).get("dual", []),
83
+ "start",
84
+ "end",
85
+ "key_frame.dual",
86
+ ),
87
+ }
88
+ issues: list[str] = []
89
+ for name, (items, begin, end, source) in layers.items():
90
+ records = []
91
+ for i, payload in enumerate(items):
92
+ start, stop = payload[begin], payload[end]
93
+ if stop > length:
94
+ issues.append(f"{name}/{i}: stop {stop} exceeds episode length {length}")
95
+ records.append(
96
+ Record(
97
+ f"{eid}/{source}/{i}",
98
+ start,
99
+ stop,
100
+ payload,
101
+ provenance={
102
+ "source": str(self.root / "meta/info.json"),
103
+ "field": source,
104
+ "episode_index": eid,
105
+ "record_index": i,
106
+ "availability": "unknown; source annotation",
107
+ },
108
+ )
109
+ )
110
+ streams[name] = RecordStream(name, records)
111
+ return replace(
112
+ episode,
113
+ streams=streams,
114
+ metadata={
115
+ **episode.metadata,
116
+ "validation_issues": issues,
117
+ "annotation_profile": "agibot/world2026@1",
118
+ },
119
+ )
epishelf/archive.py ADDED
@@ -0,0 +1,182 @@
1
+ """Resumable, bounded archive materialization; source archives remain read-only."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import stat
9
+ import tarfile
10
+ import zipfile
11
+ from collections.abc import Iterable, Iterator
12
+ from pathlib import Path
13
+ from tempfile import NamedTemporaryFile
14
+ from typing import TYPE_CHECKING, BinaryIO
15
+
16
+ from .core import DataError
17
+ from .fsio import atomic_json, publish_file, safe_name, safe_target, sha256_file
18
+
19
+ if TYPE_CHECKING:
20
+ from ._typing import JSON, PathLike
21
+ from .rangeio import HTTPRangeFile
22
+
23
+
24
+ class ReadBudget:
25
+ def __init__(self, source: BinaryIO, limit: int) -> None:
26
+ self.source, self.limit, self.bytes_read = source, limit, 0
27
+
28
+ def read(self, size: int = -1) -> bytes:
29
+ remaining = self.limit - self.bytes_read
30
+ if size < 0 or size > remaining:
31
+ raise DataError("Archive compressed-input budget exceeded")
32
+ data = self.source.read(size)
33
+ self.bytes_read += len(data)
34
+ return data
35
+
36
+ def tell(self) -> int:
37
+ return self.source.tell()
38
+
39
+ def seek(self, offset: int, whence: int = 0) -> int:
40
+ return self.source.seek(offset, whence)
41
+
42
+
43
+ def index_tar_videos(path: PathLike, *, max_read_bytes: int) -> tuple[dict[str, dict[str, int]], int]:
44
+ """Index only video members of an uncompressed tar using header seeks."""
45
+ result = {}
46
+ with Path(path).open("rb") as raw:
47
+ limited = ReadBudget(raw, max_read_bytes)
48
+ with tarfile.open(fileobj=limited, mode="r:") as archive: # ty: ignore[no-matching-overload] # typeshed's tar fileobj also needs write and close; reading needs neither
49
+ for info in archive:
50
+ if info.isfile() and info.name.endswith(".mp4"):
51
+ safe_name(info.name)
52
+ if info.name in result:
53
+ raise DataError("Duplicate source tar video member")
54
+ result[info.name] = {"offset": info.offset_data, "size": info.size}
55
+ archive.members.clear()
56
+ return result, limited.bytes_read
57
+
58
+
59
+ def copy_tar_video(path: PathLike, entry: dict[str, int], target: PathLike, *, max_bytes: int) -> dict[str, str | int]:
60
+ """Copy a member located by the current source index, with bounded payload I/O."""
61
+ if entry["size"] > max_bytes:
62
+ raise DataError("Selected tar video exceeds output/read budget")
63
+ target = Path(target)
64
+ target.parent.mkdir(parents=True, exist_ok=True)
65
+
66
+ def blocks(source: BinaryIO) -> Iterator[bytes]:
67
+ source.seek(entry["offset"])
68
+ remaining = entry["size"]
69
+ while remaining:
70
+ block = source.read(min(1024**2, remaining))
71
+ if not block:
72
+ raise DataError("Truncated tar payload")
73
+ remaining -= len(block)
74
+ yield block
75
+
76
+ with Path(path).open("rb") as source:
77
+ sha256, _ = publish_file(target, blocks(source), differs="Existing tar video differs from the source")
78
+ return {"sha256": sha256, "size": entry["size"]}
79
+
80
+
81
+ def materialize_zip(
82
+ source: PathLike | HTTPRangeFile, destination: PathLike, members: Iterable[str], *, max_output_bytes: int
83
+ ) -> dict[str, JSON]:
84
+ """Extract selected ZIP members without retaining another archive copy.
85
+
86
+ ``source`` may be a local path or a budgeted seekable HTTP range object.
87
+ Each completed file gets a hash receipt, allowing interrupted work to resume.
88
+ The caller owns dataset-level locking and completion publication.
89
+ """
90
+ with zipfile.ZipFile(source) as archive:
91
+ names = list(dict.fromkeys(members))
92
+ infos = [archive.getinfo(name) for name in names]
93
+ if sum(info.file_size for info in infos) > max_output_bytes:
94
+ raise DataError("Selected ZIP members exceed the output budget")
95
+ if any(info.is_dir() or stat.S_ISLNK(info.external_attr >> 16) for info in infos):
96
+ raise DataError("Only regular ZIP files may be materialized")
97
+ result = {}
98
+ for info in sorted(infos, key=lambda item: item.header_offset):
99
+ target = safe_target(destination, info.filename)
100
+ receipt = safe_target(
101
+ destination,
102
+ ".epishelf-receipts/" + hashlib.sha256(info.filename.encode()).hexdigest() + ".json",
103
+ )
104
+ identity = {"member": info.filename, "size": info.file_size, "crc32": info.CRC}
105
+ if target.exists():
106
+ saved = json.loads(receipt.read_text()) if receipt.is_file() else None
107
+ if (
108
+ saved is None
109
+ or saved["identity"] != identity
110
+ or target.stat().st_size != info.file_size
111
+ or sha256_file(target) != saved["sha256"]
112
+ ):
113
+ raise DataError(f"Existing archive member has no valid receipt: {target}")
114
+ result[info.filename] = saved
115
+ continue
116
+ target.parent.mkdir(parents=True, exist_ok=True)
117
+ receipt.parent.mkdir(parents=True, exist_ok=True)
118
+ digest = hashlib.sha256()
119
+ with NamedTemporaryFile(dir=target.parent, delete=False) as out:
120
+ temp = Path(out.name)
121
+ try:
122
+ with archive.open(info) as opened:
123
+ count = 0
124
+ for block in iter(lambda: opened.read(1024**2), b""):
125
+ count += len(block)
126
+ if count > info.file_size:
127
+ raise DataError("ZIP member exceeds declared size")
128
+ digest.update(block)
129
+ out.write(block)
130
+ if count != info.file_size:
131
+ raise DataError("Truncated ZIP member")
132
+ out.flush()
133
+ os.fsync(out.fileno())
134
+ saved = {"identity": identity, "sha256": digest.hexdigest()}
135
+ # Receipt first: a crash leaves either reusable content or a
136
+ # harmless receipt whose target still needs acquisition.
137
+ atomic_json(receipt, saved)
138
+ os.link(temp, target)
139
+ result[info.filename] = saved
140
+ finally:
141
+ temp.unlink(missing_ok=True)
142
+ return result
143
+
144
+
145
+ def materialize_tar(
146
+ source: PathLike, destination: PathLike, members: Iterable[str], *, max_output_bytes: int, max_read_bytes: int
147
+ ) -> dict[str, JSON]:
148
+ """One bounded forward scan of a compressed local tar; no full extraction."""
149
+ requested = set(members)
150
+ if not requested or min(max_output_bytes, max_read_bytes) <= 0:
151
+ raise ValueError("Explicit members and positive budgets are required")
152
+ for name in requested:
153
+ safe_target(destination, name)
154
+ result, written = {}, 0
155
+ with Path(source).open("rb") as raw:
156
+ limited = ReadBudget(raw, max_read_bytes)
157
+ with tarfile.open(fileobj=limited, mode="r|*") as archive: # ty: ignore[no-matching-overload] # typeshed's tar fileobj also needs write and close; reading needs neither
158
+ for info in archive:
159
+ if info.name not in requested:
160
+ continue
161
+ if not info.isfile() or written + info.size > max_output_bytes:
162
+ raise DataError("Tar member is not regular or exceeds output budget")
163
+ target = safe_target(destination, info.name)
164
+ target.parent.mkdir(parents=True, exist_ok=True)
165
+ with archive.extractfile(info) as opened:
166
+ sha256, _ = publish_file(
167
+ target,
168
+ iter(lambda: opened.read(1024**2), b""),
169
+ differs=f"Existing tar member disagrees with source: {target}",
170
+ )
171
+ result[info.name] = {"size": info.size, "sha256": sha256}
172
+ written += info.size
173
+ requested.remove(info.name)
174
+ if not requested:
175
+ break
176
+ if requested:
177
+ raise DataError(f"Missing selected tar members: {sorted(requested)}")
178
+ return {
179
+ "files": result,
180
+ "compressed_read_bytes": limited.bytes_read,
181
+ "output_bytes": written,
182
+ }