File size: 1,596 Bytes
0c0e375
 
 
 
 
 
 
2d460b1
 
 
0c0e375
2d460b1
 
 
 
42422ba
 
 
 
 
 
 
0bae5c5
 
 
 
 
2d460b1
 
 
 
 
 
0c0e375
2d460b1
0bae5c5
 
 
 
2d460b1
 
 
3f5ff9d
2d460b1
 
 
 
da30f9b
9421891
 
 
2d460b1
 
 
 
 
 
 
9fbb486
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
/**
 * 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 };