Commit a67841eb authored by Ossi Laine's avatar Ossi Laine
Browse files

Refactoring

parent 3940ede0
from flask_cors import CORS, cross_origin
from app import socketio
from flask_socketio import emit
import embody_plot
import os
import secrets
import json
from flask import (
Flask,
render_template,
request,
session,
flash,
redirect,
url_for,
Flask,
render_template,
request,
session,
flash,
redirect,
url_for,
Blueprint,
jsonify
)
......@@ -21,7 +25,7 @@ from sqlalchemy import and_, update
from flask_login import login_required
from werkzeug import secure_filename
from app import app, db
from app import app, db
from app.routes import APP_ROOT
from app.models import background_question, experiment
from app.models import background_question_answer
......@@ -31,41 +35,42 @@ from app.models import answer_set, answer, forced_id
from app.models import user, trial_randomization
from app.models import embody_answer, embody_question
from app.forms import (
CreateBackgroundQuestionForm,
CreateQuestionForm, UploadStimuliForm, EditBackgroundQuestionForm,
EditQuestionForm, EditExperimentForm, UploadResearchBulletinForm,
EditPageForm, RemoveExperimentForm, GenerateIdForm,CreateEmbodyForm
CreateBackgroundQuestionForm,
CreateQuestionForm, UploadStimuliForm, EditBackgroundQuestionForm,
EditQuestionForm, EditExperimentForm, UploadResearchBulletinForm,
EditPageForm, RemoveExperimentForm, GenerateIdForm, CreateEmbodyForm
)
from app.utils import get_mean_from_slider_answers
from app.utils import get_mean_from_slider_answers, map_answers_to_questions
#Stimuli upload folder setting
# Stimuli upload folder setting
#APP_ROOT = os.path.dirname(os.path.abspath(__file__))
experiment_blueprint = Blueprint("experiment", __name__,
template_folder='templates',
#static_folder='static',
url_prefix='/experiment')
experiment_blueprint = Blueprint("experiment", __name__,
template_folder='templates',
# static_folder='static',
url_prefix='/experiment')
# Set sliders/embody:
DEFAULT_EMBODY_PICTURE = '/static/img/dummy_600.png'
DEFAULT_EMBODY_QUESTION = 'Color the regions whose activity you feel increasing or getting stronger'
@experiment_blueprint.route('/view')
@login_required
def view():
#crap:3lines
# crap:3lines
exp_id = request.args.get('exp_id', None)
media = page.query.filter_by(experiment_idexperiment=exp_id).all()
# stimulus type
# stimulus type
mtype = page.query.filter_by(experiment_idexperiment=exp_id).first()
#experiment info
experiment_info = experiment.query.filter_by(idexperiment = exp_id).all()
#background questions
# experiment info
experiment_info = experiment.query.filter_by(idexperiment=exp_id).all()
# background questions
questions_and_options = {}
questions = background_question.query.filter_by(
experiment_idexperiment=exp_id).all()
......@@ -81,7 +86,7 @@ def view():
questions1 = questions_and_options
#sliderset
# sliderset
categories_and_scales = {}
categories = question.query.filter_by(experiment_idexperiment=exp_id).all()
......@@ -109,51 +114,59 @@ def remove():
exp_status = experiment.query.filter_by(idexperiment=exp_id).first()
if exp_status.status != 'Hidden':
flash("Experiment is public. Cannot modify structure.")
return redirect(url_for('experiment.view', exp_id=exp_id))
else:
form = RemoveExperimentForm(request.form)
if request.method == 'POST' and form.validate():
if form.remove.data == 'DELETE':
#This removes all experiment data from the database!
#Remove research bulletin if it exists
empty_filevariable = experiment.query.filter_by(idexperiment=exp_id).first()
# This removes all experiment data from the database!
# Remove research bulletin if it exists
empty_filevariable = experiment.query.filter_by(
idexperiment=exp_id).first()
if empty_filevariable.research_notification_filename is not None:
target = os.path.join(APP_ROOT, empty_filevariable.research_notification_filename)
if os.path.exists(target):
target = os.path.join(
APP_ROOT, empty_filevariable.research_notification_filename)
if os.path.exists(target):
os.remove(target)
#Tables
remove_forced_id = forced_id.query.filter_by(experiment_idexperiment=exp_id).all()
# Tables
remove_forced_id = forced_id.query.filter_by(
experiment_idexperiment=exp_id).all()
remove_rows(remove_forced_id)
#background_question_option & background_question & background question answers:
remove_background_question = background_question.query.filter_by(experiment_idexperiment=exp_id).all()
#Remove all background questions and all answers given to each bg question
# background_question_option & background_question & background question answers:
remove_background_question = background_question.query.filter_by(
experiment_idexperiment=exp_id).all()
# Remove all background questions and all answers given to each bg question
for a in range(len(remove_background_question)):
remove_background_question_option = background_question_option.query.filter_by(background_question_idbackground_question=remove_background_question[a].idbackground_question).all()
remove_background_question_option = background_question_option.query.filter_by(
background_question_idbackground_question=remove_background_question[a].idbackground_question).all()
remove_rows(remove_background_question_option)
remove_background_question_answers = background_question_answer.query.filter_by(background_question_idbackground_question=remove_background_question[a].idbackground_question).all()
remove_background_question_answers = background_question_answer.query.filter_by(
background_question_idbackground_question=remove_background_question[a].idbackground_question).all()
remove_rows(remove_background_question_answers)
db.session.delete(remove_background_question[a])
db.session.commit()
#Remove all questions and answers
remove_question = question.query.filter_by(experiment_idexperiment=exp_id).all()
# Remove all questions and answers
remove_question = question.query.filter_by(
experiment_idexperiment=exp_id).all()
for a in range(len(remove_question)):
remove_question_answers = answer.query.filter_by(question_idquestion=remove_question[a].idquestion).all()
remove_question_answers = answer.query.filter_by(
question_idquestion=remove_question[a].idquestion).all()
remove_rows(remove_question_answers)
db.session.delete(remove_question[a])
db.session.commit()
......@@ -162,54 +175,58 @@ def remove():
remove_embody_answers = embody_answer.query.filter(embody_answer.page_idpage.in_(list(map(
lambda x: x[0], page.query.with_entities(page.idpage).filter_by(experiment_idexperiment=exp_id).all())))).all()
remove_rows(remove_embody_answers)
remove_embody_questions = embody_question.query.filter_by(experiment_idexperiment=exp_id).all()
remove_embody_questions = embody_question.query.filter_by(
experiment_idexperiment=exp_id).all()
for a in range(len(remove_embody_questions)):
target = APP_ROOT + remove_embody_questions[a].picture
if os.path.exists(target) and DEFAULT_EMBODY_PICTURE != remove_embody_questions[a].picture:
if os.path.exists(target) and DEFAULT_EMBODY_PICTURE != remove_embody_questions[a].picture:
os.remove(target)
remove_rows(remove_embody_questions)
#Remove all pages and datafiles
remove_pages = page.query.filter_by(experiment_idexperiment=exp_id).all()
# Remove all pages and datafiles
remove_pages = page.query.filter_by(
experiment_idexperiment=exp_id).all()
for a in range(len(remove_pages)):
if remove_pages[a].type != 'text':
target = os.path.join(APP_ROOT, remove_pages[a].media)
if os.path.exists(target):
if os.path.exists(target):
os.remove(target)
#Now that the files are removed we can delete the page
# Now that the files are removed we can delete the page
db.session.delete(remove_pages[a])
db.session.commit()
#Remove all answer_sets and trial_randomization orders
remove_answer_set = answer_set.query.filter_by(experiment_idexperiment=exp_id).all()
# Remove all answer_sets and trial_randomization orders
remove_answer_set = answer_set.query.filter_by(
experiment_idexperiment=exp_id).all()
for a in range(len(remove_answer_set)):
remove_trial_randomizations = trial_randomization.query.filter_by(answer_set_idanswer_set=remove_answer_set[a].idanswer_set).all()
remove_trial_randomizations = trial_randomization.query.filter_by(
answer_set_idanswer_set=remove_answer_set[a].idanswer_set).all()
remove_rows(remove_trial_randomizations)
db.session.delete(remove_answer_set[a])
db.session.commit()
#Remove experiment table
remove_experiment = experiment.query.filter_by(idexperiment=exp_id).first()
# Remove experiment table
remove_experiment = experiment.query.filter_by(
idexperiment=exp_id).first()
db.session.delete(remove_experiment)
db.session.commit()
# Remove empty directories
os.rmdir(APP_ROOT + '/static/embody_images/' + str(exp_id))
os.rmdir(APP_ROOT + '/static/experiment_stimuli/' + str(exp_id))
flash("Experiment was removed from database!")
return redirect(url_for('index'))
else:
flash("Experiment was not removed!")
return redirect(url_for('experiment.view', exp_id=exp_id))
return render_template('remove_experiment.html', form=form, exp_id=exp_id)
......@@ -217,7 +234,8 @@ def remove():
@login_required
def publish():
exp_id = request.args.get('exp_id', None)
publish_experiment = experiment.query.filter_by(idexperiment = exp_id).first()
publish_experiment = experiment.query.filter_by(
idexperiment=exp_id).first()
publish_experiment.status = 'Public'
flash("Changed status to Public")
db.session.commit()
......@@ -228,7 +246,7 @@ def publish():
@login_required
def hide():
exp_id = request.args.get('exp_id', None)
hide_experiment = experiment.query.filter_by(idexperiment = exp_id).first()
hide_experiment = experiment.query.filter_by(idexperiment=exp_id).first()
hide_experiment.status = 'Hidden'
flash("Changed status to Hidden")
db.session.commit()
......@@ -239,7 +257,8 @@ def hide():
@login_required
def private():
exp_id = request.args.get('exp_id', None)
private_experiment = experiment.query.filter_by(idexperiment = exp_id).first()
private_experiment = experiment.query.filter_by(
idexperiment=exp_id).first()
private_experiment.status = 'Private'
flash("Changed status to Private")
db.session.commit()
......@@ -257,9 +276,10 @@ def randomization():
elif status == 'Off':
flash("Disabled trial randomization")
experiment.query.filter_by(idexperiment = exp_id).first().randomization = status
experiment.query.filter_by(
idexperiment=exp_id).first().randomization = status
db.session.commit()
return redirect(url_for('experiment.view', exp_id=exp_id))
......@@ -277,9 +297,10 @@ def set_forced_id():
elif status == 'Off':
flash("Disabled forced ID login")
experiment.query.filter_by(idexperiment = exp_id).first().use_forced_id = status
experiment.query.filter_by(
idexperiment=exp_id).first().use_forced_id = status
db.session.commit()
return redirect(url_for('experiment.view', exp_id=exp_id))
......@@ -291,29 +312,34 @@ def view_forced_id_list():
exp_id = request.args.get('exp_id', None)
id_list = forced_id.query.filter_by(experiment_idexperiment=exp_id).all()
form = GenerateIdForm(request.form)
if request.method == 'POST' and form.validate():
for i in range(int(request.form['number'])):
for i in range(int(request.form['number'])):
random_id = str(request.form['string']) + str(secrets.token_hex(3))
check_answer_set = answer_set.query.filter_by(session=random_id).first()
check_forced_id = forced_id.query.filter_by(pregenerated_id=random_id).first()
#here we check if the generated id is found from given answers from the whole database in answer_set table
#or from forced_id table. If so another id is generated instead to avoid a duplicate
check_answer_set = answer_set.query.filter_by(
session=random_id).first()
check_forced_id = forced_id.query.filter_by(
pregenerated_id=random_id).first()
# here we check if the generated id is found from given answers from the whole database in answer_set table
# or from forced_id table. If so another id is generated instead to avoid a duplicate
if check_answer_set is not None or check_forced_id is not None:
#flash("ID already existed; generated a new one")
random_id = secrets.token_hex(3)
check_answer_set = answer_set.query.filter_by(session=random_id).first()
check_forced_id = forced_id.query.filter_by(pregenerated_id=random_id).first()
input_id = forced_id(experiment_idexperiment=exp_id, pregenerated_id=random_id)
check_answer_set = answer_set.query.filter_by(
session=random_id).first()
check_forced_id = forced_id.query.filter_by(
pregenerated_id=random_id).first()
input_id = forced_id(
experiment_idexperiment=exp_id, pregenerated_id=random_id)
db.session.add(input_id)
db.session.commit()
return redirect(url_for('experiment.view_forced_id_list', exp_id=exp_id))
return render_template('view_forced_id_list.html', exp_id=exp_id, id_list=id_list)
......@@ -324,27 +350,27 @@ def upload_research_notification():
exp_id = request.args.get('exp_id', None)
form = UploadResearchBulletinForm(request.form)
if request.method == 'POST':
path = 'static/experiment_stimuli/' + str(exp_id)
target = os.path.join(APP_ROOT, path)
if not os.path.isdir(target):
os.mkdir(target)
#This returns a list of filenames: request.files.getlist("file")
# This returns a list of filenames: request.files.getlist("file")
for file in request.files.getlist("file"):
#save files in the correct folder
# save files in the correct folder
filename = file.filename
destination = "/".join([target, filename])
file.save(destination)
#add pages to the db
db_path = path + str('/') + str(filename)
# add pages to the db
db_path = path + str('/') + str(filename)
bulletin = experiment.query.filter_by(idexperiment=exp_id).first()
bulletin.research_notification_filename = db_path
db.session.commit()
return redirect(url_for('experiment.view', exp_id=exp_id))
return render_template('upload_research_notification.html', exp_id=exp_id, form=form)
......@@ -354,17 +380,19 @@ def upload_research_notification():
@login_required
def remove_research_notification():
'''Remove research bulletin'''
exp_id = request.args.get('exp_id', None)
empty_filevariable = experiment.query.filter_by(idexperiment=exp_id).first()
target = os.path.join(APP_ROOT, empty_filevariable.research_notification_filename)
if os.path.exists(target):
empty_filevariable = experiment.query.filter_by(
idexperiment=exp_id).first()
target = os.path.join(
APP_ROOT, empty_filevariable.research_notification_filename)
if os.path.exists(target):
os.remove(target)
empty_filevariable.research_notification_filename = None
db.session.commit()
return redirect(url_for('experiment.view', exp_id=exp_id))
......@@ -374,22 +402,20 @@ def edit():
'''Edit experiment details'''
exp_id = request.args.get('exp_id', None)
current_experiment = experiment.query.filter_by(idexperiment=exp_id).first()
current_experiment = experiment.query.filter_by(
idexperiment=exp_id).first()
form = EditExperimentForm(request.form, obj=current_experiment)
form.language.default = current_experiment.language
if request.method == 'POST' and form.validate():
form.populate_obj(current_experiment)
db.session.commit()
return redirect(url_for('experiment.view', exp_id=exp_id))
return render_template('edit_experiment.html', form=form, exp_id=exp_id)
return redirect(url_for('experiment.view', exp_id=exp_id))
return render_template('edit_experiment.html', form=form, exp_id=exp_id)
# Background questions:
......@@ -397,94 +423,100 @@ def edit():
@experiment_blueprint.route('/add_bg_question', methods=['GET', 'POST'])
@login_required
def add_bg_question():
exp_id = request.args.get('exp_id', None)
exp_status = experiment.query.filter_by(idexperiment=exp_id).first()
if exp_status.status != 'Hidden':
flash("Experiment is public. Cannot modify structure.")
return redirect(url_for('experiment.view', exp_id=exp_id))
else:
form = CreateBackgroundQuestionForm(request.form)
if request.method == 'POST' and form.validate():
#Split the form data into a list that separates questions followed by the corresponding options
# Split the form data into a list that separates questions followed by the corresponding options
str = form.bg_questions_and_options.data
str_list = str.split('/n')
#Iterate through the questions and options list
# Iterate through the questions and options list
for a in range(len(str_list)):
#Split the list cells further into questions and options
# Split the list cells further into questions and options
list = str_list[a].split(';')
#Input the first item of the list as a question in db and the items followed by that as options for that question
# Input the first item of the list as a question in db and the items followed by that as options for that question
for x in range(len(list)):
if x == 0:
add_bgquestion = background_question(background_question=list[x], experiment_idexperiment=exp_id)
add_bgquestion = background_question(
background_question=list[x], experiment_idexperiment=exp_id)
db.session.add(add_bgquestion)
db.session.commit()
else:
add_bgq_option = background_question_option(background_question_idbackground_question=add_bgquestion.idbackground_question, option=list[x])
add_bgq_option = background_question_option(
background_question_idbackground_question=add_bgquestion.idbackground_question, option=list[x])
db.session.add(add_bgq_option)
db.session.commit()
return redirect(url_for('experiment.view', exp_id=exp_id))
return redirect(url_for('experiment.view', exp_id=exp_id))
return render_template('add_bg_question.html', form=form)
@experiment_blueprint.route('/edit_bg_question', methods=['GET', 'POST'])
@login_required
def edit_bg_question():
bg_question_id = request.args.get('idbackground_question', None)
#Search for the right question and for the right options. Form a string of those separated with ";" and insert the
#formed string into the edit form
current_bg_question = background_question.query.filter_by(idbackground_question=bg_question_id).first()
exp_id=current_bg_question.experiment_idexperiment
# Search for the right question and for the right options. Form a string of those separated with ";" and insert the
# formed string into the edit form
current_bg_question = background_question.query.filter_by(
idbackground_question=bg_question_id).first()
exp_id = current_bg_question.experiment_idexperiment
question_string = current_bg_question.background_question
options = background_question_option.query.filter_by(background_question_idbackground_question=bg_question_id).all()
for o in range(len(options)):
question_string = str(question_string) + str("; ") + str(options[o].option)
options = background_question_option.query.filter_by(
background_question_idbackground_question=bg_question_id).all()
for o in range(len(options)):
question_string = str(question_string) + \
str("; ") + str(options[o].option)
form = EditBackgroundQuestionForm(request.form)
form.bg_questions_and_options.data = question_string
#After user chooses to update the question and options lets replace the old question and options with the ones from the form
# After user chooses to update the question and options lets replace the old question and options with the ones from the form
if request.method == 'POST' and form.validate():
#Explode the string with new values from the form
# Explode the string with new values from the form
form_values = form.new_values.data
form_values_list = form_values.split(';')
#Check and remove possible whitespaces from string beginnings with lstrip
# Check and remove possible whitespaces from string beginnings with lstrip
for x in range(len(form_values_list)):
form_values_list[x] = form_values_list[x].lstrip()
#Cycle through strings and update db
# Cycle through strings and update db
for x in range(len(form_values_list)):
#Replace question and update the object to database
# Replace question and update the object to database
if x == 0:
current_bg_question.background_question = form_values_list[x]
current_bg_question.background_question = form_values_list[x]
db.session.commit()
#Delete old options from db
# Delete old options from db
for o in options:
db.session.delete(o)
db.session.commit()
#Insert new options to db
# Insert new options to db
else:
new_option = background_question_option(background_question_idbackground_question=current_bg_question.idbackground_question, option=form_values_list[x])
new_option = background_question_option(
background_question_idbackground_question=current_bg_question.idbackground_question, option=form_values_list[x])
db.session.add(new_option)
db.session.commit()
return redirect(url_for('experiment.view', exp_id=exp_id))
return render_template('edit_bg_question.html', form=form, exp_id=exp_id)
......@@ -498,24 +530,24 @@ def remove_bg_question():
if exp_status.status != 'Hidden':
flash("Experiment is public. Cannot modify structure.")
return redirect(url_for('experiment.view', exp_id=exp_id))
else:
remove_id = request.args.get('idbackground_question', None)
remove_options = background_question_option.query.filter_by(background_question_idbackground_question=remove_id).all()