-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathwrite_hte.py
212 lines (186 loc) · 6.99 KB
/
write_hte.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
import argparse, os, json
import s3fs
import requests
from datacite import schema43, DataCiteRESTClient
from caltechdata_api import caltechdata_write, caltechdata_edit
from tqdm import tqdm
folder = "0_gregoire"
endpoint = "https://renc.osn.xsede.org/"
# Get metadata and files from bucket
s3 = s3fs.S3FileSystem(anon=True, client_kwargs={"endpoint_url": endpoint})
# Set up datacite client
password = os.environ["DATACITE"]
prefix = "10.25989"
datacite = DataCiteRESTClient(username="CALTECH.HTE", password=password, prefix=prefix)
path = "ini210004tommorrell/" + folder + "/"
dirs = s3.ls(path)
# Strip out reference to top level directory
repeat = dirs.pop(0)
assert repeat == path
# Switch directories to doi
records = []
for record in dirs:
body = record.split("0_gregoire/")[1]
records.append(f"{prefix}/{body}")
with open("new_ids.json", "r") as infile:
record_ids = json.load(infile)
# We are using the list of unregistered dois
# with open("unregistered_dois.json", "r") as infile:
# data = json.load(infile)
# records = data["pub"]
abstract = """This record is a component of the Materials Experiment and
Analysis Database (MEAD). It contains raw data and metadata from millions
of materials synthesis and characterization experiments, as well as the
analysis and distillation of that data into property and performance
metrics. The unprecedented quantity and diversity of experimental data
are searchable by experiment and analysis attributes generated by both
researchers and data processing software.
"""
with open("completed_dois.json", "r") as infile:
completed = json.load(infile)
for doi in completed:
if doi in records:
records.remove(doi)
else:
print(doi)
with open("excluded_dois.json", "r") as infile:
excluded = json.load(infile)
for doi in excluded:
records.remove(doi)
for record in tqdm(records):
base = record.split("/")[1]
meta_path = path + base + "/metadata.json"
metadata = None
files = s3.ls(path + base)
if len(files) == 0:
excluded.append(record)
print(f"No files available {record}")
with open("excluded_dois.json", "w") as outfile:
data = json.dump(excluded, outfile)
else:
try:
metaf = s3.open(meta_path, "rb")
metadata = json.load(metaf)
except:
print(files)
excluded.append(record)
print(f"Missing metadata {record}")
exit()
with open("excluded_dois.json", "w") as outfile:
data = json.dump(excluded, outfile)
if metadata:
metadata["identifiers"] = [{"identifier": record, "identifierType": "DOI"}]
# Find the zip file or files
zipf = s3.glob(path + base + "/*.zip")
file_links = []
description_string = f"Files available via S3 at {endpoint}{path}<br>"
for link in zipf:
fname = link.split("/")[-1]
file_links.append(endpoint + link)
metadata["types"] = {"resourceType": "", "resourceTypeGeneral": "Dataset"}
metadata["schemaVersion"] = "http://datacite.org/schema/kernel-4"
metadata["publicationYear"] = str(metadata["publicationYear"])
metadata["rightsList"] = [
{
"rights": "cc-by-sa-4.0",
"rightsUri": "http://creativecommons.org/licenses/by-sa/4.0/",
}
]
static = [
{
"relatedIdentifier": "10.25989/es8t-kswe",
"relationType": "IsPartOf",
"relatedIdentifierType": "DOI",
},
{
"relatedIdentifier": "10.1038/s41524-019-0216-x",
"relationType": "IsDocumentedBy",
"relatedIdentifierType": "DOI",
},
]
if "relatedIdentifiers" in metadata:
metadata["relatedIdentifiers"] += static
else:
metadata["relatedIdentifiers"] = static
metadata["fundingReferences"] = [
{
"funderName": "Office of Science of the U.S. Department of Energy",
"awardTitle": "Energy Innovation Hub Renewal - Fuels from Sunlight",
"awardNumber": "DE-SC0004993",
}
]
if "descriptions" not in metadata:
metadata["descriptions"] = [
{"description": abstract, "descriptionType": "Abstract"}
]
else:
print(metadata["descriptions"])
exit()
for meta in metadata.copy():
if metadata[meta] == []:
metadata.pop(meta)
for contributor in metadata["contributors"]:
if contributor["affiliation"] == []:
contributor.pop("affiliation")
new_cre = []
for creator in metadata["creators"]:
if creator["affiliation"] == []:
creator.pop("affiliation")
if creator["name"] != "Contributors":
new_cre.append(creator)
metadata["creators"] = new_cre
doi = metadata["doi"].lower()
unnecessary = [
"id",
"doi",
"container",
"providerId",
"clientId",
"agency",
"state",
]
for un in unnecessary:
if un in metadata:
metadata.pop(un)
if "dates" in metadata:
for d in metadata["dates"]:
d["date"] = str(d["date"])
valid = schema43.validate(metadata)
if not valid:
v = schema43.validator.validate(metadata)
errors = sorted(v.iter_errors(instance), key=lambda e: e.path)
for error in errors:
print(error.message)
exit()
metadata.pop("language")
community = "d0de1569-0a01-498f-b6bd-4bc75d54012f"
production = True
# We're now doing new records, so redirects are not needed
# result = requests.get(f'https://api.datacite.org/dois/{doi}')
# if result.status_code != 200:
# print('DATACITE Failed')
# print(result.text)
# exit()
# url = result.json()['data']['attributes']['url']
# old_id = url.split('data.caltech.edu/records/')[1]
new_id = caltechdata_write(
metadata,
schema="43",
publish=True,
production=True,
file_links=file_links,
s3=s3,
community=community,
)
url = f"https://data.caltech.edu/records/{new_id}"
# record_ids[old_id] = new_id
# with open("new_ids.json", "w") as outfile:
# json.dump(record_ids, outfile)
result = requests.get(f"https://api.datacite.org/dois/{doi}")
if result.status_code != 200:
doi = datacite.public_doi(doi=record, metadata=metadata, url=url)
else:
doi = datacite.update_doi(doi=record, metadata=metadata, url=url)["doi"]
completed.append(doi)
with open("completed_dois.json", "w") as outfile:
data = json.dump(completed, outfile)