Download survey_apps/main_study/src/components/TrialTaskText.js from sciminds/same-words-different-judgements: direct link, hf CLI and curl.
- Browser
- Download file 16.8 kB
-
https://huggingface.co/datasets/sciminds/same-words-different-judgements/resolve/main/survey_apps/main_study/src/components/TrialTaskText.js
- Command line
-
hf download hf://datasets/sciminds/same-words-different-judgements/survey_apps/main_study/src/components/TrialTaskText.js
-
curl -L -o TrialTaskText.js https://huggingface.co/datasets/sciminds/same-words-different-judgements/resolve/main/survey_apps/main_study/src/components/TrialTaskText.js
16.8 kB
| import { useState, useEffect } from "react"; | |
| import { db, auth } from "../firebase"; | |
| import { TEXT_COMPLETION_URL } from "../config"; | |
| import { | |
| doc, | |
| setDoc | |
| } from "firebase/firestore"; | |
| function TrialTaskText({ trialIndex, totalTrials, trialId, onNext, onExitEarly, sessionId, participantNumber }) { | |
| const [trialData, setTrialData] = useState(null); | |
| const [order, setOrder] = useState([1, 2]); | |
| const [ratings, setRatings] = useState({ r1: null, r2: null }); | |
| const [overallPreference, setOverallPreference] = useState(null); // 'A', 'Tie', or 'B' | |
| const [overallPreferenceChanges, setOverallPreferenceChanges] = useState([]); | |
| const [startTime, setStartTime] = useState(null); | |
| const [timestamps, setTimestamps] = useState({ r1: null, r2: null }); | |
| const [ratingChanges, setRatingChanges] = useState({ r1: [], r2: [] }); | |
| const [justification, setJustification] = useState(""); | |
| const [isSubmitting, setIsSubmitting] = useState(false); | |
| const isAttentionCheck = trialIndex === 0; | |
| 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", | |
| text_resp_1: "Of course! Who is the recipient and what would you like to convey in the message?", | |
| text_resp_2: "that doesn't sound like a bot. Here's a sample I tried:\n\nSup, it's [Name]. How are you? This is [name] speaking. I am calling to inquire about [insert product or service here]\n\nWhere am I going wrong?", | |
| prev_hist: "", | |
| conv_id: "attention", | |
| turn_no: "0", | |
| synth_text_1_rating: 85, | |
| synth_text_2_rating: 15, | |
| 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 timestamps for new trial | |
| setRatings({ r1: null, r2: null }); | |
| setTimestamps({ r1: null, r2: null }); | |
| setRatingChanges({ r1: [], r2: [] }); | |
| setOverallPreference(null); | |
| setOverallPreferenceChanges([]); | |
| setJustification(""); | |
| setIsSubmitting(false); | |
| // Set start time | |
| setStartTime(Date.now()); | |
| } catch (error) { | |
| console.error("Failed to load trial data:", error); | |
| } | |
| }; | |
| loadTrial(); | |
| }, [trialId, isAttentionCheck, participantNumber]); | |
| const handleSliderChange = (responseNum, value) => { | |
| setRatings((prev) => ({ ...prev, [`r${responseNum}`]: value })); | |
| }; | |
| const handleSliderRelease = (responseNum, value) => { | |
| setTimestamps((prev) => ({ | |
| ...prev, | |
| [`r${responseNum}`]: Date.now() | |
| })); | |
| // Determine the other rating's value | |
| const otherResponseNum = responseNum === 1 ? 2 : 1; | |
| const otherRatingValue = ratings[`r${otherResponseNum}`]; | |
| setRatingChanges((prev) => ({ | |
| ...prev, | |
| [`r${responseNum}`]: [ | |
| ...prev[`r${responseNum}`], | |
| { | |
| value, | |
| timestamp: new Date().toISOString(), | |
| otherRatingValue | |
| } | |
| ] | |
| })); | |
| }; | |
| const calculatePreferenceChanges = () => { | |
| // 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)); | |
| // Count preference changes | |
| let preferenceChanges = 0; | |
| let lastPreference = null; // 'r1', 'r2', or 'tie' | |
| timeline.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; | |
| if (ratings.r1 === null || ratings.r2 === null || overallPreference === null) return; | |
| setIsSubmitting(true); | |
| const endTime = Date.now(); | |
| const totalPreferenceChanges = calculatePreferenceChanges(); | |
| // Determine which response was shown first based on order | |
| const response1InOrder = order[0] === 1 ? trialData.text_resp_1 : trialData.text_resp_2; | |
| const response2InOrder = order[1] === 1 ? trialData.text_resp_1 : trialData.text_resp_2; | |
| 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, | |
| responseText1: response1InOrder, | |
| responseText2: response2InOrder, | |
| numCharacters1: response1InOrder.length, | |
| numCharacters2: response2InOrder.length, | |
| // AI Ratings (original order) | |
| aiRatingResponse1: trialData.synth_text_1_rating, | |
| aiRatingResponse2: trialData.synth_text_2_rating, | |
| prismRating1: trialData.text_1_score || null, | |
| prismRating2: trialData.text_2_score || null, | |
| // Participant Ratings | |
| participantRatingNum: trialIndex + 1, | |
| ratingResponse1: ratings.r1, | |
| ratingResponse2: ratings.r2, | |
| // Timing | |
| taskStartTime: new Date(startTime).toISOString(), | |
| taskEndTime: new Date(endTime).toISOString(), | |
| timestampRating1: timestamps.r1 ? new Date(timestamps.r1).toISOString() : null, | |
| timestampRating2: timestamps.r2 ? new Date(timestamps.r2).toISOString() : null, | |
| totalTaskDurationMs: endTime - startTime, | |
| // Order Info | |
| orderPresented: order, | |
| responseShownFirst: order[0], | |
| originalResponse1ShownAs: order[0] === 1 ? "A" : "B", | |
| originalResponse2ShownAs: order[0] === 2 ? "A" : "B", | |
| // Metadata | |
| modality: "text", | |
| submittedAt: new Date().toISOString(), | |
| isAttentionCheck: isAttentionCheck, | |
| ratingChangeHistory1: ratingChanges.r1, | |
| ratingChangeHistory2: ratingChanges.r2, | |
| // Preference Changes | |
| totalPreferenceChanges: totalPreferenceChanges, | |
| // Overall Preference | |
| overallPreference: overallPreference, | |
| overallPreferenceChangeHistory: overallPreferenceChanges, | |
| // Justification | |
| preferenceJustification: justification.trim() || null, | |
| }; | |
| const responseDocId = isAttentionCheck | |
| ? `${auth.currentUser.uid}_${sessionId}_text_attention_check` | |
| : `${auth.currentUser.uid}_${sessionId}_text_${trialId}`; | |
| console.log(auth.currentUser?.uid, responseDocId); | |
| await setDoc(doc(db, "responses", responseDocId), responseData); | |
| onNext(); // move to next trial | |
| }; | |
| if (!trialData) return <p>Loading 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> | |
| <div style={{ display: 'flex', marginBottom: '30px', gap: '20px' }}> | |
| <div style={{ flex: '1', padding: '20px', border: '1px solid #ddd', borderRadius: '8px' }}> | |
| <h4>Response A</h4> | |
| <p style={{ whiteSpace: 'pre-wrap' }}>{first === 1 ? trialData.text_resp_1 : trialData.text_resp_2}</p> | |
| </div> | |
| <div style={{ width: '300px', padding: '20px', display: 'flex', flexDirection: 'column', justifyContent: 'center' }}> | |
| <label style={{ marginBottom: '10px' }}>Response Rating:</label> | |
| <input | |
| type="range" | |
| min="1" | |
| max="100" | |
| value={ratings.r1 ?? 50} | |
| onChange={(e) => handleSliderChange(1, parseInt(e.target.value))} | |
| onMouseUp={(e) => handleSliderRelease(1, parseInt(e.target.value))} | |
| onTouchEnd={(e) => handleSliderRelease(1, 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 style={{ display: 'flex', marginBottom: '30px', gap: '20px' }}> | |
| <div style={{ flex: '1', padding: '20px', border: '1px solid #ddd', borderRadius: '8px' }}> | |
| <h4>Response B</h4> | |
| <p style={{ whiteSpace: 'pre-wrap' }}>{second === 1 ? trialData.text_resp_1 : trialData.text_resp_2}</p> | |
| </div> | |
| <div style={{ width: '300px', padding: '20px', display: 'flex', flexDirection: 'column', justifyContent: 'center' }}> | |
| <label style={{ marginBottom: '10px' }}>Response Rating:</label> | |
| <input | |
| type="range" | |
| min="1" | |
| max="100" | |
| value={ratings.r2 ?? 50} | |
| onChange={(e) => handleSliderChange(2, parseInt(e.target.value))} | |
| onMouseUp={(e) => handleSliderRelease(2, parseInt(e.target.value))} | |
| onTouchEnd={(e) => handleSliderRelease(2, 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 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 || ratings.r1 === null || ratings.r2 === null || overallPreference === null} | |
| style={{ | |
| padding: '10px 30px', | |
| fontSize: '16px', | |
| backgroundColor: !isSubmitting && ratings.r1 !== null && ratings.r2 !== null && overallPreference !== null ? '#007bff' : '#ccc', | |
| color: 'white', | |
| border: 'none', | |
| borderRadius: '5px', | |
| cursor: !isSubmitting && ratings.r1 !== null && ratings.r2 !== null && overallPreference !== null ? '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 (TEXT_COMPLETION_URL) window.location.href = TEXT_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> | |
| </form> | |
| ); | |
| } | |
| export default TrialTaskText; |