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

Use LibYAML with PyYAML if available #6266

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
16 changes: 12 additions & 4 deletions src/datasets/utils/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,20 @@
from .deprecation_utils import deprecated


try:
from yaml import CSafeDumper as SafeDumper
from yaml import CSafeLoader as SafeLoader
except ImportError:
from yaml import SafeDumper, SafeLoader


logger = get_logger(__name__)


class _NoDuplicateSafeLoader(yaml.SafeLoader):
class _NoDuplicateSafeLoader(SafeLoader):
def _check_no_duplicates_on_constructed_node(self, node):
keys = [self.constructed_objects[key_node] for key_node, _ in node.value]
keys = [tuple(key) if isinstance(key, list) else key for key in keys]
keys = (self.constructed_objects[key_node] for key_node, _ in node.value)
keys = (tuple(key) if isinstance(key, list) else key for key in keys)
counter = Counter(keys)
duplicate_keys = [key for key in counter if counter[key] > 1]
if duplicate_keys:
Expand Down Expand Up @@ -105,11 +112,12 @@ def from_yaml_string(cls, string: str) -> "DatasetMetadata":
return cls(**metadata_dict)

def to_yaml_string(self) -> str:
return yaml.safe_dump(
return yaml.dump(
{
(key.replace("_", "-") if key in self._FIELDS_WITH_DASHES else key): value
for key, value in self.items()
},
Dumper=SafeDumper,
sort_keys=False,
allow_unicode=True,
encoding="utf-8",
Expand Down
8 changes: 7 additions & 1 deletion src/datasets/utils/readme.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,20 @@
from .deprecation_utils import deprecated


try:
from yaml import CSafeLoader as SafeLoader
except ImportError:
from yaml import SafeLoader


BASE_REF_URL = "https://github.com/huggingface/datasets/tree/main/src/datasets/utils"
this_url = f"{BASE_REF_URL}/{__file__}"
logger = logging.getLogger(__name__)


def load_yaml_resource(resource: str) -> Tuple[Any, str]:
content = pkg_resources.read_text(resources, resource)
return yaml.safe_load(content), f"{BASE_REF_URL}/resources/{resource}"
return yaml.load(content, Loader=SafeLoader), f"{BASE_REF_URL}/resources/{resource}"


readme_structure, known_readme_structure_url = load_yaml_resource("readme_structure.yaml")
Expand Down
Loading