33import sys
44import tempfile
55from pathlib import Path
6- from typing import Any , Dict , Optional , Union
6+ from typing import Any , Dict , Optional , Type , Union
77
88
99if sys .version_info >= (3 , 8 ):
2323 eval_results_to_model_index ,
2424 model_index_to_eval_results ,
2525)
26+ from huggingface_hub .utils import yaml_dump
2627
2728from .constants import REPOCARD_NAME
28- from .utils import validate_hf_hub_args
29+ from .utils import EntryNotFoundError , validate_hf_hub_args
2930from .utils .logging import get_logger
3031
3132
@@ -512,7 +513,7 @@ def metadata_save(local_path: Union[str, Path], data: Dict) -> None:
512513
513514 # creates a new file if it not
514515 with open (local_path , "w" , newline = "" ) as readme :
515- data_yaml = yaml . dump (data , sort_keys = False , line_break = line_break )
516+ data_yaml = yaml_dump (data , sort_keys = False , line_break = line_break )
516517 # sort_keys: keep dict order
517518 match = REGEX_YAML_BLOCK .search (content )
518519 if match :
@@ -669,6 +670,9 @@ def metadata_update(
669670) -> str :
670671 """
671672 Updates the metadata in the README.md of a repository on the Hugging Face Hub.
673+ If the README.md file doesn't exist yet, a new one is created with metadata and an
674+ the default ModelCard or DatasetCard template. For `space` repo, an error is thrown
675+ as a Space cannot exist without a `README.md` file.
672676
673677 Args:
674678 repo_id (`str`):
@@ -685,7 +689,7 @@ def metadata_update(
685689 The Hugging Face authentication token.
686690 commit_message (`str`, *optional*):
687691 The summary / title / first line of the generated commit. Defaults to
688- `f"Update metdata with huggingface_hub"`
692+ `f"Update metadata with huggingface_hub"`
689693 commit_description (`str` *optional*)
690694 The description of the generated commit
691695 revision (`str`, *optional*):
@@ -724,7 +728,30 @@ def metadata_update(
724728 else "Update metadata with huggingface_hub"
725729 )
726730
727- card = ModelCard .load (repo_id , token = token )
731+ # Card class given repo_type
732+ card_class : Type [RepoCard ]
733+ if repo_type is None or repo_type == "model" :
734+ card_class = ModelCard
735+ elif repo_type == "dataset" :
736+ card_class = DatasetCard
737+ elif repo_type == "space" :
738+ card_class = RepoCard
739+ else :
740+ raise ValueError (f"Unknown repo_type: { repo_type } " )
741+
742+ # Either load repo_card from the Hub or create an empty one.
743+ # NOTE: Will not create the repo if it doesn't exist.
744+ try :
745+ card = card_class .load (repo_id , token = token , repo_type = repo_type )
746+ except EntryNotFoundError :
747+ if repo_type == "space" :
748+ raise ValueError (
749+ "Cannot update metadata on a Space that doesn't contain a `README.md`"
750+ " file."
751+ )
752+
753+ # Initialize a ModelCard or DatasetCard from default template and no data.
754+ card = card_class .from_template (CardData ())
728755
729756 for key , value in metadata .items ():
730757 if key == "model-index" :
0 commit comments