-
Notifications
You must be signed in to change notification settings - Fork 13
/
schema_transformations.py
752 lines (615 loc) · 33.9 KB
/
schema_transformations.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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
"""JSON schema transformation functions."""
__copyright__ = 'Copyright (c) 2019-2024, Utrecht University'
__license__ = 'GPLv3, see LICENSE'
import re
from typing import Callable, Dict
from schema_transformations_utils import correctify_isni, correctify_orcid, correctify_researcher_id, correctify_scopus
import meta
from util import *
# No rules are exported by this module.
__all__ = []
# Transformation functions {{{
# Naming scheme: _FROMSCHEMA_TOSCHEMA
#
# A transformation function takes a JSON object (OrderedDict) as an argument,
# and returns a new JSON object.
#
# The docstring of a transformation function should describe the transformation
# in a human-readable manner: it is provided to the user executing the transformation.
def _default0_default1(ctx: rule.Context, m: Dict) -> Dict:
"""
A Data type field is added to be used for publication purposes to DataCite.
This makes it possible to specify the type of data that is being published.
The default data type is Dataset.
The version number for the data package is no longer required.
Furthermore, the metadata schema is extended with a remarks field.
These remarks are intended for communication between researchers and datamanager.
Finally, the creator and contributor name fields have been split into first
and last names, to comply with the OpenAIRE standard.
:param ctx: Combined type of a callback and rei struct
:param m: Metadata to transform (default-0)
:returns: Transformed (default-1) JSON object
"""
def fixup_name(n: str) -> Dict:
"""Split a name into a first and last name, error-prone, but acceptable."""
n.strip() # Trim whitespace, if any.
# Name contains comma? Parse as: last, first, first, first.
ns = re.split(r'\s*,\s*', n, 1)
if len(ns) == 2:
return {'Given_Name': ns[1], 'Family_Name': ns[0]}
# Name contains whitespace? Parse as: first last last last.
ns = re.split(r'\s+', n, 1)
if len(ns) == 2:
return {'Given_Name': ns[0], 'Family_Name': ns[1]}
# Neither? Parse as lastname.
return {'Given_Name': '', 'Family_Name': n}
for person in m['Creator']:
if 'Name' in person:
person['Name'] = fixup_name(person['Name'])
if m.get('Contributor', False):
for person in m['Contributor']:
if 'Name' in person:
person['Name'] = fixup_name(person['Name'])
meta.metadata_set_schema_id(m, 'https://yoda.uu.nl/schemas/default-1/metadata.json')
return m
def _default1_default2(ctx: rule.Context, m: Dict) -> Dict:
"""
Metadata fields Discipline, Language and Tags have become required fields.
This to enable datapackages to be filtered and found more easily.
If not present yet Language is defaulted to 'en - English'
If not present yet a default Tag will be added containing 'yoda'
Discipline must be present in all vault packages before migration.
I.e. discipline must be manually added if not present yet.
This requires an intervention by the responsible datamanager beforehand
:param ctx: Combined type of a callback and rei struct
:param m: Metadata to transform (default-1)
:returns: Transformed (default-2) JSON object
"""
# Only add default value when Language not yet present
if not m.get('Language', False) or m['Language'] == "":
m['Language'] = 'en - English'
# Only add default value when Tag not yet present or present as a list with an empty string
if not m.get('Tag', False) or m['Tag'] == [""]:
m['Tag'] = ['yoda']
meta.metadata_set_schema_id(m, 'https://yoda.uu.nl/schemas/default-2/metadata.json')
return m
def _default2_default3(ctx: rule.Context, m: Dict) -> Dict:
"""
Add affiliation identifiers to creators and contributors.
Tags are renamed to Keywords, Related Datapackage renamed to Related Resource and improved Affiliation and Person Identifiers.
:param ctx: Combined type of a callback and rei struct
:param m: Metadata to transform (default-2)
:returns: Transformed (default-3) JSON object
"""
if m.get('Creator', False):
# For this creator step through all its affiliations
for creator in m['Creator']:
affiliations = []
for affiliation in creator['Affiliation']:
affiliations.append({"Affiliation_Name": affiliation, "Affiliation_Identifier": ""})
creator['Affiliation'] = affiliations
person_identifiers = []
for person_identifier in creator.get('Person_Identifier', []):
# Check ORCID
if person_identifier.get('Name_Identifier_Scheme', None) == 'ORCID':
# Check for incorrect ORCID format.
if not re.search("^(https://orcid.org/)[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{3}[0-9X]$", person_identifier.get('Name_Identifier', None)):
corrected_orcid = correctify_orcid(person_identifier['Name_Identifier'])
# Only if an actual correction took place change the value and mark this data as 'changed'.
if corrected_orcid is None:
log.write(ctx, "Warning: could not correct ORCID %s during schema transformation. It needs to be fixed manually."
% (person_identifier['Name_Identifier']))
elif corrected_orcid != person_identifier['Name_Identifier']:
person_identifier['Name_Identifier'] = corrected_orcid
# Check Scopus
elif person_identifier.get('Name_Identifier_Scheme', None) == 'Author identifier (Scopus)':
# Check for incorrect Scopus format.
if not re.search(r"^\d{1,11}$", person_identifier.get('Name_Identifier', None)):
corrected_scopus = correctify_scopus(person_identifier['Name_Identifier'])
# Only if an actual correction took place change the value and mark this data as 'changed'.
if corrected_scopus is None:
log.write(ctx, "Warning: could not correct Scopus %s during schema transformation. It needs to be fixed manually."
% (person_identifier['Name_Identifier']))
elif corrected_scopus != person_identifier['Name_Identifier']:
person_identifier['Name_Identifier'] = corrected_scopus
# Check ISNI
elif person_identifier.get('Name_Identifier_Scheme', None) == 'ISNI':
# Check for incorrect ISNI format.
if not re.search("^(https://isni.org/isni/)[0-9]{15}[0-9X]$", person_identifier.get('Name_Identifier', None)):
corrected_isni = correctify_isni(person_identifier['Name_Identifier'])
# Only if an actual correction took place change the value and mark this data as 'changed'.
if corrected_isni is None:
log.write(ctx, "Warning: could not correct ISNI %s during schema transformation. It needs to be fixed manually."
% (person_identifier['Name_Identifier']))
elif corrected_isni != person_identifier['Name_Identifier']:
person_identifier['Name_Identifier'] = corrected_isni
elif person_identifier.get('Name_Identifier_Scheme', None) == 'ResearcherID (Web of Science)':
# Check for incorrect ResearcherID format.
if not re.search("^(https://www.researcherid.com/rid/)[A-Z]-[0-9]{4}-[0-9]{4}$", person_identifier.get('Name_Identifier', None)):
corrected_researcher_id = correctify_researcher_id(person_identifier['Name_Identifier'])
# Only if an actual correction took place change the value and mark this data as 'changed'.
if corrected_researcher_id != person_identifier['Name_Identifier']:
person_identifier['Name_Identifier'] = corrected_researcher_id
elif 'Name_Identifier_Scheme' not in person_identifier:
continue
person_identifiers.append({"Name_Identifier_Scheme": person_identifier['Name_Identifier_Scheme'], "Name_Identifier": person_identifier['Name_Identifier']})
if len(person_identifiers) > 0:
creator['Person_Identifier'] = person_identifiers
if m.get('Contributor', False):
# For this contributor step through all its affiliations
for contributor in m['Contributor']:
affiliations = []
if contributor.get('Affiliation', False):
for affiliation in contributor['Affiliation']:
affiliations.append({"Affiliation_Name": affiliation, "Affiliation_Identifier": ""})
contributor['Affiliation'] = affiliations
person_identifiers = []
for person_identifier in contributor.get('Person_Identifier', []):
# Check ORCID
if person_identifier.get('Name_Identifier_Scheme', None) == 'ORCID':
# Check for incorrect ORCID format.
if not re.search("^(https://orcid.org/)[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{3}[0-9X]$", person_identifier.get('Name_Identifier', None)):
corrected_orcid = correctify_orcid(person_identifier['Name_Identifier'])
# Only if an actual correction took place change the value and mark this data as 'changed'.
if corrected_orcid is None:
log.write(ctx, "Warning: could not correct ORCID %s during schema transformation. It needs to be fixed manually."
% (person_identifier['Name_Identifier']))
elif corrected_orcid != person_identifier['Name_Identifier']:
person_identifier['Name_Identifier'] = corrected_orcid
# Check Scopus
elif person_identifier.get('Name_Identifier_Scheme', None) == 'Author identifier (Scopus)':
# Check for incorrect Scopus format.
if not re.search(r"^\d{1,11}$", person_identifier.get('Name_Identifier', None)):
corrected_scopus = correctify_scopus(person_identifier['Name_Identifier'])
# Only if an actual correction took place change the value and mark this data as 'changed'.
if corrected_scopus is None:
log.write(ctx, "Warning: could not correct Scopus %s during schema transformation. It needs to be fixed manually."
% (person_identifier['Name_Identifier']))
elif corrected_scopus != person_identifier['Name_Identifier']:
person_identifier['Name_Identifier'] = corrected_scopus
# Check ISNI
elif person_identifier.get('Name_Identifier_Scheme', None) == 'ISNI':
# Check for incorrect ISNI format.
if not re.search("^(https://isni.org/isni/)[0-9]{15}[0-9X]$", person_identifier.get('Name_Identifier', None)):
corrected_isni = correctify_isni(person_identifier['Name_Identifier'])
# Only if an actual correction took place change the value and mark this data as 'changed'.
if corrected_isni is None:
log.write(ctx, "Warning: could not correct ISNI %s during schema transformation. It needs to be fixed manually."
% (person_identifier['Name_Identifier']))
elif corrected_isni != person_identifier['Name_Identifier']:
person_identifier['Name_Identifier'] = corrected_isni
elif person_identifier.get('Name_Identifier_Scheme', None) == 'ResearcherID (Web of Science)':
# Check for incorrect ResearcherID format.
if not re.search("^(https://www.researcherid.com/rid/)[A-Z]-[0-9]{4}-[0-9]{4}$", person_identifier.get('Name_Identifier', None)):
corrected_researcher_id = correctify_researcher_id(person_identifier['Name_Identifier'])
# Only if an actual correction took place change the value and mark this data as 'changed'.
if corrected_researcher_id != person_identifier['Name_Identifier']:
person_identifier['Name_Identifier'] = corrected_researcher_id
elif 'Name_Identifier_Scheme' not in person_identifier:
continue
person_identifiers.append({"Name_Identifier_Scheme": person_identifier['Name_Identifier_Scheme'], "Name_Identifier": person_identifier['Name_Identifier']})
if len(person_identifiers) > 0:
contributor['Person_Identifier'] = person_identifiers
# Rename Tags to Keywords
if m.get('Tag', False):
keywords = []
for tag in m['Tag']:
keywords.append(tag)
m['Keyword'] = keywords
m.pop('Tag')
# Rename Related_Datapackage to Related_Resource
if m.get('Related_Datapackage', False):
resources = []
for resource in m['Related_Datapackage']:
# Only use the identifier regarding relation type
if resource.get('Relation_Type', False):
resource['Relation_Type'] = resource['Relation_Type'].split(':')[0]
resources.append(resource)
m['Related_Resource'] = resources
m.pop('Related_Datapackage')
# Restricted or closed data packages can't have open license.
data_access_restriction = m.get('Data_Access_Restriction', "")
if data_access_restriction == "Restricted - available upon request" or data_access_restriction == "Closed":
m['License'] = "Custom"
meta.metadata_set_schema_id(m, 'https://yoda.uu.nl/schemas/default-3/metadata.json')
return m
def _core1_core2(ctx: rule.Context, m: Dict) -> Dict:
"""
Add affiliation identifiers to creators.
Tags are renamed to Keywords.
:param ctx: Combined type of a callback and rei struct
:param m: Metadata to transform (core-1)
:returns: Transformed (core-2) JSON object
"""
if m.get('Creator', False):
# For this creator step through all its affiliations
for creator in m['Creator']:
new_affiliations = []
for affiliation in creator['Affiliation']:
new_affiliations.append({"Affiliation_Name": affiliation, "Affiliation_Identifier": ""})
creator['Affiliation'] = new_affiliations
# Rename Tags to Keywords
if m.get('Tag', False):
keywords = []
for tag in m['Tag']:
keywords.append(tag)
m['Keyword'] = keywords
m.pop('Tag')
meta.metadata_set_schema_id(m, 'https://yoda.uu.nl/schemas/core-2/metadata.json')
return m
def _dag0_default2(ctx: rule.Context, m: Dict) -> Dict:
"""
Transform dag-0 data to the default-2 schema definition
:param ctx: Combined type of a callback and rei struct
:param m: Metadata to be transformed (dag-0)
:returns: Transformed (default-2) JSON object
"""
# dag0-research group => def2
if m.get('Research_Group', False):
resrch_grp_2_contrib = {'Name': {'Given_Name': m['Research_Group'], 'Family_Name': ''},
'Affiliation': ['Affiliation'],
'Contributor_Type': 'ResearchGroup'}
if m.get('Contributor', False):
m['Contributor'].append(resrch_grp_2_contrib)
else:
m['Contributor'] = [resrch_grp_2_contrib]
# Finally, get rid of Research_Group element.
m.pop("Research_Group")
# dag0=> def2 collection name
# dag0-GeoLocation => def2-Covered_Geolocation_Place
geo_places = []
for location in m['GeoLocation']:
if 'Description_Spatial' in location:
geo_places.append(location['Description_Spatial'])
if len(geo_places):
m['Covered_Geolocation_Place'] = geo_places
else:
m['Covered_Geolocation_Place'] = [""]
m.pop('GeoLocation')
# dag0-Retention => def2-Retention
# Get the entire metadata schema to be able to get some proper values based on the previous saved values
old_schema = jsonutil.read(ctx, '/{}/yoda/schemas/dag-0/metadata.json'.format(user.zone(ctx)))
retention_years_list = old_schema['definitions']['optionsRetentionPeriod']['enum']
retention_names_list = old_schema['definitions']['optionsRetentionPeriod']['enumNames']
m["Retention_Information"] = ""
if m.get('Retention_Period', False):
for i, value in enumerate(retention_years_list):
if value == m["Retention_Period"]:
m["Retention_Information"] = retention_names_list[i]
break
m["Retention_Period"] = int(m["Retention_Period"])
else:
m["Retention_Period"] = 0
# dag0-Creator => def2-Creator
for creator in m['Creator']:
creator['Affiliation'] = [creator['Affiliation']]
if 'Owner_Role' in creator:
creator.pop('Owner_Role')
# Missing data in dag0 - License "Internal License Data Archive Geosciences 2021-01"
m["License"] = "Custom"
meta.metadata_set_schema_id(m, 'https://yoda.uu.nl/schemas/default-2/metadata.json')
return m
def _default1_teclab0(ctx: rule.Context, m: Dict) -> Dict:
"""
Transform Default-1 data to the teclab-0 schema definition
:param ctx: Combined type of a callback and rei struct
:param m: Metadata to be transformed (default-1)
:returns: Transformed (teclab-0) JSON object
"""
# First bring to default2 level
m = _default1_default2(ctx, m)
# 1) REQUIRED FIELDS
m['Discipline'] = ['Analogue modelling of geologic processes']
m['Lab'] = ['aa45f98e5c098237d0c57b58e5f953e1']
m['Main_Setting'] = ['basin plain setting']
m['Process_Hazard'] = ['deformation']
m['Geological_Structure'] = ['fault']
m['Geomorphological_Feature'] = ['alluvial and fluvial features']
m['Material'] = ['sedimentary rock - limestone - Solnhofen limestone']
m['Apparatus'] = ['2D Convection box']
m['Software'] = ['CloudCompare']
m['Measured_Property'] = ['Bulk modulus']
if not m.get('Data_Type', False):
m['Data_Type'] = 'Dataset'
if not m.get('Related_Datapackage', False):
m['Related_Datapackage'] = [{'Relation_Type': 'IsSupplementTo',
'Title': 'RDP title',
'Persistent_Identifier': {'Identifier_Scheme': 'ARK',
'Identifier': 'ARK123'}}]
else:
# Relation types of default1 have additional information in string 'IsSupplementTo: Is supplement to'
# Stripping is required for teclab/hptlab
for rdp in m['Related_Datapackage']:
try:
rdp['Relation_Type'] = rdp['Relation_Type'].split(':')[0]
except Exception:
rdp['Relation_Type'] = 'IsSupplementTo'
# Contact is a special contributor of contributor type 'ContactPerson'
# First check whether present Contributors contain contact persons.
# If not, add a placeholder Contact
# Loop through present Contributors.
# If ContactPerson is present, add as a Contacts and remove from Contributors list
new_contacts = []
contributors_remaining = []
if m.get('Contributor', False):
for contributor in m['Contributor']:
if contributor['Contributor_Type'] == 'ContactPerson':
# Add this contributor-contact-person to contacts list
new_contacts.append({'Name': {'Given_Name': contributor['Name']['Given_Name'], 'Family_Name': contributor['Name']['Family_Name']},
'Position': 'Position',
'Email': 'Email',
'Affiliation': ['Affiliation'],
'Person_Identifier': [{'Name_Identifier_Scheme': contributor['Person_Identifier'][0]['Name_Identifier_Scheme'],
'Name_Identifier': contributor['Person_Identifier'][0]['Name_Identifier']}]})
else:
# remaining list contains non-contactpersons only
contributors_remaining.append(contributor)
if len(new_contacts):
# If new contacts are present
m['Contact'] = new_contacts
m['Contributor'] = contributors_remaining
else:
m['Contact'] = [{'Name': {'Given_Name': 'Contact given name', 'Family_Name': 'Contact family name'},
'Position': 'Position',
'Email': 'Email',
'Affiliation': ['Affiliation'],
'Person_Identifier': [{'Name_Identifier_Scheme': '',
'Name_Identifier': ''}]}]
# 2) SPECIFIC TRANSFORMATION combining different attributes
# GeoBox - derived from Covered_Geolocation_Place and Covered_Period
# spatial = ', '.join(m['Covered_Geolocation_Place'])
try:
m['GeoLocation'] = [{'geoLocationBox': {'northBoundLatitude': 0.0,
'westBoundLongitude': 0.0,
'southBoundLatitude': 0.0,
'eastBoundLongitude': 0.0},
'Description_Spatial': ', '.join(m['Covered_Geolocation_Place']),
'Description_Temporal': {'Start_Date': m['Covered_Period']['Start_Date'], 'End_Date': m['Covered_Period']['End_Date']}}]
except Exception:
pass
# Funding reference is not a required field, but if present in def1 then an extra field is required
if m.get('Funding_Reference', False):
for fun_ref in m['Funding_Reference']:
fun_ref['Funder_Reference'] = 'Funder_Reference'
# 3) REMOVE ATTRIBUTES that are not part of teclab-0
try:
m.pop('Covered_Geolocation_Place')
except KeyError:
pass
try:
m.pop('Covered_Period')
except KeyError:
pass
try:
m.pop('Retention_Information')
except KeyError:
pass
try:
m.pop('Collection_Name')
except KeyError:
pass
# 4) SET CORRECT META SCHEMA
meta.metadata_set_schema_id(m, 'https://yoda.uu.nl/schemas/teclab-0/metadata.json')
return m
def _default1_hptlab0(ctx: rule.Context, m: Dict) -> Dict:
"""
Transform Default-1 data to the hptlab-0 schema definition
:param ctx: Combined type of a callback and rei struct
:param m: Metadata to be transformed (default-1)
:returns: Transformed (hptlab-0) JSON object
"""
# First bring to default2 level
m = _default1_default2(ctx, m)
# 1) REQUIRED FIELDS
m['Discipline'] = ['Rock and melt physical properties']
m['Lab'] = ['e3a4f5d02528d02c516dbea19c20b32c']
# Material, Apparatus and Apparatus might get different default values (email Vincent Brunst 15 oct)
# Pore_Fluid list still to be defined
m['Material'] = ['sedimentary rock - limestone - Solnhofen limestone']
m['Apparatus'] = ['deformation testing - compression testing - confining pressure vessel']
m['Measured_Property'] = ['strength - tensile strength']
m['Pore_Fluid'] = ['vacuum']
if not m.get('Data_Type', False):
m['Data_Type'] = 'Dataset'
if not m.get('Related_Datapackage', False):
m['Related_Datapackage'] = [{'Relation_Type': 'IsSupplementTo',
'Title': 'RDP title',
'Persistent_Identifier': {'Identifier_Scheme': 'ARK',
'Identifier': 'ARK123'}}]
else:
# Relation types of default1 have additional information in string 'IsSupplementTo: Is supplement to'
# Stripping is required for teclab/hptlab
for rdp in m['Related_Datapackage']:
try:
rdp['Relation_Type'] = rdp['Relation_Type'].split(':')[0]
except Exception:
rdp['Relation_Type'] = 'IsSupplementTo'
# Contact is a special contributor of contributor type 'ContactPerson'
# First check whether present Contributors contain contact persons.
# If not, add a placeholder Contact
# Loop through present Contributors.
# If ContactPerson is present, add as a Contacts and remove from Contributors list
new_contacts = []
contributors_remaining = []
if m.get('Contributor', False):
for contributor in m['Contributor']:
if contributor['Contributor_Type'] == 'ContactPerson':
# Add this contributor-contact-person to contacts list
new_contacts.append({'Name': {'Given_Name': contributor['Name']['Given_Name'], 'Family_Name': contributor['Name']['Family_Name']},
'Position': 'Position',
'Email': 'Email',
'Affiliation': ['Affiliation'],
'Person_Identifier': [{'Name_Identifier_Scheme': contributor['Person_Identifier'][0]['Name_Identifier_Scheme'],
'Name_Identifier': contributor['Person_Identifier'][0]['Name_Identifier']}]})
else:
# remaining list contains non-contactpersons only
contributors_remaining.append(contributor)
if len(new_contacts):
# If new contacts are present
m['Contact'] = new_contacts
m['Contributor'] = contributors_remaining
else:
m['Contact'] = [{'Name': {'Given_Name': 'Contact given name', 'Family_Name': 'Contact family name'},
'Position': 'Position',
'Email': 'Email',
'Affiliation': ['Affiliation'],
'Person_Identifier': [{'Name_Identifier_Scheme': '',
'Name_Identifier': ''}]}]
# 2) SPECIFIC TRANSFORMATION combining different attributes
# GeoBox - derived from Covered_Geolocation_Place and Covered_Period
# spatial = ', '.join(m['Covered_Geolocation_Place'])
try:
m['GeoLocation'] = [{'geoLocationBox': {'northBoundLatitude': 0.0,
'westBoundLongitude': 0.0,
'southBoundLatitude': 0.0,
'eastBoundLongitude': 0.0},
'Description_Spatial': ', '.join(m['Covered_Geolocation_Place']),
'Description_Temporal': {'Start_Date': m['Covered_Period']['Start_Date'], 'End_Date': m['Covered_Period']['End_Date']}}]
except Exception:
pass
# Funding reference is not a required field, but if present in def1 then an extra field is required
if m.get('Funding_Reference', False):
for fun_ref in m['Funding_Reference']:
fun_ref['Funder_Reference'] = 'Funder_Reference'
# 3) REMOVE ATTRIBUTES that are not part of hptlab-0
try:
m.pop('Covered_Geolocation_Place')
except KeyError:
pass
try:
m.pop('Covered_Period')
except KeyError:
pass
try:
m.pop('Retention_Information')
except KeyError:
pass
try:
m.pop('Collection_Name')
except KeyError:
pass
# 4) SET CORRECT META SCHEMA
meta.metadata_set_schema_id(m, 'https://yoda.uu.nl/schemas/hptlab-0/metadata.json')
return m
def _hptlab0_hptlab1(ctx: rule.Context, m: Dict) -> Dict:
"""
Transform hptlab-0 data to the hptlab-1 schema definition which holds better qualified lists.
:param ctx: Combined type of a callback and rei struct
:param m: Metadata to transform (hptlab-0)
:returns: Transformed (hptlab-1) JSON object
"""
try:
m.pop('Monitoring')
except KeyError:
pass
# Get the entire metadata schema to be able to get some proper values based on the previous saved values
new_schema = jsonutil.read(ctx, '/{}/yoda/schemas/hptlab-1/metadata.json'.format(user.zone(ctx)))
attributes = {'Material': 'optionsMaterial',
'Apparatus': 'optionsApparatus',
'Measured_Property': 'optionsMeasuredProperty'}
for attribute, option_list in attributes.items():
new_list = []
reference_list = new_schema['definitions'][option_list]['enum']
try:
for item_search in m[attribute]:
found = False
for _i, elem in enumerate(reference_list):
if item_search.lower() in elem.lower():
found = True
new_list.append(elem)
break
if not found:
for _i, elem in enumerate(reference_list):
# Split on ' ' an compare based on the first token
if item_search.split(' ')[0].lower() in elem.lower():
found = True
new_list.append(elem)
break
except KeyError:
pass
if len(new_list):
m[attribute] = new_list
else:
# Take first in the corresponding list as a default value
m[attribute] = [new_schema['definitions'][option_list]['enum'][0]]
# Newly introduced - no previous value present
m['Pore_Fluid'] = [new_schema['definitions']['optionsPoreFluid']['enum'][0]]
meta.metadata_set_schema_id(m, 'https://yoda.uu.nl/schemas/hptlab-1/metadata.json')
return m
def _teclab0_teclab1(ctx: rule.Context, m: Dict) -> Dict:
"""
Transform teclab-0 data to the teclab-1 schema definition which holds better qualified lists.
:param ctx: Combined type of a callback and rei struct
:param m: Metadata to transform (teclab-0)
:returns: Transformed (teclab-1) JSON object
"""
new_schema = jsonutil.read(ctx, '/{}/yoda/schemas/teclab-1/metadata.json'.format(user.zone(ctx)))
if 'Geomorphical_Feature' in m:
# Name is no longer in use.
m['Geomorphological_Feature'] = m['Geomorphical_Feature']
m.pop('Geomorphical_Feature')
attributes = {'Material': 'optionsMaterial',
'Apparatus': 'optionsApparatus',
'Measured_Property': 'optionsMeasuredProperty',
'Main_Setting': 'optionsMainSetting',
'Process_Hazard': 'optionsProcessHazard',
'Geological_Structure': 'optionsGeologicalStructure',
'Geomorphological_Feature': 'optionsGeomorphologicalFeature',
'Software': 'optionsSoftware'}
for attribute, option_list in attributes.items():
new_list = []
reference_list = new_schema['definitions'][option_list]['enum']
try:
for item_search in m[attribute]:
found = False
for _i, elem in enumerate(reference_list):
if item_search.lower() in elem.lower():
found = True
new_list.append(elem)
break
if not found:
for _i, elem in enumerate(reference_list):
# Split on ' ' an compare based on the first token
if item_search.split(' ')[0].lower() in elem.lower():
found = True
new_list.append(elem)
break
except KeyError:
pass
if len(new_list):
m[attribute] = new_list
else:
# Take first in the corresponding list as a default value
m[attribute] = [new_schema['definitions'][option_list]['enum'][0]]
meta.metadata_set_schema_id(m, 'https://yoda.uu.nl/schemas/teclab-1/metadata.json')
return m
# }}}
def get(src_id: str, dst_id: str) -> Callable | None:
"""
Get a transformation function that maps metadata from the given src schema id to the dst schema id.
:param src_id: The metadata's current schema id
:param dst_id: The metadata's destination schema id
:return: A transformation function, or None if no mapping exists for the given ids
"""
# Simplified shortcut as these are once in a lifetime!
if src_id == 'https://yoda.uu.nl/schemas/default-1/metadata.json':
if dst_id == 'https://yoda.uu.nl/schemas/hptlab-0/metadata.json':
return _default1_hptlab0
if dst_id == 'https://yoda.uu.nl/schemas/teclab-0/metadata.json':
return _default1_teclab0
transformations = {'https://yoda.uu.nl/schemas/dag-0/metadata.json':
{'https://yoda.uu.nl/schemas/default-2/metadata.json': _dag0_default2},
'https://yoda.uu.nl/schemas/default-0/metadata.json':
{'https://yoda.uu.nl/schemas/default-1/metadata.json': _default0_default1},
'https://yoda.uu.nl/schemas/default-1/metadata.json':
{'https://yoda.uu.nl/schemas/default-2/metadata.json': _default1_default2},
'https://yoda.uu.nl/schemas/default-2/metadata.json':
{'https://yoda.uu.nl/schemas/default-3/metadata.json': _default2_default3},
'https://yoda.uu.nl/schemas/core-1/metadata.json':
{'https://yoda.uu.nl/schemas/core-2/metadata.json': _core1_core2},
'https://yoda.uu.nl/schemas/hptlab-0/metadata.json':
{'https://yoda.uu.nl/schemas/hptlab-1/metadata.json': _hptlab0_hptlab1},
'https://yoda.uu.nl/schemas/teclab-0/metadata.json':
{'https://yoda.uu.nl/schemas/teclab-1/metadata.json': _teclab0_teclab1}}
x = transformations.get(src_id)
return None if x is None else x.get(dst_id)