-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathscript.js
More file actions
73 lines (62 loc) · 2.22 KB
/
script.js
File metadata and controls
73 lines (62 loc) · 2.22 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
const fileInput = document.getElementById("imageInput");
const analyzeBtn = document.getElementById("analyzeBtn");
const chatbox = document.getElementById("chatBox");
function addBotMessage(message) {
const div = document.createElement("div");
div.className = "p-2 border rounded my-1 bg-white";
div.textContent = `🤖 ${message}`;
chatbox.appendChild(div);
chatbox.scrollTop = chatbox.scrollHeight; // auto scroll
}
analyzeBtn.addEventListener("click", async () => {
const file = fileInput.files[0];
if (!file) {
addBotMessage("Please upload an image first.");
return;
}
addBotMessage("📤 Uploading and analyzing image...");
const reader = new FileReader();
reader.onload = async function () {
const base64Image = reader.result.split(",")[1]; // Get only base64 part
try {
const response = await fetch("http://localhost:3000/analyze", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ base64Image }),
});
if (!response.ok) {
const errorText = await response.text();
addBotMessage(
`❌ Server request failed with status ${response.status}.`
);
console.error("Server Error Response:", errorText);
return;
}
const json = await response.json();
if (
json.responses &&
json.responses[0] &&
json.responses[0].labelAnnotations
) {
const labels = json.responses[0].labelAnnotations.map(
(label) => `${label.description} (${(label.score * 100).toFixed(1)}%)`
);
addBotMessage(`🧠 I see: ${labels.join(", ")}`);
} else if (json.responses && json.responses[0].error) {
addBotMessage(`❌ API Error: ${json.responses[0].error.message}`);
console.error("API Error:", json.responses[0].error);
} else {
addBotMessage("⚠️ No labels detected. Try another image.");
console.error("Invalid response:", json);
}
} catch (error) {
addBotMessage(
"❌ Failed to analyze the image. Please check your server and network."
);
console.error("Error during server call:", error);
}
};
reader.readAsDataURL(file);
});