Skip to content
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 8 commits into from
Sep 15, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ def get_version() -> str:
"filelock",
"requests",
"tqdm",
"pyyaml",
"typing-extensions",
"importlib_metadata;python_version<'3.8'",
"packaging>=20.9",
Expand Down
1 change: 1 addition & 0 deletions src/huggingface_hub/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
TF_WEIGHTS_NAME = "model.ckpt"
FLAX_WEIGHTS_NAME = "flax_model.msgpack"
CONFIG_NAME = "config.json"
MODELCARD_NAME = "README.md"
Copy link
Member

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 the repocard term elsewhere - what should it be? I would favor having all instances be REPOCARD_NAME if you're looking for a repo-type-agnostic name


HUGGINGFACE_CO_URL_HOME = "https://huggingface.co/"

Expand Down
38 changes: 38 additions & 0 deletions src/huggingface_hub/repocard.py
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
Copy link
Member

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 metadata

Copy link
Member

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

Copy link
Member Author

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



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)
11 changes: 9 additions & 2 deletions src/huggingface_hub/repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@
import time
from contextlib import contextmanager
from pathlib import Path
from typing import Iterator, List, Optional, Union
from typing import Dict, Iterator, List, Optional, Union

from tqdm.auto import tqdm

from huggingface_hub.constants import REPO_TYPES_URL_PREFIXES
from huggingface_hub.constants import MODELCARD_NAME, REPO_TYPES_URL_PREFIXES
from huggingface_hub.repocard import metadata_load, metadata_save

from .hf_api import ENDPOINT, HfApi, HfFolder, repo_type_and_id_from_hf_id
from .lfs import LFS_MULTIPART_UPLOAD_COMMAND
Expand Down Expand Up @@ -976,3 +977,9 @@ def commit(
raise e

os.chdir(current_working_directory)

def repocard_metadata_load(self) -> Optional[Dict]:
return metadata_load(os.path.join(self.local_dir, MODELCARD_NAME))

def repocard_metadata_save(self, data: Dict) -> None:
return metadata_save(os.path.join(self.local_dir, MODELCARD_NAME), data)
91 changes: 91 additions & 0 deletions tests/test_repocard.py
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)