hf-release / src /hf_release /core /model_card.py
MikeChandler's picture
feat: initial release of hf-release v0.1.0
f824e2f verified
"""Model Card sync between local disk, HF Hub, and GitHub."""
from __future__ import annotations
from pathlib import Path
from huggingface_hub import ModelCard, ModelCardData
from ..utils.exceptions import ModelCardSyncError
def load_local_card(model_dir: Path) -> ModelCard | None:
readme = model_dir / "README.md"
if not readme.exists():
return None
try:
return ModelCard.load(str(readme))
except Exception as exc:
raise ModelCardSyncError(f"Failed to parse local README.md: {exc}") from exc
def update_card_metadata(card: ModelCard, version: str, extra_tags: list[str] | None = None) -> ModelCard:
"""Inject version tag and any extra tags into the card frontmatter."""
data: ModelCardData = card.data
tags: list[str] = list(data.tags or [])
if version not in tags:
tags.append(version)
for t in extra_tags or []:
if t not in tags:
tags.append(t)
data.tags = tags
card.data = data
return card
def sync_card(
*,
model_dir: Path | None,
hf_client, # HFClient | None
hf_repo: str | None,
version: str,
extra_tags: list[str] | None = None,
) -> bool:
"""
Sync model card from local dir → HF Hub.
Returns True if a card was pushed, False if skipped.
"""
if model_dir is None or hf_client is None or hf_repo is None:
return False
card = load_local_card(model_dir)
if card is None:
# Try to pull from HF and update metadata only
card = hf_client.get_model_card(hf_repo)
if card is None:
return False
card = update_card_metadata(card, version, extra_tags)
hf_client.push_model_card(card, hf_repo)
return True