Spaces:
Running on Zero
Running on Zero
File size: 20,498 Bytes
3e6f84d | 1 2 3 4 5 6 7 8 9 10 11 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 | import React, { useEffect, useRef, useState } from 'react'
import { Icon } from './Icons.jsx'
import { api, postJson } from './api.js'
import { useDraft, initialDraft } from './useDraft.js'
import { useRecorder } from './useRecorder.js'
import { useInferenceJob } from './useInferenceJob.js'
const STEPS = ['Read', 'Review', 'Exercise', 'Finish']
const differenceLabels = { skipped: 'Possibly skipped', changed: 'Possibly changed', added: 'Possible extra word' }
export function Session({ passage, savedSession, onFinish, onLeave, pilot = false }) {
const recoveryStorage = sessionStorage
const [restored] = useState(() => initialDraft(savedSession, recoveryStorage))
const [step, setStep] = useState(savedSession.status === 'completed' ? 3 : restored.step)
const [assigned, setAssigned] = useState(savedSession.exercise || null)
const [finished, setFinished] = useState(savedSession.status === 'completed')
const [audioBusy, setAudioBusy] = useState(false)
const [audioError, setAudioError] = useState('')
const restoredAudio = useRef(null)
const [size, setSize] = useState(1)
const [text, setText] = useState(restored.transcript || '')
const [source, setSource] = useState(restored.source || 'manual')
const [reviewed, setReviewed] = useState(Boolean(restored.transcript_reviewed))
const [comparison, setComparison] = useState(null)
const [dismissed, setDismissed] = useState(Object.fromEntries((restored.dismissed || []).map(id => [id, true])))
const [compared, setCompared] = useState(Boolean(restored.compared) && (!restored.source?.startsWith('speech') || Boolean(restored.transcript_reviewed)))
const [choice, setChoice] = useState(savedSession.answer?.choice ?? null)
const [answer, setAnswer] = useState(savedSession.answer || null)
const [busy, setBusy] = useState('')
const [error, setError] = useState('')
const [speechInfo, setSpeechInfo] = useState(null)
const [confirmLeave, setConfirmLeave] = useState(false)
const recorder = useRecorder()
const inference = useInferenceJob(savedSession.id, !assigned && (savedSession.has_audio || Boolean(recorder.blob)))
const task = useRef(null)
const mounted = useRef(true)
const heading = useRef(null)
const draft = { step: Math.min(step, 2), transcript: text, source, compared, transcript_reviewed: reviewed, dismissed: Object.keys(dismissed).filter(id => dismissed[id]) }
const persistence = useDraft(savedSession, draft, !assigned && !finished, recoveryStorage)
const reported = useRef(savedSession.status === 'completed')
useEffect(() => {
mounted.current = true
function beforeUnload(event) { if (!reported.current) { event.preventDefault(); event.returnValue = '' } }
window.addEventListener('beforeunload', beforeUnload)
return () => { mounted.current = false; task.current?.abort(); window.removeEventListener('beforeunload', beforeUnload) }
}, [])
useEffect(() => { heading.current?.focus() }, [step])
useEffect(() => {
if (restored.compared && restored.transcript && (!restored.source?.startsWith('speech') || restored.transcript_reviewed)) {
const controller = new AbortController()
postJson('/compare', { passage_id: passage.id, transcript: restored.transcript, source: restored.source || 'manual', transcript_reviewed: Boolean(restored.transcript_reviewed) }, { signal: controller.signal }).then(value => { if (!controller.signal.aborted) setComparison(value) }).catch(failure => { if (!controller.signal.aborted) setError(failure.message) })
return () => controller.abort()
}
}, [])
useEffect(() => {
if (!savedSession.has_audio) return
const controller = new AbortController()
setAudioBusy(true)
api(`/sessions/${savedSession.id}/audio`, { raw: true, signal: controller.signal }).then(blob => {
if (!controller.signal.aborted) { restoredAudio.current = blob; recorder.chooseFile(blob) }
}).catch(failure => { if (!controller.signal.aborted) setAudioError(failure.message) }).finally(() => { if (!controller.signal.aborted) setAudioBusy(false) })
return () => controller.abort()
}, [])
async function saveRecording(blob, reset = false) {
setAudioBusy(true)
setAudioError('')
try {
if (reset) {
const cleared = { step: 0, transcript: '', source: 'manual', compared: false, transcript_reviewed: false, dismissed: [] }
setText(''); setSource('manual'); setReviewed(false); setCompared(false); setComparison(null); setDismissed({}); setSpeechInfo(null)
await persistence.flush(cleared)
} else await persistence.flush()
const saved = await api(`/sessions/${savedSession.id}/audio`, { method: 'PUT', body: blob, headers: { 'Content-Type': blob.type || 'application/octet-stream', 'If-Match': String(persistence.getRevision()) } })
persistence.adopt(saved)
inference.refresh()
} catch (failure) { setAudioError(failure.message); throw failure }
finally { if (mounted.current) setAudioBusy(false) }
}
useEffect(() => {
if (recorder.blob && recorder.blob !== restoredAudio.current) saveRecording(recorder.blob, true).catch(() => {})
}, [recorder.blob])
function continueToExercise(skipComparison = false) {
run('Saving your review...', async signal => {
const next = { ...draft, compared: skipComparison ? false : compared }
if (skipComparison) { setCompared(false); setComparison(null) }
await persistence.flush(next)
const saved = await api(`/sessions/${savedSession.id}/exercise`, { method: 'POST', signal })
if (!mounted.current) return
persistence.adopt(saved)
setAssigned(saved.exercise)
setStep(2)
})
}
async function run(label, action) {
if (task.current) return
const controller = new AbortController()
task.current = controller
setBusy(label)
setError('')
try {
await action(controller.signal)
} catch (failure) {
if (mounted.current) setError(failure.message)
} finally {
task.current = null
if (mounted.current) setBusy('')
}
}
function transcribe() {
run('Queueing transcription...', async () => {
await saveRecording(recorder.blob)
await inference.start()
})
}
function useTranscript() {
const result = inference.job?.result
if (!result) return
run('Saving transcript...', async () => {
const next = { step: 1, transcript: result.text, source: 'speech', transcript_reviewed: false, compared: false, dismissed: [] }
await persistence.flush(next)
if (!mounted.current) return
setText(result.text); setCompared(false); setSource('speech'); setReviewed(false)
setSpeechInfo(result); setComparison(null); setDismissed({}); setStep(1)
})
}
function compare() {
if (source.startsWith('speech') && !reviewed) return
run('Comparing words...', async signal => {
const result = await postJson('/compare', { passage_id: passage.id, transcript: text, source, transcript_reviewed: reviewed }, { signal })
if (!mounted.current) return
setComparison(result)
setCompared(true)
setDismissed({})
})
}
function checkAnswer() {
run('Checking your answer...', async signal => {
const result = await postJson(`/sessions/${savedSession.id}/answer`, { choice }, { signal })
if (mounted.current) setAnswer(result)
})
}
function finish() {
run('Saving your result...', async signal => {
const saved = await api(`/sessions/${savedSession.id}/finish`, { method: 'POST', signal })
if (!mounted.current) return
reported.current = true
persistence.adopt(saved)
setFinished(true)
onFinish(saved)
setStep(3)
})
}
function updateText(value) {
setReviewed(false)
setCompared(false)
setText(value)
setComparison(null)
setDismissed({})
if (source === 'speech') setSource('speech-edited')
}
const kept = comparison?.differences.filter(item => !dismissed[item.id]).length ?? 0
const exercise = assigned || passage.exercise
const blocked = Boolean(busy) || audioBusy || Boolean(persistence.conflict)
return <div className="session">
{persistence.conflict && <div className="error-message" role="alert"><p>A newer saved session exists. Your older unsaved browser draft is shown below. Copy any words you need before continuing with the saved session.</p><textarea aria-label="Older unsaved draft" readOnly value={persistence.conflict.transcript || ''} /><button className="secondary-button" onClick={persistence.useSaved}>Use saved session</button></div>}
<div className="save-status" role="status">{persistence.status}{audioBusy ? ' / Saving or loading audio...' : ''}</div>
{persistence.error && <div className="error-message" role="alert">{persistence.error}<button className="text-button" onClick={() => persistence.flush().catch(() => {})}>Retry save</button><button className="text-button" onClick={onLeave}>Back to passages; keep browser draft</button></div>}
{audioError && <div className="error-message" role="alert">{audioError}{recorder.blob && <button className="text-button" onClick={() => saveRecording(recorder.blob).catch(() => {})}>Retry saving audio</button>}</div>}
<div className="session-top"><ol className="session-steps" aria-label="Session steps">{STEPS.map((label, index) => <li key={label} aria-current={step === index ? 'step' : undefined} className={index <= step ? 'step-active' : ''}><span>{index + 1}</span>{label}</li>)}</ol>{step < 3 && <button className="text-button" onClick={() => setConfirmLeave(true)}>Leave session</button>}</div>
{confirmLeave && <div className="notice-box" role="alert"><p>Leave this session? Saved progress and audio can be resumed from Progress. Stop any active recording first.</p><div className="button-row"><button className="secondary-button" onClick={() => setConfirmLeave(false)}>Keep reading</button><button className="secondary-button" disabled={blocked || recorder.recording || recorder.pending} onClick={() => run('Saving...', async () => { if (!assigned) await persistence.flush(); onLeave() })}>Save and leave</button></div></div>}
{error && <p className="error-message" role="alert">{error}</p>}
{busy && <div className="notice-box" role="status"><p>{busy}</p>{busy.startsWith('Transcribing') && <><p>The first request also loads the model. Keep this tab open.</p><button className="text-button" onClick={() => task.current?.abort()}>Cancel request</button></>}</div>}
{!assigned && inference.job && <section className="notice-box" aria-label="Transcription job">
<strong>Transcription: {inference.job.state}</strong>
{['queued', 'running'].includes(inference.job.state) && <><p>Keep this Space tab open while waiting. Free GPU access has queues and daily quotas.</p><button className="text-button" onClick={() => inference.cancel().catch(() => {})}>Cancel transcription</button></>}
{inference.job.error && <p>{inference.job.error}</p>}
{inference.job.retryable && <button className="secondary-button" onClick={() => inference.retry().catch(() => {})}>Retry transcription</button>}
{inference.job.state === 'completed' && <><p>Your transcript is ready. Using it replaces the current transcript and requires another review.</p><button className="primary-button" disabled={blocked} onClick={useTranscript}>Use saved transcript</button></>}
{inference.error && <p role="alert">{inference.error}</p>}
</section>}
{!inference.job && inference.error && <p className="error-message" role="alert">{inference.error}</p>}
{step === 0 && <div className="reading-layout">
<section className="reading-card"><div className="card-toolbar"><span className="passage-label">{passage.language === 'en' ? 'English' : 'Greek'} / {passage.split === 'evaluation' ? 'Unseen check' : 'Practice'}</span><div className="size-picker" role="group" aria-label="Text size"><button aria-label="Smaller text" disabled={size === 0} onClick={() => setSize(value => value - 1)}>A−</button><button aria-label="Larger text" disabled={size === 2} onClick={() => setSize(value => value + 1)}>A+</button></div></div><article className={`passage text-size-${size}`} lang={passage.language}><div className="passage-meta"><span>{passage.category}</span></div><h1 className="passage-title" ref={heading} tabIndex={-1}>{passage.title}</h1><div className="page-rule" />{passage.text.split('\n\n').map(paragraph => <p key={paragraph}>{paragraph}</p>)}</article></section>
<aside className="reading-aside"><section className="record-card"><h2>Read aloud</h2><p>Record up to two minutes. With consent, audio is sent to Hugging Face and kept temporarily for this visit.</p><p className="recording-clock" role="status">{recorder.recording ? `Recording: ${recorder.seconds}s / 120s` : recorder.pending ? 'Waiting for microphone permission...' : 'Microphone off'}</p>
{recorder.recording ? <button className="primary-button" onClick={recorder.stop}>Stop recording</button> : <button className="primary-button" disabled={blocked || recorder.pending} onClick={recorder.start}>{recorder.blob ? 'Record again' : 'Start recording'}</button>}
<label className="file-label">Or choose audio<input type="file" accept="audio/*,.wav,.webm,.ogg,.mp3,.m4a" disabled={recorder.recording || recorder.pending || blocked} onChange={event => { recorder.chooseFile(event.target.files?.[0]); event.target.value = '' }} /></label>
{recorder.error && <p className="error-message" role="alert">{recorder.error}</p>}{recorder.notice && <p role="status">{recorder.notice}</p>}
{recorder.url && <><audio controls src={recorder.url} aria-label="Your recording" /><a className="download-link" href={recorder.url} download={recorder.blob instanceof File ? recorder.blob.name : `readloops.${recorder.blob.type.includes('mp4') ? 'm4a' : recorder.blob.type.includes('ogg') ? 'ogg' : 'webm'}`}>Save a copy of the recording</a><button className="primary-button" onClick={transcribe} disabled={blocked || recorder.recording || recorder.pending}>Transcribe recording</button></>}
<p className="small-note">Transcripts can be wrong. You will review the words before comparing.</p>
</section><button className="secondary-button" disabled={blocked || recorder.recording || recorder.pending} onClick={() => setStep(1)}>Continue without transcription</button><p className="feature-note">Manage saved sessions and recordings in Progress.</p></aside>
</div>}
{step === 1 && <section className="flow-card"><h1 ref={heading} tabIndex={-1}>Review your reading</h1><p className="muted">Listen again if you recorded. Correct the transcript to match what you actually said, including words you changed or skipped.</p>
{recorder.url && <audio controls src={recorder.url} aria-label="Replay your reading" />}
<details><summary>Show the passage</summary><p className="reference-text" lang={passage.language}>{passage.text}</p></details>
<label className="field-label" htmlFor="transcript">{source.startsWith('speech') ? 'Your transcript' : 'Optional: type the words you actually read'}</label>
<textarea id="transcript" lang={passage.language} value={text} maxLength={6000} disabled={blocked} onChange={event => updateText(event.target.value)} rows={6} placeholder={passage.language === 'en' ? 'Type or correct your transcript here.' : 'Γράψτε ή διορθώστε το κείμενο εδώ.'} />
{speechInfo && <p className="small-note">Audio: {speechInfo.audio_seconds}s. Local transcription: {speechInfo.processing_seconds}s. {source === 'speech-edited' ? 'Transcript edited by you.' : ''}</p>}
{speechInfo?.selective_feedback && <p className="small-note">{speechInfo.selective_feedback.withheld} automatic suggestions withheld because confidence was not validated or was below its threshold. Reviewing your transcript still enables a full word comparison.</p>}
{source === 'speech' && speechInfo?.selective_feedback?.suggestions?.length > 0 && <details><summary>Automatic suggestions to check</summary><p>{speechInfo.selective_feedback.notice}</p><ul>{speechInfo.selective_feedback.suggestions.map(item => <li key={item.id}><span lang={passage.language}>Passage: {item.expected || '(none)'} / Transcript: {item.heard || '(none)'}</span>. Correct the transcript above if this suggestion is wrong.</li>)}</ul></details>}
{speechInfo?.warnings?.map(message => <p className="notice-box" key={message} role="status">{message}</p>)}
{(source.startsWith('speech') || pilot || savedSession.mode?.startsWith('learning-')) && <label className="review-confirmation"><input type="checkbox" checked={reviewed} disabled={blocked} onChange={event => { setReviewed(event.target.checked); setCompared(false); setComparison(null); setDismissed({}) }} /> I checked the transcript against my recording. It matches the words I actually said.</label>}
<button className="secondary-button" disabled={!text.trim() || blocked || (source.startsWith('speech') && !reviewed)} onClick={compare}>{comparison ? 'Compare again' : 'Compare words'}</button>
{comparison && <div className="comparison"><h2>{comparison.differences.length ? 'Possible differences' : 'No word differences found'}</h2><p>{comparison.notice}</p><p className="small-note">{comparison.normalization}</p><ul className="difference-list">{comparison.differences.map(item => <li key={item.id} className={dismissed[item.id] ? 'dismissed' : ''}><div><strong>{differenceLabels[item.kind]}</strong><span lang={passage.language}>Passage: {item.expected || '(none)'} / Transcript: {item.heard || '(none)'}</span>{item.reference_index !== null && <small>Passage word {item.reference_index + 1}</small>}</div><label><input type="checkbox" checked={Boolean(dismissed[item.id])} onChange={event => setDismissed(value => ({ ...value, [item.id]: event.target.checked }))} /> Dismiss suggestion</label></li>)}</ul>{comparison.differences.length > 0 && <p>{kept} suggestions kept for review. These are not confirmed reading errors.</p>}</div>}
<div className="button-row"><button className="secondary-button" disabled={blocked} onClick={() => { setStep(0); setError('') }}>Back to reading</button>{comparison ? <button className="primary-button" disabled={blocked} onClick={() => continueToExercise(false)}>Continue to exercise</button> : <button className="primary-button" disabled={blocked} onClick={() => continueToExercise(true)}>Continue without word comparison</button>}</div>
</section>}
{step === 2 && <section className="flow-card"><h1 ref={heading} tabIndex={-1}>A quick exercise</h1><p className="muted">Choose the answer that matches the passage.</p>{exercise.support_text && <div className="notice-box" lang={passage.language}><strong>Reading support</strong><p>{exercise.support_text}</p></div>}<fieldset className="exercise" lang={passage.language}><legend>{exercise.question}</legend>{exercise.options.map((option, index) => <label className={`answer-option ${choice === index ? 'chosen' : ''}`} key={option}><input type="radio" name="answer" value={index} checked={choice === index} disabled={Boolean(answer) || blocked} onChange={() => setChoice(index)} />{option}</label>)}</fieldset>
{!answer ? <button className="primary-button" disabled={choice === null || blocked} onClick={checkAnswer}>Check answer</button> : <><div className={`answer-feedback ${answer.correct ? 'correct' : ''}`} role="status"><h2>{answer.correct ? 'That’s right.' : 'Let’s check the passage.'}</h2><p lang={passage.language}>{answer.explanation}</p></div><button className="primary-button" disabled={blocked} onClick={finish}>Finish session</button></>}
</section>}
{step === 3 && <section className="flow-card completion"><span className="completion-icon"><Icon name="check" /></span><h1 ref={heading} tabIndex={-1}>Reading complete.</h1><p lang={passage.language}>{passage.title}</p><dl className="summary-grid"><div><dt>Language</dt><dd>{passage.language === 'en' ? 'English' : 'Greek'}</dd></div><div><dt>Exercise</dt><dd>{answer.correct ? 'Correct' : 'Reviewed'}</dd></div><div><dt>Word review</dt><dd>{comparison ? `${kept} suggestions kept` : 'Self-review only'}</dd></div></dl><p className="muted">Your result is saved for this temporary visit. Word suggestions are not a pronunciation score.</p><button className="primary-button" onClick={onLeave}>Choose another passage</button></section>}
</div>
}
|