feat: test and save results

This commit is contained in:
robin committed 2026-11-01 14:48:09 +01:00
1 parent 92807e857a
commit 255699a25c
12 files changed
+797 -3

No files matched your search

+1 -1
View File
@@ -6,4 +6,4 @@ app.secret_key = "secret-key-ultra-pro-max-123"
app.register_blueprint(bp) app.register_blueprint(bp)
if __name__ == "__main__": if __name__ == "__main__":
app.run(debug=True) app.run(debug=True, host="0.0.0.0")
+28
View File
@@ -0,0 +1,28 @@
[
{
"name": "r",
"guesses": [
{
"song_id": "001",
"right": true
},
{
"song_id": "002",
"right": false
}
]
},
{
"name": "Robin",
"guesses": [
{
"song_id": "001",
"right": true
},
{
"song_id": "002",
"right": true
}
]
}
]
+95 -2
View File
@@ -1,7 +1,25 @@
from flask import Blueprint, render_template, request, redirect, url_for, session from flask import Blueprint, render_template, request, redirect, url_for, session, jsonify
import json
from pathlib import Path
import random
bp = Blueprint("main", __name__) bp = Blueprint("main", __name__)
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:
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():
@@ -23,4 +41,79 @@ def index():
def test(): def test():
if "name" not in session: if "name" not in session:
return redirect(url_for("main.index")) return redirect(url_for("main.index"))
return render_template("test.html", name=session["name"]) return render_template("test.html", name=session["name"])
@bp.route("/api/getRandomSong")
def api_getRandomSong():
if "name" not in session:
return jsonify({"error": "no session detected"}), 401
done = session.get("done", [])
#print(done)
remaining = [s for s in load_songs_list() if s["id"] not in done]
#print(remaining)
if not remaining:
return jsonify({"finished": True})
song = remaining[0]
truth = random.choice(["a", "b"])
session["current"] = {"id": song["id"], "truth": truth}
truth_path = BASE_MUSIC_FILENAME_DIR + song["original"]["filename"] + ".mp3"
random_lie_path = BASE_MUSIC_FILENAME_DIR + random.choice(song["edits"])["filename"] + ".mp3"
if truth == "a":
path_a = truth_path
path_b = random_lie_path
else:
path_a = random_lie_path
path_b = truth_path
return jsonify({
"finished": False,
"a": url_for("static", filename=path_a),
"b": url_for("static", filename=path_b),
"number": len(done) + 1,
"song_name": song["name"],
})
@bp.route("/api/rate", methods=["POST"])
def api_rate():
if "name" 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 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)
done = session.get("done", [])
done.append(song_id)
session["done"] = done
session.pop("current", None)
return jsonify({"saved": True})
+38
View File
@@ -0,0 +1,38 @@
[
{
"name": "Beweis",
"artist": "Alle",
"id": "001",
"original_name": "-",
"original": {
"filename": "m001",
"sampling_rate": 44.1,
"bitrate": 48
},
"edits": [
{
"filename": "m002",
"sampling_rate": 44.1,
"bitrate": 47
}
]
},
{
"name": "Umsonst gelebt",
"artist": "Jugend Chor",
"id": "002",
"original_name": "-",
"original": {
"filename": "m003",
"sampling_rate": 44.1,
"bitrate": 256
},
"edits": [
{
"filename": "m004",
"sampling_rate": 22.1,
"bitrate": 63
}
]
}
]
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+319
View File
@@ -0,0 +1,319 @@
"use strict";
const BINS = 2000; // Auflösung der vorberechneten Pegelwerte pro Datei
const BAR_W = 3; // Balkenbreite in CSS-Pixeln
const BAR_GAP = 2; // Abstand zwischen Balken
const SEEK_STEP = 5; // Sekunden für Pfeiltasten
/** Maximaler Betrag (Spitzenpegel) pro Abschnitt, über alle Kanäle. */
function computePeaks(buffer) {
const bins = new Float32Array(BINS);
const n = buffer.length;
const step = n / BINS;
for (let ch = 0; ch < buffer.numberOfChannels; ch++) {
const data = buffer.getChannelData(ch);
for (let i = 0; i < BINS; i++) {
const s = Math.floor(i * step);
const e = Math.min(n, Math.floor((i + 1) * step));
let max = 0;
for (let j = s; j < e; j++) {
const v = Math.abs(data[j]);
if (v > max) max = v;
}
if (max > bins[i]) bins[i] = max;
}
}
return bins;
}
function fmt(t) {
t = Math.max(0, Math.floor(t));
return Math.floor(t / 60) + ":" + String(t % 60).padStart(2, "0");
}
function drawBar(g, x, y, w, h) {
g.beginPath();
if (g.roundRect) g.roundRect(x, y, w, h, w / 2);
else g.rect(x, y, w, h);
g.fill();
}
class ABPlayer {
constructor(root) {
this.root = root;
this.tracks = [...root.querySelectorAll(".track")];
this.canvases = this.tracks.map(t => t.querySelector("canvas"));
this.labels = this.tracks.map(t => t.querySelector(".track-label"));
this.playBtn = root.querySelector(".play");
this.timeEl = root.querySelector(".time");
this.statusEl = root.querySelector(".status");
this.toggleBtn = root.querySelector(".toggle");
this.ctx = null;
this.buffers = [null, null];
this.peaks = [null, null];
this.bars = [[], []];
this.norm = 1;
this.sources = [];
this.gains = [];
this.active = 0;
this.playing = false;
this.ready = false;
this.offset = 0;
this.startedAt = 0;
this.duration = 0;
this.raf = 0;
this.tick = this.tick.bind(this);
this.playBtn.addEventListener("click", () => this.toggle());
this.labels.forEach((btn, i) => btn.addEventListener("click", () => this.switchTo(i)));
this.canvases.forEach((cv, i) => cv.addEventListener("pointerdown", e => this.onCanvasPointer(e, i)));
document.addEventListener("keydown", e => this.onKey(e));
new ResizeObserver(() => { this.layout(); this.draw(); }).observe(root);
matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => this.draw());
this.toggleBtn.addEventListener("click", () => this.toggleAB());
this.refreshUI();
}
// --- Laden ---------------------------------------------------------------
async load(urlA, urlB) {
this.reset();
this.root.classList.add("is-loading");
this.setStatus("Audio wird geladen …");
const ctx = this.ctx || (this.ctx = new (window.AudioContext || window.webkitAudioContext)());
try {
this.buffers = await Promise.all([urlA, urlB].map(async url => {
const res = await fetch(url);
if (!res.ok) throw new Error("HTTP " + res.status);
return ctx.decodeAudioData(await res.arrayBuffer());
}));
} catch (err) {
this.root.classList.remove("is-loading");
this.setStatus("Audio konnte nicht geladen werden.");
throw err;
}
this.peaks = this.buffers.map(computePeaks);
// Gemeinsame Normierung, damit Pegelunterschiede zwischen A und B sichtbar bleiben
const globalMax = Math.max(...this.peaks.map(p => p.reduce((m, v) => Math.max(m, v), 0)));
this.norm = globalMax > 0 ? 1 / globalMax : 1;
this.duration = Math.max(...this.buffers.map(b => b.duration));
this.ready = true;
this.root.classList.remove("is-loading");
this.setStatus("");
this.layout();
this.refreshUI();
}
reset() {
cancelAnimationFrame(this.raf);
this.stopSources();
this.playing = false;
this.ready = false;
this.offset = 0;
this.active = 0;
this.buffers = [null, null];
this.bars = [[], []];
this.refreshUI();
}
// --- Wiedergabe ------------------------------------------------------------
position() {
if (!this.playing) return this.offset;
const elapsed = Math.max(0, this.ctx.currentTime - this.startedAt);
return Math.min(this.duration, this.offset + elapsed);
}
startSources() {
const ctx = this.ctx;
this.stopSources();
this.sources = this.buffers.map((buf, i) => {
const src = ctx.createBufferSource();
src.buffer = buf;
const gain = ctx.createGain();
gain.gain.value = i === this.active ? 1 : 0;
src.connect(gain).connect(ctx.destination);
this.gains[i] = gain;
return src;
});
// Beide Quellen starten gleichzeitig und laufen stumm bzw. hörbar parallel.
// Umschalten ändert nur die Lautstärke, daher ohne Lücke und exakt synchron.
const when = ctx.currentTime + 0.02;
this.sources.forEach(s => s.start(when, this.offset));
this.startedAt = when;
}
stopSources() {
this.sources.forEach(s => { try { s.stop(); s.disconnect(); } catch (_) {} });
this.sources = [];
}
async play() {
if (!this.ready) return;
await this.ctx.resume();
if (this.offset >= this.duration) this.offset = 0;
this.startSources();
this.playing = true;
this.refreshUI();
this.raf = requestAnimationFrame(this.tick);
}
pause() {
if (!this.playing) return;
this.offset = this.position();
this.stopSources();
this.playing = false;
cancelAnimationFrame(this.raf);
this.refreshUI();
}
toggle() { this.playing ? this.pause() : this.play(); }
seek(t) {
if (!this.ready) return;
this.offset = Math.min(Math.max(0, t), this.duration);
if (this.playing) this.startSources();
this.refreshUI();
}
switchTo(i) {
if (!this.ready || i === this.active) return;
this.active = i;
if (this.playing) {
const now = this.ctx.currentTime;
this.gains.forEach((g, k) => {
g.gain.cancelScheduledValues(now);
g.gain.setTargetAtTime(k === i ? 1 : 0, now, 0.005); // kurze Rampe gegen Knacken
});
}
this.refreshUI();
}
toggleAB() { this.switchTo(1 - this.active); }
tick() {
if (!this.playing) return;
if (this.position() >= this.duration) {
this.pause();
this.offset = 0;
this.refreshUI();
return;
}
this.refreshUI();
this.raf = requestAnimationFrame(this.tick);
}
// --- Eingaben --------------------------------------------------------------
onCanvasPointer(e, i) {
if (!this.ready) return;
if (i !== this.active) {
this.switchTo(i); // Klick auf die andere Spur: wechseln, gleiche Stelle
} else {
const rect = this.canvases[i].getBoundingClientRect();
this.seek((e.clientX - rect.left) / rect.width * this.duration);
}
}
onKey(e) {
if (!this.ready) return;
const t = e.target;
const isRadio = t.matches('input[type="radio"]');
if (t.closest("textarea, select, input:not([type=radio])")) return;
if (isRadio && (e.key === " " || e.key.startsWith("Arrow"))) return;
if ((e.key === " " || e.key === "Enter") && t.closest("button")) return;
if (e.key === " ") { e.preventDefault(); this.toggle(); }
else if (e.key === "a" || e.key === "A") this.switchTo(0);
else if (e.key === "b" || e.key === "B") this.switchTo(1);
else if (e.key === "ArrowLeft") { e.preventDefault(); this.seek(this.position() - SEEK_STEP); }
else if (e.key === "ArrowRight") { e.preventDefault(); this.seek(this.position() + SEEK_STEP); }
else if (e.key === "t" || e.key === "T") this.toggleAB();
}
// --- Darstellung -----------------------------------------------------------
setStatus(msg) { this.statusEl.textContent = msg; }
/** Balkenhöhen für die aktuelle Breite berechnen. */
layout() {
if (!this.ready) return;
this.canvases.forEach((cv, i) => {
const w = cv.clientWidth;
const n = Math.max(1, Math.floor((w + BAR_GAP) / (BAR_W + BAR_GAP)));
const buf = this.buffers[i];
const peaks = this.peaks[i];
const bars = new Array(n);
for (let k = 0; k < n; k++) {
const b0 = Math.floor((k / n) * this.duration / buf.duration * BINS);
const b1 = Math.floor(((k + 1) / n) * this.duration / buf.duration * BINS);
let max = 0;
for (let b = b0; b < Math.min(BINS, Math.max(b1, b0 + 1)); b++) {
if (peaks[b] > max) max = peaks[b];
}
bars[k] = max * this.norm;
}
this.bars[i] = bars;
});
}
refreshUI() {
this.root.classList.toggle("is-playing", this.playing);
this.playBtn.disabled = !this.ready;
this.playBtn.setAttribute("aria-label", this.playing ? "Pause" : "Abspielen");
this.toggleBtn.disabled = !this.ready;
this.tracks.forEach((el, i) => {
el.classList.toggle("is-active", i === this.active);
this.labels[i].setAttribute("aria-pressed", String(i === this.active));
});
this.timeEl.textContent = fmt(this.position()) + " / " + fmt(this.duration);
this.draw();
}
draw() {
const dpr = window.devicePixelRatio || 1;
const cs = getComputedStyle(this.root);
const accent = cs.getPropertyValue("--accent").trim() || "#2563eb";
const muted = cs.getPropertyValue("--muted").trim() || "#888";
const text = cs.getPropertyValue("--text").trim() || "#000";
const progress = this.duration ? this.position() / this.duration : 0;
this.canvases.forEach((cv, i) => {
const w = cv.clientWidth, h = cv.clientHeight;
if (cv.width !== Math.round(w * dpr) || cv.height !== Math.round(h * dpr)) {
cv.width = Math.round(w * dpr);
cv.height = Math.round(h * dpr);
}
const g = cv.getContext("2d");
g.setTransform(dpr, 0, 0, dpr, 0, 0);
g.clearRect(0, 0, w, h);
const bars = this.bars[i];
const isActive = i === this.active;
const n = bars.length;
if (!n) return;
const total = n * BAR_W + (n - 1) * BAR_GAP;
const x0 = (w - total) / 2;
for (let k = 0; k < n; k++) {
const played = (k + 0.5) / n <= progress;
g.fillStyle = played ? accent : muted;
g.globalAlpha = played ? (isActive ? 1 : 0.4) : (isActive ? 0.55 : 0.25);
const bh = Math.max(2, bars[k] * h * 0.92);
drawBar(g, x0 + k * (BAR_W + BAR_GAP), (h - bh) / 2, BAR_W, bh);
}
// Abspielposition
g.globalAlpha = isActive ? 0.9 : 0.3;
g.fillStyle = text;
g.fillRect(Math.min(w - 1, x0 + progress * total), 0, 1.5, h);
g.globalAlpha = 1;
});
}
}
+119
View File
@@ -0,0 +1,119 @@
/* A/B-Player. Nutzt die Variablen aus base.html (--surface, --border, --accent, ...) */
.ab-player {
display: flex;
flex-direction: column;
gap: .75rem;
}
.ab-player .status {
margin: 0;
color: var(--muted);
font-size: .95rem;
}
.ab-player .status:empty { display: none; }
.ab-player.is-loading .track { opacity: .5; }
/* --- Spuren -------------------------------------------------------------- */
.ab-player .track {
display: flex;
gap: .75rem;
padding: .5rem;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 10px;
transition: border-color .15s;
}
.ab-player .track.is-active { border-color: var(--accent); }
.ab-player .track canvas {
flex: 1;
min-width: 0;
width: 100%;
height: 72px;
display: block;
cursor: pointer;
touch-action: manipulation;
}
.ab-player .track-label {
flex: none;
width: 2.75rem;
padding: 0;
font-weight: 700;
color: var(--text);
background: transparent;
border: 1px solid var(--border);
border-radius: 8px;
}
.ab-player .track.is-active .track-label {
color: var(--accent-text);
background: var(--accent);
border-color: var(--accent);
}
/* --- Steuerung ----------------------------------------------------------- */
.ab-player .transport {
display: flex;
align-items: center;
gap: 1rem;
flex-wrap: wrap;
}
.ab-player .play {
display: grid;
place-items: center;
width: 3.25rem;
height: 3.25rem;
padding: 0;
border-radius: 50%;
}
.ab-player .play:disabled { opacity: .4; cursor: default; }
.ab-player .play svg { width: 1.4rem; height: 1.4rem; fill: currentColor; }
.ab-player:not(.is-playing) .icon-pause { display: none; }
.ab-player.is-playing .icon-play { display: none; }
.ab-player .time {
color: var(--muted);
font-variant-numeric: tabular-nums;
}
.ab-player .hint {
margin: 0 0 0 auto;
color: var(--muted);
font-size: .85rem;
}
.ab-player button:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
.ab-player .toggle {
min-height: 2.75rem;
padding: 0 1rem;
color: var(--text);
background: transparent;
border: 1px solid var(--border);
}
.ab-player .toggle:disabled { opacity: .4; cursor: default; }
/* --- Handy --------------------------------------------------------------- */
@media (max-width: 480px) {
.ab-player .track { gap: .5rem; }
.ab-player .track canvas { height: 56px; }
.ab-player .track-label { width: 2.5rem; }
}
/* Tastaturhinweis nur dort, wo es eine Tastatur gibt */
@media (hover: none) {
.ab-player .hint { display: none; }
}
+83
View File
@@ -0,0 +1,83 @@
.rating {
margin-top: 1.5rem;
padding-top: 1.25rem;
border-top: 1px solid var(--border);
}
.rating fieldset {
margin: 0 0 1rem;
padding: 0;
border: 0;
min-width: 0;
}
.rating legend {
padding: 0;
margin-bottom: .75rem;
font-size: 1.05rem;
font-weight: 600;
}
.rating .choices {
display: grid;
grid-template-columns: 1fr 1fr 2fr;
gap: .5rem;
}
.rating .choice {
position: relative;
display: block;
}
/* Das echte Radio bleibt für Tastatur und Screenreader erhalten, ist aber unsichtbar */
.rating .choice input {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
opacity: 0;
cursor: pointer;
}
.rating .choice span {
display: grid;
place-items: center;
min-height: 3rem;
padding: 0 .75rem;
text-align: center;
font-weight: 600;
color: var(--text);
background: var(--surface);
border: 1px solid var(--border);
border-radius: 8px;
transition: border-color .15s, background-color .15s;
}
.rating .choice input:hover + span { border-color: var(--accent); }
.rating .choice input:checked + span {
color: var(--accent-text);
background: var(--accent);
border-color: var(--accent);
}
.rating .choice input:focus-visible + span {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
.rating button[type="submit"] {
min-height: 2.75rem;
padding: 0 1.75rem;
font-weight: 600;
}
.rating button[type="submit"]:disabled { opacity: .5; cursor: default; }
@media (max-width: 480px) {
.rating .choices { grid-template-columns: 1fr 1fr; }
.rating .choice-none { grid-column: 1 / -1; }
.rating button[type="submit"] { width: 100%; }
}
+114
View File
@@ -1,4 +1,118 @@
{% extends "base.html" %} {% extends "base.html" %}
{% block content %} {% block content %}
<link rel="stylesheet" href="{{ url_for('static', filename='style/player.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='style/test.css') }}">
<h2 id="title"></h2>
<div class="ab-player" id="player">
<p class="status" role="status"></p>
<div class="track is-active">
<button type="button" class="track-label" aria-pressed="true" aria-label="Version A hören">A</button>
<canvas aria-hidden="true"></canvas>
</div>
<div class="track">
<button type="button" class="track-label" aria-pressed="false" aria-label="Version B hören">B</button>
<canvas aria-hidden="true"></canvas>
</div>
<div class="transport">
<button type="button" class="play" aria-label="Abspielen" disabled>
<svg class="icon-play" viewBox="0 0 24 24" aria-hidden="true"><path d="M7 4.5v15l13-7.5z"/></svg>
<svg class="icon-pause" viewBox="0 0 24 24" aria-hidden="true"><path d="M6 4h4v16H6zM14 4h4v16h-4z"/></svg>
</button>
<span class="time">0:00 / 0:00</span>
<button type="button" class="toggle" disabled>A/B wechseln</button>
<p class="hint">Leertaste startet und pausiert. [A] wechselt auf A, [B] auf B. [T] wechselt zwischen A und B.</p>
</div>
</div>
<form class="rating" id="rating">
<fieldset>
<legend>Welche Version hat die bessere Qualität?</legend>
<div class="choices">
<label class="choice">
<input type="radio" name="choice" value="a" required>
<span>A</span>
</label>
<label class="choice">
<input type="radio" name="choice" value="b">
<span>B</span>
</label>
<label class="choice choice-none">
<input type="radio" name="choice" value="non">
<span>Kein Unterschied</span>
</label>
</div>
</fieldset>
<button type="submit">Weiter</button>
</form>
<script src="{{ url_for('static', filename='player.js') }}"></script>
<script>
const player = new ABPlayer(document.getElementById("player"));
const form = document.getElementById("rating");
async function loadNext() {
const res = await fetch("{{ url_for('main.api_getRandomSong') }}");
if (res.status === 401) {
location.href = "{{ url_for('main.index') }}";
return;
}
const data = await res.json();
if (data.finished) {
player.reset();
document.getElementById("title").textContent = "Fertig, danke!";
document.getElementById("player").hidden = true;
form.hidden = true;
return;
}
document.getElementById("title").textContent = "Test " + data.number + ": " + data.song_name;
try {
await player.load(data.a, data.b);
} catch (err) {
console.error(err);
}
}
form.addEventListener("submit", async (e) => {
e.preventDefault();
const choice = new FormData(form).get("choice");
const submit = form.querySelector("button[type=submit]");
submit.disabled = true;
player.pause();
try {
const res = await fetch("{{ url_for('main.api_rate') }}", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ choice }),
});
if (res.status === 401) {
location.href = "{{ url_for('main.index') }}";
return;
}
if (!res.ok) throw new Error("HTTP " + res.status);
form.reset();
await loadNext();
} catch (err) {
console.error(err);
player.setStatus("Die Bewertung konnte nicht gespeichert werden. Bitte versuche es erneut.");
} finally {
submit.disabled = false;
}
});
loadNext();
</script>
{% endblock %} {% endblock %}