File size: 31,050 Bytes
c558623
 
852934c
c558623
 
 
852934c
c558623
 
 
 
 
852934c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c558623
852934c
c558623
 
 
 
 
852934c
c558623
 
 
852934c
c558623
852934c
c558623
 
 
 
852934c
c558623
 
 
852934c
c558623
 
 
 
852934c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b38fb77
852934c
 
 
b38fb77
852934c
b38fb77
852934c
 
 
 
 
 
 
b38fb77
 
852934c
 
 
 
 
 
 
 
 
 
c558623
 
852934c
c558623
 
 
 
 
852934c
 
 
c558623
 
852934c
c558623
 
 
852934c
 
 
 
 
 
 
c558623
 
 
852934c
c558623
 
 
 
852934c
 
 
c558623
 
852934c
c558623
852934c
c558623
 
 
852934c
 
c558623
 
 
 
 
 
 
 
 
852934c
 
 
 
 
 
 
c558623
852934c
c558623
852934c
 
 
 
 
 
c558623
852934c
 
c558623
b38fb77
852934c
 
 
 
 
 
 
 
 
 
 
 
b38fb77
c558623
b38fb77
852934c
 
 
 
 
 
b38fb77
 
c558623
 
852934c
 
 
 
 
c558623
 
 
852934c
 
 
 
 
c558623
 
 
 
 
 
 
 
 
 
 
 
 
 
 
852934c
c558623
 
b38fb77
 
c558623
 
 
 
 
852934c
 
b38fb77
 
 
c558623
 
 
b38fb77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
852934c
b38fb77
 
 
 
852934c
b38fb77
 
c558623
 
 
 
 
852934c
c558623
 
 
 
 
 
852934c
 
 
 
c558623
 
852934c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c558623
 
852934c
 
c558623
 
 
 
 
 
 
 
852934c
c558623
 
 
 
852934c
c558623
 
852934c
c558623
 
b38fb77
c558623
852934c
c558623
 
 
b38fb77
 
 
 
852934c
b38fb77
852934c
b38fb77
 
852934c
b38fb77
 
c558623
 
 
 
 
 
 
 
852934c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c558623
 
852934c
c558623
 
 
 
 
 
 
852934c
 
 
c558623
 
 
 
 
 
 
852934c
c558623
 
852934c
c558623
 
852934c
c558623
 
 
 
 
 
b38fb77
 
852934c
c558623
852934c
c558623
 
852934c
c558623
 
852934c
c558623
 
 
 
 
 
852934c
b38fb77
c558623
b38fb77
 
 
c558623
 
 
852934c
c558623
 
 
b38fb77
c558623
 
b38fb77
 
 
852934c
c558623
852934c
c558623
 
 
 
 
 
 
 
852934c
b38fb77
852934c
c558623
 
 
852934c
c558623
 
 
 
852934c
 
 
c558623
 
852934c
 
 
 
 
 
c558623
 
852934c
c558623
 
852934c
c558623
 
 
 
 
 
 
 
 
 
 
 
b38fb77
 
 
 
 
 
 
 
c558623
 
 
 
 
 
 
 
 
852934c
c558623
 
 
 
 
 
 
 
852934c
b38fb77
852934c
c558623
 
852934c
c558623
852934c
c558623
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b38fb77
 
c558623
 
 
 
852934c
 
c558623
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b38fb77
c558623
 
852934c
 
c558623
 
