File size: 36,404 Bytes
dc5cf56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Vehicle Tracking System</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@3.18.0/dist/tf.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/coco-ssd@2.2.2/dist/coco-ssd.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        .video-container {
            position: relative;
            width: 100%;
            height: 0;
            padding-bottom: 56.25%;
            background-color: #1a202c;
            border-radius: 0.5rem;
            overflow: hidden;
        }
        .video-container video, .video-container canvas {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        .plate-highlight {
            position: absolute;
            border: 2px solid #3B82F6;
            background-color: rgba(59, 130, 246, 0.2);
            z-index: 10;
        }
        .processing-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.7);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 20;
            color: white;
            font-size: 1.5rem;
            border-radius: 0.5rem;
        }
        .pulse {
            animation: pulse 2s infinite;
        }
        @keyframes pulse {
            0% { opacity: 0.6; }
            50% { opacity: 1; }
            100% { opacity: 0.6; }
        }
        .result-card {
            transition: all 0.3s ease;
        }
        .result-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1);
        }
    </style>
</head>
<body class="bg-gray-100 min-h-screen">
    <div class="container mx-auto px-4 py-8">
        <!-- Header -->
        <header class="mb-8 text-center">
            <h1 class="text-4xl font-bold text-blue-600 mb-2">
                <i class="fas fa-car-alt mr-2"></i>AI Vehicle Tracking System
            </h1>
            <p class="text-gray-600">Real-time car tracking with license plate recognition powered by Ultralytics and Claude AI</p>
        </header>

        <!-- Main Content -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <!-- Video Feed Section -->
            <div class="lg:col-span-2">
                <div class="bg-white rounded-xl shadow-lg p-6">
                    <div class="flex justify-between items-center mb-4">
                        <h2 class="text-xl font-semibold text-gray-800">
                            <i class="fas fa-video mr-2 text-blue-500"></i>Live Camera Feed
                        </h2>
                        <div class="flex space-x-2">
                            <button id="startBtn" class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-lg flex items-center">
                                <i class="fas fa-play mr-2"></i> Start
                            </button>
                            <button id="stopBtn" disabled class="bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded-lg flex items-center">
                                <i class="fas fa-stop mr-2"></i> Stop
                            </button>
                            <button id="uploadBtn" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg flex items-center">
                                <i class="fas fa-upload mr-2"></i> Upload
                            </button>
                            <input type="file" id="fileInput" accept="image/*,video/*" class="hidden">
                        </div>
                    </div>

                    <div class="video-container" id="videoContainer">
                        <video id="videoFeed" autoplay muted playsinline class="hidden"></video>
                        <canvas id="canvasOutput"></canvas>
                        <div id="processingOverlay" class="processing-overlay hidden">
                            <div class="text-center">
                                <i class="fas fa-cog fa-spin text-4xl mb-2 text-blue-400"></i>
                                <p class="pulse">Processing frame...</p>
                            </div>
                        </div>
                    </div>

                    <div class="mt-4 grid grid-cols-2 gap-4">
                        <div class="bg-gray-50 p-4 rounded-lg">
                            <h3 class="font-medium text-gray-700 mb-2">
                                <i class="fas fa-chart-line mr-2 text-blue-500"></i>Detection Stats
                            </h3>
                            <div class="space-y-2">
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Vehicles Detected:</span>
                                    <span id="vehicleCount" class="font-semibold">0</span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">License Plates:</span>
                                    <span id="plateCount" class="font-semibold">0</span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Processing Time:</span>
                                    <span id="processingTime" class="font-semibold">0ms</span>
                                </div>
                            </div>
                        </div>
                        <div class="bg-gray-50 p-4 rounded-lg">
                            <h3 class="font-medium text-gray-700 mb-2">
                                <i class="fas fa-sliders-h mr-2 text-blue-500"></i>Settings
                            </h3>
                            <div class="space-y-3">
                                <div>
                                    <label class="block text-sm text-gray-600 mb-1">Confidence Threshold</label>
                                    <input type="range" id="confidenceSlider" min="0.1" max="0.9" step="0.1" value="0.5" class="w-full">
                                    <div class="flex justify-between text-xs text-gray-500">
                                        <span>10%</span>
                                        <span id="confidenceValue">50%</span>
                                        <span>90%</span>
                                    </div>
                                </div>
                                <div class="flex items-center">
                                    <input type="checkbox" id="enableOCR" checked class="mr-2">
                                    <label for="enableOCR" class="text-sm text-gray-600">Enable OCR Processing</label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Results Section -->
            <div class="lg:col-span-1">
                <div class="bg-white rounded-xl shadow-lg p-6 h-full">
                    <div class="flex justify-between items-center mb-4">
                        <h2 class="text-xl font-semibold text-gray-800">
                            <i class="fas fa-clipboard-list mr-2 text-blue-500"></i>Detection Results
                        </h2>
                        <button id="clearResults" class="text-gray-500 hover:text-gray-700">
                            <i class="fas fa-trash-alt"></i>
                        </button>
                    </div>

                    <div id="resultsContainer" class="space-y-4 max-h-[calc(100vh-250px)] overflow-y-auto pr-2">
                        <div class="text-center py-10 text-gray-400" id="emptyResults">
                            <i class="fas fa-car-side text-4xl mb-3"></i>
                            <p>No detections yet. Start the camera or upload media to begin.</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- API Status -->
        <div class="mt-8 bg-white rounded-xl shadow-lg p-6">
            <h2 class="text-xl font-semibold text-gray-800 mb-4">
                <i class="fas fa-plug mr-2 text-blue-500"></i>API Status
            </h2>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div class="bg-gray-50 p-4 rounded-lg">
                    <div class="flex items-center mb-2">
                        <div id="ultralyticsStatus" class="w-3 h-3 rounded-full bg-gray-400 mr-2"></div>
                        <span class="font-medium">Ultralytics Model</span>
                    </div>
                    <p class="text-sm text-gray-600">Vehicle detection and license plate extraction</p>
                </div>
                <div class="bg-gray-50 p-4 rounded-lg">
                    <div class="flex items-center mb-2">
                        <div id="claudeStatus" class="w-3 h-3 rounded-full bg-gray-400 mr-2"></div>
                        <span class="font-medium">Claude API</span>
                    </div>
                    <p class="text-sm text-gray-600">OCR processing for license plates</p>
                </div>
                <div class="bg-gray-50 p-4 rounded-lg">
                    <div class="flex items-center mb-2">
                        <div id="systemStatus" class="w-3 h-3 rounded-full bg-gray-400 mr-2"></div>
                        <span class="font-medium">System Status</span>
                    </div>
                    <p class="text-sm text-gray-600" id="systemStatusText">Initializing...</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Result Card Template -->
    <template id="resultCardTemplate">
        <div class="result-card bg-gray-50 rounded-lg p-4 border border-gray-200">
            <div class="flex justify-between items-start mb-2">
                <div>
                    <span class="font-semibold text-blue-600 detection-type">Vehicle</span>
                    <span class="text-xs bg-blue-100 text-blue-800 px-2 py-1 rounded-full ml-2 confidence">85%</span>
                </div>
                <span class="text-xs text-gray-500 timestamp">12:34:56 PM</span>
            </div>
            <div class="flex mb-3">
                <div class="w-16 h-16 bg-gray-200 rounded-md overflow-hidden mr-3 thumbnail-container">
                    <img src="" alt="Detection" class="w-full h-full object-cover thumbnail">
                </div>
                <div class="flex-1">
                    <div class="text-sm mb-1">
                        <span class="text-gray-600">Plate:</span>
                        <span class="font-medium ml-1 plate-number">Not detected</span>
                    </div>
                    <div class="text-sm">
                        <span class="text-gray-600">Make/Model:</span>
                        <span class="font-medium ml-1 vehicle-model">Unknown</span>
                    </div>
                </div>
            </div>
            <div class="flex justify-end space-x-2">
                <button class="text-xs bg-blue-50 text-blue-600 px-3 py-1 rounded hover:bg-blue-100 view-btn">
                    <i class="fas fa-search mr-1"></i> View
                </button>
                <button class="text-xs bg-gray-100 text-gray-600 px-3 py-1 rounded hover:bg-gray-200 export-btn">
                    <i class="fas fa-download mr-1"></i> Export
                </button>
            </div>
        </div>
    </template>

    <!-- Modal for detailed view -->
    <div id="detailModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-lg w-full max-w-2xl max-h-[90vh] overflow-auto">
            <div class="p-4 border-b flex justify-between items-center">
                <h3 class="text-lg font-semibold">Detection Details</h3>
                <button id="closeModal" class="text-gray-500 hover:text-gray-700">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="p-6">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <h4 class="font-medium text-gray-700 mb-2">Detection Image</h4>
                        <img id="modalImage" src="" alt="Detection" class="w-full rounded-lg border border-gray-200">
                    </div>
                    <div>
                        <h4 class="font-medium text-gray-700 mb-2">Details</h4>
                        <div class="space-y-3">
                            <div>
                                <label class="block text-sm text-gray-500">Detection Type</label>
                                <p id="modalType" class="font-medium">Vehicle</p>
                            </div>
                            <div>
                                <label class="block text-sm text-gray-500">Confidence</label>
                                <p id="modalConfidence" class="font-medium">85%</p>
                            </div>
                            <div>
                                <label class="block text-sm text-gray-500">License Plate</label>
                                <p id="modalPlate" class="font-medium">ABC123</p>
                            </div>
                            <div>
                                <label class="block text-sm text-gray-500">Vehicle Make/Model</label>
                                <p id="modalModel" class="font-medium">Toyota Camry</p>
                            </div>
                            <div>
                                <label class="block text-sm text-gray-500">Timestamp</label>
                                <p id="modalTimestamp" class="font-medium">12:34:56 PM</p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="mt-6 pt-4 border-t">
                    <h4 class="font-medium text-gray-700 mb-2">Raw Data</h4>
                    <pre id="modalRawData" class="bg-gray-50 p-3 rounded text-xs overflow-x-auto"></pre>
                </div>
            </div>
            <div class="p-4 border-t flex justify-end space-x-3">
                <button class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">Export as JSON</button>
                <button class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">Save to Database</button>
            </div>
        </div>
    </div>

    <script>
        // DOM Elements
        const videoFeed = document.getElementById('videoFeed');
        const canvasOutput = document.getElementById('canvasOutput');
        const videoContainer = document.getElementById('videoContainer');
        const startBtn = document.getElementById('startBtn');
        const stopBtn = document.getElementById('stopBtn');
        const uploadBtn = document.getElementById('uploadBtn');
        const fileInput = document.getElementById('fileInput');
        const processingOverlay = document.getElementById('processingOverlay');
        const resultsContainer = document.getElementById('resultsContainer');
        const emptyResults = document.getElementById('emptyResults');
        const confidenceSlider = document.getElementById('confidenceSlider');
        const confidenceValue = document.getElementById('confidenceValue');
        const enableOCR = document.getElementById('enableOCR');
        const clearResults = document.getElementById('clearResults');
        const vehicleCount = document.getElementById('vehicleCount');
        const plateCount = document.getElementById('plateCount');
        const processingTime = document.getElementById('processingTime');
        const ultralyticsStatus = document.getElementById('ultralyticsStatus');
        const claudeStatus = document.getElementById('claudeStatus');
        const systemStatus = document.getElementById('systemStatus');
        const systemStatusText = document.getElementById('systemStatusText');
        const detailModal = document.getElementById('detailModal');
        const closeModal = document.getElementById('closeModal');
        const modalImage = document.getElementById('modalImage');
        const modalType = document.getElementById('modalType');
        const modalConfidence = document.getElementById('modalConfidence');
        const modalPlate = document.getElementById('modalPlate');
        const modalModel = document.getElementById('modalModel');
        const modalTimestamp = document.getElementById('modalTimestamp');
        const modalRawData = document.getElementById('modalRawData');

        // State variables
        let stream = null;
        let model = null;
        let isProcessing = false;
        let detectionHistory = [];
        let currentDetections = [];
        let confidenceThreshold = 0.5;
        let ctx = canvasOutput.getContext('2d');
        let animationId = null;
        let currentMediaType = null; // 'camera' or 'file'

        // Initialize
        document.addEventListener('DOMContentLoaded', async () => {
            // Set up canvas to match video container aspect ratio
            resizeCanvas();
            
            // Event listeners
            startBtn.addEventListener('click', startCamera);
            stopBtn.addEventListener('click', stopCamera);
            uploadBtn.addEventListener('click', () => fileInput.click());
            fileInput.addEventListener('change', handleFileUpload);
            confidenceSlider.addEventListener('input', updateConfidenceThreshold);
            clearResults.addEventListener('click', clearDetectionHistory);
            closeModal.addEventListener('click', () => detailModal.classList.add('hidden'));
            
            // Initialize models
            await initializeModels();
            
            // Update system status
            updateSystemStatus();
        });

        // Resize canvas to match container
        function resizeCanvas() {
            const containerWidth = videoContainer.clientWidth;
            const containerHeight = videoContainer.clientHeight;
            canvasOutput.width = containerWidth;
            canvasOutput.height = containerHeight;
        }

        // Initialize AI models
        async function initializeModels() {
            try {
                systemStatusText.textContent = "Loading Ultralytics model...";
                ultralyticsStatus.classList.remove('bg-gray-400', 'bg-red-500');
                ultralyticsStatus.classList.add('bg-yellow-500');
                
                // In a real implementation, we would load the actual Ultralytics model here
                // For this demo, we'll use COCO-SSD as a placeholder
                model = await cocoSsd.load();
                
                ultralyticsStatus.classList.remove('bg-yellow-500');
                ultralyticsStatus.classList.add('bg-green-500');
                systemStatusText.textContent = "Models loaded successfully";
                systemStatus.classList.remove('bg-gray-400');
                systemStatus.classList.add('bg-green-500');
                
                // Simulate Claude API connection
                setTimeout(() => {
                    claudeStatus.classList.remove('bg-gray-400');
                    claudeStatus.classList.add('bg-green-500');
                }, 1500);
            } catch (error) {
                console.error("Error loading models:", error);
                ultralyticsStatus.classList.remove('bg-yellow-500');
                ultralyticsStatus.classList.add('bg-red-500');
                systemStatusText.textContent = "Error loading models";
                systemStatus.classList.remove('bg-gray-400');
                systemStatus.classList.add('bg-red-500');
            }
        }

        // Update system status UI
        function updateSystemStatus() {
            // This would be more comprehensive in a real implementation
            const statusElements = [
                { element: ultralyticsStatus, condition: model !== null },
                { element: claudeStatus, condition: true }, // Simulated as connected
                { element: systemStatus, condition: model !== null }
            ];
            
            statusElements.forEach(item => {
                if (item.condition) {
                    item.element.classList.remove('bg-gray-400', 'bg-red-500', 'bg-yellow-500');
                    item.element.classList.add('bg-green-500');
                }
            });
        }

        // Start camera feed
        async function startCamera() {
            try {
                currentMediaType = 'camera';
                stream = await navigator.mediaDevices.getUserMedia({ 
                    video: { width: 1280, height: 720, facingMode: 'environment' },
                    audio: false 
                });
                
                videoFeed.srcObject = stream;
                videoFeed.classList.remove('hidden');
                startBtn.disabled = true;
                stopBtn.disabled = false;
                uploadBtn.disabled = true;
                
                // Start processing frames
                processVideo();
            } catch (error) {
                console.error("Error accessing camera:", error);
                alert("Could not access the camera. Please ensure you've granted camera permissions.");
            }
        }

        // Stop camera feed
        function stopCamera() {
            if (stream) {
                stream.getTracks().forEach(track => track.stop());
                stream = null;
            }
            
            if (animationId) {
                cancelAnimationFrame(animationId);
                animationId = null;
            }
            
            videoFeed.classList.add('hidden');
            startBtn.disabled = false;
            stopBtn.disabled = true;
            uploadBtn.disabled = false;
            isProcessing = false;
            
            // Clear canvas
            ctx.clearRect(0, 0, canvasOutput.width, canvasOutput.height);
        }

        // Handle file upload
        function handleFileUpload(event) {
            const file = event.target.files[0];
            if (!file) return;
            
            currentMediaType = 'file';
            const fileURL = URL.createObjectURL(file);
            
            if (file.type.startsWith('image/')) {
                processImageFile(fileURL);
            } else if (file.type.startsWith('video/')) {
                processVideoFile(fileURL);
            }
            
            // Reset file input
            event.target.value = '';
        }

        // Process image file
        function processImageFile(fileURL) {
            const img = new Image();
            img.onload = async () => {
                // Set canvas dimensions to match image
                canvasOutput.width = img.width;
                canvasOutput.height = img.height;
                
                // Draw image to canvas
                ctx.drawImage(img, 0, 0, img.width, img.height);
                
                // Process the image
                await detectObjects(canvasOutput);
            };
            img.src = fileURL;
        }

        // Process video file
        function processVideoFile(fileURL) {
            videoFeed.src = fileURL;
            videoFeed.classList.remove('hidden');
            startBtn.disabled = true;
            stopBtn.disabled = false;
            uploadBtn.disabled = true;
            
            videoFeed.onloadedmetadata = () => {
                // Set canvas dimensions to match video
                canvasOutput.width = videoFeed.videoWidth;
                canvasOutput.height = videoFeed.videoHeight;
                
                // Start processing
                processVideo();
            };
            
            videoFeed.play();
        }

        // Process video frames
        function processVideo() {
            if (!isProcessing) {
                isProcessing = true;
                processingOverlay.classList.remove('hidden');
            }
            
            // Draw video frame to canvas
            ctx.drawImage(videoFeed, 0, 0, canvasOutput.width, canvasOutput.height);
            
            // Detect objects in the frame
            detectObjects(canvasOutput).then(() => {
                if (stream || currentMediaType === 'file') {
                    animationId = requestAnimationFrame(processVideo);
                } else {
                    isProcessing = false;
                    processingOverlay.classList.add('hidden');
                }
            });
        }

        // Detect objects in frame
        async function detectObjects(canvas) {
            if (!model) return;
            
            const startTime = performance.now();
            
            try {
                // Get predictions from model
                const predictions = await model.detect(canvas);
                
                // Filter predictions based on confidence threshold and relevant classes
                const relevantClasses = ['car', 'truck', 'bus', 'motorcycle'];
                const vehiclePredictions = predictions.filter(
                    p => relevantClasses.includes(p.class) && p.score >= confidenceThreshold
                );
                
                // Clear previous detections
                currentDetections = [];
                
                // Process each vehicle detection
                for (const prediction of vehiclePredictions) {
                    const { bbox, class: className, score } = prediction;
                    const [x, y, width, height] = bbox;
                    
                    // Draw bounding box
                    ctx.strokeStyle = '#3B82F6';
                    ctx.lineWidth = 2;
                    ctx.strokeRect(x, y, width, height);
                    
                    // Draw label background
                    ctx.fillStyle = '#3B82F6';
                    const textWidth = ctx.measureText(`${className} ${Math.round(score * 100)}%`).width;
                    ctx.fillRect(x, y - 20, textWidth + 10, 20);
                    
                    // Draw label text
                    ctx.fillStyle = 'white';
                    ctx.font = '14px Arial';
                    ctx.fillText(`${className} ${Math.round(score * 100)}%`, x + 5, y - 5);
                    
                    // Simulate license plate detection (in a real app, this would use Ultralytics)
                    const hasPlate = Math.random() > 0.3; // 70% chance of detecting a plate
                    let plateText = null;
                    let plateBbox = null;
                    
                    if (hasPlate && enableOCR.checked) {
                        // Simulate plate position (bottom center of vehicle)
                        const plateWidth = width * 0.6;
                        const plateHeight = height * 0.15;
                        const plateX = x + (width - plateWidth) / 2;
                        const plateY = y + height - plateHeight * 0.8;
                        
                        plateBbox = [plateX, plateY, plateWidth, plateHeight];
                        
                        // Draw plate bounding box
                        ctx.strokeStyle = '#10B981';
                        ctx.lineWidth = 2;
                        ctx.strokeRect(plateX, plateY, plateWidth, plateHeight);
                        
                        // Simulate OCR with Claude API (in a real app, this would make an API call)
                        plateText = simulateClaudeOCR(canvas, plateBbox);
                        
                        // Draw plate text
                        ctx.fillStyle = '#10B981';
                        ctx.font = '12px Arial';
                        ctx.fillText(plateText || 'Processing...', plateX + 5, plateY + 15);
                    }
                    
                    // Save detection data
                    const detection = {
                        type: className,
                        confidence: score,
                        bbox: [x, y, width, height],
                        plate: plateText ? {
                            text: plateText,
                            bbox: plateBbox
                        } : null,
                        timestamp: new Date().toLocaleTimeString(),
                        imageData: canvas.toDataURL('image/jpeg', 0.7)
                    };
                    
                    currentDetections.push(detection);
                }
                
                // Update stats
                updateDetectionStats(vehiclePredictions.length, currentDetections.filter(d => d.plate).length);
                
                // Add to history and update UI
                if (currentDetections.length > 0) {
                    addToDetectionHistory(currentDetections);
                }
                
                // Update processing time
                const endTime = performance.now();
                processingTime.textContent = `${Math.round(endTime - startTime)}ms`;
                
            } catch (error) {
                console.error("Detection error:", error);
            } finally {
                processingOverlay.classList.add('hidden');
                isProcessing = false;
            }
        }

        // Simulate Claude API OCR processing
        function simulateClaudeOCR(canvas, bbox) {
            // In a real implementation, this would:
            // 1. Extract the license plate region from the canvas
            // 2. Send to Claude API for OCR processing
            // 3. Return the recognized text
            
            // For demo purposes, generate random plate numbers
            const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            const numbers = '0123456789';
            
            let plateText = '';
            
            // Random format: 3 letters + 3 numbers (e.g., ABC123)
            for (let i = 0; i < 3; i++) {
                plateText += letters.charAt(Math.floor(Math.random() * letters.length));
            }
            for (let i = 0; i < 3; i++) {
                plateText += numbers.charAt(Math.floor(Math.random() * numbers.length));
            }
            
            // 10% chance to return null (simulating OCR failure)
            return Math.random() > 0.1 ? plateText : null;
        }

        // Update confidence threshold
        function updateConfidenceThreshold() {
            confidenceThreshold = parseFloat(confidenceSlider.value);
            confidenceValue.textContent = `${Math.round(confidenceThreshold * 100)}%`;
        }

        // Update detection stats
        function updateDetectionStats(vehicles, plates) {
            vehicleCount.textContent = vehicles;
            plateCount.textContent = plates;
        }

        // Add detections to history
        function addToDetectionHistory(detections) {
            emptyResults.classList.add('hidden');
            
            detections.forEach(detection => {
                detectionHistory.unshift(detection);
                
                // Create result card
                const template = document.getElementById('resultCardTemplate');
                const clone = template.content.cloneNode(true);
                
                const card = clone.querySelector('.result-card');
                card.querySelector('.detection-type').textContent = detection.type;
                card.querySelector('.confidence').textContent = `${Math.round(detection.confidence * 100)}%`;
                card.querySelector('.timestamp').textContent = detection.timestamp;
                
                const thumbnail = card.querySelector('.thumbnail');
                thumbnail.src = detection.imageData;
                
                if (detection.plate) {
                    card.querySelector('.plate-number').textContent = detection.plate.text;
                } else {
                    card.querySelector('.plate-number').textContent = 'Not detected';
                }
                
                // Simulate vehicle make/model detection
                const makes = ['Toyota', 'Honda', 'Ford', 'Chevrolet', 'BMW', 'Mercedes', 'Tesla'];
                const models = ['Camry', 'Civic', 'F-150', 'Silverado', '3 Series', 'C-Class', 'Model 3'];
                const randomMake = makes[Math.floor(Math.random() * makes.length)];
                const randomModel = models[Math.floor(Math.random() * models.length)];
                card.querySelector('.vehicle-model').textContent = `${randomMake} ${randomModel}`;
                
                // Add click handlers
                card.querySelector('.view-btn').addEventListener('click', () => showDetectionDetails(detection));
                card.querySelector('.export-btn').addEventListener('click', () => exportDetection(detection));
                
                // Add to results container
                resultsContainer.prepend(card);
            });
        }

        // Show detection details in modal
        function showDetectionDetails(detection) {
            modalImage.src = detection.imageData;
            modalType.textContent = detection.type;
            modalConfidence.textContent = `${Math.round(detection.confidence * 100)}%`;
            modalPlate.textContent = detection.plate ? detection.plate.text : 'Not detected';
            
            // Simulate vehicle make/model
            const makes = ['Toyota', 'Honda', 'Ford', 'Chevrolet', 'BMW', 'Mercedes', 'Tesla'];
            const models = ['Camry', 'Civic', 'F-150', 'Silverado', '3 Series', 'C-Class', 'Model 3'];
            const randomMake = makes[Math.floor(Math.random() * makes.length)];
            const randomModel = models[Math.floor(Math.random() * models.length)];
            modalModel.textContent = `${randomMake} ${randomModel}`;
            
            modalTimestamp.textContent = detection.timestamp;
            modalRawData.textContent = JSON.stringify(detection, null, 2);
            
            detailModal.classList.remove('hidden');
        }

        // Export detection data
        function exportDetection(detection) {
            // In a real implementation, this would save the data or image
            console.log("Exporting detection:", detection);
            alert(`Detection data for ${detection.plate?.text || 'unknown plate'} has been exported.`);
        }

        // Clear detection history
        function clearDetectionHistory() {
            detectionHistory = [];
            resultsContainer.innerHTML = '';
            emptyResults.classList.remove('hidden');
        }

        // Handle window resize
        window.addEventListener('resize', () => {
            if (currentMediaType === 'camera' && stream) {
                resizeCanvas();
            }
        });
    </script>
<p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://enzostvs-deepsite.hf.space/logo.svg" alt="DeepSite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://enzostvs-deepsite.hf.space" style="color: #fff;text-decoration: underline;" target="_blank" >DeepSite</a> - 🧬 <a href="https://enzostvs-deepsite.hf.space?remix=samiesam/license-process-detection" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p></body>
</html>