card-detector / js /index.js
ujalaarshad17's picture
requirements.txt
1210fba
const video = document.getElementById("camera");
const canvas = document.getElementById("canvas");
const captureBtn = document.getElementById("capture-btn");
const imageInput = document.getElementById("imageInput");
const resultsImg = document.getElementById("results");
const chooseFileBtn = document.getElementById("chooseFileBtn");
const uploadSuccess = document.getElementById("uploadSuccess");
const confidenceScore = document.getElementById("confidenceScore");
// Access the webcam only if not on mobile
if (window.innerWidth > 768) {
navigator.mediaDevices
.getUserMedia({ video: true })
.then((stream) => {
video.srcObject = stream;
})
.catch((err) => {
console.error("Error accessing webcam: ", err);
});
} else {
// If the screen is small, stop the webcam stream if it exists
if (video.srcObject) {
const stream = video.srcObject;
const tracks = stream.getTracks();
tracks.forEach((track) => {
track.stop();
});
video.srcObject = null;
}
}
// Capture the image
captureBtn.addEventListener("click", () => {
const context = canvas.getContext("2d");
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
context.drawImage(video, 0, 0, canvas.width, canvas.height);
canvas.toBlob((blob) => {
const formData = new FormData();
formData.append("file", blob, "captured_image.png");
fetch("/predict", {
method: "POST",
body: formData,
})
.then((response) => response.json())
.then((data) => {
if (data.confidence_score !== undefined) {
resultsImg.src = canvas.toDataURL("image/png"); // Display captured image
confidenceScore.textContent =
"Confidence Score: " + data.confidence_score;
uploadSuccess.style.display = "block"; // Show success message
} else {
alert(data.error);
}
})
.catch((error) => {
console.error("Error:", error);
});
}, "image/png");
});
// Trigger click on the hidden file input when the custom button is clicked
chooseFileBtn.addEventListener("click", () => {
imageInput.click();
});
// Upload the selected image
function uploadImage() {
const file = imageInput.files[0];
if (!file) {
alert("Please select an image to upload.");
return;
}
const formData = new FormData();
formData.append("file", file);
fetch("/predict", {
method: "POST",
body: formData,
})
.then((response) => response.json())
.then((data) => {
if (data.confidence_score !== undefined) {
const reader = new FileReader();
reader.onload = function (e) {
resultsImg.src = e.target.result; // Display uploaded image
confidenceScore.textContent =
"Confidence Score: " + data.confidence_score;
uploadSuccess.style.display = "block"; // Show success message
};
reader.readAsDataURL(file);
} else {
alert(data.error);
}
})
.catch((error) => {
console.error("Error:", error);
});
}