aboutsummaryrefslogtreecommitdiffstats
path: root/python/fatcat/api_client.py
blob: 6497e9772cc13845be59946fc63096546c7d8169 (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
177
178
179
180
181
182
183
184
185
186
187
188
189

import sys
import json
import requests


class FatCatApiClient:

    def __init__(self, host_url):
        self.host_url = host_url
        self.session = requests.Session()
        self._issn_map = dict()

    def get(self, path, data=None):
        headers = {"Content-Type": "application/json"}
        rv = self.session.get(self.host_url + path, params=data,
            headers=headers)
        #if rv.status_code not in [200, 201]:
        #    print(rv)
        #    print(rv.content)
        return rv

    def post(self, path, data=None):
        headers = {"Content-Type": "application/json"}
        rv = self.session.post(self.host_url + path, json=data,
            headers=headers)
        if rv.status_code not in [200, 201]:
            #print(rv)
            #print(rv.content)
            pass
        return rv

    def new_editgroup(self):
        rv = self.post('/v0/editgroup', data=dict(
            editor_id=1))
        assert rv.status_code in [200, 201]
        editgroup_id = rv.json()['id']
        return editgroup_id

    def accept_editgroup(self, eg):
        rv = self.post('/v0/editgroup/{}/accept'.format(eg))
        assert rv.status_code == 200
        return rv

    def lookup_issn(self, issn):
        assert len(issn) == 9 and issn[4] == '-'
        if issn in self._issn_map:
            return self._issn_map[issn]
        rv = self.get('/v0/container/lookup', data=dict(issn=issn))
        container_id = None
        if rv.status_code in [200, 201]:
            container_id = rv.json().get('ident', rv.json().get('id'))
        else:
            # only other valid response is a 404; otherwise we had an error
            assert rv.status_code == 404
        self._issn_map[issn] = container_id
        return container_id

    def import_crossref_file(self, json_file, create_containers=False, batchsize=100):
        eg = self.new_editgroup()
        i = 0
        if json_file == "-":
            stream = sys.stdin
        else:
            stream = open(json_file, 'r')
        for line in stream:
            if i % batchsize == 0:
                sys.stdout.write('\n{}: '.format(i))
            if (i+1) % 20 == 0:
                sys.stdout.write('.')
            i = i + 1
            obj = json.loads(line)
            if not ("author" in obj and "title" in obj):
                continue
            try:
                self.import_crossref_dict(obj, editgroup=eg,
                    create_containers=create_containers)
            except Exception as e:
                print("CROSSREF IMPORT ERROR: {}".format(e))
                #raise e
            if i % batchsize == 0:
                self.accept_editgroup(eg)
                eg = self.new_editgroup()
        if i % batchsize != 0:
            self.accept_editgroup(eg)
        print("done!")

    def import_crossref_dict(self, meta, editgroup=None,
            create_containers=False):

        # creators
        creators = []
        for am in meta['author']:
            c = dict(name="{} {}".format(am['given'], am['family']),
                     sortname="{}, {}".format(am['family'], am['given']),
                     orcid=None)
            creators.append(c)

        # container
        issn = meta.get('ISSN', [None])[0]
        container_id = self.lookup_issn(issn)
        container = dict(
            issn=issn,
            name=meta['container-title'][0],
            container_id=container_id,
            #sortname=meta['short-container-title'][0])
            publisher=meta['publisher'])

        if container_id is None and create_containers and issn != None:
            rv = self.post('/v0/container', data=dict(
                issn=container['issn'],
                publisher=container['publisher']))
            assert rv.status_code in [200, 201]
            container_id = rv.json().get('ident', rv.json().get('id'))
            print("created container: {}".format(issn))
            container['ident'] = container_id
            self._issn_map[issn] = container_id

        # references
        refs = []
        for i, rm in enumerate(meta.get('reference', [])):
            ref = dict(
                doi=rm.get("DOI", None),
                index=i+1,
                # TODO: how to generate a proper stub here from k/v metadata?
                stub="| ".join(rm.values()))
            refs.append(ref)

        # work and release
        title = meta['title'][0]
        rv = self.post('/v0/work',
            data=dict(title=title, editgroup_id=editgroup)) #work_type="book"
        assert rv.status_code in [200, 201]
        #print(rv.json())
        work_id = rv.json().get('ident', rv.json().get('id'))

        extra = dict(crossref={
            'links': meta.get('link', []),
            'subject': meta.get('subject'),
            'type': meta['type'],
            'alternative-id': meta.get('alternative-id', [])})

        rv = self.post('/v0/release', data=dict(
            title=title,
            work_id=work_id,
            # XXX: creators=creators,
            # XXX: refs=refs,
            # XXX: container=container_id,
            release_type=meta['type'],
            doi=meta['DOI'],
            date=meta['created']['date-time'],
            license=meta.get('license', [dict(URL=None)])[0]['URL'] or None,
            issue=meta.get('issue', None),
            volume=meta.get('volume', None),
            pages=meta.get('page', None),
            editgroup_id=editgroup,
            extra=extra))
        assert rv.status_code in [200, 201]
        release_id = rv.json().get('ident', rv.json().get('id'))

    def import_issn_file(self, json_file, create_containers=False, batchsize=100):
        eg = self.new_editgroup()
        i = 0
        with open(json_file, 'r') as file:
            for line in file:
                if i % batchsize == 0:
                    sys.stdout.write('\n{}: '.format(i))
                if (i+1) % 20 == 0:
                    sys.stdout.write('.')
                i = i + 1
                obj = json.loads(line)
                if not ("author" in obj and "title" in obj):
                    continue
                try:
                    self.import_crossref_dict(obj, editgroup=eg,
                        create_containers=create_containers)
                except Exception as e:
                    print("ERROR: {}".format(e))
                if i % batchsize == 0:
                    self.accept_editgroup(eg)
                    eg = self.new_editgroup()
        if i % batchsize != 0:
            self.accept_editgroup(eg)
        print("done!")

    def health(self):
        rv = self.get("/health")
        assert rv.status_code == 200
        return rv.json()