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

Handle multiple ld types #631

Merged
merged 2 commits into from
Oct 16, 2024
Merged
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
32 changes: 17 additions & 15 deletions src/fundus/parser/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
from lxml.etree import XPath, tostring
from typing_extensions import Self, TypeAlias, deprecated

from fundus.utils.serialization import replace_keys_in_nested_dict
from fundus.utils.serialization import JSONVal, replace_keys_in_nested_dict

LDMappingValue: TypeAlias = Union[List[Dict[str, Any]], Dict[str, Any]]

Expand Down Expand Up @@ -64,23 +64,25 @@ def __init__(self, lds: Iterable[Dict[str, Any]] = ()):
def serialize(self) -> Dict[str, Any]:
return {attribute: value for attribute, value in self.__dict__.items() if "__" not in attribute}

def _add(self, ld: Dict[str, JSONVal], ld_type: str) -> None:
if value := self.__dict__.get(ld_type):
if not isinstance(value, list):
self.__dict__[ld_type] = [value]
self.__dict__[ld_type].append(ld)
else:
self.__dict__[ld_type] = ld

def add_ld(self, ld: Dict[str, Any], name: Optional[str] = None) -> None:
if ld_type := ld.get("@type", name):
if isinstance(ld_type, list):
if len(ld_type) == 1:
ld_type = ld_type[0]
else:
raise TypeError(f"Unable tp parse ld_type '{ld_type}' of type {list} with length != 1")
if value := self.__dict__.get(ld_type):
if not isinstance(value, list):
self.__dict__[ld_type] = [value]
self.__dict__[ld_type].append(ld)
if ld_type := (name or ld.get("@type")):
if isinstance(ld_type, str):
self._add(ld, ld_type)
elif isinstance(ld_type, list):
for t in ld_type:
self._add(ld, t)
else:
self.__dict__[ld_type] = ld
raise NotImplementedError(f"Unexpected LD type {type(ld_type)}")
else:
if not self.__dict__.get(self.__UNKNOWN_TYPE__):
self.__dict__[self.__UNKNOWN_TYPE__] = []
self.__dict__[self.__UNKNOWN_TYPE__].append(ld)
self._add(ld, self.__UNKNOWN_TYPE__)

@deprecated("Use xpath_search() instead")
def get_value_by_key_path(self, key_path: List[str], default: Any = None) -> Optional[Any]:
Expand Down