-
Notifications
You must be signed in to change notification settings - Fork 6
Added generic parser #215
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
Merged
Merged
Added generic parser #215
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
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
Empty file.
This file contains hidden or 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,148 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from collections import deque | ||
| from collections.abc import Generator, Iterable | ||
| from pathlib import Path | ||
| from typing import NamedTuple, Union | ||
|
|
||
|
|
||
| class BlankNode: | ||
| """Class for blank nodes, storing BN's identifier as a string.""" | ||
|
|
||
| def __init__(self, identifier: str) -> None: | ||
| self._identifier: str = identifier | ||
|
|
||
| def __repr__(self) -> str: | ||
| return f"_:{self._identifier}" | ||
|
|
||
|
|
||
| class IRI: | ||
| """Class for IRIs, storing IRI as a string.""" | ||
|
|
||
| def __init__(self, iri: str) -> None: | ||
| self._iri: str = iri | ||
|
|
||
| def __repr__(self) -> str: | ||
| return f"<{self._iri}>" | ||
|
|
||
|
|
||
| class Literal: | ||
| """ | ||
| Class for literals. | ||
|
|
||
| Notes: | ||
| Consists of: lexical form, and optional language tag and datatype. | ||
| All parts of literal are stored as strings. | ||
|
|
||
| """ | ||
|
|
||
| def __init__(self, lex: str, langtag: str | None, datatype: str | None) -> None: | ||
| self._lex: str = lex | ||
| self._langtag: str | None = langtag | ||
| self._datatype: str | None = datatype | ||
|
|
||
| def __repr__(self) -> str: | ||
| suffix = "" | ||
| if self._langtag: | ||
| suffix = f"@{self._langtag}" | ||
| elif self._datatype: | ||
| suffix = f"^^<{self._datatype}>" | ||
| return f'"{self._lex}"{suffix}' | ||
|
|
||
|
|
||
| Node = Union[BlankNode, IRI, Literal, "Triple", str] | ||
|
|
||
|
|
||
| class Triple(NamedTuple): | ||
| """Class for RDF triples.""" | ||
|
|
||
| s: Node | ||
| p: Node | ||
| o: Node | ||
|
|
||
|
|
||
| class Quad(NamedTuple): | ||
| """Class for RDF quads.""" | ||
|
|
||
| s: Node | ||
| p: Node | ||
| o: Node | ||
| g: Node | ||
|
|
||
|
|
||
| class Prefix(NamedTuple): | ||
| """Class for generic namespace declaration.""" | ||
|
|
||
| prefix: str | ||
| iri: IRI | ||
|
|
||
|
|
||
| class GenericStatementSink: | ||
| _store: deque[tuple[Node, ...]] | ||
|
|
||
| def __init__(self) -> None: | ||
| """ | ||
| Initialize statements storage and namespaces dictionary. | ||
|
|
||
| Notes: | ||
| _store preserves the order of statements. | ||
|
|
||
| """ | ||
| self._store: deque[tuple[Node, ...]] = deque() | ||
| self._namespaces: dict[str, IRI] = {} | ||
|
|
||
| def add(self, statement: Iterable[Node]) -> None: | ||
| self._store.append(tuple(statement)) | ||
|
|
||
| def bind(self, prefix: str, namespace: IRI) -> None: | ||
| self._namespaces.update({prefix: namespace}) | ||
|
|
||
| def __iter__(self) -> Generator[tuple[Node, ...]]: | ||
| yield from self._store | ||
|
|
||
| @property | ||
| def namespaces(self) -> Generator[tuple[str, IRI]]: | ||
| yield from self._namespaces.items() | ||
|
|
||
| @property | ||
| def is_triples_sink(self) -> bool: | ||
| """ | ||
| Check if the sink contains triples or quads. | ||
|
|
||
| Returns: | ||
| bool: true, if length of statement is 3. | ||
|
|
||
| """ | ||
| triples_arity = 3 | ||
| return len(self._store[0]) == triples_arity | ||
|
|
||
| def _serialize_node(self, node: Node) -> str: | ||
| """ | ||
| Serialize node to its string representation. | ||
|
|
||
| Args: | ||
| node (Node): Node to convert - RDF term, str, or Triple. | ||
|
|
||
| Returns: | ||
| str: string representation of Node. | ||
|
|
||
| """ | ||
| if isinstance(node, Triple): | ||
| quoted_triple = [self._serialize_node(t) for t in node] | ||
| return "<< " + " ".join(quoted_triple) + " >>" | ||
| return str(node) | ||
|
|
||
| def serialize(self, output_filename: Path, encoding: str = "utf-8") -> None: | ||
| """ | ||
| Serialize sink's store content to a simple N-triples/N-quads format. | ||
|
|
||
| Args: | ||
| output_filename (Path): path to the output file. | ||
| encoding (str): encoding of output. Defaults to utf-8. | ||
|
|
||
| """ | ||
| with output_filename.open("w", encoding=encoding) as output_file: | ||
| for statement in self._store: | ||
| output_file.write( | ||
| " ".join(self._serialize_node(t) for t in statement) + " .\n" | ||
| ) | ||
Oops, something went wrong.
Oops, something went wrong.
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.
currently not used anywhere, can potentially remove from here and from adapters, or just raise exception here
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.
Isn't that needed to pass conformance tests? We will have cases where you need to preserve namespaces.
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.
current conformance tests rely solely on .nt/.nq format, so no namespaces are there
from the spec, there is only one place that can issue a couple conformance tests:
value (2) – the IRI of the namespace as an RdfIri message. This field is REQUIRED.