-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathevaluator.py
2412 lines (2098 loc) · 98.5 KB
/
evaluator.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
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import ast
import csv
import gettext
import logging
import os
import sys
import urllib
import xml.etree.ElementTree as ET
from abc import ABC, abstractmethod
from functools import wraps
import idutils
import pandas as pd
import requests
import api.utils as ut
from api.vocabulary import Vocabulary
logger = logging.getLogger("api.plugin.evaluation_steps")
logger_api = logging.getLogger("api.plugin")
class ConfigTerms(property):
"""Class that simplifies and standarizes the management of the given metadata
elements and its values by generic plugins. It is expected to be called as a
decorator of the Plugin's method that implements the evaluation of a RDA indicator,
e.g.:
@ConfigTerms(term_id="identifier_term_data")
def rda_f1_02d(self, **kwargs):
...
which will add the results to the 'kwargs' dictionary (see Outputs below).
This class decorator features a 3-level of processing of each metadata element and its corresponding values:
1) Harmonization of metadata elements: which maps the Plugin's metadata element to a common FAIR-EVA's internal element name. It relies on the definition of the 'terms_map' configuration parameter within the plugin's config.ini file.
2) Homogenization of the metadata values: resulting in a common format and type in order to facilitate further processing.
3) Validation of the metadata values: with respect to well-known, standarized vocabularies.
Input parameters:
- 'term_id' (required, str): shall correspond to the name of the configuration parameter (within plugin's config.ini) containing the metadata terms.
- 'validate' (optional, boolean): triggers the validation of the gathered metadata values for each of those metadata terms.
Outputs:
- Returned values are different according to the value of 'validate' input:
+ If disabled (validate=False), the class decorator returns a dictionary of:
{
<metadata_element_1>: [<metadata_value_1>, ..]
}
+ If enabled (validate=True), the class decorator adds the validation info as:
{
<metadata_element_1>: {
'values': [<metadata_value_1>, ..],
'validation': {
<vocabulary_1>: {
'valid': [<metadata_value_1>, ..],
'non_valid': [<metadata_value_1>, ..],
}
}
}
}
- Usually captured by the decorated method through the keyword arguments dict -> **kwargs.
"""
def __init__(self, term_id, validate=False):
self.term_id = term_id
self.validate = validate
def __call__(self, wrapped_func):
@wraps(wrapped_func)
def wrapper(plugin, **kwargs):
metadata = plugin.metadata
has_metadata = True
term_list = ast.literal_eval(plugin.config[plugin.name][self.term_id])
logger.debug(
"List of metadata elements associated with the requested configuration term ID '%s': %s"
% (self.term_id, term_list)
)
# Create an empty DataFrame for term_metadata
term_metadata = pd.DataFrame(columns=["element", "qualifier"])
# Populate term_metadata with values from plugin.terms_map
for term in term_list:
if term in plugin.terms_map:
values = plugin.terms_map[term]
if isinstance(values, list):
for value in values:
if isinstance(value, list):
term_metadata = pd.concat(
[
term_metadata,
pd.DataFrame(
[
{
"element": value[0],
"qualifier": value[1],
}
]
),
]
)
else:
term_metadata = pd.concat(
[
term_metadata,
pd.DataFrame(
[{"element": value, "qualifier": None}]
),
]
)
else:
term_metadata = pd.concat(
[
term_metadata,
pd.DataFrame([{"element": values, "qualifier": None}]),
]
)
# Get values in config for the given term
if term_metadata.empty:
msg = (
"Metadata values are not defined in configuration for the term '%s'"
% self.term_id
)
has_metadata = False
else:
term_metadata = ut.check_metadata_terms_with_values(
metadata, term_metadata
)
if term_metadata.empty:
msg = (
"No access information can be found in the metadata for: %s. Please double-check the value/s provided for '%s' configuration parameter"
% (term_list, self.term_id)
)
has_metadata = False
if not has_metadata:
logger.warning(msg)
return (0, msg)
# Harmonization of metadata terms, homogenization of the data type of the metadata values & validation of those metadata values in accordance with CVs
_msg = "Proceeding with stages of: 1) Harmonization of metadata terms, 2) Homogenization of data types of metadata values"
if self.validate:
_msg += " & 3) Validation of metadata values in accordance with existing CVs"
logger_api.debug(_msg)
# 1. Iterate over the dictionary defined in plugin.terms_map
for key, value in plugin.terms_map.items():
term_key_harmonized = []
# 2. Check if the terms in term_list are present in that dictionary
if key in term_list:
# 3. Store in term_key_plugin the value of each element of term_list in the dictionary
for term_key_plugin in value:
term_values_list = []
# 4. Store in term_key_harmonized the elements of term_list for which it finds any element
term_key_harmonized.append(key)
logger.debug(
"Harmonizing metadata term '%s' to '%s'"
% (term_key_plugin, key)
)
# Homogenize the data format and type (list) of the metadata values
if isinstance(term_key_plugin, list):
term_values = term_metadata.loc[
(term_metadata["element"] == term_key_plugin[0])
& (term_metadata["qualifier"] == term_key_plugin[1])
].text_value.to_list()
else:
term_values = term_metadata.loc[
term_metadata["element"] == term_key_plugin
].text_value.to_list()
if not term_values:
logger.warning(
"No values found in the metadata associated with element '%s'"
% term_key_plugin
)
logger_api.warning(
"Not proceeding with metadata value homogenization and validation"
)
else:
logger_api.warning(
"Considering list of the values returned: %s"
% term_values
)
logger.debug(
"Values found for metadata element '%s': %s"
% (term_key_plugin, term_values)
)
# Homogenize metadata values
logger_api.debug(
"Homogenizing format and type of the metadata value for the given (raw) metadata: %s"
% term_values
)
term_values_list_temp = plugin.metadata_utils.gather(
term_values, element=key
)
# Raise exception if the homogenization resulted in no values
if not term_values_list_temp:
raise Exception(
"No values for metadata element '%s' resulted from the homogenization process"
% term_key_plugin
)
else:
logger_api.debug(
"Homogenized values for the metadata element '%s': %s"
% (term_key_plugin, term_values_list_temp)
)
term_values_list.extend(term_values_list_temp)
# Validate metadata values (if validate==True)
if self.validate:
term_values_list_validated = {}
if term_values_list:
logger_api.debug(
"Validating values for '%s' metadata element: %s"
% (term_key_plugin, term_values_list)
)
term_values_list_validated = (
plugin.metadata_utils.validate(
term_values_list,
element=term,
plugin_obj=plugin,
)
)
if term_values_list_validated:
logger_api.debug(
"Validation results for metadata element '%s': %s"
% (term_key_plugin, term_values_list_validated)
)
else:
logger_api.warning(
"Validation could not be done for metadata element '%s'"
% term_key_plugin
)
# Update kwargs according to the format:
# <metadata_element_1>: {
# 'values': [<metadata_value_1>, ..],
# 'validation': {
# <vocabulary_1>: {
# 'valid': [<metadata_value_1>, ..],
# 'non_valid': [<metadata_value_1>, ..],
# }
# }
# }
_metadata_payload = {
"values": term_values_list,
"validation": term_values_list_validated,
}
logger.debug(
"Resulting metadata payload for element '%s': %s"
% (term_key_plugin, _metadata_payload)
)
# Merge if the same harmonized metadata element points to multiple elements in the original metadata schema (see 'terms_map' config attribute)
if term in list(kwargs):
_previous_payload = kwargs[term]
logger.debug(
"Merge with previously collected metadata payload: %s"
% _previous_payload
)
_metadata_payload.update(_previous_payload)
logger.debug(
"Resulting metadata payload for element '%s' (after merging): %s"
% (term_key_plugin, _metadata_payload)
)
# Update 'kwargs'
if isinstance(key, list):
for tkh in key:
kwargs.update({tkh: _metadata_payload})
else:
kwargs.update({key: _metadata_payload})
else:
logger.debug(
"Not validating values from metadata element '%s'" % key
)
# Merge if the same harmonized metadata element points to multiple elements in the original metadata schema (see 'terms_map' config attribute)
if key in list(kwargs):
_previous_values_list = kwargs[key]
logger.debug(
"Merge with previously collected metadata values: %s"
% _previous_values_list
)
term_values_list.extend(_previous_values_list)
logger.debug(
"Resulting metadata values for element '%s' (after merging): %s"
% (key, term_values_list)
)
# Update kwargs according to format:
# {
# <metadata_element_1>: [<metadata_value_1>, ..]
# }
kwargs.update({key: term_values_list})
logger.info(
"Passing metadata elements and associated values to wrapped method '%s': %s"
% (wrapped_func.__name__, kwargs)
)
# Check if all keys in kwargs have values assigned
total_keys = len(kwargs)
keys_with_values = sum(1 for key, value in kwargs.items() if value)
if keys_with_values == total_keys:
points = 100
else:
points = (keys_with_values / total_keys) * 100
return wrapped_func(plugin, **kwargs, points=points)
return wrapper
class MetadataValuesBase(property):
"""Base class that provides the main methods for processing the metadata values:
- gather(), which transforms metadata values to a common representation (data format and type).
- validate(), which performs the validation of the metadata values across a series of vocabularies.
Specific gathering (_get_* methods) and validation (_validate_* methods) can be defined. In particular case of the validation, these methods shall return a dictionary of the form:
{
<vocabulary_1>: {
"valid": [<metadata_value_1>, ..],
"non_valid": [<metadata_value_1>, ..]
}
}
"""
@classmethod
def gather(cls, element_values_list, element):
"""Gets the metadata value according to the given element.
It calls the appropriate class method.
"""
_values = []
try:
for element_values in element_values_list:
if element == "Metadata Identifier":
temp_values = cls._get_identifiers_metadata(element_values)
if temp_values is not None:
_values.append(temp_values)
elif element == "Data Identifier":
temp_values = cls._get_identifiers_data(element_values)
if temp_values is not None:
_values.append(temp_values)
elif element == "Temporal Coverage":
temp_values = cls._get_temporal_coverage(element_values)
if temp_values is not None:
_values.append(temp_values)
elif element == "Spatial Coverage":
temp_values = cls._get_spatial_coverage(element_values)
if temp_values is not None:
_values.append(temp_values)
elif element == "Person Identifier":
temp_values = cls._get_person_identifier(element_values)
if temp_values is not None:
_values.append(temp_values)
elif element == "Keywords":
temp_values = cls._get_keywords(element_values)
if temp_values is not None:
_values.append(temp_values)
elif element == "Format":
temp_values = cls._get_formats(element_values)
if temp_values is not None:
_values.append(temp_values)
elif element == "Metadata for Resource Discovery":
temp_values = cls._get_resource_discovery(element_values)
_values.append(temp_values)
elif element == "Metadata for accesibility":
temp_values = cls._get_metadata_accessibility(element_values)
_values.append(temp_values)
elif element == "Metadata connection":
temp_values = cls._get_metadata_connection(element_values)
_values.append(temp_values)
elif element == "Data connection":
temp_values = cls._get_identifiers_data(element_values)
_values.append(temp_values)
else:
raise NotImplementedError(
"Self-invoking NotImplementedError exception"
)
except Exception as e:
logger_api.exception(str(e))
_values = element_values
for element_values in element_values_list:
if isinstance(element_values, str):
_values = [element_values]
logger_api.warning(
"No specific plugin's gather method defined for metadata element '%s'. Returning input values formatted to list: %s"
% (element, _values)
)
else:
logger_api.debug(
"Successful call to plugin's gather method for the metadata element '%s'. Returning: %s"
% (element, _values)
)
finally:
return _values
@classmethod
def validate(cls, element_values, element, plugin_obj=None, **kwargs):
"""Validates the metadata values provided with respect to the supported
controlled vocabularies.
E.g. call:
>>> MetadataValuesBase.validate(["http://orcid.org/0000-0003-4551-3339/Contact"], "Person Identifier")
"""
from itertools import chain
# Get CVs
controlled_vocabularies = plugin_obj.config["Generic"].get(
"controlled_vocabularies", {}
)
if not controlled_vocabularies:
msg = "Controlled vocabularies not defined in configuration: please check 'Generic:controlled_vocabularies'"
logger_api.error(msg)
raise Exception(msg)
else:
controlled_vocabularies = ast.literal_eval(controlled_vocabularies)
matching_vocabularies = controlled_vocabularies.get(element, {})
if matching_vocabularies:
logger_api.debug(
"Found matching vocabulary/ies for element <%s>: %s"
% (element, matching_vocabularies)
)
else:
logger_api.warning(
"No matching vocabulary found for element <%s>" % element
)
# Trigger validation
if element == "Format":
logger_api.debug(
"Calling _validate_format() method for element: <%s>" % element
)
_result_data = cls._validate_format(
cls,
element_values,
matching_vocabularies,
plugin_obj=plugin_obj,
**kwargs,
)
elif element == "License":
logger_api.debug(
"Calling _validate_license() method for element: <%s>" % element
)
_result_data = cls._validate_license(
cls, element_values, matching_vocabularies, **kwargs
)
elif (
element == "Keywords"
or element == "Metadata for Resource Discovery"
or element == "Metadata connection"
):
logger_api.debug(
"Calling _validate_any_vocabulary() method for element: <%s>" % element
)
_result_data = cls._validate_any_vocabulary(
element_values, matching_vocabularies, plugin_obj.config
)
elif element == "Person Identifier":
_result_data = {}
for vocabulary_id, vocabulary_url in matching_vocabularies.items():
_result_data[vocabulary_id] = {"valid": [], "non_valid": []}
for value in element_values:
if ut.orcid_basic_info(value):
_result_data[vocabulary_id]["valid"].append(value)
else:
_result_data[vocabulary_id]["non_valid"].append(value)
elif element == "Data connection":
logger_api.debug(
"Calling _validate_data_connection() method for element: <%s>" % element
)
_result_data = cls._validate_data_connection(element_values)
else:
# logger_api.warning("Validation not implemented for element: <%s>" % element)
# _result_data = {}
logger_api.debug(
"Calling _validate_any_vocabulary() method for element: <%s>" % element
)
_result_data = cls._validate_any_vocabulary(
element_values, matching_vocabularies, plugin_obj.config
)
return _result_data
@classmethod
def _get_identifiers_metadata(cls, element_values):
raise NotImplementedError
@classmethod
def _get_identifiers_data(cls, element_values):
raise NotImplementedError
@classmethod
def _get_formats(cls, element_values):
return NotImplementedError
@classmethod
def _get_licenses(cls, element_values):
return NotImplementedError
@classmethod
def _get_temporal_coverage(cls, element_values, matching_vocabularies):
"""Get start and end dates, when defined, that characterise the temporal
coverage of the dataset.
* Expected output:
[
{
'start_date': <class 'datetime.datetime'>,
'end_date': <class 'datetime.datetime'>,
}
]
"""
return NotImplementedError
@classmethod
def _get_spatial_coverage(cls, element_values):
return NotImplementedError
@classmethod
def _get_resource_discovery(cls, element_values):
return element_values
@classmethod
def _get_person_identifier(cls, element_values):
return element_values
@classmethod
def _get_keywords(cls, element_values):
return element_values
@classmethod
def _get_metadata_accessibility(cls, element_values):
return element_values
@classmethod
def _get_metadata_connection(cls, element_values):
return NotImplementedError
@classmethod
def _validate_format(cls, element_values):
return NotImplementedError
@classmethod
def _validate_license(cls, element_values):
return NotImplementedError
@classmethod
def _validate_metadata_for_resource_discovery(
self, element_values, matching_vocabularies, config
):
"""Validates the metadata values for resource discovery with respect to the
supported controlled vocabularies."""
result_data = {}
for vocabulary_id, vocabulary_url in matching_vocabularies.items():
result_data[vocabulary_id] = {"valid": [], "non_valid": []}
if vocabulary_id == "Agrovoc":
from api.vocabulary import Agrovoc
agrovoc = Agrovoc(config)
for value in element_values:
if agrovoc.collect(term=value):
result_data[vocabulary_id]["valid"].append(value)
else:
result_data[vocabulary_id]["non_valid"].append(value)
elif vocabulary_id == "Getty":
from api.vocabulary import Getty
getty = Getty(config)
for value in element_values:
if getty.collect(term=value):
result_data[vocabulary_id]["valid"].append(value)
else:
result_data[vocabulary_id]["non_valid"].append(value)
# Add more vocabularies as needed
# elif vocabulary_id == "AnotherVocabulary":
# ...
return result_data
@classmethod
def _validate_any_vocabulary(self, element_values, matching_vocabularies, config):
result_data = {}
for vocabulary_id, vocabulary_url in matching_vocabularies.items():
try:
from api import vocabulary as voc
except ImportError as ex:
logger.error("Error importing vocabulary module: %s" % ex)
continue
# Check if a corresponding class exists in vocabulary.py
if hasattr(voc, vocabulary_id):
vocab_class = getattr(voc, vocabulary_id)
vocab_instance = vocab_class(config)
result_data[vocabulary_id] = {"valid": [], "non_valid": []}
for value in element_values:
# Attempt to call collect with 'term'; if fails, try with 'search_topic'
try:
valid = vocab_instance.collect(value)
if valid:
result_data[vocabulary_id]["valid"].append(value)
else:
result_data[vocabulary_id]["non_valid"].append(value)
except Exception as ex:
logger.error(ex)
else:
logger.warning(
"Vocabulary '%s' is not implemented in vocabulary.py"
% vocabulary_id
)
return result_data
@classmethod
def _validate_data_connection(self, element_values):
result_data = {}
result_data["Data Connection"] = {"valid": [], "non_valid": []}
for value in element_values:
if ut.validate_any_pid(value):
result_data["Data Connection"]["valid"].append(value)
else:
result_data["Data Connection"]["non_valid"].append(value)
return result_data
class EvaluatorBase(ABC):
"""A class used to define FAIR indicators tests. It contains all the references to all the tests
...
Attributes
----------
item_id : str
Digital Object identifier, which can be a generic one (DOI, PID), or an internal (e.g. an
identifier from the repo)
api_endpoint : str
Open Archives initiative , This is the place in which the API will ask for the metadata
lang : str
Two-letter language code
config : ConfigParser object
ConfigParser's object containing both plugin's and main configuration.
name : str
FAIR-EVA's plugin name.
"""
def __init__(
self, item_id, api_endpoint=None, lang="en", config=None, name=None, **kwargs
):
self.item_id = item_id
self.api_endpoint = api_endpoint
self.lang = lang
self.config = config
self.name = name
self.metadata = None
self.cvs = []
# Config attributes
self.terms_map = ast.literal_eval(self.config[self.name]["terms_map"])
self.identifier_term = ast.literal_eval(
self.config[self.name]["identifier_term"]
)
self.terms_quali_generic = ast.literal_eval(
self.config[self.name]["terms_quali_generic"]
)
self.terms_quali_disciplinar = ast.literal_eval(
self.config[self.name]["terms_quali_disciplinar"]
)
self.terms_cv = ast.literal_eval(self.config[self.name]["terms_cv"])
self.supported_data_formats = ast.literal_eval(
self.config[self.name]["supported_data_formats"]
)
self.terms_qualified_references = ast.literal_eval(
self.config[self.name]["terms_qualified_references"]
)
self.terms_relations = ast.literal_eval(
self.config[self.name]["terms_relations"]
)
self.metadata_access_manual = ast.literal_eval(
self.config[self.name]["metadata_access_manual"]
)
self.data_access_manual = ast.literal_eval(
self.config[self.name]["data_access_manual"]
)
self.terms_access_protocols = ast.literal_eval(
self.config[self.name]["terms_access_protocols"]
)
# self.vocabularies = ast.literal_eval(self.config[self.name]["vocabularies"])
self.dict_vocabularies = ast.literal_eval(
self.config[self.name]["dict_vocabularies"]
)
self.vocabularies = list(self.dict_vocabularies.keys())
self.metadata_standard = ast.literal_eval(
self.config[self.name]["metadata_standard"]
)
self.metadata_authentication = ast.literal_eval(
self.config[self.name]["metadata_authentication"]
)
self.metadata_persistence = ast.literal_eval(
self.config[self.name]["metadata_persistence"]
)
global _
_ = self.translation()
def translation(self):
# Translations
t = gettext.translation(
"messages", "translations", fallback=True, languages=[self.lang]
)
_ = t.gettext
return _
def metadata_values(self):
raise NotImplementedError
def eval_persistency(self, id_list, data_or_metadata="(meta)data"):
points = 0
msg_list = []
points_per_id = round(100 / len(id_list))
for _id in id_list:
_points = 0
if ut.is_persistent_id(_id):
_msg = _("Found persistent identifier for the")
_msg = _msg + " %s: %s" % (
data_or_metadata,
_id,
)
_points = points_per_id
points = 100
else:
_msg = _("Identifier is not persistent for the")
_msg = _msg + "%s: %s" % (
data_or_metadata,
_id,
)
_points = 0
msg_list.append({"message": _msg, "points": _points})
return (points, msg_list)
@abstractmethod
def get_metadata(self):
"""Method to be implemented by plugins."""
raise NotImplementedError("Derived class mus implement get_metadata method")
def eval_uniqueness(self, id_list, data_or_metadata="(meta)data"):
points = 0
msg_list = []
points_per_id = round(100 / len(id_list))
for _id in id_list:
_points = 0
if ut.is_unique_id(_id):
_msg = _("Found a globally unique identifier for the")
_msg = _msg + "%s: %s" % (
data_or_metadata,
_id,
)
_points = points_per_id
points = 100
else:
_msg = "Identifier found for the %s is not globally unique: %s" % (
data_or_metadata,
_id,
)
_points = 0
msg_list.append({"message": _msg, "points": _points})
return (points, msg_list)
def eval_validated_basic(self, validation_payload):
"""Basic evaluation of validated metadata elements: scores according to the number of metadata elements using standard vocabularies over the total amount of metadata elements given as input.
This method is useful for RDA methods that use ConfigTerms() decorator with 'validate=True'.
:validation_payload: dictionary containing the validation results. Format as returned by ConfigTerms(validate=True)
"""
# Delete 'points' if it exists before further processing
if "points" in validation_payload:
del validation_payload["points"]
# Loop over validated metadata elements
elements_using_vocabulary = []
for element, data in validation_payload.items():
try:
validation_data = data.get("validation", {})
except Exception:
logger_api.warning(
"No validation data could be gathered for the metadata element '%s'"
% element
)
continue
if not validation_data:
_msg = (
"No validation data could be gathered for the metadata element '%s'"
% element
)
if data["values"]:
_msg += (
": values present, but FAIR-EVA could not assert compliance with any vocabulary: %s"
% data["values"]
)
else:
_msg += ": values not found in the metadata repository"
logger_api.warning(_msg)
else:
# At least one value compliant with a CV is necessary
vocabulary_in_use = []
for vocabulary_id, validation_results in validation_data.items():
if len(validation_results["valid"]) > 0:
vocabulary_in_use.append(vocabulary_id)
if vocabulary_in_use:
elements_using_vocabulary.append(element)
logger.info(
"Found standard vocabulary/ies in the values of metadata element '%s': %s"
% (element, vocabulary_in_use)
)
else:
logger.warning(
"Could not find standard vocabulary/ies in the values of metadata element '%s'. Vocabularies being checked: %s"
% (element, validation_data.keys())
)
# Compound message
total_elements = len(validation_payload)
total_elements_using_vocabulary = len(elements_using_vocabulary)
_msg = (
_("Found metadata elements using standard vocabularies:") + " %s (%s) out of %s (%s)"
% (
total_elements_using_vocabulary,
elements_using_vocabulary,
total_elements,
list(validation_payload),
)
)
logger.info(_msg)
# Get scores
_points = 0
if total_elements > 0:
_points = total_elements_using_vocabulary / total_elements * 100
return (_msg, _points)
# TESTS
# FINDABLE
@ConfigTerms(term_id="identifier_term")
def rda_f1_01m(self, **kwargs):
"""Indicator RDA-F1-01M: Metadata is identified by a persistent identifier.
This indicator is linked to the following principle: F1 (meta)data are assigned a globally
unique and eternally persistent identifier. More information about that principle can be found
here.
This indicator evaluates whether or not the metadata is identified by a persistent identifier.
A persistent identifier ensures that the metadata will remain findable over time, and reduces
the risk of broken links.
Parameters
----------
identifier_term : dict
A dictionary with metadata information about the identifier/s used for the metadata (see ConfigTerms class for further details)
Returns
-------
points
- 0/100 if no persistent identifier is used for the metadata
- 100/100 if a persistent identifier is used for the metadata
msg
Message with the results or recommendations to improve this indicator
"""
id_list = kwargs["Metadata Identifier"]
points, msg_list = self.eval_persistency(id_list, data_or_metadata="metadata")
logger.debug(msg_list)
if points == 0:
if self.metadata_persistence:
if self.check_link(self.metadata_persistence):
points = 100
msg = "Identifier found and persistence policy given "
return (points, {"message": msg, "points": points})
return (points, msg_list)
@ConfigTerms(term_id="identifier_term_data")
def rda_f1_01d(self, **kwargs):
"""Indicator RDA-F1-01D: Data is identified by a persistent identifier.
This indicator is linked to the following principle: F1 (meta)data are assigned a globally
unique and eternally persistent identifier. More information about that principle can be found
here.
This indicator evaluates whether or not the data is identified by a persistent identifier.
A persistent identifier ensures that the data will remain findable over time and reduces the
risk of broken links.
Parameters
----------
identifier_term_data : dict
A dictionary with metadata information about the identifier/s used for the data (see ConfigTerms class for further details)
Returns
-------
points
Returns a value (out of 100) that reflects the amount of data identifiers that are persistent.
msg
Message with the results or recommendations to improve this indicator
"""
id_list = kwargs["Data Identifier"]
points, msg_list = self.eval_persistency(id_list, data_or_metadata="data")
logger.debug(msg_list)
return (points, msg_list)
@ConfigTerms(term_id="identifier_term")
def rda_f1_02m(self, **kwargs):
"""Indicator RDA-F1-02M: Metadata is identified by a globally unique identifier.
This indicator is linked to the following principle: F1 (meta)data are assigned a globally unique and eternally persistent identifier.
The indicator serves to evaluate whether the identifier of the metadata is globally unique, i.e. that there are no two identical
identifiers that identify different metadata records.
Parameters
----------
identifier_term_data : dict
A dictionary with metadata information about the identifier/s used for the data (see ConfigTerms class for further details)
Returns
-------
points
- 0/100 if the identifier used for the metadata is not globally unique.
- 100/100 if the identifier used for the metadata is globally unique.
msg
Message with the results or recommendations to improve this indicator
"""
id_list = kwargs["Metadata Identifier"]
points, msg_list = self.eval_uniqueness(id_list, data_or_metadata="metadata")
logger.debug(msg_list)
return (points, msg_list)
@ConfigTerms(term_id="identifier_term_data")
def rda_f1_02d(self, **kwargs):
"""Indicator RDA-F1-02D: Data is identified by a globally unique identifier.
This indicator is linked to the following principle: F1 (meta)data are assigned a globally unique and eternally persistent identifier.
The indicator serves to evaluate whether the identifier of the data is globally unique, i.e. that there are no two people that would
use that same identifier for two different digital objects.
Parameters
----------
identifier_term_data : dict
A dictionary with metadata information about the identifier/s used for the data (see ConfigTerms class for further details)
Returns
-------
points
Returns a value (out of 100) that reflects the amount of data identifiers that are globally unique (i.e. DOI, Handle, UUID).
msg
Message with the results or recommendations to improve this indicator
"""
id_list = kwargs["Data Identifier"]
points, msg_list = self.eval_uniqueness(id_list, data_or_metadata="data")
logger.debug(msg_list)
return (points, msg_list)
@ConfigTerms(term_id="terms_quali_generic")
def rda_f2_01m(self, **kwargs):
"""Indicator RDA-F2-01M
This indicator is linked to the following principle: F2: Data are described with rich metadata.
The indicator is about the presence of metadata, but also about how much metadata is
provided and how well the provided metadata supports discovery.
Technical proposal: Two different tests to evaluate generic and disciplinar metadata if needed.
Parameters
----------
item_id : str
Digital Object identifier, which can be a generic one (DOI, PID), or an internal (e.g. an
identifier from the repo)
Returns
-------
points
Returns a value (out of 100) that reflects the grade of compliance with the generic and disciplinary metadata schemas.
msg