From 43185dee640eb22d3a09e644d78154b348929033 Mon Sep 17 00:00:00 2001 From: Robin Schanbacher Date: Sun, 1 Nov 2026 21:46:03 +0100 Subject: [PATCH] feat: save guesses and show in admin page --- results.json => data/results.json | 4 +- songs.json => data/songs.json | 0 db.py | 60 +++++++++ main.py | 7 +- routes.py | 200 ++++++++++++++++++++++++------ static/style/admin.css | 78 ++++++++++++ static/style/style.css | 12 ++ templates/admin.html | 72 +++++++++++ templates/admin_login.html | 15 +++ templates/base.html | 13 +- 10 files changed, 414 insertions(+), 47 deletions(-) rename results.json => data/results.json (87%) rename songs.json => data/songs.json (100%) create mode 100644 db.py create mode 100644 static/style/admin.css create mode 100644 templates/admin.html create mode 100644 templates/admin_login.html diff --git a/results.json b/data/results.json similarity index 87% rename from results.json rename to data/results.json index 172c01b..3978ebd 100644 --- a/results.json +++ b/data/results.json @@ -17,11 +17,11 @@ "guesses": [ { "song_id": "001", - "right": true + "right": false }, { "song_id": "002", - "right": true + "right": false } ] } diff --git a/songs.json b/data/songs.json similarity index 100% rename from songs.json rename to data/songs.json diff --git a/db.py b/db.py new file mode 100644 index 0000000..9da1f12 --- /dev/null +++ b/db.py @@ -0,0 +1,60 @@ +import sqlite3 +import uuid +from contextlib import closing +from datetime import datetime +from pathlib import Path + +from flask import g + +DB_PATH = Path(__file__).parent / "results.db" + + +def init_db(): + with closing(sqlite3.connect(DB_PATH)) as con: + con.execute("PRAGMA journal_mode=WAL") # bessere Parallelität beim Schreiben + con.executescript(""" + CREATE TABLE IF NOT EXISTS participants ( + id TEXT PRIMARY KEY, -- zufällige ID pro Teilnahme + name TEXT NOT NULL, + created TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS ratings ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + participant_id TEXT NOT NULL, + song_id NOT NULL, -- bewusst ohne Typ: bleibt Zahl oder Text wie in songs.json + choice TEXT NOT NULL, -- 'a', 'b' oder 'non' + truth TEXT NOT NULL, -- Position des Originals ('a' oder 'b') + original_chosen INTEGER NOT NULL, -- 1 = Original als besser gewählt + edit TEXT, -- welche Bearbeitung gespielt wurde + created TEXT NOT NULL, + UNIQUE (participant_id, song_id) -- Doppelklick erzeugt keine zweite Zeile + ); + """) + con.commit() + + +def get_db(): + if "db" not in g: + g.db = sqlite3.connect(DB_PATH, timeout=10) # wartet bei gleichzeitigem Schreiben + g.db.row_factory = sqlite3.Row + return g.db + + +def close_db(_exc=None): + db = g.pop("db", None) + if db is not None: + db.close() + + +def now(): + return datetime.now().strftime("%Y-%m-%d %H:%M:%S") + + +def create_participant(name): + pid = uuid.uuid4().hex + db = get_db() + with db: + db.execute("INSERT INTO participants (id, name, created) VALUES (?, ?, ?)", + (pid, name, now())) + return pid \ No newline at end of file diff --git a/main.py b/main.py index 374141e..2ff110d 100644 --- a/main.py +++ b/main.py @@ -1,8 +1,13 @@ from flask import Flask from routes import bp +import os +from dotenv import load_dotenv + +load_dotenv() + app = Flask(__name__) -app.secret_key = "secret-key-ultra-pro-max-123" +app.secret_key = os.environ["SECRET_KEY"] app.register_blueprint(bp) if __name__ == "__main__": diff --git a/routes.py b/routes.py index 31d470c..f90ecfb 100644 --- a/routes.py +++ b/routes.py @@ -1,26 +1,28 @@ -from flask import Blueprint, render_template, request, redirect, url_for, session, jsonify +from flask import Blueprint, render_template, request, redirect, url_for, session, jsonify, Response, current_app, abort import json from pathlib import Path import random +import csv +import hmac +import io +import os +import time +from functools import wraps +from db import init_db, get_db, close_db, create_participant, now bp = Blueprint("main", __name__) +init_db() +bp.teardown_app_request(close_db) + BASE_DIR = Path(__file__).parent BASE_MUSIC_DIR = BASE_DIR / "static" / "data" / "music" BASE_MUSIC_FILENAME_DIR = "data/music/" def load_songs_list(): - with open("songs.json", encoding="utf-8") as f: + with open(BASE_DIR / "data" / "songs.json", encoding="utf-8") as f: return json.load(f) -def load_results_list(): - with open("results.json", encoding="utf-8") as f: - return json.load(f) - -def write_results_list(results): - with open("results.json", mode="w", encoding="utf-8") as f: - json.dump(results, f, ensure_ascii=False, indent=2) - @bp.route("/login") def login(): if "name" in session: @@ -31,12 +33,19 @@ def login(): @bp.route("/", methods=["GET", "POST"]) def index(): if request.method == "POST": - session["name"] = request.form["name"].strip() - if "name" not in session: + name = request.form.get("name", "").strip()[:60] + if not name: + return redirect(url_for("main.login")) + session.clear() # neuer Teilnehmer = frischer Stand + session["name"] = name + session["pid"] = create_participant(name) + return redirect(url_for("main.test")) + if "pid" not in session: return redirect(url_for("main.login")) return render_template("index.html") + @bp.route("/test") def test(): if "name" not in session: @@ -79,41 +88,150 @@ def api_getRandomSong(): @bp.route("/api/rate", methods=["POST"]) def api_rate(): - if "name" not in session or "current" not in session: + if "pid" not in session or "current" not in session: return jsonify({"error": "no session detected"}), 401 - + data = request.get_json(silent=True) or {} choice = data.get("choice") + if choice == "gleich": # beide Schreibweisen akzeptieren + choice = "non" if choice not in ("a", "b", "non"): return jsonify({"error": "invalid choice"}), 400 - - song_id = session["current"]["id"] - solution = session["current"]["truth"] - name = session["name"] - - results = load_results_list() - - person = next((p for p in results if p["name"] == name), None) - - if person is None: # create person if not created yet - results.append({ - "name": name, - "guesses": [{ - "song_id": song_id, - "right": choice == solution - }] - }) - else: - person["guesses"].append({ - "song_id": song_id, - "right": choice == solution - }) - - write_results_list(results) - + + cur = session["current"] + db = get_db() + with db: # eine Transaktion, wird automatisch committet + db.execute( + """INSERT OR IGNORE INTO ratings + (participant_id, song_id, choice, truth, original_chosen, edit, created) + VALUES (?, ?, ?, ?, ?, ?, ?)""", + (session["pid"], cur["id"], choice, cur["truth"], + int(choice == cur["truth"]), cur.get("edit"), now())) + done = session.get("done", []) - done.append(song_id) + if cur["id"] not in done: + done.append(cur["id"]) session["done"] = done session.pop("current", None) - + return jsonify({"saved": True}) + + +def admin_required(view): + @wraps(view) + def wrapper(*args, **kwargs): + if not session.get("admin"): + return redirect(url_for("main.admin_login")) + return view(*args, **kwargs) + return wrapper + + +@bp.route("/admin/login", methods=["GET", "POST"]) +def admin_login(): + error = None + if request.method == "POST": + # Erst zur Anfragezeit lesen, damit load_dotenv() aus main.py schon gelaufen ist + expected = os.environ.get("ADMIN_PASSWORD", "") + given = request.form.get("password", "") + + if not expected: + error = "Es ist kein Admin-Passwort konfiguriert (.env)." + elif hmac.compare_digest(given.encode(), expected.encode()): + session["admin"] = True + return redirect(url_for("main.admin")) + else: + time.sleep(1) # bremst automatisches Durchprobieren + error = "Falsches Passwort." + return render_template("admin_login.html", error=error) + + +@bp.route("/admin/logout", methods=["POST"]) +def admin_logout(): + session.pop("admin", None) + return redirect(url_for("main.admin_login")) + + +CHOICE_LABELS = {"a": "A", "b": "B", "non": "Kein Unterschied"} + + +@bp.route("/admin") +@admin_required +def admin(): + db = get_db() + songs = {s["id"]: s["name"] for s in load_songs_list()} + + by_person = {} + for r in db.execute("SELECT * FROM ratings ORDER BY id"): + by_person.setdefault(r["participant_id"], []).append({ + "song_id": r["song_id"], + "right": bool(r["original_chosen"]), + "choice": CHOICE_LABELS.get(r["choice"], r["choice"]), + "edit": r["edit"] or "–", + }) + + rows = [] + for p in db.execute("SELECT id, name, created FROM participants ORDER BY created DESC"): + guesses = by_person.get(p["id"], []) + if not guesses: + continue # nur Teilnehmer mit mindestens einer Bewertung + total = len(guesses) + right = sum(g["right"] for g in guesses) + rows.append({ + "name": p["name"], + "started": p["created"], + "total": total, + "right": right, + "quote": round(100 * right / total), + "guesses": guesses, + }) + + total_all = sum(r["total"] for r in rows) + right_all = sum(r["right"] for r in rows) + stats = { + "people": len(rows), + "guesses": total_all, + "quote": round(100 * right_all / total_all) if total_all else None, + } + return render_template("admin.html", rows=rows, stats=stats, songs=songs) + + +def csv_safe(value): + """Verhindert, dass Calc/Excel einen Namen wie '=1+1' als Formel ausführt.""" + s = str(value) + return "'" + s if s[:1] in ("=", "+", "-", "@") else s + + +@bp.route("/admin/export.csv") +@admin_required +def admin_export(): + songs = {s["id"]: s["name"] for s in load_songs_list()} + out = io.StringIO() + w = csv.writer(out, delimiter=";") + w.writerow(["Name", "Gestartet", "Song-ID", "Song", "Original gewählt", + "Wahl", "Position Original", "Bearbeitung"]) + + query = """SELECT p.name, p.created AS started, r.song_id, r.original_chosen, + r.choice, r.truth, r.edit + FROM ratings r JOIN participants p ON p.id = r.participant_id + ORDER BY p.created, r.id""" + for r in get_db().execute(query): + w.writerow([ + csv_safe(r["name"]), + r["started"], + r["song_id"], + csv_safe(songs.get(r["song_id"], "")), + "ja" if r["original_chosen"] else "nein", + CHOICE_LABELS.get(r["choice"], r["choice"]), + r["truth"].upper(), + r["edit"] or "", + ]) + + return Response("\ufeff" + out.getvalue(), mimetype="text/csv", + headers={"Content-Disposition": "attachment; filename=ergebnisse.csv"}) + +@bp.route("/debug/reset", methods=["POST"]) +def debug_reset(): + if not current_app.debug: + abort(404) # im normalen Betrieb existiert die Route praktisch nicht + session.clear() + return redirect(url_for("main.login")) \ No newline at end of file diff --git a/static/style/admin.css b/static/style/admin.css new file mode 100644 index 0000000..644d595 --- /dev/null +++ b/static/style/admin.css @@ -0,0 +1,78 @@ +/* static/admin.css */ + +.form-error { + margin: 0 0 1rem; + padding: .5rem .75rem; + color: var(--text); + background: var(--surface); + border: 1px solid #d14343; + border-radius: 8px; + font-size: .95rem; +} + +.admin-head { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: .75rem; + margin-bottom: 1rem; +} +.admin-head h2 { margin: 0; } + +.admin-actions { display: flex; flex-wrap: wrap; gap: .5rem; align-items: center; } +.admin-actions form { margin: 0; } + +.button { + display: inline-flex; + align-items: center; + min-height: 2.75rem; + padding: 0 1rem; + color: var(--accent-text); + background: var(--accent); + border-radius: 6px; + text-decoration: none; +} + +button.secondary { + min-height: 2.75rem; + color: var(--text); + background: transparent; + border-color: var(--border); +} + +.stats { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(9rem, 1fr)); + gap: .75rem; + margin-bottom: 1.5rem; +} + +.stat { + display: flex; + flex-direction: column; + padding: .75rem 1rem; + background: var(--surface); + border: 1px solid var(--border); + border-radius: 10px; +} +.stat-value { font-size: 1.6rem; font-weight: 700; font-variant-numeric: tabular-nums; } +.stat-label { color: var(--muted); font-size: .9rem; } + +.table-wrap { overflow-x: auto; margin-bottom: 1rem; } + +table { width: 100%; border-collapse: collapse; } +th, td { padding: .5rem .75rem; text-align: left; border-bottom: 1px solid var(--border); } +th { color: var(--muted); font-size: .85rem; font-weight: 600; white-space: nowrap; } +td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; } + +.person { + margin-bottom: .5rem; + background: var(--surface); + border: 1px solid var(--border); + border-radius: 10px; +} +.person summary { padding: .75rem 1rem; cursor: pointer; font-weight: 600; } +.person .table-wrap { margin: 0; padding: 0 .5rem .5rem; } + +.muted, .empty { color: var(--muted); font-weight: 400; } \ No newline at end of file diff --git a/static/style/style.css b/static/style/style.css index 9c4f097..a0378dc 100644 --- a/static/style/style.css +++ b/static/style/style.css @@ -43,6 +43,7 @@ header { align-items: center; justify-content: space-between; gap: 1rem; + flex-wrap: wrap; } .brand { @@ -128,4 +129,15 @@ audio { width: 100%; } .login-card button { margin-top: 1rem; +} + +.header-right { display: flex; align-items: center; gap: .75rem; } +.header-right form { margin: 0; } + +.debug-reset { + padding: .25rem .6rem; + font-size: .8rem; + color: var(--text); + background: transparent; + border: 1px dashed var(--muted); } \ No newline at end of file diff --git a/templates/admin.html b/templates/admin.html new file mode 100644 index 0000000..d338d72 --- /dev/null +++ b/templates/admin.html @@ -0,0 +1,72 @@ +{% extends "base.html" %} +{% block title %}Auswertung – HörVergleich{% endblock %} +{% block content %} + + +
+

