-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsyncUpload.tsx
More file actions
74 lines (63 loc) · 2.16 KB
/
Copy pathAsyncUpload.tsx
File metadata and controls
74 lines (63 loc) · 2.16 KB
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
'use client';
/**
* A long PDF through the queue.
*
* A synchronous request is killed at 60 seconds, which a 50-page contract will blow past.
* The submission returns a task id immediately, and `useTask` polls until it settles — so
* the tab can stay responsive, and the user can watch it progress.
*/
import { useState } from 'react';
import { unwrap, useTask } from '@devrobotlab/visionapi-react';
export function AsyncUpload() {
const [taskId, setTaskId] = useState<string | null>(null);
const [submitting, setSubmitting] = useState(false);
const { task, isPolling, isDone, error, stop } = useTask(taskId, {
pollInterval: 2000,
maxWait: 15 * 60_000,
});
async function submit(file: File) {
setSubmitting(true);
try {
const form = new FormData();
form.set('file', file);
form.set('preset', 'contract');
form.set('pages', '1-50');
// Your endpoint calls analyzeAsync() and returns the { task_id } it gets back.
const response = await fetch('/api/vision/analyze-async', { method: 'POST', body: form });
const body = await response.json();
setTaskId(body.task_id);
} finally {
setSubmitting(false);
}
}
return (
<section>
<input
type="file"
accept="application/pdf"
disabled={submitting}
onChange={(event) => {
const file = event.target.files?.[0];
if (file) void submit(file);
}}
/>
{isPolling && (
<p>
{task?.status === 'processing' ? 'Extracting…' : 'Queued…'}{' '}
<button onClick={stop}>Stop watching</button>
</p>
)}
{error && <p role="alert">{error.userMessage}</p>}
{isDone && task?.status === 'failed' && (
// A failed task costs 0 credits — the reservation is released in full.
<p role="alert">Extraction failed ({task.error?.code}). You were not charged.</p>
)}
{isDone && task?.status === 'completed' && (
<>
<p>{task.credits_used} credits · {task.pages} pages</p>
<pre>{JSON.stringify(unwrap(task.result, { dropNull: true }), null, 2)}</pre>
</>
)}
</section>
);
}