Source code

Download source archive ↓

src/rdflib/tools/rdf2dot.py

1"""
2A commandline tool for drawing RDF graphs in Graphviz DOT format
3
4You can draw the graph of an RDF file directly:
5
6```bash
7rdf2dot my_rdf_file.rdf | dot -Tpng | display
8```
9"""
10
11from __future__ import annotations
12
13import collections
14import html
15import sys
16from typing import Any, Dict, TextIO
17
18import rdflib
19import rdflib.extras.cmdlineutils
20from rdflib import XSD
21from rdflib.graph import Graph
22from rdflib.term import Literal, Node, URIRef
23
24LABEL_PROPERTIES = [
25    rdflib.RDFS.label,
26    rdflib.URIRef("http://purl.org/dc/elements/1.1/title"),
27    rdflib.URIRef("http://xmlns.com/foaf/0.1/name"),
28    rdflib.URIRef("http://www.w3.org/2006/vcard/ns#fn"),
29    rdflib.URIRef("http://www.w3.org/2006/vcard/ns#org"),
30]
31
32XSDTERMS = [
33    XSD[x]
34    for x in (
35        "anyURI",
36        "base64Binary",
37        "boolean",
38        "byte",
39        "date",
40        "dateTime",
41        "decimal",
42        "double",
43        "duration",
44        "float",
45        "gDay",
46        "gMonth",
47        "gMonthDay",
48        "gYear",
49        "gYearMonth",
50        "hexBinary",
51        "ID",
52        "IDREF",
53        "IDREFS",
54        "int",
55        "integer",
56        "language",
57        "long",
58        "Name",
59        "NCName",
60        "negativeInteger",
61        "NMTOKEN",
62        "NMTOKENS",
63        "nonNegativeInteger",
64        "nonPositiveInteger",
65        "normalizedString",
66        "positiveInteger",
67        "QName",
68        "short",
69        "string",
70        "time",
71        "token",
72        "unsignedByte",
73        "unsignedInt",
74        "unsignedLong",
75        "unsignedShort",
76    )
77]
78
79EDGECOLOR = "blue"
80NODECOLOR = "black"
81ISACOLOR = "black"
82
83
84def rdf2dot(g: Graph, stream: TextIO, opts: Dict[str, Any] = {}):
85    """
86    Convert the RDF graph to DOT
87    writes the dot output to the stream
88    """
89
90    fields = collections.defaultdict(set)
91    nodes: Dict[Node, str] = {}
92
93    def node(x: Node) -> str:
94        if x not in nodes:
95            nodes[x] = "node%d" % len(nodes)
96        return nodes[x]
97
98    def label(x: Node, g: Graph):
99        for labelProp in LABEL_PROPERTIES:  # noqa: N806
100            l_ = g.value(x, labelProp)
101            if l_:
102                return l_
103        try:
104            # type error: Argument 1 to "compute_qname" of "NamespaceManager" has incompatible type "Node"; expected "str"
105            return g.namespace_manager.compute_qname(x)[2]  # type: ignore[arg-type]
106        except Exception:
107            return x
108
109    def formatliteral(l: Literal, g):  # noqa: E741
110        v = html.escape(l)
111        if l.datatype:
112            return ""%s"^^%s" % (v, qname(l.datatype, g))
113        elif l.language:
114            return ""%s"@%s" % (v, l.language)
115        return ""%s"" % v
116
117    def qname(x: URIRef, g: Graph) -> str:
118        try:
119            q = g.compute_qname(x)
120            return q[0] + ":" + q[2]
121        except Exception:
122            return x
123
124    def color(p):
125        return "BLACK"
126
127    stream.write('digraph { \n node [ fontname="DejaVu Sans" ] ; \n')
128
129    for s, p, o in g:
130        sn = node(s)
131        if p == rdflib.RDFS.label:
132            continue
133        if isinstance(o, (rdflib.URIRef, rdflib.BNode)):
134            on = node(o)
135            opstr = (
136                "\t%s -> %s [ color=%s, label=< <font point-size='10' "
137                + "color='#336633'>%s</font> > ] ;\n"
138            )
139            # type error: Argument 1 to "qname" has incompatible type "Node"; expected "URIRef"
140            stream.write(opstr % (sn, on, color(p), qname(p, g)))  # type: ignore[arg-type]
141        else:
142            # type error: Argument 1 to "qname" has incompatible type "Node"; expected "URIRef"
143            fields[sn].add((qname(p, g), formatliteral(o, g)))  # type: ignore[arg-type]
144
145    for u, n in nodes.items():
146        stream.write("# %s %s\n" % (u, n))
147        f = [
148            "<tr><td align='left'>%s</td><td align='left'>%s</td></tr>" % x
149            for x in sorted(fields[n])
150        ]
151        opstr = (
152            "%s [ shape=none, color=%s label=< <table color='#666666'"
153            + " cellborder='0' cellspacing='0' border='1'><tr>"
154            + "<td colspan='2' bgcolor='grey'><B>%s</B></td></tr><tr>"
155            + "<td href='%s' bgcolor='#eeeeee' colspan='2'>"
156            + "<font point-size='10' color='#6666ff'>%s</font></td>"
157            + "</tr>%s</table> > ] \n"
158        )
159        stream.write(
160            opstr
161            # type error: Value of type variable "AnyStr" of "escape" cannot be "Node"
162            % (n, NODECOLOR, html.escape(label(u, g)), u, html.escape(u), "".join(f))  # type: ignore[type-var]
163        )
164
165    stream.write("}\n")
166
167
168def _help():
169    sys.stderr.write(
170        """
171rdf2dot.py [-f <format>] files...
172Read RDF files given on STDOUT, writes a graph of the RDFS schema in DOT
173language to stdout
174-f specifies parser to use, if not given,
175
176"""
177    )
178
179
180def main():
181    rdflib.extras.cmdlineutils.main(rdf2dot, _help)
182
183
184if __name__ == "__main__":
185    main()