summaryrefslogtreecommitdiff
path: root/formatRefs.py
blob: 4da52c69121d797cf19621cd93afdd3d26b6241c (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
#!/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):
    ret = []

    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))

    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)

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

        # 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 = [formatParent (s, g, p) for  p in parents]

        # 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)