hf-release / src /hf_release /core /hf_client.py
MikeChandler's picture
feat: initial release of hf-release v0.1.0
f824e2f verified
"""Hugging Face Hub operations."""
from __future__ import annotations
from pathlib import Path
from huggingface_hub import HfApi, ModelCard
from huggingface_hub.errors import (
EntryNotFoundError,
RepositoryNotFoundError,
RevisionNotFoundError,
)
from ..utils.exceptions import AuthenticationError, ModelCardSyncError, RepoNotFoundError, TagConflictError, UploadError
class HFClient:
def __init__(self, token: str) -> None:
self._token = token
self._api = HfApi(token=token)
# ------------------------------------------------------------------
# Repo helpers
# ------------------------------------------------------------------
def ensure_repo_exists(self, repo_id: str, create: bool = False) -> None:
try:
self._api.repo_info(repo_id=repo_id, repo_type="model")
except RepositoryNotFoundError:
if create:
self._api.create_repo(repo_id=repo_id, repo_type="model", private=False)
else:
raise RepoNotFoundError(
f"HF repo '{repo_id}' not found.",
suggestion="Create it on huggingface.co or pass --create-repo.",
)
except Exception as exc:
if "401" in str(exc) or "403" in str(exc):
raise AuthenticationError(
"HF token rejected.",
suggestion="Check that HF_TOKEN has write access to the repo.",
) from exc
raise
# ------------------------------------------------------------------
# Upload
# ------------------------------------------------------------------
def push_model(
self,
local_path: Path,
repo_id: str,
branch: str = "main",
commit_message: str | None = None,
ignore_patterns: list[str] | None = None,
) -> str:
"""Upload a local directory to HF Hub. Returns the commit URL."""
msg = commit_message or f"Upload model via hf-release"
try:
result = self._api.upload_folder(
folder_path=str(local_path),
repo_id=repo_id,
repo_type="model",
commit_message=msg,
revision=branch,
ignore_patterns=ignore_patterns or [],
)
except RepositoryNotFoundError:
raise RepoNotFoundError(
f"HF repo '{repo_id}' not found.",
suggestion="Create it on huggingface.co or pass --create-repo.",
)
except Exception as exc:
raise UploadError(f"Failed to upload model: {exc}") from exc
return result if isinstance(result, str) else str(result)
# ------------------------------------------------------------------
# Tagging
# ------------------------------------------------------------------
def create_tag(self, repo_id: str, tag: str, message: str | None = None) -> None:
try:
self._api.create_tag(
repo_id=repo_id,
repo_type="model",
tag=tag,
tag_message=message or tag,
)
except RevisionNotFoundError:
raise TagConflictError(
f"Could not create tag '{tag}' on HF repo '{repo_id}': revision not found.",
suggestion="Make sure the model was pushed before tagging.",
)
except Exception as exc:
if "already exists" in str(exc).lower():
# Tag already there — treat as idempotent success
return
raise TagConflictError(f"Failed to create HF tag '{tag}': {exc}") from exc
# ------------------------------------------------------------------
# Model card
# ------------------------------------------------------------------
def get_model_card(self, repo_id: str) -> ModelCard | None:
try:
path = self._api.hf_hub_download(
repo_id=repo_id,
filename="README.md",
repo_type="model",
)
return ModelCard.load(path)
except EntryNotFoundError:
return None
except RepositoryNotFoundError:
raise RepoNotFoundError(f"HF repo '{repo_id}' not found.")
except Exception as exc:
raise ModelCardSyncError(f"Failed to fetch model card: {exc}") from exc
def push_model_card(self, card: ModelCard, repo_id: str) -> None:
try:
card.push_to_hub(repo_id, token=self._token)
except Exception as exc:
raise ModelCardSyncError(f"Failed to push model card to HF: {exc}") from exc