File size: 2,489 Bytes
12f098c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
75
76
77
78
79
80
81
82
83
84
async function initializeWebGPU() {
    const canvas = document.getElementById("webgpu-canvas");

    if (!navigator.gpu) {
        document.body.innerHTML = "<p>Your browser does not support WebGPU.</p>";
        return;
    }

    console.log("WebGPU is supported.");

    const adapter = await navigator.gpu.requestAdapter();
    if (!adapter) {
        console.error("Failed to get GPU adapter.");
        return;
    }
    console.log("GPU adapter obtained.");

    const device = await adapter.requestDevice();
    if (!device) {
        console.error("Failed to get GPU device.");
        return;
    }
    console.log("GPU device obtained.");

    const context = canvas.getContext("webgpu");
    if (!context) {
        console.error("Failed to get WebGPU context.");
        return;
    }
    console.log("WebGPU context obtained.");

    context.configure({
        device: device,
        format: navigator.gpu.getPreferredCanvasFormat(),
        alphaMode: "opaque",
    });

    console.log("WebGPU initialized and canvas configured.");
}

// Call the initializeWebGPU function to ensure it runs
initializeWebGPU();

async function submitQuestion(imageFile, question) {
    const formData = new FormData();
    formData.append("image", imageFile);
    formData.append("text", question);

    try {
        const response = await fetch("/predict", {
            method: "POST",
            body: formData,
        });

        if (!response.ok) {
            const errorText = await response.text();
            console.error("Failed to get a response:", response.status, response.statusText, errorText);
            return `Error: Unable to fetch the answer. Status: ${response.status}, ${response.statusText}`;
        }

        const result = await response.json();
        return result.data[0];
    } catch (error) {
        console.error("Fetch error:", error);
        return `Error: Unable to fetch the answer. ${error.message}`;
    }
}

// Handle user interactions
document.getElementById("submit-btn").addEventListener("click", async () => {
    const imageFile = document.getElementById("image-upload").files[0];
    if (!imageFile) {
        alert("Please upload an image.");
        return;
    }
    const question = document.getElementById("question").value;

    const answer = await submitQuestion(imageFile, question);
    document.getElementById("answer").innerText = `Answer: ${answer}`;
});

// Initialize WebGPU when the page loads
initializeWebGPU();