summaryrefslogtreecommitdiff
path: root/tools/formatRefs.py
blob: 280a444f35930f91a393693d448ab129b64ed246 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
#!/usr/bin/env python3

from rdflib import URIRef, BNode, Literal, Graph, Namespace
from rdflib.namespace import RDF, NamespaceManager
from urllib.parse import urlparse
import sys
from itertools import chain

def first (it):
    try:
        return next (it)
    except StopIteration:
        return None

def humanList (l):
    if len (l) == 0:
        return ''
    elif len (l) == 1:
        return l[0]
    else:
        return ', '.join (l[:-1]) + ' and ' + l[-1]

def formatDomain (url):
    d = urlparse (url).hostname
    if d.startswith ('www.'):
        d = d[4:]
    return d

def formatPerson (s, g, n):
    firstname = first (g.objects (n, s.givenName))
    familyname = first (g.objects (n, s.familyName))
    if firstname:
        return '{} {}'.format (firstname, familyname)
    else:
        return familyname

def formatParent (s, g, n, useName = True):
    ret = []

    if useName:
        parentname = first (g.objects (n, s.name))
        if parentname:
            ret.append (parentname)

    volume = first (g.objects (n, s.volumeNumber))
    if volume:
        ret.append ('volume {}'.format (volume))

    issue = first (g.objects (n, s.issueNumber))
    if issue:
        ret.append ('issue {}'.format (issue))

    # pages
    start = first (g.objects (n, s.pageStart))
    end = first (g.objects (n, s.pageEnd))
    if start:
        try:
            num = int (end)-int (start)
        except (ValueError, TypeError):
            num = 1
        if end and num >= 1:
            ret.append ('pp. {}–{}'.format (start, end))
        else:
            ret.append ('p. {}'.format (start))

    return ', '.join (ret)

def relUri (base, u):
    if u.startswith (base):
        return u[len (base):]
    else:
        return u

def hideLocalUri (base, l):
    """
    Show local uris only iff no other sources are available
    """
    l = list (l)
    notLocal = list (filter (lambda u: relUri (base, u) == u, l))
    return notLocal or l

def getRecursive (s, g, n, predicate):
    """
    Look for predicate in n and all Things it is a part of until it is found
    """
    res = g.objects (n, predicate)
    if res:
        yield from res
    parents = g.objects (n, s.isPartOf)
    for p in parents:
        yield from getRecursive (s, g, p, predicate)

def getRecursiveAll (s, g, n, predicate):
    parents = list (g.objects (n, predicate))
    yield from parents
    for p in parents:
        yield from getRecursiveAll (s, g, p, predicate)

def warnUnusedButDefined (graph, rootNode):
    """
    Warn about defined, but unused subjects
    """

    subjects = set ()
    objects = set ()
    for s, p, o in graph:
        subjects.add (s)
        objects.add (o)
    for unused in subjects.difference (objects):
        if unused == rootNode:
            continue
        print ('Unused: {}'.format (unused), file=sys.stderr)
        for ctxp, ctxo in g[unused]:
            print ('\t{} {}'.format (ctxp, ctxo), file=sys.stderr)

if __name__ == '__main__':
    g = Graph()
    result = g.parse ("index.ttl", format='turtle')
    rootUri = sys.argv[1]
    rootNode = URIRef (rootUri)
    s = Namespace("https://schema.org/")

    warnUnusedButDefined (result, rootNode)

    for ref in result.objects (rootNode, s.citation):
        t = list (g.objects (ref, RDF.type))
        assert len (t) == 1
        t = t[0]

        # object _must_ have a name
        what = first (g.objects (ref, s.name))

        # look for people who wrote/translated/edited it
        who = map (lambda a: formatPerson (s, g, a), getRecursive (s, g, ref, s.author))
        #who = chain (who, map (lambda a: formatPerson (s, g, a) + ' (ed.)', getRecursive (s, g, ref, s.editor)))
        #who = chain (who, map (lambda a: formatPerson (s, g, a) + ' (trans.)', getRecursive (s, g, ref, s.translator)))
        who = humanList (list (who))

        # when was it published?
        when = first (getRecursive (s, g, ref, s.datePublished))
        if not when:
            # fall back to creation date
            when = first (getRecursive (s, g, ref, s.dateCreated))

        # where can we find it? (print)
        # print from root to ref (i.e. magazine, volume, issue)
        parents = reversed (list (getRecursiveAll (s, g, ref, s.isPartOf)))
        where = list (filter (lambda x: x, [formatParent (s, g, p) for p in parents]))
        thiswhere = formatParent (s, g, ref, False)
        if thiswhere:
            where.append (thiswhere)

        # where can we find it? (online)
        urls = hideLocalUri (rootUri, g.objects (ref, s.url))
        urls = ['`{} <{}>`__'.format (formatDomain (url), relUri (rootUri, url)) for url in urls]

        refname = urlparse (ref).fragment
        if not refname:
            refname = first (g.objects (ref, s.alternateName))
        ret = '.. [{}] \\ '.format (refname)

        if who:
            ret += ' {}:'.format (who)

        ret += ' *{}*.'.format (what)

        if where:
            ret += ' {}.'.format (', '.join (where))

        if when:
            ret += ' {}.'.format (when)

        if urls:
            ret += ' {}.'.format (', '.join (urls))
        print (ret)