forked from kaushal2161/Mathaware-Q-A-System
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.py
More file actions
398 lines (330 loc) · 13.4 KB
/
app.py
File metadata and controls
398 lines (330 loc) · 13.4 KB
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
import json
import os
import re
from flask import Flask
from flask import render_template
from flask import request
from flask.json import jsonify
from flask_cors import CORS
from ppp_datamodel import Sentence
from sympy import Symbol
from sympy.core.sympify import sympify
from sympy.parsing.latex import parse_latex
import getidentifiers
import latexformlaidentifiers
# identifier symbol retrieval
from semanticsearch.IdentifierSemantics import get_identifier_symbol
from semanticsearch.SemanticSearch_Wikidata_mathqa import get_formula_qid
# semantic search using arXiv or Wikipedia index
from semanticsearch.SemanticSearch_arXivWikipedia_mathqa import get_identifier_semantics_catalog,search_formulae_by_identifiers
# semantic search using Wikidata SPARQL query
from semanticsearch.SemanticSearch_Wikidata_mathqa import search_formulae_by_identifiers_Wikidata,search_formulae_by_concept_name_Wikidata
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.sys.path.insert(0, parentdir)
os.environ['PPP_QUESTIONPARSING_GRAMMATICAL_CONFIG'] = os.path.dirname(
os.path.abspath(__file__)) + '/example_config.json'
os.environ['PYWIKIBOT2_NO_USER_CONFIG'] = '1'
# os.environ['PYWIKIBOT2_DIR'] = os.path.dirname(os.path.abspath(__file__)) + '/pywikibot'
from ppp_datamodel.communication import Request
from ppp_questionparsing_grammatical import RequestHandler
from getformula import get_formula
from getformula import FormulaRequestHandler
from getformula import HindiRequestHandler
from latexformlaidentifiers import Formulacalculation
from identifier_properties import retrieve_identifier_properties
# from identifier_properties import retrieve_identifier_name
# from identifier_properties import retrieve_identifier_value
import traceback
# get input from question (identifier symbols / relationships)
def get_input(question,exclude):
input = []
candidates = question.split()
for word in candidates:
if "?" in word:
word = word.strip("?")
if not word in exclude and len(word) > 0:
input.append(word)
return input
show_single_identifier_names = True
def getlhsrhs(formula, ext):
"""
Break the formula into lhs and rhs
"""
lhs, rhs = formula.split(ext, 1)
return lhs,rhs
def makeidentifier(symbol, values):
"""
Make dictionary for Values of Symbol
"""
symvalue = {}
for i in symbol:
for j in values:
if i == Symbol(j):
value = values[j]
symvalue[i] = value
return symvalue
def makeresponse(formul,subject,mode,datasource):
"""
Make response for the API
"""
try:
# TODO: unbreak for english
#subject = req.subject
reques = Formulacalculation(formul)
identifiers = reques.answer()
# todo: build identifier value output
if identifiers is not None:
listidentifiers = list(identifiers)
responselist = []
valuelist = []
# item = identifier
identifier_properties = retrieve_identifier_properties(subject)
for item in listidentifiers:
try:
# symbol question
if mode == 'symbol_question':
name = " (" + subject + ")"
# if relationship_question:
#
# if show_single_identifier_names:
# # single identifier name
# inv_sem_idx = get_identifier_semantics_catalog(inverse=False,multiple=False)
# name = " (" + inv_sem_idx[str(item)[0]] + ")"
#
# if not show_single_identifier_names:
# # multiple identifier names
# inv_sem_idx = get_identifier_semantics_catalog(inverse=False, multiple=True)
# name = " (" + str(inv_sem_idx[str(item)[0]]) + ")"
# # only the first symbol is the identifier (the others may be sub- oder superscripts)
#
else:
name = " (" + identifier_properties[str(item)]['name'] + ")"
except:
name = ""
try:
valuelist.append(identifier_properties[str(item)]['value'])
except:
valuelist.append("Enter value")
# responselist.append(str(item))
responselist.append(str(item) + name)
# get qid
try:
qid = get_formula_qid(subject)
except:
qid = ""
responselist.append(dict(formula=formul))
responselist.append(dict(values=valuelist))
responselist.append(dict(qid=qid,datasource=datasource))
#responselist.append(dict(datasource=datasource))
#json_data = json.dumps(responselist)
response = jsonify(responselist)
# json_data2 = json.dumps(valuelist)
# response.values = jsonify(valuelist)
response.status_code = 200
return response
else:
response = jsonify(formul)
response.status_code = 206
print(response)
return response
except:
response = jsonify("System is not able to find the result.")
response.status_code = 202
return response
# OUT: response
app = Flask(__name__)
CORS(app)
@app.route('/')
def my_form():
return render_template("index.html")
@app.route('/getresponse', methods=['POST'])
def my_form_post():
"""
Get formula from the user input and process it
Return response
"""
try:
if request.form['formula']:
global formula
formula = request.form['formula']
global processedformula
processedformula = latexformlaidentifiers.prepformula(formula)
if formula is not None:
return makeresponse(processedformula,None,None,'Wikidata')
# except:
# response= jsonify("System is not able to find the result.")
# response.status_code = 202
# return response
except Exception as ex:
print(''.join(traceback.format_exception(etype=type(ex), value=ex, tb=ex.__traceback__)))
@app.route('/getengformula', methods=['POST'])
def get_formula():
"""
Get English question from the user parse it to Questionparsing module to get Triple
Parse Triple (Subject, predicate, ?) to FormulaRequestHandler to get Formula from Wikidata
Return response
"""
# parse question
try:
question = request.form['formula']
# lowercase first letter of question
question = question[:1].lower() + question[1:]
print("Question: " + question)
# Determine question type
# identifier symbol question
if "symbol" in question:
mode = 'symbol_question'
print("Symbol question")
exclude = ["what", "is", "the", "symbol", "for", "?"]
subject = get_input(question,exclude)
formula = get_identifier_symbol(identifier_name=subject)
# relationship question (semantic search)
elif "relationship" in question or "relation" in question:
mode = 'relationship_question'
print("Relationship question")
exclude = ["what","is","the","relationship","relation","between","and","?"]
input = get_input(question,exclude)
# check if input is identifier names or symbols
# symbols if all characters
#
#symbols = True
#for element in input:
# if len(element) > 1:
# symbols = False
# names if at least one is word
#if symbols:
# mode_number = 1
#else:
# mode_number = 2
#
# results = search_formulae_by_identifier_names\
# (identifier_names=identifier_names,catalog="NTCIR-12_arXiv_astro-ph"\
# ,inverse=True,multiple=False)
#results = search_formulae_by_identifiers(input=input,
# mode_number=mode_number)
formula,subject = search_formulae_by_identifiers_Wikidata(identifiers=input)
#formula = list(results.items())[0][0].split(" (")[0]
# Formula question
elif "formula" in question:
mode = 'formula_question'
print("Formula question")
exclude = ["what ", "is ", "the ", "formula ", "for ", "?"]
for word in exclude:
question = question.replace(word,"")
# strip whitespace (at beginning) and end
#subject = question[1:].strip()
subject = question.strip()
formula,datasource = search_formulae_by_concept_name_Wikidata(subject)
# General or geometry question
else:
mode = 'general_geometry'
print("General or geometry question")
meas = {'accuracy': 0.5, 'relevance': 0.5}
q = RequestHandler(Request(language="en", id=1, tree=Sentence(question), measures=meas))
try:
query = q.answer()
except:
print("Stanford CoreNLP was unable to parse the question")
reques = FormulaRequestHandler(query)
subject = reques.request[0]._attributes['tree']._attributes['subject']._attributes['value']
formula = reques.answer()
formula = latexformlaidentifiers.prepformula(formula)
# generate response
if not (formula.startswith("System")):
try:
datasource = datasource
except:
datasource = 'Wikidata'
return makeresponse(formula,subject,mode,datasource)
else:
response = jsonify(formula)
response.status_code = 202
print(response)
return response
except Exception :
response= jsonify("System is not able to find the result.")
response.status_code = 202
return response
#return ("System is not able to find the result.")
# except Exception as ex:
# print(''.join(traceback.format_exception(etype=type(ex), value=ex, tb=ex.__traceback__)))
@app.route('/gethindiformula', methods=['POST'])
def get_hindiformula():
"""
Get Hindi question from the user and apply regex to get subject and predicate
Parse subject and predicate to HindiRequestHandler to get formula
Return response
"""
try:
question = request.form['formula']
matchObj = re.match(r'(.*)की (.*?) .*', question, re.M | re.I)
matchObj1 = re.match(r'(.*)के लिए (.*?) क्या है *', question, re.M | re.I)
matchObj2 = re.match(r'(.*)और (.*?) के बीच *', question, re.M | re.I)
if matchObj:
subject = matchObj.group(1)
predicate = matchObj.group(2)
if matchObj1:
subject = matchObj1.group(1)
predicate = matchObj1.group(2)
if matchObj2:
subject = matchObj2.group(1)
predicate = matchObj2.group(2)
reques = HindiRequestHandler("hi", subject, predicate)
global formula
formula = reques.answer()
global processedformula
processedformula = latexformlaidentifiers.prepformula(formula)
print(processedformula)
if not (formula.startswith("System")):
return makeresponse(processedformula,None,None,'Wikidata')
else:
response = jsonify(formula)
response.status_code = 202
return response
except Exception:
response = jsonify("System is not able to find the result.")
response.status_code = 202
return response
@app.route('/getfinalresult', methods=['POST'])
def my_form_json():
"""
Get Values for the identifiers
Return Calculated result
"""
try:
result = json.loads(request.data.decode('utf8'))
formula = result['formula']
del result['formula']
identifiers_dict = result
# slice off identifier names for calculation
symbolvalue = {}
for identifier in identifiers_dict.items():
try:
symbol = identifier[0].split(" (")[0]
value = identifier[1]
symbolvalue[symbol] = value
except:
pass
# remove displaystyle
formula = formula.replace("\\displaystyle","")
# formula parsing and calculation
seprator = getidentifiers.formuladivision(formula)
if seprator is not None:
lhs, rhs = getlhsrhs(formula, seprator)
f = parse_latex(rhs)
f1 = parse_latex(lhs)
latexlhs = sympify(f1)
l = sympify(f)
# print(l)
#symbolvalue = makeidentifier(identifier, identifiers_dict)
value = l.evalf(subs=symbolvalue)
return ("%s %s %.2e" % (latexlhs, seprator, value))
else:
l = sympify(formula)
value = l.evalf(subs=identifiers_dict)
return ("%.2e" % value)
except Exception:
return ("System is not able to find the result.")
if __name__ == '__main__':
app.run(debug=True,host='0.0.0.0')
# get_formula()