This repository has been archived on 2026-10-21. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
PICKA_python/www/app.py
T
2026-09-22 11:52:03 +02:00

194 lines
5.6 KiB
Python

from flask import Flask, render_template, request, url_for, redirect, jsonify
from celery import Celery
from naoqi import ALBroker
import subprocess
import os
import sys
import pickle
import time
from multiprocessing import Pool
if True:
sys.path.append("../")
from tools.exit_condition import ExitExperimentModule
import tools.settings as settings
app = Flask(__name__)
_pool = None
# app.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0'
# app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:6379/0'
# website_url = "picka-exp.xyx:5000"
# app.config["SERVER_NAME"] = website_url
# celery = Celery(app.name, broker=app.config["CELERY_BROKER_URL"])
# celery.conf.update(app.config)
expe_exit = None
global language
IP_ADDRESS = "169.254.165.5"
# IP_ADDRESS = "sam.local"
# @celery.task(bind=True)
# def runPickaExp(self, subject, game, phase, lang, p_exists, ip):
def runPickaExp(subject, game, phase, lang, p_exists, ip):
sys.path.append(os.getcwd())
from picka import pickaMain
#
# This might take several minutes to complete
# @celery.task(bind=True)
# def runPickaExp(self, subject, game, phase, lang, p_exists, ip):
print("Started picka!!")
if os.getcwd() != '/home/nao/Documents/Sam_files/Python_scripts':
os.chdir('../')
pickaMain(subject, game, phase, lang, p_exists, ip, broker=True)
# main(subject, game, phase, lang, p_exists,
# ip, broker=True, cel_id=self.request.id)
print "End of running process."
@app.route('/')
def hello():
return render_template("main.html")
@app.route("/run_picka", methods=["GET", "POST"])
def runPicka():
global language
error = 0
p_exists = request.form.get("p_exists")
game = request.form.get("game")
subject = request.form.get("participant").strip()
phase = request.form.get("phase").strip().lower()
lang = request.form.get("lang").strip()
language = lang
ip = IP_ADDRESS
p_exists = int(p_exists == 'true')
port = "9559"
try:
if p_exists != None:
# runPickaExp.delay(subject, game, phase, lang, p_exists, ip)
try:
# runPickaExp(subject, game, phase, lang, p_exists, ip)
begin = _pool.apply_async(
runPickaExp, [subject, game, phase, lang, p_exists, ip])
except:
raise Exception()
return jsonify({'game': game})
except RuntimeError as e:
error = 1
print e
print "There was an error."
return jsonify({'game': game, "error": error})
# cmd = "/usr/bin/python picka.py -s {} -g {} -p {} -l {} -e {}".format(
# subject, game, phase, lang, p_exists)
# print cmd
# subprocess.call(cmd, shell=True)
@app.route('/check_participant', methods=['GET', 'POST'])
def check_participant():
if os.getcwd() != "/home/nao/Documents/Sam_files/Python_scripts/www":
os.chdir("./www")
game = request.form.get("game")
subject = request.form.get("participant").strip()
phase = request.form.get("phase").strip().lower()
lang = request.form.get("lang").strip()
if game == "fishy":
participant = os.path.join(
"../results/" + subject,
"jnd_{}_{}_robot.mat".format(lang.lower(), subject))
else:
participant = os.path.join(
"../results/" + subject,
"{}_{}_{}_robot.mat".format(game[:3], lang.lower(), subject))
# subprocess.call(cmd, shell=True)
p_exists = 0
if os.path.exists(participant):
p_exists = 1
# os.chdir("www/")
# return redirect(url_for('checkParticipant', participant=participant))
return jsonify({
'p_exists': p_exists,
"game": game,
"subject": subject,
"phase": phase,
"lang": lang
})
@app.route('/no-interaction')
def noInt():
return render_template('no-int.html')
@app.route('/no-interaction-diagram')
def noIntDiagram():
return render_template('no-int-w-diagram.html')
@app.route('/crm-game')
def runCRM():
global language
while not os.path.exists('../crm/trials.p'):
time.sleep(0.01)
if os.path.isfile('../crm/trials.p'):
try:
with open('../crm/trials.p', 'rb') as f:
data = pickle.load(f)
except EOFError as e:
print e
os.remove('../crm/trials.p')
language = 'en'
return render_template("crm-game.html",
lang=language,
current_trial=int(data["current_trial"]),
total_trials=int(data["total_trials"]))
@app.route('/crm_answer', methods=["GET", "POST"])
def save_answer():
colour = request.form.get("colour")
number = request.form.get("number")
answer = {"colour": colour, "number": number}
pickle.dump(answer, open('../crm/answer.p', 'wb'))
while not os.path.exists('../crm/trials.p'):
time.sleep(0.01)
if os.path.isfile('../crm/trials.p'):
try:
with open('../crm/trials.p', 'rb') as f:
data = pickle.load(f)
except EOFError as e:
print e
os.remove('../crm/trials.p')
resp = {"answer": answer, "trials": data}
# return redirect(url_for('runCRM'))
return jsonify(resp)
if __name__ == "__main__":
# runPickaExp("NHA927", "crm", "training", "EN", 0, IP_ADDRESS)
global expe_exit
settings.init()
_pool = Pool(processes=4)
try:
# myBroker = ALBroker("myBroker", "0.0.0.0", 0, IP_ADDRESS, 9559)
# expe_exit = ExitExperimentModule("expe_exit", myBroker, "EN")
app.run(host="0.0.0.0", debug=True)
except SystemError as e:
print e
_pool.close()
_pool.join()
os._exit(1)