852934c
c558623
 
 
 
 
 
 
 
 
 
 
 
 
 
 
852934c
c558623
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
852934c
c558623
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>Futuristic Dataset Visualizer v6</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/js-yaml/4.1.0/js-yaml.min.js"></script>
    <style>
        @keyframes aurora {
            0% {
                background-position: 0% 50%;
            }

            50% {
                background-position: 100% 50%;
            }

            100% {
                background-position: 0% 50%;
            }
        }

        html {
            scroll-behavior: smooth;
        }

        body {
            font-family: 'SF Mono', 'Courier New', Courier, monospace;
            background-color: #0D1117;
            color: #E6EDF3;
            background-image: radial-gradient(at 27% 37%, hsla(215, 98%, 61%, 0.1) 0px, transparent 50%),
                radial-gradient(at 97% 21%, hsla(125, 98%, 72%, 0.1) 0px, transparent 50%);
            background-size: 250% 250%;
            animation: aurora 20s ease infinite;
        }

        .glass-card {
            background: rgba(17, 25, 40, 0.75);
            backdrop-filter: blur(16px) saturate(180%);
            -webkit-backdrop-filter: blur(16px) saturate(180%);
            border: 1px solid rgba(255, 255, 255, 0.1);
        }

        .btn-glow:hover {
            box-shadow: 0 0 20px rgba(59, 130, 246, 0.5), 0 0 8px rgba(59, 130, 246, 0.4);
        }

        .card-glow:hover {
            transform: translateY(-4px);
            box-shadow: 0 0 25px rgba(59, 130, 246, 0.3), 0 0 10px rgba(59, 130, 246, 0.2);
        }

        .modal {
            background: rgba(13, 17, 23, 0.85);
            backdrop-filter: blur(16px);
        }

        #modal-canvas {
            cursor: grab;
            touch-action: none;
        }

        #modal-canvas:active {
            cursor: grabbing;
        }

        input[type=range] {
            -webkit-appearance: none;
            background: transparent;
        }

        input[type=range]:focus {
            outline: none;
        }

        input[type=range]::-webkit-slider-runnable-track {
            height: 4px;
            background: rgba(59, 130, 246, 0.5);
            border-radius: 5px;
        }

        input[type=range]::-webkit-slider-thumb {
            -webkit-appearance: none;
            height: 18px;
            width: 18px;
            border-radius: 50%;
            background: #E6EDF3;
            border: 2px solid #0D1117;
            margin-top: -7px;
            cursor: pointer;
        }

        .badge {
            position: absolute;
            top: 0.5rem;
            font-size: 0.7rem;
            font-weight: bold;
            padding: 0.15rem 0.5rem;
            border-radius: 0.375rem;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
        }
    </style>
</head>

