HESRT / examples /hesrt_io.py
Biogod's picture
Release 2026-09-17-v1.6: nine misaligned samples withdrawn (4,682 samples, 530 studies)
b225c97 verified
Raw History Blame Contribute Delete
6.96 kB
"""Small, public, checksum-verifying HESRT reader (Python 3.11+)."""
from __future__ import annotations
import hashlib
import json
import shutil
import tarfile
import tempfile
from pathlib import Path
from typing import Any
import pandas as pd
import zstandard as zstd
from huggingface_hub import HfApi, hf_hub_download
REPO_ID = "Biogod/HESRT"
RELEASE_TAG = "2026-09-17-v1.6"
PREFIX = "releases/2026-09-17/"
def sha256(path: Path) -> str:
"""Hash without loading the file into memory."""
h = hashlib.sha256()
with Path(path).open("rb") as handle:
for block in iter(lambda: handle.read(8 * 1024**2), b""):
h.update(block)
return h.hexdigest()
def load_catalog(revision: str = RELEASE_TAG, cache_dir: str | None = None) -> tuple[pd.DataFrame, str]:
"""Resolve the revision once, so catalog and packages use one immutable commit."""
commit = HfApi().dataset_info(REPO_ID, revision=revision, timeout=30).sha
path = hf_hub_download(REPO_ID, PREFIX + "catalog.parquet", repo_type="dataset",
revision=commit, cache_dir=cache_dir)
frame = pd.read_parquet(path)
if frame.gsm_id.duplicated().any():
raise ValueError("Catalog GSM identifiers are not unique")
return frame, commit
def member_name(name: str) -> str:
"""HESRT packages contain flat regular files, never paths or links."""
if not name or name in {".", ".."} or "/" in name or "\\" in name or ":" in name:
raise ValueError(f"Unsafe or unsupported archive member: {name!r}")
return name
def verify_members(directory: Path) -> dict[str, Any]:
"""Verify every member listed in the embedded package manifest."""
directory = Path(directory)
manifest = json.loads((directory / "manifest.json").read_text())
names: set[str] = set()
for record in manifest["members"]:
name = member_name(record["name"])
if name in names or name == "manifest.json":
raise ValueError(f"Duplicate/self-referential manifest member: {name}")
names.add(name)
p = directory / name
if p.is_symlink() or not p.is_file() or p.stat().st_size != record["bytes"]:
raise ValueError(f"Missing, linked, or wrong-size member: {name}")
if sha256(p) != record["sha256"]:
raise ValueError(f"Member SHA256 mismatch: {name}")
return manifest
def extract_verified(archive: Path, destination: Path, expected_sha256: str,
expected_uncompressed_bytes: int, expected_members: int) -> Path:
"""Verify, stream into a temporary directory, then atomically expose the result."""
archive, destination = Path(archive), Path(destination)
if sha256(archive) != expected_sha256:
raise ValueError("Archive SHA256 mismatch; do not use this download")
if destination.exists() or destination.is_symlink():
raise FileExistsError(f"Refusing to overwrite {destination}")
destination.parent.mkdir(parents=True, exist_ok=True)
tmp = Path(tempfile.mkdtemp(prefix=".hesrt-extract-", dir=destination.parent))
seen: set[str] = set()
total = 0
# The catalog excludes the manifest itself from its uncompressed-byte sum.
limit = int(expected_uncompressed_bytes) + 16 * 1024**2
try:
with archive.open("rb") as compressed, zstd.ZstdDecompressor().stream_reader(compressed) as stream:
with tarfile.open(fileobj=stream, mode="r|") as tar:
for item in tar:
name = member_name(item.name)
if not item.isfile() or name in seen or item.size < 0:
raise ValueError(f"Unsafe/duplicate archive entry: {name}")
total += item.size
if total > limit or len(seen) >= expected_members:
raise ValueError("Archive exceeds its catalog byte/member limits")
seen.add(name)
handle = tar.extractfile(item)
if handle is None:
raise ValueError(f"Unreadable archive member: {name}")
with handle, (tmp / name).open("xb") as out:
shutil.copyfileobj(handle, out, length=8 * 1024**2)
if (tmp / name).stat().st_size != item.size:
raise ValueError(f"Truncated member: {name}")
if len(seen) != expected_members or "manifest.json" not in seen:
raise ValueError("Incomplete package")
manifest = verify_members(tmp)
declared = {r["name"] for r in manifest["members"]} | {"manifest.json"}
if seen != declared:
raise ValueError("Archive and embedded manifest disagree")
if sum(int(r["bytes"]) for r in manifest["members"]) != expected_uncompressed_bytes:
raise ValueError("Catalog and manifest uncompressed-byte totals disagree")
tmp.rename(destination)
return destination
except BaseException:
shutil.rmtree(tmp, ignore_errors=True)
raise
def download_sample(row: Any, output: Path, revision: str,
cache_dir: str | None = None) -> Path:
"""Download one GSM; completed downloads are reverified rather than overwritten."""
name = str(row["archive_path"])
expected = PREFIX + f"samples/{row['gse_id']}/{row['gsm_id']}.tar.zst"
if name != expected:
raise ValueError("Unexpected package path")
for accession in [row["gse_id"], row["gsm_id"]]:
member_name(str(accession))
destination = Path(output) / str(row["gse_id"]) / str(row["gsm_id"])
receipt = destination / "download_receipt.json"
if destination.exists():
if destination.is_symlink() or not receipt.is_file():
raise FileExistsError(f"Existing directory has no trusted download receipt: {destination}")
saved = json.loads(receipt.read_text())
if saved.get("archive_sha256") != row["archive_sha256"]:
raise ValueError("Existing sample belongs to a different package")
manifest = verify_members(destination)
else:
archive = Path(hf_hub_download(REPO_ID, name, repo_type="dataset", revision=revision,
cache_dir=cache_dir))
if archive.stat().st_size != int(row["archive_bytes"]):
raise ValueError("Archive size mismatch")
destination = extract_verified(archive, destination, row["archive_sha256"],
int(row["uncompressed_bytes"]), int(row["member_count"]))
manifest = json.loads((destination / "manifest.json").read_text())
receipt.write_text(json.dumps({"repo_id": REPO_ID, "revision": revision,
"archive_path": name, "archive_sha256": row["archive_sha256"]}, indent=2) + "\n")
if manifest["gsm_id"] != row["gsm_id"] or manifest["gse_id"] != row["gse_id"]:
raise ValueError("Manifest accession mismatch")
return destination