""" 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"