ReactorRoom / web_app.py
princessamygdala
Claude Opus 4.8 (1M context)
Scaffold ReactorRoom: observational-learning-of-empathy NiceWebRL task
63879a2
Raw History Blame Contribute Delete
21.5 kB
import os.path
import asyncio
from asyncio import Lock
from nicegui import app, ui
from fastapi import Request
from tortoise import Tortoise
import httpx
import config
import nicewebrl
from nicewebrl.logging import setup_logging, get_logger
from nicewebrl.utils import wait_for_button_or_keypress
from nicewebrl import stages, TimeStep
import nicewebrl
import os
from importlib.util import find_spec
import shutil
import asyncio
import json
import time
from datetime import datetime
from nicewebrl.logging import get_logger
from nicegui import app
def _stamped_names(files):
"""Map local filenames -> '<pid>_<date>_<time>...' so every stored file carries
the participant id + the date/time of the session (PsychoPy-style, no overwrites)."""
pid = app.storage.user.get("pid", "") or app.storage.user.get("seed", "unknown")
ts = app.storage.user.get("session_ts")
if not ts:
ts = datetime.now().strftime("%Y-%m-%d_%Hh%M.%S")
app.storage.user["session_ts"] = ts # one stamp per session
name_map = {}
for f in files:
if not f:
continue
b = os.path.basename(f)
# strip the internal "user_data_<seed>" prefix, keep any suffix (e.g. _qualtrics.csv)
rest = b.split(".", 1)
ext = "." + rest[1] if len(rest) > 1 else ""
suffix = ""
stem = rest[0]
if "_" in stem.replace("user_data_", "", 1):
suffix = "_" + stem.replace("user_data_", "", 1).split("_", 1)[1]
name_map[b] = f"{pid}_{ts}{suffix}{ext}"
return name_map
# Google Cloud Storage functionality (copied from xland-LLM-assistant)
from dotenv import load_dotenv
from google.auth.exceptions import TransportError
from google.cloud import storage
from google.cloud.exceptions import exceptions as gcs_exceptions
import numpy as np
import ole_design
import ole_stages as E
from ole_stages import experiment
load_dotenv()
logger = get_logger(__name__)
GOOGLE_CREDENTIALS = "./google-cloud-key.json"
# Google Cloud Storage
BUCKET_NAME = "jaxmaze"
# Data
DATA_DIR = "./data"
DATABASE_FILE = "db.sqlite"
_user_locks = {}
async def save_file_to_gcs(local_filename, blob_filename, bucket_name: str):
try:
storage_client = storage.Client.from_service_account_json(GOOGLE_CREDENTIALS)
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(blob_filename)
# Run the blocking upload in a thread pool
await asyncio.to_thread(blob.upload_from_filename, local_filename)
logger.info(f"Saved {blob_filename} in bucket {bucket.name}")
return True # Successfully saved
except Exception as e:
logger.info(f"Unexpected error: {e}")
logger.info("Skipping GCS upload")
return False # Failed to save
async def save_to_gcs_with_retries(
files_to_save, max_retries=5, retry_delay=5, bucket_name: str = ""
):
"""Save multiple files to Google Cloud Storage with retry logic."""
assert bucket_name != "", "Bucket name is required"
for attempt in range(max_retries):
try:
# Try to save all files
for local_file in files_to_save:
saved = await save_file_to_gcs(
local_filename=local_file, blob_filename=local_file, bucket_name=bucket_name
)
if not saved:
raise Exception(f"Failed to save {local_file}")
logger.info(f"Successfully saved data to GCS on attempt {attempt + 1}")
return True
except Exception as e:
if attempt < max_retries - 1:
logger.info(f"Error saving to GCS: {e}. Retrying in {retry_delay} seconds...")
await asyncio.sleep(retry_delay)
else:
logger.info(f"Failed to save to GCS after {max_retries} attempts: {e}")
return False
def get_user_lock():
user_seed = app.storage.user["seed"]
if user_seed not in _user_locks:
_user_locks[user_seed] = Lock()
return _user_locks[user_seed]
async def global_handle_key_press(e, container):
logger.info("global_handle_key_press")
if experiment.finished():
logger.info("Experiment finished")
return
stage = await experiment.get_stage()
if stage.get_user_data("finished", False):
return
await stage.handle_key_press(e, container)
local_handle_key_press = stage.get_user_data("local_handle_key_press")
if local_handle_key_press is not None:
await local_handle_key_press()
setup_logging(DATA_DIR, nicegui_storage_user_key="seed")
logger = get_logger("main")
if not os.path.exists(DATA_DIR):
os.mkdir(DATA_DIR)
async def init_db() -> None:
await Tortoise.init(
db_url=f"sqlite://{DATA_DIR}/{DATABASE_FILE}",
modules={"models": ["nicewebrl.stages"]},
)
await Tortoise.generate_schemas()
async def close_db() -> None:
await Tortoise.close_connections()
app.on_startup(init_db)
app.on_shutdown(close_db)
#####################################
# Participant ID + intro flow (mouse-only, Back/Next)
#####################################
INTRO_PAGES = ["welcome"]
# dev/debug: ?dev=1&start=<point> skips every stage BEFORE that point.
_INSTR = {"Instruction_Welcome", "Instruction_CoverStory", "Instruction_HowTo"}
DEV_SKIP = {
"practice": set(_INSTR),
"baseline": _INSTR | {"Practice", "Comprehension", "IRI",
"Impression_pre", "Willingness_pre"},
"learning": _INSTR | {"Practice", "Comprehension", "IRI",
"Impression_pre", "Willingness_pre", "Baseline"},
"end": _INSTR | {"Practice", "Comprehension", "IRI",
"Impression_pre", "Willingness_pre", "Baseline",
"Learn1", "Learn2", "Learn3", "Learn4", "AttentionCheck",
"Generalization", "Impression_post", "Willingness_post"},
}
def _store_schedule():
"""Once the PID is known, cache the participant's group + co-viewers (and a
baseline_mean placeholder) in app.storage.user for the stages/exporter to read."""
pid = app.storage.user.get("pid")
if not pid or app.storage.user.get("schedule_stored"):
return
try:
sched = ole_design.make_schedule(pid)
app.storage.user["group"] = sched["group"]
app.storage.user["coviewers"] = sched["coviewers"]
app.storage.user.setdefault("baseline_mean", None)
app.storage.user["schedule_stored"] = True
logger.info(f"schedule stored for pid={pid} group={sched['group']} "
f"coviewers={[c['name'] for c in sched['coviewers']]}")
except Exception as e:
logger.warning(f"could not store schedule for pid={pid}: {e}")
async def pid_screen(container):
"""Experimenter types the participant ID; it's stored and reflected in the URL."""
nicewebrl.clear_element(container)
ev = asyncio.Event()
with container.style("align-items:center; max-width:600px;"):
ui.markdown("**Experimenter:** enter the participant ID, then click Start.")
pid_in = ui.input("Participant ID", value=str(app.storage.user.get("pid", "")))
def start():
pid = (pid_in.value or "").strip()
app.storage.user["pid"] = pid
try:
ui.run_javascript(
"history.replaceState(null,'','?pid='+encodeURIComponent(" + repr(pid) + "))"
)
except Exception:
pass
ev.set()
ui.button("Start", on_click=start)
await ev.wait()
async def _intro_page(container, page, can_back):
nicewebrl.clear_element(container)
result = {"val": None}
ev = asyncio.Event()
with container.style("align-items:center; max-width:780px;"):
if page == "welcome":
ui.markdown("## 🎬 ReactorRoom")
ui.markdown(
"Welcome! You're about to join an online **video-reaction platform**. "
"Everything is done with the **mouse** — you'll drag sliders and click buttons.\n\n"
"Press **Next** to begin."
)
with ui.row().style("margin-top:14px;"):
if can_back:
ui.button("Back", on_click=lambda: (result.update(val="back"), ev.set())).props("outline")
ui.button("Next", on_click=lambda: (result.update(val="next"), ev.set()))
await ev.wait()
return result["val"]
async def device_gate(container):
"""Desktop gate + fullscreen prompt (prevents bad mobile data)."""
nicewebrl.clear_element(container)
ev = asyncio.Event()
with container.style("align-items:center; max-width:640px;"):
ui.markdown("## 🖥️ Before you start")
ui.markdown(
"Please take part on a **computer or laptop** with a **mouse or trackpad** — "
"you'll drag sliders and click buttons to rate short video clips.\n\n"
"It will **not** work well on a phone. For the best experience we'll switch to "
"**fullscreen**."
)
warn = ui.markdown("")
def start():
try:
ui.run_javascript(
"try{var e=document.documentElement;"
"(e.requestFullscreen||e.webkitRequestFullscreen||function(){}).call(e);}catch(e){}")
except Exception:
pass
ev.set()
ui.button("Enter fullscreen & start 🎬", on_click=start)
# gentle warning if this looks like a touch device
try:
is_touch = await ui.run_javascript(
"(('ontouchstart' in window)||navigator.maxTouchPoints>0) && "
"Math.min(window.innerWidth,window.innerHeight)<820", timeout=5)
if is_touch:
warn.set_content("⚠️ **This looks like a touch device.** Please switch to a computer "
"before continuing.")
except Exception:
pass
await ev.wait()
async def run_intro(container):
# if the ID was passed in the URL (?pid=...), skip the experimenter set-up screen
if not app.storage.user.get("pid"):
await pid_screen(container)
_store_schedule()
if not app.storage.user.get("device_ok"):
await device_gate(container)
app.storage.user["device_ok"] = True
idx = 0
while idx < len(INTRO_PAGES):
res = await _intro_page(container, INTRO_PAGES[idx], can_back=(idx > 0))
idx = max(0, idx - 1) if res == "back" else idx + 1
async def start_experiment(meta_container, stage_container):
# ========================================
# Intro (participant ID, welcome) -- mouse only
# ========================================
if not (app.storage.user.get("experiment_started", False)):
await run_intro(stage_container)
app.storage.user["experiment_started"] = True
_store_schedule()
# ========================================
# Register key handler (only used to advance "press to continue" screens)
# ========================================
ui.on("key_pressed", lambda e: global_handle_key_press(e, stage_container))
# dev/debug: skip every stage before the requested start point
dev_skip = set()
if app.storage.user.get("dev_mode"):
dev_skip = DEV_SKIP.get(app.storage.user.get("dev_start", "baseline"), set())
logger.info("Starting experiment")
while not experiment.finished():
stage = await experiment.get_stage()
if stage.name in dev_skip:
await experiment.advance_stage()
continue
await run_stage(stage, stage_container)
await stage.finish_saving_user_data()
await experiment.advance_stage()
await finish_experiment(stage_container)
async def finish_experiment(container):
app.storage.user["experiment_finished"] = True
# save quietly (no feedback prompt)
with container:
nicewebrl.clear_element(container)
ui.markdown("### Saving your responses... please don't close the page.")
try:
await save_data(feedback=None)
app.storage.user["data_saved"] = True
except Exception as e:
logger.error(f"Save failed: {e}")
with container.style("align-items:center;"):
nicewebrl.clear_element(container)
ui.markdown("## Thank you! 🙏")
ui.markdown("Your responses have been saved. Please let your experimenter know you're done.")
async def save_data(feedback=None, **kwargs):
if not GOOGLE_CREDENTIALS:
logger.warning("No Google credentials found, skipping save")
return
user_data_file = nicewebrl.user_data_file()
user_metadata_file = nicewebrl.user_metadata_file()
# --------------------------------
# save user data to final line of file
# --------------------------------
user_storage = nicewebrl.make_serializable(dict(app.storage.user))
metadata = dict(
finished=True,
feedback=feedback,
user_storage=user_storage,
**kwargs,
)
with open(user_metadata_file, "w") as f:
json.dump(metadata, f)
files_to_save = [user_data_file, user_metadata_file]
# Local-first: KEEP the participant's data on disk. Only upload to Google Cloud
# and delete locally if a real bucket is configured AND credentials exist.
bucket = getattr(config, "BUCKET_NAME", None)
gcs_ok = False
if bucket and os.path.exists(GOOGLE_CREDENTIALS):
logger.info(f"Saving to bucket: {bucket}")
gcs_ok = await save_to_gcs_with_retries(
files_to_save, max_retries=5, bucket_name=bucket
)
if gcs_ok:
from nicewebrl.stages import StageStateModel
await StageStateModel.filter(session_id=app.storage.browser["id"]).delete()
for local_file in files_to_save:
try:
os.remove(local_file)
logger.info(f"Uploaded + removed local file: {local_file}")
except Exception as e:
logger.warning(f"Failed to delete local file {local_file}: {str(e)}")
else:
# no cloud bucket -> keep data locally, export the single long-format CSV,
# push to GitLab, and append the participant's randomization-log row.
logger.info(f"No cloud bucket; keeping data locally at {user_data_file}")
csv_path = None
try:
import export_csv
csv_path = export_csv.export(user_data_file, pid=app.storage.user.get("pid"))
except Exception as e:
logger.warning(f"CSV export failed: {e}")
try:
import gitlab_save
pid = app.storage.user.get("pid", "") or app.storage.user.get("seed", "unknown")
to_push = [f for f in [user_data_file, user_metadata_file, csv_path] if f and os.path.exists(f)]
ok = gitlab_save.push_to_gitlab(to_push, subdir=f"data/{pid}", name_map=_stamped_names(to_push))
logger.info(f"GitLab push {'ok' if ok else 'skipped/failed'} -> data/{pid}/")
try:
gitlab_save.append_to_log(ole_design.manifest_row(pid))
except Exception as e:
logger.warning(f"randomization log append failed: {e}")
except Exception as e:
logger.warning(f"GitLab push error: {e}")
async def incremental_save():
"""Periodically push the current data to GitLab so a mid-quit participant isn't lost."""
try:
if not app.storage.user.get("pid"):
return
udf = nicewebrl.user_data_file()
if not os.path.exists(udf):
return
import export_csv
import gitlab_save
csv_path = await asyncio.to_thread(export_csv.export, udf, app.storage.user.get("pid"))
to_push = [f for f in [udf, csv_path] if f and os.path.exists(f)]
pid = app.storage.user["pid"]
await asyncio.to_thread(gitlab_save.push_to_gitlab, to_push, f"data/{pid}",
name_map=_stamped_names(to_push))
except Exception as e:
logger.warning(f"incremental save failed: {e}")
async def run_stage(stage, container):
stage_over_event = asyncio.Event()
async def local_handle_key_press():
async with get_user_lock():
if stage.get_user_data("finished", False):
logger.info(f"Finished {stage.name} via key press")
stage_over_event.set()
await stage.set_user_data(local_handle_key_press=local_handle_key_press)
async def handle_button_press():
if stage.get_user_data("finished", False):
return
await stage.handle_button_press(container)
async with get_user_lock():
if stage.get_user_data("finished", False):
logger.info(f"Finished {stage.name} via button press")
stage_over_event.set()
with container.style("align-items: center;"):
await stage.activate(container)
if stage.get_user_data("finished", False):
logger.info(f"Finished {stage.name} immediately after activation")
stage_over_event.set()
if stage.next_button:
with container:
button = ui.button("Next page")
await wait_for_button_or_keypress(button)
await handle_button_press()
await stage_over_event.wait()
async def check_if_over(container, episode_limit=60):
minutes_passed = nicewebrl.get_user_session_minutes()
minutes_passed = app.storage.user["session_duration"]
if minutes_passed > episode_limit:
pass
@ui.page("/")
async def index(request: Request):
nicewebrl.initialize_user(request=request)
await experiment.initialize()
# let the participant ID be pre-filled via ?pid=... in the URL
pid_q = request.query_params.get("pid")
if pid_q and not app.storage.user.get("pid"):
app.storage.user["pid"] = pid_q
# ---- dev/debug shortcuts (jump past the front matter; flagged in data) ----
# e.g. ?dev=1&start=learning&trials=3
if request.query_params.get("dev") in ("1", "true", "yes"):
app.storage.user["dev_mode"] = True
app.storage.user["experiment_started"] = True # skip the intro (gate/welcome)
app.storage.user["device_ok"] = True
if not app.storage.user.get("pid"):
app.storage.user["pid"] = pid_q or "1DEV"
start = (request.query_params.get("start") or "baseline").lower()
if start in DEV_SKIP:
app.storage.user["dev_start"] = start
t = request.query_params.get("trials")
if t and t.isdigit():
app.storage.user["dev_trials"] = max(1, min(48, int(t)))
_store_schedule()
basic_javascript_file = nicewebrl.basic_javascript_file()
with open(basic_javascript_file) as f:
ui.add_body_html("<script>" + f.read() + "</script>")
# load the clip player (browser-side canvas clip engine)
clips_js = os.path.join(os.path.dirname(__file__), "static", "clips.js")
try:
with open(clips_js) as f:
ui.add_body_html("<script>" + f.read() + "</script>")
except FileNotFoundError:
logger.warning(f"static/clips.js not found at {clips_js}; clips will not render")
card = (
ui.card(align_items=["center"])
.classes("fixed-center")
.style(
"width: 80vw;"
"max-height: 90vh;"
"overflow: auto;"
"display: flex;"
"flex-direction: column;"
"justify-content: flex-start;"
"align-items: center;"
"padding: 1rem;"
)
)
with card:
meta_container = ui.column()
with meta_container.style("align-items: center;"):
display_container = ui.row()
with display_container.style("align-items: center;"):
stage_container = ui.column()
ui.timer(
interval=10,
callback=lambda: check_if_over(
episode_limit=200, container=stage_container),
)
# push partial data to GitLab every ~2 min so a mid-quit isn't lost
ui.timer(interval=120, callback=incremental_save)
footer_container = ui.row()
with meta_container.style("align-items: center;"):
await footer(footer_container)
with display_container.style("align-items: center;"):
await start_experiment(display_container, stage_container)
async def footer(footer_container):
"""Footer shown on EVERY screen: fullscreen, a sound on/off toggle, and a Pause
button (with a 'Paused' overlay)."""
overlay = ui.column().style(
"position:fixed; inset:0; z-index:9999; background:rgba(10,14,22,0.93);"
"align-items:center; justify-content:center; gap:6px;")
with overlay:
ui.icon("pause_circle", size="80px").style("color:#7c5cff;")
ui.markdown("## Paused").classes("text-center")
ui.markdown("Take a breather.").classes("text-center")
resume_btn = ui.button("Resume", icon="play_arrow")
overlay.set_visibility(False)
def do_resume():
app.storage.user["on_break"] = False
try:
ui.run_javascript("window.Clips && Clips.resume && Clips.resume()")
except Exception:
pass
overlay.set_visibility(False)
resume_btn.on_click(do_resume)
def do_pause():
app.storage.user["on_break"] = True
try:
ui.run_javascript("window.Clips && Clips.pause && Clips.pause()")
except Exception:
pass
overlay.set_visibility(True)
with footer_container:
ui.button("Fullscreen", icon="fullscreen",
on_click=nicewebrl.utils.toggle_fullscreen).props("flat")
sound_on = app.storage.user.get("sound_on", True)
sbtn = ui.button("Sound on" if sound_on else "Sound off",
icon="volume_up" if sound_on else "volume_off").props("flat")
def toggle_sound():
on = not app.storage.user.get("sound_on", True)
app.storage.user["sound_on"] = on
sbtn.text = "Sound on" if on else "Sound off"
sbtn.props(f'icon={"volume_up" if on else "volume_off"}')
try:
ui.run_javascript(f"window.Clips && Clips.configure && "
f"Clips.configure({{muted:{'false' if on else 'true'}}})")
except Exception:
pass
sbtn.on_click(toggle_sound)
ui.button("Pause", icon="pause", on_click=do_pause).props("flat")
# apply the saved mute state to the engine on load
if not app.storage.user.get("sound_on", True):
try:
ui.run_javascript("window.Clips && Clips.configure && Clips.configure({muted:true})")
except Exception:
pass
ui.run(
storage_secret=os.getenv("STORAGE_SECRET", "private key to secure the browser session cookie"),
reload=os.getenv("RELOAD", "1") == "1" and "FLY_ALLOC_ID" not in os.environ,
title="ReactorRoom",
host="0.0.0.0",
port=int(os.getenv("PORT", "8084")),
)