-
Notifications
You must be signed in to change notification settings - Fork 6
/
app.py
2307 lines (1892 loc) · 82.2 KB
/
app.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 copy
import eventlet
# from https://github.com/eventlet/eventlet/issues/670
# eventlet.monkey_patch(select=False)
eventlet.monkey_patch()
import sys
from flask import (
Flask,
Response,
request,
render_template,
session,
send_file,
send_from_directory,
make_response,
Blueprint,
url_for,
)
from flask_restx import Resource, Api, fields, reqparse
from flask_swagger_ui import get_swaggerui_blueprint
from flask_cors import CORS
from flask_socketio import SocketIO
from flask_socketio import emit
from flask_caching import Cache
from flask import current_app
from os import environ, path
from dotenv import load_dotenv, dotenv_values
import secrets
import time
from string import Template
import os
import io
import uuid
import argparse
import functools
from argparse import RawTextHelpFormatter
from datetime import datetime, timedelta
import json
from json import JSONDecodeError
from pathlib import Path
import rdflib
from rdflib import ConjunctiveGraph, URIRef
from rdflib.namespace import RDF
import extruct
import logging
from rich.console import Console
from rich.table import Table
from rich.text import Text
from rich.progress import track
import metrics.util as util
import metrics.statistics as stats
from metrics import test_metric
from metrics.FAIRMetricsFactory import FAIRMetricsFactory
from metrics.WebResource import WebResource
from metrics.Evaluation import Result, Evaluation
from profiles.bioschemas_shape_gen import validate_any_from_KG
from profiles.bioschemas_shape_gen import validate_any_from_microdata
from metrics.util import SOURCE, inspect_onto_reg
from metrics.F1B_Impl import F1B_Impl
from metrics.F1B_Impl import F1B_Impl
from urllib.parse import urlparse
from profiles.Profile import Profile
from profiles.ProfileFactory import (
ProfileFactory,
PROFILES,
find_conformsto_subkg,
load_profiles,
update_profiles,
evaluate_profile_with_conformsto,
evaluate_profile_from_type,
dyn_evaluate_profile_with_conformsto,
)
import time
import atexit
import requests
from requests.exceptions import ConnectionError
from pymongo import MongoClient
from bson import ObjectId
from bson.errors import InvalidId
requests.packages.urllib3.disable_warnings(
requests.packages.urllib3.exceptions.InsecureRequestWarning
)
from apscheduler.schedulers.background import BackgroundScheduler
import git
basedir = path.abspath(path.dirname(__file__))
app = Flask(__name__)
app.config.SWAGGER_UI_OPERATION_ID = True
app.config.SWAGGER_UI_REQUEST_DURATION = True
@app.route("/")
def index():
return render_template(
"index.html",
title="FAIR-Checker",
subtitle="Improve the FAIRness of your web resources",
)
# app.logger.setLevel(logging.DEBUG)
app.logger.propagate = False
CORS(app)
app.config["CORS_HEADERS"] = "Content-Type"
prod_logger = logging.getLogger("PROD")
dev_logger = logging.getLogger("DEV")
app_logger = logging.getLogger("app")
root_logger = logging.getLogger("root")
app_logger.propagate = False
root_logger.propagate = False
# loggers = [logging.getLogger(name) for name in logging.root.manager.loggerDict]
# for logger in loggers:
# print(logger)
print(f'ENV is set to: {app.config["ENV"]}')
if app.config["ENV"] == "production":
app.config.from_object("config.ProductionConfig")
prod_log_handler = logging.FileHandler("prod.log")
# prod_log_handler = logging.StreamHandler(sys.stdout)
### Add a formatter
prod_formatter = logging.Formatter(
"%(asctime)s - [%(levelname)s] %(message)s", "%d/%m/%Y %H:%M:%S"
)
prod_log_handler.setFormatter(prod_formatter)
prod_logger.addHandler(prod_log_handler)
prod_logger.setLevel(logging.INFO)
# Prevent DEV logger from output
dev_logger.propagate = False
# Update bioschemas profile when starting server in production
# update_profiles()
else:
app.config.from_object("config.DevelopmentConfig")
dev_log_handler = logging.StreamHandler()
### Add a formatter
dev_formatter = logging.Formatter(
"[%(name)s-%(levelname)s][%(filename)s-%(lineno)d] - %(message)s",
)
dev_log_handler.setFormatter(dev_formatter)
dev_logger.addHandler(dev_log_handler)
dev_logger.setLevel(logging.DEBUG)
# Prevent PROD logger from output
prod_logger.propagate = False
# dev_logger.warning("Watch out dev!")
# dev_logger.info("I told you so dev")
# dev_logger.debug("DEBUG dev")
#
# prod_logger.warning("Watch out prod!")
# prod_logger.info("I told you so prod")
# prod_logger.debug("DEBUG prod")
api = Api(
app=app,
title="FAIR-Checker API",
doc="/swagger",
base_path="https://fair-checker.france-bioinformatique.fr",
# base_url=app.config["SERVER_IP"],
description=app.config["SERVER_IP"],
# url_scheme="https://fair-checker.france-bioinformatique.fr/",
)
# app.register_blueprint(blueprint)
metrics_namespace = api.namespace("metrics", description="Metrics assessment")
fc_check_namespace = api.namespace(
"api/check", description="FAIR Metrics assessment from Check"
)
fc_inspect_namespace = api.namespace(
"api/inspect", description="FAIR improvement from Inspect"
)
cache = Cache(app)
socketio = SocketIO(app)
socketio.init_app(app, cors_allowed_origins="*", async_mode="eventlet")
app.secret_key = secrets.token_urlsafe(16)
sample_resources = {
"Examples": [
{
"text": "Dataset Dataverse",
"url": "https://data.inrae.fr/dataset.xhtml?persistentId=doi:10.15454/P27LDX",
},
{
"text": "Workflow",
"url": "https://workflowhub.eu/workflows/18", # Workflow in WorkflowHub
},
{
"text": "Publication Datacite",
"url": "https://search.datacite.org/works/10.7892/boris.108387", # Publication in Datacite
},
{
"text": "Dataset",
"url": "https://doi.pangaea.de/10.1594/PANGAEA.914331", # dataset in PANGAEA
},
{
"text": "Tool",
"url": "https://bio.tools/jaspar",
},
],
}
metrics = [
{"name": "f1", "category": "F", "description": "F1 verifies that ... "},
{"name": "f2", "category": "F", "description": "F2 verifies that ... "},
{"name": "f3", "category": "F", "description": "F3 verifies that ... "},
{"name": "a1", "category": "A"},
{"name": "a2", "category": "A"},
]
# Load bs profils dict (from github if not already in local)
load_profiles()
METRICS = {}
# json_metrics = test_metric.getMetrics()
factory = FAIRMetricsFactory()
# # A DEPLACER AU LANCEMENT DU SERVEUR ######
# METRICS_RES = test_metric.getMetrics()
METRICS_CUSTOM = factory.get_FC_metrics()
for i, key in enumerate(METRICS_CUSTOM):
METRICS_CUSTOM[key].set_id("FC_" + str(i))
KGS = {}
RDF_TYPE = {}
FILE_UUID = ""
DICT_TEMP_RES = {}
# Get status from bioportal external service
try:
STATUS_BIOPORTAL = requests.head("https://bioportal.bioontology.org/").status_code
except ConnectionError:
STATUS_BIOPORTAL = 0
# Get statust from OLS external service
try:
STATUS_OLS = requests.head("https://www.ebi.ac.uk/ols4/index").status_code
except ConnectionError:
STATUS_OLS = 0
# Get statust from LOV external service
try:
STATUS_LOV = requests.head(
"https://lov.linkeddata.es/dataset/lov/sparql"
).status_code
except ConnectionError:
STATUS_LOV = 0
DICT_BANNER_INFO = {"banner_message_info": {}}
# Update banner info with the message in .env
@app.context_processor
def display_info():
global DICT_BANNER_INFO
try:
env_banner_info = dotenv_values(".env")["BANNER_INFO"]
except KeyError:
dev_logger.warning(
"BANNER_INFO is not set in .env (e.g. BANNER_INFO='Write your message here')"
)
DICT_BANNER_INFO["banner_message_info"].pop("env_info", None)
return DICT_BANNER_INFO
if env_banner_info != "":
DICT_BANNER_INFO["banner_message_info"]["env_info"] = env_banner_info
else:
DICT_BANNER_INFO["banner_message_info"].pop("env_info", None)
return DICT_BANNER_INFO
def update_vocab_status():
global DICT_BANNER_INFO, STATUS_BIOPORTAL, STATUS_OLS, STATUS_LOV
STATUS_BIOPORTAL = requests.head("https://bioportal.bioontology.org/").status_code
STATUS_OLS = requests.head("https://www.ebi.ac.uk/ols4/index").status_code
STATUS_LOV = requests.head(
"https://lov.linkeddata.es/dataset/lov/sparql"
).status_code
if STATUS_BIOPORTAL != 200:
info_bioportal = "BioPortal might not be reachable. Status code: " + str(
STATUS_BIOPORTAL
)
DICT_BANNER_INFO["banner_message_info"]["status_bioportal"] = info_bioportal
else:
DICT_BANNER_INFO["banner_message_info"].pop("status_bioportal", None)
if STATUS_OLS != 200:
info_ols = "OLS might not be reachable. Status code: " + str(STATUS_OLS)
DICT_BANNER_INFO["banner_message_info"]["status_ols"] = info_ols
else:
DICT_BANNER_INFO["banner_message_info"].pop("status_ols", None)
if STATUS_LOV != 200:
info_lov = "LOV might not be reachable. Status code: " + str(STATUS_LOV)
DICT_BANNER_INFO["banner_message_info"]["status_lov"] = info_lov
else:
DICT_BANNER_INFO["banner_message_info"].pop("status_lov", None)
prod_logger.info("Updating banner status")
profiles = PROFILES
@app.context_processor
def display_vocab_status():
global DICT_BANNER_INFO
return DICT_BANNER_INFO
scheduler = BackgroundScheduler()
scheduler.add_job(func=update_vocab_status, trigger="interval", seconds=600)
scheduler.add_job(
func=F1B_Impl.update_identifiers_org_dump, trigger="interval", seconds=604800
)
scheduler.add_job(func=update_profiles, trigger="interval", seconds=604800)
scheduler.add_job(func=util.gen_usage_statistics, trigger="interval", seconds=10000)
scheduler.start()
# Shut down the scheduler when exiting the app
atexit.register(lambda: scheduler.shutdown())
@app.context_processor
def inject_app_version():
repo = git.Repo(".")
tags = sorted(repo.tags, key=lambda t: t.commit.committed_datetime)
latest_tag = tags[-1]
return dict(version_tag=latest_tag)
@app.context_processor
def inject_jsonld():
return dict(jld=buildJSONLD())
@app.route("/favicon.ico")
def favicon():
return send_from_directory(
os.path.join(app.root_path, "static"),
"favicon.ico",
mimetype="image/vnd.microsoft.icon",
)
@app.route("/docs/<path:filename>")
def documentation(filename):
return send_from_directory("docs/_build/html", filename)
@app.route("/")
def home():
return render_template(
# "index.html",
# title="FAIR-Checker",
# subtitle="Improve the FAIRness of your web resources",
)
@app.route("/about")
def about():
return render_template(
"about.html",
title="About us",
# subtitle="More about FAIR-Checker",
)
@app.route("/terms")
def terms():
return render_template(
"terms.html",
title="Terms of use",
)
@app.route("/statistics")
def statistics():
usage_stats = {}
with open("data/usage_stats.json", "r") as infile:
usage_stats = json.load(infile)
return render_template(
"statistics.html",
title="Statistics",
subtitle="Visualize usage statistics of FAIR-Checker",
evals_30=usage_stats["evals_30"],
success_30=usage_stats["success_30"],
failures_30=usage_stats["failures_30"],
f_success_30=usage_stats["f_success_30"],
f_failures_30=usage_stats["f_failures_30"],
a_success_30=usage_stats["a_success_30"],
a_failures_30=usage_stats["a_failures_30"],
i_success_30=usage_stats["i_success_30"],
i_failures_30=usage_stats["i_failures_30"],
r_success_30=usage_stats["r_success_30"],
r_failures_30=usage_stats["r_failures_30"],
total_monthly=usage_stats["total_monthly"],
)
reqparse = reqparse.RequestParser()
reqparse.add_argument(
"url",
type=str,
required=True,
location="args",
help="The URL/DOI of the resource to be evaluated",
)
def generate_check_api(metric):
@fc_check_namespace.route("/metric_" + metric.get_principle_tag())
class MetricEval(Resource):
@fc_check_namespace.doc(
"Evaluate " + metric.get_principle_tag() + " FAIR metric"
)
@fc_check_namespace.expect(reqparse)
def get(self):
args = reqparse.parse_args()
url = args["url"]
web_res = WebResource(url)
metric.set_web_resource(web_res)
result = metric.evaluate()
data = {
"metric": result.get_metrics(),
"score": result.get_score(),
"target_uri": result.get_target_uri(),
"eval_time": str(result.get_test_time()),
"recommendation": result.get_recommendation(),
"comment": result.get_log(),
}
result.persist(str(SOURCE.API))
return data
get.__doc__ = metric.get_name()
MetricEval.__name__ = MetricEval.__name__ + metric.get_principle_tag()
for key in METRICS_CUSTOM.keys():
generate_check_api(METRICS_CUSTOM[key])
@app.route("/data/<ID>")
def derefLD(ID):
mimetype = None
if "Content-Type" in request.headers:
mimetype = request.headers["Content-Type"].split(";")[0]
try:
client = MongoClient()
db = client.fair_checker
evaluations = db.evaluations
eval_json = evaluations.find_one({"_id": ObjectId(ID)})
e = Evaluation()
e.build_from_json(data=eval_json)
ttl = e.to_rdf_turtle(id=ID)
kg = ConjunctiveGraph()
try:
kg.parse(data=ttl, format="turtle")
except Exception:
return Response(
"Error while parsing RDF:\n\n" + e.to_rdf_turtle(id=ID), mimetype="text"
)
if mimetype == "application/json":
return Response(kg.serialize(format="json-ld"), mimetype="application/json")
elif mimetype == "application/ld+json":
return Response(
kg.serialize(format="json-ld"), mimetype="application/ld+json"
)
elif mimetype == "application/rdf+xml":
return Response(kg.serialize(format="xml"), mimetype="application/rdf+xml")
elif mimetype == "text/n3":
return Response(kg.serialize(format="nt"), mimetype="text/n3")
elif mimetype == "text/nt":
return Response(kg.serialize(format="nt"), mimetype="text/n3")
elif mimetype == "text/turtle":
return Response(kg.serialize(format="turtle"), mimetype="text/turtle")
else:
return Response(kg.serialize(format="turtle"), mimetype="text/turtle")
except InvalidId:
return Response(f"Cannot find evaluation {ID}", mimetype="text")
# Generate machine readable FAIR assessment report
@app.route("/assessment/<ID>")
def deref_assessment_LD(ID):
mimetype = None
if "Content-Type" in request.headers:
mimetype = request.headers["Content-Type"].split(";")[0]
try:
client = MongoClient()
db = client.fair_checker
assessments = db.assessments
assess_json = assessments.find_one({"_id": ObjectId(ID)})
target_url = assess_json["target_url"]
score = assess_json["score"]
evals = assess_json["wasDerivedFrom"]
genAtTime = assess_json["generatedAtTime"]
print(target_url)
print(score)
print(evals)
prefix = """
@prefix daq: <http://purl.org/eis/vocab/daq#> .
@prefix dcat: <http://www.w3.org/ns/dcat#> .
@prefix dcterms: <http://purl.org/dc/terms/> .
@prefix dqv: <http://www.w3.org/ns/dqv#> .
@prefix duv: <http://www.w3.org/ns/duv#> .
@prefix oa: <http://www.w3.org/ns/oa#> .
@prefix prov: <http://www.w3.org/ns/prov#> .
@prefix sdmx-attribute: <http://purl.org/linked-data/sdmx/2009/attribute#> .
@prefix skos: <http://www.w3.org/2004/02/skos/core#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix : <https://fair-checker.france-bioinformatique.fr/data/> .
"""
assess_tpl = """
:$id
a dqv:QualityMeasurement ;
dqv:computedOn <$url> ;
dqv:value "$value"^^xsd:integer ;
prov:generatedAtTime "$date"^^xsd:dateTime ;
prov:wasAttributedTo <https://github.com/IFB-ElixirFr/fair-checker> ;
prov:wasDerivedFrom $evaluations ;
rdfs:seeAlso <https://doi.org/10.1186/s13326-023-00289-5> ."""
assess_ttl = Template(assess_tpl).safe_substitute(
id=str(ID),
url=target_url,
value=score,
date=genAtTime.isoformat(),
evaluations="<" + ">, <".join(evals) + ">",
)
ttl = prefix + assess_ttl
print(ttl)
kg = ConjunctiveGraph()
try:
kg.parse(data=ttl, format="turtle")
except Exception:
return Response("Error while parsing RDF:\n\n" + ttl, mimetype="text")
if mimetype == "application/json":
return Response(kg.serialize(format="json-ld"), mimetype="application/json")
elif mimetype == "application/ld+json":
return Response(
kg.serialize(format="json-ld"), mimetype="application/ld+json"
)
elif mimetype == "application/rdf+xml":
return Response(kg.serialize(format="xml"), mimetype="application/rdf+xml")
elif mimetype == "text/n3":
return Response(kg.serialize(format="n3"), mimetype="text/n3")
elif mimetype == "text/turtle":
return Response(kg.serialize(format="turtle"), mimetype="text/turtle")
else:
return Response(kg.serialize(format="turtle"), mimetype="text/turtle")
except InvalidId:
return Response(f"Cannot find evaluation {ID}", mimetype="text")
@fc_check_namespace.route("/metrics_all")
class MetricEvalAll(Resource):
@fc_check_namespace.doc(
"Evaluates all FAIR metrics at once, and produces a JSON-LD output based on the DQV and PROV ontologies"
)
@fc_check_namespace.expect(reqparse)
def get(self):
"""All FAIR metrics, producing a JSON-LD output"""
args = reqparse.parse_args()
url = args["url"]
web_res = WebResource(url)
metrics_collection = []
for metric_key in METRICS_CUSTOM.keys():
metric = METRICS_CUSTOM[metric_key]
metric.set_web_resource(web_res)
metrics_collection.append(metric)
results = []
kg = ConjunctiveGraph()
for metric in metrics_collection:
result = metric.evaluate()
data = {
"metric": result.get_metrics(),
"score": result.get_score(),
"target_uri": result.get_target_uri(),
"eval_time": str(result.get_test_time()),
"recommendation": result.get_recommendation(),
"comment": result.get_log(),
}
r = result.persist(str(SOURCE.API))
kg.parse(data=result.to_rdf_turtle(id=r.inserted_id), format="turtle")
results.append(data)
# print(kg.serialize(format="turtle"))
json_str = kg.serialize(format="json-ld", indent=4)
json_obj = json.loads(json_str)
return json_obj
@fc_check_namespace.route("/legacy/metrics_all")
class MetricEvalAllLegacy(Resource):
@fc_check_namespace.doc(
"Evaluates all FAIR metrics at once, and produces a JSON output"
)
@fc_check_namespace.expect(reqparse)
def get(self):
"""All FAIR metrics (legacy)"""
args = reqparse.parse_args()
url = args["url"]
web_res = WebResource(url)
metrics_collection = []
for metric_key in METRICS_CUSTOM.keys():
metric = METRICS_CUSTOM[metric_key]
metric.set_web_resource(web_res)
metrics_collection.append(metric)
results = []
for metric in metrics_collection:
result = metric.evaluate()
data = {
"metric": result.get_metrics(),
"score": result.get_score(),
"target_uri": result.get_target_uri(),
"eval_time": str(result.get_test_time()),
"recommendation": result.get_recommendation(),
"comment": result.get_log(),
}
result.persist(str(SOURCE.API))
results.append(data)
return results
# fc_check_namespace.add_resource(MetricEvalAll, "/metrics_all")
@fc_inspect_namespace.route("/get_rdf_metadata")
class RetrieveMetadata(Resource):
@fc_inspect_namespace.produces(["application/ld+json"])
@fc_inspect_namespace.expect(reqparse)
def get(self):
"""Get RDF metadata in JSON-LD from a web resource"""
args = reqparse.parse_args()
url = args["url"]
eval = Evaluation()
eval.set_start_time()
eval.set_target_uri(url)
eval.set_reason("metadata harvesting, success score == metadata size")
web_res = WebResource(url)
kg = web_res.get_rdf()
size = len(kg)
data_str = kg.serialize(format="json-ld")
data_json = json.loads(data_str)
eval.set_score(size)
eval.set_end_time()
eval.persist(source="API")
return data_json
describe_list = [
util.describe_opencitation,
util.describe_wikidata,
util.describe_openaire,
]
jsonld_example = '{"@context":"http://schema.org","@type":"ScholarlyArticle","@id":"https://doi.org/10.7892/boris.108387","url":"https://boris.unibe.ch/108387/","name":"Diagnostic value of contrast-enhanced magnetic resonance angiography in large-vessel vasculitis.","author":[{"name":"Sabine Adler","givenName":"Sabine","familyName":"Adler","@type":"Person"},{"name":"Marco Sprecher","givenName":"Marco","familyName":"Sprecher","@type":"Person"},{"name":"Felix Wermelinger","givenName":"Felix","familyName":"Wermelinger","@type":"Person"},{"name":"Thorsten Klink","givenName":"Thorsten","familyName":"Klink","@type":"Person"},{"name":"Harald Marcel Bonel","givenName":"Harald Marcel","familyName":"Bonel","@type":"Person"},{"name":"Peter M Villiger","givenName":"Peter M","familyName":"Villiger","@type":"Person"}],"description":"OBJECTIVE To evaluate contrast-enhanced magnetic resonance angiography (MRA) in diagnosis of inflammatory aortic involvement in patients with clinical suspicion of large-vessel vasculitis. PATIENTS AND METHODS Seventy-five patients, mean age 62 years (range 16-82 years), 44 female and 31 male, underwent gadolinium-enhanced MRA and were evaluated retrospectively. Thoracic MRA was performed in 32 patients, abdominal MRA in 7 patients and both thoracic and abdominal MRA in 36 patients. Temporal arterial biopsies were obtained from 22/75 patients. MRA positivity was defined as increased aortic wall signal in late gadolinium-enhanced axial turbo inversion recovery magnitude (TIRM) series. The influence of prior glucocorticoid intake on MRA outcome was evaluated. RESULTS MRA was positive in 24/75 patients, with lesions located in the thorax in 7 patients, the abdomen in 5 and in both thorax and abdomen in 12. Probability for positive MRA after glucocorticoid intake for more than 5 days before MRA was reduced by 89.3%. Histology was negative in 3/10 MRA-positive patients and positive in 5/12 MRA-negative patients. All 5/12 histology positive / MRA-negative patients had glucocorticoids for >5 days prior to MRA and were diagnosed as having vasculitis. Positive predictive value for MRA was 92%, negative predictive value was 88%. CONCLUSIONS Contrast-enhanced MRA reliably identifies large vessel vasculitis. Vasculitic signals in MRA are very sensitive to glucocorticoids, suggesting that MRA should be done before glucocorticoid treatment.","keywords":"610 Medicine & health","inLanguage":"en","encodingFormat":"application/pdf","datePublished":"2017","schemaVersion":"http://datacite.org/schema/kernel-4","publisher":{"@type":"Organization","name":"EMH Schweizerischer Ärzteverlag"},"provider":{"@type":"Organization","name":"datacite"}}'
""" Model for documenting the API"""
graph_payload = fc_inspect_namespace.model(
"graph_payload",
{
"url": fields.Url(
description="URL of the resource to be enriched", required=True
),
"json-ld": fields.String(
description="RDF graph in JSON-LD", required=True, exemple="JSON-LD string"
),
},
)
def generate_ask_api(describe):
@fc_inspect_namespace.route("/" + describe.__name__, methods=["GET"])
@fc_inspect_namespace.route("/" + describe.__name__ + "/", methods=["POST"])
# @api.doc(params={"url": "An URL"})
class Ask(Resource):
@fc_inspect_namespace.expect(reqparse)
def get(self):
args = reqparse.parse_args()
url = args["url"]
web_res = WebResource(url)
kg = web_res.get_rdf()
old_kg = copy.deepcopy(kg)
if util.is_DOI(url):
url = util.get_DOI(url)
new_kg = describe(url, old_kg)
triples_before = len(kg)
triples_after = len(new_kg)
data = {
"triples_before": triples_before,
"triples_after": triples_after,
"@graph": json.loads(new_kg.serialize(format="json-ld")),
}
return data
get.__doc__ = (
"Retrieve RDF metadata from URL and try to enrich it with SPARQL request"
)
@fc_inspect_namespace.expect(graph_payload)
def post(self):
json_data = request.get_json(force=True)
url = json_data["url"]
kg = ConjunctiveGraph()
kg.parse(data=json_data["json-ld"], format="json-ld")
old_kg = copy.deepcopy(kg)
if util.is_DOI(url):
url = util.get_DOI(url)
new_kg = describe(url, old_kg)
triples_before = len(kg)
triples_after = len(new_kg)
data = {
"triples_before": triples_before,
"triples_after": triples_after,
"@graph": json.loads(new_kg.serialize(format="json-ld")),
}
return data
post.__doc__ = "Try to enrich RDF metadata with SPARQL request"
Ask.__name__ = Ask.__name__ + describe.__name__.capitalize()
for describe in describe_list:
generate_ask_api(describe)
@fc_inspect_namespace.route("/inspect_ontologies")
class InspectOntologies(Resource):
# @fc_inspect_namespace.doc('Evaluates all FAIR metrics at once')
@fc_inspect_namespace.expect(reqparse)
def get(self):
"""Inspect if RDF properties and classes are found in ontology registries (OLS, LOV, BioPortal)"""
args = reqparse.parse_args()
url = args["url"]
web_res = WebResource(url)
kg = web_res.get_rdf()
return inspect_onto_reg(kg, False)
def suggest_profile(kg):
entities = util.list_all_instances(kg)
results = {}
final_results = []
for e in entities:
sub_kg = ConjunctiveGraph()
for s, p, o in kg.triples((e, None, None)):
sub_kg.add((s, p, o))
has_matching_profile = False
for p_name in profiles.keys():
profile = profiles[p_name]
sim = profile.compute_similarity(sub_kg)
# sim = profile.compute_loose_similarity(kg)
results[p_name] = {"score": sim, "ref": profile.get_name()}
if sim > 0:
# print(f"closests_profile({e},{p_name}) = {sim}")
has_matching_profile = True
sorted_results = dict(
sorted(
results.items(),
key=lambda item: item[1]["score"],
reverse=True,
)
)
if has_matching_profile:
for hit in sorted_results.keys():
if sorted_results[hit]["score"] > 0:
final_results.append(
{
"entity": str(e),
"profile_name": sorted_results[hit]["ref"],
"score": sorted_results[hit]["score"],
"profile_url": hit,
}
)
res_sorted = sorted(final_results, key=lambda item: item["score"], reverse=True)
return res_sorted
@fc_inspect_namespace.route("/suggest_profile")
class SuggestBioschemasProfile(Resource):
@fc_inspect_namespace.expect(reqparse)
def get(self):
"""Validate an RDF JSON-LD graph against Bioschemas profiles"""
args = reqparse.parse_args()
url = args["url"]
eval = Evaluation()
eval.set_start_time()
eval.set_target_uri(url)
eval.set_reason("profile recommendation")
web_res = WebResource(url)
kg = web_res.get_rdf()
results = suggest_profile(kg)
eval.set_end_time()
eval.persist(source="API")
return results
# TODO update method
@fc_inspect_namespace.route("/bioschemas_validation")
class InspectBioschemas(Resource):
@fc_inspect_namespace.expect(reqparse)
def get(self):
"""Validate an RDF JSON-LD graph against Bioschemas profiles"""
args = reqparse.parse_args()
url = args["url"]
eval = Evaluation()
eval.set_start_time()
eval.set_target_uri(url)
eval.set_reason("bioschemas metadata validation")
web_res = WebResource(url)
kg = web_res.get_rdf()
results = {}
# Evaluate only profile with conformsTo
results_conformsto = dyn_evaluate_profile_with_conformsto(kg)
# Try to match and evaluate all found corresponding profiles
results_type = evaluate_profile_from_type(kg)
for result_key in results_conformsto.keys():
results[result_key] = results_conformsto[result_key]
for result_key in results_type.keys():
if result_key not in results:
results[result_key] = results_type[result_key]
eval.set_end_time()
eval.persist(source="API")
# TODO Try similarity match her for profiles that are not matched
return results
@fc_inspect_namespace.route("/bioschemas_validation_by_conformsto")
class InspectBioschemasConformsTo(Resource):
@fc_inspect_namespace.expect(reqparse)
def get(self):
"""Validate an RDF JSON-LD graph against Bioschemas profiles using dct:conformsTo"""
args = reqparse.parse_args()
url = args["url"]
eval = Evaluation()
eval.set_start_time()
eval.set_target_uri(url)
eval.set_reason("bioschemas metadata validation (from conforms_to)")
web_res = WebResource(url)
kg = web_res.get_rdf()
# Evaluate only profile with conformsTo
results_conformsto = dyn_evaluate_profile_with_conformsto(kg)
# TODO Try similarity match her for profiles that are not matched
eval.set_end_time()
eval.persist(source="API")
return results_conformsto
@fc_inspect_namespace.route("/bioschemas_validation_by_types")
class InspectBioschemasTypesMatch(Resource):
@fc_inspect_namespace.expect(reqparse)
def get(self):
"""Validate an RDF JSON-LD graph against Bioschemas profiles using types"""
args = reqparse.parse_args()
url = args["url"]
eval = Evaluation()
eval.set_start_time()
eval.set_target_uri(url)
eval.set_reason("bioschemas metadata validation (from types)")
web_res = WebResource(url)
kg = web_res.get_rdf()
# Try to match and evaluate all found corresponding profiles
results_type = evaluate_profile_from_type(kg)
eval.set_end_time()
eval.persist(source="API")
# TODO Try similarity match her for profiles that are not matched
return results_type
def list_routes():
return ["%s" % rule for rule in app.url_map.iter_rules()]
# def has_no_empty_params(rule):
# defaults = rule.defaults if rule.defaults is not None else ()
# arguments = rule.arguments if rule.arguments is not None else ()
# return len(defaults) >= len(arguments)
# @app.route("/site-map")
# def site_map():
# links = []
# for rule in app.url_map.iter_rules():
# # Filter out rules we can't navigate to in a browser
# # and rules that require parameters
# if "GET" in rule.methods and has_no_empty_params(rule):
# url = url_for(rule.endpoint, **(rule.defaults or {}))
# links.append((url, rule.endpoint))
# # links is now a list of url, endpoint tuples
# return render_template("site_map.html", links=links)
@socketio.on("webresource")
def handle_webresource(url):
dev_logger.info("A new url to retrieve metadata from !")
@socketio.on("evaluate_metric")
def handle_metric(json):
"""
socketio Handler for a metric calculation requests, calling FAIRMetrics API.
emit the result of the test
@param json dict Contains the necessary informations to execute evaluate a metric.
"""