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
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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">    
    <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
    <title>Korean Object Scanner</title>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/[email protected]/dist/coco-ssd.min.js"></script>
    <style>

        body {

            touch-action: none;

            overscroll-behavior: none;

            -webkit-overflow-scrolling: touch;

        }

        #videoContainer {

            position: relative;

            width: 100%;

            height: 100vh;

            overflow: hidden;

            background-color: #000;

        }

        #videoElement, #processedElement {

            position: absolute;

            top: 0;

            left: 0;

            width: 100%;

            height: 100%;

            object-fit: cover;

        }

        #processedElement {

            display: block !important;

            pointer-events: none;

        }

        

        .detection-box {

            position: absolute;

            border: 3px solid #4ADE80;

            border-radius: 4px;

            z-index: 10;

        }

        

        .detection-label {

            position: absolute;

            background-color: #4ADE80;

            color: #1F2937;

            padding: 2px 8px;

            border-radius: 4px;

            font-size: 14px;

            font-weight: 500;

            transform: translateY(-100%);

            z-index: 11;

        }

        

        .pulse {

            animation: pulse 2s infinite;

        }

        

        @keyframes pulse {

            0% { opacity: 1; }

            50% { opacity: 0.5; }

            100% { opacity: 1; }

        }

        

        .loading-spinner {

            width: 40px;

            height: 40px;

            border: 4px solid rgba(255,255,255,0.3);

            border-radius: 50%;

            border-top-color: #fff;

            animation: spin 1s ease-in-out infinite;

        }

        

        @keyframes spin {

            to { transform: rotate(360deg); }

        }

        

        .progress-bar {

            width: 200px;

            height: 8px;

            background-color: rgba(255,255,255,0.2);

            border-radius: 4px;

            margin-top: 16px;

            overflow: hidden;

        }

        

        .progress-fill {

            height: 100%;

            background-color: #4ADE80;

            width: 0%;

            transition: width 0.3s ease;

        }

    </style>
