-
Notifications
You must be signed in to change notification settings - Fork 0
/
exporter.py
345 lines (316 loc) · 12.8 KB
/
exporter.py
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
import requests
import os
from requests.auth import HTTPBasicAuth
import vcr
from vcr.record_mode import RecordMode
import csv
NAME = os.environ.get('NAME')
XRELEASE_ID = os.environ.get('XRELEASE_ID')
COL_API = os.environ.get('COL_API')
if COL_API is None or COL_API == '':
COL_API = 'https://api.checklistbank.org'
COL_USER = os.environ.get('COL_USER')
COL_PASS = os.environ.get('COL_PASS')
TAXON_ID = os.environ.get('TAXON_ID')
def login():
print('\nAuthenticating')
login_url = COL_API + '/user/login'
r = requests.get(login_url, auth=HTTPBasicAuth(COL_USER, COL_PASS))
r.raise_for_status()
bearer = r.text
headers = {'Authorization': 'Bearer ' + bearer, 'Accept': '*/*'}
return headers
def crawl(headers):
print('\nCrawling merged name usages')
search_url = COL_API + '/dataset/' + XRELEASE_ID + '/nameusage/search'
params = {
'TAXON_ID': TAXON_ID,
'facet': ['rank', 'issue', 'status', 'nomStatus', 'nomCode', 'nameType', 'field', 'authorship', 'authorshipYear',
'extinct', 'environment', 'origin', 'sectorMode', 'secondarySourceGroup', 'sectorDatasetKey', 'group'],
'limit': 1000,
'offset': 0,
'sectorMode': 'merge',
'sortBy': 'taxonomic'
}
total = float('inf')
results = []
i = 0
while params['offset'] < total:
with vcr.use_cassette(f'raw/vcr_cassettes/{NAME}_{XRELEASE_ID}_{TAXON_ID}/nameusages/{params["offset"]}.yaml',
filter_headers=['authorization'], record_mode=RecordMode.NEW_EPISODES):
r = requests.get(search_url, headers=headers, params=params)
r.raise_for_status()
if 'result' in r.json():
results += r.json()['result']
params['offset'] += params['limit']
total = r.json()['total']
if i % params['limit'] == 0:
print(f"{i} of {total}")
i += params['limit']
if len(results) != total:
exit('Error: only ' + str(len(results)) + ' of ' + str(total) + ' results were returned')
return results
def format_classification(classification):
output = {
'kingdom': '',
'phylum': '',
'subphylum': '',
'class': '',
'order': '',
'suborder': '',
'infraorder': '',
'parvorder': '',
'superfamily': '',
'family': '',
'subfamily': '',
'tribe': '',
'subtribe': '',
'genus': '',
'subgenus': '',
'species': '',
'subspecies': '',
'infraspecies': '',
'form': '',
'variety': '',
'aberration': '',
'other': ''
}
for row in classification:
output[row['rank']] = row['name']
# unranked causes problems because barcodes use unranked as rank and Biota uses rank unranked
output.pop('unranked', None)
return output
def get_datasets(results, headers):
dataset_ids = []
for row in results:
dataset_id = row['sectorDatasetKey']
if dataset_id not in dataset_ids:
dataset_ids.append(dataset_id)
dataset_ids = list(set(dataset_ids))
print('\nCrawling dataset metadata')
datasets = {}
i = 0
for dataset_id in dataset_ids:
if i % 10 == 0:
print(f"{i} of {len(dataset_ids)}")
with vcr.use_cassette(f'raw/vcr_cassettes/{NAME}_{XRELEASE_ID}_{TAXON_ID}/datasets/{dataset_id}.yaml',
filter_headers=['authorization'], record_mode=RecordMode.NEW_EPISODES):
dataset_url = COL_API + '/dataset/' + str(dataset_id)
r = requests.get(dataset_url, headers=headers)
r.raise_for_status()
datasets[dataset_id] = r.json()
i += 1
return datasets
def format_people(people):
output = []
for person in people:
output.append(person['name'])
return '; '.join(output)
def write_datasets(datasets):
print('\nWriting dataset output')
tsv_file = f'output/{NAME}_{XRELEASE_ID}_{TAXON_ID}_datasets.tsv'
headers = [
'dataset_id',
'alias',
'title',
'issued',
'version',
'description',
'contact',
'creator',
'editor',
'publisher',
'contributor',
'doi',
'license',
'geographic_scope',
'temporal_scope',
'taxonomic_scope',
'confidence',
'completeness',
'logo',
'created',
'modified',
'type',
'origin'
]
with open(tsv_file, 'w', newline='') as f:
writer = csv.writer(f, delimiter='\t', quotechar='"', quoting=csv.QUOTE_MINIMAL, escapechar='\\')
writer.writerow(headers)
for dataset_id, dataset in datasets.items():
output = {}
output['dataset_id'] = dataset_id
output['alias'] = dataset.get('alias', '')
output['title'] = dataset.get('title', '')
output['issued'] = dataset.get('issued', '')
output['version'] = dataset.get('version', '')
output['description'] = dataset.get('description', '')
contact = dataset.get('contact', '')
output['contact'] = contact.get('name', '')
output['creator'] = format_people(dataset.get('creator', []))
output['editor'] = format_people(dataset.get('editor', []))
publisher = dataset.get('publisher', {'name': ''})
output['publisher'] = publisher.get('name', '')
output['contributor'] = format_people(dataset.get('contributor', []))
output['doi'] = dataset.get('doi', '')
output['license'] = dataset.get('license', '')
output['geographic_scope'] = dataset.get('geographicScope', '')
output['temporal_scope'] = dataset.get('temporalScope', '')
output['taxonomic_scope'] = dataset.get('taxonomicScope', '')
output['confidence'] = dataset.get('confidence', '')
output['completeness'] = dataset.get('completeness', '')
output['logo'] = dataset.get('logo', '')
output['created'] = dataset.get('created', '')
output['modified'] = dataset.get('modified', '')
output['type'] = dataset.get('type', '')
output['origin'] = dataset.get('origin', '')
writer.writerow(output.values())
def write_tsv(results, datasets):
print('\nWriting name usage output')
tsv_file = f'output/{NAME}_{XRELEASE_ID}_{TAXON_ID}.tsv'
reference_ids = []
headers = [
'kingdom',
'phylum',
'subphylum',
'class',
'order',
'suborder',
'infraorder',
'parvorder',
'superfamily',
'family',
'subfamily',
'tribe',
'subtribe',
'genus',
'subgenus',
'species',
'subspecies',
'infraspecies',
'form',
'variety',
'aberration',
'other',
'dataset_id',
'dataset_alias',
'parent_id',
'taxon_id',
'name_id',
'rank',
'accepted_id',
'accepted_name',
'accepted_author',
'scientific_name',
'authorship',
'authors',
'year',
'status',
'extinct',
'temporal_range_start',
'temporal_range_end',
'link',
'reference_id',
'identifiers'
]
with open(tsv_file, 'w', newline='') as f:
writer = csv.writer(f, delimiter='\t', quotechar='"', quoting=csv.QUOTE_MINIMAL, escapechar='\\')
writer.writerow(headers)
for row in results:
sector_dataset_id = ''
if 'sectorDatasetKey' in row:
sector_dataset_id = row['sectorDatasetKey']
if 'alias' in datasets[sector_dataset_id]:
sector_dataset = datasets[sector_dataset_id]['alias']
else:
sector_dataset = datasets[sector_dataset_id]['title']
status = row['usage']['status']
accepted_id = ''
accepted_name = ''
accepted_author = ''
if status == 'synonym':
accepted_id = row['usage']['accepted']['id']
accepted_name = row['usage']['accepted']['name']['scientificName']
if '†' in row['usage']['accepted']['label']:
accepted_name = '†' + accepted_name
accepted_author = row['usage']['accepted']['name'].get('authorship', '')
output = format_classification(row['classification'])
output['sector_dataset_id'] = sector_dataset_id
output['sector_dataset_alias'] = sector_dataset
output['parent_id'] = row['usage']['parentId']
output['taxon_id'] = row['usage']['id']
output['name_id'] = row['usage']['name']['id']
output['rank'] = row['usage']['name']['rank']
output['accepted_id'] = accepted_id
output['accepted_name'] = accepted_name
output['accepted_author'] = accepted_author
output['scientific_name'] = row['usage']['name']['scientificName']
output['authorship'] = row['usage']['name'].get('authorship', '')
combinationAuthorship = row['usage']['name'].get('combinationAuthorship', {})
output['authors'] = '|'.join(combinationAuthorship.get('authors', ''))
output['year'] = combinationAuthorship.get('year', '')
output['status'] = status
output['extinct'] = row['usage'].get('extinct', '')
output['temporal_range_start'] = row['usage'].get('temporalRangeStart', '')
output['temporal_range_end'] = row['usage'].get('temporalRangeEnd', '')
output['link'] = row['usage'].get('link', '')
referenceIds = row['usage'].get('referenceIds', [])
output['reference_id'] = '|'.join(referenceIds)
output['identifiers'] = '|'.join(row['usage']['name'].get('identifier', ''))
reference_ids.extend([ref_id for ref_id in referenceIds if ref_id not in reference_ids])
writer.writerow(output.values())
return reference_ids
def crawl_references(references_ids, headers):
print('\nCrawling references')
i = 0
results = []
for ref_id in references_ids:
if i % 10 == 0:
print(f"{i} of {len(references_ids)}")
with vcr.use_cassette(f'raw/vcr_cassettes/{NAME}_{XRELEASE_ID}_{TAXON_ID}/references/{ref_id}.yaml',
filter_headers=['authorization'], record_mode=RecordMode.NEW_EPISODES):
ref_url = COL_API + '/dataset/' + XRELEASE_ID +'/reference/' + ref_id
r = requests.get(ref_url, headers=headers)
r.raise_for_status()
results.append(r.json())
i += 1
return results
def write_references(results):
print('\nWriting references output')
tsv_file = f'output/{NAME}_{XRELEASE_ID}_{TAXON_ID}_references.tsv'
headers = ['reference_id', 'source_id', 'type', 'authors', 'year',
'title', 'citation', 'journal', 'volume', 'page']
with open(tsv_file, 'w', newline='') as f:
writer = csv.writer(f, delimiter='\t', quotechar='"', quoting=csv.QUOTE_MINIMAL, escapechar='\\')
writer.writerow(headers)
for row in results:
output = {}
output['reference_id'] = row['id']
csl = row.get('csl', {})
output['source_id'] = csl.get('id', '')
output['type'] = csl.get('type', '')
output['authors'] = csl.get('author', '')
output['year'] = row.get('year', '')
output['title'] = csl.get('title', '')
output['citation'] = row.get('citation', '')
output['journal'] = csl.get('container-title', '')
output['volume'] = csl.get('volume', '')
output['page'] = csl.get('page', '')
writer.writerow(output.values())
def import_tsv_to_sqlite():
print('\nImporting TSV files to SQLite')
os.system(f'sqlite3 output/{NAME}_{XRELEASE_ID}_{TAXON_ID}.sqlite < schema.sql')
os.system(f'sqlite3 output/{NAME}_{XRELEASE_ID}_{TAXON_ID}.sqlite ".mode tabs" ".import --skip 1 output/{NAME}_{XRELEASE_ID}_{TAXON_ID}.tsv nameusage"')
os.system(f'sqlite3 output/{NAME}_{XRELEASE_ID}_{TAXON_ID}.sqlite ".mode tabs" ".import --skip 1 output/{NAME}_{XRELEASE_ID}_{TAXON_ID}_references.tsv reference"')
os.system(f'sqlite3 output/{NAME}_{XRELEASE_ID}_{TAXON_ID}.sqlite ".mode tabs" ".import --skip 1 output/{NAME}_{XRELEASE_ID}_{TAXON_ID}_datasets.tsv dataset"')
def main():
headers = login()
results = crawl(headers=headers)
datasets = get_datasets(results=results, headers=headers)
write_datasets(datasets=datasets)
reference_ids = write_tsv(results=results, datasets=datasets)
references = crawl_references(references_ids=reference_ids, headers=headers)
write_references(references)
import_tsv_to_sqlite()
if __name__ == '__main__':
main()