Download survey_apps/main_study/src/components/TrialTaskAudio.js from sciminds/same-words-different-judgements: direct link, hf CLI and curl.
- Browser
- Download file 37.7 kB
-
https://huggingface.co/datasets/sciminds/same-words-different-judgements/resolve/main/survey_apps/main_study/src/components/TrialTaskAudio.js
- Command line
-
hf download hf://datasets/sciminds/same-words-different-judgements/survey_apps/main_study/src/components/TrialTaskAudio.js
-
curl -L -o TrialTaskAudio.js https://huggingface.co/datasets/sciminds/same-words-different-judgements/resolve/main/survey_apps/main_study/src/components/TrialTaskAudio.js
37.7 kB
import { useEffect, useRef, useState } from "react";
import { db, auth } from "../firebase";
import { AUDIO_COMPLETION_URL } from "../config";
import {
doc,
setDoc
} from "firebase/firestore";
function TrialTaskAudio({ trialIndex, totalTrials, trialId, onNext, onExitEarly, sessionId, participantNumber }) {
const DEV_MODE = false; // Set to false for production
const [trialData, setTrialData] = useState(null);
const [order, setOrder] = useState([1, 2]);
const [ratings, setRatings] = useState({ r1: null, r2: null });
const [quality, setQuality] = useState({ q1: null, q2: null });
const [timestamps, setTimestamps] = useState({});
const [plays, setPlays] = useState({ a1: 0, a2: 0 });
const [listenTimes, setListenTimes] = useState({ a1: [], a2: [] });
const [relistenTimes, setRelistenTimes] = useState({ a1: [], a2: [] });
const [startTime, setStartTime] = useState(null);
const [isPlaying, setIsPlaying] = useState({ a1: false, a2: false });
const [currentTime, setCurrentTime] = useState({ a1: 0, a2: 0 });
const [duration, setDuration] = useState({ a1: 0, a2: 0 });
const [ratingChanges, setRatingChanges] = useState({ r1: [], r2: [] });
const [qualityChanges, setQualityChanges] = useState({ q1: [], q2: [] });
const [seekEvents, setSeekEvents] = useState({ a1: [], a2: [] });
const [skipEvents, setSkipEvents] = useState({ a1: [], a2: [] });
const [seekStartTime, setSeekStartTime] = useState({ a1: null, a2: null });
const [hasCompletedOnce, setHasCompletedOnce] = useState({ a1: false, a2: false });
const [completionTimestamps, setCompletionTimestamps] = useState({ a1: null, a2: null });
const [overallPreference, setOverallPreference] = useState(null); // 'A', 'Tie', or 'B'
const [overallPreferenceChanges, setOverallPreferenceChanges] = useState([]);
const [justification, setJustification] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const isAttentionCheck = trialIndex === 0;
const audioRefs = {
a1: useRef(null),
a2: useRef(null),
};
useEffect(() => {
// Scroll to top when new trial loads
window.scrollTo(0, 0);
const loadTrial = async () => {
try {
// If this is the first trial, use it as an attention check
if (isAttentionCheck) {
const attentionCheckData = {
id: "attention_check",
query: "Hello AI! I need some help writing a text message",
audio_file_1: "37_0_0.mp3",
audio_file_2: "37_0_1.mp3",
audio_1_len: 4.775, // You may want to update with actual lengths
audio_2_len: 12.775, // You may want to update with actual lengths
prev_hist: "",
conv_id: "attention",
turn_no: "0",
synth_text_1_rating: 85,
synth_text_2_rating: 15,
synth_audio_1_rating: 85,
synth_audio_2_rating: 15,
synth_audio_quality_1_rating: 95,
synth_audio_quality_2_rating: 95,
text_1_score: null,
text_2_score: null
};
setTrialData(attentionCheckData);
} else {
// Load survey data from JSON
const response = await fetch('/survey_data.json');
const allSamples = await response.json();
// Find the trial by ID
const trial = allSamples.find(sample => sample.id.toString() === trialId.toString());
if (trial) {
setTrialData(trial);
}
}
// Deterministic order assignment (ensures 5x5 split per modality)
// Every 2 participants get the same order, alternating between [1,2] and [2,1]
const orderFlip = Math.floor(participantNumber / 2) % 2;
setOrder(orderFlip === 0 ? [1, 2] : [2, 1]);
// Reset ratings and quality for new trial
setRatings({ r1: null, r2: null });
setQuality({ q1: null, q2: null });
setTimestamps({});
setPlays({ a1: 0, a2: 0 });
setIsPlaying({ a1: false, a2: false });
setCurrentTime({ a1: 0, a2: 0 });
setDuration({ a1: 0, a2: 0 });
// Reset rating/quality change history for new trial
setRatingChanges({ r1: [], r2: [] });
setQualityChanges({ q1: [], q2: [] });
// Reset seek/skip tracking for new trial
setSeekEvents({ a1: [], a2: [] });
setSkipEvents({ a1: [], a2: [] });
setSeekStartTime({ a1: null, a2: null });
setHasCompletedOnce({ a1: false, a2: false });
setCompletionTimestamps({ a1: null, a2: null });
setOverallPreference(null);
setOverallPreferenceChanges([]);
setJustification("");
setIsSubmitting(false);
setStartTime(Date.now());
} catch (error) {
console.error("Failed to load trial data:", error);
}
};
loadTrial();
}, [trialId, isAttentionCheck, participantNumber]);
const handlePlay = (clipNum) => {
const key = `a${clipNum}`;
const otherKey = clipNum === 1 ? 'a2' : 'a1';
const audio = audioRefs[key].current;
const otherAudio = audioRefs[otherKey].current;
if (!audio) return;
if (isPlaying[key]) {
audio.pause();
setIsPlaying(prev => ({ ...prev, [key]: false }));
} else {
// Pause the other audio if it's playing
if (otherAudio && isPlaying[otherKey]) {
otherAudio.pause();
setIsPlaying(prev => ({ ...prev, [otherKey]: false }));
}
const currentTimeStamp = Date.now();
// Track listen times
setListenTimes((prev) => ({
...prev,
[key]: [...prev[key], currentTimeStamp]
}));
// Track relisten times (if played more than once)
if (plays[key] > 0) {
setRelistenTimes((prev) => ({
...prev,
[key]: [...prev[key], currentTimeStamp]
}));
}
setPlays((prev) => ({ ...prev, [key]: prev[key] + 1 }));
audio.play();
setIsPlaying(prev => ({ ...prev, [key]: true }));
}
};
const handleReplay = (clipNum) => {
const key = `a${clipNum}`;
const otherKey = clipNum === 1 ? 'a2' : 'a1';
const audio = audioRefs[key].current;
const otherAudio = audioRefs[otherKey].current;
if (!audio) return;
// Pause the other audio if it's playing
if (otherAudio && isPlaying[otherKey]) {
otherAudio.pause();
setIsPlaying(prev => ({ ...prev, [otherKey]: false }));
}
audio.currentTime = 0;
const currentTimeStamp = Date.now();
setListenTimes((prev) => ({
...prev,
[key]: [...prev[key], currentTimeStamp]
}));
// Track relisten times (if played more than once)
if (plays[key] > 0) {
setRelistenTimes((prev) => ({
...prev,
[key]: [...prev[key], currentTimeStamp]
}));
}
setPlays((prev) => ({ ...prev, [key]: prev[key] + 1 }));
audio.play();
setIsPlaying(prev => ({ ...prev, [key]: true }));
};
const handleSeek = (clipNum, value) => {
const key = `a${clipNum}`;
const audio = audioRefs[key].current;
if (!audio || !hasCompletedOnce[key]) return;
const seekTime = (value / 100) * duration[key];
audio.currentTime = seekTime;
setCurrentTime(prev => ({ ...prev, [key]: seekTime }));
};
const handleSeekStart = (clipNum) => {
const key = `a${clipNum}`;
const audio = audioRefs[key].current;
if (!audio || !hasCompletedOnce[key]) return;
setSeekStartTime(prev => ({ ...prev, [key]: audio.currentTime }));
};
const handleSeekEnd = (clipNum, value) => {
const key = `a${clipNum}`;
const audio = audioRefs[key].current;
if (!audio || !hasCompletedOnce[key]) return;
const startTime = seekStartTime[key];
const endTime = (value / 100) * duration[key];
// Only track if there was a meaningful seek (more than 0.5 seconds)
if (startTime !== null && Math.abs(endTime - startTime) > 0.5) {
setSeekEvents(prev => ({
...prev,
[key]: [...prev[key], {
timestamp: new Date().toISOString(),
fromTime: startTime,
toTime: endTime,
seekDirection: endTime > startTime ? 'forward' : 'backward',
seekDistance: Math.abs(endTime - startTime)
}]
}));
}
// Reset seek start time
setSeekStartTime(prev => ({ ...prev, [key]: null }));
};
const handleSkipBack = (clipNum, seconds = 10) => {
const key = `a${clipNum}`;
const audio = audioRefs[key].current;
if (!audio) return;
const oldTime = audio.currentTime;
const newTime = Math.max(0, audio.currentTime - seconds);
// Track the skip event
setSkipEvents(prev => ({
...prev,
[key]: [...prev[key], {
timestamp: new Date().toISOString(),
fromTime: oldTime,
toTime: newTime,
skipType: 'backward',
skipAmount: seconds,
actualSkipped: oldTime - newTime
}]
}));
audio.currentTime = newTime;
};
const setupAudioListeners = (clipNum) => {
const key = `a${clipNum}`;
const audio = audioRefs[key].current;
if (!audio) return;
const updateTime = () => {
setCurrentTime(prev => ({ ...prev, [key]: audio.currentTime }));
};
const updateDuration = () => {
setDuration(prev => ({ ...prev, [key]: audio.duration }));
};
const handleEnded = () => {
setIsPlaying(prev => ({ ...prev, [key]: false }));
setHasCompletedOnce(prev => ({ ...prev, [key]: true }));
setCompletionTimestamps(prev => {
// Only record the first completion timestamp
if (prev[key] === null) {
return { ...prev, [key]: Date.now() };
}
return prev;
});
};
audio.addEventListener('timeupdate', updateTime);
audio.addEventListener('loadedmetadata', updateDuration);
audio.addEventListener('ended', handleEnded);
return () => {
audio.removeEventListener('timeupdate', updateTime);
audio.removeEventListener('loadedmetadata', updateDuration);
audio.removeEventListener('ended', handleEnded);
};
};
useEffect(() => {
if (trialData) {
const cleanup1 = setupAudioListeners(1);
const cleanup2 = setupAudioListeners(2);
return () => {
cleanup1?.();
cleanup2?.();
};
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [trialData]);
const handleRating = (key, value) => {
setRatings((prev) => ({ ...prev, [key]: value }));
};
const handleRatingRelease = (key, value) => {
setTimestamps((prev) => ({ ...prev, [`${key}Time`]: Date.now() }));
// Determine which audio this rating is for (r1 -> a1, r2 -> a2)
const audioKey = key === 'r1' ? 'a1' : 'a2';
const otherAudioKey = key === 'r1' ? 'a2' : 'a1';
const otherRatingKey = key === 'r1' ? 'r2' : 'r1';
const otherRatingValue = ratings[otherRatingKey];
setRatingChanges((prev) => ({
...prev,
[key]: [...prev[key], {
value,
timestamp: new Date().toISOString(),
otherRatingValue,
audioPlaying: isPlaying[audioKey],
audioCurrentTime: currentTime[audioKey],
audioDuration: duration[audioKey],
otherAudioPlaying: isPlaying[otherAudioKey],
otherAudioCurrentTime: currentTime[otherAudioKey],
otherAudioDuration: duration[otherAudioKey]
}]
}));
};
const handleQuality = (key, value) => {
setQuality((prev) => ({ ...prev, [key]: value }));
};
const handleQualityRelease = (key, value) => {
setTimestamps((prev) => ({ ...prev, [`${key}Time`]: Date.now() }));
// Determine which audio this quality rating is for (q1 -> a1, q2 -> a2)
const audioKey = key === 'q1' ? 'a1' : 'a2';
const otherAudioKey = key === 'q1' ? 'a2' : 'a1';
const otherQualityKey = key === 'q1' ? 'q2' : 'q1';
const otherQualityValue = quality[otherQualityKey];
setQualityChanges((prev) => ({
...prev,
[key]: [...prev[key], {
value,
timestamp: new Date().toISOString(),
otherQualityValue,
audioPlaying: isPlaying[audioKey],
audioCurrentTime: currentTime[audioKey],
audioDuration: duration[audioKey],
otherAudioPlaying: isPlaying[otherAudioKey],
otherAudioCurrentTime: currentTime[otherAudioKey],
otherAudioDuration: duration[otherAudioKey]
}]
}));
};
const calculatePreferenceChanges = (afterCompletionTime = null) => {
// Build a timeline of all rating changes
const timeline = [];
ratingChanges.r1.forEach(change => {
timeline.push({
timestamp: change.timestamp,
r1: change.value,
r2: change.otherRatingValue
});
});
ratingChanges.r2.forEach(change => {
timeline.push({
timestamp: change.timestamp,
r1: change.otherRatingValue,
r2: change.value
});
});
// Sort by timestamp
timeline.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
// Filter by completion time if specified
let filteredTimeline = timeline;
if (afterCompletionTime !== null) {
filteredTimeline = timeline.filter(entry =>
new Date(entry.timestamp).getTime() >= afterCompletionTime
);
}
// Count preference changes
let preferenceChanges = 0;
let lastPreference = null; // 'r1', 'r2', or 'tie'
filteredTimeline.forEach(entry => {
if (entry.r1 !== null && entry.r2 !== null) {
let currentPreference;
if (entry.r1 > entry.r2) {
currentPreference = 'r1';
} else if (entry.r2 > entry.r1) {
currentPreference = 'r2';
} else {
currentPreference = 'tie';
}
if (lastPreference !== null && lastPreference !== currentPreference) {
preferenceChanges++;
}
lastPreference = currentPreference;
}
});
return preferenceChanges;
};
const handleOverallPreferenceChange = (newPreference) => {
setOverallPreference(newPreference);
setOverallPreferenceChanges((prev) => [
...prev,
{
value: newPreference,
timestamp: new Date().toISOString(),
previousValue: overallPreference
}
]);
};
const handleSubmit = async (e) => {
e.preventDefault();
// Prevent double submission
if (isSubmitting) return;
// Validate all requirements are met
if (!DEV_MODE) {
if (
ratings.r1 === null ||
ratings.r2 === null ||
quality.q1 === null ||
quality.q2 === null ||
overallPreference === null ||
!hasCompletedOnce.a1 ||
!hasCompletedOnce.a2
) {
return;
}
}
setIsSubmitting(true);
const endTime = Date.now();
// Calculate when both audios were fully listened to
const bothAudiosCompletedTime = completionTimestamps.a1 && completionTimestamps.a2
? Math.max(completionTimestamps.a1, completionTimestamps.a2)
: null;
// Calculate preference changes
const totalPreferenceChanges = calculatePreferenceChanges();
const preferenceChangesAfterCompletion = bothAudiosCompletedTime
? calculatePreferenceChanges(bothAudiosCompletedTime)
: null;
// Calculate time between both audios completed and trial end
const timeAfterBothCompleted = bothAudiosCompletedTime
? endTime - bothAudiosCompletedTime
: null;
const first = order[0];
const second = order[1];
// Determine which audio was shown first based on order
const audio1InOrder = first === 1 ? trialData.audio_file_1 : trialData.audio_file_2;
const audio2InOrder = second === 1 ? trialData.audio_file_1 : trialData.audio_file_2;
const length1InOrder = first === 1 ? trialData.audio_1_len : trialData.audio_2_len;
const length2InOrder = second === 1 ? trialData.audio_1_len : trialData.audio_2_len;
const responseData = {
// Participant and Trial Info
participantId: auth.currentUser.uid,
promptId: `${trialData.conv_id}_${trialData.turn_no}`,
trialNumber: trialIndex, // Now 0 for attention check, 1-20 for real trials
trialId: isAttentionCheck ? "attention_check" : trialId,
// Content
conversationHistory: trialData.prev_hist || "",
query: trialData.query,
audioClip1: audio1InOrder,
audioClip2: audio2InOrder,
audioLength1: length1InOrder,
audioLength2: length2InOrder,
// PRISM Ratings
prismRating1: trialData.text_1_score,
prismRating2: trialData.text_2_score,
// AI Ratings (original order)
aiRatingResponse1: trialData.synth_text_1_rating,
aiRatingResponse2: trialData.synth_text_2_rating,
aiAudioRatingResponse1: trialData.synth_audio_1_rating,
aiAudioRatingResponse2: trialData.synth_audio_2_rating,
aiQualityRatingResponse1: trialData.synth_audio_quality_1_rating,
aiQualityRatingResponse2: trialData.synth_audio_quality_2_rating,
// Participant Ratings
participantRatingNum: trialIndex + 1,
ratingAudio1: ratings.r1,
ratingAudio2: ratings.r2,
qualityRatingAudio1: quality.q1,
qualityRatingAudio2: quality.q2,
// NEW: Rating & Quality Change History
ratingChangeHistoryAudio1: ratingChanges.r1,
ratingChangeHistoryAudio2: ratingChanges.r2,
qualityChangeHistoryAudio1: qualityChanges.q1,
qualityChangeHistoryAudio2: qualityChanges.q2,
// Timing
taskStartTime: new Date(startTime).toISOString(),
taskEndTime: new Date(endTime).toISOString(),
timestampRatingAudio1: timestamps.r1Time ? new Date(timestamps.r1Time).toISOString() : null,
timestampRatingAudio2: timestamps.r2Time ? new Date(timestamps.r2Time).toISOString() : null,
timestampQualityRating1: timestamps.q1Time ? new Date(timestamps.q1Time).toISOString() : null,
timestampQualityRating2: timestamps.q2Time ? new Date(timestamps.q2Time).toISOString() : null,
totalTaskDurationMs: endTime - startTime,
// Audio completion timestamps
audio1CompletionTimestamp: completionTimestamps.a1 ? new Date(completionTimestamps.a1).toISOString() : null,
audio2CompletionTimestamp: completionTimestamps.a2 ? new Date(completionTimestamps.a2).toISOString() : null,
bothAudiosCompletedTimestamp: bothAudiosCompletedTime ? new Date(bothAudiosCompletedTime).toISOString() : null,
timeAfterBothCompletedMs: timeAfterBothCompleted,
// Order Info
orderPresented: order,
audioShownFirst: order[0],
originalAudio1ShownAs: order[0] === 1 ? "A" : "B",
originalAudio2ShownAs: order[0] === 2 ? "A" : "B",
// Listening Data
timesRelistenedAudio1: plays.a1 > 0 ? plays.a1 - 1 : 0,
timesRelistenedAudio2: plays.a2 > 0 ? plays.a2 - 1 : 0,
listeningTimesAudio1: listenTimes.a1.map(t => new Date(t).toISOString()),
listeningTimesAudio2: listenTimes.a2.map(t => new Date(t).toISOString()),
relistenTimesAudio1: relistenTimes.a1.map(t => new Date(t).toISOString()),
relistenTimesAudio2: relistenTimes.a2.map(t => new Date(t).toISOString()),
// Seek/Skip Data
seekEventsAudio1: seekEvents.a1,
seekEventsAudio2: seekEvents.a2,
skipEventsAudio1: skipEvents.a1,
skipEventsAudio2: skipEvents.a2,
totalSeeksAudio1: seekEvents.a1.length,
totalSeeksAudio2: seekEvents.a2.length,
totalSkipsAudio1: skipEvents.a1.length,
totalSkipsAudio2: skipEvents.a2.length,
// Metadata
modality: "audio",
submittedAt: new Date().toISOString(),
isAttentionCheck: isAttentionCheck,
// Preference Changes
totalPreferenceChanges: totalPreferenceChanges,
preferenceChangesAfterCompletion: preferenceChangesAfterCompletion,
// Overall Preference
overallPreference: overallPreference,
overallPreferenceChangeHistory: overallPreferenceChanges,
// Justification
preferenceJustification: justification.trim() || null,
};
const docId = isAttentionCheck
? `${auth.currentUser.uid}_${sessionId}_audio_attention_check`
: `${auth.currentUser.uid}_${sessionId}_audio_${trialId}`;
await setDoc(doc(db, "responses", docId), responseData);
onNext(); // Go to next trial
};
if (!trialData) return <p>Loading audio trial...</p>;
const [first, second] = order;
return (
<form onSubmit={handleSubmit} style={{ maxWidth: '1200px', margin: '0 auto', padding: '20px' }}>
<h3>Trial {trialIndex} of {totalTrials - 1}</h3>
{trialData.prev_hist && trialData.prev_hist.trim() && (
<div style={{ marginBottom: '30px', padding: '15px', backgroundColor: '#f5f5f5', borderRadius: '8px' }}>
<p style={{ margin: '0 0 15px 0', fontSize: '16px' }}><strong>Conversation History:</strong></p>
<div style={{ backgroundColor: '#fff', padding: '15px', borderRadius: '5px', border: '1px solid #ddd' }}>
{(() => {
const parts = trialData.prev_hist.split(/role: (user|model)\\n response: /).filter(part => part.trim());
const messages = [];
for (let i = 0; i < parts.length; i += 2) {
const role = parts[i];
const content = parts[i + 1];
if (role && content) {
messages.push({ role, content });
}
}
return messages.map((message, index) => (
<div key={index} style={{
margin: '15px 0',
padding: '10px',
borderRadius: '5px',
backgroundColor: message.role === 'user' ? '#f0f9ff' : '#fef2f2',
border: message.role === 'user' ? '1px solid #bfdbfe' : '1px solid #fecaca'
}}>
<div style={{
fontWeight: 'bold',
color: message.role === 'user' ? '#1e40af' : '#dc2626',
marginBottom: '5px'
}}>
{message.role === 'user' ? 'User' : 'Assistant'}:
</div>
<div style={{ whiteSpace: 'pre-wrap', lineHeight: '1.5' }}>
{message.content}
</div>
</div>
));
})()}
</div>
</div>
)}
<div style={{ marginBottom: '30px', padding: '15px', backgroundColor: '#f0f9ff', borderRadius: '8px', border: '1px solid #bfdbfe' }}>
<p style={{ margin: '0', fontSize: '16px' }}>
<strong style={{ color: '#1e40af' }}>User:</strong> <span style={{ color: '#000000' }}>{trialData.query}</span>
</p>
</div>
{/* Audio A */}
<div style={{ display: 'flex', marginBottom: '30px', gap: '20px' }}>
<div style={{ flex: '1', padding: '20px', border: '1px solid #ddd', borderRadius: '8px' }}>
<h4>Audio A</h4>
<audio
ref={audioRefs.a1}
src={`/audio/${first === 1 ? trialData.audio_file_1 : trialData.audio_file_2}`}
preload="metadata"
/>
<div style={{ marginBottom: '15px' }}>
<div style={{ display: 'flex', gap: '10px', marginBottom: '10px' }}>
<button
type="button"
onClick={() => handlePlay(1)}
style={{
padding: '8px 16px',
fontSize: '14px',
backgroundColor: isPlaying.a1 ? '#dc3545' : '#007bff',
color: 'white',
border: 'none',
borderRadius: '5px',
cursor: 'pointer',
minWidth: '80px'
}}
>
{isPlaying.a1 ? 'Pause' : 'Play'}
</button>
<button
type="button"
onClick={() => handleReplay(1)}
style={{
padding: '8px 16px',
fontSize: '14px',
backgroundColor: '#6c757d',
color: 'white',
border: 'none',
borderRadius: '5px',
cursor: 'pointer'
}}
>
Replay
</button>
<button
type="button"
onClick={() => handleSkipBack(1, 10)}
style={{
padding: '8px 16px',
fontSize: '14px',
backgroundColor: '#6c757d',
color: 'white',
border: 'none',
borderRadius: '5px',
cursor: 'pointer'
}}
>
-10s
</button>
</div>
<div style={{ marginBottom: '5px' }}>
<input
type="range"
min="0"
max="100"
value={duration.a1 ? (currentTime.a1 / duration.a1) * 100 : 0}
onChange={(e) => handleSeek(1, e.target.value)}
onMouseDown={() => handleSeekStart(1)}
onMouseUp={(e) => handleSeekEnd(1, e.target.value)}
onTouchStart={() => handleSeekStart(1)}
onTouchEnd={(e) => handleSeekEnd(1, e.target.value)}
disabled={!hasCompletedOnce.a1}
style={{ width: '100%', height: '6px', cursor: hasCompletedOnce.a1 ? 'pointer' : 'not-allowed', opacity: hasCompletedOnce.a1 ? 1 : 0.5 }}
/>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', color: '#666' }}>
<span>{Math.floor(currentTime.a1 / 60)}:{Math.floor(currentTime.a1 % 60).toString().padStart(2, '0')}</span>
<span>{Math.floor(duration.a1 / 60)}:{Math.floor(duration.a1 % 60).toString().padStart(2, '0')}</span>
</div>
</div>
</div>
<div style={{ width: '300px', padding: '20px', display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: '20px' }}>
<div>
<label style={{ marginBottom: '10px', display: 'block' }}>Response Rating:</label>
<input
type="range"
min="1"
max="100"
value={ratings.r1 ?? 50}
onChange={(e) => handleRating("r1", parseInt(e.target.value))}
onMouseUp={(e) => handleRatingRelease("r1", parseInt(e.target.value))}
onTouchEnd={(e) => handleRatingRelease("r1", parseInt(e.target.value))}
style={{ width: '100%', height: '30px', marginBottom: '5px' }}
/>
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', color: '#666' }}>
<span>Terrible</span>
<span>Perfect</span>
</div>
</div>
<div>
<label style={{ marginBottom: '10px', display: 'block' }}>Audio Quality Rating:</label>
<input
type="range"
min="1"
max="100"
value={quality.q1 ?? 50}
onChange={(e) => handleQuality("q1", parseInt(e.target.value))}
onMouseUp={(e) => handleQualityRelease("q1", parseInt(e.target.value))}
onTouchEnd={(e) => handleQualityRelease("q1", parseInt(e.target.value))}
style={{ width: '100%', height: '30px', marginBottom: '5px' }}
/>
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', color: '#666' }}>
<span>Terrible</span>
<span>Perfect</span>
</div>
</div>
</div>
</div>
{/* Audio B */}
<div style={{ display: 'flex', marginBottom: '30px', gap: '20px' }}>
<div style={{ flex: '1', padding: '20px', border: '1px solid #ddd', borderRadius: '8px' }}>
<h4>Audio B</h4>
<audio
ref={audioRefs.a2}
src={`/audio/${second === 1 ? trialData.audio_file_1 : trialData.audio_file_2}`}
preload="metadata"
/>
<div style={{ marginBottom: '15px' }}>
<div style={{ display: 'flex', gap: '10px', marginBottom: '10px' }}>
<button
type="button"
onClick={() => handlePlay(2)}
style={{
padding: '8px 16px',
fontSize: '14px',
backgroundColor: isPlaying.a2 ? '#dc3545' : '#007bff',
color: 'white',
border: 'none',
borderRadius: '5px',
cursor: 'pointer',
minWidth: '80px'
}}
>
{isPlaying.a2 ? 'Pause' : 'Play'}
</button>
<button
type="button"
onClick={() => handleReplay(2)}
style={{
padding: '8px 16px',
fontSize: '14px',
backgroundColor: '#6c757d',
color: 'white',
border: 'none',
borderRadius: '5px',
cursor: 'pointer'
}}
>
Replay
</button>
<button
type="button"
onClick={() => handleSkipBack(2, 10)}
style={{
padding: '8px 16px',
fontSize: '14px',
backgroundColor: '#6c757d',
color: 'white',
border: 'none',
borderRadius: '5px',
cursor: 'pointer'
}}
>
-10s
</button>
</div>
<div style={{ marginBottom: '5px' }}>
<input
type="range"
min="0"
max="100"
value={duration.a2 ? (currentTime.a2 / duration.a2) * 100 : 0}
onChange={(e) => handleSeek(2, e.target.value)}
onMouseDown={() => handleSeekStart(2)}
onMouseUp={(e) => handleSeekEnd(2, e.target.value)}
onTouchStart={() => handleSeekStart(2)}
onTouchEnd={(e) => handleSeekEnd(2, e.target.value)}
disabled={!hasCompletedOnce.a2}
style={{ width: '100%', height: '6px', cursor: hasCompletedOnce.a2 ? 'pointer' : 'not-allowed', opacity: hasCompletedOnce.a2 ? 1 : 0.5 }}
/>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', color: '#666' }}>
<span>{Math.floor(currentTime.a2 / 60)}:{Math.floor(currentTime.a2 % 60).toString().padStart(2, '0')}</span>
<span>{Math.floor(duration.a2 / 60)}:{Math.floor(duration.a2 % 60).toString().padStart(2, '0')}</span>
</div>
</div>
</div>
<div style={{ width: '300px', padding: '20px', display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: '20px' }}>
<div>
<label style={{ marginBottom: '10px', display: 'block' }}>Response Rating:</label>
<input
type="range"
min="1"
max="100"
value={ratings.r2 ?? 50}
onChange={(e) => handleRating("r2", parseInt(e.target.value))}
onMouseUp={(e) => handleRatingRelease("r2", parseInt(e.target.value))}
onTouchEnd={(e) => handleRatingRelease("r2", parseInt(e.target.value))}
style={{ width: '100%', height: '30px', marginBottom: '5px' }}
/>
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', color: '#666' }}>
<span>Terrible</span>
<span>Perfect</span>
</div>
</div>
<div>
<label style={{ marginBottom: '10px', display: 'block' }}>Audio Quality Rating:</label>
<input
type="range"
min="1"
max="100"
value={quality.q2 ?? 50}
onChange={(e) => handleQuality("q2", parseInt(e.target.value))}
onMouseUp={(e) => handleQualityRelease("q2", parseInt(e.target.value))}
onTouchEnd={(e) => handleQualityRelease("q2", parseInt(e.target.value))}
style={{ width: '100%', height: '30px', marginBottom: '5px' }}
/>
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', color: '#666' }}>
<span>Terrible</span>
<span>Perfect</span>
</div>
</div>
</div>
</div>
<div style={{ marginBottom: '30px' }}>
<label style={{ display: 'block', marginBottom: '10px', fontWeight: 'bold' }}>
Overall, which response do you prefer?
</label>
<div style={{ display: 'flex', gap: '15px', justifyContent: 'center' }}>
{['A', 'Tie', 'B'].map((option) => (
<button
key={option}
type="button"
onClick={() => handleOverallPreferenceChange(option)}
style={{
padding: '12px 30px',
fontSize: '16px',
backgroundColor: overallPreference === option ? '#007bff' : '#f0f0f0',
color: overallPreference === option ? 'white' : '#333',
border: overallPreference === option ? '2px solid #0056b3' : '2px solid #ddd',
borderRadius: '5px',
cursor: 'pointer',
fontWeight: overallPreference === option ? 'bold' : 'normal',
minWidth: '80px',
transition: 'all 0.2s ease'
}}
>
{option}
</button>
))}
</div>
</div>
<div style={{ marginBottom: '30px' }}>
<label style={{ display: 'block', marginBottom: '10px', fontWeight: 'bold' }}>
Why did you prefer one response over the other? (Optional)
</label>
<textarea
value={justification}
onChange={(e) => setJustification(e.target.value)}
rows={4}
style={{
width: '100%',
padding: '10px',
fontSize: '14px',
border: '1px solid #ddd',
borderRadius: '5px',
fontFamily: 'inherit',
resize: 'vertical'
}}
placeholder="Please share your reasoning..."
/>
</div>
<div style={{ display: 'flex', gap: '15px', alignItems: 'center' }}>
<button
type="submit"
disabled={
isSubmitting || (
!DEV_MODE && (
ratings.r1 === null ||
ratings.r2 === null ||
quality.q1 === null ||
quality.q2 === null ||
overallPreference === null ||
!hasCompletedOnce.a1 ||
!hasCompletedOnce.a2
))
}
style={{
padding: '10px 30px',
fontSize: '16px',
backgroundColor: (
!isSubmitting && (
DEV_MODE || (
ratings.r1 !== null &&
ratings.r2 !== null &&
quality.q1 !== null &&
quality.q2 !== null &&
overallPreference !== null &&
hasCompletedOnce.a1 &&
hasCompletedOnce.a2
))
) ? '#007bff' : '#ccc',
color: 'white',
border: 'none',
borderRadius: '5px',
cursor: (
!isSubmitting && (
DEV_MODE || (
ratings.r1 !== null &&
ratings.r2 !== null &&
quality.q1 !== null &&
quality.q2 !== null &&
overallPreference !== null &&
hasCompletedOnce.a1 &&
hasCompletedOnce.a2
))
) ? 'pointer' : 'not-allowed'
}}
>
{isSubmitting ? 'Submitting...' : 'Submit Ratings'}
</button>
<button
type="button"
onClick={() => {
if (window.confirm('Are you sure you want to exit the study early? Your progress will be saved but you will not complete the full study.')) {
if (AUDIO_COMPLETION_URL) window.location.href = AUDIO_COMPLETION_URL;
else if (typeof onExitEarly === 'function') onExitEarly();
}
}}
style={{
padding: '10px 20px',
fontSize: '14px',
backgroundColor: '#dc3545',
color: 'white',
border: 'none',
borderRadius: '5px',
cursor: 'pointer'
}}
>
Exit Study Early
</button>
</div>
{(!hasCompletedOnce.a1 || !hasCompletedOnce.a2) && (
<p style={{ color: '#dc3545', marginTop: '10px' }}>
Please listen to both audio clips in full and adjust the rating slider for all ratings before submitting.
</p>
)}
</form>
);
}
export default TrialTaskAudio;
import { useEffect, useRef, useState } from "react";
import { db, auth } from "../firebase";
import { AUDIO_COMPLETION_URL } from "../config";
import {
doc,
setDoc
} from "firebase/firestore";
function TrialTaskAudio({ trialIndex, totalTrials, trialId, onNext, onExitEarly, sessionId, participantNumber }) {
const DEV_MODE = false; // Set to false for production
const [trialData, setTrialData] = useState(null);
const [order, setOrder] = useState([1, 2]);
const [ratings, setRatings] = useState({ r1: null, r2: null });
const [quality, setQuality] = useState({ q1: null, q2: null });
const [timestamps, setTimestamps] = useState({});
const [plays, setPlays] = useState({ a1: 0, a2: 0 });
const [listenTimes, setListenTimes] = useState({ a1: [], a2: [] });
const [relistenTimes, setRelistenTimes] = useState({ a1: [], a2: [] });
const [startTime, setStartTime] = useState(null);
const [isPlaying, setIsPlaying] = useState({ a1: false, a2: false });
const [currentTime, setCurrentTime] = useState({ a1: 0, a2: 0 });
const [duration, setDuration] = useState({ a1: 0, a2: 0 });
const [ratingChanges, setRatingChanges] = useState({ r1: [], r2: [] });
const [qualityChanges, setQualityChanges] = useState({ q1: [], q2: [] });
const [seekEvents, setSeekEvents] = useState({ a1: [], a2: [] });
const [skipEvents, setSkipEvents] = useState({ a1: [], a2: [] });
const [seekStartTime, setSeekStartTime] = useState({ a1: null, a2: null });
const [hasCompletedOnce, setHasCompletedOnce] = useState({ a1: false, a2: false });
const [completionTimestamps, setCompletionTimestamps] = useState({ a1: null, a2: null });
const [overallPreference, setOverallPreference] = useState(null); // 'A', 'Tie', or 'B'
const [overallPreferenceChanges, setOverallPreferenceChanges] = useState([]);
const [justification, setJustification] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const isAttentionCheck = trialIndex === 0;
const audioRefs = {
a1: useRef(null),
a2: useRef(null),
};
useEffect(() => {
// Scroll to top when new trial loads
window.scrollTo(0, 0);
const loadTrial = async () => {
try {
// If this is the first trial, use it as an attention check
if (isAttentionCheck) {
const attentionCheckData = {
id: "attention_check",
query: "Hello AI! I need some help writing a text message",
audio_file_1: "37_0_0.mp3",
audio_file_2: "37_0_1.mp3",
audio_1_len: 4.775, // You may want to update with actual lengths
audio_2_len: 12.775, // You may want to update with actual lengths
prev_hist: "",
conv_id: "attention",
turn_no: "0",
synth_text_1_rating: 85,
synth_text_2_rating: 15,
synth_audio_1_rating: 85,
synth_audio_2_rating: 15,
synth_audio_quality_1_rating: 95,
synth_audio_quality_2_rating: 95,
text_1_score: null,
text_2_score: null
};
setTrialData(attentionCheckData);
} else {
// Load survey data from JSON
const response = await fetch('/survey_data.json');
const allSamples = await response.json();
// Find the trial by ID
const trial = allSamples.find(sample => sample.id.toString() === trialId.toString());
if (trial) {
setTrialData(trial);
}
}
// Deterministic order assignment (ensures 5x5 split per modality)
// Every 2 participants get the same order, alternating between [1,2] and [2,1]
const orderFlip = Math.floor(participantNumber / 2) % 2;
setOrder(orderFlip === 0 ? [1, 2] : [2, 1]);
// Reset ratings and quality for new trial
setRatings({ r1: null, r2: null });
setQuality({ q1: null, q2: null });
setTimestamps({});
setPlays({ a1: 0, a2: 0 });
setIsPlaying({ a1: false, a2: false });
setCurrentTime({ a1: 0, a2: 0 });
setDuration({ a1: 0, a2: 0 });
// Reset rating/quality change history for new trial
setRatingChanges({ r1: [], r2: [] });
setQualityChanges({ q1: [], q2: [] });
// Reset seek/skip tracking for new trial
setSeekEvents({ a1: [], a2: [] });