""" Shared utilities for the subjective evaluation apps (Block 1 and Block 2). """ from __future__ import annotations import datetime as dt import json import random import re import time from pathlib import Path from typing import Dict, List, Optional, Set, Tuple import pandas as pd import streamlit as st # --------------------------------------------------------------------------- # Paths # --------------------------------------------------------------------------- _APP_DIR = Path(__file__).parent BLOCK_1_AUDIO_DIR = _APP_DIR / "block_1_audio" BLOCK_2_AUDIO_DIR = _APP_DIR / "block_2_audio" BLOCK_1_METADATA_PATH = _APP_DIR / "block_1_metadata.json" BLOCK_2_METADATA_PATH = _APP_DIR / "block_2_metadata.json" RESPONSES_DIR = _APP_DIR / "responses" BLOCK_1_RESPONSES_DIR = _APP_DIR / "responses_block1" BLOCK_2_RESPONSES_DIR = _APP_DIR / "responses_block2" INTRO_IMAGE_PATH = _APP_DIR / "intro_image.png" # --------------------------------------------------------------------------- # MOS scale (1–5) # --------------------------------------------------------------------------- MOS_SCALE = [1, 2, 3, 4, 5] MOS_LABELS = { 1: "1 – Very Poor", 2: "2 – Poor", 3: "3 – Fair", 4: "4 – Good", 5: "5 – Excellent", } # --------------------------------------------------------------------------- # Response CSV column order # --------------------------------------------------------------------------- RESPONSE_BASE_COLUMNS = [ "timestamp_utc", "participant_id", "participant_name", "hearing_condition", "uses_hearing_aids", "using_headphones", "quiet_environment", "consent_acknowledged", "block", "sample_id", "model_name", "mixture_audio_path", "output_audio_path", "scene_name", "instruction", "instruction_followed", "instruction_following_mos", "extraction_quality_mos", "spatial_preservation_mos", "contextual_correct", "response_duration_sec", ] # --------------------------------------------------------------------------- # Participant intake options # --------------------------------------------------------------------------- HEARING_OPTIONS = [ "No", "Yes, mild", "Yes, moderate or severe", ] BOOLEAN_OPTIONS = ["Yes", "No"] # --------------------------------------------------------------------------- # Sidebar instructions # --------------------------------------------------------------------------- SIDEBAR_INSTRUCTIONS_SHORT = ( "**Step 1:** Listen to both clips (mixture + output).\n\n" "**Step 2:** Answer the questions for each sample.\n\n" "MOS scale: 1 Very Poor – 5 Excellent\n\n" "You can take a break at any time and resume later with the same participant ID." ) # =================================================================== # Utility helpers # =================================================================== def rerun_app() -> None: """Compatibility wrapper for Streamlit rerun API.""" if hasattr(st, "experimental_rerun"): st.experimental_rerun() else: st.rerun() def sanitize_participant_id(participant_id: str) -> str: safe = re.sub(r"[^A-Za-z0-9_-]+", "_", participant_id.strip()) return safe.strip("_") def render_sidebar_image() -> None: if INTRO_IMAGE_PATH.exists(): st.sidebar.image(str(INTRO_IMAGE_PATH), use_container_width=True) # =================================================================== # Data loading # =================================================================== def load_block_metadata(block: int) -> List[Dict]: """Load metadata JSON for a block. Returns list of sample dicts.""" path = BLOCK_1_METADATA_PATH if block == 1 else BLOCK_2_METADATA_PATH if not path.exists(): st.error(f"Metadata file not found: {path}") st.stop() with open(path) as f: data = json.load(f) return data["samples"] def get_block_audio_dir(block: int) -> Path: return BLOCK_1_AUDIO_DIR if block == 1 else BLOCK_2_AUDIO_DIR def validate_audio_files(samples: List[Dict], audio_dir: Path) -> List[Dict]: """Keep only samples where both mixture and output WAV files exist.""" valid = [] for s in samples: mixture_path = audio_dir / s["mixture_file"] output_path = audio_dir / s["output_file"] if mixture_path.exists() and output_path.exists(): valid.append(s) return valid # =================================================================== # Response persistence # =================================================================== def _responses_dir_for_block(block_num: int) -> Path: if block_num == 1: return BLOCK_1_RESPONSES_DIR return BLOCK_2_RESPONSES_DIR def response_path_for_participant(participant_id: str, block_num: int) -> Path: resp_dir = _responses_dir_for_block(block_num) resp_dir.mkdir(parents=True, exist_ok=True) safe_id = sanitize_participant_id(participant_id) filename = f"responses_{safe_id}.csv" if safe_id else "responses.csv" return resp_dir / filename def completed_samples_from_responses(participant_id: str, block_num: int, block_filter: Optional[str] = None) -> Set[Tuple[str, str]]: """Return set of (block, sample_id) already completed by this participant. If block_filter is provided (e.g. "block_1"), only return entries for that block. """ path = response_path_for_participant(participant_id, block_num) if not path.exists(): return set() try: df = pd.read_csv(path) except Exception: return set() completed: Set[Tuple[str, str]] = set() if "block" not in df.columns or "sample_id" not in df.columns: return completed for _, row in df.iterrows(): block = str(row.get("block", "")) sample_id = str(row.get("sample_id", "")) if block and sample_id: if block_filter is None or block == block_filter: completed.add((block, sample_id)) return completed def build_response_record( sample: Dict, block: str, audio_dir: Path, instruction_followed: str = "", instruction_following_mos: object = "", extraction_quality_mos: object = "", spatial_preservation_mos: object = "", contextual_correct: str = "", start_time_key: str = "", ) -> Dict: profile = st.session_state.get("participant_profile", {}) start_time = st.session_state.get(start_time_key) duration = max(0.0, time.time() - start_time) if isinstance(start_time, (int, float)) else 0.0 return { "timestamp_utc": dt.datetime.utcnow().isoformat(), "participant_id": st.session_state.participant_id, "participant_name": profile.get("participant_name", ""), "hearing_condition": profile.get("hearing_condition", ""), "uses_hearing_aids": profile.get("uses_hearing_aids", ""), "using_headphones": profile.get("using_headphones", ""), "quiet_environment": profile.get("quiet_environment", ""), "consent_acknowledged": profile.get("consent_acknowledged", ""), "block": block, "sample_id": sample["sample_id"], "model_name": sample.get("model_name", ""), "mixture_audio_path": str(audio_dir / sample["mixture_file"]), "output_audio_path": str(audio_dir / sample["output_file"]), "scene_name": sample.get("scene_name", ""), "instruction": sample.get("instruction", ""), "instruction_followed": instruction_followed, "instruction_following_mos": instruction_following_mos, "extraction_quality_mos": extraction_quality_mos, "spatial_preservation_mos": spatial_preservation_mos, "contextual_correct": contextual_correct, "response_duration_sec": f"{duration:.2f}", } def append_response(record: Dict, participant_id: str, block_num: int) -> None: response_path = response_path_for_participant(participant_id, block_num) new_df = pd.DataFrame([record]) if response_path.exists(): existing = pd.read_csv(response_path) combined = pd.concat([existing, new_df], ignore_index=True) else: combined = new_df column_order = [col for col in RESPONSE_BASE_COLUMNS if col in combined.columns] remaining = sorted(col for col in combined.columns if col not in column_order) combined = combined[column_order + remaining] combined.to_csv(response_path, index=False) # =================================================================== # Session state helpers # =================================================================== def init_session_state_single_block() -> None: """Initialise session state for a single-block study.""" defaults = { "participant_initialized": False, "participant_id": "", "participant_profile": {}, "participant_pending_id": "", "intro_page_complete": False, "instructions_page_complete": False, "sample_order": [], "sample_index": 0, "block_complete": False, "completed_samples": set(), "responses": [], } for key, val in defaults.items(): st.session_state.setdefault(key, val) def start_single_block_session( participant_id: str, block_num: int, samples: List[Dict], ) -> None: """Set up a session for a single-block study.""" participant_id = participant_id.strip() st.session_state.participant_id = participant_id st.session_state.participant_initialized = True # Randomise sample order (deterministic per participant) ids = [s["sample_id"] for s in samples] random.Random(participant_id + f"_block{block_num}").shuffle(ids) st.session_state.sample_order = ids # Determine resume position block_label = f"block_{block_num}" completed = completed_samples_from_responses(participant_id, block_num, block_filter=block_label) st.session_state.completed_samples = completed idx = 0 all_done = True for i, sid in enumerate(ids): if (block_label, sid) not in completed: idx = i all_done = False break if all_done: idx = len(ids) st.session_state.block_complete = all_done st.session_state.sample_index = idx st.session_state.responses = [] def advance_sample(block_num: int, sample_id: str) -> None: """Mark sample complete and advance the index.""" completed = set(st.session_state.get("completed_samples", set())) completed.add((f"block_{block_num}", sample_id)) st.session_state.completed_samples = completed st.session_state.sample_index = st.session_state.get("sample_index", 0) + 1 # Clean up transient keys for this sample prefix = f"b{block_num}" for suffix in ["_unlocked", "_start"]: key = f"{prefix}_{sample_id}{suffix}" st.session_state.pop(key, None) # =================================================================== # Shared page renderers # =================================================================== def render_participant_gate( block_num: int, samples: List[Dict], study_title: str = "Model Evaluation Study", ) -> None: st.sidebar.markdown( f"
{study_title}
", unsafe_allow_html=True, ) st.subheader("Fill this form to begin") participant_name = st.text_input( "Name or Participant ID * (to resume a previous session, enter the same ID)", key="participant_name_input", ) if participant_name.strip(): block_label = f"block_{block_num}" completed = completed_samples_from_responses(participant_name, block_num, block_filter=block_label) if completed: total = len(samples) done = len(completed) remaining = max(0, total - done) pct = (done / total) * 100 if total else 0 if remaining: st.info( f"Welcome back! You've completed {done} of {total} samples " f"({pct:.0f}%). {remaining} samples remain — you'll resume " "where you left off." ) else: st.success( f"Great news, {participant_name.strip()}! " f"You've already completed all {total} samples." ) if "participant_hearing_condition" not in st.session_state: st.session_state.participant_hearing_condition = HEARING_OPTIONS[0] hearing_condition = st.radio( "Do you have any known hearing loss or hearing-related conditions?", HEARING_OPTIONS, key="participant_hearing_condition", horizontal=True, ) if "participant_uses_hearing_aids" not in st.session_state: st.session_state.participant_uses_hearing_aids = BOOLEAN_OPTIONS[1] uses_hearing_aids = st.radio( "Are you currently wearing hearing aids or assistive listening devices?", BOOLEAN_OPTIONS, key="participant_uses_hearing_aids", horizontal=True, ) headphone_options = [ "Yes, I confirm I am using headphones/earphones", "No, I am not using headphones", ] if "participant_using_headphones" not in st.session_state: st.session_state.participant_using_headphones = headphone_options[0] using_headphones = st.radio( "Are you using headphones or earphones for this study? " "(Please switch to headphones if not.)", headphone_options, key="participant_using_headphones", ) if "participant_quiet_environment" not in st.session_state: st.session_state.participant_quiet_environment = BOOLEAN_OPTIONS[0] quiet_environment = st.radio( "We recommend a quiet environment. Are you in a quiet space right now?", BOOLEAN_OPTIONS, key="participant_quiet_environment", horizontal=True, ) if "participant_consent_ack" not in st.session_state: st.session_state.participant_consent_ack = False consent_ack = st.checkbox( "I have read and understood the above, and I agree to participate in this audio-based study.", key="participant_consent_ack", ) begin = st.button("I confirm and would like to begin the study") if begin: participant_name_clean = participant_name.strip() errors = [] if not participant_name_clean: errors.append("Please provide your name or participant ID.") if using_headphones == headphone_options[1]: errors.append("Please switch to headphones before continuing.") if not consent_ack: errors.append("You must acknowledge the participation agreement to continue.") if errors: for msg in errors: st.warning(msg) return profile = { "participant_name": participant_name_clean, "hearing_condition": hearing_condition, "uses_hearing_aids": uses_hearing_aids, "using_headphones": using_headphones, "quiet_environment": quiet_environment, "consent_acknowledged": "Yes" if consent_ack else "No", } st.session_state.participant_profile = profile st.session_state.participant_pending_id = participant_name_clean st.session_state.participant_initialized = False st.session_state.intro_page_complete = False st.session_state.instructions_page_complete = False block_label = f"block_{block_num}" st.session_state.completed_samples = completed_samples_from_responses( participant_name_clean, block_num, block_filter=block_label ) rerun_app() def render_intro_page(description: str) -> None: render_sidebar_image() st.title("Welcome to the Model Evaluation Study") intro_html = ( "
" + description.strip().replace("\n\n", "

