|
32 | 32 |
|
33 | 33 | if TYPE_CHECKING: # pragma: no cover |
34 | 34 | import pandas |
| 35 | + import rdflib |
35 | 36 |
|
36 | 37 | __all__ = [ |
37 | 38 | "Converter", |
@@ -538,6 +539,39 @@ def from_jsonld_github( |
538 | 539 | url = f"https://raw.githubusercontent.com/{owner}/{repo}/{branch}/{rest}" |
539 | 540 | return cls.from_jsonld(url) |
540 | 541 |
|
| 542 | + @classmethod |
| 543 | + def from_rdflib( |
| 544 | + cls, |
| 545 | + graph_or_manager: Union["rdflib.Graph", "rdflib.namespace.NamespaceManager"], |
| 546 | + **kwargs: Any, |
| 547 | + ) -> "Converter": |
| 548 | + """Get a converter from an RDFLib graph or namespace manager. |
| 549 | +
|
| 550 | + :param graph_or_manager: A RDFLib graph or manager object |
| 551 | + :param kwargs: Keyword arguments to pass to :meth:`from_prefix_map` |
| 552 | + :return: A converter |
| 553 | +
|
| 554 | + In the following example, a :class:`rdflib.Graph` is created, a namespace |
| 555 | + is bound to it, then a converter is made: |
| 556 | +
|
| 557 | + >>> import rdflib, curies |
| 558 | + >>> graph = rdflib.Graph() |
| 559 | + >>> graph.bind("hgnc", "https://bioregistry.io/hgnc:") |
| 560 | + >>> converter = curies.Converter.from_rdflib(graph) |
| 561 | + >>> converter.expand("hgnc:1234") |
| 562 | + 'https://bioregistry.io/hgnc:1234' |
| 563 | +
|
| 564 | + This also works if you directly start with a :class:`rdflib.namespace.NamespaceManager`: |
| 565 | +
|
| 566 | + >>> converter = curies.Converter.from_rdflib(graph.namespace_manager) |
| 567 | + >>> converter.expand("hgnc:1234") |
| 568 | + 'https://bioregistry.io/hgnc:1234' |
| 569 | + """ |
| 570 | + # it's required to stringify namespace since it's a rdflib.URIRef |
| 571 | + # object, which acts funny if not coerced into a string |
| 572 | + prefix_map = {prefix: str(namespace) for prefix, namespace in graph_or_manager.namespaces()} |
| 573 | + return cls.from_prefix_map(prefix_map, **kwargs) |
| 574 | + |
541 | 575 | def get_prefixes(self) -> Set[str]: |
542 | 576 | """Get the set of prefixes covered by this converter.""" |
543 | 577 | return {record.prefix for record in self.records} |
|
0 commit comments