"""Bootstrap and atomic same-revision publication through Hugging Face Hub.""" from __future__ import annotations import logging import os import shutil import tempfile from pathlib import Path logger = logging.getLogger(__name__) def bootstrap_from_hf( *, data_dir: Path, repo_id: str, token: str | None = None ) -> bool: """Hydrate prior append-only state on an ephemeral scheduled runner.""" if any((data_dir / "filings").glob("**/*.parquet")): return False try: from huggingface_hub import snapshot_download from huggingface_hub.errors import HfHubHTTPError, RepositoryNotFoundError except ImportError as error: # pragma: no cover - exercised in publish environment raise RuntimeError("install the 'publish' extra to bootstrap from Hugging Face") from error temporary = Path(tempfile.mkdtemp(prefix="insider-hf-bootstrap-")) try: try: snapshot_download( repo_id=repo_id, repo_type="dataset", token=token, allow_patterns=["data/**"], local_dir=temporary, ) except RepositoryNotFoundError: return False # first publication except HfHubHTTPError as error: if getattr(error.response, "status_code", None) == 404: return False raise downloaded = temporary / "data" if not downloaded.exists(): return False data_dir.mkdir(parents=True, exist_ok=True) for source in downloaded.glob("**/*"): if not source.is_file(): continue target = data_dir / source.relative_to(downloaded) target.parent.mkdir(parents=True, exist_ok=True) if not target.exists(): shutil.copy2(source, target) return True finally: shutil.rmtree(temporary, ignore_errors=True) def publish_to_hf( *, project_root: Path, repo_id: str, token: str | None = None ) -> str: try: from huggingface_hub import HfApi except ImportError as error: # pragma: no cover - exercised in publish environment raise RuntimeError("install the 'publish' extra to publish to Hugging Face") from error api = HfApi(token=token) api.create_repo(repo_id=repo_id, repo_type="dataset", exist_ok=True) local = { str(path.relative_to(project_root)) for path in project_root.glob("data/**/*.parquet") } commit = api.upload_folder( repo_id=repo_id, repo_type="dataset", folder_path=project_root, # Without this, an upload only ever adds. Partition file names are # derived from their contents, so a rebuild writes different names and # the previous build's files stay behind -- every row then appears # twice, and years dropped from the rebuild come back from the dead. # The published tree has to be what is on disk, not the union of every # build that ever ran. delete_patterns=["data/**"], allow_patterns=[ "data/**", "recipe/**", "tests/**", "jobs/**", "README.md", "PIPELINE.md", "manifest.json", "pyproject.toml", "LICENSE", "NOTICE", ], # The append lock is local coordination state, not published data. ignore_patterns=["**/__pycache__/**", "**/*.pyc", "**/.append.lock"], commit_message="Update the security master", ) # A mirror that quietly failed to mirror is the failure this guards. Names # are enough: a partition file's name is derived from its contents, so a # set difference catches both a leftover from a previous build and a file # that never arrived -- without downloading anything. published = { sibling.rfilename for sibling in api.dataset_info(repo_id).siblings if sibling.rfilename.startswith("data/") and sibling.rfilename.endswith(".parquet") } stale, missing = published - local, local - published if stale or missing: raise RuntimeError( f"published tree does not match the local one: {len(stale)} stale file(s) " f"left behind, {len(missing)} missing. Examples: " f"stale={sorted(stale)[:3]} missing={sorted(missing)[:3]}" ) logger.info("published tree mirrors %d local data files", len(local)) return str(commit.oid) def hf_token() -> str | None: """The token to act with: the environment first, then a stored login. A scheduled job receives HF_TOKEN as a secret; a person running the same command locally has usually run `hf auth login` instead, and should not have to export the token again to use it. """ token = os.environ.get("HF_TOKEN") if token: return token try: from huggingface_hub import get_token except ImportError: # pragma: no cover - exercised in the publish environment return None return get_token()