-
Notifications
You must be signed in to change notification settings - Fork 613
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
Merged
Merged
Changes from 7 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
f382bb9
repocard utilities + tests
julien-c 09c9ddd
mix those methods on Repository
julien-c 450eb93
handle case of no README.md inside repo
julien-c 59b41a9
suggestion from @osanseviero
julien-c f4abbbf
tiny doc add
julien-c 7e181de
`MODELCARD_NAME` => more general `REPOCARD_NAME`
julien-c c182c6e
Merge branch 'main' into repo_metadata_load_and_save
julien-c d82cc92
Additional test
LysandreJik File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
|
||
|
||
# exact same regex as in the Hub server. Please keep in sync. | ||
REGEX_YAML_BLOCK = re.compile(r"---[\n\r]+([\S\s]*?)[\n\r]+---[\n\r]") | ||
|
||
|
||
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 | ||
|
||
|
||
def metadata_save(local_path: Union[str, Path], data: Dict) -> None: | ||
data_yaml = yaml.dump(data, sort_keys=False) | ||
# sort_keys: keep dict order | ||
content = Path(local_path).read_text() if Path(local_path).is_file() else "" | ||
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 REPOCARD_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) / REPOCARD_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) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
This should probably raise an error too, right? Running
metadata_load
on any random file will return nothing while I would expect it to fail if it doesn't find any metadataThere 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.
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 comment
The 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