traffic / index.html
AnjaniAI's picture
Add 2 files
64c0164 verified
Raw History Blame Contribute Delete
45.4 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Adaptive Traffic Optimization with YOLO</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<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>
<style>
.traffic-light {
width: 60px;
height: 60px;
border-radius: 50%;
margin: 5px auto;
opacity: 0.3;
transition: all 0.3s ease;
}
.traffic-light.active {
opacity: 1;
box-shadow: 0 0 20px 5px currentColor;
}
.lane-container:hover {
transform: translateY(-5px);
box-shadow: 0 10px 25px rgba(0,0,0,0.1);
}
.chart-container {
height: 300px;
transition: all 0.5s ease;
}
.pulse-animation {
animation: pulse 2s infinite;
}
@keyframes pulse {
0% { transform: scale(1); }
50% { transform: scale(1.05); }
100% { transform: scale(1); }
}
.video-feed {
transition: all 0.3s ease;
position: relative;
background-color: #1a202c;
}
.video-feed:hover {
transform: scale(1.02);
z-index: 10;
}
.detection-canvas {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.vehicle-count-badge {
position: absolute;
top: 10px;
right: 10px;
background-color: rgba(0,0,0,0.7);
color: white;
padding: 5px 10px;
border-radius: 20px;
font-size: 14px;
font-weight: bold;
}
.glow {
box-shadow: 0 0 10px 2px rgba(0, 255, 255, 0.7);
}
.signal-timing-bar {
height: 8px;
border-radius: 4px;
transition: width 0.5s ease;
}
.simulated-video {
width: 100%;
height: 100%;
object-fit: cover;
}
.road-canvas {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body class="bg-gray-100 font-sans">
<div class="container mx-auto px-4 py-8">
<!-- Header -->
<header class="bg-gradient-to-r from-blue-600 to-blue-800 text-white rounded-xl shadow-lg p-6 mb-8 pulse-animation">
<div class="flex flex-col md:flex-row justify-between items-center">
<div>
<h1 class="text-3xl md:text-4xl font-bold mb-2">Adaptive Traffic Optimization System</h1>
<p class="text-blue-100">YOLO-powered real-time traffic signal adjustment based on vehicle density</p>
</div>
<div class="mt-4 md:mt-0 flex items-center space-x-4">
<div class="bg-blue-500 rounded-full p-3 glow">
<i class="fas fa-brain text-white text-2xl"></i>
</div>
<div class="bg-blue-500 rounded-full p-3 glow">
<i class="fas fa-traffic-light text-white text-2xl"></i>
</div>
</div>
</div>
</header>
<!-- Main Dashboard -->
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
<!-- Video Feeds with YOLO Detection -->
<div class="lg:col-span-2 bg-white rounded-xl shadow-md overflow-hidden">
<div class="bg-blue-700 text-white px-4 py-3 flex justify-between items-center">
<h2 class="text-xl font-semibold">Live CCTV Monitoring with YOLO Detection</h2>
<div class="flex space-x-2">
<span class="bg-blue-600 px-3 py-1 rounded-full text-sm">Real-time</span>
<span class="bg-green-500 px-3 py-1 rounded-full text-sm">YOLO Active</span>
</div>
</div>
<div class="grid grid-cols-2 gap-4 p-4">
<!-- Lane 1 Video Feed -->
<div class="video-feed rounded-lg overflow-hidden relative" style="height: 240px;">
<canvas id="lane1-road" class="road-canvas"></canvas>
<canvas id="lane1-canvas" class="detection-canvas"></canvas>
<div class="vehicle-count-badge">
<i class="fas fa-car mr-1"></i>
<span id="lane1-count">0</span> vehicles
</div>
<div class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/70 to-transparent p-3">
<h3 class="text-white font-medium">Lane 1 - Northbound</h3>
<div class="flex justify-between items-center mt-1">
<span class="text-yellow-300 text-sm"><i class="fas fa-car"></i> <span id="lane1-count-text">0</span> vehicles</span>
<span class="text-xs text-white bg-blue-600 px-2 py-1 rounded">Priority: Medium</span>
</div>
</div>
</div>
<!-- Lane 2 Video Feed -->
<div class="video-feed rounded-lg overflow-hidden relative" style="height: 240px;">
<canvas id="lane2-road" class="road-canvas"></canvas>
<canvas id="lane2-canvas" class="detection-canvas"></canvas>
<div class="vehicle-count-badge">
<i class="fas fa-car mr-1"></i>
<span id="lane2-count">0</span> vehicles
</div>
<div class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/70 to-transparent p-3">
<h3 class="text-white font-medium">Lane 2 - Southbound</h3>
<div class="flex justify-between items-center mt-1">
<span class="text-yellow-300 text-sm"><i class="fas fa-car"></i> <span id="lane2-count-text">0</span> vehicles</span>
<span class="text-xs text-white bg-green-600 px-2 py-1 rounded">Priority: Low</span>
</div>
</div>
</div>
<!-- Lane 3 Video Feed -->
<div class="video-feed rounded-lg overflow-hidden relative" style="height: 240px;">
<canvas id="lane3-road" class="road-canvas"></canvas>
<canvas id="lane3-canvas" class="detection-canvas"></canvas>
<div class="vehicle-count-badge">
<i class="fas fa-car mr-1"></i>
<span id="lane3-count">0</span> vehicles
</div>
<div class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/70 to-transparent p-3">
<h3 class="text-white font-medium">Lane 3 - Eastbound</h3>
<div class="flex justify-between items-center mt-1">
<span class="text-yellow-300 text-sm"><i class="fas fa-car"></i> <span id="lane3-count-text">0</span> vehicles</span>
<span class="text-xs text-white bg-red-600 px-2 py-1 rounded">Priority: High</span>
</div>
</div>
</div>
<!-- Lane 4 Video Feed -->
<div class="video-feed rounded-lg overflow-hidden relative" style="height: 240px;">
<canvas id="lane4-road" class="road-canvas"></canvas>
<canvas id="lane4-canvas" class="detection-canvas"></canvas>
<div class="vehicle-count-badge">
<i class="fas fa-car mr-1"></i>
<span id="lane4-count">0</span> vehicles
</div>
<div class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/70 to-transparent p-3">
<h3 class="text-white font-medium">Lane 4 - Westbound</h3>
<div class="flex justify-between items-center mt-1">
<span class="text-yellow-300 text-sm"><i class="fas fa-car"></i> <span id="lane4-count-text">0</span> vehicles</span>
<span class="text-xs text-white bg-green-600 px-2 py-1 rounded">Priority: Low</span>
</div>
</div>
</div>
</div>
</div>
<!-- Traffic Light Control -->
<div class="bg-white rounded-xl shadow-md overflow-hidden">
<div class="bg-blue-700 text-white px-4 py-3">
<h2 class="text-xl font-semibold">Traffic Signal Control</h2>
</div>
<div class="p-6">
<div class="flex justify-center mb-6">
<div class="bg-gray-900 p-4 rounded-lg inline-block">
<div class="traffic-light bg-red-600" id="red-light"></div>
<div class="traffic-light bg-yellow-500" id="yellow-light"></div>
<div class="traffic-light bg-green-500" id="green-light"></div>
</div>
</div>
<div class="mb-6">
<h3 class="text-lg font-medium text-gray-700 mb-3">Current Signal Timing</h3>
<div class="bg-gray-100 rounded-lg p-4">
<div class="flex justify-between items-center mb-2">
<span class="text-gray-700">Active Lane:</span>
<span class="font-semibold" id="active-lane">Lane 1 (Northbound)</span>
</div>
<div class="flex justify-between items-center">
<span class="text-gray-700">Time Remaining:</span>
<span class="font-semibold text-blue-600" id="time-remaining">30s</span>
</div>
</div>
</div>
<div class="mb-6">
<h3 class="text-lg font-medium text-gray-700 mb-3">Signal Timing Progress</h3>
<div class="bg-gray-200 rounded-full h-2.5">
<div id="signal-timing-progress" class="bg-blue-600 h-2.5 rounded-full signal-timing-bar" style="width: 100%"></div>
</div>
</div>
<div class="space-y-3">
<h3 class="text-lg font-medium text-gray-700">Next Signal Prediction</h3>
<div class="space-y-2">
<div class="flex justify-between items-center bg-blue-50 p-3 rounded-lg">
<span>Lane 1 (Northbound)</span>
<span class="text-blue-600 font-medium" id="lane1-time">30s</span>
</div>
<div class="flex justify-between items-center bg-gray-50 p-3 rounded-lg">
<span>Lane 2 (Southbound)</span>
<span class="text-gray-600 font-medium" id="lane2-time">20s</span>
</div>
<div class="flex justify-between items-center bg-gray-50 p-3 rounded-lg">
<span>Lane 3 (Eastbound)</span>
<span class="text-gray-600 font-medium" id="lane3-time">25s</span>
</div>
<div class="flex justify-between items-center bg-gray-50 p-3 rounded-lg">
<span>Lane 4 (Westbound)</span>
<span class="text-gray-600 font-medium" id="lane4-time">15s</span>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Statistics and Analytics -->
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
<!-- Lane 1 Stats -->
<div class="lane-container bg-white rounded-xl shadow-md p-6 transition-all duration-300">
<div class="flex justify-between items-start mb-4">
<div>
<h3 class="text-gray-500 font-medium">Lane 1</h3>
<h2 class="text-2xl font-bold text-blue-600" id="lane1-count-big">0</h2>
</div>
<div class="bg-blue-100 p-3 rounded-full">
<i class="fas fa-car text-blue-600"></i>
</div>
</div>
<div class="h-2 bg-gray-200 rounded-full mb-2">
<div class="h-2 bg-blue-600 rounded-full" id="lane1-bar" style="width: 0%"></div>
</div>
<div class="flex justify-between text-sm text-gray-500">
<span>0</span>
<span id="lane1-max">20 vehicles</span>
</div>
</div>
<!-- Lane 2 Stats -->
<div class="lane-container bg-white rounded-xl shadow-md p-6 transition-all duration-300">
<div class="flex justify-between items-start mb-4">
<div>
<h3 class="text-gray-500 font-medium">Lane 2</h3>
<h2 class="text-2xl font-bold text-green-600" id="lane2-count-big">0</h2>
</div>
<div class="bg-green-100 p-3 rounded-full">
<i class="fas fa-truck text-green-600"></i>
</div>
</div>
<div class="h-2 bg-gray-200 rounded-full mb-2">
<div class="h-2 bg-green-600 rounded-full" id="lane2-bar" style="width: 0%"></div>
</div>
<div class="flex justify-between text-sm text-gray-500">
<span>0</span>
<span id="lane2-max">20 vehicles</span>
</div>
</div>
<!-- Lane 3 Stats -->
<div class="lane-container bg-white rounded-xl shadow-md p-6 transition-all duration-300">
<div class="flex justify-between items-start mb-4">
<div>
<h3 class="text-gray-500 font-medium">Lane 3</h3>
<h2 class="text-2xl font-bold text-red-600" id="lane3-count-big">0</h2>
</div>
<div class="bg-red-100 p-3 rounded-full">
<i class="fas fa-bus text-red-600"></i>
</div>
</div>
<div class="h-2 bg-gray-200 rounded-full mb-2">
<div class="h-2 bg-red-600 rounded-full" id="lane3-bar" style="width: 0%"></div>
</div>
<div class="flex justify-between text-sm text-gray-500">
<span>0</span>
<span id="lane3-max">20 vehicles</span>
</div>
</div>
<!-- Lane 4 Stats -->
<div class="lane-container bg-white rounded-xl shadow-md p-6 transition-all duration-300">
<div class="flex justify-between items-start mb-4">
<div>
<h3 class="text-gray-500 font-medium">Lane 4</h3>
<h2 class="text-2xl font-bold text-green-600" id="lane4-count-big">0</h2>
</div>
<div class="bg-green-100 p-3 rounded-full">
<i class="fas fa-motorcycle text-green-600"></i>
</div>
</div>
<div class="h-2 bg-gray-200 rounded-full mb-2">
<div class="h-2 bg-green-600 rounded-full" id="lane4-bar" style="width: 0%"></div>
</div>
<div class="flex justify-between text-sm text-gray-500">
<span>0</span>
<span id="lane4-max">20 vehicles</span>
</div>
</div>
</div>
<!-- System Controls -->
<div class="bg-white rounded-xl shadow-md overflow-hidden mb-8">
<div class="bg-blue-700 text-white px-4 py-3 flex justify-between items-center">
<h2 class="text-xl font-semibold">System Controls</h2>
<div class="flex items-center space-x-2">
<span class="bg-green-500 px-3 py-1 rounded-full text-sm">System Active</span>
<div class="w-3 h-3 bg-green-400 rounded-full animate-pulse"></div>
</div>
</div>
<div class="p-6 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
<div class="flex flex-col items-center">
<button id="start-btn" class="bg-green-600 hover:bg-green-700 text-white px-6 py-3 rounded-lg mb-2 w-full transition-colors">
<i class="fas fa-play mr-2"></i> Start Detection
</button>
<p class="text-gray-500 text-sm text-center">Begin vehicle detection and analysis</p>
</div>
<div class="flex flex-col items-center">
<button id="pause-btn" class="bg-yellow-500 hover:bg-yellow-600 text-white px-6 py-3 rounded-lg mb-2 w-full transition-colors">
<i class="fas fa-pause mr-2"></i> Pause System
</button>
<p class="text-gray-500 text-sm text-center">Temporarily stop detection</p>
</div>
<div class="flex flex-col items-center">
<button id="reset-btn" class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-lg mb-2 w-full transition-colors">
<i class="fas fa-sync-alt mr-2"></i> Reset Counts
</button>
<p class="text-gray-500 text-sm text-center">Reset all vehicle counts</p>
</div>
<div class="flex flex-col items-center">
<button id="stop-btn" class="bg-red-600 hover:bg-red-700 text-white px-6 py-3 rounded-lg mb-2 w-full transition-colors">
<i class="fas fa-power-off mr-2"></i> Stop System
</button>
<p class="text-gray-500 text-sm text-center">Stop all detection</p>
</div>
</div>
</div>
<!-- Performance Metrics -->
<div class="bg-white rounded-xl shadow-md overflow-hidden">
<div class="bg-blue-700 text-white px-4 py-3">
<h2 class="text-xl font-semibold">Performance Metrics</h2>
</div>
<div class="p-6 grid grid-cols-1 md:grid-cols-3 gap-6">
<div class="text-center">
<div class="text-4xl font-bold text-blue-600 mb-2" id="wait-time">0%</div>
<div class="text-gray-700 font-medium">Reduction in wait time</div>
<div class="text-gray-500 text-sm mt-1">Compared to fixed timing</div>
</div>
<div class="text-center">
<div class="text-4xl font-bold text-green-600 mb-2" id="throughput">0%</div>
<div class="text-gray-700 font-medium">Increase in throughput</div>
<div class="text-gray-500 text-sm mt-1">More vehicles per hour</div>
</div>
<div class="text-center">
<div class="text-4xl font-bold text-purple-600 mb-2" id="fuel-savings">0%</div>
<div class="text-gray-700 font-medium">Fuel savings</div>
<div class="text-gray-500 text-sm mt-1">Less idling time</div>
</div>
</div>
</div>
</div>
<!-- Footer -->
<footer class="bg-gray-800 text-white py-6">
<div class="container mx-auto px-4">
<div class="flex flex-col md:flex-row justify-between items-center">
<div class="mb-4 md:mb-0">
<h3 class="text-xl font-bold">Adaptive Traffic Optimization</h3>
<p class="text-gray-400">YOLO-powered smart traffic management system</p>
</div>
<div class="flex space-x-4">
<a href="#" class="text-gray-400 hover:text-white transition-colors">
<i class="fab fa-github text-xl"></i>
</a>
<a href="#" class="text-gray-400 hover:text-white transition-colors">
<i class="fab fa-linkedin text-xl"></i>
</a>
<a href="#" class="text-gray-400 hover:text-white transition-colors">
<i class="fas fa-envelope text-xl"></i>
</a>
</div>
</div>
<div class="mt-6 pt-6 border-t border-gray-700 text-center text-gray-400 text-sm">
&copy; 2023 Adaptive Traffic Optimization System. All rights reserved.
</div>
</div>
</footer>
<script>
// Global variables
let model = null;
let isDetectionRunning = false;
let detectionInterval = null;
const vehicleCounts = [0, 0, 0, 0];
const maxVehicleCounts = [20, 20, 20, 20];
let currentActiveLane = 0; // 0-3 for lanes 1-4
let timeRemaining = 30;
let totalSignalTime = 30;
let trafficLightInterval = null;
let roadCanvases = [];
let roadContexts = [];
// DOM elements
const canvasElements = [
document.getElementById('lane1-canvas'),
document.getElementById('lane2-canvas'),
document.getElementById('lane3-canvas'),
document.getElementById('lane4-canvas')
];
// Road canvases for simulated CCTV footage
const roadCanvasElements = [
document.getElementById('lane1-road'),
document.getElementById('lane2-road'),
document.getElementById('lane3-road'),
document.getElementById('lane4-road')
];
// Initialize the application
document.addEventListener('DOMContentLoaded', async function() {
// Set green light active initially
document.getElementById('green-light').classList.add('active');
// Load COCO-SSD model (YOLO-like model)
try {
console.log("Loading COCO-SSD model...");
model = await cocoSsd.load();
console.log("Model loaded successfully");
// Enable start button
document.getElementById('start-btn').disabled = false;
} catch (error) {
console.error("Failed to load model:", error);
alert("Failed to load the AI model. Please check your internet connection.");
}
// Setup road canvases for simulated CCTV footage
setupRoadCanvases();
// Setup event listeners for buttons
document.getElementById('start-btn').addEventListener('click', startDetection);
document.getElementById('pause-btn').addEventListener('click', pauseDetection);
document.getElementById('reset-btn').addEventListener('click', resetCounts);
document.getElementById('stop-btn').addEventListener('click', stopDetection);
// Start traffic light simulation
startTrafficLightSimulation();
// Simulate some initial data for demo purposes
simulateInitialData();
});
// Setup road canvases for simulated CCTV footage
function setupRoadCanvases() {
roadCanvasElements.forEach((canvas, index) => {
// Set canvas dimensions
const container = canvas.parentElement;
canvas.width = container.clientWidth;
canvas.height = container.clientHeight;
const ctx = canvas.getContext('2d');
roadContexts.push(ctx);
// Draw initial road
drawRoadScene(ctx, canvas.width, canvas.height, index);
// Start animation
animateRoad(index);
});
}
// Draw a road scene on canvas
function drawRoadScene(ctx, width, height, laneIndex) {
// Draw road background
ctx.fillStyle = '#2d3748';
ctx.fillRect(0, 0, width, height);
// Draw lane markings
ctx.strokeStyle = '#e2e8f0';
ctx.lineWidth = 2;
// Draw center line (dashed)
ctx.beginPath();
const centerY = height / 2;
for (let x = 0; x < width; x += 20) {
ctx.moveTo(x, centerY);
ctx.lineTo(x + 10, centerY);
}
ctx.stroke();
// Draw side lines (solid)
ctx.beginPath();
ctx.moveTo(0, 10);
ctx.lineTo(width, 10);
ctx.moveTo(0, height - 10);
ctx.lineTo(width, height - 10);
ctx.stroke();
// Draw some static background elements (buildings, trees, etc.)
ctx.fillStyle = '#4a5568';
for (let i = 0; i < 3; i++) {
const buildingWidth = 40 + Math.random() * 40;
const buildingHeight = 30 + Math.random() * 70;
ctx.fillRect(
width * 0.2 + i * 100,
height - buildingHeight - 10,
buildingWidth,
buildingHeight
);
}
}
// Animate road scene with moving vehicles
function animateRoad(laneIndex) {
const canvas = roadCanvasElements[laneIndex];
const ctx = roadContexts[laneIndex];
const width = canvas.width;
const height = canvas.height;
// Clear canvas
ctx.clearRect(0, 0, width, height);
// Redraw static elements
drawRoadScene(ctx, width, height, laneIndex);
// Draw moving vehicles (simulated)
const vehicleCount = vehicleCounts[laneIndex];
const maxVehicles = maxVehicleCounts[laneIndex];
const actualVehicles = Math.min(vehicleCount, maxVehicles);
// Draw vehicles based on count
for (let i = 0; i < actualVehicles; i++) {
drawVehicle(ctx, width, height, laneIndex, i, actualVehicles);
}
// Continue animation
requestAnimationFrame(() => animateRoad(laneIndex));
}
// Draw a vehicle on the road
function drawVehicle(ctx, width, height, laneIndex, vehicleIndex, totalVehicles) {
const now = Date.now();
const centerY = height / 2;
const laneHeight = height / 3;
// Determine vehicle type and color based on lane and index
let vehicleType, color;
if (laneIndex === 0) {
vehicleType = 'car';
color = '#3b82f6'; // blue
} else if (laneIndex === 1) {
vehicleType = 'truck';
color = '#10b981'; // green
} else if (laneIndex === 2) {
vehicleType = 'bus';
color = '#ef4444'; // red
} else {
vehicleType = 'motorcycle';
color = '#10b981'; // green
}
// Calculate position based on time and index for smooth movement
const speed = 0.5 + Math.random() * 0.3;
const xPos = (now * 0.05 * speed + vehicleIndex * (width / totalVehicles)) % (width + 100) - 50;
// Draw vehicle body
ctx.fillStyle = color;
if (vehicleType === 'car') {
ctx.fillRect(xPos, centerY - 15, 40, 20);
// Windows
ctx.fillStyle = '#93c5fd';
ctx.fillRect(xPos + 5, centerY - 12, 30, 8);
}
else if (vehicleType === 'truck') {
ctx.fillRect(xPos, centerY - 20, 60, 30);
// Cabin
ctx.fillStyle = '#6ee7b7';
ctx.fillRect(xPos + 40, centerY - 20, 20, 15);
}
else if (vehicleType === 'bus') {
ctx.fillRect(xPos, centerY - 25, 50, 30);
// Windows
ctx.fillStyle = '#fca5a5';
for (let i = 0; i < 4; i++) {
ctx.fillRect(xPos + 5 + i * 10, centerY - 20, 8, 10);
}
}
else { // motorcycle
ctx.fillRect(xPos, centerY - 10, 25, 10);
// Seat
ctx.fillStyle = '#a7f3d0';
ctx.fillRect(xPos + 5, centerY - 8, 15, 5);
}
// Wheels
ctx.fillStyle = '#1e293b';
if (vehicleType === 'motorcycle') {
ctx.beginPath();
ctx.arc(xPos + 5, centerY, 5, 0, Math.PI * 2);
ctx.arc(xPos + 20, centerY, 5, 0, Math.PI * 2);
ctx.fill();
} else {
ctx.beginPath();
ctx.arc(xPos + 8, centerY + (vehicleType === 'bus' ? 10 : 10), 5, 0, Math.PI * 2);
ctx.arc(xPos + (vehicleType === 'bus' ? 42 : 32), centerY + (vehicleType === 'bus' ? 10 : 10), 5, 0, Math.PI * 2);
ctx.fill();
}
}
// Start vehicle detection
function startDetection() {
if (!model) {
alert("AI model is not loaded yet. Please wait.");
return;
}
if (isDetectionRunning) return;
isDetectionRunning = true;
console.log("Starting vehicle detection...");
// Run detection every 1 second
detectionInterval = setInterval(() => {
detectVehicles();
}, 1000);
// Update UI
document.getElementById('start-btn').classList.remove('bg-green-600');
document.getElementById('start-btn').classList.add('bg-gray-500');
document.getElementById('start-btn').disabled = true;
document.getElementById('pause-btn').disabled = false;
document.getElementById('stop-btn').disabled = false;
}
// Pause detection
function pauseDetection() {
if (!isDetectionRunning) return;
isDetectionRunning = false;
clearInterval(detectionInterval);
console.log("Vehicle detection paused");
// Update UI
document.getElementById('start-btn').classList.remove('bg-gray-500');
document.getElementById('start-btn').classList.add('bg-green-600');
document.getElementById('start-btn').disabled = false;
}
// Stop detection
function stopDetection() {
isDetectionRunning = false;
clearInterval(detectionInterval);
console.log("Vehicle detection stopped");
// Clear all detections
canvasElements.forEach(canvas => {
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
});
// Update UI
document.getElementById('start-btn').classList.remove('bg-gray-500');
document.getElementById('start-btn').classList.add('bg-green-600');
document.getElementById('start-btn').disabled = false;
document.getElementById('pause-btn').disabled = true;
}
// Reset all counts
function resetCounts() {
for (let i = 0; i < 4; i++) {
vehicleCounts[i] = 0;
updateLaneUI(i);
}
console.log("All vehicle counts reset");
}
// Detect vehicles in all lanes (simulated for demo)
async function detectVehicles() {
for (let i = 0; i < 4; i++) {
try {
// Simulate vehicle detection with random variation
const baseCount = vehicleCounts[i];
const variation = Math.floor(Math.random() * 3) - 1; // -1, 0, or 1
let newCount = baseCount + variation;
// Keep counts within reasonable bounds
newCount = Math.max(0, newCount);
newCount = Math.min(maxVehicleCounts[i], newCount);
vehicleCounts[i] = newCount;
// Simulate drawing detections on canvas
simulateDetections(canvasElements[i], newCount, i);
// Update UI for this lane
updateLaneUI(i);
// Update traffic light timing based on vehicle density
updateTrafficTiming();
} catch (error) {
console.error(`Error detecting vehicles in lane ${i + 1}:`, error);
}
}
}
// Simulate detections on canvas
function simulateDetections(canvas, count, laneIndex) {
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Only draw if count > 0
if (count <= 0) return;
// Font settings
ctx.font = '16px Arial';
ctx.textBaseline = 'top';
// Draw simulated bounding boxes
for (let i = 0; i < count; i++) {
// Random position and size for the bounding box
const width = 60 + Math.random() * 40;
const height = 40 + Math.random() * 20;
const x = Math.random() * (canvas.width - width);
const y = Math.random() * (canvas.height - height);
// Determine vehicle type based on lane
let vehicleType;
if (laneIndex === 0) vehicleType = 'car';
else if (laneIndex === 1) vehicleType = 'truck';
else if (laneIndex === 2) vehicleType = 'bus';
else vehicleType = 'motorcycle';
// Random confidence score (70-100%)
const score = 0.7 + Math.random() * 0.3;
// Draw bounding box
ctx.strokeStyle = '#00FFFF';
ctx.lineWidth = 2;
ctx.strokeRect(x, y, width, height);
// Draw label background
ctx.fillStyle = '#00FFFF';
const text = `${vehicleType} ${Math.round(score * 100)}%`;
const textWidth = ctx.measureText(text).width;
const textHeight = 16;
ctx.fillRect(x, y, textWidth + 4, textHeight + 4);
// Draw text
ctx.fillStyle = '#000000';
ctx.fillText(text, x + 2, y + 2);
}
}
// Update UI for a specific lane
function updateLaneUI(laneIndex) {
const count = vehicleCounts[laneIndex];
const maxCount = maxVehicleCounts[laneIndex];
const percentage = Math.min(100, (count / maxCount) * 100);
// Update count displays
document.getElementById(`lane${laneIndex + 1}-count`).textContent = count;
document.getElementById(`lane${laneIndex + 1}-count-text`).textContent = count;
document.getElementById(`lane${laneIndex + 1}-count-big`).textContent = count;
// Update progress bar
document.getElementById(`lane${laneIndex + 1}-bar`).style.width = `${percentage}%`;
// Update priority indicator
const priorityElement = document.querySelector(`#lane${laneIndex + 1}-count-text`).parentElement.nextElementSibling;
if (count > maxCount * 0.75) { // High priority
priorityElement.textContent = "Priority: High";
priorityElement.className = "text-xs text-white bg-red-600 px-2 py-1 rounded";
} else if (count > maxCount * 0.4) { // Medium priority
priorityElement.textContent = "Priority: Medium";
priorityElement.className = "text-xs text-white bg-blue-600 px-2 py-1 rounded";
} else { // Low priority
priorityElement.textContent = "Priority: Low";
priorityElement.className = "text-xs text-white bg-green-600 px-2 py-1 rounded";
}
}
// Update traffic light timing based on vehicle density
function updateTrafficTiming() {
// Calculate base times (10-30 seconds) based on vehicle counts
const baseTimes = vehicleCounts.map(count => {
// Minimum 10s, maximum 30s, scaled by vehicle count
return 10 + Math.min(20, count * 2);
});
// Update the display for next signal prediction
for (let i = 0; i < 4; i++) {
document.getElementById(`lane${i + 1}-time`).textContent = `${baseTimes[i]}s`;
}
// Update performance metrics based on current counts
updatePerformanceMetrics();
}
// Update performance metrics
function updatePerformanceMetrics() {
// Simple calculations based on vehicle distribution
const totalVehicles = vehicleCounts.reduce((sum, count) => sum + count, 0);
if (totalVehicles > 0) {
// Calculate how balanced the traffic is
const balancedIndex = Math.min(1, Math.max(0,
1 - (Math.std(vehicleCounts) / (totalVehicles / 4))));
// Update metrics based on balance
document.getElementById('wait-time').textContent =
`${Math.round(30 * balancedIndex)}%`;
document.getElementById('throughput').textContent =
`${Math.round(45 * balancedIndex)}%`;
document.getElementById('fuel-savings').textContent =
`${Math.round(28 * balancedIndex)}%`;
}
}
// Calculate standard deviation (helper for performance metrics)
Math.std = function(arr) {
const mean = arr.reduce((sum, val) => sum + val, 0) / arr.length;
return Math.sqrt(
arr.reduce((sum, val) => sum + Math.pow(val - mean, 2), 0) / arr.length
);
};
// Traffic light simulation
function startTrafficLightSimulation() {
// Start with lane 1 (index 0)
currentActiveLane = 0;
timeRemaining = 30;
totalSignalTime = 30;
updateActiveLaneDisplay();
// Run the simulation
trafficLightInterval = setInterval(() => {
timeRemaining--;
document.getElementById('time-remaining').textContent = `${timeRemaining}s`;
// Update progress bar
const progressPercentage = (timeRemaining / totalSignalTime) * 100;
document.getElementById('signal-timing-progress').style.width = `${progressPercentage}%`;
if (timeRemaining <= 0) {
// Change to next lane
currentActiveLane = (currentActiveLane + 1) % 4;
// Get the base time for this lane (10-30s)
const baseTime = 10 + Math.min(20, vehicleCounts[currentActiveLane] * 2);
timeRemaining = baseTime;
totalSignalTime = baseTime;
// Update display
updateActiveLaneDisplay();
// Animate traffic light change
changeTrafficLight();
}
}, 1000);
}
// Update active lane display
function updateActiveLaneDisplay() {
const laneNames = [
"Lane 1 (Northbound)",
"Lane 2 (Southbound)",
"Lane 3 (Eastbound)",
"Lane 4 (Westbound)"
];
document.getElementById('active-lane').textContent = laneNames[currentActiveLane];
document.getElementById('time-remaining').textContent = `${timeRemaining}s`;
// Reset progress bar
document.getElementById('signal-timing-progress').style.width = '100%';
}
// Animate traffic light change
function changeTrafficLight() {
// Current green turns yellow
document.getElementById('green-light').classList.remove('active');
document.getElementById('yellow-light').classList.add('active');
// After 2 seconds, yellow turns red and next green activates
setTimeout(() => {
document.getElementById('yellow-light').classList.remove('active');
document.getElementById('red-light').classList.add('active');
setTimeout(() => {
document.getElementById('red-light').classList.remove('active');
document.getElementById('green-light').classList.add('active');
}, 1000);
}, 2000);
}
// Simulate some initial data for demo purposes
function simulateInitialData() {
// Set some initial vehicle counts
vehicleCounts[0] = 12; // Lane 1
vehicleCounts[1] = 5; // Lane 2
vehicleCounts[2] = 18; // Lane 3
vehicleCounts[3] = 3; // Lane 4
// Update UI for all lanes
for (let i = 0; i < 4; i++) {
updateLaneUI(i);
}
// Update traffic timing
updateTrafficTiming();
}
</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=AnjaniAI/traffic" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p></body>
</html>