Skip to content

Commit

Permalink
Preserve card metadata format/ordering on load->save (#2570)
Browse files Browse the repository at this point in the history
* Preserve card metadata format/ordering on load->save

* Update tests/test_repocard.py

---------

Co-authored-by: Lucain <lucainp@gmail.com>
  • Loading branch information
hlky and Wauplin authored Oct 3, 2024
1 parent 8042483 commit 1b8e9cf
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 3 deletions.
3 changes: 2 additions & 1 deletion src/huggingface_hub/repocard.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def __init__(self, content: str, ignore_metadata_errors: bool = False):
def content(self):
"""The content of the RepoCard, including the YAML block and the Markdown body."""
line_break = _detect_line_ending(self._content) or "\n"
return f"---{line_break}{self.data.to_yaml(line_break=line_break)}{line_break}---{line_break}{self.text}"
return f"---{line_break}{self.data.to_yaml(line_break=line_break, original_order=self._original_order)}{line_break}---{line_break}{self.text}"

@content.setter
def content(self, content: str):
Expand All @@ -110,6 +110,7 @@ def content(self, content: str):
self.text = content

self.data = self.card_data_class(**data_dict, ignore_metadata_errors=self.ignore_metadata_errors)
self._original_order = list(data_dict.keys())

def __str__(self):
return self.content
Expand Down
10 changes: 8 additions & 2 deletions src/huggingface_hub/repocard_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ class CardData:
def __init__(self, ignore_metadata_errors: bool = False, **kwargs):
self.__dict__.update(kwargs)

def to_dict(self) -> Dict[str, Any]:
def to_dict(self):
"""Converts CardData to a dict.
Returns:
Expand All @@ -195,7 +195,7 @@ def _to_dict(self, data_dict):
"""
pass

def to_yaml(self, line_break=None) -> str:
def to_yaml(self, line_break=None, original_order: Optional[List[str]] = None) -> str:
"""Dumps CardData to a YAML block for inclusion in a README.md file.
Args:
Expand All @@ -205,6 +205,12 @@ def to_yaml(self, line_break=None) -> str:
Returns:
`str`: CardData represented as a YAML block.
"""
if original_order:
self.__dict__ = {
k: self.__dict__[k]
for k in original_order + list(set(self.__dict__.keys()) - set(original_order))
if k in self.__dict__
}
return yaml_dump(self.to_dict(), sort_keys=False, line_break=line_break).strip()

def __repr__(self):
Expand Down
5 changes: 5 additions & 0 deletions tests/test_repocard.py
Original file line number Diff line number Diff line change
Expand Up @@ -847,6 +847,11 @@ def test_model_card_from_template_eval_results(self):
self.assertTrue(card.data.to_dict().get("eval_results") is None)
self.assertEqual(str(card)[: len(DUMMY_MODELCARD_EVAL_RESULT)], DUMMY_MODELCARD_EVAL_RESULT)

def test_preserve_order_load_save(self):
model_card = ModelCard(DUMMY_MODELCARD)
model_card.data.license = "test"
self.assertEqual(model_card.content, "---\nlicense: test\ndatasets:\n- foo\n- bar\n---\n\nHello\n")


class DatasetCardTest(TestCaseWithHfApi):
def test_load_datasetcard_from_file(self):
Expand Down

0 comments on commit 1b8e9cf

Please sign in to comment.