Spaces:
Running
Running
Commit
Β·
0f56e30
1
Parent(s):
8545382
Create index.js
Browse files
index.js
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
function onFileSelected(event) {
|
2 |
+
const selectedFile = event.target.files[0];
|
3 |
+
const reader = new FileReader();
|
4 |
+
|
5 |
+
const imgtag = document.getElementById("myImage");
|
6 |
+
imgtag.title = selectedFile.name;
|
7 |
+
|
8 |
+
reader.onload = function(event) {
|
9 |
+
// set the myImage div to show the uploaded image file
|
10 |
+
imgtag.src = event.target.result;
|
11 |
+
};
|
12 |
+
|
13 |
+
reader.readAsDataURL(selectedFile);
|
14 |
+
|
15 |
+
const predictionDiv = document.getElementById('prediction')
|
16 |
+
const errorDiv = document.getElementById('error')
|
17 |
+
|
18 |
+
reader.addEventListener("loadend", function() {
|
19 |
+
fetch('https://hf.space/embed/jph00/testing/+/api/predict/', {
|
20 |
+
method: "POST",
|
21 |
+
// reader.result is the base64 string of the uploaded image
|
22 |
+
body: JSON.stringify({"data": [reader.result]}),
|
23 |
+
headers: { "Content-Type": "application/json" } })
|
24 |
+
.then(function(response) {
|
25 |
+
if (response.status != 200) {
|
26 |
+
// early return if the api errors out and show error message
|
27 |
+
errorDiv.innerHTML = '<u>Sorry the API is not working currently. Please try again later</u>'
|
28 |
+
predictionDiv.innerHTML = '';
|
29 |
+
return;
|
30 |
+
}
|
31 |
+
return response.json(); })
|
32 |
+
.then(function(json_response) {
|
33 |
+
const label = json_response?.data[0]?.label
|
34 |
+
// show the prediction
|
35 |
+
predictionDiv.innerHTML = `π <u>Prediction: ${label}</u> π`
|
36 |
+
errorDiv.innerHTML = '';
|
37 |
+
return;
|
38 |
+
})
|
39 |
+
});
|
40 |
+
}
|