routes.py 66.4 KB
Newer Older
Timo Heikkilä's avatar
Timo Heikkilä committed
1
2
3
4
5
6
from app import app, db
from flask import render_template, request
from app.models import background_question, experiment
from app.models import background_question_answer
from app.models import page, question
from app.models import background_question_option
Timo Heikkilä's avatar
Timo Heikkilä committed
7
from app.models import answer_set, answer, forced_id
Timo Heikkilä's avatar
Timo Heikkilä committed
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from flask import session
from app.forms import LoginForm, RegisterForm
from flask import flash, redirect
from flask import url_for
from wtforms_sqlalchemy.fields import QuerySelectField
from app.forms import Answers, Questions
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy, BaseQuery
from app.forms import BackgroundQuestionForm
from wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField
from app.forms import TestForm, TestForm1, TestForm2, TaskForm
from collections import OrderedDict
from sqlalchemy import func, desc
from app.forms import ContinueTaskForm
from sqlalchemy import and_
from app.models import user, trial_randomization
from flask_login import current_user, login_user
from flask_login import logout_user
from flask_login import login_required
from sqlalchemy import update
from app.forms import StartWithIdForm
import secrets
Timo Heikkilä's avatar
Timo Heikkilä committed
30
from app.forms import CreateExperimentForm, CreateBackgroundQuestionForm, CreateQuestionForm, UploadStimuliForm, EditBackgroundQuestionForm, EditQuestionForm, EditExperimentForm, UploadResearchBulletinForm
Timo Heikkilä's avatar
Timo Heikkilä committed
31
32
33
34
35
36
37
38
39
40
41
42
from app.forms import EditPageForm, RemoveExperimentForm
import os
import random
from flask import Flask, make_response
import pyexcel as pe
import io
from io import BytesIO
import csv
from flask import send_file
from flask import make_response
from flask_babel import Babel
from app import babel
Timo Heikkilä's avatar
Timo Heikkilä committed
43
44
45
46
47
from datetime import datetime
from app.forms import GenerateIdForm
import math
from flask_babel import _
from flask_babel import lazy_gettext as _l
Timo Heikkilä's avatar
Timo Heikkilä committed
48
49
50
51
52
53
54
55
56
57
58
59

#Stimuli upload folder setting
APP_ROOT = os.path.dirname(os.path.abspath(__file__))




@app.route('/')
@app.route('/index')
def index():

    experiments = experiment.query.all()
Timo Heikkilä's avatar
Timo Heikkilä committed
60
61
62
63
64
65
66
    
    if session:
        
        flash("")
    
    else:
        
Timo Heikkilä's avatar
Timo Heikkilä committed
67
68
        #flash("sessio ei voimassa")
        session['language'] = "English"
Timo Heikkilä's avatar
Timo Heikkilä committed
69
    
Timo Heikkilä's avatar
Timo Heikkilä committed
70
71
72
73
74
75
    return render_template('index.html', title='Home', experiments=experiments)


@app.route('/consent')
def consent():
    exp_id = request.args.get('exp_id', None)
Timo Heikkilä's avatar
Timo Heikkilä committed
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90

    experiment_info = experiment.query.filter_by(idexperiment=exp_id).first()
    
    
    
    

    if experiment_info.use_forced_id == 'On':
        
        return redirect(url_for('begin_with_id', exp_id=exp_id))
        



    return render_template('consent.html', exp_id=exp_id, experiment_info=experiment_info)
Timo Heikkilä's avatar
Timo Heikkilä committed
91
92


Timo Heikkilä's avatar
Timo Heikkilä committed
93
94
95
96
97
@app.route('/set_language')
def set_language():
    
    session['language'] = request.args.get('language', None)
    
Timo Heikkilä's avatar
Timo Heikkilä committed
98
    lang = request.args.get('lang', None)
Timo Heikkilä's avatar
Timo Heikkilä committed
99
100
    
    
Timo Heikkilä's avatar
Timo Heikkilä committed
101
    return redirect(url_for('index', lang=lang))
Timo Heikkilä's avatar
Timo Heikkilä committed
102
103
104
105
106
107
108
109
110
111
112
113
114
115

@app.route('/remove_language')
def remove_language():
    
    
    experiments = experiment.query.all()
    
    
    return render_template('index.html', title='Home', experiments=experiments)





Timo Heikkilä's avatar
Timo Heikkilä committed
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
@app.route('/session')
def participant_session():

    #start session
    session['exp_id'] = request.args.get('exp_id', None)
    session['agree'] = request.args.get('agree', None)
    
  
    #If user came via the route for "I have already a participant ID that I wish to use, Use that ID, otherwise generate a random ID
    
    if 'begin_with_id' in session:

        session['user'] = session['begin_with_id']
        session.pop('begin_with_id', None)

    else:
        
        #lets generate a random id. If the same id is allready in db, lets generate a new one and finally use that in session['user']
        
        random_id = secrets.token_hex(3)
        check_id = answer_set.query.filter_by(session=random_id).first()

        while check_id is not None:
        
            #flash("ID already existed; generated a new one")
            random_id = secrets.token_hex(3)
            check_id = answer_set.query.filter_by(session=random_id).first()

        
        
        session['user'] = random_id
    
    
    #create answer set for the participant in the database
Timo Heikkilä's avatar
Timo Heikkilä committed
150
151
152
    the_time = datetime.now()
    the_time = the_time.replace(microsecond=0)
    participant_answer_set = answer_set(experiment_idexperiment=session['exp_id'], session=session['user'], agreement = session['agree'], answer_counter = '0', registration_time=the_time, last_answer_time=the_time)
Timo Heikkilä's avatar
Timo Heikkilä committed
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
    db.session.add(participant_answer_set)
    db.session.commit()
    
    
    
    #If trial randomization is set to 'On' for the experiment, create a randomized trial order for this participant
    #identification is based on the uniquie answer set id

    exp_status = experiment.query.filter_by(idexperiment=session['exp_id']).first()

    if exp_status.randomization == 'On':
    
        session['randomization'] = 'On'
        
        #flash("answer_set_id")
        #flash(participant_answer_set.idanswer_set)
        
        #create a list of page id:s for the experiment
        experiment_pages = page.query.filter_by(experiment_idexperiment=session['exp_id']).all()
        original_id_order_list = [(int(o.idpage)) for o in experiment_pages]
        
        
        #flash("original Page id order:")
        #for a in range(len(original_id_order_list)):
            
            #flash(original_id_order_list[a])
        
        #create a randomized page id list    
        helper_list = original_id_order_list 
        randomized_order_list = []
    
        for i in range(len(helper_list)):
    
            element = random.choice(helper_list)
            helper_list.remove(element)
            randomized_order_list.append(element)
       
        
        #Input values into trial_randomization table where the original page_ids have a corresponding randomized counterpart
        experiment_pages = page.query.filter_by(experiment_idexperiment=session['exp_id']).all()
        original_id_order_list = [(int(o.idpage)) for o in experiment_pages]
        
        for c in range(len(original_id_order_list)):
    
            random_page = trial_randomization(page_idpage=original_id_order_list[c], randomized_idpage=randomized_order_list[c], answer_set_idanswer_set = participant_answer_set.idanswer_set, experiment_idexperiment = session['exp_id'])
            db.session.add(random_page)
            db.session.commit()
    
    if exp_status.randomization == "Off":
        
        session['randomization'] = "Off"
    
    
    
    
    #store participants session id in session list as answer_set

    #old: was missing experiment id so made duplicates
    #session_id_for_participant = answer_set.query.filter_by(session=session['user']).first()
    
    #store participants session id in session list as answer_set, based on experiment id and session id
    session_id_for_participant = answer_set.query.filter(and_(answer_set.session==session['user'], answer_set.experiment_idexperiment==session['exp_id'])).first()
    session['answer_set'] = session_id_for_participant.idanswer_set
    
    #collect experiments mediatype from db to session['type']. 
    #This is later used in task.html to determine page layout based on stimulus type
    mediatype = page.query.filter_by(experiment_idexperiment=session['exp_id']).first()

    if mediatype:
        session['type'] = mediatype.type
    else:
        flash('No pages or mediatype set for experiment')
        return redirect('/')
    
    
    if 'user' in session:
        user = session['user']
        #flash('Session started for user {}'.format(user))
        return redirect('/register')
      
    return "Session start failed return <a href = '/login'></b>" + "Home</b></a>"


@app.route('/register', methods=['GET', 'POST'])
def register():
    
    
    form = RegisterForm(request.form)
    questions_and_options = {}
    questions = background_question.query.filter_by(experiment_idexperiment=session['exp_id']).all()

    for q in questions:    
    
        options = background_question_option.query.filter_by(background_question_idbackground_question=q.idbackground_question).all()
        options_list = [(o.option, o.idbackground_question_option) for o in options]
        questions_and_options[q.idbackground_question, q.background_question]  = options_list
    
 
    form.questions1 = questions_and_options
    
    if request.method == 'POST'and form.validate():
    
        data = request.form.to_dict()
        for key, value in data.items():

            
            #tähän db insertit

            #flash(key)
            #flash(value)
            #Input registration page answers to database
            participant_background_question_answers = background_question_answer(answer_set_idanswer_set=session['answer_set'], answer=value, background_question_idbackground_question=key)
            db.session.add(participant_background_question_answers)
            db.session.commit()

        return redirect('/instructions')
   
    
    return render_template('register.html', form=form)


@app.route('/task_completed')
def task_completed():
    
    session.pop('user', None)
    session.pop('exp_id', None)    
    session.pop('agree', None)
    session.pop('answer_set', None)
    session.pop('type', None)
    session.pop('randomization', None)

    
    return render_template('task_completed.html')


@app.route('/continue_task', methods=['GET', 'POST'])
def continue_task():
    
    
    exp_id = request.args.get('exp_id', None)
    form = ContinueTaskForm()
    

    if form.validate_on_submit():
        
        #check if participant ID is found from db and that the answer set is linked to the correct experiment
        participant = answer_set.query.filter(and_(answer_set.session==form.participant_id.data, answer_set.experiment_idexperiment==exp_id)).first()
        if participant is None:
            flash('Invalid ID')
            return redirect(url_for('continue_task', exp_id=exp_id))        
        
        #flash('Login requested for participant {}'.format(form.participant_id.data))
        
        #if correct participant_id is found with the correct experiment ID; start session for that user
        session['exp_id'] = exp_id
        session['user'] = form.participant_id.data 
        session['answer_set'] = participant.idanswer_set
        mediatype = page.query.filter_by(experiment_idexperiment=session['exp_id']).first()
        
        rand = experiment.query.filter_by(idexperiment=session['exp_id']).first()
        
        session['randomization'] = rand.randomization
    
        if mediatype:
            session['type'] = mediatype.type
        else:
            flash('No pages or mediatype set for experiment')
            return redirect('/')


        #If participant has done just the registration redirect to the first page of the experiment        
        if participant.answer_counter == 0:
            #flash("Ei vastauksia ohjataan ekalle sivulle")
            return redirect( url_for('task', page_num=1))
        
        
        redirect_to_page = participant.answer_counter + 1
        
        
        #flash("redirect to page:")
        #flash(redirect_to_page)

        experiment_page_count = db.session.query(page).filter_by(experiment_idexperiment=session['exp_id']).count()
        
        #If participant has ansvered all pages allready redirect to task completed page
        if experiment_page_count == participant.answer_counter:
            
            return redirect( url_for('task_completed'))
        
        
        return redirect( url_for('task', page_num=redirect_to_page))
        
    return render_template('continue_task.html', exp_id=exp_id, form=form)


@app.route('/begin_with_id', methods=['GET', 'POST'])
def begin_with_id():
    
    
    exp_id = request.args.get('exp_id', None)
    form = StartWithIdForm()
Timo Heikkilä's avatar
Timo Heikkilä committed
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
    experiment_info = experiment.query.filter_by(idexperiment=exp_id).first()

    if form.validate_on_submit():
        
        variable = form.participant_id.data
        
        #check if participant ID is found from db with this particular ID. If a match is found inform about error
        participant = answer_set.query.filter(and_(answer_set.session==variable, answer_set.experiment_idexperiment==exp_id)).first()
        is_id_valid = forced_id.query.filter(and_(forced_id.pregenerated_id==variable, forced_id.experiment_idexperiment==exp_id)).first()
        
        if participant is not None:
            flash(_('ID already in use'))
            return redirect(url_for('begin_with_id', exp_id=exp_id))        
        
        #if there was not a participant already in DB:
        if participant is None:
    
            if is_id_valid is None:

                                
                flash(_('No such ID set for this experiment'))
                return redirect(url_for('begin_with_id', exp_id=exp_id))        

            else:
                
                #save the participant ID in session list for now, this is deleted after the session has been started in participant_session-view
                session['begin_with_id'] = form.participant_id.data
                return render_template('consent.html', exp_id=exp_id, experiment_info=experiment_info)
        
    return render_template('begin_with_id.html', exp_id=exp_id, form=form)


@app.route('/admin_dryrun', methods=['GET', 'POST'])
@login_required
def admin_dryrun():
    
    
    exp_id = request.args.get('exp_id', None)
    form = StartWithIdForm()
    experiment_info = experiment.query.filter_by(idexperiment=exp_id).first()
Timo Heikkilä's avatar
Timo Heikkilä committed
394
395
396
397
398
399
400

    if form.validate_on_submit():
        
        #check if participant ID is found from db with this particular ID. If a match is found inform about error
        participant = answer_set.query.filter(and_(answer_set.session==form.participant_id.data, answer_set.experiment_idexperiment==exp_id)).first()
        if participant is not None:
            flash('ID already in use')
Timo Heikkilä's avatar
Timo Heikkilä committed
401
            return redirect(url_for('admin_dryrun', exp_id=exp_id))        
Timo Heikkilä's avatar
Timo Heikkilä committed
402
403
404
405
406
        
        #if there was not a participant already in DB:
        if participant is None:
            #save the participant ID in session list for now, this is deleted after the session has been started in participant_session-view
            session['begin_with_id'] = form.participant_id.data
Timo Heikkilä's avatar
Timo Heikkilä committed
407
            return render_template('consent.html', exp_id=exp_id, experiment_info=experiment_info)
Timo Heikkilä's avatar
Timo Heikkilä committed
408
409

        
Timo Heikkilä's avatar
Timo Heikkilä committed
410
411
    return render_template('admin_dryrun.html', exp_id=exp_id, form=form)

Timo Heikkilä's avatar
Timo Heikkilä committed
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429


@app.route('/create_task')
def create_task():
    return render_template('create_task.html')


@app.route('/instructions')
def instructions():
    
    participant_id = session['user']
    instructions = experiment.query.filter_by(idexperiment = session['exp_id']).all()
    return render_template('instructions.html', instructions=instructions, participant_id=participant_id)


@app.route('/task/<int:page_num>', methods=['GET', 'POST'])
def task(page_num):

Timo Heikkilä's avatar
Timo Heikkilä committed
430
431
432
433
434
435
436
437
438
    
    experiment_info = experiment.query.filter_by(idexperiment=session['exp_id']).first()
    rating_instruction = experiment_info.single_sentence_instruction
    stimulus_size = experiment_info.stimulus_size
    
    #for text stimuli the size needs to be calculated since the template element utilises h1-h6 tags.
    #A value of stimulus size 12 gives h1 and value of 1 gives h6
    stimulus_size_text = 7-math.ceil((int(stimulus_size)/2))
    
Timo Heikkilä's avatar
Timo Heikkilä committed
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
    pages = page.query.filter_by(experiment_idexperiment=session['exp_id']).paginate(per_page=1, page=page_num, error_out=True)
    progress_bar_percentage = round((pages.page/pages.pages)*100)

    #this variable is feeded to the template as empty if trial randomization is set to "off"
    randomized_stimulus = ""



    #if trial randomization is on we will still use the same functionality that is used otherwise
    #but we will pass the randomized pair of the page_id from trial randomization table to the task.html
    if session['randomization'] == 'On':
        
    
        randomized_page_id = trial_randomization.query.filter(and_(trial_randomization.answer_set_idanswer_set==session['answer_set'], trial_randomization.page_idpage==pages.items[0].idpage)).first()
        #answer.query.filter(and_(answer.answer_set_idanswer_set==session['answer_set'], answer.page_idpage==session['current_idpage'])).first()
        #flash("randomized page:")
        #flash(randomized_page_id.randomized_idpage)
        #set the stimulus to be shown if randomization is on
        randomized_stimulus = page.query.filter_by(idpage=randomized_page_id.randomized_idpage).first()
        

        
    for p in pages.items:
        session['current_idpage'] = p.idpage
    
    #slider set
    form = TaskForm(request.form)
    categories_and_scales = {}
    categories = question.query.filter_by(experiment_idexperiment=session['exp_id']).all()

    for cat in categories:    
        
        scale_list = [(cat.left, cat.right)]
        categories_and_scales[cat.idquestion, cat.question]  = scale_list
    
    form.categories1 = categories_and_scales
    

    #slider set form handling
    if request.method == 'POST'and form.validate():
        

        #Lets check if there are answers in database already for this page_id (eg. if user returned to previous page and tried to answer again)
        #If so flash ("Page has been answered already. Answers discarded"), else insert values in to db
        #this has to be done separately for trial randomization "on" and "off" situations        
        
        if session['randomization'] == 'On':
        
            check_answer = answer.query.filter(and_(answer.answer_set_idanswer_set==session['answer_set'], answer.page_idpage==randomized_page_id.randomized_idpage)).first()
        
        if session['randomization'] == 'Off':
        
            check_answer = answer.query.filter(and_(answer.answer_set_idanswer_set==session['answer_set'], answer.page_idpage==session['current_idpage'])).first()
        


Timo Heikkilä's avatar
Timo Heikkilä committed
495
496
497
498
        if check_answer is None:
            
            the_time = datetime.now()
            the_time = the_time.replace(microsecond=0)
Timo Heikkilä's avatar
Timo Heikkilä committed
499
500
501
            
            update_answer_counter = answer_set.query.filter_by(idanswer_set=session['answer_set']).first()
            update_answer_counter.answer_counter = int(update_answer_counter.answer_counter) + 1 
Timo Heikkilä's avatar
Timo Heikkilä committed
502
503
            update_answer_counter.last_answer_time = the_time
        
Timo Heikkilä's avatar
Timo Heikkilä committed
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
            #flash("vastauksia:")
            #flash(update_answer_counter.answer_counter)
            db.session.commit()
        
            data = request.form.to_dict()
            for key, value in data.items():
            
                #flash(key)
                #flash(value)
                #flash(session['current_idpage'])
            
            
                #Insert slider values to database
                
                
                #If trial randomization is set to 'Off' the values are inputted for session['current_idpage']
                #Otherwise the values are set for the corresponding id found in the trial randomization table
                
                if session['randomization'] == 'Off':
                
                    participant_answer = answer(question_idquestion=key, answer_set_idanswer_set=session['answer_set'], answer=value, page_idpage=session['current_idpage'])
                    db.session.add(participant_answer)
                    db.session.commit()

                else:

                    participant_answer = answer(question_idquestion=key, answer_set_idanswer_set=session['answer_set'], answer=value, page_idpage=randomized_page_id.randomized_idpage)
                    db.session.add(participant_answer)
                    db.session.commit()
                    

        else:
                flash("Page has been answered already. Answers discarded")
        
        page_num=pages.next_num
        
        if pages.has_next:
            return redirect( url_for('task', page_num=pages.next_num))
        
        return redirect ( url_for('task_completed'))

    
Timo Heikkilä's avatar
Timo Heikkilä committed
546
    return render_template('task.html', pages=pages, progress_bar_percentage=progress_bar_percentage, form=form, randomized_stimulus=randomized_stimulus, rating_instruction=rating_instruction, stimulus_size=stimulus_size, stimulus_size_text=stimulus_size_text)
Timo Heikkilä's avatar
Timo Heikkilä committed
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565



@app.route('/quit_task')
def quit_task():
    
    user_id = session['user']
    session.pop('user', None)
    session.pop('exp_id', None)    
    session.pop('agree', None)
    session.pop('answer_set', None)
    session.pop('type', None)
    
    return render_template('quit_task.html', user_id=user_id)


@app.route('/researcher_login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
Timo Heikkilä's avatar
Timo Heikkilä committed
566
        #flash("allready logged in")
Timo Heikkilä's avatar
Timo Heikkilä committed
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
        return redirect(url_for('index'))
    form = LoginForm()
    if form.validate_on_submit():
        user_details = user.query.filter_by(username=form.username.data).first()
        if user_details is None or not user_details.check_password(form.password.data):
            flash('Invalid username or password')
            return redirect(url_for('login'))
        login_user(user_details, remember=form.remember_me.data)    
        return redirect(url_for('index'))
    
#        flash('Login requested for user {}, remember_me={}'.format(
#            form.username.data, form.remember_me.data))
#        return redirect('/index')
    return render_template('researcher_login.html', title='Sign In', form=form)


@app.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('index'))


@app.route('/experiment_statistics')
@login_required
def experiment_statistics():
    
    exp_id = request.args.get('exp_id', None)
    
    experiment_info = experiment.query.filter_by(idexperiment = exp_id).all()
    participants = answer_set.query.filter_by(experiment_idexperiment= exp_id).all()
    
    
Timo Heikkilä's avatar
Timo Heikkilä committed
599
600
601
602
603
    #Rating task headers
    question_headers = question.query.filter_by(experiment_idexperiment=exp_id).all()
    stimulus_headers = page.query.filter_by(experiment_idexperiment=exp_id).all()
    

Timo Heikkilä's avatar
Timo Heikkilä committed
604
605
606
607



    pages = page.query.filter_by(experiment_idexperiment=exp_id).all()
Timo Heikkilä's avatar
Timo Heikkilä committed
608
    questions = question.query.filter_by(experiment_idexperiment=exp_id).all()
Timo Heikkilä's avatar
Timo Heikkilä committed
609
610
611
612
    pages_and_questions = {}

    for p in pages:
        
Timo Heikkilä's avatar
Timo Heikkilä committed
613
        questions_list = [(p.idpage, a.idquestion) for a in questions]
Timo Heikkilä's avatar
Timo Heikkilä committed
614
        pages_and_questions[p.idpage] = questions_list 
Timo Heikkilä's avatar
Timo Heikkilä committed
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637



        
    #List of answers per participant in format question Stimulus ID/Question ID
    #those are in answer table as page_idpage and question_idquestion respectively
    
    
    
    """
    pages = page.query.filter_by(experiment_idexperiment=exp_id).all()
    
    participants_and_answers = {}
    
    #participants on kaikki expin osallistujat
    for participant in participants:
 
            
        #kaikki yhden khn vastaukset ko experimentille koska answer_setin id matchaa answereiden kanssa
             
    
        flash(participant.session)
        for p in pages:
Timo Heikkilä's avatar
Timo Heikkilä committed
638
        
Timo Heikkilä's avatar
Timo Heikkilä committed
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
            answers = answer.query.filter_by(answer_set_idanswer_set=participant.idanswer_set).all()
            #kaikki yhden participantin vastaukset pagelle
            answers_for_page = answer.query.filter(and_(answer.answer_set_idanswer_set==participant.idanswer_set, answer.page_idpage==p.idpage)).all()
            
            
            for ans in answers:
            
                
                
                if ans.page_idpage == p.idpage:
                
                    #flash(ans.page_idpage)
                    flash("X")
                    
                    
                    
                    
                else:
                    
                    flash("NA")
            
            #pages on kaikki experimentin paget
          
                      
            
            for a in answers:

                if p.idpage == a.page_idpage:
                    flash("match")
                
                else:
                    flash("no match")
                 flash("participant:")
                flash(participant.session)
                flash("stimulus:")
                flash(a.page_idpage)
                flash("Kysymys")
                flash(a.question_idquestion)
                flash("vastaus:")
                flash(a.answer)
            
                
                
                
            #answers_list = (a.idanswer, a.question_idquestion, a.answer_set_idanswer_set, a.answer, a.page_idpage)

            #participants_and_answers[participant.session] = answers_list 

    
            """
    
    participants_and_answers = {}
    
    for participant in participants:
 
        answers = answer.query.filter_by(answer_set_idanswer_set=participant.idanswer_set).all()     
        answers_list = [(a.idanswer, a.question_idquestion, a.answer_set_idanswer_set, a.answer, a.page_idpage) for a in answers]    
        participants_and_answers[participant.session] = answers_list 
    
    

    #Background question answers
Timo Heikkilä's avatar
Timo Heikkilä committed
701
702
703
        
    bg_questions = background_question.query.filter_by(experiment_idexperiment=exp_id).all()
    bg_answers_for_participants = {}
Timo Heikkilä's avatar
Timo Heikkilä committed
704

Timo Heikkilä's avatar
Timo Heikkilä committed
705
706
707
708
709
710
    for participant in participants:
        
        bg_answers = background_question_answer.query.filter_by(answer_set_idanswer_set=participant.idanswer_set).all() 
        bg_answers_list = [(a.answer) for a in bg_answers] 
        bg_answers_for_participants[participant.session] = bg_answers_list 
     
Timo Heikkilä's avatar
Timo Heikkilä committed
711
712

    #started and finished ratings counters    
Timo Heikkilä's avatar
Timo Heikkilä committed
713
    started_ratings = answer_set.query.filter_by(experiment_idexperiment=exp_id).count()
Timo Heikkilä's avatar
Timo Heikkilä committed
714
715
    experiment_page_count = page.query.filter_by(experiment_idexperiment=exp_id).count()
    finished_ratings = answer_set.query.filter(and_(answer_set.answer_counter==experiment_page_count, answer_set.experiment_idexperiment==exp_id)).count()
Timo Heikkilä's avatar
Timo Heikkilä committed
716
717
718
    
    
    
Timo Heikkilä's avatar
Timo Heikkilä committed
719
    return render_template('experiment_statistics.html', experiment_info=experiment_info, participants_and_answers=participants_and_answers, pages_and_questions=pages_and_questions, bg_questions=bg_questions, bg_answers_for_participants=bg_answers_for_participants, started_ratings=started_ratings, finished_ratings=finished_ratings, question_headers=question_headers, stimulus_headers=stimulus_headers)
Timo Heikkilä's avatar
Timo Heikkilä committed
720
721
722
723
724
725
726
727
728
729
730
731
732
733



#EDIT FUNCTIONS

@app.route('/create_experiment', methods=['GET', 'POST'])
@login_required
def create_experiment():
    
    form = CreateExperimentForm(request.form)   


    if request.method == 'POST' and form.validate():
        
Timo Heikkilä's avatar
Timo Heikkilä committed
734
735
736
737
738
        
        the_time = datetime.now()
        the_time = the_time.replace(microsecond=0)
        
        new_exp = experiment(name=request.form['name'], instruction=request.form['instruction'], language=request.form['language'], status='Hidden', randomization='Off', single_sentence_instruction=request.form['single_sentence_instruction'], short_instruction=request.form['short_instruction'], creator_name=request.form['creator_name'], is_archived='False', creation_time=the_time, stimulus_size='7', consent_text=request.form['consent_text'], use_forced_id='Off')
Timo Heikkilä's avatar
Timo Heikkilä committed
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
        db.session.add(new_exp)
        db.session.commit()        
        
        #flash("lol")
        #flash(new_exp.idexperiment)
        
        exp_id = new_exp.idexperiment

        #data = request.form.to_dict()
        #for key, value in data.items():
            #tähän db insertit

            #flash(key)
            #flash(value)
            #flash('{}'.format(form.name.data))
        
            #Input registration page answers to database
           # participant_background_question_answers = background_question_answer(answer_set_idanswer_set=session['answer_set'], answer=value, background_question_idbackground_question=key)
           # db.session.add(participant_background_question_answers)
           # db.session.commit()

        return redirect(url_for('create_experiment_bgquestions', exp_id=exp_id))

    return render_template('create_experiment.html', form=form)



@app.route('/create_experiment_bgquestions', methods=['GET', 'POST'])
@login_required
def create_experiment_bgquestions():
    
    exp_id = request.args.get('exp_id', None)
    form = CreateBackgroundQuestionForm(request.form)
    
    if request.method == 'POST' and form.validate():
        
        #data = request.form.to_dict()
        
        #flash(data)
        #flash(form.bg_questions_and_options.data)
        

        str = form.bg_questions_and_options.data

        #Split the form data into a list that separates questions followed by the corresponding options
        str_list = str.split('/n')

        #Iterate through the questions and options list
        for a in range(len(str_list)):
        
            #Split the list cells further into questions and options
            list = str_list[a].split(';')
        
            #flash(list[0])
            #flash("id oikein?")
            #flash(add_bgquestion.idbackground_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:
                    #flash("Kysymys")
                    #flash(list[x])
                    add_bgquestion = background_question(background_question=list[x], experiment_idexperiment=exp_id)
                    db.session.add(add_bgquestion)
                    db.session.commit()

                else:
                    #flash("optio")
                    #flash(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('create_experiment_questions', exp_id=exp_id))    

    return render_template('create_experiment_bgquestions.html', form=form, exp_id=exp_id)


@app.route('/create_experiment_questions', methods=['GET', 'POST'])
@login_required
def create_experiment_questions():
    
    exp_id = request.args.get('exp_id', None)
    
    form = CreateQuestionForm(request.form)
    
    if request.method == 'POST' and form.validate():

        str = form.questions_and_options.data

        str_list = str.split('/n')

        for a in range(len(str_list)): 

            list = str_list[a].split(';')
                     
Timo Heikkilä's avatar
Timo Heikkilä committed
837
838
839
840
841
            #If there are the wrong amount of values for any of the the slider input values
            #redirect back to the form
            if len(list) != 3:
                

Timo Heikkilä's avatar
Timo Heikkilä committed
842
843
844
845
                flash("Error Each slider must have 3 parameters separated by ; Some slider has:")
                flash(len(list))
                    
                return redirect(url_for('create_experiment_questions', exp_id=exp_id))
