-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
735 lines (662 loc) · 26.4 KB
/
Copy pathindex.html
File metadata and controls
735 lines (662 loc) · 26.4 KB
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
<!DOCTYPE html>
<html lang="tr">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>🗑️ Garbage Classifier</title>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@4.10.0/dist/tf.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/mobilenet@2.1.0/dist/mobilenet.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/coco-ssd@2.2.2/dist/coco-ssd.min.js"></script>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
background: #0f172a;
color: #f1f5f9;
font-family: 'Segoe UI', system-ui, sans-serif;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
padding: 1.5rem 1rem;
}
header { text-align: center; margin-bottom: 1.2rem; }
header h1 {
font-size: 2rem; font-weight: 700;
background: linear-gradient(135deg, #34d399, #60a5fa);
-webkit-background-clip: text; -webkit-text-fill-color: transparent;
margin-bottom: 0.3rem;
}
header p { color: #94a3b8; font-size: 0.9rem; }
.mode-toggle {
display: flex; gap: 0.5rem;
background: #1e293b; border-radius: 12px; padding: 4px;
margin-bottom: 1.2rem;
}
.mode-btn {
padding: 0.5rem 1.4rem; border-radius: 9px; border: none;
font-size: 0.9rem; font-weight: 600; cursor: pointer;
transition: all 0.2s; color: #64748b; background: transparent;
}
.mode-btn.active { background: #34d399; color: #0f172a; }
.card {
background: #1e293b; border: 1px solid #334155;
border-radius: 16px; padding: 1.5rem;
width: 100%; max-width: 700px; margin-bottom: 1.2rem;
}
/* ── CAMERA MODE ── */
#camera-section { display: block; }
.video-wrapper {
position: relative; width: 100%;
border-radius: 12px; overflow: hidden;
background: #000; aspect-ratio: 16/10;
}
#video {
width: 100%; height: 100%;
object-fit: cover; display: block;
}
#overlay-canvas {
position: absolute; top: 0; left: 0;
width: 100%; height: 100%; pointer-events: none;
}
#live-badge {
position: absolute; bottom: 10px; left: 50%;
transform: translateX(-50%);
background: rgba(15,23,42,0.88);
backdrop-filter: blur(8px);
border: 1px solid rgba(52,211,153,0.4);
border-radius: 99px; padding: 0.4rem 1.2rem;
font-size: 1rem; font-weight: 700;
white-space: nowrap; pointer-events: none;
display: none; transition: border-color 0.3s;
}
#detect-label {
position: absolute; top: 10px; left: 10px;
background: rgba(15,23,42,0.75);
backdrop-filter: blur(4px);
border-radius: 8px; padding: 0.25rem 0.7rem;
font-size: 0.72rem; font-weight: 600; color: #64748b;
white-space: nowrap; pointer-events: none;
display: none;
}
.camera-controls {
display: flex; gap: 0.6rem; margin-top: 0.9rem; justify-content: center;
}
.btn {
background: linear-gradient(135deg, #34d399, #059669);
color: #fff; border: none;
padding: 0.6rem 1.5rem; border-radius: 8px;
font-size: 0.9rem; font-weight: 600; cursor: pointer;
transition: opacity 0.2s;
}
.btn:hover { opacity: 0.85; }
.btn.secondary { background: #334155; }
.btn.danger { background: linear-gradient(135deg, #dc2626, #7f1d1d); }
/* ── UPLOAD MODE ── */
#upload-section { display: none; }
#drop-zone {
border: 2px dashed #475569; border-radius: 12px;
padding: 2.2rem 1rem; text-align: center; cursor: pointer;
transition: all 0.2s;
}
#drop-zone:hover, #drop-zone.drag-over {
border-color: #34d399; background: rgba(52,211,153,0.05);
}
#drop-zone .icon { font-size: 2.2rem; margin-bottom: 0.7rem; }
#drop-zone p { color: #94a3b8; font-size: 0.88rem; }
#drop-zone strong { color: #34d399; }
#file-input { display: none; }
#preview-area { display: none; text-align: center; }
#preview-img {
max-width: 100%; max-height: 280px;
border-radius: 10px; margin-bottom: 0.8rem;
border: 2px solid #334155;
}
#status {
text-align: center; padding: 0.6rem;
color: #94a3b8; font-size: 0.88rem;
}
.spinner {
display: inline-block; width: 16px; height: 16px;
border: 2px solid #475569; border-top-color: #34d399;
border-radius: 50%; animation: spin 0.8s linear infinite;
vertical-align: middle; margin-right: 5px;
}
@keyframes spin { to { transform: rotate(360deg); } }
#result-area { display: none; }
.result-main {
display: flex; align-items: center; gap: 1rem;
margin-bottom: 1.2rem; padding: 1rem;
background: #0f172a; border-radius: 12px;
}
.result-emoji { font-size: 3rem; }
.result-label { font-size: 1.6rem; font-weight: 700; text-transform: capitalize; }
.result-conf { font-size: 0.88rem; color: #94a3b8; margin-top: 0.15rem; }
.result-conf span { color: #34d399; font-weight: 600; }
.bars-title {
font-size: 0.8rem; color: #64748b;
margin-bottom: 0.7rem;
text-transform: uppercase; letter-spacing: 0.05em;
}
.bar-item { margin-bottom: 0.5rem; }
.bar-label {
display: flex; justify-content: space-between;
font-size: 0.8rem; margin-bottom: 3px; text-transform: capitalize;
}
.bar-label .name { color: #cbd5e1; }
.bar-label .pct { color: #94a3b8; }
.bar-bg { background: #0f172a; border-radius: 99px; height: 7px; overflow: hidden; }
.bar-fill { height: 100%; border-radius: 99px; transition: width 0.4s ease; }
#recycle-tip {
margin-top: 0.9rem; padding: 0.7rem 0.9rem; border-radius: 10px;
font-size: 0.85rem;
background: rgba(52,211,153,0.1);
border: 1px solid rgba(52,211,153,0.25); color: #a7f3d0;
}
#live-bars { display: none; }
footer { margin-top: 1.5rem; color: #475569; font-size: 0.78rem; text-align: center; }
</style>
</head>
<body>
<header>
<h1>🗑️ Garbage Classifier</h1>
<p>Kamerayı çöpe tut, kategorisini öğren</p>
</header>
<div class="mode-toggle">
<button class="mode-btn active" id="btn-camera" onclick="switchMode('camera')">📷 Kamera</button>
<button class="mode-btn" id="btn-upload" onclick="switchMode('upload')">📁 Fotoğraf</button>
</div>
<!-- CAMERA SECTION -->
<div id="camera-section">
<div class="card" style="padding:1rem;">
<div class="video-wrapper">
<video id="video" autoplay playsinline muted></video>
<canvas id="overlay-canvas"></canvas>
<div id="detect-label">—</div>
<div id="live-badge">—</div>
</div>
<div class="camera-controls">
<button class="btn" id="start-btn" onclick="startCamera()">📷 Kamerayı Aç</button>
<button class="btn danger" id="stop-btn" onclick="stopCamera()" style="display:none;">⏹ Durdur</button>
</div>
</div>
<div class="card" id="live-bars">
<div class="bars-title">Canlı Tahmin</div>
<div id="live-bars-container"></div>
<div id="live-tip" style="margin-top:0.8rem;padding:0.6rem 0.9rem;border-radius:10px;font-size:0.83rem;background:rgba(52,211,153,0.1);border:1px solid rgba(52,211,153,0.25);color:#a7f3d0;"></div>
</div>
</div>
<!-- UPLOAD SECTION -->
<div id="upload-section">
<div class="card">
<div id="drop-zone" onclick="document.getElementById('file-input').click()">
<div class="icon">📸</div>
<p><strong>Fotoğraf seç</strong> veya buraya sürükle</p>
<p style="margin-top:0.3rem;font-size:0.78rem;">JPG, PNG, WEBP desteklenir</p>
</div>
<input type="file" id="file-input" accept="image/*" onchange="handleFile(event)"/>
<div id="preview-area">
<img id="preview-img" src="" alt="Önizleme"/>
<br/>
<button class="btn" onclick="classifyUpload()">🔍 Sınıflandır</button>
<button class="btn secondary" onclick="resetUpload()">🔄 Yeni Fotoğraf</button>
</div>
</div>
<div id="status-upload" class="card"
style="padding:0.8rem;text-align:center;color:#94a3b8;font-size:0.88rem;display:none;"></div>
<div class="card" id="result-area">
<div class="result-main">
<div class="result-emoji" id="res-emoji">📦</div>
<div>
<div class="result-label" id="res-label">cardboard</div>
<div class="result-conf">Güven: <span id="res-conf">0%</span></div>
</div>
</div>
<div class="bars-title">Tüm Kategoriler</div>
<div id="bars-container"></div>
<div id="recycle-tip"></div>
</div>
</div>
<div id="status"><span class="spinner"></span> Model yükleniyor...</div>
<footer>Metehan Ulusoy · Bilgisayar Mühendisliği · MobileNetV2 + COCO-SSD Transfer Learning</footer>
<script>
/* ── CONSTANTS ── */
const CLASSES = ['cardboard','glass','metal','paper','plastic','trash'];
const EMOJIS = {cardboard:'📦', glass:'🍶', metal:'🥫', paper:'📄', plastic:'🧴', trash:'🗑️'};
const COLORS = {cardboard:'#f59e0b', glass:'#06b6d4', metal:'#94a3b8', paper:'#84cc16', plastic:'#ec4899', trash:'#ef4444'};
const TIPS = {
cardboard: '♻️ Mavi (kağıt/karton) kutusuna at.',
glass: '♻️ Yeşil (cam) kutusuna at.',
metal: '♻️ Sarı (metal) kutusuna at.',
paper: '♻️ Mavi (kağıt/karton) kutusuna at.',
plastic: '♻️ Sarı (plastik) kutusuna at.',
trash: '🗑️ Geri dönüşümsüz — normal çöp kutusuna at.'
};
// COCO-SSD detection hints → boost matching garbage category score
const COCO_HINTS = {
'bottle': {plastic: 2.5, glass: 2.0},
'wine glass': {glass: 4.0},
'cup': {paper: 2.0, plastic: 1.5},
'bowl': {glass: 1.8, plastic: 1.3},
'fork': {metal: 3.5},
'knife': {metal: 3.5},
'spoon': {metal: 3.5},
'scissors': {metal: 4.0}, // zımba, makas vb.
'vase': {glass: 3.0},
'book': {paper: 2.5},
'laptop': {trash: 2.5},
'cell phone': {trash: 2.5},
'remote': {trash: 2.0},
'keyboard': {trash: 2.0},
'mouse': {trash: 2.0},
'backpack': {trash: 1.5},
'handbag': {trash: 1.5},
'suitcase': {cardboard: 1.5},
'toothbrush': {plastic: 2.5},
'banana': {trash: 2.0},
'apple': {trash: 2.0},
'clock': {metal: 1.8, trash: 1.5},
'toaster': {metal: 2.0, trash: 1.5},
'microwave': {metal: 1.8, trash: 1.5},
'sink': {metal: 2.0},
'potted plant':{trash: 1.5},
};
/* ── STATE ── */
let mobileNet, cocoDetector, kernelTensor, biasTensor;
let modelReady = false;
let cameraStream = null, animFrame = null;
let currentMode = 'camera';
// Tracking
let trackedBox = null; // smoothed display box {x,y,w,h}
let targetBox = null; // latest COCO raw detection {x,y,w,h}
let targetBoxAge = 0; // timestamp when targetBox was last set
let currentCocoClass = null;
let currentTopClass = null;
const BOX_FADE_MS = 2000; // fall back to center after N ms no detection
const COCO_INTERVAL = 280; // ms between COCO detection runs
const CLASSIFY_INT = 750; // ms between classification runs
const LERP_ALPHA = 0.45; // smoothing factor (higher = snappier)
let lastCocoTime = 0;
let lastClassifyTime = 0;
/* ── INIT ── */
async function init() {
try {
setStatus('<span class="spinner"></span> MobileNet yükleniyor...');
mobileNet = await mobilenet.load({version: 2, alpha: 1.0});
setStatus('<span class="spinner"></span> Nesne takip modeli yükleniyor...');
cocoDetector = await cocoSsd.load();
setStatus('<span class="spinner"></span> Ağırlıklar yükleniyor...');
const buf = await (await fetch('model/dense_weights.bin')).arrayBuffer();
const w = new Float32Array(buf);
kernelTensor = tf.tensor2d(w.slice(0, 1280 * 6), [1280, 6]);
biasTensor = tf.tensor1d(w.slice(1280 * 6));
modelReady = true;
setStatus('✅ Model hazır! Kamerayı aç ve nesneyi göster.');
} catch(e) {
setStatus('❌ Yükleme hatası: ' + e.message);
console.error(e);
}
}
function setStatus(html) { document.getElementById('status').innerHTML = html; }
/* ── MODE SWITCH ── */
function switchMode(mode) {
currentMode = mode;
if (mode === 'camera') {
document.getElementById('camera-section').style.display = 'block';
document.getElementById('upload-section').style.display = 'none';
document.getElementById('btn-camera').classList.add('active');
document.getElementById('btn-upload').classList.remove('active');
} else {
stopCamera();
document.getElementById('camera-section').style.display = 'none';
document.getElementById('upload-section').style.display = 'block';
document.getElementById('btn-camera').classList.remove('active');
document.getElementById('btn-upload').classList.add('active');
}
}
/* ── CAMERA ── */
async function startCamera() {
if (!modelReady) { setStatus('⏳ Model henüz yüklenmedi, bekle...'); return; }
try {
cameraStream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: 'environment', width: {ideal: 1280}, height: {ideal: 720} }
});
const video = document.getElementById('video');
video.srcObject = cameraStream;
await video.play();
document.getElementById('start-btn').style.display = 'none';
document.getElementById('stop-btn').style.display = 'inline-block';
document.getElementById('live-badge').style.display = 'block';
document.getElementById('detect-label').style.display = 'block';
document.getElementById('live-bars').style.display = 'block';
setStatus('📷 Kamera aktif — nesneyi kameraya göster');
drawLoop();
} catch(e) {
setStatus('❌ Kamera açılamadı: ' + e.message);
}
}
function stopCamera() {
if (cameraStream) { cameraStream.getTracks().forEach(t => t.stop()); cameraStream = null; }
if (animFrame) { cancelAnimationFrame(animFrame); animFrame = null; }
trackedBox = null; targetBox = null; currentTopClass = null;
document.getElementById('start-btn').style.display = 'inline-block';
document.getElementById('stop-btn').style.display = 'none';
document.getElementById('live-badge').style.display = 'none';
document.getElementById('detect-label').style.display = 'none';
document.getElementById('live-bars').style.display = 'none';
const canvas = document.getElementById('overlay-canvas');
canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
setStatus('✅ Model hazır!');
}
/* ── DRAW LOOP ── */
function drawLoop() {
const video = document.getElementById('video');
const canvas = document.getElementById('overlay-canvas');
const ctx = canvas.getContext('2d');
const vw = video.videoWidth || canvas.offsetWidth;
const vh = video.videoHeight || canvas.offsetHeight;
if (vw > 0) { canvas.width = vw; canvas.height = vh; }
ctx.clearRect(0, 0, vw, vh);
const now = Date.now();
// Run COCO detection every COCO_INTERVAL ms
if (cameraStream && now - lastCocoTime > COCO_INTERVAL) {
lastCocoTime = now;
runCoco(video, vw, vh);
}
// Determine active box target (COCO or center fallback)
let activeTarget;
if (targetBox && now - targetBoxAge < BOX_FADE_MS) {
activeTarget = targetBox;
} else {
// Compact center scanning box as fallback (fits hand-held objects)
const size = Math.min(vw, vh) * 0.50;
activeTarget = { x: (vw - size) / 2, y: (vh - size) / 2, w: size, h: size };
currentCocoClass = null;
document.getElementById('detect-label').textContent = '🔍 nesne aranıyor...';
}
// Lerp toward active target
trackedBox = lerpBox(trackedBox, activeTarget, LERP_ALPHA);
if (trackedBox) drawTrackingBox(ctx, trackedBox, vw, vh, now);
// Classify every CLASSIFY_INT ms
if (modelReady && cameraStream && now - lastClassifyTime > CLASSIFY_INT) {
lastClassifyTime = now;
classifyRegion(video, trackedBox, vw, vh);
}
animFrame = requestAnimationFrame(drawLoop);
}
/* ── COCO DETECTION ── */
// These are stationary background objects — never track them
const BG_CLASSES = new Set([
'refrigerator','oven','microwave','toaster','sink','dishwasher',
'tv','monitor','laptop',
'chair','couch','sofa','bench','bed','dining table','toilet',
'potted plant','traffic light','stop sign','parking meter','fire hydrant',
'clock','mirror','door','window',
]);
async function runCoco(video, vw, vh) {
if (!cocoDetector || !video.videoWidth) return;
try {
const detections = await cocoDetector.detect(video);
const frameArea = vw * vh;
// Face/head zone: top 40% of each person bbox → exclude objects detected there
const faceZones = detections
.filter(d => d.class === 'person' && d.score > 0.45)
.map(d => ({
x: d.bbox[0], y: d.bbox[1],
w: d.bbox[2], h: d.bbox[3] * 0.40,
}));
// Candidate objects for tracking
const objs = detections.filter(d => {
if (d.class === 'person') return false;
if (BG_CLASSES.has(d.class)) return false; // known furniture/bg
if (d.score < 0.18) return false; // very low confidence
if (d.bbox[2] * d.bbox[3] / frameArea > 0.55) return false; // fills >55% frame
// Skip if center is inside someone's face/head zone
const cx = d.bbox[0] + d.bbox[2] / 2;
const cy = d.bbox[1] + d.bbox[3] / 2;
for (const fz of faceZones) {
if (cx > fz.x && cx < fz.x + fz.w &&
cy > fz.y && cy < fz.y + fz.h) return false;
}
return true;
});
// Always update hint class from best non-person, non-bg detection
const hintable = detections.filter(d =>
d.class !== 'person' && d.score > 0.18
);
if (hintable.length > 0) {
hintable.sort((a, b) => b.score - a.score);
currentCocoClass = hintable[0].class;
}
if (objs.length === 0) {
document.getElementById('detect-label').textContent = '🔍 nesne aranıyor...';
return;
}
// Pick highest-confidence trackable object
objs.sort((a, b) => b.score - a.score);
const best = objs[0];
const pad = 0.10;
const bx = best.bbox[0], by = best.bbox[1];
const bw = best.bbox[2], bh = best.bbox[3];
const padX = bw * pad, padY = bh * pad;
targetBox = {
x: Math.max(0, bx - padX),
y: Math.max(0, by - padY),
w: Math.min(vw - (bx - padX), bw + padX * 2),
h: Math.min(vh - (by - padY), bh + padY * 2),
};
targetBoxAge = Date.now();
currentCocoClass = best.class;
document.getElementById('detect-label').textContent =
'🔍 ' + best.class + ' (' + (best.score * 100).toFixed(0) + '%)';
} catch(e) { /* ignore mid-frame errors */ }
}
/* ── LERP ── */
function lerpBox(cur, tgt, a) {
if (!cur) return { ...tgt };
return {
x: cur.x + (tgt.x - cur.x) * a,
y: cur.y + (tgt.y - cur.y) * a,
w: cur.w + (tgt.w - cur.w) * a,
h: cur.h + (tgt.h - cur.h) * a,
};
}
/* ── DRAW TRACKING BOX ── */
function drawTrackingBox(ctx, box, vw, vh, now) {
const { x, y, w, h } = box;
const boxColor = currentTopClass ? COLORS[currentTopClass] : '#34d399';
const pulse = 0.55 + 0.45 * Math.sin(now / 550);
const cornerLen = Math.min(w, h) * 0.18;
// Dimmed overlay outside the box
ctx.fillStyle = 'rgba(0,0,0,0.38)';
ctx.fillRect(0, 0, vw, vh);
ctx.clearRect(x, y, w, h);
// Glow
ctx.shadowColor = boxColor;
ctx.shadowBlur = 14 * pulse;
ctx.strokeStyle = boxColor;
ctx.lineWidth = 3;
ctx.lineCap = 'round';
// Corner brackets
const corners = [
[x, y, 1, 1],
[x + w, y, -1, 1],
[x, y + h, 1, -1],
[x + w, y + h,-1, -1],
];
corners.forEach(([cx, cy, dx, dy]) => {
ctx.beginPath();
ctx.moveTo(cx + dx * cornerLen, cy);
ctx.lineTo(cx, cy);
ctx.lineTo(cx, cy + dy * cornerLen);
ctx.stroke();
});
ctx.shadowBlur = 0;
// Class label tag above the box
if (currentTopClass) {
const label = EMOJIS[currentTopClass] + ' ' + currentTopClass;
ctx.font = 'bold 13px Segoe UI, sans-serif';
const tw = ctx.measureText(label).width + 16;
const th = 22;
const tx = Math.min(x, vw - tw - 4);
const ty = Math.max(y - th - 4, 4);
ctx.fillStyle = boxColor + 'cc';
roundRect(ctx, tx, ty, tw, th, 6);
ctx.fillStyle = '#0f172a';
ctx.fillText(label, tx + 8, ty + 15);
}
}
function roundRect(ctx, x, y, w, h, r) {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.lineTo(x + w - r, y);
ctx.quadraticCurveTo(x + w, y, x + w, y + r);
ctx.lineTo(x + w, y + h - r);
ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
ctx.lineTo(x + r, y + h);
ctx.quadraticCurveTo(x, y + h, x, y + h - r);
ctx.lineTo(x, y + r);
ctx.quadraticCurveTo(x, y, x + r, y);
ctx.closePath();
ctx.fill();
}
/* ── CLASSIFY REGION ── */
async function classifyRegion(video, box, vw, vh) {
if (!box || !video.videoWidth) return;
try {
const tmp = document.createElement('canvas');
tmp.width = 224; tmp.height = 224;
tmp.getContext('2d').drawImage(video, box.x, box.y, box.w, box.h, 0, 0, 224, 224);
let probs = tf.tidy(() => {
let emb = mobileNet.infer(tmp, true);
if (emb.shape.length === 4) emb = emb.mean([1, 2]);
if (emb.shape.length === 1) emb = emb.expandDims(0);
const logits = tf.add(tf.matMul(emb, kernelTensor), biasTensor);
return tf.softmax(logits).squeeze().arraySync();
});
// Apply COCO class hints to boost accuracy
if (currentCocoClass) probs = applyCocoHints(probs, currentCocoClass);
currentTopClass = CLASSES[probs.indexOf(Math.max(...probs))];
updateLiveBadge(probs);
updateLiveResult(probs);
} catch(e) { console.error(e); }
}
/* ── COCO HINTS ── */
function applyCocoHints(probs, cocoClass) {
const hints = COCO_HINTS[cocoClass];
if (!hints) return probs;
const boosted = probs.map((p, i) => p * (hints[CLASSES[i]] || 1.0));
const sum = boosted.reduce((a, b) => a + b, 0);
return boosted.map(p => p / sum);
}
/* ── UI UPDATES ── */
function updateLiveBadge(probs) {
const topIdx = probs.indexOf(Math.max(...probs));
const cls = CLASSES[topIdx];
const conf = (probs[topIdx] * 100).toFixed(1);
const badge = document.getElementById('live-badge');
badge.textContent = EMOJIS[cls] + ' ' + cls + ' — ' + conf + '%';
badge.style.borderColor = COLORS[cls] + '88';
}
function updateLiveResult(probs) {
const topIdx = probs.indexOf(Math.max(...probs));
const topClass = CLASSES[topIdx];
const sorted = [...probs.map((p, i) => ({ p, i }))].sort((a, b) => b.p - a.p);
const container = document.getElementById('live-bars-container');
container.innerHTML = '';
sorted.forEach(({ p, i }) => {
const cls = CLASSES[i], pct = (p * 100).toFixed(1), col = COLORS[cls];
const div = document.createElement('div');
div.className = 'bar-item';
div.innerHTML = `
<div class="bar-label">
<span class="name">${EMOJIS[cls]} ${cls.charAt(0).toUpperCase()+cls.slice(1)}</span>
<span class="pct">${pct}%</span>
</div>
<div class="bar-bg">
<div class="bar-fill" style="width:${pct}%;background:${col}"></div>
</div>`;
container.appendChild(div);
});
document.getElementById('live-tip').textContent = TIPS[topClass];
}
/* ── UPLOAD MODE ── */
function handleFile(e) {
const file = e.target.files[0]; if (!file) return;
const reader = new FileReader();
reader.onload = ev => {
document.getElementById('preview-img').src = ev.target.result;
document.getElementById('drop-zone').style.display = 'none';
document.getElementById('preview-area').style.display = 'block';
document.getElementById('result-area').style.display = 'none';
};
reader.readAsDataURL(file);
}
const dz = document.getElementById('drop-zone');
dz.addEventListener('dragover', e => { e.preventDefault(); dz.classList.add('drag-over'); });
dz.addEventListener('dragleave', () => dz.classList.remove('drag-over'));
dz.addEventListener('drop', e => {
e.preventDefault(); dz.classList.remove('drag-over');
const file = e.dataTransfer.files[0];
if (file) handleFile({ target: { files: [file] } });
});
async function classifyUpload() {
if (!modelReady) { setStatus('⏳ Bekle...'); return; }
setStatus('<span class="spinner"></span> Tahmin yapılıyor...');
const img = document.getElementById('preview-img');
try {
let probs = tf.tidy(() => {
let emb = mobileNet.infer(img, true);
if (emb.shape.length === 4) emb = emb.mean([1, 2]);
if (emb.shape.length === 1) emb = emb.expandDims(0);
const logits = tf.add(tf.matMul(emb, kernelTensor), biasTensor);
return tf.softmax(logits).squeeze().arraySync();
});
// Also run COCO on upload image for hints
if (cocoDetector) {
try {
const dets = await cocoDetector.detect(img);
const best = dets.filter(d => d.class !== 'person' && d.score > 0.35)
.sort((a, b) => b.score - a.score)[0];
if (best) probs = applyCocoHints(probs, best.class);
} catch(e) { /* skip hints on error */ }
}
showUploadResult(probs);
setStatus('✅ Tahmin tamamlandı!');
} catch(e) { setStatus('❌ Hata: ' + e.message); }
}
function showUploadResult(probs) {
const topIdx = probs.indexOf(Math.max(...probs));
const topClass = CLASSES[topIdx];
document.getElementById('res-emoji').textContent = EMOJIS[topClass];
document.getElementById('res-label').textContent = topClass;
document.getElementById('res-conf').textContent = (probs[topIdx] * 100).toFixed(1) + '%';
document.getElementById('recycle-tip').textContent = TIPS[topClass];
const sorted = [...probs.map((p, i) => ({ p, i }))].sort((a, b) => b.p - a.p);
const container = document.getElementById('bars-container');
container.innerHTML = '';
sorted.forEach(({ p, i }) => {
const cls = CLASSES[i], pct = (p * 100).toFixed(1), col = COLORS[cls];
const div = document.createElement('div'); div.className = 'bar-item';
div.innerHTML = `
<div class="bar-label">
<span class="name">${EMOJIS[cls]} ${cls.charAt(0).toUpperCase()+cls.slice(1)}</span>
<span class="pct">${pct}%</span>
</div>
<div class="bar-bg">
<div class="bar-fill" style="width:${pct}%;background:${col}"></div>
</div>`;
container.appendChild(div);
});
document.getElementById('result-area').style.display = 'block';
}
function resetUpload() {
document.getElementById('file-input').value = '';
document.getElementById('preview-img').src = '';
document.getElementById('drop-zone').style.display = 'block';
document.getElementById('preview-area').style.display = 'none';
document.getElementById('result-area').style.display = 'none';
}
init();
</script>
</body>
</html>