Source code

Download source archive ↓

src/rdflib/tools/rdfs2dot.py

1"""
2A commandline tool for drawing RDFS Class diagrams in Graphviz DOT
3format
4
5You can draw the graph of an RDFS file directly:
6
7```bash
8rdf2dot my_rdfs_file.rdf | dot -Tpng | display
9```
10"""
11
12from __future__ import annotations
13
14import collections
15import itertools
16import sys
17from typing import Dict
18
19import rdflib.extras.cmdlineutils
20from rdflib import RDF, RDFS, XSD
21from rdflib.term import Identifier
22
23XSDTERMS = [
24    XSD[x]
25    for x in (
26        "anyURI",
27        "base64Binary",
28        "boolean",
29        "byte",
30        "date",
31        "dateTime",
32        "decimal",
33        "double",
34        "duration",
35        "float",
36        "gDay",
37        "gMonth",
38        "gMonthDay",
39        "gYear",
40        "gYearMonth",
41        "hexBinary",
42        "ID",
43        "IDREF",
44        "IDREFS",
45        "int",
46        "integer",
47        "language",
48        "long",
49        "Name",
50        "NCName",
51        "negativeInteger",
52        "NMTOKEN",
53        "NMTOKENS",
54        "nonNegativeInteger",
55        "nonPositiveInteger",
56        "normalizedString",
57        "positiveInteger",
58        "QName",
59        "short",
60        "string",
61        "time",
62        "token",
63        "unsignedByte",
64        "unsignedInt",
65        "unsignedLong",
66        "unsignedShort",
67    )
68]
69
70EDGECOLOR = "blue"
71NODECOLOR = "black"
72ISACOLOR = "black"
73
74
75def rdfs2dot(g, stream, opts={}):
76    """
77    Convert the RDFS schema in a graph
78    writes the dot output to the stream
79    """
80
81    fields = collections.defaultdict(set)
82    nodes: Dict[Identifier, str] = {}
83
84    def node(nd):
85        if nd not in nodes:
86            nodes[nd] = "node%d" % len(nodes)
87        return nodes[nd]
88
89    def label(xx, grf):
90        lbl = grf.value(xx, RDFS.label)
91        if lbl is None:
92            try:
93                lbl = grf.namespace_manager.compute_qname(xx)[2]
94            except Exception:
95                pass  # bnodes and some weird URIs cannot be split
96        return lbl
97
98    stream.write('digraph { \n node [ fontname="DejaVu Sans" ] ; \n')
99
100    for x in g.subjects(RDF.type, RDFS.Class):
101        n = node(x)
102
103    for x, y in g.subject_objects(RDFS.subClassOf):
104        x = node(x)
105        y = node(y)
106        stream.write("\t%s -> %s [ color=%s ] ;\n" % (y, x, ISACOLOR))
107
108    for x in g.subjects(RDF.type, RDF.Property):
109        for a, b in itertools.product(
110            g.objects(x, RDFS.domain), g.objects(x, RDFS.range)
111        ):
112            if b in XSDTERMS or b == RDFS.Literal:
113                l_ = label(b, g)
114                if b == RDFS.Literal:
115                    l_ = "literal"
116                fields[node(a)].add((label(x, g), l_))
117            else:
118                #            if a in nodes and b in nodes:
119                stream.write(
120                    '\t%s -> %s [ color=%s, label="%s" ];\n'
121                    % (node(a), node(b), EDGECOLOR, label(x, g))
122                )
123
124    for u, n in nodes.items():
125        stream.write("# %s %s\n" % (u, n))
126        f = [
127            "<tr><td align='left'>%s</td><td>%s</td></tr>" % x
128            for x in sorted(fields[n])
129        ]
130        opstr = (
131            "%s [ shape=none, color=%s label=< <table color='#666666'"
132            + " cellborder='0' cellspacing='0' border='1'><tr>"
133            + "<td colspan='2' bgcolor='grey'><B>%s</B></td>"
134            + "</tr>%s</table> > ] \n"
135        )
136        stream.write(opstr % (n, NODECOLOR, label(u, g), "".join(f)))
137
138    stream.write("}\n")
139
140
141def _help():
142    sys.stderr.write(
143        """
144rdfs2dot.py [-f <format>] files...
145Read RDF files given on STDOUT, writes a graph of the RDFS schema in
146DOT language to stdout
147-f specifies parser to use, if not given,
148
149"""
150    )
151
152
153def main():
154    rdflib.extras.cmdlineutils.main(rdfs2dot, _help)
155
156
157if __name__ == "__main__":
158    main()