From 6b8c27c5ef02c4794bf16c51fc731bc983522653 Mon Sep 17 00:00:00 2001 From: "Moritz Schubotz (physikerwelt)" Date: Mon, 18 Dec 2017 03:49:34 +0900 Subject: [PATCH] Add WSGI option --- README.md | 24 +++++- application.wsgi | 5 ++ calculation.py | 15 ++-- extra.py | 178 ++++++++++++++++++++++++++++++++++++++++++ static/demo.html | 182 +++++++++++++++++++++---------------------- static/main.js | 14 ++-- static/style.css | 2 +- templates/index.html | 6 +- 8 files changed, 319 insertions(+), 107 deletions(-) create mode 100644 application.wsgi create mode 100644 extra.py diff --git a/README.md b/README.md index 574fabf..c3821a5 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -##Matheaware QA system +## Matheaware QA system This system is able to answer mathematical questions asked in natural language by the user. @@ -78,3 +78,25 @@ kaushal@kaushal:/workspace1/matheaware_Q-A_system/$ export FLASK_APP=calculation kaushal@kaushal:/workspace1/matheaware_Q-A_system/$ flask run ``` Then you can see the the system in your browser by opening the localhost which is : http://127.0.0.1:5000/ + +## run as wsgi module + +* Make sure that /var/www/nltk_data is writeable for www-data or in general the nltk_data folder of the home folder of the apache user +* Make sure to set the correct permissions in the pywikibot folder i.e. sudo chown www-data user-config.py + +The apache 2 vhost config (adjust the paths) +``` + + ServerName 192.52.3.166 + ServerAdmin admin@192.52.3.166 + WSGIDaemonProcess flaskapp user=ubuntu group=ubuntu home=/home/ubuntu/Formual_Calculation/ threads=5 + WSGIScriptAlias / /home/ubuntu/Formual_Calculation/application.wsgi + DocumentRoot /home/ubunutu/Formual_Calculation + + Require all granted + + ErrorLog ${APACHE_LOG_DIR}/error.log + LogLevel debug + CustomLog ${APACHE_LOG_DIR}/access.log combined + + diff --git a/application.wsgi b/application.wsgi new file mode 100644 index 0000000..9fd3a66 --- /dev/null +++ b/application.wsgi @@ -0,0 +1,5 @@ +import os, sys, logging +logging.basicConfig(stream=sys.stderr) +sys.path.insert(0, '/home/ubuntu/Formual_Calculation') + +from calculation import app as application diff --git a/calculation.py b/calculation.py index 3f0ddd3..df7ce6d 100644 --- a/calculation.py +++ b/calculation.py @@ -2,6 +2,7 @@ from flask import request from flask import render_template import json +from flask_cors import CORS from process_latex import process_sympy from flask.json import jsonify from sympy.core.sympify import sympify @@ -19,7 +20,8 @@ parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) os.sys.path.insert(0,parentdir) -os.environ['PPP_QUESTIONPARSING_GRAMMATICAL_CONFIG'] = 'ppp_questionparsing_grammatical/nlp_classical_config.json' +os.environ['PPP_QUESTIONPARSING_GRAMMATICAL_CONFIG'] = os.path.dirname(os.path.abspath(__file__)) + '/ppp_questionparsing_grammatical/nlp_classical_config.json' +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 FormulaRequestHandler @@ -64,8 +66,7 @@ def makeresponse(formul): for item in listidentifiers: newlist.append(str(item)) - newlist.append(dict(formula=formul)) - + newlist.append(dict(formula=formul)) json_data=json.dumps(newlist) response=jsonify(newlist) response.status_code = 200 @@ -82,6 +83,8 @@ def makeresponse(formul): app = Flask(__name__) +CORS(app) + @app.route('/') def my_form(): return render_template("index.html") @@ -131,7 +134,8 @@ def get_formula(): formula=reques.answer() global processedformula - processedformula=latexformlaidentifiers.prepformula(formula) + processedformula=latexformlaidentifiers.prepformula(formula) + print(processedformula) if not (formula.startswith("System")): return makeresponse(processedformula) else: @@ -175,7 +179,8 @@ def get_hindiformula(): global formula formula=reques.answer() global processedformula - processedformula=latexformlaidentifiers.prepformula(formula) + processedformula=latexformlaidentifiers.prepformula(formula) + print(processedformula) if not (formula.startswith("System")): return makeresponse(processedformula) else: diff --git a/extra.py b/extra.py new file mode 100644 index 0000000..b00cbb3 --- /dev/null +++ b/extra.py @@ -0,0 +1,178 @@ +import ast +import parser +import re +from process_latex import process_sympy +from sympy.core.sympify import sympify +from sympy import Number, NumberSymbol, Symbol +import sympy +#import scipy.constants +import json +''' +text = open('/home/kaushal/gold.json').read() +d = json.loads(text) +for each in d: + #c+=1 + #print(c) + formula=each["math_inputtex"] + print(formula) +''' + + +contant={'pi':'3.141592653589793','golden':'1.618033988749895','golden_ratio':'1.618033988749895','c':'299792458.0','speed_of_light':'299792458.0','mu_0':'1.2566370614359173e-06',\ + 'epsilon_0':'8.854187817620389e-12','Planck':'6.62607004e-34','hbar':'1.0545718001391127e-34','G':'6.67408e-11',\ + 'gravitational_constant':'6.67408e-11','g':'9.80665','e':'1.6021766208e-19','elementary_charge':'1.6021766208e-19','gas_constant':'8.3144598',\ + 'alpha':'0.0072973525664','fine_structure':'0.0072973525664','N_A':'6.022140857e+23','Avogadro':'6.022140857e+23','k':'1.38064852e-23',\ + 'Boltzmann':'1.38064852e-23','sigma':'5.670367e-08','Stefan_Boltzmann':'5.670367e-08','Wien':'0.0028977729','Rydberg':'10973731.568508',\ + 'm_e':'9.10938356e-31','electron_mass':'9.10938356e-31','m_p':'1.672621898e-27','proton_mass':'1.672621898e-27','m_n':'1.672621898e-27','neutron_mass':'1.672621898e-27','S':'5.24411510858423962092'} +def prepformula(formula): + + replace={"{\displaystyle":"","\\tfrac":"\\frac","\\left":"","\\right":"","\\mathrm":"","\\textbf":"","\\begin":"","\end":"","\\bigg":"","\\vec":"","\cdots":""} + + if formula.startswith('{\displaystyle') and formula.endswith('}'): + fformula=formula.rsplit('}',1) + return replace_all(fformula[0],replace) + + if formula.endswith('.'): + fformula=formula.split('.') + return replace_all(fformula[0],replace) + + if formula.endswith(","): + fformula=formula.split(',') + return replace_all(fformula[0],replace) + + else: + return replace_all(formula,replace) + + +def replace_all(text, dic): + for i, j in dic.items(): + text = text.replace(i, j) + return text + + + + +def evalformula(formula): + try: + f=process_sympy(formula) + a=sympify(f) + symbol=a.atoms(Symbol) + return (list(symbol)) + except: + return "error" + pass + + ''' + identifier={} + + for x in symbol: + if str(x) in contant: + value=contant.get(str(x)) + identifier[x]=value + else: + data = float(input("Enter a value for" + " " + str(x) +":")) + identifier[x]=data + + value=a.evalf(subs=identifier) + print(value) + return value + ''' + + + +def equality(formula,ext): + lhs,rhs=formula.split(ext,1) + value=evalformula(rhs) + return value + #value1=evalformula(lhs) + #print(value) + #print(value1) + + + #if value1 is not None: + # return ("value of %s : = %.2e" % (rhs,value1)) + + #if value is not None: + # return ("value of %s : = %.2e" % (lhs,value)) + +def value(formula): + try: + f=process_sympy(formula) + a=sympify(f) + symbol=a.atoms(Symbol) + identifier={} + return (list(symbol)) + except: + return "error" + pass + + ''' + identifiers={} + + for x in symbol: + if str(x) in contant: + value=contant.get(str(x)) + identifier[x]=value + + else: + data = float(input("Enter a value for" + " " + str(x) +":")) + identifier[x]=data + print(identifier) + #identifiers1={'aleph_0': '6.0', 'omega': '5.0', 'alpha: '0.0072973525664'} + value=a.evalf(subs=identifiers) + + print(value) + return ("value of equation := %.2e" % value) + ''' + + + +dict={} +#formula="W(2, k) > 2^k/k^\\varepsilon" +def answer(): + try: + text = open('/home/kaushal/gold.json').read() + d = json.loads(text) + #for each in d: + #formula=each["math_inputtex"] + formula="\\bar{V}^*" + preprocessedformula=prepformula(formula) + #print(preprocessedformula) + k=['=','\leq','\req','\\approx','\le'] + + if '=' in preprocessedformula: + ext='=' + val=(equality(preprocessedformula,ext)) + dict[preprocessedformula]=val + if '\leq' in preprocessedformula: + ext='\leq' + val=equality(preprocessedformula,ext) + dict[preprocessedformula]=val + if '\req' in preprocessedformula: + ext='\req' + val= equality(preprocessedformula,ext) + dict[preprocessedformula]=val + if '\le' in preprocessedformula: + ext='\le' + val=equality(preprocessedformula,ext) + dict[preprocessedformula]=val + if '\\approx' in preprocessedformula: + ext='\\approx' + val= equality(preprocessedformula,ext) + dict[preprocessedformula]=val + + if not any(ext in preprocessedformula for ext in k): + val=(value(preprocessedformula)) + dict[preprocessedformula]=val + for k,v in dict.items(): + print (k,v) + #import json + #with open('/home/kaushal/Desktop/test.json', 'w') as fp: + #json_string = json.dumps(dict) + #print(json_string) + except Exception as e : print(e) + + +answer() + + diff --git a/static/demo.html b/static/demo.html index 84192a5..3e834b2 100644 --- a/static/demo.html +++ b/static/demo.html @@ -1,91 +1,91 @@ - - - - - - - - - - - - - - - - - - -
-
- -
-
-

