carankt's picture
Verification: upload code and scripts only
c22b544 verified
Raw
History Blame Contribute Delete
32.2 kB
#!/usr/bin/env python3
"""
Streamlit app for subjective evaluation of a model's audio extraction results.
The study has two blocks:
Block 1 – Instruction Following: participants hear mixture + model output
with an instruction, and rate instruction-following + extraction quality.
Block 2 – Contextual Evaluation: participants hear mixture + model output
without an instruction, and judge whether the headphone behaviour
was appropriate + rate extraction quality.
Prerequisites:
pip install streamlit pandas
Run locally:
streamlit run app.py
"""
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"
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"]
# ---------------------------------------------------------------------------
# Text content
# ---------------------------------------------------------------------------
INTRO_DESCRIPTION = (
"In this study, you'll use headphones to evaluate how well a model "
"processes audio scenes.\n\n"
"The study is divided into two blocks:\n\n"
"**Block 1 – Instruction Following:** You will hear the original audio mixture "
"and the model's output, along with the instruction the model was given. "
"You will rate how well the model followed the instruction and the quality "
"of the extracted audio.\n\n"
"**Block 2 – Contextual Evaluation:** You will hear the original audio mixture "
"and the model's output, but without seeing any instruction. Instead, imagine "
"you are wearing noise-cancelling headphones that reacted to your environment. "
"You will judge whether the headphone did the right thing and rate the quality "
"of the extracted audio.\n\n"
"Each sample takes about 30–60 seconds. You can take a break between samples "
"by exiting the app and returning later with the same participant ID."
)
INSTRUCTIONS_PAGE_TEXT = (
"Each sample will guide you through these steps:\n\n"
"**Step 1: Listen** – Press Play to hear both the original audio mixture "
"(before processing) and the model's output (after processing). "
"Listen to each clip at least once.\n\n"
"**Step 2: Answer Questions** – Rate the model's performance using the questions provided.\n\n"
"**Block 1** (Instruction Following) has four questions per sample:\n"
"1. Did the model follow the instruction? (Yes / No)\n"
"2. How well did the model follow the instruction? (1–5 MOS scale)\n"
"3. Rate the quality of the extracted audio (1–5 MOS scale)\n"
"4. Were the spatial cues preserved in the output? (1–5 MOS scale)\n\n"
"**Block 2** (Contextual Evaluation) has two questions per sample:\n"
"1. Did the headphone do the right thing? (Yes / No)\n"
"2. Rate the quality of the extracted audio (1–5 MOS scale)\n\n"
"The MOS scale is:\n"
"1 – Very Poor | 2 – Poor | 3 – Fair | 4 – Good | 5 – Excellent\n\n"
"Click **Start** when you're ready."
)
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."
)
BLOCK_2_TRANSITION_TEXT = (
"In this block, you will again hear an input mixture and a model output. "
"However, **no instruction will be shown**.\n\n"
"Instead, imagine you are wearing noise-cancelling headphones. "
"The headphone heard the environment around you and produced the output you hear. "
"Your job is to evaluate whether the headphone did the right thing.\n\n"
"**Questions per sample:**\n"
"1. Did the headphone do the right thing? (Yes / No)\n"
"2. Rate the quality / purity of the extracted audio (1–5 MOS scale)"
)
# ===================================================================
# 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 response_path_for_participant(participant_id: str) -> Path:
RESPONSES_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 RESPONSES_DIR / filename
def completed_samples_from_responses(participant_id: str) -> Set[Tuple[str, str]]:
"""Return set of (block, sample_id) already completed by this participant."""
path = response_path_for_participant(participant_id)
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:
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) -> None:
response_path = response_path_for_participant(participant_id)
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 management
# ===================================================================
def init_session_state() -> None:
defaults = {
"participant_initialized": False,
"participant_id": "",
"participant_profile": {},
"participant_pending_id": "",
"intro_page_complete": False,
"instructions_page_complete": False,
"current_block": 1,
"block_1_order": [],
"block_2_order": [],
"block_1_index": 0,
"block_2_index": 0,
"block_1_complete": False,
"block_2_instructions_shown": False,
"completed_samples": set(),
"responses": [],
}
for key, val in defaults.items():
st.session_state.setdefault(key, val)
def start_participant_session(
participant_id: str,
block_1_samples: List[Dict],
block_2_samples: List[Dict],
) -> None:
participant_id = participant_id.strip()
st.session_state.participant_id = participant_id
st.session_state.participant_initialized = True
# Randomise sample order within each block (deterministic per participant)
b1_ids = [s["sample_id"] for s in block_1_samples]
b2_ids = [s["sample_id"] for s in block_2_samples]
random.Random(participant_id + "_block1").shuffle(b1_ids)
random.Random(participant_id + "_block2").shuffle(b2_ids)
st.session_state.block_1_order = b1_ids
st.session_state.block_2_order = b2_ids
# Determine resume position
completed = completed_samples_from_responses(participant_id)
st.session_state.completed_samples = completed
# Find first incomplete in block 1
b1_idx = 0
b1_all_done = True
for i, sid in enumerate(b1_ids):
if ("block_1", sid) not in completed:
b1_idx = i
b1_all_done = False
break
if b1_all_done:
b1_idx = len(b1_ids)
st.session_state.block_1_complete = b1_all_done
st.session_state.block_1_index = b1_idx
if b1_all_done:
st.session_state.current_block = 2
st.session_state.block_2_instructions_shown = True # skip re-showing on resume
b2_idx = 0
b2_all_done = True
for i, sid in enumerate(b2_ids):
if ("block_2", sid) not in completed:
b2_idx = i
b2_all_done = False
break
if b2_all_done:
b2_idx = len(b2_ids)
st.session_state.block_2_index = b2_idx
else:
st.session_state.current_block = 1
st.session_state.block_2_index = 0
st.session_state.responses = []
# ===================================================================
# Helper to advance to next sample and clean up keys
# ===================================================================
def _advance_sample(block_num: int, sample_id: str) -> None:
"""Mark sample complete and advance the index for the given block."""
completed = set(st.session_state.get("completed_samples", set()))
completed.add((f"block_{block_num}", sample_id))
st.session_state.completed_samples = completed
prefix = f"b{block_num}"
index_key = f"block_{block_num}_index"
st.session_state[index_key] = st.session_state.get(index_key, 0) + 1
# Clean up transient keys for this sample
for suffix in ["_unlocked", "_start"]:
key = f"{prefix}_{sample_id}{suffix}"
st.session_state.pop(key, None)
# ===================================================================
# Page renderers
# ===================================================================
def render_intro_page() -> None:
render_sidebar_image()
st.title("Welcome to the Model Evaluation Study")
intro_html = (
"<div style='font-size:1.15rem; line-height:1.8;'>"
+ INTRO_DESCRIPTION.strip().replace("\n\n", "<br><br>").replace("\n", "<br>")
+ "</div>"
)
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_participant_gate(
block_1_samples: List[Dict],
block_2_samples: List[Dict],
) -> None:
st.sidebar.markdown(
"<div style='font-size:1.3rem; font-weight:600;'>Model Evaluation Study</div>",
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():
completed = completed_samples_from_responses(participant_name)
if completed:
total = len(block_1_samples) + len(block_2_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
st.session_state.completed_samples = completed_samples_from_responses(
participant_name_clean
)
rerun_app()
def render_instruction_page(
block_1_samples: List[Dict],
block_2_samples: List[Dict],
) -> None:
render_sidebar_image()
st.title("Study Instructions")
st.markdown(
INSTRUCTIONS_PAGE_TEXT.replace("\n\n", "<br><br>").replace("\n", "<br>"),
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_participant_session(participant_id, block_1_samples, block_2_samples)
st.session_state.instructions_page_complete = True
rerun_app()
# ===================================================================
# Block renderers
# ===================================================================
def render_block_1_sample(block_1_samples: List[Dict]) -> None:
order = st.session_state.block_1_order
idx = st.session_state.block_1_index
if idx >= len(order):
st.session_state.block_1_complete = True
rerun_app()
return
sample_id = order[idx]
sample = next(s for s in block_1_samples if s["sample_id"] == sample_id)
audio_dir = get_block_audio_dir(1)
st.markdown(
f"### Block 1: Instruction Following &nbsp; "
f"(Sample {idx + 1} of {len(order)})"
)
# Show instruction
st.info(f'**Instruction given to the model:** "{sample["instruction"]}"')
# Audio playback – two columns
col1, col2 = st.columns(2)
with col1:
st.markdown("**Input Mixture (before processing):**")
st.audio(str(audio_dir / sample["mixture_file"]))
with col2:
st.markdown("**Model Output (after processing):**")
st.audio(str(audio_dir / sample["output_file"]))
# "I finished listening" gate
unlock_key = f"b1_{sample_id}_unlocked"
if not st.session_state.get(unlock_key, False):
if st.button("I finished listening", key=f"unlock_b1_{sample_id}"):
st.session_state[unlock_key] = True
st.session_state[f"b1_{sample_id}_start"] = time.time()
rerun_app()
st.info("Questions will appear after you confirm listening.")
return
elif f"b1_{sample_id}_start" not in st.session_state:
st.session_state[f"b1_{sample_id}_start"] = time.time()
# Questions form
with st.form(key=f"b1_form_{sample_id}"):
st.markdown("#### Question 1: Did the model follow the instruction?")
instruction_followed = st.radio(
"Did the model follow the instruction?",
options=["Yes", "No"],
index=None,
horizontal=True,
key=f"b1_q1_{sample_id}",
)
st.markdown("#### Question 2: How well did the model follow the instruction?")
instruction_mos = st.select_slider(
"Rate from 1 (Very Poor) to 5 (Excellent)",
options=MOS_SCALE,
format_func=lambda v: MOS_LABELS[v],
key=f"b1_q2_{sample_id}",
)
st.markdown("#### Question 3: Rate the quality of the extracted audio")
quality_mos = st.select_slider(
"Rate from 1 (Very Poor) to 5 (Excellent)",
options=MOS_SCALE,
format_func=lambda v: MOS_LABELS[v],
key=f"b1_q3_{sample_id}",
)
st.markdown("#### Question 4: Were the spatial cues preserved in the output?")
spatial_mos = st.select_slider(
"Rate from 1 (Very Poor) to 5 (Excellent)",
options=MOS_SCALE,
format_func=lambda v: MOS_LABELS[v],
key=f"b1_q4_{sample_id}",
)
submit = st.form_submit_button("Submit and continue")
if submit:
errors = []
if instruction_followed is None:
errors.append("Please answer whether the model followed the instruction.")
if instruction_mos is None:
errors.append("Please rate how well the model followed the instruction.")
if quality_mos is None:
errors.append("Please rate the extraction quality.")
if spatial_mos is None:
errors.append("Please rate the spatial preservation.")
if errors:
for e in errors:
st.warning(e)
else:
record = build_response_record(
sample,
block="block_1",
audio_dir=audio_dir,
instruction_followed=instruction_followed,
instruction_following_mos=instruction_mos,
extraction_quality_mos=quality_mos,
spatial_preservation_mos=spatial_mos,
start_time_key=f"b1_{sample_id}_start",
)
append_response(record, st.session_state.participant_id)
_advance_sample(1, sample_id)
# Clean up form keys
for suffix in [f"b1_q1_{sample_id}", f"b1_q2_{sample_id}", f"b1_q3_{sample_id}", f"b1_q4_{sample_id}"]:
st.session_state.pop(suffix, None)
rerun_app()
def render_block_transition() -> None:
st.title("Block 1 Complete!")
st.success("You have completed all samples in Block 1. Thank you!")
st.markdown("---")
st.markdown("### Block 2: Contextual Evaluation")
st.markdown(BLOCK_2_TRANSITION_TEXT)
if st.button("Continue to Block 2"):
st.session_state.block_2_instructions_shown = True
st.session_state.current_block = 2
rerun_app()
def render_block_2_sample(block_2_samples: List[Dict]) -> None:
order = st.session_state.block_2_order
idx = st.session_state.block_2_index
if idx >= len(order):
st.success(
"Thank you! You have completed all samples in both blocks. "
"You may close this window."
)
return
sample_id = order[idx]
sample = next(s for s in block_2_samples if s["sample_id"] == sample_id)
audio_dir = get_block_audio_dir(2)
st.markdown(
f"### Block 2: Contextual Evaluation &nbsp; "
f"(Sample {idx + 1} of {len(order)})"
)
scene_name = sample.get("scene_name", "this environment")
st.info(
f"Imagine you are at **{scene_name}** wearing noise-cancelling headphones. "
"Your headphone heard the environment and produced the output below."
)
# Audio playback – two columns
col1, col2 = st.columns(2)
with col1:
st.markdown("**What your headphone heard (input mixture):**")
st.audio(str(audio_dir / sample["mixture_file"]))
with col2:
st.markdown("**What your headphone produced (output):**")
st.audio(str(audio_dir / sample["output_file"]))
# "I finished listening" gate
unlock_key = f"b2_{sample_id}_unlocked"
if not st.session_state.get(unlock_key, False):
if st.button("I finished listening", key=f"unlock_b2_{sample_id}"):
st.session_state[unlock_key] = True
st.session_state[f"b2_{sample_id}_start"] = time.time()
rerun_app()
st.info("Questions will appear after you confirm listening.")
return
elif f"b2_{sample_id}_start" not in st.session_state:
st.session_state[f"b2_{sample_id}_start"] = time.time()
# Questions form
with st.form(key=f"b2_form_{sample_id}"):
st.markdown("#### Question 1: Did the headphone do the right thing?")
contextual_correct = st.radio(
"Given the input environment, did the headphone react appropriately?",
options=["Yes", "No"],
index=None,
horizontal=True,
key=f"b2_q1_{sample_id}",
)
st.markdown("#### Question 2: Rate the quality / purity of the extracted audio")
quality_mos = st.select_slider(
"Rate from 1 (Very Poor) to 5 (Excellent)",
options=MOS_SCALE,
format_func=lambda v: MOS_LABELS[v],
key=f"b2_q2_{sample_id}",
)
submit = st.form_submit_button("Submit and continue")
if submit:
errors = []
if contextual_correct is None:
errors.append("Please answer whether the headphone reacted appropriately.")
if quality_mos is None:
errors.append("Please rate the extraction quality.")
if errors:
for e in errors:
st.warning(e)
else:
record = build_response_record(
sample,
block="block_2",
audio_dir=audio_dir,
extraction_quality_mos=quality_mos,
contextual_correct=contextual_correct,
start_time_key=f"b2_{sample_id}_start",
)
append_response(record, st.session_state.participant_id)
_advance_sample(2, sample_id)
for suffix in [f"b2_q1_{sample_id}", f"b2_q2_{sample_id}"]:
st.session_state.pop(suffix, None)
rerun_app()
# ===================================================================
# Sidebar progress
# ===================================================================
def render_sidebar_progress() -> None:
pid = st.session_state.participant_id
st.sidebar.markdown(f"**Participant:** {pid}")
completed = st.session_state.get("completed_samples", set())
b1_total = len(st.session_state.block_1_order)
b2_total = len(st.session_state.block_2_order)
b1_done = sum(1 for b, _ in completed if b == "block_1")
b2_done = sum(1 for b, _ in completed if b == "block_2")
total = b1_total + b2_total
done = b1_done + b2_done
if total > 0:
st.sidebar.progress(done / total)
st.sidebar.markdown(f"Overall: **{done} / {total}**")
st.sidebar.markdown(f"Block 1: {b1_done} / {b1_total}")
st.sidebar.markdown(f"Block 2: {b2_done} / {b2_total}")
current = st.session_state.current_block
st.sidebar.markdown(f"**Currently in:** Block {current}")
st.sidebar.markdown("---")
st.sidebar.markdown("**Instructions (for reference)**")
st.sidebar.markdown(SIDEBAR_INSTRUCTIONS_SHORT)
# ===================================================================
# Main
# ===================================================================
def main() -> None:
st.set_page_config(page_title="Model Subjective Evaluation", layout="centered")
# Load metadata
block_1_samples = load_block_metadata(1)
block_2_samples = load_block_metadata(2)
# Validate audio files exist
block_1_samples = validate_audio_files(block_1_samples, BLOCK_1_AUDIO_DIR)
block_2_samples = validate_audio_files(block_2_samples, BLOCK_2_AUDIO_DIR)
if not block_1_samples and not block_2_samples:
st.error(
"No valid audio samples found in either block. "
"Please add audio files to block_1_audio/ and block_2_audio/."
)
st.stop()
init_session_state()
# Page flow gates
if not st.session_state.get("participant_profile"):
render_participant_gate(block_1_samples, block_2_samples)
return
if not st.session_state.get("intro_page_complete", False):
render_intro_page()
return
if not st.session_state.get("instructions_page_complete", False):
render_instruction_page(block_1_samples, block_2_samples)
return
if not st.session_state.participant_initialized:
st.warning("Initializing session. Please wait...")
return
# Sidebar
render_sidebar_progress()
# Block routing
if st.session_state.current_block == 1:
if st.session_state.block_1_complete:
if not st.session_state.block_2_instructions_shown:
render_block_transition()
else:
st.session_state.current_block = 2
rerun_app()
else:
render_block_1_sample(block_1_samples)
else:
render_block_2_sample(block_2_samples)
if __name__ == "__main__":
main()