forked from jacobvsdanniel/pubmedkb_web
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.py
3278 lines (2645 loc) · 101 KB
/
server.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 csv
import sys
import copy
import html
import json
import time
import asyncio
import logging
import traceback
import urllib.parse
from collections import defaultdict
from flask import Flask, render_template, request, stream_with_context
from kb_utils import query_variant, NEN, V2G, NCBIGene, VariantNEN, KB, PaperKB, GeVarToGLOF, Meta
from kb_utils import GVDScore, GDScore, DiseaseToGene
from kb_utils import MESHNameKB, MESHGraph, MESHChemical, ChemicalDiseaseKB
from kb_utils import ner_gvdc_mapping, entity_type_to_real_type_mapping
from kb_utils import get_paper_meta_html
from summary_utils import Summary
from VarSum_germline import GermlineVarSum
try:
import gpt_utils
from gpt_utils import PaperGPT, ReviewGPT
except ModuleNotFoundError:
pass
from kb_utils import QA, run_paper_qa
app = Flask(__name__)
logger = logging.getLogger(__name__)
logging.basicConfig(
format="%(asctime)s - %(process)d - %(name)s - %(message)s",
datefmt="%Y/%m/%d %H:%M:%S",
level=logging.INFO,
force=True,
)
csv.register_dialect(
"csv", delimiter=",", quoting=csv.QUOTE_MINIMAL, quotechar='"', doublequote=True,
escapechar=None, lineterminator="\n", skipinitialspace=False,
)
csv.register_dialect(
"tsv", delimiter="\t", quoting=csv.QUOTE_NONE, quotechar=None, doublequote=False,
escapechar=None, lineterminator="\n", skipinitialspace=False,
)
nen = NEN(None)
v2g = V2G(None, None)
ncbi_gene = NCBIGene(None)
variant_nen = VariantNEN(None)
kb = KB(None)
kb_meta = Meta(None)
paper_nen = PaperKB(None)
paper_glof = PaperKB(None)
entity_glof = GeVarToGLOF(None)
gvd_score = GVDScore(None)
gd_score = GDScore(None)
gd_db = GVDScore(None)
disease_to_gene = DiseaseToGene()
mesh_name_kb = MESHNameKB(None)
mesh_graph = MESHGraph(None)
mesh_chemical = MESHChemical(None)
chemical_disease_kb = ChemicalDiseaseKB(None)
qa = QA(None)
kb_type = None
show_aid = False
@app.route("/")
def serve_base():
return render_template("base.html")
@app.route("/home")
def serve_home():
return render_template("home.html")
@app.route("/name_to_id_alias")
def serve_name_to_id_alias():
return render_template("name_to_id_alias.html")
@app.route("/var")
def serve_var():
return render_template("var.html")
@app.route("/rel")
def serve_rel():
return render_template("rel.html")
@app.route("/paper")
def serve_paper():
return render_template("paper.html")
@app.route("/rs_hgvs_gene")
def serve_rs_hgvs_gene():
return render_template("rs_hgvs_gene.html")
@app.route("/pmid_glof")
def serve_pmid_glof():
return render_template("pmid_glof.html")
@app.route("/ent_glof")
def serve_ent_glof():
return render_template("ent_glof.html")
@app.route("/id_to_name")
def serve_id_to_name():
return render_template("id_to_name.html")
@app.route("/varsum")
def serve_varsum():
return render_template("varsum.html")
@app.route("/litsum")
def serve_litsum():
return render_template("litsum.html")
@app.route("/gvd_stats")
def serve_gvd_stats():
return render_template("gvd_stats.html")
@app.route("/gd_db")
def serve_gd_db():
return render_template("gd_db.html")
@app.route("/disease_to_gene")
def serve_disease_to_gene():
return render_template("disease_to_gene.html")
@app.route("/mesh_disease")
def serve_mesh_disease():
return render_template("mesh_disease.html")
@app.route("/mesh_chemical")
def serve_mesh_chemical():
return render_template("mesh_chemical.html")
@app.route("/chemical_disease")
def serve_chemical_disease():
return render_template("chemical_disease.html")
@app.route("/chemical_disease_qa")
def serve_chemical_disease_qa():
return render_template("chemical_disease_qa.html")
@app.route("/question_to_paper")
def serve_question_to_paper():
return render_template("question_to_paper.html")
@app.route("/qa")
def serve_qa():
return render_template("qa.html")
@app.route("/yolo")
def serve_yolo():
return render_template("yolo.html")
@app.route("/run_name_to_id_alias", methods=["POST"])
def run_name_to_id_alias():
data = json.loads(request.data)
query = data["query"].strip()
case_sensitive = data["case_sensitive"] == "Y"
max_length_diff = int(data["max_length_diff"])
min_similarity = float(data["min_similarity"])
max_names = int(data["max_names"])
max_aliases = int(data["max_aliases"])
logger.info(
f"query={query}"
f" case_sensitive={case_sensitive}"
f" max_length_diff={max_length_diff}"
f" min_similarity_ratio={min_similarity}"
f" max_aliases={max_aliases}"
)
name_similarity_list = nen.get_names_by_query(
query,
case_sensitive=case_sensitive,
max_length_diff=max_length_diff,
min_similarity=min_similarity,
max_names=max_names,
)
names = len(name_similarity_list)
logger.info(f"{names:,} names")
result = ""
for name, similarity in name_similarity_list:
# name
logger.info(f"name: {name}, similarity: {similarity}")
caption_html = html.escape(f"Name: {name}") + " " * 4 + html.escape(f"Similarity: {similarity:.0%}")
result += f"<label style='font-size: 22px;'>{caption_html}</label><br /><br />"
# id
type_id_frequency_list = nen.get_ids_by_name(name)
ids = len(type_id_frequency_list)
logger.info(f"ids: {ids}")
table_html = \
f"<table><tr>" \
f"<th>Type</th>" \
f"<th>ID</th>" \
f"<th>Frequency of (Type, ID, Name) in all texts</th>" \
f"<th>Top {max_aliases:,} aliases by frequency of (Type, ID, Alias) in all texts</th>" \
f"</tr>"
# alias
for _type, _id, id_frequency in type_id_frequency_list:
alias_frequency_list = nen.get_aliases_by_id(_type, _id, max_aliases=max_aliases)
# logger.info(f"({_type}, {_id}, {name}, {id_frequency}): alias_list={alias_frequency_list}")
type_html = html.escape(_type)
id_html = html.escape(_id)
id_frequency_html = html.escape(f"{id_frequency:,}")
table_html += \
f"<tr>" \
f"<td>{type_html}</td>" \
f"<td>{id_html}</td>" \
f"<td>{id_frequency_html}</td>" \
f"<td>"
for alias, alias_frequency in alias_frequency_list:
alias_html = html.escape(f"{alias} ({alias_frequency:,})")
table_html += " " + alias_html
table_html += "</td></tr>"
table_html += "</table>"
result += table_html + "<br /><br /><br />"
response = {"result": result}
return json.dumps(response)
@app.route("/query_name_to_id_alias")
def query_name_to_id_alias():
response = {}
# url argument
query = request.args.get("query")
case_sensitive = request.args.get("case_sensitive")
max_length_diff = request.args.get("max_length_diff")
min_similarity = request.args.get("min_similarity")
max_names = request.args.get("max_names")
max_aliases = request.args.get("max_aliases")
response["url_argument"] = {
"query": query,
"case_sensitive": case_sensitive,
"max_length_diff": max_length_diff,
"min_similarity": min_similarity,
"max_names": max_names,
"max_aliases": max_aliases,
}
query = query.strip()
case_sensitive = case_sensitive == "Y"
max_length_diff = int(max_length_diff)
min_similarity = float(min_similarity)
max_names = int(max_names)
max_aliases = int(max_aliases)
logger.info(
f"query={query}"
f" case_sensitive={case_sensitive}"
f" max_length_diff={max_length_diff}"
f" min_similarity_ratio={min_similarity}"
f" max_aliases={max_aliases}"
)
# name matches
name_similarity_list = nen.get_names_by_query(
query,
case_sensitive=case_sensitive,
max_length_diff=max_length_diff,
min_similarity=min_similarity,
max_names=max_names,
)
names = len(name_similarity_list)
logger.info(f"{names:,} names")
response["match_list"] = []
for name, similarity in name_similarity_list:
match = {
"name": name,
"similarity": similarity,
"type_id_alias_list": [],
}
logger.info(f"name: {name}, similarity: {similarity}")
# id
type_id_frequency_list = nen.get_ids_by_name(name)
ids = len(type_id_frequency_list)
logger.info(f"ids: {ids}")
for _type, _id, id_frequency in type_id_frequency_list:
type_id_alias = {
"type": _type,
"id": _id,
"type_id_name_frequency": id_frequency,
}
# alias
alias_frequency_list = nen.get_aliases_by_id(_type, _id, max_aliases=max_aliases)
type_id_alias["alias_list"] = [
{
"alias": alias,
"type_id_alias_frequency": alias_frequency,
}
for alias, alias_frequency in alias_frequency_list
]
match["type_id_alias_list"].append(type_id_alias)
# logger.info(f"({_type}, {_id}, {name}, {id_frequency}): alias_list={alias_frequency_list}")
response["match_list"].append(match)
return json.dumps(response)
@app.route("/run_id_to_name", methods=["POST"])
def run_id_to_name():
arg = json.loads(request.data)
_type = arg.get("type", "").strip()
_id = arg.get("id", "").strip()
top_k = 20
logger.info(f"[query] type={_type} id={_id}")
# expand the umbrella type to real types and query KB
name_frequency_list = []
for _type in entity_type_to_real_type_mapping.get(_type, [_type]):
name_frequency_list += nen.get_aliases_by_id(_type, _id, max_aliases=top_k)
name_frequency_list = sorted(name_frequency_list, key=lambda nf: -nf[1])[:top_k]
# table html
table_html = f"<table><tr><th>Name</th><th>Frequency</th></tr>"
for name, frequency in name_frequency_list:
name_html = html.escape(name)
frequency_html = html.escape(f"{frequency:,}")
table_html += f"<tr><td>{name_html}</td><td>{frequency_html}</td></tr>"
table_html += "</table>"
result = table_html + "<br /><br /><br /><br /><br />"
response = {"result": result}
return json.dumps(response)
@app.route("/query_id_to_name")
def query_id_to_name():
arg = request.args
_type = arg.get("type", "")
_id = arg.get("id", "")
top_k = 20
response = {}
# url argument
_type = arg.get("type", "").strip()
_id = arg.get("id", "").strip()
response["url_argument"] = {
"type": _type,
"id": _id,
}
logger.info(f"[query] type={_type} id={_id}")
# expand the umbrella type to real types and query KB
name_frequency_list = []
for _type in entity_type_to_real_type_mapping.get(_type, [_type]):
name_frequency_list += nen.get_aliases_by_id(_type, _id, max_aliases=top_k)
name_frequency_list = sorted(name_frequency_list, key=lambda nf: -nf[1])[:top_k]
response["name_frequency_list"] = name_frequency_list
return json.dumps(response)
@app.route("/run_var", methods=["POST"])
def run_var():
data = json.loads(request.data)
query = data["query"].strip()
logger.info(f"query={query}")
extraction_list = query_variant(query)
result = ""
for extraction_id, (id_list, name_list, gene_list) in enumerate(extraction_list):
logger.info(f"{id_list} {name_list} {gene_list}")
caption_html = html.escape(f"Match #{extraction_id + 1}")
result += f"<label style='font-size: 22px;'>{caption_html}</label><br /><br />"
# attribute table
result += html.escape("Normalization:")
attribute_table_html = \
f"<table><tr>" \
f"<th>Attribute</th>" \
f"<th>Values</th>" \
f"</tr>"
for key, value in [("ID", id_list), ("Name", name_list), ("Gene", gene_list)]:
key_html = html.escape(f"{key}")
value_html = [html.escape(v) for v in value]
value_html = " ".join(value_html)
attribute_table_html += \
f"<tr>" \
f"<td>{key_html}</td>" \
f"<td>{value_html}</td>" \
f"</tr>"
attribute_table_html += "</table>"
result += attribute_table_html + "<br />"
# tuple table
result += html.escape("(Type, ID, Name) tuples with relations in current KB:")
type_id_name_frequency_list = nen.get_variant_in_kb(id_list, name_list)
tuples = len(type_id_name_frequency_list)
logger.info(f"tuples: {tuples}")
tuple_table_html = \
f"<table><tr>" \
f"<th>Type</th>" \
f"<th>ID</th>" \
f"<th>Name</th>" \
f"<th>Frequency in all texts</th>" \
f"</tr>"
for _type, _id, name, frequency in type_id_name_frequency_list:
logger.info(f"-> ({_type} {_id} {name}): {frequency}")
type_html = html.escape(_type)
id_html = html.escape(_id)
name_html = html.escape(name)
frequency_html = html.escape(f"{frequency:,}")
tuple_table_html += \
f"<tr>" \
f"<td>{type_html}</td>" \
f"<td>{id_html}</td>" \
f"<td>{name_html}</td>" \
f"<td>{frequency_html}</td>" \
f"</tr>"
tuple_table_html += "</table>"
result += tuple_table_html + "<br /><br /><br />"
response = {"result": result}
return json.dumps(response)
@app.route("/query_var")
def query_var():
response = {}
# url argument
query = request.args.get("query")
response["url_argument"] = {
"query": query,
}
query = query.strip()
logger.info(f"query={query}")
# variant matches
extraction_list = query_variant(query)
response["match_list"] = []
for extraction_id, (id_list, name_list, gene_list) in enumerate(extraction_list):
logger.info(f"{id_list} {name_list} {gene_list}")
match = {
"attribute": {},
"kb_entity_list": [],
}
# attribute
for key, value in [("id_list", id_list), ("name_list", name_list), ("gene_list", gene_list)]:
match["attribute"][key] = value
# tuple_in_kb
type_id_name_frequency_list = nen.get_variant_in_kb(id_list, name_list)
tuples = len(type_id_name_frequency_list)
logger.info(f"tuples: {tuples}")
for _type, _id, name, frequency in type_id_name_frequency_list:
match["kb_entity_list"].append({
"type": _type,
"id": _id,
"name": name,
"frequency_in_text": frequency,
})
response["match_list"].append(match)
return json.dumps(response)
@app.route("/run_rs_hgvs_gene", methods=["POST"])
def run_rs_hgvs_gene():
data = json.loads(request.data)
query = data["query"].strip()
logger.info(f"query={query}")
hgvs_to_frequency, rs_to_frequency, gene_to_frequency = v2g.query(query)
result = ""
table_html = \
f"<table><tr>" \
f"<th>Type</th>" \
f"<th>Name (Frequency)</th>" \
f"</tr>"
for key, value in [("HGVS", hgvs_to_frequency), ("RS#", rs_to_frequency), ("Gene", gene_to_frequency)]:
logger.info(f"[{key}] {value}")
key_html = html.escape(f"{key}")
value_html = [
html.escape(f"{name}") + " " + html.escape(f"({frequency:,})")
for name, frequency in value.items()
]
value_html = " ".join(value_html)
table_html += \
f"<tr>" \
f"<td>{key_html}</td>" \
f"<td>{value_html}</td>" \
f"</tr>"
table_html += "</table>"
result += table_html + "<br />"
response = {"result": result}
return json.dumps(response)
@app.route("/query_rs_hgvs_gene")
def query_rs_hgvs_gene():
response = {}
# url argument
query = request.args.get("query")
response["url_argument"] = {
"query": query,
}
query = query.strip()
logger.info(f"query={query}")
hgvs_to_frequency, rs_to_frequency, gene_to_frequency = v2g.query(query)
for key, value in [("HGVS", hgvs_to_frequency), ("RS#", rs_to_frequency), ("Gene", gene_to_frequency)]:
logger.info(f"[{key}] {value}")
response[key] = [
{"name": name, "frequency": frequency}
for name, frequency in value.items()
]
return json.dumps(response)
class Paper:
def __init__(self, pmid, aid_score_list):
self.pmid = pmid
self.meta = {}
self.aid_score_list = aid_score_list
self.sentence_index_to_sentence_mention = {}
self.annotator_to_relation = {}
self.relevance = 0
return
def get_relevance(self):
self.relevance = sum(score for _aid, score in self.aid_score_list)
return
def get_meta(self):
self.meta = kb_meta.get_meta_by_pmid(self.pmid)
return
def get_sentence_and_relation(self):
if kb_type == "relation":
annotator_list = ["rbert_cre", "odds_ratio", "spacy_ore", "openie_ore"]
else:
annotator_list = ["co_occurrence"]
annotator_to_relation = {annotator: [] for annotator in annotator_list}
sid_to_sentence_index = dict()
sentence_index_to_sentence_mention = dict()
for aid, _ann_score in self.aid_score_list:
sid, h_list, t_list, annotator, annotation = kb.get_annotation(aid)
# sentence and mention
if sid not in sid_to_sentence_index:
sentence_index, sentence, mention_list = kb.get_sentence(sid)
mention_list = [
{
"name": name,
"type": _type,
"id": id_list,
"offset": pos,
}
for name, _type, id_list, pos in mention_list
]
sid_to_sentence_index[sid] = sentence_index
sentence_index_to_sentence_mention[sentence_index] = {
"sentence": sentence,
"mention": mention_list,
}
sentence_index = sid_to_sentence_index[sid]
# relation
if annotator == "rbert_cre":
annotation = {
"relation": annotation[0],
"score": annotation[1],
}
elif annotator == "odds_ratio":
annotation = {
"OR": annotation[0],
"CI": annotation[1],
"p-value": annotation[2],
}
elif annotator in ["spacy_ore", "openie_ore"]:
annotation = {
"subject": annotation[0],
"predicate": annotation[1],
"object": annotation[2],
}
elif annotator == "co_occurrence":
pass
relation = {
"head_mention": h_list,
"tail_mention": t_list,
"annotation": annotation,
"sentence_index": sentence_index,
"annotation_id": aid,
}
annotator_to_relation[annotator].append(relation)
# sort cre relation by score
if "rbert_cre" in annotator_to_relation:
relation_list = annotator_to_relation["rbert_cre"]
score_list = [
float(relation_list[i]["annotation"]["score"][:-1])
for i in range(len(relation_list))
]
index_list = sorted(
range(len(relation_list)),
key=lambda i: score_list[i],
reverse=True,
)
annotator_to_relation["rbert_cre"] = [relation_list[i] for i in index_list]
self.sentence_index_to_sentence_mention = sentence_index_to_sentence_mention
self.annotator_to_relation = annotator_to_relation
return
class Rel:
def __init__(self, raw_arg):
str_arg = {}
for arg_name, arg_value in raw_arg.items():
if arg_value is None:
continue
arg_value = arg_value.strip()
if arg_value == "":
continue
str_arg[arg_name] = arg_value
self.raw_arg = raw_arg
self.str_arg = str_arg
self.arg = copy.deepcopy(str_arg)
self.paper_list = []
self.statistics = {}
self.text_summary = {}
self.html_summary = ""
return
def run_pipeline(self):
self.get_argument()
self.get_paper_annotation_id()
self.sort_papers_and_paginate()
self.get_paper_relation()
self.get_paper_meta()
self.get_statistics()
self.get_summary()
return
def run_no_pagination_get_statistics_pipeline(self):
self.get_argument()
self.get_paper_annotation_id()
return
def get_argument(self):
arg = self.arg
logger.info("[Query]")
# entity
for spec in ["e1_spec", "e2_spec"]:
if spec in arg:
arg[spec] = json.loads(arg[spec])
else:
arg[spec] = None
logger.info(f"{spec}: {arg[spec]}")
# pmid
if "pmid" not in arg:
arg["pmid"] = None
logger.info(f"pmid: {arg['pmid']}")
# pagination
try:
arg["paper_start"] = int(arg["paper_start"])
except (KeyError, ValueError):
arg["paper_start"] = None # slice from the first item
try:
arg["paper_end"] = int(arg["paper_end"])
except (KeyError, ValueError):
arg["paper_end"] = None # slice to the last item
logger.info(f"pagination: request papers in [{arg['paper_start']}, {arg['paper_end']})")
return
def get_paper_annotation_id(self):
arg = self.arg
# query paper and annotation id, score from kb
pmid_to_ann = kb.query_pmid_to_annotation_list(arg["e1_spec"], arg["e2_spec"], arg["pmid"])
papers = len(pmid_to_ann)
relations = sum(len(ann_list) for _pmid, ann_list in pmid_to_ann.items())
self.statistics["papers_before_pagination"] = papers
self.statistics["relations_before_pagination"] = relations
logger.info(f"Before pagination: {papers:,} papers; {relations:,} relations")
self.paper_list = [
Paper(pmid, aid_score_list)
for pmid, aid_score_list in pmid_to_ann.items()
]
return
def sort_papers_and_paginate(self):
arg = self.arg
paper_list = self.paper_list
if "paper_sort" in arg:
key_list = [(0, 0) for _ in paper_list]
if arg["paper_sort"] == "relevance":
for pi, paper in enumerate(paper_list):
paper.get_relevance()
key_list[pi] = (paper.relevance, int(paper.pmid))
elif arg["paper_sort"] == "citation":
for pi, paper in enumerate(paper_list):
paper.get_meta()
try:
citation = int(paper.meta["citation"])
except ValueError:
citation = 0
key_list[pi] = (citation, int(paper.pmid))
elif arg["paper_sort"] == "year":
for pi, paper in enumerate(paper_list):
paper.get_meta()
try:
year = int(paper.meta["year"])
except ValueError:
year = 0
key_list[pi] = (year, int(paper.pmid))
elif arg["paper_sort"] == "journal_impact":
for pi, paper in enumerate(paper_list):
paper.get_meta()
try:
journal_impact = float(paper.meta["journal_impact"])
except ValueError:
journal_impact = 0
key_list[pi] = (journal_impact, int(paper.pmid))
else:
assert False
pi_list = sorted(range(len(paper_list)), key=lambda _pi: key_list[_pi], reverse=True)
pi_list = pi_list[arg["paper_start"]:arg["paper_end"]]
paper_list = [paper_list[pi] for pi in pi_list]
else:
paper_list = paper_list[arg["paper_start"]:arg["paper_end"]]
self.paper_list = paper_list
return
def get_paper_relation(self):
for paper in self.paper_list:
paper.get_sentence_and_relation()
return
def get_paper_meta(self):
for paper in self.paper_list:
if not paper.meta:
paper.get_meta()
return
def get_statistics(self):
papers = len(self.paper_list)
sentences = 0
relations = 0
annotator_to_relations = defaultdict(lambda: 0)
for paper in self.paper_list:
sentences += len(paper.sentence_index_to_sentence_mention)
relations += len(paper.aid_score_list)
for annotator, relation_list in paper.annotator_to_relation.items():
annotator_to_relations[annotator] += len(relation_list)
self.statistics["papers"] = papers
self.statistics["sentences"] = sentences
self.statistics["relations"] = relations
log = "[statistics] "
for item, number in self.statistics.items():
log += f" {number:,} {item};"
logger.info(log[:-1])
self.statistics["annotator_to_relations"] = annotator_to_relations
log = "[statistics] relations: "
for annotator, relations in annotator_to_relations.items():
log += f" {relations:,} {annotator};"
logger.info(log[:-1])
return
def get_summary(self):
arg = self.arg
if kb_type == "relation" and self.paper_list:
try:
summary = Summary(self.paper_list, arg["e1_spec"], arg["e2_spec"], arg["pmid"])
summary.run_pipeline()
text_summary = summary.text_summary
html_summary = summary.html_summary
logger.info("[summary] created")
except Exception:
traceback.print_exc()
text_summary = {
"text": "No summary.",
"term_to_span": {},
}
html_summary = html.escape(text_summary["text"])
else:
text_summary = {
"text": "No summary.",
"term_to_span": {},
}
html_summary = html.escape(text_summary["text"])
html_summary = \
"<div style='font-size: 15px; color: #131523; line-height: 200%'>" \
"<span style='font-size: 17px'> " \
"Summary" \
"</span> " \
+ html_summary \
+ "</div>"
self.text_summary = text_summary
self.html_summary = html_summary
return
@app.route("/run_rel", methods=["POST"])
def run_rel():
raw_arg = json.loads(request.data)
rel = Rel(raw_arg)
rel.run_pipeline()
# statistics table
statistics_table_html = "<table>"
statistics_table_html += "<tr>"
for key, value in rel.statistics.items():
if key != "annotator_to_relations":
statistics_table_html += f"<th>{key}</th>"
else:
for annotator, _relations in value.items():
statistics_table_html += f"<th>{annotator}</th>"
statistics_table_html += "</tr>"
statistics_table_html += "<tr>"
for key, value in rel.statistics.items():
if key != "annotator_to_relations":
statistics_table_html += f"<td>{value:,}</td>"
else:
for _annotator, relations in value.items():
statistics_table_html += f"<td>{relations:,}</td>"
statistics_table_html += "</tr><table>"
# relation table
relation_table_html = \
f"<table><tr>" \
f'<th style="width:20%">Head</th>' \
f'<th style="width:20%">Tail</th>' \
f'<th style="width:5%">Annotator</th>' \
f'<th style="width:20%">Annotation</th>' \
f'<th style="width:5%">PMID</th>' \
f'<th style="width:30%">Sentence</th>' \
f"</tr>"
for paper in rel.paper_list:
pmid = paper.pmid
sentence_index_to_sentence_mention = paper.sentence_index_to_sentence_mention
annotator_to_relation = paper.annotator_to_relation
for annotator, relation_list in annotator_to_relation.items():
annotator_html = html.escape(annotator)
for relation in relation_list:
h_list = relation["head_mention"]
t_list = relation["tail_mention"]
annotation = relation["annotation"]
sentence_index = relation["sentence_index"]
aid = relation["annotation_id"]
sentence_data = sentence_index_to_sentence_mention[sentence_index]
sentence = sentence_data["sentence"]
mention_list = sentence_data["mention"]
head_type, head_id, head_name = set(), set(), set()
tail_type, tail_id, tail_name = set(), set(), set()
for mi in h_list:
mention = mention_list[mi]
head_type.add(mention["type"])
head_name.add(mention["name"])
for _id in mention["id"]:
head_id.add(_id)
for mi in t_list:
mention = mention_list[mi]
tail_type.add(mention["type"])
tail_name.add(mention["name"])
for _id in mention["id"]:
tail_id.add(_id)
head_type, head_id, head_name = sorted(head_type), sorted(head_id), sorted(head_name)
tail_type, tail_id, tail_name = sorted(tail_type), sorted(tail_id), sorted(tail_name)
head_type = "\n".join(head_type) + "\n"
head_id = "\n".join(head_id)
head_name = "\n".join(head_name) + "\n"
tail_type = "\n".join(tail_type) + "\n"
tail_id = "\n".join(tail_id)
tail_name = "\n".join(tail_name) + "\n"
head_type = html.escape(head_type)
head_id = html.escape(head_id)
head_name = html.escape(head_name)
tail_type = html.escape(tail_type)
tail_id = html.escape(tail_id)
tail_name = html.escape(tail_name)
head_html = f"<b>{head_name}</b>{head_type}<i>{head_id}</i>"
tail_html = f"<b>{tail_name}</b>{tail_type}<i>{tail_id}</i>"
pmid_html = f'<a href="https://pubmed.ncbi.nlm.nih.gov/{pmid}">{pmid}</a>'
if annotator == "rbert_cre":
annotation = f"{annotation['relation']}: {annotation['score']}"
elif annotator == "odds_ratio":
annotation = f"OR: {annotation['OR']}, CI: {annotation['CI']}, p-value: {annotation['p-value']}"
elif annotator in ["spacy_ore", "openie_ore"]:
annotation = f"{annotation['subject']}, {annotation['predicate']}, {annotation['object']}"
elif annotator == "co_occurrence":
annotation = str(annotation)
annotation_html = html.escape(annotation)
if isinstance(sentence, str):
section_type = "ABSTRACT"