English questions

-
-
    -
  • What is the volume of Regular dodecahedron ?

  • -
  • What is the formula for geometric mean theorem ?

  • -
  • What is the volume of pentagonal prism ?

  • -
  • What is the formula for BEST theorem ?

  • -
  • What is the formula for gas ?

  • -
  • What is the formula for Virasoro algebra ?

  • -
  • What is the volume of pyramid ?

  • -
  • What is the surface area of triangular cupola ?

  • -
  • Area of sphere?

  • -
  • What is the formula for pythagorean theorem ?

  • -
-
-

Hindi questions

-
-
    -
  • पाइथागोरस प्रमेय के लिए फार्मूला क्या है ?

  • -
  • ऊर्जा और द्रव्यमान के बीच क्या संबंध है ?

  • -
  • द्रव्यमान और त्वरण के बीच क्या संबंध है ?

  • -
  • गोला के लिए आयतन क्या है ?

  • -
-
-

Direct Formula

-
-
    -
  • A = \frac{1}{2}(x_1 + x_2 )h

  • -
  • A = \frac{{\theta r^2 }}{2}

  • -
  • P = 2l + 2w

  • -
  • V = \frac{{4\pi r^3 }}{3}

  • -
  • A = \frac{1}{2}ab\sin C

  • -
  • \lambda = \frac{h}{{mv}}

  • -
  • T = \frac{{\hbar c^3 }}{{8\pi kGM}}

  • -
  • E = mc^2

  • -
