Datasets:
Download src/explicit_learning/cli/resource.py from sungguk/visual-answerability: direct link, hf CLI and curl.
- Browser
- Download file 7.32 kB
-
https://huggingface.co/datasets/sungguk/visual-answerability/resolve/main/src/explicit_learning/cli/resource.py
- Command line
-
hf download hf://datasets/sungguk/visual-answerability/src/explicit_learning/cli/resource.py
-
curl -L -o resource.py https://huggingface.co/datasets/sungguk/visual-answerability/resolve/main/src/explicit_learning/cli/resource.py
7.32 kB
| """``explicit-resource`` — exact-revision resource fetch and verification. | |
| Subcommands: | |
| list Show every pinned resource with its role, revision, required approval | |
| gates, and current block status given an approval file. | |
| fetch Download one or all resources at pinned revisions into the model/data | |
| roots, appending a ``resource_snapshot.jsonl`` row per success. A | |
| blocked gate skips the resource with a reason (never substitutes). | |
| verify Offline-verify a previously fetched resource against its recorded | |
| snapshot row (recompute the file-tree manifest, detect LFS pointers, | |
| reject a resolved/requested-commit mismatch or content drift). | |
| See ``docs/01_RESOURCE_CATALOG.md`` §7 and ``docs/07_IMPLEMENTATION_TASKS.md`` | |
| section 3. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import os | |
| import sys | |
| from pathlib import Path | |
| from .. import __version__ | |
| from ..config import ConfigError, load_resources | |
| from ..logging_setup import get_logger | |
| from ..paths import repo_root | |
| from ..resources import ( | |
| ResourceError, | |
| block_reason, | |
| fetch_one, | |
| load_approval, | |
| plan, | |
| verify_one, | |
| ) | |
| logger = get_logger("resource") | |
| def _add_config(parser: argparse.ArgumentParser) -> None: | |
| parser.add_argument( | |
| "--resources", | |
| type=Path, | |
| default=repo_root() / "configs" / "resources.yaml", | |
| ) | |
| def _token() -> str | None: | |
| """Read ``HF_TOKEN`` from the environment (never logged).""" | |
| return os.environ.get("HF_TOKEN") or None | |
| def cmd_list(args: argparse.Namespace) -> int: | |
| try: | |
| resources = load_resources(args.resources) | |
| except (ConfigError, FileNotFoundError) as exc: | |
| print(f"RESOURCE LIST FAILED: {exc}", file=sys.stderr) | |
| return 1 | |
| approval = load_approval(args.approval) | |
| rows = [] | |
| for ref in plan(resources): | |
| reason = block_reason(ref, approval) | |
| rows.append( | |
| { | |
| "logical_name": ref.logical_name, | |
| "kind": ref.kind, | |
| "role": ref.role, | |
| "repo_id": ref.repo_id, | |
| "revision": ref.revision, | |
| "local_path": str(ref.local_path), | |
| "required_gates": list(ref.required_gates), | |
| "blocked": reason is not None, | |
| "block_reason": reason, | |
| } | |
| ) | |
| print(json.dumps({"resources": rows}, sort_keys=True)) | |
| return 0 | |
| def _snapshot_path(args: argparse.Namespace) -> Path: | |
| return Path(args.snapshot) | |
| def cmd_fetch(args: argparse.Namespace) -> int: | |
| try: | |
| resources = load_resources(args.resources) | |
| except (ConfigError, FileNotFoundError) as exc: | |
| print(f"RESOURCE FETCH FAILED: {exc}", file=sys.stderr) | |
| return 1 | |
| approval = load_approval(args.approval) | |
| refs = plan(resources) | |
| if args.name: | |
| wanted = set(args.name) | |
| refs = [r for r in refs if r.logical_name in wanted] | |
| missing = wanted - {r.logical_name for r in refs} | |
| if missing: | |
| print(f"RESOURCE FETCH FAILED: unknown resource(s): {sorted(missing)}", file=sys.stderr) | |
| return 1 | |
| allow = tuple(args.include) if args.include else None | |
| snapshot_path = _snapshot_path(args) | |
| snapshot_path.parent.mkdir(parents=True, exist_ok=True) | |
| results = [] | |
| failures = 0 | |
| for ref in refs: | |
| try: | |
| result = fetch_one( | |
| ref, | |
| approval, | |
| snapshot_path=snapshot_path, | |
| allow_patterns=allow, | |
| token=_token(), | |
| ) | |
| except ResourceError as exc: | |
| # ResourceError messages must never carry the token; verify defensively. | |
| failures += 1 | |
| logger.error("fetch %s failed: %s", ref.logical_name, exc) | |
| results.append( | |
| {"status": "failed", "logical_name": ref.logical_name, "error": str(exc)} | |
| ) | |
| continue | |
| results.append(result) | |
| if result["status"] == "skipped": | |
| logger.info("skip %s: %s", ref.logical_name, result["reason"]) | |
| else: | |
| logger.info("fetched %s (%d files)", ref.logical_name, result["row"]["file_count"]) | |
| print(json.dumps({"results": results, "failures": failures}, sort_keys=True)) | |
| return 1 if failures else 0 | |
| def cmd_verify(args: argparse.Namespace) -> int: | |
| try: | |
| resources = load_resources(args.resources) | |
| except (ConfigError, FileNotFoundError) as exc: | |
| print(f"RESOURCE VERIFY FAILED: {exc}", file=sys.stderr) | |
| return 1 | |
| refs = plan(resources) | |
| if args.name: | |
| wanted = set(args.name) | |
| refs = [r for r in refs if r.logical_name in wanted] | |
| missing = wanted - {r.logical_name for r in refs} | |
| if missing: | |
| print( | |
| f"RESOURCE VERIFY FAILED: unknown resource(s): {sorted(missing)}", file=sys.stderr | |
| ) | |
| return 1 | |
| snapshot_path = _snapshot_path(args) | |
| results = [] | |
| failures = 0 | |
| for ref in refs: | |
| try: | |
| result = verify_one(ref, snapshot_path) | |
| except ResourceError as exc: | |
| failures += 1 | |
| result = {"logical_name": ref.logical_name, "ok": False, "error": str(exc)} | |
| results.append(result) | |
| print(json.dumps({"results": results, "failures": failures}, sort_keys=True)) | |
| return 1 if failures else 0 | |
| def build_parser() -> argparse.ArgumentParser: | |
| parser = argparse.ArgumentParser(prog="explicit-resource") | |
| parser.add_argument("--version", action="version", version=f"explicit-resource {__version__}") | |
| sub = parser.add_subparsers(dest="command", required=True) | |
| p_list = sub.add_parser("list", help="List pinned resources and their gate status.") | |
| _add_config(p_list) | |
| p_list.add_argument("--approval", type=Path, default=None, help="resource_approval.json path.") | |
| p_list.set_defaults(func=cmd_list) | |
| p_fetch = sub.add_parser("fetch", help="Download resources at pinned revisions.") | |
| _add_config(p_fetch) | |
| p_fetch.add_argument("--approval", type=Path, default=None) | |
| p_fetch.add_argument("--name", action="append", help="resource logical name (repeatable).") | |
| p_fetch.add_argument( | |
| "--include", | |
| action="append", | |
| help="glob allow-pattern forwarded to the downloader (repeatable, small-fetch fixture).", | |
| ) | |
| p_fetch.add_argument( | |
| "--snapshot", | |
| type=Path, | |
| default=repo_root() / "resource_snapshot.jsonl", | |
| help="resource_snapshot.jsonl path to append rows to.", | |
| ) | |
| p_fetch.set_defaults(func=cmd_fetch) | |
| p_verify = sub.add_parser( | |
| "verify", help="Offline-verify a fetched resource vs its snapshot row." | |
| ) | |
| _add_config(p_verify) | |
| p_verify.add_argument("--name", action="append", help="resource logical name (repeatable).") | |
| p_verify.add_argument( | |
| "--snapshot", | |
| type=Path, | |
| default=repo_root() / "resource_snapshot.jsonl", | |
| help="resource_snapshot.jsonl path to verify against.", | |
| ) | |
| p_verify.set_defaults(func=cmd_verify) | |
| return parser | |
| def main(argv: list[str] | None = None) -> int: | |
| parser = build_parser() | |
| args = parser.parse_args(argv) | |
| return int(args.func(args)) | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |