Spaces:
Running
Running
/** | |
* Reconcile paths for hf.space resources fetched from hf.co iframe | |
*/ | |
const pathFor = (path) => { | |
const basePath = document.location.origin + document.location.pathname; | |
return new URL(path, basePath).href; | |
}; | |
const generateDetails = async () => { | |
const details = await fetch(pathFor('details')); | |
return await details.json(); | |
}; | |
const createTask = async (prompt) => { | |
const taskResponse = await fetch(pathFor('task/create'), { | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/json', | |
}, | |
body: JSON.stringify({ prompt }), | |
}); | |
if (!taskResponse.ok || !taskResponse.headers.get('content-type')?.includes('application/json')) { | |
throw new Error(await taskResponse.text()); | |
} | |
const task = await taskResponse.json(); | |
return task; | |
}; | |
const pollTask = async (task) => { | |
const taskResponse = await fetch(pathFor(`task/poll?task_id=${task.task_id}`)); | |
if (!taskResponse.ok || !taskResponse.headers.get('content-type')?.includes('application/json')) { | |
throw new Error(await taskResponse.text()); | |
} | |
return await taskResponse.json(); | |
}; | |
const longPollTask = async (task, interval = 5_000, max) => { | |
const etaDisplay = document.querySelector('.eta'); | |
task = await pollTask(task); | |
if (task.status === 'completed' || task.status === 'failed' || (max && task.poll_count > max)) { | |
return task; | |
} | |
etaDisplay.textContent = Math.round(task.eta); | |
await new Promise((resolve) => setTimeout(resolve, interval)); | |
return await longPollTask(task, interval, max); | |
}; | |
export { generateDetails, createTask, longPollTask }; | |