carankt's picture
Verification: upload code and scripts only
c22b544 verified
Raw
History Blame Contribute Delete
7.71 kB
#!/usr/bin/env python3
"""
Streamlit app for Block 2 – Contextual Evaluation.
Participants hear an audio mixture + model output without seeing the instruction.
They imagine wearing noise-cancelling headphones and judge whether the headphone
behaviour was appropriate, plus rate extraction quality.
Run:
streamlit run app_block2.py
"""
from __future__ import annotations
import time
from typing import Dict, List
import streamlit as st
from shared import (
BLOCK_2_AUDIO_DIR,
MOS_LABELS,
MOS_SCALE,
advance_sample,
append_response,
build_response_record,
get_block_audio_dir,
init_session_state_single_block,
load_block_metadata,
render_intro_page,
render_instruction_page,
render_participant_gate,
render_sidebar_progress,
rerun_app,
validate_audio_files,
)
BLOCK_NUM = 2
# ---------------------------------------------------------------------------
# Text content
# ---------------------------------------------------------------------------
INTRO_DESCRIPTION = (
"In this study, you'll use headphones to evaluate how a model "
"processes audio scenes.\n\n"
"**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_TEXT = (
"Each sample will guide you through these steps:\n\n"
"**Step 1: Listen** – Press Play to hear both the original audio mixture "
"(what the headphone heard) and the model's output (what the headphone produced). "
"Listen to each clip at least once.\n\n"
"**Step 2: Answer Questions** – Rate the model's performance using the "
"questions provided.\n\n"
"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"
"There are two 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)\n\n"
"The MOS scale is:\n"
"1 – Very Poor | 2 – Poor | 3 – Fair | 4 – Good | 5 – Excellent\n\n"
"Click **I understand and I'm ready to begin** when you're ready."
)
# ===================================================================
# Block 2 sample renderer
# ===================================================================
def render_block_2_sample(samples: List[Dict]) -> None:
order = st.session_state.sample_order
idx = st.session_state.sample_index
if idx >= len(order):
st.session_state.block_complete = True
st.success(
"Thank you! You have completed all samples. "
"You may close this window."
)
return
sample_id = order[idx]
sample = next(s for s in samples if s["sample_id"] == sample_id)
audio_dir = get_block_audio_dir(2)
st.markdown(
f"### Contextual Evaluation   "
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, BLOCK_NUM)
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()
# ===================================================================
# Main
# ===================================================================
def main() -> None:
st.set_page_config(
page_title="Block 2: Contextual Evaluation",
layout="centered",
)
samples = load_block_metadata(BLOCK_NUM)
samples = validate_audio_files(samples, BLOCK_2_AUDIO_DIR)
if not samples:
st.error(
"No valid audio samples found for Block 2. "
"Please add audio files to block_2_audio/."
)
st.stop()
init_session_state_single_block()
# Page flow
if not st.session_state.get("participant_profile"):
render_participant_gate(BLOCK_NUM, samples, study_title="Block 2: Contextual Evaluation")
return
if not st.session_state.get("intro_page_complete", False):
render_intro_page(INTRO_DESCRIPTION)
return
if not st.session_state.get("instructions_page_complete", False):
render_instruction_page(BLOCK_NUM, samples, INSTRUCTIONS_TEXT)
return
if not st.session_state.participant_initialized:
st.warning("Initializing session. Please wait...")
return
render_sidebar_progress(BLOCK_NUM)
render_block_2_sample(samples)
if __name__ == "__main__":
main()