-
Notifications
You must be signed in to change notification settings - Fork 608
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Repo metadata load and save #339
Changes from 2 commits
f382bb9
09c9ddd
450eb93
59b41a9
f4abbbf
7e181de
c182c6e
d82cc92
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import re | ||
from pathlib import Path | ||
from typing import Dict, Optional, Union | ||
|
||
import yaml | ||
|
||
|
||
REGEX_YAML_BLOCK = re.compile(r"---[\n\r]+([\S\s]*?)[\n\r]+---[\n\r]") | ||
# exact same regex as in the hf hub server. Please keep in sync. | ||
julien-c marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
|
||
def metadata_load(local_path: Union[str, Path]) -> Optional[Dict]: | ||
content = Path(local_path).read_text() | ||
match = REGEX_YAML_BLOCK.search(content) | ||
if match: | ||
yaml_block = match.group(1) | ||
data = yaml.safe_load(yaml_block) | ||
if isinstance(data, dict): | ||
return data | ||
else: | ||
raise ValueError("repo card metadata block should be a dict") | ||
else: | ||
return None | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This should probably raise an error too, right? Running There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If that's the expected behavior then I would also put it in a test to ensure that it doesn't switch to raising an error in the future There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. as discussed offline we have a lot of repo cards (model cards, etc) that do not have a yaml block, and i think the expected behavior here is to return None. If need be, we might modify this in a subsequent PR |
||
|
||
|
||
def metadata_save(local_path: Union[str, Path], data: Dict) -> None: | ||
data_yaml = yaml.dump(data, sort_keys=False) | ||
# keep dict order | ||
content = Path(local_path).read_text() | ||
match = REGEX_YAML_BLOCK.search(content) | ||
if match: | ||
output = ( | ||
content[: match.start()] + f"---\n{data_yaml}---\n" + content[match.end() :] | ||
) | ||
else: | ||
output = f"---\n{data_yaml}---\n{content}" | ||
|
||
Path(local_path).write_text(output) |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
# Copyright 2021 The HuggingFace Team. All rights reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
import os | ||
import shutil | ||
import unittest | ||
from pathlib import Path | ||
|
||
from huggingface_hub.constants import MODELCARD_NAME | ||
from huggingface_hub.repocard import metadata_load, metadata_save | ||
|
||
from .testing_utils import set_write_permission_and_retry | ||
|
||
|
||
DUMMY_MODELCARD = """ | ||
|
||
Hi | ||
|
||
--- | ||
license: mit | ||
datasets: | ||
- foo | ||
- bar | ||
--- | ||
|
||
Hello | ||
""" | ||
|
||
DUMMY_MODELCARD_TARGET = """ | ||
|
||
Hi | ||
|
||
--- | ||
meaning_of_life: 42 | ||
--- | ||
|
||
Hello | ||
""" | ||
|
||
DUMMY_MODELCARD_TARGET_NO_YAML = """--- | ||
meaning_of_life: 42 | ||
--- | ||
Hello | ||
""" | ||
|
||
REPOCARD_DIR = os.path.join( | ||
os.path.dirname(os.path.abspath(__file__)), "fixtures/repocard" | ||
) | ||
|
||
|
||
class RepocardTest(unittest.TestCase): | ||
def setUp(self): | ||
os.makedirs(REPOCARD_DIR, exist_ok=True) | ||
|
||
def tearDown(self) -> None: | ||
try: | ||
shutil.rmtree(REPOCARD_DIR, onerror=set_write_permission_and_retry) | ||
except FileNotFoundError: | ||
pass | ||
|
||
def test_metadata_load(self): | ||
filepath = Path(REPOCARD_DIR) / MODELCARD_NAME | ||
filepath.write_text(DUMMY_MODELCARD) | ||
data = metadata_load(filepath) | ||
self.assertDictEqual(data, {"license": "mit", "datasets": ["foo", "bar"]}) | ||
|
||
def test_metadata_save(self): | ||
filename = "dummy_target.md" | ||
filepath = Path(REPOCARD_DIR) / filename | ||
filepath.write_text(DUMMY_MODELCARD) | ||
metadata_save(filepath, {"meaning_of_life": 42}) | ||
content = filepath.read_text() | ||
self.assertEqual(content, DUMMY_MODELCARD_TARGET) | ||
|
||
def test_metadata_save_from_file_no_yaml(self): | ||
filename = "dummy_target_2.md" | ||
filepath = Path(REPOCARD_DIR) / filename | ||
filepath.write_text("Hello\n") | ||
metadata_save(filepath, {"meaning_of_life": 42}) | ||
content = filepath.read_text() | ||
self.assertEqual(content, DUMMY_MODELCARD_TARGET_NO_YAML) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You're setting
MODELCARD_NAME
here but using therepocard
term elsewhere - what should it be? I would favor having all instances beREPOCARD_NAME
if you're looking for a repo-type-agnostic name