Auswertung

+
+ CSV exportieren +
+ +
+
+
+ +
+
{{ stats.people }}Teilnehmer
+
{{ stats.guesses }}Bewertungen
+
+ {{ stats.quote ~ ' %' if stats.quote is not none else '–' }} + Original gewählt +
+
+ +{% if not rows %} +

Noch keine Ergebnisse vorhanden.

+{% else %} +
+ + + + + + + + + {% for r in rows %} + + + + + + + + {% endfor %} + +
NameGestartetBewertungenOriginal gewähltQuote
{{ r.name }}{{ r.started }}{{ r.total }}{{ r.right }}{{ r.quote }} %
+
+ +

Einzelergebnisse

+ {% for r in rows %} +
+ {{ r.name }} ({{ r.right }}/{{ r.total }}, {{ r.started }}) +
+ + + + {% for g in r.guesses %} + + + + + + + {% endfor %} + +
SongOriginal gewähltWahlBearbeitung
{{ songs.get(g.song_id, g.song_id) }}{{ 'ja' if g.right else 'nein' }}{{ g.choice }}{{ g.edit }}
+
+
+ {% endfor %} +{% endif %} +{% endblock %} \ No newline at end of file diff --git a/templates/admin_login.html b/templates/admin_login.html new file mode 100644 index 0000000..4e9bc17 --- /dev/null +++ b/templates/admin_login.html @@ -0,0 +1,15 @@ +{% extends "base.html" %} +{% block content %} +
+ +
+{% endblock %} \ No newline at end of file diff --git a/templates/base.html b/templates/base.html index d23e9de..6aa1f11 100644 --- a/templates/base.html +++ b/templates/base.html @@ -11,9 +11,16 @@
AudioRating - {% if session.get('name') %} - Angemeldet als {{ session['name'] }} - {% endif %} +
+ {% if session.get('name') %} + Angemeldet als {{ session['name'] }} + {% endif %} + {% if config.DEBUG %} +
+ +
+ {% endif %} +