Spaces:
Running on Zero
Running on Zero
Download frontend/src/useInferenceJob.js from ManasT2485/readloops: direct link, hf CLI and curl.
- Browser
- Download file 1.63 kB
-
https://huggingface.co/spaces/ManasT2485/readloops/resolve/main/frontend/src/useInferenceJob.js
- Command line
-
hf download hf://spaces/ManasT2485/readloops/frontend/src/useInferenceJob.js
-
curl -L -o useInferenceJob.js https://huggingface.co/spaces/ManasT2485/readloops/resolve/main/frontend/src/useInferenceJob.js
1.63 kB
| import { useCallback, useEffect, useState } from 'react' | |
| import { api } from './api.js' | |
| // The server owns the job. Closing this tab only stops polling, not inference. | |
| export function useInferenceJob(sessionId, enabled) { | |
| const [job, setJob] = useState(null) | |
| const [error, setError] = useState('') | |
| const [revision, setRevision] = useState(0) | |
| const refresh = useCallback(() => setRevision(value => value + 1), []) | |
| useEffect(() => { | |
| if (!enabled) return | |
| const controller = new AbortController() | |
| let timer | |
| async function poll() { | |
| try { | |
| const jobs = await api(`/sessions/${sessionId}/jobs`, { signal: controller.signal }) | |
| if (controller.signal.aborted) return | |
| const latest = Array.isArray(jobs) ? jobs[0] : null | |
| setJob(latest || null) | |
| setError('') | |
| if (latest && ['queued', 'running'].includes(latest.state)) timer = setTimeout(poll, 1500) | |
| } catch (failure) { | |
| if (!controller.signal.aborted) { | |
| setError(failure.message) | |
| timer = setTimeout(poll, 4000) | |
| } | |
| } | |
| } | |
| poll() | |
| return () => { controller.abort(); clearTimeout(timer) } | |
| }, [sessionId, enabled, revision]) | |
| async function command(path) { | |
| setError('') | |
| try { | |
| const next = await api(path, { method: 'POST' }) | |
| setJob(next) | |
| refresh() | |
| return next | |
| } catch (failure) { setError(failure.message); throw failure } | |
| } | |
| return { job, error, refresh, | |
| start: () => command(`/sessions/${sessionId}/jobs`), | |
| cancel: () => command(`/jobs/${job.id}/cancel`), | |
| retry: () => command(`/jobs/${job.id}/retry`) } | |
| } | |