").replace("\n", "
") + "
" ) st.markdown(intro_html, unsafe_allow_html=True) if st.button("Next: Detailed instructions"): st.session_state.intro_page_complete = True rerun_app() def render_instruction_page( block_num: int, samples: List[Dict], instructions_text: str, ) -> None: render_sidebar_image() st.title("Study Instructions") st.markdown( instructions_text.replace("\n\n", "

").replace("\n", "
"), unsafe_allow_html=True, ) if st.button("I understand and I'm ready to begin"): participant_id = st.session_state.get("participant_pending_id", "").strip() if not participant_id: st.warning("Participant information missing. Please refill the form.") st.session_state.participant_profile = {} st.session_state.intro_page_complete = False st.session_state.instructions_page_complete = False rerun_app() return start_single_block_session(participant_id, block_num, samples) st.session_state.instructions_page_complete = True rerun_app() def render_sidebar_progress(block_num: int) -> None: pid = st.session_state.participant_id st.sidebar.markdown(f"**Participant:** {pid}") completed = st.session_state.get("completed_samples", set()) total = len(st.session_state.sample_order) block_label = f"block_{block_num}" done = sum(1 for b, _ in completed if b == block_label) if total > 0: st.sidebar.progress(done / total) st.sidebar.markdown(f"Progress: **{done} / {total}**") st.sidebar.markdown("---") st.sidebar.markdown("**Instructions (for reference)**") st.sidebar.markdown(SIDEBAR_INSTRUCTIONS_SHORT)