document.addEventListener("DOMContentLoaded", () => {
// 1. Exact DOM Elements matching your index.html
const imageInput = document.getElementById("imageInput");
const analyzeBtn = document.getElementById("analyzeBtn");
const removeBtn = document.getElementById("removeBtn");
const imagePreview = document.getElementById("imagePreview");
const uploadState = document.getElementById("uploadState");
const previewState = document.getElementById("previewState");
const resultCard = document.getElementById("resultCard");
const predictionOutput = document.getElementById("predictionOutput");
const detectorForm = document.getElementById("detectorForm");
// 2. Image Selection & UI Toggling Logic
imageInput.addEventListener("change", function() {
const file = this.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(e) {
// Show the preview, hide the upload button
imagePreview.src = e.target.result;
uploadState.classList.add("hidden");
previewState.classList.remove("hidden");
// Enable the Analyze button
analyzeBtn.disabled = false;
// Hide any previous results
resultCard.classList.add("hidden");
}
reader.readAsDataURL(file);
}
});
// 3. Remove Image Logic
removeBtn.addEventListener("click", function(e) {
e.preventDefault();
// Reset the input
imageInput.value = "";
imagePreview.src = "";
// Swap the UI back to upload mode
previewState.classList.add("hidden");
uploadState.classList.remove("hidden");
// Disable the Analyze button again
analyzeBtn.disabled = true;
// Hide results
resultCard.classList.add("hidden");
});
// 4. API Communication (The Core Connection)
detectorForm.addEventListener("submit", async function(e) {
e.preventDefault();
if (!imageInput.files || imageInput.files.length === 0) {
alert("Please select an image first.");
return;
}
const file = imageInput.files[0];
const formData = new FormData();
// 'image' key exactly matches app.py
formData.append("image", file);
// UI Loading State
const originalText = analyzeBtn.innerText;
analyzeBtn.innerText = "Extracting Frequencies...";
analyzeBtn.disabled = true;
try {
const response = await fetch("/api/v1/detect", {
method: "POST",
body: formData
});
if (!response.ok) {
throw new Error(`Server returned ${response.status}`);
}
const data = await response.json();
if (data.status === "success") {
// Show the result card
resultCard.classList.remove("hidden");
// Format the output elegantly
const confPercentage = (data.confidence * 100).toFixed(2);
predictionOutput.innerHTML = `
Detected Class: ${data.prediction}
Confidence: ${confPercentage}%