-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathapp.py
executable file
·260 lines (236 loc) · 9.67 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
# -*- coding:utf-8 -*-
from flask import Flask, request, render_template, url_for, jsonify, Response, redirect, session
import json, sys
import requests
from gevent.pywsgi import WSGIServer
import os
from sets import Set
from elasticsearch import Elasticsearch
app = Flask(__name__, static_url_path='/static')
#bootstrap = Bootstrap(app)
es = Elasticsearch()
#Autocomplete part......
#@app.route('/_autocomplete', methods=['GET'])
#def autocomplete():
# search = request.args.get('term')
# res = es.search(index='autocompleteindex1', doc_type='questions', body={"suggest": {"question-suggest": {"prefix": search,"completion": {"field": "question"}}}})
# results = []
# #print json.dumps(res)
# for entry in res['suggest']['question-suggest']:
# for q in entry['options']:
# results.append(q['_source']['question']['input'][0])
# return Response(json.dumps(results), mimetype='application/json')
def processEarlResult(earlResult, question):
resultResourceDict = {
"question": question,
"answer": "No result found",
"entity": "No result found",
"earltop": "",
"sqg": "",
"type": "No result found",
"abstract": "No result found",
"summary":"No result found",
"recommendations":"No result found",
"related_entities":"No result found",
"similar_entities":"No result found",
"question_type":"resource"
}
resultListDict = {
"question": question,
"answer": { "0": "No result found"
},
"abstract":{ "0": "No result found"
},
"question_type":"list",
"earltop":"",
"sqg":""
}
resultBolDict = {
"question": question,
"answer": "No result found",
"question_type":"bol",
"earltop": "",
"sqg": ""
}
resultLiteralDict = {
"question": question,
"answer": "No result found",
"question_type":"literal",
"earltop": "",
"sqg":""
}
s = Set()
if not earlResult:
return {'question': question, 'question_type': "none"}
for item in earlResult[0]:
if not item:
continue
d = item.values()[0]
if d['type'] == 'uri':
s.add(d['value'])
if d['type'] == 'typed-literal':
s.add(d['value'])
if len(s) == 0:
return resultListDict
elif len(s) == 1:
print earlResult
if earlResult[0][0].values()[0]['type'] == 'typed-literal':
returnType = 'literal'
resultLiteralDict["answer"] = earlResult[0][0].values()[0]['value']
return resultLiteralDict
else:
returnType = 'resource'
for item in earlResult[0]:
if not item:
continue
d1 = item.values()[0]
if d1['type'] == 'uri':
uri = d1['value']
q = """select ?label ?abstract where { <%s> rdfs:label ?label . <%s> <http://dbpedia.org/ontology/abstract> ?abstract . }"""%(uri,uri)
url = "http://dbpedia.org/sparql"
p = {'query': q}
h = {'Accept': 'application/json'}
proxydict = {"http":"http://webproxy.iai.uni-bonn.de:3128"}
try:
r = requests.get(url, params=p, headers=h, proxies=proxydict)
d =json.loads(r.text)
except Exception,e:
print e
try:
for row in d['results']['bindings']:
if 'abstract' in row and 'label' in row:
if row['abstract']['xml:lang'] == 'en' and row['label']['xml:lang'] == 'en':
#print row,count
resultResourceDict['answer'] = row['label']['value']
resultResourceDict['abstract'] = row['abstract']['value']
except Exception,e:
print e
uri = d1['value']
q = """select distinct ?entityType ?label where {
<%s> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?entityType .
?entityType rdfs:label ?label
FILTER regex(?entityType, "http://dbpedia.org/ontology/")
FILTER langMatches( lang(?label), "EN") }"""%(uri)
url = "http://dbpedia.org/sparql"
p = {'query': q}
h = {'Accept': 'application/json'}
proxydict = {"http":"http://webproxy.iai.uni-bonn.de:3128"}
try:
r = requests.get(url, params=p, headers=h, proxies=proxydict)
d =json.loads(r.text)
except Exception,e:
print e
try:
typeString = []
for row in d['results']['bindings']:
typeString.append(row['label']['value'])
resultResourceDict['type'] = '/'.join(typeString)
except Exception,e:
print e
return resultResourceDict
elif len(s) > 1:
if earlResult[0][0].values()[0]['type'] == 'typed-literal':
returnType = 'literal'
resultLiteralDict["answer"] = earlResult[0][0].values()[0]['value']
return resultLiteralDict
else:
returnType = 'list'
count = 0
for item in earlResult[0]:
d1 = item.values()[0]
if d1['type'] == 'uri':
uri = d1['value']
q = """select ?label ?abstract where { <%s> rdfs:label ?label . <%s> <http://dbpedia.org/ontology/abstract> ?abstract . }"""%(uri,uri)
url = "http://dbpedia.org/sparql"
p = {'query': q}
h = {'Accept': 'application/json'}
proxydict = {"http":"http://webproxy.iai.uni-bonn.de:3128"}
try:
r = requests.get(url, params=p, headers=h, proxies=proxydict)
d =json.loads(r.text)
except Exception,e:
print e
try:
for row in d['results']['bindings']:
if 'abstract' in row and 'label' in row:
if row['abstract']['xml:lang'] == 'en' and row['label']['xml:lang'] == 'en':
#print row,count
resultListDict['answer'][str(count)] = row['label']['value']
resultListDict['abstract'][str(count)] = row['abstract']['value']
count += 1
except Exception,e:
print e
return resultListDict
#get resource json
@app.route('/_getJSON', methods=['POST', 'GET'])
def getJSON():
if request.method == 'POST':
question = request.form.get('question')
global QUESTION
QUESTION = question
print(QUESTION)
#res = es.index(index="autocompleteindex1", doc_type='questions', id=QUESTION, body={"question":{"input":[QUESTION]}}) #Store input questions for autocomplete
inputDict = {'remote_addr': request.environ['HTTP_X_REAL_IP'],'nlquery':QUESTION, 'pagerankflag': True}
try:
r = requests.post("https://asknowdemo.sda.tech/earl/api/answerdetail", data=json.dumps(inputDict), headers={"content-type": "application/json"})
earlResult = json.loads(r.text)
resourceDict = processEarlResult(earlResult['answers'], QUESTION)
resourceDict['fullDetail'] = earlResult
return Response(json.dumps(resourceDict), mimetype='application/json')
except Exception,e:
print e
return Response(json.dumps({'question': QUESTION, 'question_type': "none"}), mimetype='application/json')
# index part
# question name
@app.route('/', methods=['GET', 'POST'])
def index():
return render_template('index.html')
@app.route('/resource', methods=['GET', 'POST'])
def showResource():
if request.method == 'GET':
question=request.args.get('question')
global QUESTION
QUESTION=question
return render_template('resource.html')
return render_template('resource.html')
@app.route('/list')
def showList():
if request.method == 'GET':
question=request.args.get('question')
global QUESTION
QUESTION=question
return render_template('list.html')
return render_template('list.html')
@app.route('/literal')
def showLiteral():
if request.method == 'GET':
question=request.args.get('question')
global QUESTION
QUESTION=question
return render_template('literal.html')
return render_template('literal.html')
@app.route('/bol')
def showBoolean():
if request.method == 'GET':
question=request.args.get('question')
global QUESTION
QUESTION=question
return render_template('bol.html')
return render_template('bol.html')
app.route('/none', methods=['GET', 'POST'])
def showResource():
if request.method == 'GET':
question=request.args.get('question')
global QUESTION
QUESTION=question
return render_template('none.html')
return render_template('none.html')
@app.route('/404')
def showNothing():
return render_template('none.html')
@app.errorhandler(404)
def not_found(error):
return render_template('none.html')
if __name__ == '__main__':
http_server = WSGIServer(('', int(sys.argv[1])), app)
http_server.serve_forever()