| """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: |
| 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 |
| 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: |
| 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, |
| |
| |
| |
| |
| |
| |
| delete_patterns=["data/**"], |
| allow_patterns=[ |
| "data/**", |
| "recipe/**", |
| "tests/**", |
| "jobs/**", |
| "README.md", |
| "PIPELINE.md", |
| "manifest.json", |
| "pyproject.toml", |
| "LICENSE", |
| "NOTICE", |
| ], |
| |
| ignore_patterns=["**/__pycache__/**", "**/*.pyc", "**/.append.lock"], |
| commit_message="Update the security master", |
| ) |
| |
| |
| |
| |
| 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: |
| return None |
| return get_token() |
|
|