File size: 12,501 Bytes
30d5634
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7954a1d
 
 
 
 
 
 
 
 
 
 
30d5634
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
// Basic front-end logic

document.addEventListener('DOMContentLoaded', () => {
    const inputMode = document.getElementById('input-mode');
    const fileInput = document.getElementById('file-input');
    const startProcessingBtn = document.getElementById('start-processing');
    const confidenceSlider = document.getElementById('confidence-threshold');
    const confidenceValue = document.getElementById('confidence-value');
    const progress = document.getElementById('progress');
    const progressText = document.getElementById('progress-text');
    const processingStatus = document.getElementById('processing-status');
    const statusOutput = document.getElementById('status-output');
    const resultsTableBody = document.querySelector('#results-table tbody');
    const previewImage = document.getElementById('preview-image');
    const imageInfo = document.getElementById('image-info');
    const prevBtn = document.getElementById('prev-image');
    const nextBtn = document.getElementById('next-image');
    const exportCsvBtn = document.getElementById('export-csv');
    const exportImagesBtn = document.getElementById('export-images');
    const zoomInBtn = document.getElementById('zoom-in');
    const zoomOutBtn = document.getElementById('zoom-out');

    let currentResults = [];
    let currentImageIndex = -1;
    let currentJobId = null;

    // Update confidence value display
    confidenceSlider.addEventListener('input', () => {
        confidenceValue.textContent = confidenceSlider.value;
    });

    // Handle input mode change (single file vs multiple)
    inputMode.addEventListener('change', () => {
        if (inputMode.value === 'single') {
            fileInput.removeAttribute('multiple');
        } else {
            fileInput.setAttribute('multiple', '');
        }
    });

    // --- Updated Start Processing Logic ---
    startProcessingBtn.addEventListener('click', async () => {
        const files = fileInput.files;
        if (!files || files.length === 0) {
            logStatus('Error: No files selected.');
            alert('Please select one or more image files.');
            return;
        }

        const mode = inputMode.value;
        if (mode === 'single' && files.length > 1) {
            logStatus('Error: Single File mode selected, but multiple files chosen.');
            alert('Single File mode allows only one file. Please select one file or switch to Directory mode.');
            return;
        }

        logStatus('Starting upload and processing...');
        processingStatus.textContent = 'Uploading...';
        startProcessingBtn.disabled = true;
        progress.value = 0;
        progressText.textContent = '0%';
        resultsTableBody.innerHTML = ''; // Clear previous results
        clearPreview(); // Clear image preview

        const formData = new FormData();
        for (const file of files) {
            formData.append('files', file);
        }
        formData.append('input_mode', mode);
        formData.append('confidence_threshold', confidenceSlider.value);

        // Basic progress simulation for upload (replace with XHR progress if needed)
        progress.value = 50;
        progressText.textContent = '50%';
        processingStatus.textContent = 'Processing...';

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

            progress.value = 100;
            progressText.textContent = '100%';

            // First check if the response is valid
            const contentType = response.headers.get('content-type');
            if (!contentType || !contentType.includes('application/json')) {
                // Handle non-JSON response
                const textResponse = await response.text();
                logStatus(`Error: Server returned non-JSON response: ${textResponse.substring(0, 200)}...`);
                processingStatus.textContent = 'Error: Server returned invalid format';
                throw new Error('Server returned non-JSON response');
            }

            // Now we can safely parse JSON
            const data = await response.json();

            if (response.ok) {
                logStatus('Processing successful.');
                processingStatus.textContent = 'Processing finished.';
                currentJobId = data.job_id; // Store the job ID
                logStatus(`Job ID: ${currentJobId}`);
                if (data.log) {
                    logStatus("--- Server Log ---");
                    logStatus(data.log);
                    logStatus("--- End Log ---");
                }
                if (data.error_files && data.error_files.length > 0) {
                    logStatus(`Warning: Skipped invalid files: ${data.error_files.join(', ')}`);
                }
                displayResults(data.results || []);
            } else {
                logStatus(`Error: ${data.error || 'Unknown processing error.'}`);
                if (data.log) {
                    logStatus("--- Server Log ---");
                    logStatus(data.log);
                    logStatus("--- End Log ---");
                }
                processingStatus.textContent = 'Error during processing.';
                alert(`Processing failed: ${data.error || 'Unknown error'}`);
            }

        } catch (error) {
            console.error('Fetch Error:', error);
            logStatus(`Network or Server Error: ${error.message}`);
            processingStatus.textContent = 'Network Error.';
            progress.value = 0;
            progressText.textContent = 'Error';
            alert(`An error occurred while communicating with the server: ${error.message}`);
        } finally {
            startProcessingBtn.disabled = false; // Re-enable button
        }
    });

    function logStatus(message) {
        statusOutput.value += message + '\n';
        statusOutput.scrollTop = statusOutput.scrollHeight; // Auto-scroll
    }

    function displayResults(results) {
        currentResults = results; // Store results
        resultsTableBody.innerHTML = ''; // Clear existing results
        currentImageIndex = -1; // Reset index
        currentJobId = currentJobId; // Ensure job ID is current

        if (!results || results.length === 0) {
            logStatus("No results returned from processing.");
            clearPreview();
            exportCsvBtn.disabled = true;
            exportImagesBtn.disabled = true;
            updateNavButtons(); // Ensure nav buttons are disabled
            return; // Exit early
        }

        results.forEach((result, index) => {
            const row = resultsTableBody.insertRow();
            row.classList.add('result-row'); // Add class for styling/selection
            row.innerHTML = `<td>${result.filename}</td><td>${result.num_eggs}</td>`;
            // Add data attributes for easy access
            row.dataset.index = index;
            row.dataset.filename = result.filename;
            row.dataset.annotatedFilename = result.annotated_filename;

            row.addEventListener('click', () => {
                displayImage(index);
            });
        });

        displayImage(0); // Show the first image initially
        // Enable export buttons IF there are results
        exportCsvBtn.disabled = !results.some(r => r.filename); // Enable if at least one result has a filename
        exportImagesBtn.disabled = !results.some(r => r.annotated_filename); // Enable if at least one result has an annotated image
    }

    function displayImage(index) {
        if (index < 0 || index >= currentResults.length || !currentJobId) {
            clearPreview();
            return;
        }

        currentImageIndex = index;
        const result = currentResults[index];

        if (result.annotated_filename) {
            const imageUrl = `/results/${currentJobId}/${result.annotated_filename}`;
            previewImage.src = imageUrl;
            previewImage.alt = `Annotated ${result.filename}`;
            imageInfo.textContent = `Filename: ${result.filename} - Eggs detected: ${result.num_eggs}`;
            logStatus(`Displaying image: ${result.annotated_filename}`);
        } else {
            // Handle cases where annotation failed or wasn't produced
            previewImage.src = ''; // Clear image
            previewImage.alt = 'Annotated image not available';
            imageInfo.textContent = `Filename: ${result.filename} - Eggs detected: ${result.num_eggs} (Annotation N/A)`;
            logStatus(`Annotated image not available for: ${result.filename}`);
        }

        updateNavButtons();

        // Highlight selected row
        document.querySelectorAll('.result-row').forEach(row => {
            row.classList.remove('selected');
        });
        const selectedRow = resultsTableBody.querySelector(`tr[data-index="${index}"]`);
        if (selectedRow) {
            selectedRow.classList.add('selected');
        }
    }

    function clearPreview() {
        previewImage.src = '';
        previewImage.alt = 'Annotated image preview';
        imageInfo.textContent = 'Filename: - Eggs detected: -';
        currentImageIndex = -1;
        updateNavButtons();
    }

    function updateNavButtons() {
        prevBtn.disabled = currentImageIndex <= 0;
        nextBtn.disabled = currentImageIndex < 0 || currentImageIndex >= currentResults.length - 1;
    }

    prevBtn.addEventListener('click', () => {
        if (currentImageIndex > 0) {
            displayImage(currentImageIndex - 1);
        }
    });

    nextBtn.addEventListener('click', () => {
        if (currentImageIndex < currentResults.length - 1) {
            displayImage(currentImageIndex + 1);
        }
    });

    // --- Export Logic (Placeholders - requires backend implementation) ---
    exportCsvBtn.addEventListener('click', () => {
        if (!currentJobId) {
            alert("No job processed yet.");
            return;
        }
        // Construct the CSV download URL
        const csvFilename = `${currentJobId}_results.csv`;
        const downloadUrl = `/results/${currentJobId}/${csvFilename}`;
        logStatus(`Triggering CSV download: ${csvFilename}`);
        // Create a temporary link and click it
        const link = document.createElement('a');
        link.href = downloadUrl;
        link.download = csvFilename; // Suggest filename to browser
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    });

    exportImagesBtn.addEventListener('click', () => {
        if (!currentJobId) {
            alert("No job processed yet.");
            return;
        }
        // This is more complex. Ideally, the backend would provide a zip file.
        // For now, just log and maybe open the first image?
        logStatus('Image export clicked. Downloading individual images or a zip file is needed.');
        alert('Image export functionality requires backend support to create a downloadable archive (zip file).');
        // Example: trigger download of the currently viewed image
        if (currentImageIndex !== -1 && currentResults[currentImageIndex].annotated_filename) {
            const imgFilename = currentResults[currentImageIndex].annotated_filename;
            const downloadUrl = `/results/${currentJobId}/${imgFilename}`;
            const link = document.createElement('a');
            link.href = downloadUrl;
            link.download = imgFilename;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    });

    // --- Zoom Logic (Placeholder - requires a library or complex CSS/JS) ---
    zoomInBtn.addEventListener('click', () => {
        console.log('Zoom In clicked');
        logStatus('Zoom functionality not yet implemented.');
        alert('Zoom functionality is not yet implemented.');
    });

    zoomOutBtn.addEventListener('click', () => {
        console.log('Zoom Out clicked');
        logStatus('Zoom functionality not yet implemented.');
        alert('Zoom functionality is not yet implemented.');
    });

    // Initial setup
    if (inputMode.value === 'single') {
        fileInput.removeAttribute('multiple');
    }
    logStatus('Application initialized. Ready for file selection.');
    exportCsvBtn.disabled = true;
    exportImagesBtn.disabled = true;
    clearPreview(); // Ensure preview is cleared on load
});