-
Notifications
You must be signed in to change notification settings - Fork 2
/
datacite.py
executable file
·271 lines (220 loc) · 8.23 KB
/
datacite.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
import pandas, requests, requests_cache, os, html, base64, xmltodict
from pandas import ExcelWriter
requests_cache.install_cache('datacite_api_cache')
input_filename = 'output.xlsx'
output_filename = 'output_datasets.xlsx'
export_dir = 'datasets_html'
def write_field_header_as_html(file, name):
file.write('<b style="color:grey;">')
file.write(html.escape(name))
file.write('</b>')
file.write('<br>')
def write_field_as_html_input(file, value, rows):
file.write('<textarea rows="{}" cols="120" readonly onclick="this.focus();this.select()">'.format(rows))
if value is not None:
file.write(html.escape(str(value)))
file.write('</textarea>')
file.write('<br>')
file.write('<br>')
def write_field_as_html_input_single(file, metadata, name, rows):
if (name in metadata.keys()):
write_field_as_html_input(file, metadata[name], rows)
def render(doi, metadata, publications):
prefix_start = doi.find('10.')
prefix_end = doi.find('/', prefix_start)
prefix = doi[prefix_start:prefix_end]
short_doi = doi[prefix_start:]
if not os.path.exists(export_dir):
os.mkdir(export_dir)
dir_path = os.path.join(export_dir, prefix)
if not os.path.exists(dir_path):
os.mkdir(dir_path)
file_path = os.path.join(dir_path, short_doi.replace('/','-') + '.html')
xml_text = base64.b64decode(metadata['xml'])
xml_dict = xmltodict.parse(xml_text)
if 'resource' in xml_dict.keys():
xml_resource = xml_dict['resource']
else:
xml_resource = xml_dict['default:resource']
print('\tXML Error - default:resource')
return
file = open(file_path, 'w', encoding='utf-8')
file.write('<html><head>')
file.write('<meta charset="UTF-8">')
file.write('<title>Metadata for {}</title>'.format(short_doi))
file.write('</head><body>')
file.write('<h1>')
file.write('<a href="https://doi.org/{}" target="_blank">'.format(short_doi))
file.write(short_doi)
file.write('</a>')
file.write('</h1>')
file.write('<h3>Title</h3>')
write_field_as_html_input_single(file, metadata, 'title', 2)
file.write('<h3>Description</h3>')
write_field_as_html_input_single(file, metadata, 'description', 10)
file.write('<h3>Date of data production</h3>')
write_field_as_html_input_single(file, metadata, 'published', 2)
creators = []
if len(metadata['author']) == 1:
creators.append(xml_resource['creators']['creator'])
else:
for creator in xml_resource['creators']['creator']:
creators.append(creator)
file.write('<h3>People - creators ({})</h3>'.format(len(creators)))
for creator in creators:
orcid = None
affiliation = None
if 'affiliation' in creator:
if isinstance(creator['affiliation'], list):
affiliation = '; '.join(creator['affiliation'])
else:
affiliation = creator['affiliation']
if 'nameIdentifier' in creator:
if isinstance(creator['nameIdentifier'], list):
for identifier in creator['nameIdentifier']:
if identifier['@nameIdentifierScheme'] == 'ORCID':
orcid = identifier['#text']
else:
identifier = creator['nameIdentifier']
if identifier['@nameIdentifierScheme'] == 'ORCID':
orcid = identifier['#text']
if isinstance(creator['creatorName'], str):
creatorText = creator['creatorName']
else:
creatorText = creator['creatorName']['#text']
if affiliation is not None:
creatorText += '\nAffiliation: ' + str(affiliation)
if orcid is not None:
creatorText += '\nORCID: ' + orcid
write_field_as_html_input(file, creatorText, 3)
contributors = []
if 'contributors' in xml_resource.keys() and xml_resource['contributors'] is not None:
if isinstance(xml_resource['contributors']['contributor'], list):
for contributor in xml_resource['contributors']['contributor']:
contributors.append(contributor)
else:
contributors.append(xml_resource['contributors']['contributor'])
if (len(contributors) > 0):
file.write('<h3>People - contributors ({})</h3>'.format(len(contributors)))
for contributor in contributors:
orcid = None
affiliation = None
if 'affiliation' in contributor:
if isinstance(contributor['affiliation'], list):
affiliation = '; '.join(contributor['affiliation'])
else:
affiliation = contributor['affiliation']
if 'nameIdentifier' in contributor:
if isinstance(contributor['nameIdentifier'], list):
for identifier in contributor['nameIdentifier']:
if identifier['@nameIdentifierScheme'] == 'ORCID':
orcid = identifier['#text']
else:
identifier = contributor['nameIdentifier']
if identifier['@nameIdentifierScheme'] == 'ORCID':
orcid = identifier['#text']
if isinstance(contributor['contributorName'], str):
contributorText = contributor['contributorName']
else:
contributorText = contributor['contributorName']['#text']
if affiliation is not None:
contributorText += '\nAffiliation: ' + affiliation
if orcid is not None:
contributorText += '\nORCID: ' + orcid
write_field_as_html_input(file, contributorText, 3)
file.write('<h3>Publisher</h3>')
if ('publisher' in xml_resource.keys()):
write_field_as_html_input_single(file, xml_resource, 'publisher', 2)
file.write('<h3>DOI</h3>')
write_field_as_html_input(file, doi, 2)
file.write('<h3>Related publications ({})</h3>'.format(len(publications)))
for publication in publications.keys():
write_field_as_html_input(file, publication, 2)
file.write('</body></html>')
file.close()
def get_datacite_metadata(doi):
prefix_start = doi.find('10.')
url = 'https://api.datacite.org/works/' + doi[prefix_start:]
print(url)
r = requests.get(url)
return r.json()
# Get input DOIs from excel file
df = pandas.read_excel(input_filename)
df = df.where(pandas.notnull(df), None)
data = df.to_dict()
records = []
filtered_records = []
for index in data['doi']:
doi = data['doi'][index]
dataset_title = data['dataset_title'][index]
dataset_doi = data['dataset_doi'][index]
records.append({'doi': doi, 'dataset_title': dataset_title, 'dataset_doi': dataset_doi})
prefixes = {}
publications_for_dataset = {}
dataset_dois = []
for record in records:
publication_doi = record['doi']
dataset_doi = record['dataset_doi']
prefix_start = dataset_doi.find('10.')
prefix_end = dataset_doi.find('/', prefix_start)
prefix = dataset_doi[prefix_start:prefix_end]
skip = False
# De-duplicate
if not skip:
for filtered_record in filtered_records:
if filtered_record['doi'] == record['doi'] and filtered_record['dataset_doi'] == record['dataset_doi']:
skip = True
break
if not skip:
filtered_records.append(record)
dataset_dois.append(record['dataset_doi'])
if prefix in prefixes:
prefixes[prefix] += 1
else:
prefixes[prefix] = 1
if record['dataset_doi'] not in publications_for_dataset:
publications_for_dataset[record['dataset_doi']] = {}
publications_for_dataset[record['dataset_doi']][record['doi']] = True
print('')
unique_dataset_dois = list(set(dataset_dois))
print('{0} unique dataset DOIs ({1} total)'.format(len(unique_dataset_dois), len(dataset_dois)))
print('')
for prefix in sorted(prefixes, key=prefixes.get, reverse=True):
print(prefix, prefixes[prefix])
print('')
final_dataset_dois = []
for dataset_doi in unique_dataset_dois:
result = get_datacite_metadata(dataset_doi)
print('')
if ('errors' in result):
print('\tError ' + result['errors'][0]['status'])
else:
attributes = result['data']['attributes']
title = attributes['title']
description = attributes['description']
published = attributes['published']
authors = attributes['author']
print('\ttitle:', title)
print('\tpublished:', published)
print('\tauthors:', len(authors))
if (len(authors) == 0):
print(dataset_doi)
publications = publications_for_dataset[dataset_doi]
if title is not None:
render(dataset_doi, attributes, publications)
final_dataset_doi = {}
final_dataset_doi['doi'] = dataset_doi
final_dataset_doi['title'] = title
prefix_start = dataset_doi.find('10.')
prefix_end = dataset_doi.find('/', prefix_start)
prefix = dataset_doi[prefix_start:prefix_end]
final_dataset_doi['prefix'] = prefix
final_dataset_dois.append(final_dataset_doi)
print('')
# Create the output file
print('Writing output file "{0}"'.format(output_filename))
writer = ExcelWriter(output_filename)
summary_df = pandas.DataFrame(final_dataset_dois)
summary_df.to_excel(writer, 'DOI List ({0})'.format(len(final_dataset_dois)), columns=['prefix', 'doi', 'title'])
writer.save()
print('')