def home(): form = TestForm() if form.validate_on_submit(): name = form.name.data return render_template("home.html", form=form, name=name) return render_template("home.html", form=form, logout=users.create_logout_url(request.url))
def tm(page=1): if g.user.role.name == ROLE_HEAD_OF_TACTICAL_LEVEL: is_om_answered_on_questions = ApplicationData.is_om_answered_on_questions() try: chosen_processes = UserChoice.user_choice_processes_by_role_id(g.user.role_id).paginate(page, 1, False) except NoResultFound: chosen_processes = [] if is_om_answered_on_questions.status: current_process = chosen_processes.items[0] questions_by_process = Question.chosen_questions(current_process.id).all() else: current_process = None questions_by_process = [] form = TestForm(questions=questions_by_process) is_tm_answered_on_questions = ApplicationData.is_tm_answered_on_questions() if form.validate_on_submit(): if form.finish.data: page = chosen_processes.pages save_answers_to_db(form, g.user.role_id, current_process.id) if not is_tm_answered_on_questions.status: is_tm_answered_on_questions.status = bool(not is_tm_answered_on_questions.status) is_tm_answered_on_questions.update() if form.next_page.data: save_answers_to_db(form, g.user.role_id, current_process.id) page = chosen_processes.next_num return redirect(url_for('tm', page=page)) html = render_template('roles/tm.html', form=form, current_process=current_process, is_om_answered_on_questions=is_om_answered_on_questions, is_tm_answered_on_questions=is_tm_answered_on_questions, processes=chosen_processes, investment_level=UserChoice.user_choice_chosen_investment_level()) return __make_tooltips(html) else: return u'Вы не можете получить доступ к этой странице'
def cso_testing(page=1): if g.user.role.name == ROLE_HEAD_OF_INFORMATION_SECURITY: is_tm_answered_on_questions = ApplicationData.is_tm_answered_on_questions() chosen_processes = UserChoice.user_choice_processes_by_role_id(g.user.role_id).paginate(page, 1, False) if is_tm_answered_on_questions.status: current_process = chosen_processes.items[0] questions_by_process = Question.chosen_questions(current_process.id).all() else: current_process = None questions_by_process = [] form = TestForm(questions=questions_by_process) is_cso_answered_on_questions = ApplicationData.is_cso_answered_on_questions() if form.validate_on_submit(): if form.finish.data: save_answers_to_db(form, g.user.role_id, current_process.id) if not is_cso_answered_on_questions.status: is_cso_answered_on_questions.status = bool(not is_cso_answered_on_questions.status) is_cso_answered_on_questions.update() make_statistic() return redirect(url_for('cso')) if form.next_page.data: save_answers_to_db(form, g.user.role_id, current_process.id) page = chosen_processes.next_num return redirect(url_for('cso_testing', page=page)) html = render_template('roles/cso_testing.html', form=form, current_process=current_process, is_tm_answered_on_questions=is_tm_answered_on_questions, is_cso_answered_on_questions=is_cso_answered_on_questions, processes=chosen_processes, investment_level=UserChoice.user_choice_chosen_investment_level()) return __make_tooltips(html) else: return u'Вы не можете получить доступ к этой странице'
def new_test(): form = TestForm() if form.validate_on_submit(): test = Test( test_name=form.test_name.data, num_mc=form.num_mc.data, mc_answers=int(form.mc_answers.data), num_or=form.num_or.data, #or_points = int(form.or_points.data), num_students=form.num_students.data, #test_data = defaultGrid(form.num_mc.data, int(form.mc_answers.data), form.num_or.data, form.or_points.data,form.num_students.data), mc_data=mcDetails(form.num_mc.data, int(form.mc_answers.data)), or_data=orDetails(form.num_mc.data, form.num_or.data), student_data=studentDetails(form.num_students.data), added_by=session['email']) try: test.put() test_id = test.key.id() test = Test.get_by_id(test_id) mc_data = json.dumps(test.mc_data) or_data = json.dumps(test.or_data) student_data = json.dumps(test.student_data) flash(u'Test %s successfully saved.' % test_id, 'success') return render_template('test_details.html', test=Test.get_by_id(test_id), test_id=test_id, mc_data=mc_data, or_data=or_data, student_data=student_data) except CapabilityDisabledError: flash(u'App Engine Datastore is currently in read-only mode.', 'info') return redirect(url_for('list_tests')) return redirect(url_for('list_tests'))
def new_test(): form = TestForm() if form.validate_on_submit(): test = Test( test_name=form.test_name.data, num_mc=form.num_mc.data, mc_answers = int(form.mc_answers.data), num_or=form.num_or.data, #or_points = int(form.or_points.data), num_students=form.num_students.data, #test_data = defaultGrid(form.num_mc.data, int(form.mc_answers.data), form.num_or.data, form.or_points.data,form.num_students.data), mc_data = mcDetails(form.num_mc.data, int(form.mc_answers.data)), or_data = orDetails(form.num_mc.data,form.num_or.data), student_data = studentDetails(form.num_students.data), added_by=session['email'] ) try: test.put() test_id = test.key.id() test = Test.get_by_id(test_id) mc_data = json.dumps(test.mc_data) or_data = json.dumps(test.or_data) student_data = json.dumps(test.student_data) flash(u'Test %s successfully saved.' % test_id, 'success') return render_template('test_details.html', test = Test.get_by_id(test_id), test_id = test_id, mc_data = mc_data, or_data = or_data, student_data = student_data) except CapabilityDisabledError: flash(u'App Engine Datastore is currently in read-only mode.', 'info') return redirect(url_for('list_tests')) return redirect(url_for('list_tests'))
def cio(page=1): """ Отображение страницы для CIO :param page: номер страницы (int) :return: html """ # Проверяем полномочия пользователя (пользователь может просматривать страницы только по своему уровню доступа) if g.user.role.name == ROLE_HEAD_OF_BASE_LEVEL: # Получаем информацию о состоянии системы is_cso_choose_processes = ApplicationData.is_cso_choose_processes() # Получаем процессы, по которым должен пользователь пройти тестирование # метод paginate(page, count, error_out) возвращает список объектов в количестве count на страницу page # тем самым добиваемся того, что тестирование по 1 процессу является 1 страница try: chosen_processes = UserChoice.user_choice_processes_by_role_id(g.user.role_id).paginate(page, 1, False) except NoResultFound: chosen_processes = [] if is_cso_choose_processes.status: # Определяем текущий процесс и список вопросов, которые нужно будет отрисовать на форме current_process = chosen_processes.items[0] questions_by_process = Question.chosen_questions(current_process.id).all() else: # Эта ветвь необходима для корректного завершения функции (например, когда тестирование не началось, # а CSO прошёл аутентификацию current_process = None questions_by_process = [] # Создаём форму, в которую будут поступать ответы пользователя form = TestForm(questions=questions_by_process) is_cio_answered_on_questions = ApplicationData.is_cio_answered_on_questions() # Форма прошла валидацию и отправлена? if form.validate_on_submit(): # Тестирование завершено? if form.finish.data: page = chosen_processes.pages # Сохраняем ответы в базу данных save_answers_to_db(form, g.user.role_id, current_process.id) if not is_cio_answered_on_questions.status: # Изменяем параметр пройденности тестирования пользователя cio на обратное (False -> True) is_cio_answered_on_questions.status = bool(not is_cio_answered_on_questions.status) # Сохраняем параметр в базе данных is_cio_answered_on_questions.update() # Если пользователю предстоит проходить тестирование по нескольким процессам, # и есть ещё процессы, на вопросы которых он не ответил, # то сохраняем ответы со страницы и изменяем номер страницы на 1 if form.next_page.data: save_answers_to_db(form, g.user.role_id, current_process.id) page = chosen_processes.next_num # Перенаправление пользователя на новый номер страницы return redirect(url_for('cio', page=page)) # Отрисовка страницы html = render_template('roles/cio.html', form=form, current_process=current_process, is_cso_choose_processes=is_cso_choose_processes, is_cio_answered_on_questions=is_cio_answered_on_questions, processes=chosen_processes, investment_level=UserChoice.user_choice_chosen_investment_level()) return __make_tooltips(html) else: return u'Вы не можете получить доступ к этой странице'
def test(user_id, step, reps=5): form = TestForm() test_image_urls = get_gesture_sequence(reps) data = form.data.data gesture = form.image.data.split('/')[-1].replace( '_', ' ').split('.')[0].strip() # Handle index out of range error if step >= len(test_image_urls): return redirect( url_for('.test', user_id=user_id, step=len(test_image_urls) - 1)) tests_per_rep = int(len(test_image_urls) / reps) rep = math.ceil((step + 1) / tests_per_rep) # remove data with matching id, cal_id && gesture from database db.clear_existing_data({ 'subject_id': user_id, 'gesture': gesture, 'repetition': rep }) if form.validate_on_submit(): rows = [] # insert data into database for count, item in enumerate(data): reading, timestamp = item timestamp = time.strftime( "%H:%M:%S.{}".format(str(timestamp).split('.')[-1]), time.localtime(timestamp)) rows.append({ 'subject_id': user_id, 'gesture': gesture, 'repetition': rep, 'reading_count': count, 'readings': reading, 'timestamp': timestamp }) try: db.insert_data_repetition(rows) except Exception as identifier: sys.stderr.write(repr(identifier)) flash('Could not insert into database, please try again.', 'danger') if step == len(test_image_urls) - 1: return redirect(url_for('.done')) else: return redirect(url_for('.test', user_id=user_id, step=step + 1)) form.image.data = test_image_urls[step] form.data.data = None status_text = f'''Test: {int(step % tests_per_rep) + 1} / {tests_per_rep} Rep: {rep} / {reps}''' return render_template('test.html', form=form, status=status_text)
def edit_test(test_id): test = Test.get_by_id(test_id) form = TestForm(obj=test) if request.method == "POST": if form.validate_on_submit(): test.test_name = form.data.get('test_name') test.num_mc = form.data.get('num_mc') test.num_or = form.data.get('num_or') #test.num_students = json.dumps(form.data.get('num_students')) test.num_students = form.data.get('num_students') test.put() flash(u'Test %s successfully saved.' % test_id, 'success') return redirect(url_for('list_tests')) return render_template('edit_test.html', test=test, form=form)
def tests(): ''' Testing options over the web GUI. Works only for hardcoded testsurvey at the moment. ''' import requests from forms import TestForm form = TestForm() flash("test") if form.validate_on_submit(): print("generate summary button pressed") #debug r = requests.get('http://localhost:5000/smmrs/create/testsurvey') return render_template('tests.html', form=form, title='server tests')
def test(test_id): form = TestForm() if form.validate_on_submit(): conn1 = try_connect() cursor1 = conn1.cursor() test_result = int(form.result1.data) + int(form.result2.data) + int(form.result3.data) + int( form.result4.data) + int( form.result5.data) + int(form.result6.data) + int(form.result7.data) + int(form.result8.data) print(test_result) if test_result <= 10: test_result = 10 elif 10 < test_result <= 20: test_result = 20 elif 20 < test_result <= 30: test_result = 30 elif 30 < test_result <= 40: test_result = 40 elif 40 < test_result <= 50: test_result = 50 elif 50 < test_result <= 60: test_result = 60 else: test_result = 60 now = datetime.datetime.now() cursor1.execute('UPDATE uuser SET nutrition_id = %s, nutrition_start = %s WHERE uuser_id = %s', (test_result, now, current_user.id)) conn1.commit() cursor1.execute('INSERT INTO test_result VALUES(DEFAULT, %s, %s, %s, %s)', (current_user.id, test_id, test_result, now)) conn1.commit() cursor1.close() conn1.close() return redirect(url_for('nutrition_program', nutrition_id=test_result)) return render_template('Test.html', title='Your Test', form=form)
def index(): trainForm = TrainForm() testForm = TestForm() if trainForm.submitTrain.data and trainForm.validate_on_submit(): if request.method == "POST": if os.path.exists('temp'): directoryUtils.rmtree("temp") os.mkdir('temp') for f in trainForm.images.data: # remove underscores to avoid ambiguity # as secure_filename() replaces os.path.sep with underscore safe_name = f.filename.replace('_', '') fil = secure_filename(safe_name) if allowed_file(fil, ['jpg', 'jpeg', 'png']): f.save(os.path.join('temp', fil)) split = float(trainForm.split.data) epochs = int(trainForm.epochs.data) if os.path.isfile(LOG_FILE_TRAIN): os.remove(LOG_FILE_TRAIN) w = open(LOG_FILE_TRAIN, 'w+') cmd = [ 'python', '-u', 'modelTrain.py', str(split), str(epochs), str(trainForm.width.data), str(trainForm.height.data) ] subprocess.Popen(cmd, stdout=w, stderr=subprocess.STDOUT) w.close() return redirect(url_for('trainResults')) if testForm.submitTest.data and testForm.validate_on_submit(): if request.method == "POST": if os.path.exists('temp'): directoryUtils.rmtree("temp") os.mkdir('temp') os.mkdir(os.path.join("temp", "model")) os.mkdir(os.path.join("temp", "label")) os.mkdir(os.path.join("temp", "images")) model = testForm.model.data label = testForm.labels.data if allowed_file(secure_filename(model.filename), ['h5']): model.save( os.path.join("temp", "model", secure_filename(model.filename))) else: return 'Invalid model.' if allowed_file(secure_filename(label.filename), ['dat']): label.save( os.path.join("temp", "label", secure_filename(label.filename))) else: return 'Invalid labels.' # process based on source print('Beginning handover to prediction script.') images_dir_path = None if testForm.source.data == 'images': for f in testForm.images.data: if allowed_file(secure_filename(f.filename), ['jpeg', 'jpg', 'png']): f.save( os.path.join('temp', 'images', secure_filename(f.filename))) images_dir_path = 'temp' elif testForm.source.data == 'path': images_dir_path = testForm.path.data if os.path.isfile(LOG_FILE_TEST): os.remove(LOG_FILE_TEST) w = open(LOG_FILE_TEST, 'w+') cmd = ['python', '-u', 'modelPredict.py', images_dir_path] subprocess.Popen(cmd, stdout=w, stderr=subprocess.STDOUT) w.close() return redirect(url_for('testResults')) return render_template("HTML_Interface.html", trainForm=trainForm, testForm=testForm)
def test(): t1 = u'Еще не запускали!' form = TestForm() if form.validate_on_submit(): t1 = form.test1.data return render_template('test.html', form=form, t1=t1)
def index(): trainForm = TrainForm() testForm = TestForm() if trainForm.submit.data and trainForm.validate_on_submit(): if request.method == "POST": if os.path.exists('temp'): directoryUtils.rmtree("temp") os.mkdir('temp') for f in trainForm.images.data: if allowed_file(secure_filename(f.filename), ['jpg', 'jpeg', 'png']): fil = secure_filename(f.filename) f.save(os.path.join('temp', fil)) split = float(trainForm.split.data) epochs = int(trainForm.epochs.data) print("Beginning handover to training script.") modelTrain.trainModel(split, epochs) modelList = [] query = re.compile(r'^(\w+)_(\d.\d{3})_(\d.\d{3}).h5$') for file in os.listdir("output"): matches = query.findall(file) model = {} if len(matches) > 0: model['specialization'] = "Maximum Accuracy" if matches[0][ 0] == "max_acc" else "Minimum Loss" model['val_loss'] = '{:.3f}'.format(float(matches[0][1])) model['val_acc'] = '{:.1f}%'.format( float(matches[0][2]) * 100) model['filename'] = file modelList.append(model) directoryUtils.rmtree("temp") return render_template("trainResults.html", models=modelList) if testForm.submit.data and testForm.validate_on_submit(): if request.method == "POST": if os.path.exists('temp'): directoryUtils.rmtree("temp") os.mkdir('temp') os.mkdir(os.path.join("temp", "model")) os.mkdir(os.path.join("temp", "label")) os.mkdir(os.path.join("temp", "images")) model = testForm.model.data label = testForm.labels.data if allowed_file(secure_filename(model.filename), ['h5']): model.save( os.path.join("temp", "model", secure_filename(model.filename))) else: return 'Invalid model.' if allowed_file(secure_filename(label.filename), ['dat']): label.save( os.path.join("temp", "label", secure_filename(label.filename))) else: return 'Invalid labels.' for f in testForm.images.data: if allowed_file(secure_filename(f.filename), ['jpeg', 'jpg', 'png']): f.save( os.path.join('temp', 'images', secure_filename(f.filename))) print("Beginning handover to prediction script.") modelPredict.predict() directoryUtils.rmtree("temp") return render_template("testResults.html") return render_template("HTML_Interface.html", trainForm=trainForm, testForm=testForm)