Spaces:
Running on Zero

readloops / frontend /src /App.jsx
ManasT2485's picture
Deploy original ReadLoops React interface with ZeroGPU speech bridge
3e6f84d verified
Raw History Blame Contribute Delete
16.8 kB
import React, { useEffect, useRef, useState } from 'react'
import { PandaIllustration, Icon, LoopIcon } from './Icons.jsx'
import { api, postJson } from './api.js'
import { Session } from './Session.jsx'
import { clearDraft } from './useDraft.js'
import { Lab } from './Lab.jsx'
const policyNames = { fixed: 'Fixed practice', adaptive: 'Adaptive practice', comparison: 'Compare approaches', 'learning-fixed': 'Reading outcome: fixed', 'learning-epsilon': 'Reading outcome: epsilon greedy', 'learning-linucb': 'Reading outcome: LinUCB', 'learning-comparison': 'Reading outcome: randomized comparison' }
export function App() {
const [language, setLanguage] = useState('en')
const [split, setSplit] = useState('practice')
const [mode, setMode] = useState('fixed')
const [view, setView] = useState('reading')
const [catalog, setCatalog] = useState([])
const [sessions, setSessions] = useState([])
const [selected, setSelected] = useState(null)
const [health, setHealth] = useState(null)
const [report, setReport] = useState(null)
const [benchmark, setBenchmark] = useState(null)
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
const [opening, setOpening] = useState(false)
const [remove, setRemove] = useState(null)
const [attempt, setAttempt] = useState(0)
const pendingStart = useRef(null)
useEffect(() => {
const controller = new AbortController()
setLoading(true)
setError('')
setCatalog([]); setSessions([]); setReport(null)
Promise.all([
api('/health', { signal: controller.signal }),
api(`/passages?language=${language}&split=${split}`, { signal: controller.signal }),
api(`/sessions?language=${language}`, { signal: controller.signal }),
api(`/policy-report?language=${language}`, { signal: controller.signal }),
api('/benchmarks/latest', { signal: controller.signal }),
]).then(([status, passages, saved, comparison, measured]) => {
if (controller.signal.aborted) return
setHealth(status); setCatalog(passages); setSessions(saved); setReport(comparison); setBenchmark(measured)
if (status.pilot) {
setLanguage(status.pilot.language)
setMode(status.pilot.arm)
if (status.pilot.next) setSplit(status.pilot.next.stage === 'practice' ? 'practice' : 'evaluation')
}
}).catch(failure => { if (!controller.signal.aborted) setError(failure.message) }).finally(() => { if (!controller.signal.aborted) setLoading(false) })
return () => controller.abort()
}, [language, split, attempt])
async function openPassage(passageId) {
if (opening) return
setOpening(true); setError('')
try {
if (!pendingStart.current || pendingStart.current.passage_id !== passageId || pendingStart.current.mode !== mode) pendingStart.current = { id: health?.pilot?.next?.session_id || crypto.randomUUID(), passage_id: passageId, mode }
const created = await postJson('/sessions', pendingStart.current)
const saved = await api(`/sessions/${created.id}`)
pendingStart.current = null
setSelected(saved)
} catch (failure) { setError(failure.message); setAttempt(value => value + 1) }
finally { setOpening(false) }
}
async function resume(id) {
setOpening(true); setError('')
try { setSelected(await api(`/sessions/${id}`)) }
catch (failure) { setError(failure.message) }
finally { setOpening(false) }
}
async function deleteSaved() {
setOpening(true); setError('')
try { await api(`/sessions/${remove.id}`, { method: 'DELETE' }); clearDraft(remove.id); setRemove(null); setAttempt(value => value + 1) }
catch (failure) { setError(failure.message) }
finally { setOpening(false) }
}
function leave() { setSelected(null); setAttempt(value => value + 1) }
const visible = catalog.filter(p => split !== 'evaluation' || !sessions.some(session => session.passage_id === p.id))
const finished = sessions.filter(session => session.status === 'completed')
const active = sessions.filter(session => session.status === 'active')
const measured = benchmark?.languages?.find(item => item.language === language)
const pilot = health?.pilot
if (pilot && health.version === '0.10.0') return <main className="flow-card"><h1>Continue your pilot</h1><p>This participant uses the original study version. Open its preserved reading interface to continue.</p><a className="primary-button" href="http://127.0.0.1:8000">Open pilot reading</a></main>
return <div className={`app ${selected ? 'is-focused' : ''}`}>
<a className="skip-link" href="#main">Skip to content</a>
<aside className="sidebar"><a href="/read/" className="brand" aria-label="ReadLoops home"><LoopIcon /><span>readloops</span></a><nav aria-label="Main navigation">{[['reading', 'book', 'Read'], ['progress', 'progress', 'Progress'], ['compare', 'compare', 'Compare'], ['lab', 'lab', 'Experiments'], ['setup', 'settings', 'Setup']].filter(([name]) => !pilot || !['compare', 'lab'].includes(name)).map(([name, icon, label]) => <button key={name} className={`nav-button ${view === name ? 'is-selected' : ''}`} aria-label={label} aria-current={view === name ? 'page' : undefined} disabled={opening} onClick={() => setView(name)}><Icon name={icon} /><span>{label}</span></button>)}</nav><div className="sidebar-footer"><span className="tiny-book"><Icon name="book" /></span><span>English & Greek<br /><small>Reading practice for adults</small></span></div></aside>
<div className="workspace"><header className="topbar"><span className="page-label">{selected && <LoopIcon />}{selected ? 'Reading session' : { reading: 'Reading practice', progress: 'Saved progress', compare: 'Practice comparison', lab: 'Experiments', setup: 'Demo setup' }[view]}</span><span className="age-label">18+</span></header>
<main id="main" tabIndex={-1}>{selected ? <Session pilot={Boolean(pilot)} key={selected.id} passage={selected.passage} savedSession={selected} onFinish={() => {}} onLeave={leave} /> : <>
<div className="page-heading"><div><h1>{{ reading: 'Let’s read.', progress: 'Your progress', compare: 'Compare approaches', lab: 'Experiments', setup: 'Demo setup' }[view]}</h1><p>{view === 'reading' ? 'A short passage. Your own pace.' : 'Temporary progress for this visit. Separate results for each language.'}</p></div><div className="language-picker" role="group" aria-label="Reading language"><button disabled={opening || Boolean(pilot)} aria-pressed={language === 'en'} onClick={() => setLanguage('en')}><span className="language-symbol english" aria-hidden="true">Aa</span>English</button><button lang="el" disabled={opening || Boolean(pilot)} aria-pressed={language === 'el'} onClick={() => setLanguage('el')}><span className="language-symbol greek" aria-hidden="true">Ω</span>Ελληνικά</button></div></div>
{error && <div className="error-message" role="alert"><p>{error}</p><button className="secondary-button" onClick={() => setAttempt(value => value + 1)}>Retry connection</button></div>}
{loading && <p role="status">Loading saved data...</p>}
{pilot && <section className="notice-box pilot-notice" aria-label="Pilot session"><strong>{pilot.next ? `Pilot reading ${pilot.completed + 1} of ${pilot.total}` : 'Pilot readings complete. Thank you.'}</strong><p>{pilot.notice}</p><p>For this pilot, save a recording and review its transcript before the exercise. You can type a transcript if recognition fails.</p><p>To stop, choose Leave session. To withdraw your data, contact: {pilot.contact}.</p><details><summary>Your participant code</summary><code>{pilot.code}</code><p>Personal data deletion deadline: {new Date(pilot.delete_by).toLocaleDateString()}</p></details></section>}
{view === 'reading' && <>
<div className="mode-picker" role="group" aria-label="Passage set"><button disabled={opening || Boolean(pilot)} aria-pressed={split === 'practice'} onClick={() => setSplit('practice')}>Practice</button><button disabled={opening || Boolean(pilot)} aria-pressed={split === 'evaluation'} onClick={() => setSplit('evaluation')}>Unseen check</button></div>
{split === 'practice' && !pilot ? <div className="policy-choice"><label htmlFor="policy">Exercise selection</label><select id="policy" value={mode} disabled={opening} onChange={event => setMode(event.target.value)}>{Object.entries(policyNames).map(([value, label]) => <option key={value} value={value}>{label}</option>)}</select><p className="small-note">{mode.startsWith('learning-') ? 'Experimental: chooses exercise type and reading support. A later reviewed practice reading supplies a delayed reward. This does not establish learning improvement.' : mode === 'fixed' ? 'Consistent rules choose an exercise from your word review.' : mode === 'adaptive' ? 'Uses past exercise answers in this language and occasionally tries another exercise.' : 'Randomly assigns fixed or adaptive selection for a fairer comparison. No approach is known to be better yet.'}</p></div> : <p className="notice-box">{pilot && split === 'practice' ? 'Follow the assigned practice sequence. The same two passages repeat in this feasibility pilot. ' : 'Unseen passages are kept separate from practice. '} Once opened, a passage stays marked as seen during this visit. Expiry or a server restart resets that record. These checks do not train the exercise policy.</p>}
{active.length > 0 && <p className="notice-box">You have {active.length} unfinished session{active.length === 1 ? '' : 's'} in this language. <button className="text-button" onClick={() => setView('progress')}>Resume from Progress</button></p>}
<div className="reading-layout"><section className="passage-list" aria-label="Choose a passage">{visible.map(p => <article className="passage-choice" key={p.id}><span className="mini-book"><Icon name="book" /></span><div><h2 lang={language}>{p.title}</h2><p>{p.word_count} words / {language === 'en' ? 'English' : 'Greek'}</p></div><button className="primary-button passage-start" disabled={opening || loading} onClick={() => openPassage(p.id)}>Read</button></article>)}{!loading && !error && !visible.length && <p className="notice-box">{pilot && !pilot.next ? 'All eight pilot readings are complete. The organiser can now prepare the human review.' : 'No unseen passages remain in this language. Resume an unfinished check from Progress, or return to practice.'}</p>}</section><aside className="reading-aside"><section className="start-card"><div className="illustration-area"><PandaIllustration /></div><div className="start-content"><h2>Read. Review. Practise.</h2><p>Choose a passage to begin.<br />Recording is optional.</p></div></section><p className="feature-note">Public demo: progress and recordings are temporary. Manage this visit in Progress.</p></aside></div>
</>}
{view === 'progress' && <section className="flow-card"><h2>Continue a session</h2>{!active.length && <p className="muted">No unfinished sessions.</p>}<ul className="result-list">{active.map(row => <li key={row.id}><strong>{row.title || row.passage_id}</strong><span>{row.split === 'evaluation' ? 'Unseen check' : policyNames[row.mode]} / {row.has_audio ? 'Recording saved' : 'No saved recording'}</span><div className="button-row"><button className="primary-button" disabled={opening} onClick={() => resume(row.id)}>Resume</button>{!pilot && <button className="text-button" onClick={() => setRemove(row)}>Delete session</button>}</div></li>)}</ul>
{['practice', 'evaluation'].map(group => <div key={group}><h2>{group === 'practice' ? 'Practice history' : 'Unseen checks'}</h2>{!finished.some(row => row.split === group) && <p className="muted">No completed sessions yet.</p>}<ul className="result-list">{finished.filter(row => row.split === group).map(row => <li key={row.id}><strong lang={language}>{row.title || row.passage_id}</strong><span>Exercise: {row.result.exercise_correct ? 'correct' : 'reviewed'} / {row.result.suggestions_kept === null ? 'self-review' : `${row.result.suggestions_kept} suggestions kept`}</span><small>{new Date(row.updated_at).toLocaleString()} / {row.decision?.policy} / {row.result.source}{row.result.word_difference_rate !== null ? ` / text difference rate ${(row.result.word_difference_rate * 100).toFixed(1)}%` : ''}</small><div className="button-row"><button className="secondary-button" disabled={opening} onClick={() => resume(row.id)}>View session</button>{!pilot && <button className="text-button" onClick={() => setRemove(row)}>Delete session</button>}</div></li>)}</ul></div>)}<p className="small-note">Text differences can come from recognition errors. These are not pronunciation scores. Passages are not calibrated for difficulty, so differences across sessions do not by themselves establish improvement.</p>
{remove && <div className="error-message" role="alert"><p>Delete this session’s transcript, recording, and result? This cannot be undone in the app. Existing backups may still contain it. Evaluation passages remain marked as seen.</p><div className="button-row"><button className="secondary-button" disabled={opening} onClick={() => setRemove(null)}>Keep session</button><button className="secondary-button" disabled={opening} onClick={deleteSaved}>Delete permanently</button></div></div>}
</section>}
{view === 'compare' && <section className="flow-card"><h2>Randomized practice comparison</h2><p className="muted">Choose “Compare approaches” when starting practice to contribute an outcome. Directly selected fixed or adaptive sessions are excluded from this comparison.</p><div className="report-table"><table><thead><tr><th>Approach</th><th>Assigned</th><th>Answered</th><th>Completed</th><th>Correct answers</th><th>95% interval</th></tr></thead><tbody>{report?.arms.map(arm => <tr key={arm.policy}><th>{policyNames[arm.policy]}</th><td>{arm.assigned}</td><td>{arm.answered}</td><td>{arm.completed}</td><td>{arm.success_rate === null ? 'No data' : `${(arm.success_rate * 100).toFixed(1)}%`}</td><td>{arm.wilson_95 ? arm.wilson_95.map(value => `${(value * 100).toFixed(0)}%`).join(' to ') : 'No data'}</td></tr>)}</tbody></table></div><p className="small-note">{report?.notice}</p><p className="notice-box">Correct exercise answers are a useful check, but they do not prove better reading. Adaptive selection may favour easier exercises. No winner is declared.</p></section>}
{view === 'lab' && !pilot && <Lab language={language} />}
{view === 'setup' && <section className="setup-card"><div className="connection-row"><span>Backend</span><strong>{health ? 'Connected' : 'Unavailable'}</strong></div><div className="connection-row"><span>Hosted speech model</span><strong>{health?.speech?.ready ? `${health.speech.model?.split('/').pop()} / ZeroGPU` : 'Not ready'}</strong></div><button className="secondary-button" disabled={loading} onClick={() => setAttempt(value => value + 1)}>Check connection</button><div className="setup-note"><h2>Temporary data</h2><p>{pilot ? 'This pilot participant has a separate local database.' : 'One temporary visitor profile, separate from other visitors.'} Progress and recordings expire after one hour of inactivity or a Space restart. Use Progress to resume or delete a session.</p><p>{pilot ? "The organiser manages pilot data and withdrawal. Avoid creating extra copies of participant recordings." : "The public demo does not provide durable storage or backups."}</p><h2>Speech benchmark</h2>{measured ? <><p className="small-note">Measured model: {benchmark.model}. The report describes this model, which may differ from an environment override.</p><p>{measured.samples} FLEURS {benchmark.partition === 'holdout' ? 'held-out' : 'test'} clips / {language === 'en' ? 'English' : 'Greek'} / CPU INT8.</p><dl className="summary-grid"><div><dt>Word error rate</dt><dd>{(measured.word_error_rate * 100).toFixed(1)}%</dd></div><div><dt>Successful warm median</dt><dd>{measured.warm_latency_p50_seconds == null ? 'No success' : `${measured.warm_latency_p50_seconds}s`}</dd></div><div><dt>Successful warm p95</dt><dd>{measured.warm_latency_p95_seconds == null ? 'No success' : `${measured.warm_latency_p95_seconds}s`}</dd></div></dl><p>{measured.failed_warm_runs} failed attempts out of {measured.warm_runs ?? measured.samples * 2} warm runs. Rejected clips remain in the accuracy result; successful runs alone determine the latency figures.</p><p className="small-note">{benchmark.limitations}</p></> : <p className="muted">This hosted inference adapter has not been benchmarked. Local CPU results do not describe this deployment.</p>}</div></section>}
</>}</main><footer className="page-footer"><span>readloops</span><span>English & Greek</span></footer></div>
</div>
}