-
-
-
-
- - - - + + + + + + + + + + + + + + + + + + +
+
+ +
+
+

English questions

+
+
    +
  • What is the volume of Regular dodecahedron ?

  • +
  • What is the formula for geometric mean theorem ?

  • +
  • What is the volume of pentagonal prism ?

  • +
  • What is the formula for BEST theorem ?

  • +
  • What is the formula for gas ?

  • +
  • What is the formula for Virasoro algebra ?

  • +
  • What is the volume of pyramid ?

  • +
  • What is the surface area of triangular cupola ?

  • +
  • Area of sphere?

  • +
  • What is the formula for pythagorean theorem ?

  • +
+
+

Hindi questions

+
+
    +
  • पाइथागोरस प्रमेय के लिए फार्मूला क्या है ?

  • +
  • ऊर्जा और द्रव्यमान के बीच क्या संबंध है ?

  • +
  • द्रव्यमान और त्वरण के बीच क्या संबंध है ?

  • +
  • गोला के लिए आयतन क्या है ?

  • +
+
+

Direct Formula

+
+
    +
  • A = \frac{1}{2}(x_1 + x_2 )h

  • +
  • A = \frac{{\theta r^2 }}{2}

  • +
  • P = 2l + 2w

  • +
  • V = \frac{{4\pi r^3 }}{3}

  • +
  • A = \frac{1}{2}ab\sin C

  • +
  • \lambda = \frac{h}{{mv}}

  • +
  • T = \frac{{\hbar c^3 }}{{8\pi kGM}}

  • +
  • E = mc^2

  • +
+
+
+
+
+ + + + \ No newline at end of file diff --git a/static/main.js b/static/main.js index a6a522b..31690fe 100644 --- a/static/main.js +++ b/static/main.js @@ -30,15 +30,15 @@ function getResult() { var data={'formula':enteredFormula}; var url = ""; - if (enteredFormula.match("^wh") || enteredFormula.match("^Wh") || lang == "hn") { + if (enteredFormula.indexOf("=") >= 0) { + url = "/getresponse"; + } else if (lang == "hn" || lang == "en") { statementQueFlag = true; if(lang == "en") { - url = "http://127.0.0.1:5000/getengformula"; + url = "/getengformula"; } else if(lang == "hn") { - url = "http://127.0.0.1:5000/gethindiformula"; + url = "/gethindiformula"; } - } else { - url = "http://127.0.0.1:5000/getresponse"; } @@ -57,6 +57,7 @@ function getResult() { $('.submitBtn').hide(); $('.userinputPanel').show(); $('.userInputDiv').empty(); + $('.userInputDiv').hide(); $('#Loader1').hide(); }, 200); } else { @@ -66,6 +67,7 @@ function getResult() { $('.resultValue').text(""); $('.resultPanel').hide(); $('.userInputDiv').empty(); + $('.userInputDiv').show(); $('.InputErrorDiv').hide(); $('.submitBtn').show(); if(resultString.length == 1) { @@ -200,7 +202,7 @@ function getResultFromInputs() { var saveData = $.ajax({ type: 'POST', - url: "http://127.0.0.1:5000/getfinalresult", + url: "/getfinalresult", data: JSON.stringify(formJSON), dataType: "json", contentType: "", diff --git a/static/style.css b/static/style.css index f610b6b..d23da70 100644 --- a/static/style.css +++ b/static/style.css @@ -110,4 +110,4 @@ h1 { /* .formula.latex img { width:23%; -} */ +} */ \ No newline at end of file diff --git a/templates/index.html b/templates/index.html index ab92b48..dd547aa 100644 --- a/templates/index.html +++ b/templates/index.html @@ -30,9 +30,9 @@ @@ -91,4 +91,4 @@

Solution

- + \ No newline at end of file