File size: 7,032 Bytes
1a11305
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260

const fileInput = document.getElementById('file-input');
const button = document.getElementById('button');
const errorMessage = document.getElementById('error-message');
const container = document.getElementById('container');

const imageContainer = document.getElementById('image-container');
const previewImage = document.getElementById('file-image');
const resultImage = document.getElementById('result-image');


const fileTitle = document.querySelector(".title");
const predInfo = document.querySelector(".pred-info");

const predictedValue = document.querySelector(".pred-info h3 span");


const topPred = document.querySelector(".pred-info ul");



const sendByCanvas = document.getElementById("canvas-send");


function createBlobFromImageData(imageData, mimeType = "image/jpeg") {
    const buffer = new ArrayBuffer(imageData.length);
    const view = new Uint8Array(buffer);
    for (let i = 0; i < imageData.length; i++) {
        view[i] = imageData.charCodeAt(i);
    }

    return new Blob([buffer], { type: mimeType });
}


function initialState() {
    button.textContent = 'Choose file';
    predInfo.style.display = 'none';
    fileTitle.textContent = "Upload your file here";
    imageContainer.style.display = 'none';
}

function displayError(message, timeout = 3000) { // Set default timeout if needed
    errorMessage.textContent = message;
    errorMessage.style.display = 'block';
    initialState();
    setTimeout(() => {
        errorMessage.style.display = 'none';
    }, timeout);
}


async function sendImageToServer(image, filename) {



    // Send the file to the server using Fetch API
    try {
        const formData = new FormData();

        console.log(image)

        const base64Data = image.split(',')[1];

        formData.append('file-input-64', base64Data);




        // formData.append('file-name', filename);

        // console.log(`form data ${formData}`);


        predInfo.style.display = 'none';
        button.textContent = 'Processing....';
        fileTitle.textContent = filename;



        console.log("Submit button is clicked");

        const response = await fetch('/upload', {
            method: 'POST',
            body: formData
        });

        topPred.innerHTML = "";
        console.log('I am here')

        const jsonData = await response.json();

        console.log(jsonData)
        console.log(typeof (jsonData))
        const jsonObject = JSON.parse(jsonData);

        if (!response.ok) {
            throw new Error(`Error uploading file: ${jsonData.error}`);
        }

        resultImage.src = `data:image/jpeg;base64,` + jsonObject["ig"];
        predInfo.style.display = 'flex';

        predictedValue.textContent = `${jsonObject.item[0]} ( ${(jsonObject.prob[0] * 100).toFixed(3)}%)`;

        for (let index = 0; index < jsonObject.item.length; index++) {
            const newItem = document.createElement("li");
            newItem.textContent = `${jsonObject.item[index]} ( ${(jsonObject.prob[index] * 100).toFixed(3)}%)`
            topPred.appendChild(newItem);
        }


        // Handle successful upload response (e.g., display message)
        console.log('File uploaded successfully!');

    } catch (error) {
        // errorMessage.textContent = `Error uploading file: ${error.message}`;
        displayError(error.message);
    } finally {
        // Hide progress message (optional)
        button.textContent = 'Choose file';
    }
}

async function sentImageDataToSeverViaImage(event) {

    const file = event.target.files[0];
    const allowedExtensions = ['jpeg', 'jpg'];

    const extension = file.name.split('.').pop().toLowerCase();


    // console.log(extension);

    if (!allowedExtensions.includes(extension)) {
        event.target.value = ''; // Clear file selection
        displayError('Invalid file format. Please upload a JPG or JPEG image.')
    } else {


        const reader = new FileReader();


        reader.onload = function (event) {
            previewImage.src = event.target.result;
            resultImage.src = '';

            imageContainer.style.display = 'flex';

        };

        reader.readAsDataURL(file); // Read the file and convert it to a data URL


        // Send the file to the server using Fetch API
        try {
            const formData = new FormData();
            formData.append('file-input', file);



            button.textContent = 'Processing....';
            fileTitle.textContent = file.name;
            predInfo.style.display = 'none';




            const response = await fetch('/upload', {
                method: 'POST',
                body: formData
            });

            if (!response.ok) {
                throw new Error(`Error uploading file: ${response.statusText}`);
            }

            topPred.innerHTML = "";

            const jsonData = await response.json();

            console.log(jsonData)
            console.log(typeof (jsonData))
            const jsonObject = JSON.parse(jsonData);


            resultImage.src = `data:image/jpeg;base64,` + jsonObject["ig"];
            predInfo.style.display = 'flex';

            predictedValue.textContent = `${jsonObject.item[0]} ( ${(jsonObject.prob[0] * 100).toFixed(3)}%)`;

            for (let index = 0; index < jsonObject.item.length; index++) {
                const newItem = document.createElement("li");
                newItem.textContent = `${jsonObject.item[index]} ( ${(jsonObject.prob[index] * 100).toFixed(3)}%)`
                topPred.appendChild(newItem);
            }


            // Handle successful upload response (e.g., display message)
            console.log('File uploaded successfully!');

        } catch (error) {
            errorMessage.textContent = `Error uploading file: ${error.message}`;
        } finally {
            // Hide progress message (optional)
            button.textContent = 'Choose file';
        }
        errorMessage.style.display = 'none'; // Hide the error message
    }
}


async function sentImageDataToSeverViaCanvas() {
    const canvas = document.getElementById('drawing-board'); // Replace with your canvas ID
    var dataURL = canvas.toDataURL("image/jpeg");

    previewImage.src = dataURL;
    resultImage.src = '';

    imageContainer.style.display = 'flex';

    // // Create a dummy link text
    // var a = document.createElement('a');
    // // Set the link to the image so that when clicked, the image begins downloading
    // a.href = dataURL
    // // Specify the image filename
    // a.download = 'canvas-download.jpeg';
    // // Click on the link to set off download
    // a.click();

    closeDialog();

    await sendImageToServer(dataURL, 'canvas_image.jpeg');




}



button.addEventListener('click', () => {
    errorMessage.style.display = 'none';
    fileInput.click();
});




sendByCanvas.addEventListener('click', async () => {



    sentImageDataToSeverViaCanvas();
});


fileInput.addEventListener('change', async (event) => {
    sentImageDataToSeverViaImage(event);
});