from flask import Blueprint, render_template, request, redirect, url_for, session, jsonify import json from pathlib import Path import random 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") def login(): if "name" in session: return redirect(url_for("main.index")) return render_template("login.html") @bp.route("/", methods=["GET", "POST"]) def index(): if request.method == "POST": session["name"] = request.form["name"].strip() if "name" not in session: return redirect(url_for("main.login")) return render_template("index.html") @bp.route("/test") def test(): if "name" not in session: return redirect(url_for("main.index")) 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})