/
dayekb
/
vibecoding_abtest
Обзор
Документация
Войти
/
dayekb
/
vibecoding_abtest
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
app.py
191 строка
6 KB
dayekb
upload files
24 авг 2025, 16:15
24 авг 2025, 16:15
c6cce30
Код
Авторство
О чём код?
from flask import Flask, render_template, request, redirect, url_for, session, flash import pandas as pd import os from werkzeug.utils import secure_filename import json from datetime import datetime from flask import send_from_directory app = Flask(__name__) app.secret_key = 'your-secret-key-here' # Конфигурация для загрузки файлов UPLOAD_FOLDER = 'uploads' ALLOWED_EXTENSIONS = {'xlsx', 'xls'} if not os.path.exists(UPLOAD_FOLDER): os.makedirs(UPLOAD_FOLDER) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS def load_test_data(filename): """Загружает данные из Excel файла""" try: file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) df = pd.read_excel(file_path) # Проверяем, что есть как минимум 2 столбца if len(df.columns) < 2: return None, "Файл должен содержать как минимум 2 столбца" # Берем первые два столбца column_a = df.columns[0] column_b = df.columns[1] # Создаем список тестов tests = [] for index, row in df.iterrows(): test = { 'id': index, 'option_a': str(row[column_a]), 'option_b': str(row[column_b]), 'result': None } tests.append(test) return tests, None except Exception as e: return None, f"Ошибка при загрузке файла: {str(e)}" @app.route('/') def index(): return render_template('index.html') @app.route('/upload', methods=['POST']) def upload_file(): if 'file' not in request.files: flash('Файл не выбран') return redirect(request.url) file = request.files['file'] if file.filename == '': flash('Файл не выбран') return redirect(request.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) file.save(file_path) # Загружаем данные из файла tests, error = load_test_data(filename) if error: flash(error) return redirect(url_for('index')) # Сохраняем тесты в сессии session['tests'] = tests session['current_test_index'] = 0 session['filename'] = filename return redirect(url_for('test')) else: flash('Разрешены только файлы Excel (.xlsx, .xls)') return redirect(url_for('index')) @app.route('/test') def test(): if 'tests' not in session: return redirect(url_for('index')) tests = session['tests'] current_index = session.get('current_test_index', 0) if current_index >= len(tests): return redirect(url_for('results')) current_test = tests[current_index] return render_template('test.html', test=current_test, current_index=current_index + 1, total_tests=len(tests)) @app.route('/submit_answer', methods=['POST']) def submit_answer(): if 'tests' not in session: return redirect(url_for('index')) tests = session['tests'] current_index = session.get('current_test_index', 0) if current_index >= len(tests): return redirect(url_for('results')) # Получаем ответ пользователя answer = request.form.get('answer') if answer not in ['A', 'B', 'both_bad', 'both_good']: flash('Неверный ответ') return redirect(url_for('test')) # Сохраняем результат tests[current_index]['result'] = answer session['tests'] = tests # Переходим к следующему тесту session['current_test_index'] = current_index + 1 if session['current_test_index'] >= len(tests): return redirect(url_for('results')) else: return redirect(url_for('test')) @app.route('/results') def results(): if 'tests' not in session: return redirect(url_for('index')) tests = session['tests'] # Подсчитываем статистику stats = { 'A': 0, 'B': 0, 'both_bad': 0, 'both_good': 0, 'total': len(tests) } for test in tests: if test['result']: stats[test['result']] += 1 return render_template('results.html', tests=tests, stats=stats) @app.route('/download_results') def download_results(): if 'tests' not in session: return redirect(url_for('index')) tests = session['tests'] # Создаем DataFrame для экспорта results_data = [] for test in tests: results_data.append({ 'Вариант A': test['option_a'], 'Вариант B': test['option_b'], 'Результат': test['result'] if test['result'] else 'Не оценено' }) df = pd.DataFrame(results_data) # Сохраняем в Excel output_filename = f"ab_test_results_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx" output_path = os.path.join(app.config['UPLOAD_FOLDER'], output_filename) df.to_excel(output_path, index=False) return redirect(url_for('download_file', filename=output_filename)) @app.route('/downloads/<filename>') def download_file(filename): return send_from_directory(app.config['UPLOAD_FOLDER'], filename, as_attachment=True) @app.route('/reset') def reset(): session.clear() return redirect(url_for('index')) if __name__ == '__main__': app.run(debug=True)