69 lines
1.8 KiB
Python
69 lines
1.8 KiB
Python
import functools
|
|
import re
|
|
|
|
import flask
|
|
|
|
text2bool = {"absència": True, "absencia": True, "presencia": False, "presència": False, "absent": True, "present": False}
|
|
bool2text = {True: "absent", False: "present"}
|
|
|
|
app = flask.Flask(__name__)
|
|
|
|
|
|
class HTTPError(flask.Response, Exception):
|
|
def __init__(self, *args, status_code, **kwargs):
|
|
super().__init__(*args, **kwargs)
|
|
self.status_code = status_code
|
|
|
|
|
|
def handle_errors(func):
|
|
@functools.wraps(func)
|
|
def wrapped(*args, **kwargs):
|
|
try:
|
|
return func(*args, **kwargs)
|
|
except HTTPError as r:
|
|
return r, r.status_code
|
|
except Exception as e:
|
|
print(e)
|
|
return flask.Response("Oh no! Hi ha hagut un error en el servidor :(", status="Internal error"), 500
|
|
|
|
return wrapped
|
|
|
|
|
|
@app.route("/")
|
|
def index():
|
|
return flask.render_template("./index.html")
|
|
|
|
|
|
@app.route("/calcula", methods=['POST'])
|
|
@handle_errors
|
|
def calcula():
|
|
frase = flask.request.get_json().get('frase')
|
|
if not frase:
|
|
raise HTTPError("Cal introduir una frase!", status_code=400, status="Missing parameter")
|
|
return calcula_presencia(frase)
|
|
|
|
|
|
@app.route("/static/<path:path>")
|
|
def static_files(path):
|
|
return flask.send_from_directory('static', path)
|
|
|
|
|
|
def xor(a, b):
|
|
return (a and not b) or (b and not a)
|
|
|
|
|
|
def calcula_presencia(frase):
|
|
frase = frase[3:]
|
|
subjecte, atribut = frase.split(" és ")
|
|
llista_subjecte = re.split(" de | d'", subjecte)
|
|
objecte = llista_subjecte[-1]
|
|
llista_bool = [text2bool[x.strip()] for x in llista_subjecte[:-1]]
|
|
bool_total = text2bool[atribut]
|
|
for bool in llista_bool:
|
|
bool_total = xor(bool_total, bool)
|
|
return f'{objecte} és {bool2text[bool_total]}'
|
|
|
|
|
|
if __name__ == "__main__":
|
|
app.run()
|