Timo Heikkilä's avatar
Timo Heikkilä committed
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863

        #If all the slider inputs were of length 3 items
        #we can input them to db
        for a in range(len(str_list)): 

            list = str_list[a].split(';')
       
            #flash("Question:")
            #flash(list[0])
            #flash("Left:")
            #flash(list[1])
            #flash("Right:")
            #flash(list[2])

            add_question = question(experiment_idexperiment=exp_id, question=list[0], left=list[1], right=list[2])
            db.session.add(add_question)
            db.session.commit()
                    
Timo Heikkilä's avatar
Timo Heikkilä committed
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
        
        return redirect(url_for('create_experiment_upload_stimuli', exp_id=exp_id))    

    return render_template('create_experiment_questions.html', form=form)


@app.route('/create_experiment_upload_stimuli', methods=['GET', 'POST'])
@login_required
def create_experiment_upload_stimuli():
    
    exp_id = request.args.get('exp_id', None)
    
    form = UploadStimuliForm(request.form)
    
    if request.method == 'POST' and form.validate():
    
        #flash("validated")    
        #flash(form.type.data)
        #flash(form.text.data)
        
        
        #If stimulus type is text lets parse the information and insert it to database
        
        if form.type.data == 'text':
        
            #flash("db insert text")
            
            string = form.text.data
            str_list = string.split('/n')

            for a in range(len(str_list)):

                #flash("lisättiin:")
                #flash(str_list[a])
                add_text_stimulus = page(experiment_idexperiment=exp_id, type='text', text=str_list[a], media='none')
                db.session.add(add_text_stimulus)
                db.session.commit()

                #flash("Succes!")
                
            return redirect(url_for('view_experiment', exp_id=exp_id))  
                
                
        
        else:

            #Upload stimuli into /static/experiment_stimuli/exp_id folder
            #Create the pages for the stimuli by inserting experiment_id, stimulus type, text and names of the stimulus files (as a path to the folder)
            path = 'static/experiment_stimuli/' + str(exp_id)
        
            target = os.path.join(APP_ROOT, path)
            #flash(target)
            
            if not os.path.isdir(target):
                os.mkdir(target)
                #flash("make dir")
        
        
            #This returns a list of filenames: request.files.getlist("file")
        
            for file in request.files.getlist("file"):
            
                #save files in the correct folder
                #flash(file.filename)
                filename = file.filename
                destination = "/".join([target, filename])
                #flash("destination")
                #flash(destination)
                file.save(destination)
                
                #add pages to the db
                db_path = path +  str('/') + str(filename)
                
                #flash("db path")
                #flash(db_path)
                
                new_page = page(experiment_idexperiment=exp_id, type=form.type.data, media=db_path)
                
                db.session.add(new_page)
                db.session.commit()
                
                #flash("Succes!")
                
            return redirect(url_for('view_experiment', exp_id=exp_id))
            
        return redirect(url_for('create_experiment_upload_stimuli', exp_id=exp_id))

    return render_template('create_experiment_upload_stimuli.html', form=form)


@app.route('/view_experiment')
@login_required
def view_experiment():
    
    #crap:3lines
    exp_id = request.args.get('exp_id', None)
Timo Heikkilä's avatar
Timo Heikkilä committed
960
    media = page.query.filter_by(experiment_idexperiment=exp_id).all()
Timo Heikkilä's avatar
Timo Heikkilä committed
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
    mtype = page.query.filter_by(experiment_idexperiment=exp_id).first()
    
    #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()

    for q in questions:    
    
        options = background_question_option.query.filter_by(background_question_idbackground_question=q.idbackground_question).all()
        options_list = [(o.option, o.idbackground_question_option) for o in options]
        questions_and_options[q.idbackground_question, q.background_question]  = options_list
 
    questions1 = questions_and_options
    
    #sliderset
    categories_and_scales = {}
    categories = question.query.filter_by(experiment_idexperiment=exp_id).all()

    for cat in categories:    
        
        scale_list = [(cat.left, cat.right)]
        categories_and_scales[cat.idquestion, cat.question]  = scale_list
 
    categories1 = categories_and_scales
    
    
    return render_template('view_experiment.html', exp_id=exp_id, media=media, mtype=mtype, experiment_info=experiment_info, categories1=categories1, questions1=questions1)


@app.route('/edit_experiment', methods=['GET', 'POST'])
@login_required
def edit_experiment():

    exp_id = request.args.get('exp_id', None)
        
    current_experiment = experiment.query.filter_by(idexperiment=exp_id).first()
    
For faster browsing, not all history is shown. View entire blame