forked from Sylvia-Liang/QAsparql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lcquad_answer.py
executable file
·178 lines (144 loc) · 6.19 KB
/
lcquad_answer.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
from parser.lc_quad_linked import LC_Qaud_Linked
from parser.lc_quad import LC_QaudParser
from common.container.sparql import SPARQL
from common.container.answerset import AnswerSet
from common.graph.graph import Graph
from common.utility.stats import Stats
from common.query.querybuilder import QueryBuilder
import common.utility.utility as utility
from linker.goldLinker import GoldLinker
from linker.earl import Earl
from learning.classifier.svmclassifier import SVMClassifier
import json
import argparse
import logging
import sys
import os
import numpy as np
def safe_div(x, y):
if y == 0:
return None
return x / y
def qg(linker, kb, parser, qapair, force_gold=True):
logger.info(qapair.sparql)
logger.info(qapair.question.text)
h1_threshold = 9999999
# Get Answer from KB online
status, raw_answer_true = kb.query(qapair.sparql.query.replace("https", "http"))
answerset_true = AnswerSet(raw_answer_true, parser.parse_queryresult)
qapair.answerset = answerset_true
ask_query = "ASK " in qapair.sparql.query
count_query = "COUNT(" in qapair.sparql.query
sort_query = "order by" in qapair.sparql.raw_query.lower()
entities, ontologies = linker.do(qapair, force_gold=force_gold)
double_relation = False
relation_uris = [u for u in qapair.sparql.uris if u.is_ontology() or u.is_type()]
if len(relation_uris) != len(set(relation_uris)):
double_relation = True
else:
double_relation = False
print('ask_query: ', ask_query)
print('count_query: ', count_query)
print('double_relation: ', double_relation)
if entities is None or ontologies is None:
return "-Linker_failed", []
graph = Graph(kb)
queryBuilder = QueryBuilder()
logger.info("start finding the minimal subgraph")
graph.find_minimal_subgraph(entities, ontologies, double_relation=double_relation, ask_query=ask_query,
sort_query=sort_query, h1_threshold=h1_threshold)
logger.info(graph)
wheres = queryBuilder.to_where_statement(graph, parser.parse_queryresult, ask_query=ask_query,
count_query=count_query, sort_query=sort_query)
output_where = [{"query": " .".join(item["where"]), "correct": False, "target_var": "?u_0"} for item in wheres]
for item in list(output_where):
logger.info(item["query"])
if len(wheres) == 0:
return "-without_path", output_where
correct = False
for idx in range(len(wheres)):
where = wheres[idx]
if "answer" in where:
answerset = where["answer"]
target_var = where["target_var"]
else:
target_var = "?u_" + str(where["suggested_id"])
raw_answer = kb.query_where(where["where"], target_var, count_query, ask_query)
answerset = AnswerSet(raw_answer, parser.parse_queryresult)
output_where[idx]["target_var"] = target_var
sparql = SPARQL(kb.sparql_query(where["where"], target_var, count_query, ask_query), ds.parser.parse_sparql)
if (answerset == qapair.answerset) != (sparql == qapair.sparql):
print("error")
if answerset == qapair.answerset:
correct = True
output_where[idx]["correct"] = True
output_where[idx]["target_var"] = target_var
else:
if target_var == "?u_0":
target_var = "?u_1"
else:
target_var = "?u_0"
raw_answer = kb.query_where(where["where"], target_var, count_query, ask_query)
print("Q_H ",)
# print(raw_answer)
print("Q_")
answerset = AnswerSet(raw_answer, parser.parse_queryresult)
sparql = SPARQL(kb.sparql_query(where["where"], target_var, count_query, ask_query), ds.parser.parse_sparql)
if (answerset == qapair.answerset) != (sparql == qapair.sparql):
print("error")
if answerset == qapair.answerset:
correct = True
output_where[idx]["correct"] = True
output_where[idx]["target_var"] = target_var
return "correct" if correct else "-incorrect", output_where
if __name__ == "__main__":
logger = logging.getLogger(__name__)
utility.setup_logging()
ds = LC_Qaud_Linked(path="./data/LC-QUAD/linked_answer.json")
ds.load()
ds.parse()
if not ds.parser.kb.server_available:
logger.error("Server is not available. Please check the endpoint at: {}".format(ds.parser.kb.endpoint))
sys.exit(0)
parser = LC_QaudParser()
kb = parser.kb
stats = Stats()
linker = GoldLinker()
output_file = 'lcquad_gold'
tmp = []
output = []
na_list = []
for qapair in ds.qapairs:
print('='*10)
stats.inc("total")
output_row = {"question": qapair.question.text,
"id": qapair.id,
"query": qapair.sparql.query,
"answer": "",
"features": list(qapair.sparql.query_features()),
"generated_queries": []}
if qapair.answerset is None or len(qapair.answerset) == 0:
stats.inc("query_no_answer")
output_row["answer"] = "-no_answer"
na_list.append(output_row['id'])
else:
result, where = qg(linker, ds.parser.kb, ds.parser, qapair, False)
stats.inc(result)
output_row["answer"] = result
newwhere = []
for iwhere in where:
if iwhere not in newwhere:
newwhere.append(iwhere)
output_row["generated_queries"] = newwhere
logger.info(result)
logger.info(stats)
output.append(output_row)
if stats["total"] % 100 == 0:
with open("output/{}.json".format(output_file), "w") as data_file:
json.dump(output, data_file, sort_keys=True, indent=4, separators=(',', ': '))
with open("output/{}.json".format(output_file), "w") as data_file:
json.dump(output, data_file, sort_keys=True, indent=4, separators=(',', ': '))
print('stats: ', stats)
with open('na_list_lcquadgold.txt', 'w') as f:
for i in na_list:
f.write("{}\n".format(i))