#!/usr/bin/env python3 """Serve the HTML study and store anonymous responses in a local SQLite file.""" import argparse import os from assignment import make_assignment from datetime import datetime, timezone from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import json import math import mimetypes from pathlib import Path import re import sqlite3 import threading from urllib.parse import unquote, urlsplit, parse_qs import uuid import webbrowser ROOT = Path(__file__).resolve().parent DATA = Path(os.environ.get("STUDY_DATA", ROOT.parent)).resolve() STATIC = {"index.html", "study.js", "model.js", "style.css", "lib/foa.js", "lib/panorama.js", "vendor/omnitone.min.js", "vendor/OMNITONE_LICENSE"} def load_study(): study = json.loads((ROOT / "study_config.json").read_text()) for asset in study["assets"].values(): path = (DATA / asset["path"]).resolve() if not path.is_relative_to(DATA) or not path.is_file(): raise ValueError(f"Missing study media: {asset['path']}") return study def public_study(study, participant_id=None): participant_id = str(uuid.UUID(participant_id)) if participant_id else str(uuid.uuid4()) seed, assignment = make_assignment(study, participant_id) return {"version": study["version"], "participant_id": participant_id, "name": study["name"], "rating_scale": study["rating_scale"], "random_seed": seed, "assignment": assignment, "trials": [ {key: trial[key] for key in ["id", "kind", "title", "duration", "questions", "global_prompt", "prompt_segments", "foreground_objects"]} | { "candidates": [{key: c[key] for key in ["id", "video", "audio", "gain_db"] if key in c} for c in trial["candidates"] if c["id"] in assignment["option_order"][trial["id"]]]} for trial in study["trials"]]} def finite_number(value, low, high): return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) and low <= value <= high def validate_response(body, study): if not isinstance(body, dict) or body.get("version") != study["version"]: raise ValueError("The study version changed. Start a new session.") try: participant = str(uuid.UUID(body["participant_id"])) except (ValueError, KeyError, TypeError, AttributeError): raise ValueError("Invalid anonymous participant ID.") from None trials = {t["id"]: t for t in study["trials"]} order = body.get("trial_order") if not isinstance(order, list) or len(order) != len(trials) or set(order) != set(trials): raise ValueError("Invalid trial order.") kinds = [trials[key]["kind"] for key in order] if sum(a != b for a, b in zip(kinds, kinds[1:])) != 1: raise ValueError("Trials must remain in two modality blocks.") option_order = body.get("option_order") seed, assignment = make_assignment(study, participant) if body.get("random_seed") != seed or order != assignment["trial_order"] or option_order != assignment["option_order"]: raise ValueError("Assignments must match this participant’s randomized selection.") if not isinstance(option_order, dict) or set(option_order) != set(trials): raise ValueError("Missing option order.") for key, trial in trials.items(): options = option_order[key] if not isinstance(options, list) or len(options) != 4 or len(set(options)) != 4 or not set(options).issubset({c["id"] for c in trial["candidates"]}): raise ValueError("Invalid option order.") answers = body.get("answers") if not isinstance(answers, dict) or not set(answers).issubset(trials): raise ValueError("Invalid answers.") if set(answers) != set(order[:len(answers)]): raise ValueError("Answers must follow the assigned trial order.") decoded = [] for index, key in enumerate(order): if key not in answers: continue answer, trial = answers[key], trials[key] ratings = answer.get("ratings") if isinstance(answer, dict) else None question_ids = {q["id"] for q in trial["questions"]} if isinstance(answer, dict) and answer.get("skipped"): raise ValueError("Skipping is not supported in this study.") if not isinstance(ratings, dict) or set(ratings) != set(option_order[key]): raise ValueError("Rate all four samples on all three criteria.") for scores in ratings.values(): if not isinstance(scores, dict) or set(scores) != question_ids or any(type(score) is not int or not 1 <= score <= 5 for score in scores.values()): raise ValueError("Each criterion requires an integer rating from 1 to 5.") reviewed = answer.get("reviewed_seconds", {}) if not isinstance(reviewed, dict) or set(reviewed) != set(option_order[key]): raise ValueError("Invalid playback statistics.") if not all(finite_number(seconds, 0, 86400) for seconds in reviewed.values()): raise ValueError("Invalid playback statistics.") if not finite_number(answer.get("elapsed_seconds"), 0, 86400 * 30): raise ValueError("Invalid elapsed time.") pose = answer.get("pose", {}) if not isinstance(pose, dict) or not all(finite_number(pose.get(k), lo, hi) for k, lo, hi in [("yaw", -180, 180), ("pitch", -85, 85), ("fov", 35, 120)]): raise ValueError("Invalid viewing direction.") if not finite_number(answer.get("volume_db"), -60, 0): raise ValueError("Invalid listening volume.") mapping = {c["id"]: c for c in trial["candidates"]} decoded_ratings = [] for candidate_id in option_order[key]: candidate = mapping[candidate_id] for question in trial["questions"]: decoded_ratings.append({"criterion_id": question["id"], "criterion_label": question["label"], "candidate_id": candidate_id, "option": "ABCDEF"[option_order[key].index(candidate_id)], "method": candidate["method"], "method_label": candidate["label"], "score": ratings.get(candidate_id, {}).get(question["id"])}) decoded.append({"trial_id": key, "trial_number": index + 1, "kind": trial["kind"], "scene": trial["scene"], "ratings": decoded_ratings, "option_mapping": {"ABCDEF"[i]: mapping[c]["method"] for i, c in enumerate(option_order[key])}, **{k: answer[k] for k in ["reviewed_seconds", "elapsed_seconds", "pose", "volume_db"]}}) complete = body.get("complete") is True if complete and len(answers) != len(trials): raise ValueError("Complete all trials before submitting.") return {"participant_id": participant, "version": study["version"], "random_seed": seed, "trial_order": order, "option_order": option_order, "answers": decoded, "complete": complete} def initialize_database(path): path.parent.mkdir(parents=True, exist_ok=True) with sqlite3.connect(path) as db: db.execute("""CREATE TABLE IF NOT EXISTS sessions ( participant_id TEXT PRIMARY KEY, version TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, completed_at TEXT, answer_count INTEGER NOT NULL, payload TEXT NOT NULL)""") def save_response(path, record): now = datetime.now(timezone.utc).isoformat() with sqlite3.connect(path, timeout=10) as db: db.execute("BEGIN IMMEDIATE") existing = db.execute("SELECT version, answer_count, completed_at, payload FROM sessions WHERE participant_id=?", (record["participant_id"],)).fetchone() if existing: previous = json.loads(existing[3]) if existing[0] != record["version"] or previous["trial_order"] != record["trial_order"] or previous["option_order"] != record["option_order"]: raise ValueError("This participant ID already has a different assignment.") if len(record["answers"]) < existing[1]: raise ValueError("A newer response is already saved. Use the latest study tab.") if existing[2] and previous != record: raise ValueError("This session is already submitted. Start a new participant.") completed = (existing[2] if existing else None) or (now if record["complete"] else None) db.execute("""INSERT INTO sessions VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(participant_id) DO UPDATE SET updated_at=excluded.updated_at, completed_at=excluded.completed_at, answer_count=excluded.answer_count, payload=excluded.payload""", (record["participant_id"], record["version"], now, now, completed, len(record["answers"]), json.dumps(record))) return {"saved": True, "participant_id": record["participant_id"], "answer_count": len(record["answers"]), "complete": record["complete"], "saved_at": now} def byte_range(header, size): match = re.fullmatch(r"bytes=(\d*)-(\d*)", header) if not match or not any(match.groups()): raise ValueError("Invalid range") first, last = match.groups() start = int(first) if first else max(0, size - int(last)) end = min(int(last), size - 1) if first and last else size - 1 if not 0 <= start <= end < size: raise ValueError("Unsatisfiable range") return start, end def handler_for(study, database, response_store=None): save_lock = threading.Lock() class Handler(BaseHTTPRequestHandler): def json_reply(self, data, code=200): payload = json.dumps(data).encode() self.send_response(code) self.send_header("Content-Type", "application/json; charset=utf-8") self.send_header("Cache-Control", "no-store") self.send_header("Content-Length", str(len(payload))) self.end_headers() if self.command != "HEAD": self.wfile.write(payload) def do_POST(self): if urlsplit(self.path).path != "/api/responses": self.send_error(404) return origin = self.headers.get("Origin") if origin and urlsplit(origin).netloc != self.headers.get("Host"): self.json_reply({"error": "Use the study's own page to submit."}, 403) return try: size = int(self.headers.get("Content-Length", "0")) if not 0 < size <= 100_000: raise ValueError("Invalid response size.") body = json.loads(self.rfile.read(size)) record = validate_response(body, study) with save_lock: result = save_response(database, record) if response_store: try: response_store.save(record, result) except Exception: self.json_reply({"error": "Durable response storage is temporarily unavailable. Please retry; your browser progress is retained."}, 503) return self.json_reply(result) except (ValueError, TypeError, KeyError, UnicodeError): self.json_reply({"error": "The response is invalid or conflicts with a saved session. Choose a valid option, or resume in your original tab."}, 400) except sqlite3.Error: self.json_reply({"error": "The server could not save your response. Your browser copy is retained; please retry."}, 503) def do_HEAD(self): self.do_GET() def do_GET(self): route = unquote(urlsplit(self.path).path) if route == "/api/study": try: participant = parse_qs(urlsplit(self.path).query).get("participant_id", [None])[0] self.json_reply(public_study(study, participant)) except ValueError: self.json_reply({"error": "Invalid participant ID."}, 400) return if route.startswith("/media/"): asset = study["assets"].get(route[len("/media/"):]) if not asset: self.send_error(404) return path = (DATA / asset["path"]).resolve() else: name = route.lstrip("/") or "index.html" if name not in STATIC: self.send_error(404) return path = ROOT / name size = path.stat().st_size start, end, code = 0, size - 1, 200 if self.headers.get("Range"): try: start, end = byte_range(self.headers["Range"], size) code = 206 except ValueError: self.send_response(416) self.send_header("Content-Range", f"bytes */{size}") self.send_header("Content-Length", "0") self.end_headers() return self.send_response(code) self.send_header("Content-Type", mimetypes.guess_type(path.name)[0] or "application/octet-stream") self.send_header("Content-Length", str(end - start + 1)) self.send_header("Accept-Ranges", "bytes") self.send_header("Cache-Control", "no-cache") if code == 206: self.send_header("Content-Range", f"bytes {start}-{end}/{size}") self.end_headers() if self.command == "HEAD": return try: with path.open("rb") as stream: stream.seek(start) left = end - start + 1 while left: chunk = stream.read(min(left, 262144)) if not chunk: break self.wfile.write(chunk) left -= len(chunk) except (BrokenPipeError, ConnectionResetError): pass def log_message(self, format_, *args): if len(args) > 1 and str(args[1]) not in {"200", "206"}: super().log_message(format_, *args) return Handler def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--port", type=int, default=int(os.environ.get("PORT", "8766"))) parser.add_argument("--host", default="127.0.0.1") parser.add_argument("--no-open", action="store_true") parser.add_argument("--results", type=Path, default=ROOT / "responses/study.sqlite3") args = parser.parse_args() study = load_study() database = args.results.expanduser().resolve() initialize_database(database) response_store = None if os.environ.get("RESPONSE_DATASET"): from response_store import ResponseStore response_store = ResponseStore(os.environ["RESPONSE_DATASET"], os.environ["HF_TOKEN"]) response_store.restore(database) elif os.environ.get("SPACE_ID"): raise RuntimeError("Configure a private RESPONSE_DATASET and HF_TOKEN before collecting hosted responses") server = ThreadingHTTPServer((args.host, args.port), handler_for(study, database, response_store)) url = f"http://127.0.0.1:{server.server_port}" print(f"Study: {url}\nResponses: {database}\nPress Control+C to stop.", flush=True) if not args.no_open: threading.Timer(0.4, webbrowser.open, args=(url,)).start() try: server.serve_forever() except KeyboardInterrupt: pass finally: server.server_close() if __name__ == "__main__": main()