Spaces:
Running on Zero
Running on Zero
Download frontend/src/api.js from ManasT2485/readloops: direct link, hf CLI and curl.
- Browser
- Download file 4.69 kB
-
https://huggingface.co/spaces/ManasT2485/readloops/resolve/main/frontend/src/api.js
- Command line
-
hf download hf://spaces/ManasT2485/readloops/frontend/src/api.js
-
curl -L -o api.js https://huggingface.co/spaces/ManasT2485/readloops/resolve/main/frontend/src/api.js
4.69 kB
| // 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) }) | |
| } | |