Spaces:
Running on Zero
Running on Zero
File size: 4,693 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 | // Same React API, served on this Space. The bearer token scopes one temporary visit.
const TOKEN_KEY = 'readloops-space-visitor-v1'
let visitorPromise
let adult = false
let audioConsent = false
const submitted = new Set()
function storedToken() { try { return sessionStorage.getItem(TOKEN_KEY) } catch { return null } }
function keepToken(token) { try { sessionStorage.setItem(TOKEN_KEY, token) } catch { /* Memory-only visit still works. */ } }
async function visitor() {
if (!visitorPromise) visitorPromise = (async () => {
const saved = storedToken()
if (saved) return saved
const response = await fetch('/backend/api/visitor', { method: 'POST', signal: AbortSignal.timeout(15000) })
const body = await response.json()
if (!response.ok) throw new Error(body.detail || 'The demo is unavailable. Try again later.')
keepToken(body.token)
return body.token
})().catch(error => { visitorPromise = null; throw error })
return visitorPromise
}
async function consent(token, audio) {
if (!adult && !window.confirm('ReadLoops is for adults aged 18 or older. This public demo stores this visit temporarily on Hugging Face, not only on your computer. Continue only if you are 18 or older.')) throw new Error('Adult confirmation is required to start a session.')
adult = true
if (audio && !audioConsent) {
if (!window.confirm('Send this recording to Hugging Face for transcription? Avoid personal information. Recordings and results are held temporarily for this visit and expire after an hour of inactivity or a restart. The demo does not train models on recordings.')) throw new Error('Recording upload cancelled. You can continue with typed words.')
audioConsent = true
}
const response = await fetch('/backend/api/consent', { method: 'POST',
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ adult, audio: audioConsent }) })
if (!response.ok) throw new Error('Consent could not be saved. Reload and try again.')
}
function dispatch(job, token) {
if (!job || job.state !== 'queued' || window.parent === window) return
const key = `${job.id}:${job.attempts}:${job.created_at}`
if (submitted.has(key)) return
submitted.add(key)
window.parent.postMessage({ type: 'readloops:transcribe', token, jobId: job.id }, location.origin)
}
export async function api(path, options = {}) {
const { timeoutMs = 15000, signal, raw = false, ...request } = options
const controller = new AbortController()
const abort = () => controller.abort()
if (signal?.aborted) controller.abort()
signal?.addEventListener('abort', abort, { once: true })
let timer
try {
const token = await visitor()
const method = request.method || 'GET'
if ((path === '/sessions' && method === 'POST') || (path.endsWith('/audio') && method === 'PUT')) await consent(token, path.endsWith('/audio'))
if (method === 'POST' && /\/(jobs|retry)$/.test(path) && window.parent === window) throw new Error('Open the Space homepage to use its transcription connection.')
timer = setTimeout(abort, timeoutMs)
const response = await fetch(`/backend/api${path}`, { ...request,
headers: { ...request.headers, Authorization: `Bearer ${token}` }, signal: controller.signal })
if (response.ok && raw) return await response.blob()
const data = await response.json().catch(() => null)
if (!response.ok) {
if (response.status === 401) {
try { sessionStorage.removeItem(TOKEN_KEY) } catch { /* Reload starts fresh. */ }
visitorPromise = null; adult = false; audioConsent = false
}
const detail = typeof data?.detail === 'string' ? data.detail : 'The request could not be completed. Check your input and try again.'
throw new Error(detail)
}
if (data === null) throw new Error('The backend returned an unreadable response. Please retry.')
if (/\/(jobs|retry)$/.test(path)) {
for (const job of Array.isArray(data) ? data : [data]) dispatch(job, token)
}
return data
} catch (error) {
if (controller.signal.aborted) throw new Error('The request was stopped or took too long. Your recording is still available to retry.')
if (error instanceof TypeError) throw new Error('Cannot reach the Space. Check your connection, then retry.')
throw error
} finally {
clearTimeout(timer)
signal?.removeEventListener('abort', abort)
}
}
export function postJson(path, body, options) {
return api(path, { ...options, method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
}
|