#!/usr/bin/env python3 """Download one or more LocateAnything datasets and their media dependencies.""" from __future__ import annotations import argparse import fnmatch import json import os import sys from pathlib import Path from typing import Any, Iterable DEFAULT_REPO_ID = "NVEagle/LocateAnything-Data" DATASETS_MANIFEST = "manifests/datasets.jsonl" VIEWS_MANIFEST = "manifests/views.jsonl" POOLS_MANIFEST = "manifests/media-pools.jsonl" def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser( description=( "Download selected LocateAnything datasets together with their " "JSONL records, source mappings, and required media pools." ) ) parser.add_argument( "--dataset", action="append", default=[], metavar="ID[,ID...]", help=( "Dataset ID to download. Repeat the option or provide a " "comma-separated list." ), ) parser.add_argument( "--repo-id", default=DEFAULT_REPO_ID, help=f"Hugging Face dataset repository (default: {DEFAULT_REPO_ID}).", ) parser.add_argument( "--revision", default="main", help="Branch, tag, or full commit hash to download (default: main).", ) parser.add_argument( "--local-dir", type=Path, default=Path("LocateAnything-Data"), help="Destination directory (default: ./LocateAnything-Data).", ) parser.add_argument( "--cache-dir", type=Path, default=None, help=( "Hugging Face cache directory. Defaults to " "/.cache/huggingface." ), ) parser.add_argument( "--annotations-only", action="store_true", help="Download records and mappings but omit hosted TAR payloads.", ) parser.add_argument( "--dry-run", action="store_true", help="Show the dependency plan and download size without downloading.", ) parser.add_argument( "--list", action="store_true", help="List available dataset IDs and exit.", ) parser.add_argument( "--max-workers", type=int, default=8, help="Concurrent Hugging Face download workers (default: 8).", ) parser.add_argument( "--token", default=None, help=( "Optional Hugging Face token. Prefer `hf auth login` or HF_TOKEN " "instead of placing a token on the command line." ), ) args = parser.parse_args() if args.max_workers < 1: parser.error("--max-workers must be at least 1") if not args.list and not args.dataset: parser.error("provide at least one --dataset, or use --list") return args def import_huggingface_hub() -> tuple[Any, Any, Any]: try: from huggingface_hub import HfApi, hf_hub_download, snapshot_download except ImportError as exc: raise SystemExit( "huggingface_hub is required. Install it with " "`pip install -U huggingface_hub`." ) from exc return HfApi, hf_hub_download, snapshot_download def read_jsonl(path: str | Path) -> list[dict[str, Any]]: rows: list[dict[str, Any]] = [] with Path(path).open("r", encoding="utf-8") as handle: for line_number, line in enumerate(handle, 1): line = line.strip() if not line: continue try: row = json.loads(line) except json.JSONDecodeError as exc: raise SystemExit( f"invalid JSON in {path} at line {line_number}: {exc}" ) from exc if not isinstance(row, dict): raise SystemExit( f"expected a JSON object in {path} at line {line_number}" ) rows.append(row) return rows def download_manifest( hf_hub_download: Any, *, repo_id: str, revision: str, filename: str, token: str | None, cache_dir: Path, ) -> Path: return Path( hf_hub_download( repo_id=repo_id, repo_type="dataset", revision=revision, filename=filename, token=token, cache_dir=str(cache_dir), ) ) def normalize_dataset_ids(values: Iterable[str]) -> list[str]: dataset_ids: list[str] = [] seen: set[str] = set() for value in values: for item in value.split(","): dataset_id = item.strip() if dataset_id and dataset_id not in seen: dataset_ids.append(dataset_id) seen.add(dataset_id) return dataset_ids def human_bytes(size: int) -> str: value = float(size) units = ("B", "KiB", "MiB", "GiB", "TiB") for unit in units: if value < 1024 or unit == units[-1]: return f"{value:.1f} {unit}" value /= 1024 raise AssertionError("unreachable") def main() -> int: args = parse_args() cache_dir = args.cache_dir or args.local_dir / ".cache" / "huggingface" cache_dir.mkdir(parents=True, exist_ok=True) os.environ.setdefault("HF_HOME", str(cache_dir)) os.environ.setdefault("HF_HUB_CACHE", str(cache_dir / "hub")) os.environ.setdefault("HF_XET_CACHE", str(cache_dir / "xet")) HfApi, hf_hub_download, snapshot_download = import_huggingface_hub() manifest_paths = { DATASETS_MANIFEST: download_manifest( hf_hub_download, repo_id=args.repo_id, revision=args.revision, filename=DATASETS_MANIFEST, token=args.token, cache_dir=cache_dir, ), VIEWS_MANIFEST: download_manifest( hf_hub_download, repo_id=args.repo_id, revision=args.revision, filename=VIEWS_MANIFEST, token=args.token, cache_dir=cache_dir, ), POOLS_MANIFEST: download_manifest( hf_hub_download, repo_id=args.repo_id, revision=args.revision, filename=POOLS_MANIFEST, token=args.token, cache_dir=cache_dir, ), } datasets = { row["dataset_id"]: row for row in read_jsonl(manifest_paths[DATASETS_MANIFEST]) } views = read_jsonl(manifest_paths[VIEWS_MANIFEST]) pools = { row["pool_id"]: row for row in read_jsonl(manifest_paths[POOLS_MANIFEST]) } if args.list: for dataset_id in sorted(datasets): row = datasets[dataset_id] print( f"{dataset_id}\t{row.get('availability', 'unknown')}\t" f"{row.get('view_count', '?')} view(s)" ) return 0 selected = normalize_dataset_ids(args.dataset) unknown = sorted(set(selected) - datasets.keys()) if unknown: print( "Unknown dataset ID(s): " + ", ".join(unknown), file=sys.stderr, ) print( "Use --list to show valid IDs.", file=sys.stderr, ) return 2 pool_ids: set[str] = set() for dataset_id in selected: pool_ids.update(datasets[dataset_id].get("media_pool_ids", [])) for view in views: if view.get("dataset_id") not in selected: continue for source in view.get("aux_sources", []): pool_id = source.get("pool_id") if pool_id: pool_ids.add(pool_id) missing_pools = sorted(pool_ids - pools.keys()) if missing_pools: raise SystemExit( "media pool(s) absent from manifest: " + ", ".join(missing_pools) ) patterns = { "README.md", "README_CN.md", "release-policy.json", "manifests/**", "schemas/**", "examples/read_energon.py", "examples/read_indexed_jsonl.py", "tools/download_subset.py", "tools/hydrate_restricted_media.py", } for dataset_id in selected: patterns.add(f"datasets/{dataset_id}/**") patterns.add(f"mappings/views/{dataset_id}/**") for pool_id in pool_ids: patterns.add(f"mappings/media/{pool_id}/**") if args.annotations_only: patterns.add(f"media/{pool_id}/availability.json") else: patterns.add(f"media/{pool_id}/**") print("Datasets:") for dataset_id in selected: print(f" - {dataset_id}") print("Resolved media pools:") for pool_id in sorted(pool_ids): pool = pools[pool_id] availability = pool.get("availability", "unknown") payload = bool(pool.get("payload_in_hf_release")) if args.annotations_only and payload: status = "hosted payload omitted (--annotations-only)" elif payload: status = "hosted payload included" else: status = "external media; annotations and mappings only" print(f" - {pool_id}: {availability}; {status}") if args.dry_run: repo_info = HfApi().repo_info( repo_id=args.repo_id, repo_type="dataset", revision=args.revision, files_metadata=True, token=args.token, ) files = [ item for item in repo_info.siblings if any( fnmatch.fnmatchcase(item.rfilename, pattern) for pattern in patterns ) ] total_size = sum(int(getattr(item, "size", 0) or 0) for item in files) print( f"Dry run: {len(files)} selected file(s), " f"{human_bytes(total_size)} total." ) else: result = snapshot_download( repo_id=args.repo_id, repo_type="dataset", revision=args.revision, local_dir=str(args.local_dir), cache_dir=str(cache_dir), allow_patterns=sorted(patterns), token=args.token, max_workers=args.max_workers, ) print(f"Downloaded subset to: {result}") external = [ pool_id for pool_id in sorted(pool_ids) if not bool(pools[pool_id].get("payload_in_hf_release")) ] if external: print("External media still required for:") for pool_id in external: print(f" - {pool_id}") print( "Follow README.md and tools/hydrate_restricted_media.py after " "obtaining the upstream media." ) return 0 if __name__ == "__main__": raise SystemExit(main())