Datasets:
Download code/robohome/src/engine/source/packages/asset_registry/ingestion.py from RoboParty/RoboHome: direct link, hf CLI and curl.
- Browser
- Download file 18.2 kB
-
https://huggingface.co/datasets/RoboParty/RoboHome/resolve/main/code/robohome/src/engine/source/packages/asset_registry/ingestion.py
- Command line
-
hf download hf://datasets/RoboParty/RoboHome/code/robohome/src/engine/source/packages/asset_registry/ingestion.py
-
curl -L -o ingestion.py https://huggingface.co/datasets/RoboParty/RoboHome/resolve/main/code/robohome/src/engine/source/packages/asset_registry/ingestion.py
18.2 kB
| from __future__ import annotations | |
| import hashlib | |
| import json | |
| import os | |
| import shutil | |
| import urllib.error | |
| import urllib.request | |
| import uuid | |
| from concurrent.futures import ThreadPoolExecutor | |
| from datetime import UTC, datetime | |
| from enum import StrEnum | |
| from pathlib import Path, PurePosixPath | |
| from typing import Literal | |
| import yaml # type: ignore[import-untyped] | |
| from pydantic import BaseModel, ConfigDict, Field, model_validator | |
| from packages.core.files import atomic_write_text | |
| class _StrictModel(BaseModel): | |
| model_config = ConfigDict(extra="forbid", validate_assignment=True) | |
| class SourceAccess(StrEnum): | |
| OPEN = "open" | |
| GATED = "gated" | |
| MANUAL_AGREEMENT = "manual_agreement" | |
| LICENSE_REVIEW = "license_review" | |
| class DownloadArtifact(_StrictModel): | |
| artifact_id: str = Field(pattern=r"^[a-z0-9][a-z0-9_.-]*$") | |
| url: str | |
| relative_path: str | |
| expected_sha256: str | None = Field(default=None, pattern=r"^[0-9a-f]{64}$") | |
| expected_md5: str | None = Field(default=None, pattern=r"^[0-9a-f]{32}$") | |
| expected_size_bytes: int | None = Field(default=None, gt=0) | |
| def validate_relative_path(self) -> DownloadArtifact: | |
| path = PurePosixPath(self.relative_path) | |
| if path.is_absolute() or ".." in path.parts or not path.name: | |
| raise ValueError("artifact relative_path must stay inside its raw version directory") | |
| return self | |
| class AssetSourceSpec(_StrictModel): | |
| source_id: str = Field(pattern=r"^[a-z0-9][a-z0-9_.-]*$") | |
| display_name: str | |
| descriptor_source_aliases: list[str] = Field(default_factory=list) | |
| version: str | |
| purpose: list[str] = Field(default_factory=list) | |
| ingestion_priority: int = Field(default=100, ge=1) | |
| license_id: str | |
| license_url: str | |
| access: SourceAccess | |
| registration_required: bool = False | |
| auto_download_allowed: bool = False | |
| download_method: str | |
| source_url: str | |
| official_size_bytes: int | None = Field(default=None, gt=0) | |
| current_local_path: str | None = None | |
| current_local_size_bytes: int | None = Field(default=None, ge=0) | |
| artifacts: list[DownloadArtifact] = Field(default_factory=list) | |
| notes: list[str] = Field(default_factory=list) | |
| def validate_access_policy(self) -> AssetSourceSpec: | |
| if self.access != SourceAccess.OPEN and self.auto_download_allowed: | |
| raise ValueError("restricted sources cannot enable unattended download") | |
| if self.auto_download_allowed and not self.artifacts: | |
| raise ValueError("auto-download source requires explicit versioned artifacts") | |
| return self | |
| class SourceRegistry(_StrictModel): | |
| schema_version: Literal["1.0"] = "1.0" | |
| generated_for: str = "RoboHouseGen" | |
| sources: list[AssetSourceSpec] | |
| def validate_source_ids(self) -> SourceRegistry: | |
| ids = [source.source_id for source in self.sources] | |
| if len(ids) != len(set(ids)): | |
| raise ValueError("source registry IDs must be unique") | |
| return self | |
| def from_yaml(cls, path: Path) -> SourceRegistry: | |
| return cls.model_validate(yaml.safe_load(path.read_text(encoding="utf-8"))) | |
| def require(self, source_id: str) -> AssetSourceSpec: | |
| for source in self.sources: | |
| if source.source_id == source_id: | |
| return source | |
| raise KeyError(f"asset source is not registered: {source_id}") | |
| class AssetStoreLayout(_StrictModel): | |
| root: Path | |
| raw: Path | |
| staged: Path | |
| certified: Path | |
| quarantine: Path | |
| manifests: Path | |
| def for_root(cls, root: Path) -> AssetStoreLayout: | |
| resolved = root.resolve() | |
| if resolved == Path(resolved.anchor): | |
| raise ValueError("asset store root cannot be a filesystem root") | |
| return cls( | |
| root=resolved, | |
| raw=resolved / "raw", | |
| staged=resolved / "staged", | |
| certified=resolved / "certified", | |
| quarantine=resolved / "quarantine", | |
| manifests=resolved / "manifests", | |
| ) | |
| def initialize(self) -> None: | |
| for path in (self.raw, self.staged, self.certified, self.quarantine, self.manifests): | |
| path.mkdir(parents=True, exist_ok=True) | |
| class LicenseBlockedError(RuntimeError): | |
| pass | |
| class ChecksumMismatchError(RuntimeError): | |
| pass | |
| class ResumeNotSupportedError(RuntimeError): | |
| pass | |
| class IngestArtifactResult(_StrictModel): | |
| artifact_id: str | |
| status: Literal["downloaded", "reused", "blocked", "failed", "staged", "duplicate"] | |
| raw_path: str | None = None | |
| staged_path: str | None = None | |
| bytes: int = Field(default=0, ge=0) | |
| sha256: str | None = None | |
| resumed_from_bytes: int = Field(default=0, ge=0) | |
| message: str = "" | |
| class IngestRunManifest(_StrictModel): | |
| schema_version: Literal["1.0"] = "1.0" | |
| run_id: str | |
| source_id: str | |
| source_version: str | |
| source_license: str | |
| license_url: str | |
| authorization_record: str | None = None | |
| authorization_record_sha256: str | None = Field(default=None, pattern=r"^[0-9a-f]{64}$") | |
| started_at: datetime | |
| completed_at: datetime | |
| asset_store_root: str | |
| raw_immutable: Literal[True] = True | |
| results: list[IngestArtifactResult] | |
| def sha256_file(path: Path) -> str: | |
| digest = hashlib.sha256() | |
| with path.open("rb") as handle: | |
| for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""): | |
| digest.update(chunk) | |
| return digest.hexdigest() | |
| def md5_file(path: Path) -> str: | |
| """Return a source checksum when an upstream catalog publishes only MD5. | |
| SHA-256 remains the content identity used by RoboHouseGen. MD5 is evaluated | |
| only as an additional exact-byte check against the publisher's manifest. | |
| """ | |
| digest = hashlib.md5(usedforsecurity=False) | |
| with path.open("rb") as handle: | |
| for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""): | |
| digest.update(chunk) | |
| return digest.hexdigest() | |
| class AssetIngestor: | |
| def __init__(self, layout: AssetStoreLayout, *, timeout_s: int = 120) -> None: | |
| self.layout = layout | |
| self.timeout_s = timeout_s | |
| def _check_authorization(source: AssetSourceSpec, authorization_record: Path | None) -> None: | |
| if source.access == SourceAccess.OPEN and not source.auto_download_allowed: | |
| raise LicenseBlockedError( | |
| f"{source.source_id} is plan-only until its version-pinned artifact manifest " | |
| "is reviewed and auto_download_allowed is enabled" | |
| ) | |
| if source.access == SourceAccess.OPEN: | |
| return | |
| if authorization_record is None or not authorization_record.is_file(): | |
| raise LicenseBlockedError( | |
| f"{source.source_id} requires a local authorization record; " | |
| "RoboHouseGen will not accept terms or supply credentials automatically" | |
| ) | |
| def _raw_destination(self, source: AssetSourceSpec, artifact: DownloadArtifact) -> Path: | |
| version_root = (self.layout.raw / source.source_id / source.version).resolve() | |
| destination = (version_root / Path(*PurePosixPath(artifact.relative_path).parts)).resolve() | |
| if version_root not in destination.parents: | |
| raise ValueError("raw destination escaped source version root") | |
| return destination | |
| def download( | |
| self, | |
| source: AssetSourceSpec, | |
| artifact: DownloadArtifact, | |
| *, | |
| authorization_record: Path | None = None, | |
| ) -> IngestArtifactResult: | |
| self._check_authorization(source, authorization_record) | |
| destination = self._raw_destination(source, artifact) | |
| partial = destination.with_suffix(destination.suffix + ".part") | |
| destination.parent.mkdir(parents=True, exist_ok=True) | |
| if destination.exists(): | |
| digest = sha256_file(destination) | |
| if artifact.expected_sha256 and digest != artifact.expected_sha256: | |
| raise ChecksumMismatchError( | |
| f"existing immutable raw file hash differs: {destination}" | |
| ) | |
| if ( | |
| artifact.expected_size_bytes | |
| and destination.stat().st_size != artifact.expected_size_bytes | |
| ): | |
| raise ChecksumMismatchError( | |
| f"existing immutable raw file size differs: {destination}" | |
| ) | |
| if artifact.expected_md5 and md5_file(destination) != artifact.expected_md5: | |
| raise ChecksumMismatchError( | |
| f"existing immutable raw file publisher checksum differs: {destination}" | |
| ) | |
| return IngestArtifactResult( | |
| artifact_id=artifact.artifact_id, | |
| status="reused", | |
| raw_path=str(destination), | |
| bytes=destination.stat().st_size, | |
| sha256=digest, | |
| ) | |
| resume_from = partial.stat().st_size if partial.is_file() else 0 | |
| request = urllib.request.Request( | |
| artifact.url, | |
| headers={ | |
| "User-Agent": "RoboHouseGen-AssetIngest/1.0", | |
| **({"Range": f"bytes={resume_from}-"} if resume_from else {}), | |
| }, | |
| ) | |
| try: | |
| response = urllib.request.urlopen(request, timeout=self.timeout_s) # noqa: S310 | |
| except urllib.error.URLError as error: | |
| raise RuntimeError(f"asset download failed: {artifact.url}: {error}") from error | |
| status = getattr(response, "status", response.getcode()) | |
| if resume_from and status != 206: | |
| response.close() | |
| raise ResumeNotSupportedError( | |
| f"server did not honor Range for {artifact.artifact_id}; " | |
| f"partial retained at {partial}" | |
| ) | |
| mode = "ab" if resume_from else "xb" | |
| try: | |
| with partial.open(mode) as handle, response: | |
| shutil.copyfileobj(response, handle, length=4 * 1024 * 1024) | |
| handle.flush() | |
| os.fsync(handle.fileno()) | |
| except FileExistsError as error: | |
| raise RuntimeError(f"concurrent partial download detected: {partial}") from error | |
| size = partial.stat().st_size | |
| if artifact.expected_size_bytes is not None and size != artifact.expected_size_bytes: | |
| raise ChecksumMismatchError( | |
| f"download size mismatch for {artifact.artifact_id}: {size} != " | |
| f"{artifact.expected_size_bytes}; partial retained" | |
| ) | |
| digest = sha256_file(partial) | |
| if artifact.expected_md5 is not None and md5_file(partial) != artifact.expected_md5: | |
| raise ChecksumMismatchError( | |
| f"download publisher checksum mismatch for {artifact.artifact_id}; partial retained" | |
| ) | |
| if artifact.expected_sha256 is not None and digest != artifact.expected_sha256: | |
| raise ChecksumMismatchError( | |
| f"download checksum mismatch for {artifact.artifact_id}; partial retained" | |
| ) | |
| partial.replace(destination) | |
| destination.chmod(0o444) | |
| return IngestArtifactResult( | |
| artifact_id=artifact.artifact_id, | |
| status="downloaded", | |
| raw_path=str(destination), | |
| bytes=size, | |
| sha256=digest, | |
| resumed_from_bytes=resume_from, | |
| ) | |
| def stage( | |
| self, | |
| source: AssetSourceSpec, | |
| artifact: DownloadArtifact, | |
| download: IngestArtifactResult, | |
| ) -> IngestArtifactResult: | |
| if not download.raw_path or not download.sha256: | |
| raise ValueError("only a verified raw artifact can be staged") | |
| raw = Path(download.raw_path).resolve() | |
| expected_raw_root = (self.layout.raw / source.source_id / source.version).resolve() | |
| if expected_raw_root not in raw.parents: | |
| raise ValueError("raw artifact does not belong to this source version") | |
| relative = raw.relative_to(expected_raw_root) | |
| staged = (self.layout.staged / source.source_id / source.version / relative).resolve() | |
| if staged.exists(): | |
| if sha256_file(staged) != download.sha256: | |
| raise FileExistsError(f"refusing to overwrite staged artifact: {staged}") | |
| status: Literal["staged", "duplicate"] = "duplicate" | |
| else: | |
| staged.parent.mkdir(parents=True, exist_ok=True) | |
| # Never hard-link staged data to raw: a converter that writes in | |
| # place would otherwise mutate the supposedly immutable raw inode. | |
| shutil.copy2(raw, staged) | |
| staged.chmod(0o644) | |
| status = "staged" | |
| content_record = ( | |
| self.layout.manifests / "content" / download.sha256[:2] / (download.sha256 + ".json") | |
| ) | |
| if not content_record.exists(): | |
| content_record.parent.mkdir(parents=True, exist_ok=True) | |
| atomic_write_text( | |
| content_record, | |
| json.dumps( | |
| { | |
| "schema_version": "1.0", | |
| "sha256": download.sha256, | |
| "first_raw_path": str(raw), | |
| "source_id": source.source_id, | |
| "source_version": source.version, | |
| }, | |
| indent=2, | |
| sort_keys=True, | |
| ) | |
| + "\n", | |
| ) | |
| return IngestArtifactResult( | |
| artifact_id=artifact.artifact_id, | |
| status=status, | |
| raw_path=str(raw), | |
| staged_path=str(staged), | |
| bytes=download.bytes, | |
| sha256=download.sha256, | |
| resumed_from_bytes=download.resumed_from_bytes, | |
| ) | |
| def run( | |
| self, | |
| source: AssetSourceSpec, | |
| *, | |
| authorization_record: Path | None = None, | |
| stage: bool = True, | |
| workers: int = 1, | |
| ) -> IngestRunManifest: | |
| if not 1 <= workers <= 64: | |
| raise ValueError("ingestion workers must be between 1 and 64") | |
| self.layout.initialize() | |
| started = datetime.now(UTC) | |
| results: list[IngestArtifactResult] = [] | |
| try: | |
| self._check_authorization(source, authorization_record) | |
| except LicenseBlockedError as error: | |
| results.append( | |
| IngestArtifactResult( | |
| artifact_id="source-access", | |
| status="blocked", | |
| message=str(error), | |
| ) | |
| ) | |
| access_blocked = bool(results and results[0].artifact_id == "source-access") | |
| def download_one(artifact: DownloadArtifact) -> IngestArtifactResult: | |
| try: | |
| return self.download(source, artifact, authorization_record=authorization_record) | |
| except LicenseBlockedError as error: | |
| return IngestArtifactResult( | |
| artifact_id=artifact.artifact_id, | |
| status="blocked", | |
| message=str(error), | |
| ) | |
| except Exception as error: | |
| return IngestArtifactResult( | |
| artifact_id=artifact.artifact_id, | |
| status="failed", | |
| message=f"{type(error).__name__}:{error}", | |
| ) | |
| if not access_blocked: | |
| if workers == 1: | |
| downloads = [download_one(artifact) for artifact in source.artifacts] | |
| else: | |
| # Download distinct immutable destinations concurrently, then stage | |
| # in manifest order. Serial staging keeps the content-hash ledger | |
| # deterministic even if two URLs resolve to identical bytes. | |
| with ThreadPoolExecutor( | |
| max_workers=workers, | |
| thread_name_prefix=f"ingest-{source.source_id}", | |
| ) as executor: | |
| downloads = list(executor.map(download_one, source.artifacts)) | |
| for artifact, downloaded in zip(source.artifacts, downloads, strict=True): | |
| if stage and downloaded.status in {"downloaded", "reused"}: | |
| try: | |
| results.append(self.stage(source, artifact, downloaded)) | |
| except Exception as error: | |
| results.append( | |
| IngestArtifactResult( | |
| artifact_id=artifact.artifact_id, | |
| status="failed", | |
| raw_path=downloaded.raw_path, | |
| bytes=downloaded.bytes, | |
| sha256=downloaded.sha256, | |
| resumed_from_bytes=downloaded.resumed_from_bytes, | |
| message=f"{type(error).__name__}:{error}", | |
| ) | |
| ) | |
| else: | |
| results.append(downloaded) | |
| completed = datetime.now(UTC) | |
| run_id = completed.strftime("%Y%m%dT%H%M%SZ") + "-" + uuid.uuid4().hex[:8] | |
| manifest = IngestRunManifest( | |
| run_id=run_id, | |
| source_id=source.source_id, | |
| source_version=source.version, | |
| source_license=source.license_id, | |
| license_url=source.license_url, | |
| authorization_record=( | |
| str(authorization_record.resolve()) if authorization_record else None | |
| ), | |
| authorization_record_sha256=( | |
| sha256_file(authorization_record) | |
| if authorization_record is not None and authorization_record.is_file() | |
| else None | |
| ), | |
| started_at=started, | |
| completed_at=completed, | |
| asset_store_root=str(self.layout.root), | |
| results=results, | |
| ) | |
| destination = self.layout.manifests / source.source_id / source.version / f"{run_id}.json" | |
| destination.parent.mkdir(parents=True, exist_ok=True) | |
| atomic_write_text(destination, manifest.model_dump_json(indent=2) + "\n") | |
| return manifest | |