Spaces:
Running
Running
File size: 37,476 Bytes
6c74f21 |
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 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Quadcopter Interceptor Simulation</title>
<script src="https://cdn.jsdelivr.net/npm/onnxruntime-web/dist/ort.min.js"></script>
<script src="https://cdn.tailwindcss.com"></script>
<style>
/* --- Base & Theming --- */
:root {
--bg-start: #f4f6f9;
--bg-end: #e2e8f0;
--card-bg: rgba(255, 255, 255, 0.7);
--text-primary: #1f2937;
--text-secondary: #4b5563;
--border-color: rgba(0, 0, 0, 0.1);
--shadow: 0 10px 30px rgba(0, 0, 0, 0.07);
--primary-gradient: linear-gradient(90deg, #3b82f6, #8b5cf6);
--primary-hover-gradient: linear-gradient(90deg, #2563eb, #7c3aed);
--detail-bg: rgba(0, 0, 0, 0.04);
--propeller-color: #64748b;
}
html.dark {
--bg-start: #111827;
--bg-end: #1f2937;
--card-bg: rgba(31, 41, 55, 0.7);
--text-primary: #f9fafb;
--text-secondary: #d1d5db;
--border-color: rgba(255, 255, 255, 0.1);
--shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
--detail-bg: rgba(255, 255, 255, 0.06);
--propeller-color: #94a3b8;
}
body {
background: linear-gradient(-45deg, var(--bg-start), var(--bg-end));
transition: background 0.5s;
font-family: 'Inter', sans-serif;
}
/* Helpers */
.text-text-primary {
color: var(--text-primary);
}
.text-text-secondary {
color: var(--text-secondary);
}
.border-border-color {
border-color: var(--border-color);
}
.bg-card-bg {
background-color: var(--card-bg);
}
.bg-detail-bg {
background-color: var(--detail-bg);
}
.backdrop-blur-xl {
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
}
/* Propeller Animation */
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
.propeller-blade {
animation: spin 1s linear infinite;
animation-play-state: paused;
/* Start paused */
background-color: var(--propeller-color);
transition: background-color 0.3s;
}
/* Custom scrollbar for results & gallery */
.custom-scrollbar::-webkit-scrollbar {
height: 6px;
width: 6px;
}
.custom-scrollbar::-webkit-scrollbar-track {
background: transparent;
}
.custom-scrollbar::-webkit-scrollbar-thumb {
background: rgba(0, 0, 0, 0.2);
border-radius: 3px;
}
html.dark .custom-scrollbar::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.2);
}
</style>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<script>
tailwind.config = {
darkMode: 'class',
theme: {
extend: {
fontFamily: {
sans: ['Inter', 'sans-serif'],
},
}
}
}
</script>
</head>
<body class="min-h-screen flex items-center justify-center p-2 sm:p-4 antialiased">
<!-- Model Loading Overlay -->
<div id="model-loading-overlay"
class="fixed inset-0 bg-black/70 flex flex-col items-center justify-center z-50 transition-opacity duration-300">
<div class="flex flex-col items-center gap-4">
<div class="animate-spin rounded-full h-16 w-16 border-b-4 border-blue-400"></div>
<span class="text-white text-2xl font-bold tracking-wide">Loading AI Model...</span>
<span class="text-blue-200 text-sm">This may take a few seconds on first load.</span>
</div>
</div>
<!-- Main Application Card -->
<div
class="w-full max-w-7xl mx-auto bg-card-bg border border-border-color rounded-2xl sm:rounded-3xl shadow-2xl backdrop-blur-xl p-4 md:p-6 transition-all duration-500">
<div class="grid grid-cols-1 lg:grid-cols-2 gap-4 md:gap-6">
<!-- Left Panel: Quadcopter Simulation -->
<div class="flex flex-col gap-4">
<header class="flex justify-between items-center">
<h1 class="text-lg sm:text-xl md:text-2xl font-bold text-text-primary">Quadcopter Simulation</h1>
<button id="theme-switcher"
class="w-10 h-10 flex items-center justify-center rounded-full hover:bg-black/5 dark:hover:bg-white/10 transition"
aria-label="Switch theme" title="Switch theme">
<svg id="sun-icon" class="w-6 h-6 text-text-secondary" fill="none" stroke="currentColor"
viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z">
</path>
</svg>
<svg id="moon-icon" class="w-6 h-6 text-text-secondary hidden" fill="none" stroke="currentColor"
viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z">
</path>
</svg>
</button>
</header>
<div
class="relative w-full aspect-square bg-detail-bg rounded-2xl p-4 sm:p-6 flex items-center justify-center">
<div class="relative w-full h-full max-w-[350px] max-h-[350px]">
<div class="absolute inset-0 flex items-center justify-center">
<div
class="w-[28%] h-[28%] bg-gray-400 dark:bg-gray-600 rounded-full shadow-lg flex items-center justify-center text-white font-bold text-lg">
<svg xmlns="http://www.w3.org/2000/svg" class="w-1/2 h-1/2 opacity-50"
viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
stroke-linecap="round" stroke-linejoin="round">
<path
d="M12 22s-8-4.5-8-11.8A8 8 0 0 1 12 2a8 8 0 0 1 8 8.2c0 7.3-8 11.8-8 11.8z" />
<circle cx="12" cy="10" r="3" />
</svg>
</div>
</div>
<div
class="absolute w-[90%] h-1.5 top-1/2 left-[5%] -translate-y-1 bg-gray-300 dark:bg-gray-500 rounded-full">
</div>
<div
class="absolute h-[90%] w-1.5 left-1/2 top-[5%] -translate-x-1 bg-gray-300 dark:bg-gray-500 rounded-full">
</div>
<div id="motor-fl" class="absolute top-0 left-0"></div>
<div id="motor-fr" class="absolute top-0 right-0"></div>
<div id="motor-rl" class="absolute bottom-0 left-0"></div>
<div id="motor-rr" class="absolute bottom-0 right-0"></div>
</div>
</div>
<div>
<h2 class="text-base sm:text-lg font-semibold text-text-primary mb-2">Flight Telemetry</h2>
<div class="grid grid-cols-2 gap-2 text-left">
<div class="bg-detail-bg p-2 rounded-lg flex items-center gap-2">
<svg class="w-5 h-5 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1V10a1 1 0 00-1-1H7a1 1 0 00-1 1v10a1 1 0 001 1h2z">
</path>
</svg>
<div>
<p class="text-xs text-text-secondary font-medium">TARGET</p>
<p id="telemetry-target" class="text-sm sm:text-base font-bold text-text-primary">-</p>
</div>
</div>
<div class="bg-detail-bg p-2 rounded-lg flex items-center gap-2">
<svg class="w-5 h-5 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
</svg>
<div>
<p class="text-xs text-text-secondary font-medium">STATUS</p>
<p id="telemetry-status" class="text-sm sm:text-base font-bold text-text-primary">IDLE
</p>
</div>
</div>
<div class="bg-detail-bg p-2 rounded-lg flex items-center gap-2">
<svg class="w-5 h-5 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M4 8h16M4 16h16"></path>
</svg>
<div>
<p class="text-xs text-text-secondary font-medium">X-VECTOR</p>
<p id="telemetry-x" class="text-sm sm:text-base font-bold text-text-primary">0.00</p>
</div>
</div>
<div class="bg-detail-bg p-2 rounded-lg flex items-center gap-2">
<svg class="w-5 h-5 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M8 4v16M16 4v16"></path>
</svg>
<div>
<p class="text-xs text-text-secondary font-medium">Y-VECTOR</p>
<p id="telemetry-y" class="text-sm sm:text-base font-bold text-text-primary">0.00</p>
</div>
</div>
</div>
</div>
</div>
<!-- Right Panel: AI Detector -->
<div id="detector-card"
class="bg-card-bg/50 dark:bg-card-bg/50 border border-border-color rounded-2xl p-4 md:p-6 flex flex-col">
<header class="flex justify-between items-center mb-4">
<h1 class="text-lg sm:text-xl md:text-2xl font-bold text-text-primary">AI Vision System</h1>
</header>
<div id="content-area" class="flex-grow flex flex-col min-h-0">
<div id="uploader-view" class="flex-grow flex flex-col">
<div id="drop-zone"
class="flex-grow flex flex-col items-center justify-center border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-2xl p-4 text-center cursor-pointer hover:border-blue-500 dark:hover:border-blue-400 hover:scale-[1.01] transition-all duration-300"
tabindex="0">
<svg class="w-12 h-12 sm:w-16 sm:h-16 opacity-50 text-text-secondary" fill="none"
stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12">
</path>
</svg>
<p class="mt-3 font-semibold text-text-primary">Drag & Drop Sky Image</p>
<p class="text-xs sm:text-sm text-text-secondary mt-1">or</p>
<label for="image-upload"
class="mt-3 px-5 py-2 rounded-lg font-semibold text-white cursor-pointer transition-all duration-300 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 text-sm"
style="background: var(--primary-gradient);"
onmouseover="this.style.background='var(--primary-hover-gradient)'"
onmouseout="this.style.background='var(--primary-gradient)'">
Select File
</label>
<input type="file" id="image-upload" class="hidden" accept="image/*">
</div>
<div class="mt-4">
<h3 class="text-sm font-semibold text-text-secondary text-center mb-2">Or Select a Preset
</h3>
<div id="preset-gallery" class="custom-scrollbar flex gap-2 overflow-x-auto pb-2">
<!-- Presets will be injected here -->
</div>
</div>
</div>
<div id="results-view" class="hidden flex-grow flex flex-col min-h-0">
<div class="relative mb-2 group">
<canvas id="output-canvas" class="w-full h-auto rounded-xl shadow-md"></canvas>
<button id="reset-button"
class="absolute top-2 right-2 w-9 h-9 bg-black/40 hover:bg-black/60 backdrop-blur-sm rounded-full flex items-center justify-center transition opacity-0 group-hover:opacity-100"
title="Analyze another image">
<svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M19 12H5M12 19l-7-7 7-7"></path>
</svg>
</button>
</div>
<div id="results-summary" class="flex-grow overflow-y-auto space-y-2 pr-2 custom-scrollbar">
</div>
</div>
</div>
<footer id="status-footer" class="mt-4 text-center text-sm text-text-secondary h-5"></footer>
</div>
</div>
</div>
<!-- Toast Notification -->
<div id="toast"
class="fixed bottom-6 right-6 bg-red-600 text-white px-4 py-2 rounded-lg shadow-lg opacity-0 transform translate-y-4 pointer-events-none transition-all duration-300 z-50">
</div>
<script>
// --- DOM Elements ---
const uploaderView = document.getElementById('uploader-view');
const resultsView = document.getElementById('results-view');
const dropZone = document.getElementById('drop-zone');
const imageUpload = document.getElementById('image-upload');
const outputCanvas = document.getElementById('output-canvas');
const resultsSummary = document.getElementById('results-summary');
const statusFooter = document.getElementById('status-footer');
const resetButton = document.getElementById('reset-button');
const themeSwitcher = document.getElementById('theme-switcher');
const sunIcon = document.getElementById('sun-icon');
const moonIcon = document.getElementById('moon-icon');
const modelLoadingOverlay = document.getElementById('model-loading-overlay');
const toast = document.getElementById('toast');
const presetGallery = document.getElementById('preset-gallery');
const telemetry = {
target: document.getElementById('telemetry-target'),
status: document.getElementById('telemetry-status'),
x: document.getElementById('telemetry-x'),
y: document.getElementById('telemetry-y'),
};
const motorElements = {
fl: document.getElementById('motor-fl'),
fr: document.getElementById('motor-fr'),
rl: document.getElementById('motor-rl'),
rr: document.getElementById('motor-rr'),
};
let session;
// --- Constants ---
const MODEL_URL = "https://huggingface.co/aaurelions/yolo11n.onnx/resolve/main/yolo11n.onnx";
const COCO_CLASSES = ['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'];
const TARGET_CLASS = 'airplane';
const COLORS = ["#3b82f6", "#ef4444", "#22c55e", "#f97316", "#8b5cf6", "#fde047", "#ec4899", "#14b8a6", "#64748b"];
// --- UI & Initialization Logic ---
function showToast(message, duration = 3000) {
toast.textContent = message;
toast.classList.remove('opacity-0', 'translate-y-4');
setTimeout(() => {
toast.classList.add('opacity-0', 'translate-y-4');
}, duration);
}
function showModelLoading(show) {
modelLoadingOverlay.style.display = show ? 'flex' : 'none';
modelLoadingOverlay.classList.toggle('opacity-0', !show);
}
function setDarkMode(isDark) {
document.documentElement.classList.toggle('dark', isDark);
sunIcon.classList.toggle('hidden', isDark);
moonIcon.classList.toggle('hidden', !isDark);
localStorage.setItem('theme', isDark ? 'dark' : 'light');
}
themeSwitcher.addEventListener('click', () => setDarkMode(!document.documentElement.classList.contains('dark')));
resetButton.addEventListener('click', () => {
resultsView.classList.add('hidden');
uploaderView.classList.remove('hidden');
statusFooter.textContent = 'Model is ready. Select an image.';
imageUpload.value = '';
resetSimulation();
});
// --- Drag & Drop Logic ---
['dragenter', 'dragover'].forEach(eventName => {
dropZone.addEventListener(eventName, (e) => {
e.preventDefault();
dropZone.classList.add('ring-4', 'ring-blue-400', 'scale-105', 'border-solid');
}, false);
});
['dragleave', 'drop'].forEach(eventName => {
dropZone.addEventListener(eventName, (e) => {
e.preventDefault();
dropZone.classList.remove('ring-4', 'ring-blue-400', 'scale-105', 'border-solid');
}, false);
});
dropZone.addEventListener('drop', (e) => {
const file = e.dataTransfer.files[0];
if (file) handleFile(file);
});
imageUpload.addEventListener('change', (e) => { if (e.target.files[0]) handleFile(e.target.files[0]); });
// --- Quadcopter Simulation Logic ---
function createMotorComponent(container, label) {
container.classList.add('w-14', 'h-14', 'sm:w-16', 'sm:h-16', 'flex', 'items-center', 'justify-center', 'transform');
if (label.includes('l')) container.classList.add('-translate-x-1/2'); else container.classList.add('translate-x-1/2');
if (label.includes('f')) container.classList.add('-translate-y-1/2'); else container.classList.add('translate-y-1/2');
const mount = document.createElement('div');
mount.className = 'w-7 h-7 sm:w-8 sm:h-8 bg-gray-300 dark:bg-gray-700 rounded-full shadow-inner';
const propeller = document.createElement('div');
propeller.className = 'absolute w-full h-full flex items-center justify-center';
propeller.innerHTML = `<div class="propeller-blade absolute w-full h-1.5 rounded-full"></div><div class="propeller-blade absolute w-1.5 h-full rounded-full"></div>`;
const speedDisplay = document.createElement('div');
speedDisplay.className = 'absolute -bottom-4 text-xs font-mono text-text-secondary';
speedDisplay.textContent = '0%';
const labelDisplay = document.createElement('div');
labelDisplay.className = 'absolute -top-4 text-xs font-bold text-text-secondary tracking-wider';
labelDisplay.textContent = label.toUpperCase();
container.append(labelDisplay, mount, propeller, speedDisplay);
}
function updateMotor(motorEl, speed) {
const clampedSpeed = Math.max(0, Math.min(100, speed));
const speedDisplay = motorEl.querySelector('.absolute.-bottom-4');
speedDisplay.textContent = `${Math.round(clampedSpeed)}%`;
const blades = motorEl.querySelectorAll('.propeller-blade');
if (clampedSpeed > 5) {
const animationDuration = 1 / (clampedSpeed / 20);
blades.forEach(b => {
b.style.animationPlayState = 'running';
b.style.animationDuration = `${Math.max(0.05, animationDuration)}s`;
});
} else {
blades.forEach(b => b.style.animationPlayState = 'paused');
}
}
function resetSimulation() {
Object.values(motorElements).forEach(el => updateMotor(el, 0));
telemetry.target.textContent = '-';
telemetry.status.textContent = 'IDLE';
telemetry.x.textContent = '0.00';
telemetry.y.textContent = '0.00';
telemetry.status.classList.remove('text-green-500', 'text-red-500', 'text-yellow-500');
}
function calculateMotorSpeeds(target, imageWidth, imageHeight) {
const [x1, y1, x2, y2] = target.box;
const targetX = x1 + (x2 - x1) / 2;
const targetY = y1 + (y2 - y1) / 2;
const normX = (targetX / imageWidth - 0.5) * 2;
const normY = (targetY / imageHeight - 0.5) * 2;
const BASE_SPEED = 60;
const MANEUVER_INTENSITY = 25;
const pitch_adjustment = normY * MANEUVER_INTENSITY;
const roll_adjustment = normX * MANEUVER_INTENSITY;
const speeds = {
fl: BASE_SPEED - pitch_adjustment - roll_adjustment,
fr: BASE_SPEED - pitch_adjustment + roll_adjustment,
rl: BASE_SPEED + pitch_adjustment - roll_adjustment,
rr: BASE_SPEED + pitch_adjustment + roll_adjustment,
};
updateMotor(motorElements.fl, speeds.fl);
updateMotor(motorElements.fr, speeds.fr);
updateMotor(motorElements.rl, speeds.rl);
updateMotor(motorElements.rr, speeds.rr);
telemetry.target.textContent = 'AIRPLANE';
telemetry.status.textContent = 'TRACKING';
telemetry.status.classList.remove('text-red-500', 'text-yellow-500');
telemetry.status.classList.add('text-green-500');
telemetry.x.textContent = normX.toFixed(2);
telemetry.y.textContent = normY.toFixed(2);
}
// --- Core AI & Rendering Logic ---
async function handleFile(file) {
if (!session) { showToast("AI Model is not loaded yet."); return; }
if (!file || !file.type.startsWith('image/')) { showToast("Please select a valid image file."); return; }
const image = new Image();
image.src = URL.createObjectURL(file);
image.onload = () => {
runAnalysis(image);
URL.revokeObjectURL(image.src);
};
image.onerror = () => {
showToast("Could not load the selected image file.");
statusFooter.textContent = "Error: Invalid image.";
}
}
async function handleUrl(url) {
if (!session) { showToast("AI Model is not loaded yet."); return; }
const image = new Image();
image.crossOrigin = "anonymous"; // Handle CORS for remote images
image.src = url;
image.onload = () => runAnalysis(image);
image.onerror = () => {
showToast(`Could not load image from URL: ${url}`);
statusFooter.textContent = "Error: Invalid image URL.";
};
}
async function runAnalysis(image) {
resetSimulation();
statusFooter.innerHTML = '<div class="flex items-center justify-center gap-2"><div class="animate-spin rounded-full h-4 w-4 border-b-2 border-text-primary"></div><span>Analyzing image...</span></div>';
uploaderView.classList.add('hidden');
resultsView.classList.remove('hidden');
try {
const inputTensor = preprocess(image);
const results = await session.run({ 'images': inputTensor });
const boxes = postprocess(results.output0, image.width, image.height);
const finalBoxes = nonMaxSuppression(boxes, 0.5, 0.45);
const airplanes = finalBoxes.filter(b => COCO_CLASSES[b.classId] === TARGET_CLASS);
let primaryTarget = null;
if (airplanes.length > 0) {
primaryTarget = airplanes.sort((a, b) => b.confidence - a.confidence)[0];
calculateMotorSpeeds(primaryTarget, image.naturalWidth, image.naturalHeight);
} else {
telemetry.target.textContent = 'NONE';
telemetry.status.textContent = 'SCANNING';
telemetry.status.classList.add('text-yellow-500');
}
drawDetections(image, finalBoxes, primaryTarget);
displaySummary(finalBoxes);
statusFooter.textContent = `Found ${finalBoxes.length} object(s). ${airplanes.length > 0 ? 'Target acquired.' : 'No target found.'}`;
} catch (e) {
showToast(`An error occurred: ${e.message}`);
statusFooter.textContent = "Error during analysis.";
resetButton.click();
}
}
function preprocess(img) {
const canvas = document.createElement('canvas');
const modelWidth = 640, modelHeight = 640;
canvas.width = modelWidth;
canvas.height = modelHeight;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, modelWidth, modelHeight);
const imageData = ctx.getImageData(0, 0, modelWidth, modelHeight);
const float32Data = new Float32Array(1 * 3 * modelHeight * modelWidth);
for (let i = 0, j = 0; i < imageData.data.length; i += 4, j++) {
float32Data[j] = imageData.data[i] / 255.0;
float32Data[modelWidth * modelHeight + j] = imageData.data[i + 1] / 255.0;
float32Data[2 * modelWidth * modelHeight + j] = imageData.data[i + 2] / 255.0;
}
return new ort.Tensor('float32', float32Data, [1, 3, modelHeight, modelWidth]);
}
function postprocess(tensor, originalWidth, originalHeight) {
const data = tensor.data;
const boxes = [];
const modelWidth = 640, modelHeight = 640;
const xRatio = originalWidth / modelWidth;
const yRatio = originalHeight / modelHeight;
for (let i = 0; i < tensor.dims[2]; i++) {
const classScores = [];
for (let j = 0; j < COCO_CLASSES.length; j++) {
classScores.push(data[(4 + j) * tensor.dims[2] + i]);
}
const maxScore = Math.max(...classScores);
if (maxScore > 0.25) {
const classId = classScores.indexOf(maxScore);
const [cx, cy, w, h] = [data[i], data[tensor.dims[2] + i], data[2 * tensor.dims[2] + i], data[3 * tensor.dims[2] + i]];
const x1 = (cx - w / 2) * xRatio;
const y1 = (cy - h / 2) * yRatio;
const x2 = (cx + w / 2) * xRatio;
const y2 = (cy + h / 2) * yRatio;
boxes.push({ classId, confidence: maxScore, box: [x1, y1, x2, y2] });
}
}
return boxes;
}
function nonMaxSuppression(boxes, iouThreshold, scoreThreshold) {
boxes.sort((a, b) => b.confidence - a.confidence);
const finalBoxes = [];
while (boxes.length > 0) {
const current = boxes.shift();
if (current.confidence < scoreThreshold) continue;
finalBoxes.push(current);
boxes = boxes.filter(box => {
if (box.classId !== current.classId) return true;
const iou = calculateIoU(current.box, box.box);
return iou <= iouThreshold;
});
}
return finalBoxes;
}
function calculateIoU(box1, box2) {
const [x1, y1, x2, y2] = box1;
const [x1_b, y1_b, x2_b, y2_b] = box2;
const interX1 = Math.max(x1, x1_b);
const interY1 = Math.max(y1, y1_b);
const interX2 = Math.min(x2, x2_b);
const interY2 = Math.min(y2, y2_b);
const interArea = Math.max(0, interX2 - interX1) * Math.max(0, interY2 - interY1);
const box1Area = (x2 - x1) * (y2 - y1);
const box2Area = (x2_b - x1_b) * (y2_b - y1_b);
const unionArea = box1Area + box2Area - interArea;
return unionArea > 0 ? interArea / unionArea : 0;
}
function drawDetections(img, boxes, primaryTarget) {
const ctx = outputCanvas.getContext('2d');
outputCanvas.width = img.naturalWidth;
outputCanvas.height = img.naturalHeight;
ctx.drawImage(img, 0, 0, outputCanvas.width, outputCanvas.height);
boxes.forEach(det => {
const isTarget = (det === primaryTarget);
const [x1, y1, x2, y2] = det.box;
const w = x2 - x1;
const h = y2 - y1;
const color = isTarget ? '#ef4444' : COLORS[det.classId % COLORS.length];
ctx.strokeStyle = color;
ctx.lineWidth = isTarget ? Math.max(4, outputCanvas.width * 0.005) : Math.max(2, outputCanvas.width * 0.003);
ctx.strokeRect(x1, y1, w, h);
ctx.fillStyle = color;
const label = `${COCO_CLASSES[det.classId]} (${(det.confidence * 100).toFixed(1)}%)`;
const fontSize = Math.max(14, outputCanvas.width * 0.015);
ctx.font = `bold ${fontSize}px sans-serif`;
const textWidth = ctx.measureText(label).width;
ctx.fillRect(x1 - (ctx.lineWidth / 2), y1 - (fontSize + 8), textWidth + 10, fontSize + 8);
ctx.fillStyle = '#ffffff';
ctx.fillText(label, x1 + 5, y1 - 5);
});
if (primaryTarget) {
const [x1, y1, x2, y2] = primaryTarget.box;
const targetX = x1 + (x2 - x1) / 2;
const targetY = y1 + (y2 - y1) / 2;
const centerX = outputCanvas.width / 2;
const centerY = outputCanvas.height / 2;
ctx.beginPath();
ctx.moveTo(centerX, centerY);
ctx.lineTo(targetX, targetY);
ctx.strokeStyle = 'rgba(239, 68, 68, 0.8)';
ctx.lineWidth = 3;
ctx.setLineDash([10, 5]);
ctx.stroke();
ctx.setLineDash([]);
ctx.beginPath();
ctx.arc(centerX, centerY, 10, 0, 2 * Math.PI);
ctx.fillStyle = 'rgba(255, 255, 255, 0.9)';
ctx.fill();
ctx.strokeStyle = 'rgba(239, 68, 68, 0.9)';
ctx.stroke();
}
}
function displaySummary(boxes) {
resultsSummary.innerHTML = '';
if (boxes.length === 0) {
resultsSummary.innerHTML = '<p class="text-text-secondary text-center">No objects detected.</p>';
return;
}
boxes.forEach(box => {
const wrapper = document.createElement('div');
wrapper.className = 'bg-gray-500/10 rounded-lg p-2 flex items-center gap-3';
const color = COLORS[box.classId % COLORS.length];
const className = COCO_CLASSES[box.classId];
wrapper.innerHTML = `
<div class="w-1 h-8 rounded" style="background-color: ${color}"></div>
<div class="flex-grow">
<div class="flex justify-between items-center">
<span class="font-semibold text-sm text-text-primary">${className}</span>
<span class="font-mono text-xs text-text-primary bg-white/50 dark:bg-black/20 px-1.5 py-0.5 rounded">${(box.confidence * 100).toFixed(1)}%</span>
</div>
<p class="text-xs text-text-secondary font-mono">
Pos: ${Math.round(box.box[0])},${Math.round(box.box[1])}
</p>
</div>`;
resultsSummary.appendChild(wrapper);
});
}
function populatePresetGallery() {
for (let i = 1; i <= 10; i++) {
const thumbSrc = `/images/thumbnails/${i}.jpg`;
const fullSrc = `/images/${i}.jpg`;
const img = document.createElement('img');
img.src = thumbSrc;
img.className = "w-20 h-20 object-cover rounded-lg cursor-pointer border-2 border-transparent hover:border-blue-500 transition-all duration-200 flex-shrink-0";
img.loading = "lazy";
img.alt = `Preset Image ${i}`;
img.onclick = () => handleUrl(fullSrc);
img.onerror = () => {
img.src = `https://placehold.co/80x80/e2e8f0/4b5563?text=Img+${i}`;
img.onclick = null; // Disable click if placeholder
};
presetGallery.appendChild(img);
}
}
// --- App Initialization ---
async function initialize() {
setDarkMode(localStorage.getItem('theme') === 'dark' || (window.matchMedia('(prefers-color-scheme: dark)').matches && !localStorage.getItem('theme')));
createMotorComponent(motorElements.fl, 'fl');
createMotorComponent(motorElements.fr, 'fr');
createMotorComponent(motorElements.rl, 'rl');
createMotorComponent(motorElements.rr, 'rr');
populatePresetGallery();
resetSimulation();
statusFooter.textContent = 'Initializing AI engine...';
showModelLoading(true);
try {
session = await ort.InferenceSession.create(MODEL_URL, { executionProviders: ['wasm'] });
statusFooter.textContent = 'Model is ready. Select an image.';
} catch (e) {
statusFooter.textContent = `Error loading model: ${e.message}`;
showToast(`Failed to load the AI model. Please refresh. ${e.message}`);
} finally {
showModelLoading(false);
}
}
document.addEventListener('DOMContentLoaded', initialize);
</script>
</body>
</html> |