</head>
<body class="bg-gray-900 text-white">
    <!-- Loading overlay -->
    <div id="loadingOverlay" class="fixed inset-0 bg-black bg-opacity-90 flex flex-col items-center justify-center z-50">
        <div class="loading-spinner mb-4"></div>
        <p id="loadingText" class="text-lg font-medium">Loading AI model...</p>
        <div class="progress-bar">
            <div id="modelProgress" class="progress-fill"></div>
        </div>
        <p id="loadingSubtext" class="text-sm text-gray-400 mt-2">Initializing object detection</p>
    </div>
    
    <!-- Error overlay -->
    <div id="errorOverlay" class="fixed inset-0 bg-black bg-opacity-90 flex flex-col items-center justify-center z-50 hidden">
        <div class="bg-red-500 rounded-full p-4 mb-4">
            <span class="material-icons text-white text-4xl">error</span>
        </div>
        <h2 class="text-xl font-bold mb-2">Model Failed to Load</h2>
        <p id="errorMessage" class="text-center max-w-xs mb-6">There was an issue loading the AI model.</p>
        <button id="retryButton" class="bg-blue-500 hover:bg-blue-600 text-white px-6 py-2 rounded-full flex items-center">
            <span class="material-icons mr-2">refresh</span>
            Try Again
        </button>
    </div>
    
    <!-- Camera permission overlay -->
    <div id="permissionOverlay" class="fixed inset-0 bg-black bg-opacity-90 flex flex-col items-center justify-center z-50 hidden">
        <div class="bg-blue-500 rounded-full p-4 mb-4">
            <span class="material-icons text-white text-4xl">camera_alt</span>
        </div>
        <h2 class="text-xl font-bold mb-2">Camera Access Needed</h2>
        <p class="text-center max-w-xs mb-6">Please allow camera access to use the object scanner.</p>
        <button id="startCameraButton" class="bg-blue-500 hover:bg-blue-600 text-white px-6 py-2 rounded-full flex items-center">
            <span class="material-icons mr-2">camera</span>
            Start Camera
        </button>
    </div>
    
    <!-- Main UI -->
    <div id="videoContainer">
        <video id="videoElement" autoplay playsinline muted></video>
        <canvas id="processedElement"></canvas>
        
        <!-- Detection results container -->
        <div id="detectionsContainer"></div>
    </div>
    
    <!-- Bottom controls -->
    <div class="fixed bottom-0 left-0 right-0 bg-gradient-to-t from-black to-transparent pb-4 pt-8 px-4 flex justify-center z-40">
        <div class="flex space-x-4">
            <button id="toggleDetectionButton" class="bg-blue-500 hover:bg-blue-600 text-white px-6 py-3 rounded-full flex items-center hidden">
                <span class="material-icons mr-2">visibility</span>
                Toggle Detection
            </button>
            
            <button id="switchCameraButton" class="bg-gray-700 hover:bg-gray-600 text-white px-4 py-3 rounded-full flex items-center hidden">
                <span class="material-icons">flip_camera_ios</span>
            </button>
        </div>
    </div>
    
    <!-- Status indicator -->
    <div id="statusIndicator" class="fixed top-4 left-1/2 transform -translate-x-1/2 bg-gray-800 text-white px-4 py-2 rounded-full text-sm flex items-center hidden">
        <span class="material-icons mr-1 text-green-400">circle</span>
        <span id="statusText">Ready</span>
    </div>
    
    <script>

        document.addEventListener('DOMContentLoaded', async function() {

            // DOM elements

            const videoElement = document.getElementById('videoElement');

            const processedElement = document.getElementById('processedElement');

            const detectionsContainer = document.getElementById('detectionsContainer');

            const loadingOverlay = document.getElementById('loadingOverlay');

            const loadingText = document.getElementById('loadingText');

            const loadingSubtext = document.getElementById('loadingSubtext');

            const modelProgress = document.getElementById('modelProgress');

            const errorOverlay = document.getElementById('errorOverlay');

            const errorMessage = document.getElementById('errorMessage');

            const retryButton = document.getElementById('retryButton');

            const permissionOverlay = document.getElementById('permissionOverlay');

            const startCameraButton = document.getElementById('startCameraButton');

            const statusIndicator = document.getElementById('statusIndicator');

            const statusText = document.getElementById('statusText');

            const toggleDetectionButton = document.getElementById('toggleDetectionButton');

            const switchCameraButton = document.getElementById('switchCameraButton');

            

            // App state

            let objectDetector = null;

            let isDetecting = true;

            let lastDetectionTime = 0;

            const detectionInterval = 300; // ms between detections

            let currentStream = null;

            let facingMode = "environment";

            

            // Korean labels dictionary (expanded)

            const koreanLabels = {

                        "person": "์‚ฌ๋žŒ",

                        "bicycle": "์ž์ „๊ฑฐ",

                        "car": "์ž๋™์ฐจ",

                        "motorcycle": "์˜คํ† ๋ฐ”์ด",

                        "airplane": "๋น„ํ–‰๊ธฐ",

                        "bus": "๋ฒ„์Šค",

                        "train": "๊ธฐ์ฐจ",

                        "truck": "ํŠธ๋Ÿญ",

                        "boat": "๋ณดํŠธ",

                        "traffic light": "์‹ ํ˜ธ๋“ฑ",

                        "fire hydrant": "์†Œํ™”์ „",

                        "stop sign": "์ •์ง€ ํ‘œ์ง€ํŒ",

                        "parking meter": "์ฃผ์ฐจ ์š”๊ธˆ๊ธฐ",

                        "bench": "๋ฒค์น˜",

                        "bird": "์ƒˆ",

                        "cat": "๊ณ ์–‘์ด",

                        "dog": "๊ฐ•์•„์ง€",

                        "horse": "๋ง",

                        "sheep": "์–‘",

                        "cow": "์†Œ",

                        "elephant": "์ฝ”๋ผ๋ฆฌ",

                        "bear": "๊ณฐ",

                        "zebra": "์–ผ๋ฃฉ๋ง",

                        "giraffe": "๊ธฐ๋ฆฐ",

                        "backpack": "๋ฐฐ๋‚ญ",

                        "umbrella": "์šฐ์‚ฐ",

                        "handbag": "ํ•ธ๋“œ๋ฐฑ",

                        "tie": "๋ฌถ๋‹ค",

                        "suitcase": "์—ฌํ–‰ ๊ฐ€๋ฐฉ",

                        "frisbee": "ํ”„๋ฆฌ์Šค๋น„",

                        "skis": "์Šคํ‚ค",

                        "snowboard": "์Šค๋…ธ์šฐ๋ณด๋“œ",

                        "sports ball": "์Šคํฌ์ธ  ๊ณต",

                        "kite": "์—ฐ",

                        "baseball bat": "์•ผ๊ตฌ๋ฐฉ๋ง์ด",

                        "baseball glove": "์•ผ๊ตฌ ๊ธ€๋Ÿฌ๋ธŒ",

                        "skateboard": "์Šค์ผ€์ดํŠธ๋ณด๋“œ",

                        "surfboard": "์„œํ•‘๋ณด๋“œ",

                        "tennis racket": "ํ…Œ๋‹ˆ์Šค ๋ผ์ผ“",

                        "bottle": "๋ณ‘",

                        "wine glass": "์™€์ธ์ž”",

                        "cup": "์ปต",

                        "fork": "ํฌํฌ",

                        "knife": "์นผ",

                        "spoon": "์ˆŸ๊ฐ€๋ฝ",

                        "bowl": "๊ทธ๋ฆ‡",

                        "banana": "๋ฐ”๋‚˜๋‚˜",

                        "apple": "์‚ฌ๊ณผ",

                        "sandwich": "์ƒŒ๋“œ์œ„์น˜",

                        "orange": "์˜ค๋ Œ์ง€",

                        "broccoli": "๋ธŒ๋กœ์ฝœ๋ฆฌ",

                        "carrot": "๋‹น๊ทผ",

                        "hot dog": "ํ•ซ๋„๊ทธ",

                        "pizza": "ํ”ผ์ž",

                        "donut": "๋„๋„›",

                        "cake": "์ผ€์ดํฌ",

                        "chair": "์˜์ž",

                        "couch": "์†ŒํŒŒ",

                        "potted plant": "ํ™”๋ถ„",

                        "bed": "์นจ๋Œ€",

                        "dining table": "์‹ํƒ",

                        "toilet": "ํ™”์žฅ์‹ค",

                        "tv": "ํ…”๋ ˆ๋น„์ „",

                        "laptop": "๋…ธํŠธ๋ถ",

                        "mouse": "๋งˆ์šฐ์Šค",

                        "remote": "๋ฆฌ๋ชจ์ปจ",

                        "keyboard": "ํ‚ค๋ณด๋“œ",

                        "cell phone": "ํœด๋Œ€ํฐ",

                        "microwave": "์ „์ž๋ ˆ์ธ์ง€",

                        "oven": "์˜ค๋ธ",

                        "toaster": "ํ† ์Šคํ„ฐ",

                        "sink": "์‹ฑํฌ๋Œ€",

                        "refrigerator": "๋ƒ‰์žฅ๊ณ ",

                        "book": "์ฑ…",

                        "clock": "์‹œ๊ณ„",

                        "vase": "๊ฝƒ๋ณ‘",

                        "scissors": "๊ฐ€์œ„",

                        "teddy bear": "์žฅ๋‚œ๊ฐ ๊ณฐ",

                        "hair drier": "ํ—ค์–ด๋“œ๋ผ์ด์–ด",

                        "toothbrush": "์นซ์†”"

                        };



            // Initialize COCO-SSD model

            async function initializeModel() {

                loadingText.textContent = 'Loading COCO-SSD model...';

                loadingSubtext.textContent = 'This lightweight model works offline';

                modelProgress.style.width = '30%';

                

                try {

                    // Load TensorFlow.js backend

                    await tf.setBackend('webgl');

                    modelProgress.style.width = '60%';

                    

                    // Load COCO-SSD model

                    objectDetector = await cocoSsd.load({

                        base: 'lite_mobilenet_v2'

                    });

                    

                    modelProgress.style.width = '100%';

                    

                    // Add slight delay to show 100% progress before hiding

                    await new Promise(resolve => setTimeout(resolve, 300));

                    

                    loadingOverlay.classList.add('hidden');

                    return true;

                } catch (error) {

                    console.error("Failed to load COCO-SSD:", error);

                    showError("Failed to load object detection model", error);

                    return false;

                }

            }

            

            // Initialize camera with user permission

            async function initCamera() {

                try {

                    if (currentStream) {

                        currentStream.getTracks().forEach(track => track.stop());

                    }

                    

                    const stream = await navigator.mediaDevices.getUserMedia({

                        video: { 

                            facingMode: facingMode,

                            width: { ideal: 640 },

                            height: { ideal: 480 }

                        },

                        audio: false

                    });

                    

                    currentStream = stream;

                    videoElement.srcObject = stream;

                    

                    return new Promise((resolve) => {

                        videoElement.onloadedmetadata = () => {

                            processedElement.width = videoElement.videoWidth;

                            processedElement.height = videoElement.videoHeight;

                            permissionOverlay.classList.add('hidden');

                            toggleDetectionButton.classList.remove('hidden');

                            switchCameraButton.classList.remove('hidden');

                            statusIndicator.classList.remove('hidden');

                            resolve(true);

                        };

                    });

                } catch (err) {

                    console.error("Camera error:", err);

                    permissionOverlay.classList.remove('hidden');

                    return false;

                }

            }

            

            // Process each video frame

            async function processFrame(timestamp) {

                if (!objectDetector || !isDetecting) {

                    requestAnimationFrame(processFrame);

                    return;

                }

                

                // Throttle processing

                if (timestamp - lastDetectionTime < detectionInterval) {

                    requestAnimationFrame(processFrame);

                    return;

                }

                

                lastDetectionTime = timestamp;

                

                if (videoElement.readyState < videoElement.HAVE_ENOUGH_DATA) {

                    requestAnimationFrame(processFrame);

                    return;

                }

                

                try {

                    statusText.textContent = "Detecting objects...";

                    

                    const detections = await objectDetector.detect(videoElement);

                    drawDetections(detections);

                    

                    statusText.textContent = `Detected ${detections.length} objects`;

                } catch (error) {

                    console.error("Detection error:", error);

                    statusText.textContent = "Detection error";

                }

                

                requestAnimationFrame(processFrame);

            }

            

            // Draw bounding boxes and labels

            function drawDetections(detections) {

                // Clear previous detections

                detectionsContainer.innerHTML = '';

                

                if (!detections || detections.length === 0) {

                    return;

                }

                

                for (const detection of detections) {

                    if (!detection.bbox || !detection.class) continue;

                    

                    const [x, y, width, height] = detection.bbox;

                    const score = detection.score;

                    const label = detection.class;

                    const koreanLabel = koreanLabels[label.toLowerCase()] || label;

                    

                    // Only show if confidence is high enough

                    if (score < 0.5) continue;

                    

                    // Create detection box element

                    const boxElement = document.createElement('div');

                    boxElement.className = 'detection-box';

                    boxElement.style.left = `${x}px`;

                    boxElement.style.top = `${y}px`;

                    boxElement.style.width = `${width}px`;

                    boxElement.style.height = `${height}px`;

                    

                    // Create label element

                    const labelElement = document.createElement('div');

                    labelElement.className = 'detection-label';

                    labelElement.textContent = `${koreanLabel} (${Math.round(score * 100)}%)`;

                    labelElement.style.left = `${x}px`;

                    labelElement.style.top = `${y}px`;

                    

                    // Add to container

                    detectionsContainer.appendChild(boxElement);

                    detectionsContainer.appendChild(labelElement);

                }

            }

            

            // Toggle detection on/off

            function toggleDetection() {

                isDetecting = !isDetecting;

                if (isDetecting) {

                    toggleDetectionButton.innerHTML = '<span class="material-icons mr-2">visibility_off</span> Pause Detection';

                    statusText.textContent = "Detection resumed";

                } else {

                    toggleDetectionButton.innerHTML = '<span class="material-icons mr-2">visibility</span> Resume Detection';

                    statusText.textContent = "Detection paused";

                    detectionsContainer.innerHTML = '';

                }

            }

            

            // Switch between front and back camera

            async function switchCamera() {

                facingMode = facingMode === "user" ? "environment" : "user";

                statusText.textContent = "Switching camera...";

                await initCamera();

                statusText.textContent = "Camera switched";

            }

            

            // Show error message

            function showError(message, error) {

                loadingOverlay.classList.add('hidden');

                errorOverlay.classList.remove('hidden');

                errorMessage.textContent = message;

                if (error) {

                    console.error(error);

                }

            }

            

            // Start everything

            async function startApp() {

                loadingOverlay.classList.remove('hidden');

                errorOverlay.classList.add('hidden');

                

                const modelLoaded = await initializeModel();

                if (!modelLoaded) return;

                

                // Check camera permissions

                const cameraPermission = await initCamera();

                if (!cameraPermission) return;

                

                // Start processing frames

                requestAnimationFrame(processFrame);

            }

            

            // Event listeners

            retryButton.addEventListener('click', startApp);

            startCameraButton.addEventListener('click', initCamera);

            toggleDetectionButton.addEventListener('click', toggleDetection);

            switchCameraButton.addEventListener('click', switchCamera);

            

            // Start the app

            startApp();

        });

    </script>
</body>
</html>