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12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
"""
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"<div style='font-size:1.3rem; font-weight:600;'>{study_title}</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():
        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 = (
        "<div style='font-size:1.15rem; line-height:1.8;'>"
        + 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_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", "<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_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)