Compare commits

..
2 Commits
Author SHA1 Message Date
robin 43185dee64 feat: save guesses and show in admin page 2026-11-01 21:46:03 +01:00
robin 023152d417 update .gitignore 2026-11-01 21:45:56 +01:00
11 changed files with 418 additions and 47 deletions

No files matched your search

+4
View File
@@ -174,3 +174,7 @@ cython_debug/
# PyPI configuration file # PyPI configuration file
.pypirc .pypirc
# Database
results.db
results.db-wal
results.db-shm
+2 -2
View File
@@ -17,11 +17,11 @@
"guesses": [ "guesses": [
{ {
"song_id": "001", "song_id": "001",
"right": true "right": false
}, },
{ {
"song_id": "002", "song_id": "002",
"right": true "right": false
} }
] ]
} }
View File
File renamed without changes.
+60
View File
@@ -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
+6 -1
View File
@@ -1,8 +1,13 @@
from flask import Flask from flask import Flask
from routes import bp from routes import bp
import os
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__) app = Flask(__name__)
app.secret_key = "secret-key-ultra-pro-max-123" app.secret_key = os.environ["SECRET_KEY"]
app.register_blueprint(bp) app.register_blueprint(bp)
if __name__ == "__main__": if __name__ == "__main__":
+159 -41
View File
@@ -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 import json
from pathlib import Path from pathlib import Path
import random 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__) bp = Blueprint("main", __name__)
init_db()
bp.teardown_app_request(close_db)
BASE_DIR = Path(__file__).parent BASE_DIR = Path(__file__).parent
BASE_MUSIC_DIR = BASE_DIR / "static" / "data" / "music" BASE_MUSIC_DIR = BASE_DIR / "static" / "data" / "music"
BASE_MUSIC_FILENAME_DIR = "data/music/" BASE_MUSIC_FILENAME_DIR = "data/music/"
def load_songs_list(): 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) 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") @bp.route("/login")
def login(): def login():
if "name" in session: if "name" in session:
@@ -31,12 +33,19 @@ def login():
@bp.route("/", methods=["GET", "POST"]) @bp.route("/", methods=["GET", "POST"])
def index(): def index():
if request.method == "POST": if request.method == "POST":
session["name"] = request.form["name"].strip() name = request.form.get("name", "").strip()[:60]
if "name" not in session: 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 redirect(url_for("main.login"))
return render_template("index.html") return render_template("index.html")
@bp.route("/test") @bp.route("/test")
def test(): def test():
if "name" not in session: if "name" not in session:
@@ -79,41 +88,150 @@ def api_getRandomSong():
@bp.route("/api/rate", methods=["POST"]) @bp.route("/api/rate", methods=["POST"])
def api_rate(): 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 return jsonify({"error": "no session detected"}), 401
data = request.get_json(silent=True) or {} data = request.get_json(silent=True) or {}
choice = data.get("choice") choice = data.get("choice")
if choice == "gleich": # beide Schreibweisen akzeptieren
choice = "non"
if choice not in ("a", "b", "non"): if choice not in ("a", "b", "non"):
return jsonify({"error": "invalid choice"}), 400 return jsonify({"error": "invalid choice"}), 400
song_id = session["current"]["id"] cur = session["current"]
solution = session["current"]["truth"] db = get_db()
name = session["name"] with db: # eine Transaktion, wird automatisch committet
db.execute(
results = load_results_list() """INSERT OR IGNORE INTO ratings
(participant_id, song_id, choice, truth, original_chosen, edit, created)
person = next((p for p in results if p["name"] == name), None) VALUES (?, ?, ?, ?, ?, ?, ?)""",
(session["pid"], cur["id"], choice, cur["truth"],
if person is None: # create person if not created yet int(choice == cur["truth"]), cur.get("edit"), now()))
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)
done = session.get("done", []) done = session.get("done", [])
done.append(song_id) if cur["id"] not in done:
done.append(cur["id"])
session["done"] = done session["done"] = done
session.pop("current", None) session.pop("current", None)
return jsonify({"saved": True}) 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"))
+78
View File
@@ -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; }
+12
View File
@@ -43,6 +43,7 @@ header {
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
gap: 1rem; gap: 1rem;
flex-wrap: wrap;
} }
.brand { .brand {
@@ -128,4 +129,15 @@ audio { width: 100%; }
.login-card button { .login-card button {
margin-top: 1rem; 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);
} }
+72
View File
@@ -0,0 +1,72 @@
{% extends "base.html" %}
{% block title %}Auswertung – HörVergleich{% endblock %}
{% block content %}
<link rel="stylesheet" href="{{ url_for('static', filename='style/admin.css') }}">
<div class="admin-head">
<h2>Auswertung</h2>
<div class="admin-actions">
<a class="button" href="{{ url_for('main.admin_export') }}">CSV exportieren</a>
<form method="post" action="{{ url_for('main.admin_logout') }}">
<button type="submit" class="secondary">Abmelden</button>
</form>
</div>
</div>
<div class="stats">
<div class="stat"><span class="stat-value">{{ stats.people }}</span><span class="stat-label">Teilnehmer</span></div>
<div class="stat"><span class="stat-value">{{ stats.guesses }}</span><span class="stat-label">Bewertungen</span></div>
<div class="stat">
<span class="stat-value">{{ stats.quote ~ ' %' if stats.quote is not none else '–' }}</span>
<span class="stat-label">Original gewählt</span>
</div>
</div>
{% if not rows %}
<p class="empty">Noch keine Ergebnisse vorhanden.</p>
{% else %}
<div class="table-wrap">
<table>
<thead>
<tr>
<th>Name</th><th>Gestartet</th>
<th class="num">Bewertungen</th><th class="num">Original gewählt</th><th class="num">Quote</th>
</tr>
</thead>
<tbody>
{% for r in rows %}
<tr>
<td>{{ r.name }}</td>
<td class="muted">{{ r.started }}</td>
<td class="num">{{ r.total }}</td>
<td class="num">{{ r.right }}</td>
<td class="num">{{ r.quote }} %</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<h3>Einzelergebnisse</h3>
{% for r in rows %}
<details class="person">
<summary>{{ r.name }} <span class="muted">({{ r.right }}/{{ r.total }}, {{ r.started }})</span></summary>
<div class="table-wrap">
<table>
<thead><tr><th>Song</th><th>Original gewählt</th><th>Wahl</th><th>Bearbeitung</th></tr></thead>
<tbody>
{% for g in r.guesses %}
<tr>
<td>{{ songs.get(g.song_id, g.song_id) }}</td>
<td>{{ 'ja' if g.right else 'nein' }}</td>
<td>{{ g.choice }}</td>
<td>{{ g.edit }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</details>
{% endfor %}
{% endif %}
{% endblock %}
+15
View File
@@ -0,0 +1,15 @@
{% extends "base.html" %}
{% block content %}
<div class="login-wrap">
<div class="login-card">
<h1>Auswertung</h1>
<p class="login-hint">Dieser Bereich ist passwortgeschützt.</p>
{% if error %}<p class="form-error" role="alert">{{ error }}</p>{% endif %}
<form method="post">
<label for="password">Passwort</label>
<input id="password" name="password" type="password" autocomplete="current-password" required autofocus>
<button type="submit">Anmelden</button>
</form>
</div>
</div>
{% endblock %}
+10 -3
View File
@@ -11,9 +11,16 @@
<header> <header>
<div class="header-inner"> <div class="header-inner">
<a class="brand" href="{{ url_for('main.index') }}">AudioRating</a> <a class="brand" href="{{ url_for('main.index') }}">AudioRating</a>
{% if session.get('name') %} <div class="header-right">
<span class="user">Angemeldet als {{ session['name'] }}</span> {% if session.get('name') %}
{% endif %} <span class="user">Angemeldet als {{ session['name'] }}</span>
{% endif %}
{% if config.DEBUG %}
<form method="post" action="{{ url_for('main.debug_reset') }}">
<button type="submit" class="debug-reset" title="Nur im Debug-Modus sichtbar">Reset</button>
</form>
{% endif %}
</div>
</div> </div>
</header> </header>