<body class="overscroll-none">

    <div class="container mx-auto p-4 lg:p-8">

        <header class="text-center mb-10">
            <h1
                class="text-3xl md:text-5xl font-bold text-transparent bg-clip-text bg-gradient-to-r from-blue-400 to-teal-300 mb-2">
                Dataset Visualizer v6</h1>
            <p class="text-gray-400">Inspect, pan, and zoom your vision datasets with precision.</p>
        </header>

        <div class="glass-card p-4 sm:p-6 rounded-xl mb-10 max-w-3xl mx-auto">
            <div id="control-panel-content">
                <h2 class="text-2xl font-semibold text-blue-300 mb-4 text-center">Get Started</h2>
                <label for="zip-file"
                    class="btn-glow bg-blue-600 text-white flex items-center justify-center w-full p-4 rounded-lg cursor-pointer text-xl transition-all duration-300">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mr-3" fill="none" viewBox="0 0 24 24"
                        stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" />
                    </svg>
                    Upload dataset.zip
                </label>
                <input type="file" id="zip-file" accept=".zip" class="hidden">
                <p id="zip-file-name" class="text-center text-gray-500 mt-2 text-sm h-5"></p>
                <div id="status-container" class="h-6 text-center mt-2"></div>
            </div>
            <div id="labels-panel" class="hidden mt-4 pt-4 border-t border-gray-700">
                <h3 class="text-lg font-semibold text-blue-300 mb-2">Class Labels (Optional)</h3>
                <textarea id="yaml-paste" rows="4"
                    class="w-full bg-gray-900 border border-gray-600 rounded-md p-3 focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="Paste COCO .yaml content here..."></textarea>
            </div>
        </div>

        <div id="image-container-wrapper">
            <div id="empty-state" class="text-center glass-card p-10 rounded-xl">
                <h3 class="text-2xl text-gray-400">Your visualizer is ready.</h3>
                <p class="text-gray-500">Upload a dataset to begin.</p>
            </div>
            <div id="image-container"
                class="hidden grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4 md:gap-6"></div>
        </div>

        <div id="pagination" class="flex justify-center items-center space-x-2 mt-10"></div>
    </div>

    <!-- Modal -->
    <div id="modal-backdrop" class="fixed inset-0 z-50 flex items-center justify-center hidden">
        <div class="modal w-full h-full relative flex items-center justify-center overflow-hidden">
            <div id="modal-spinner" class="absolute z-10">
                <svg class="animate-spin h-10 w-10 text-white" xmlns="http://www.w3.org/2000/svg" fill="none"
                    viewBox="0 0 24 24">
                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                    <path class="opacity-75" fill="currentColor"
                        d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z">
                    </path>
                </svg>
            </div>

            <canvas id="modal-canvas" class="absolute top-0 left-0 w-full h-full"></canvas>

            <div id="modal-info" class="absolute top-4 left-4 glass-card p-3 rounded-lg text-sm z-20 hidden"></div>
            <div id="modal-legend"
                class="absolute bottom-4 left-4 glass-card p-3 rounded-lg max-h-48 overflow-y-auto text-sm z-20 hidden">
            </div>

            <div class="absolute top-4 right-4 z-20 flex flex-col gap-2">
                <button id="modal-close"
                    class="bg-red-600/80 text-white rounded-full w-10 h-10 flex items-center justify-center text-3xl font-bold">×</button>
            </div>

            <button id="prev-image-btn"
                class="absolute left-4 top-1/2 -translate-y-1/2 z-20 glass-card rounded-full p-3"><svg
                    xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24"
                    stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
                </svg></button>
            <button id="next-image-btn"
                class="absolute right-4 top-1/2 -translate-y-1/2 z-20 glass-card rounded-full p-3"><svg
                    xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24"
                    stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
                </svg></button>

            <div class="absolute bottom-4 right-4 z-20 glass-card rounded-lg flex items-center">
                <div class="p-3 flex items-center gap-3 border-r border-gray-600">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                        <path d="M10 12a2 2 0 100-4 2 2 0 000 4z" />
                        <path fill-rule="evenodd"
                            d="M.458 10C3.732 4.943 9.522 3 10 3s6.268 1.943 9.542 7c-3.274 5.057-9.064 7-9.542 7S3.732 15.057.458 10zM14 10a4 4 0 11-8 0 4 4 0 018 0z"
                            clip-rule="evenodd" />
                    </svg>
                    <input type="range" id="line-thickness-slider" min="1" max="15" value="3" class="w-24">
                </div>
                <button id="zoom-out-btn" class="p-3 text-2xl">-</button>
                <button id="reset-view-btn" class="p-3">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                        <path fill-rule="evenodd"
                            d="M4 2a1 1 0 011 1v2.101a7.002 7.002 0 0111.601 2.566 1 1 0 11-1.885.666A5.002 5.002 0 005.999 7H9a1 1 0 010 2H4a1 1 0 01-1-1V3a1 1 0 011-1zm.008 9.057a1 1 0 011.276.61A5.002 5.002 0 0014.001 13H11a1 1 0 110-2h5a1 1 0 011 1v5a1 1 0 11-2 0v-2.101a7.002 7.002 0 01-11.601-2.566 1 1 0 01.61-1.276z"
                            clip-rule="evenodd" />
                    </svg>
                </button>
                <button id="zoom-in-btn" class="p-3 text-2xl">+</button>
                <button id="fullscreen-btn" class="p-3 ml-2 border-l border-gray-600">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                        <path fill-rule="evenodd"
                            d="M3 4a1 1 0 011-1h4a1 1 0 110 2H5v2a1 1 0 11-2 0V4zm12 0a1 1 0 011 1v2a1 1 0 11-2 0V5h-2a1 1 0 110-2h4zM4 17a1 1 0 01-1-1v-2a1 1 0 112 0v2h2a1 1 0 110 2H4zm12 0a1 1 0 01-1-1h-4a1 1 0 110-2h2v-2a1 1 0 112 0v2z"
                            clip-rule="evenodd" />
                    </svg>
                </button>
            </div>
        </div>
    </div>

    <script>
        const dom = {
            zipFileInput: document.getElementById('zip-file'), zipFileNameDisplay: document.getElementById('zip-file-name'),
            yamlPasteArea: document.getElementById('yaml-paste'),
            imageContainer: document.getElementById('image-container'), emptyState: document.getElementById('empty-state'),
            paginationContainer: document.getElementById('pagination'), statusContainer: document.getElementById('status-container'),
            labelsPanel: document.getElementById('labels-panel'),
            modal: {
                backdrop: document.getElementById('modal-backdrop'), canvas: document.getElementById('modal-canvas'),
                closeBtn: document.getElementById('modal-close'), legend: document.getElementById('modal-legend'),
                info: document.getElementById('modal-info'), spinner: document.getElementById('modal-spinner'),
                zoomInBtn: document.getElementById('zoom-in-btn'), zoomOutBtn: document.getElementById('zoom-out-btn'),
                resetViewBtn: document.getElementById('reset-view-btn'), fullscreenBtn: document.getElementById('fullscreen-btn'),
                prevBtn: document.getElementById('prev-image-btn'), nextBtn: document.getElementById('next-image-btn'),
                thicknessSlider: document.getElementById('line-thickness-slider'),
            }
        };

        let state = {
            allImageData: [], classNames: {}, classColors: {}, currentPage: 1, imagesPerPage: 20,
            modal: {
                transform: new DOMMatrix(), initialTransform: new DOMMatrix(), isPanning: false,
                lastPos: { x: 0, y: 0 }, img: null, labelText: '', currentItem: null,
                currentIndex: -1, lineWidth: 3
            }
        };

        // --- Event Listeners ---
        document.addEventListener('DOMContentLoaded', () => {
            dom.zipFileInput.addEventListener('change', handleZipUpload);
            dom.yamlPasteArea.addEventListener('input', handleYamlPaste);
            dom.modal.backdrop.addEventListener('click', (e) => e.target === dom.modal.backdrop && closeModal());
            dom.modal.closeBtn.addEventListener('click', closeModal);
            dom.modal.canvas.addEventListener('mousedown', panStart);
            dom.modal.canvas.addEventListener('mousemove', panMove);
            dom.modal.canvas.addEventListener('mouseup', panEnd);
            dom.modal.canvas.addEventListener('mouseout', panEnd);
            dom.modal.canvas.addEventListener('wheel', handleZoom);
            dom.modal.canvas.addEventListener('touchstart', touchStart, { passive: false });
            dom.modal.canvas.addEventListener('touchmove', touchMove, { passive: false });
            dom.modal.canvas.addEventListener('touchend', panEnd, { passive: false });
            dom.modal.zoomInBtn.addEventListener('click', () => applyZoom(1.2));
            dom.modal.zoomOutBtn.addEventListener('click', () => applyZoom(0.8));
            dom.modal.resetViewBtn.addEventListener('click', () => { state.modal.transform = state.modal.initialTransform.translate(0, 0); redrawModalCanvas(); });
            dom.modal.fullscreenBtn.addEventListener('click', toggleFullscreen);
            dom.modal.thicknessSlider.addEventListener('input', handleThicknessChange);
            dom.modal.prevBtn.addEventListener('click', navigateImage.bind(null, -1));
            dom.modal.nextBtn.addEventListener('click', navigateImage.bind(null, 1));
            window.addEventListener('resize', () => { if (state.modal.img) showModal(state.modal.currentItem); });
            window.addEventListener('keydown', handleKeyPress);
        });

        // --- Core Logic ---
        async function handleZipUpload(event) {
            const file = event.target.files[0];
            if (!file) return;

            showStatus('Processing Zip...', 'loading');
            dom.zipFileNameDisplay.textContent = file.name;
            dom.labelsPanel.classList.remove('hidden');

            try {
                const zip = await JSZip.loadAsync(file);
                const imageFiles = {};
                const labelFiles = {};

                // Separate files into images and labels
                for (const filename in zip.files) {
                    if (zip.files[filename].dir) continue;
                    if (/\.(jpe?g|png|webp)$/i.test(filename)) {
                        imageFiles[filename] = zip.files[filename];
                    } else if (/\.txt$/i.test(filename)) {
                        labelFiles[filename] = zip.files[filename];
                    }
                }

                state.allImageData = [];
                let index = 0;
                // Iterate over all found images
                for (const imagePath in imageFiles) {
                    const imageFile = imageFiles[imagePath];

                    // Construct possible label paths
                    const pathParts = imagePath.split('/');
                    const imageName = pathParts.pop();
                    const baseName = imageName.split('.').slice(0, -1).join('.');
                    const labelName = `${baseName}.txt`;

                    // A common structure is '/images/train/' paired with '/labels/train/'
                    const possibleLabelPath = [...pathParts, labelName].join('/').replace(/images/i, 'labels');

                    const labelFile = labelFiles[possibleLabelPath] || null;

                    // Determine the dataset split (train/val/test) from the path
                    const splitMatch = imagePath.match(/(train|val|validation|test|testing)/i);
                    const split = splitMatch ? splitMatch[0].replace('validation', 'val').replace('testing', 'test') : 'unknown';

                    state.allImageData.push({
                        id: imagePath, // Use the full path as a unique ID
                        image: imageFile,
                        label: labelFile,
                        split: split,
                        originalIndex: index++
                    });
                }

                state.allImageData.sort((a, b) => a.id.localeCompare(b.id));


                if (state.allImageData.length > 0) {
                    dom.imageContainer.classList.remove('hidden');
                    dom.emptyState.classList.add('hidden');
                    renderPage(1);
                    setupPagination();
                    showStatus(`${state.allImageData.length} images loaded.`, 'success');
                } else {
                    showStatus('No images found in the zip file.', 'error');
                }
            } catch (e) { showStatus('Error reading zip file.', 'error'); console.error(e); }
        }


        function handleYamlPaste(event) {
            const yamlString = event.target.value;
            if (!yamlString) { state.classNames = {}; if (state.allImageData.length > 0) renderPage(state.currentPage); return; }
            try {
                const data = jsyaml.load(yamlString);
                state.classNames = (data && Array.isArray(data.names)) ? data.names : {};
                showStatus('YAML class names updated.', 'success');
                if (state.allImageData.length > 0) renderPage(state.currentPage);
            } catch (e) { showStatus('Invalid YAML format.', 'warning'); }
        }

        function handleThicknessChange(event) {
            state.modal.lineWidth = event.target.value;
            redrawModalCanvas();
        }

        function handleKeyPress(e) {
            if (dom.modal.backdrop.classList.contains('hidden')) return;
            if (e.key === 'ArrowLeft') navigateImage(-1);
            if (e.key === 'ArrowRight') navigateImage(1);
            if (e.key === 'Escape') closeModal();
        }

        // --- UI & Drawing ---
        async function renderPage(page) {
            state.currentPage = page;
            dom.imageContainer.innerHTML = '';
            const paginatedItems = state.allImageData.slice((page - 1) * state.imagesPerPage, page * state.imagesPerPage);

            for (const item of paginatedItems) {
                const card = document.createElement('div');
                card.className = 'relative card-glow glass-card rounded-xl overflow-hidden transition-all duration-300 cursor-pointer';

                const splitColors = {
                    train: 'bg-blue-600/90',
                    val: 'bg-purple-600/90',
                    test: 'bg-green-600/90',
                };

                const badgeColorClass = splitColors[item.split.toLowerCase()] || 'bg-gray-500/90';

                const splitBadge = item.split !== 'unknown'
                    ? `<div class="badge left-2 ${badgeColorClass} text-white">${item.split.toUpperCase()}</div>`
                    : '';
                const noLabelBadge = !item.label ? `<div class="badge right-2 bg-yellow-600/90 text-white">NO LABEL</div>` : '';

                card.innerHTML = `
                    <div class="relative">
                        <canvas class="w-full h-40 md:h-48 object-cover bg-gray-900/50"></canvas>
                        ${splitBadge}
                        ${noLabelBadge}
                    </div>
                    <h3 class="p-3 font-semibold text-sm text-blue-300 truncate">${item.image.name.split('/').pop()}</h3>`;

                dom.imageContainer.appendChild(card);
                card.addEventListener('click', () => showModal(item));

                const canvas = card.querySelector('canvas');
                const ctx = canvas.getContext('2d');
                const img = new Image();
                img.src = URL.createObjectURL(await item.image.async('blob'));
                img.onload = async () => {
                    canvas.width = img.width; canvas.height = img.height;
                    ctx.drawImage(img, 0, 0);
                    if (item.label) {
                        drawAnnotations(ctx, await item.label.async('string'), img.width, img.height);
                    }
                    URL.revokeObjectURL(img.src);
                };
            }
            updateActivePagination();
        }

        function drawAnnotations(ctx, labelText, w, h, isModal = false) {
            if (!labelText) return;
            const lines = labelText.trim().split('\n').filter(line => line.trim() !== '');
            if (lines.length === 0) return;

            const isDetection = lines[0].trim().split(' ').length === 5;
            const uniqueClasses = new Set();

            lines.forEach(line => {
                const parts = line.split(' ').map(parseFloat);
                const classId = parts[0];
                uniqueClasses.add(classId);
                const color = generateColor(classId);
                ctx.strokeStyle = color;
                const baseLineWidth = isModal ? state.modal.lineWidth : 2;
                ctx.lineWidth = baseLineWidth / (isModal ? state.modal.transform.a : 1);

                ctx.beginPath();
                if (isDetection) { // Bounding Box: [class, x_center, y_center, width, height]
                    const [, xc, yc, width, height] = parts;
                    ctx.rect((xc - width / 2) * w, (yc - height / 2) * h, width * w, height * h);
                } else { // Segmentation: [class, x1, y1, x2, y2, ...]
                    const points = parts.slice(1);
                    ctx.moveTo(points[0] * w, points[1] * h);
                    for (let i = 2; i < points.length; i += 2) ctx.lineTo(points[i] * w, points[i + 1] * h);
                    ctx.closePath();
                }
                ctx.stroke();
            });
            if (isModal) buildLegend(uniqueClasses);
        }

        // --- Modal, Pan/Zoom, Gallery ---
        async function showModal(item) {
            state.modal.currentItem = item;
            state.modal.currentIndex = state.allImageData.findIndex(d => d.id === item.id);

            dom.modal.backdrop.classList.remove('hidden');
            dom.modal.spinner.classList.remove('hidden');
            dom.modal.legend.classList.add('hidden');
            dom.modal.info.classList.add('hidden');

            const canvas = dom.modal.canvas;
            const ctx = canvas.getContext('2d');
            canvas.width = canvas.clientWidth; canvas.height = canvas.clientHeight;
            ctx.clearRect(0, 0, canvas.width, canvas.height);

            if (state.modal.img && state.modal.img.src.startsWith('blob:')) {
                URL.revokeObjectURL(state.modal.img.src);
            }

            state.modal.img = new Image();
            state.modal.labelText = item.label ? await item.label.async('string') : '';

            state.modal.img.onerror = () => {
                console.error("Modal image failed to load.");
                showStatus('Error: Could not load the full-size image.', 'error');
                closeModal();
            };

            state.modal.img.onload = () => {
                if (!state.modal.img || !state.modal.currentItem) return;
                canvas.width = canvas.clientWidth; canvas.height = canvas.clientHeight;

                const hRatio = canvas.width / state.modal.img.width;
                const vRatio = canvas.height / state.modal.img.height;
                const initialScale = Math.min(hRatio, vRatio) * 0.9;

                state.modal.transform = new DOMMatrix()
                    .translate(canvas.width / 2, canvas.height / 2)
                    .scale(initialScale, initialScale)
                    .translate(-state.modal.img.width / 2, -state.modal.img.height / 2);

                state.modal.initialTransform = state.modal.transform.translate(0, 0);

                dom.modal.spinner.classList.add('hidden');
                dom.modal.legend.classList.remove('hidden');
                dom.modal.info.classList.remove('hidden');

                // Populate modal info
                const splitText = item.split !== 'unknown' ? `<span class="block mt-1 text-xs font-bold text-blue-300 bg-blue-900/50 px-2 py-1 rounded-full">${item.split.toUpperCase()}</span>` : '';
                dom.modal.info.innerHTML = `<p class="truncate">${item.image.name.split('/').pop()}</p>${splitText}`;

                redrawModalCanvas();
            };

            state.modal.img.src = URL.createObjectURL(await item.image.async('blob'));
        }

        function redrawModalCanvas() {
            if (!state.modal.img) return;
            const canvas = dom.modal.canvas, ctx = canvas.getContext('2d');
            ctx.save();
            ctx.setTransform(1, 0, 0, 1, 0, 0);
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.setTransform(state.modal.transform);
            ctx.drawImage(state.modal.img, 0, 0);
            drawAnnotations(ctx, state.modal.labelText, state.modal.img.width, state.modal.img.height, true);
            ctx.restore();
        }

        function navigateImage(direction) {
            if (state.modal.currentIndex === -1) return;
            let newIndex = state.modal.currentIndex + direction;
            if (newIndex < 0) newIndex = state.allImageData.length - 1;
            if (newIndex >= state.allImageData.length) newIndex = 0;
            showModal(state.allImageData[newIndex]);
        }

        function panStart(e) { e.preventDefault(); state.modal.isPanning = true; state.modal.lastPos = { x: e.clientX, y: e.clientY }; }
        function panMove(e) {
            e.preventDefault();
            if (!state.modal.isPanning) return;
            state.modal.transform.translateSelf((e.clientX - state.modal.lastPos.x) / state.modal.transform.a, (e.clientY - state.modal.lastPos.y) / state.modal.transform.d);
            redrawModalCanvas();
            state.modal.lastPos = { x: e.clientX, y: e.clientY };
        }
        function panEnd() { state.modal.isPanning = false; }

        function applyZoom(scaleAmount, clientX, clientY) {
            const canvas = dom.modal.canvas;
            const pt = new DOMPoint(clientX ?? canvas.clientWidth / 2, clientY ?? canvas.clientHeight / 2);
            const transformedPt = pt.matrixTransform(state.modal.transform.inverse());
            state.modal.transform.translateSelf(transformedPt.x, transformedPt.y)
                .scaleSelf(scaleAmount, scaleAmount).translateSelf(-transformedPt.x, -transformedPt.y);
            redrawModalCanvas();
        }

        function handleZoom(e) { e.preventDefault(); applyZoom(e.deltaY > 0 ? 0.95 : 1.05, e.clientX, e.clientY); }

        function touchStart(e) {
            if (e.touches.length === 1) { e.preventDefault(); panStart(e.touches[0]); }
            if (e.touches.length === 2) { e.preventDefault(); state.modal.lastPos = { dist: Math.hypot(e.touches[0].clientX - e.touches[1].clientX, e.touches[0].clientY - e.touches[1].clientY) }; }
        }

        function touchMove(e) {
            e.preventDefault();
            if (e.touches.length === 1) panMove(e.touches[0]);
            if (e.touches.length === 2) {
                const newDist = Math.hypot(e.touches[0].clientX - e.touches[1].clientX, e.touches[0].clientY - e.touches[1].clientY);
                applyZoom(newDist / state.modal.lastPos.dist, (e.touches[0].clientX + e.touches[1].clientX) / 2, (e.touches[0].clientY + e.touches[1].clientY) / 2);
                state.modal.lastPos.dist = newDist;
            }
        }

        function closeModal() {
            dom.modal.backdrop.classList.add('hidden');
            if (state.modal.img && state.modal.img.src.startsWith('blob:')) {
                URL.revokeObjectURL(state.modal.img.src);
            }
            state.modal.img = null;
            state.modal.currentItem = null;
            state.modal.currentIndex = -1;
            if (document.fullscreenElement) document.exitFullscreen();
        }

        function toggleFullscreen() {
            if (!document.fullscreenElement) {
                dom.modal.backdrop.requestFullscreen().catch(err => alert(`Error trying to enable full-screen mode: ${err.message} (${err.name})`));
            } else { document.exitFullscreen(); }
        }

        // --- Helpers ---
        function generateColor(classId) {
            if (!state.classColors[classId]) {
                const hue = (classId * 137.508) % 360;
                state.classColors[classId] = `hsl(${hue}, 95%, 65%)`;
            }
            return state.classColors[classId];
        }

        function buildLegend(classIds) {
            dom.modal.legend.innerHTML = '';
            if (classIds.size > 0) {
                const list = document.createElement('ul');
                classIds.forEach(id => {
                    const name = state.classNames[id] || `Class ${id}`;
                    list.innerHTML += `<li class="flex items-center gap-2 mt-1"><span class="w-4 h-4 rounded-full border border-white/50" style="background-color:${generateColor(id)};"></span>${name}</li>`;
                });
                dom.modal.legend.appendChild(list);
            } else {
                dom.modal.legend.innerHTML = '<p class="text-gray-400">No annotations</p>';
            }
        }

        function setupPagination() {
            dom.paginationContainer.innerHTML = '';
            const pageCount = Math.ceil(state.allImageData.length / state.imagesPerPage);
            if (pageCount > 1) {
                for (let i = 1; i <= pageCount; i++) {
                    const button = document.createElement('button');
                    button.innerText = i;
                    button.dataset.page = i;
                    button.className = "px-4 py-2 rounded-md bg-gray-800 text-gray-300 hover:bg-blue-600 transition-colors";
                    button.addEventListener('click', (e) => renderPage(parseInt(e.target.dataset.page)));
                    dom.paginationContainer.appendChild(button);
                }
            }
            updateActivePagination();
        }

        function updateActivePagination() {
            dom.paginationContainer.querySelectorAll('button').forEach(btn => {
                const isActive = parseInt(btn.dataset.page) === state.currentPage;
                btn.classList.toggle('bg-blue-600', isActive);
                btn.classList.toggle('text-white', isActive);
            });
        }

        function showStatus(message, type = 'info') {
            const styles = {
                info: 'text-gray-400', success: 'text-green-400',
                warning: 'text-yellow-400', error: 'text-red-500', loading: 'text-blue-400'
            };
            dom.statusContainer.innerHTML = `<p class="${styles[type]}">${message}</p>`;
        }
    </script>
</body>

</html>