Spaces:
Runtime error
Runtime error
File size: 12,402 Bytes
aee643c | 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 | import gradio as gr
import numpy as np
import cv2
import time
import json
from datetime import datetime
from typing import List, Dict, Tuple, Optional
import random
class SecuritySystem:
def __init__(self):
self.detection_history = []
self.alarm_settings = {
"sensitivity": 0.5,
"detection_zones": [],
"alarm_sound": True,
"email_alerts": False,
"motion_threshold": 30,
"alert_cooldown": 10
}
self.last_alert_time = 0
self.is_monitoring = False
def detect_people(self, frame: np.ndarray) -> Tuple[np.ndarray, List[Dict]]:
"""Mock person detection with random bounding boxes"""
height, width = frame.shape[:2]
detections = []
# Simulate random detections
if random.random() < self.alarm_settings["sensitivity"]:
num_people = random.randint(0, 3)
for i in range(num_people):
x1 = random.randint(50, width - 150)
y1 = random.randint(50, height - 150)
x2 = x1 + random.randint(80, 150)
y2 = y1 + random.randint(120, 200)
confidence = random.uniform(0.7, 0.95)
detections.append({
"bbox": (x1, y1, x2, y2),
"confidence": confidence,
"label": "Person",
"timestamp": datetime.now().strftime("%H:%M:%S")
})
# Draw bounding box
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(frame, f"Person {confidence:.2f}",
(x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
return frame, detections
def check_alarm_trigger(self, detections: List[Dict]) -> bool:
"""Check if alarm should be triggered"""
current_time = time.time()
if current_time - self.last_alert_time < self.alarm_settings["alert_cooldown"]:
return False
if detections and self.alarm_settings["sensitivity"] > 0.3:
self.last_alert_time = current_time
return True
return False
def log_detection(self, detections: List[Dict]):
"""Log detection events"""
for detection in detections:
event = {
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"type": "Person Detected",
"confidence": detection["confidence"],
"location": detection["bbox"]
}
self.detection_history.append(event)
if len(self.detection_history) > 100:
self.detection_history.pop(0)
security_system = SecuritySystem()
def process_camera_stream(frame: np.ndarray, enable_detection: bool) -> Tuple[np.ndarray, str, str]:
"""Process camera frame for person detection"""
if frame is None:
return np.zeros((480, 640, 3), dtype=np.uint8), "No camera feed", "System Idle"
if enable_detection:
processed_frame, detections = security_system.detect_people(frame.copy())
# Check for alarm trigger
alarm_status = "Monitoring"
if security_system.check_alarm_trigger(detections):
alarm_status = "ALARM TRIGGERED!"
security_system.log_detection(detections)
# Update status
status_text = f"Active | Detections: {len(detections)}"
if detections:
status_text += f" | Last: {detections[-1]['timestamp']}"
return processed_frame, status_text, alarm_status
else:
return frame, "Camera Active", "Monitoring Disabled"
def update_alarm_settings(sensitivity: float, motion_threshold: int,
alarm_sound: bool, email_alerts: bool,
alert_cooldown: int) -> str:
"""Update alarm system settings"""
security_system.alarm_settings.update({
"sensitivity": sensitivity,
"motion_threshold": motion_threshold,
"alarm_sound": alarm_sound,
"email_alerts": email_alerts,
"alert_cooldown": alert_cooldown
})
return "Settings updated successfully!"
def get_detection_log() -> str:
"""Get formatted detection history"""
if not security_system.detection_history:
return "No detections recorded yet"
log_text = "=== Detection Log ===\n"
for event in security_system.detection_history[-10:]: # Show last 10 events
log_text += f"{event['timestamp']} - {event['type']} (Confidence: {event['confidence']:.2f})\n"
return log_text
def get_system_stats() -> Dict:
"""Get system statistics"""
total_detections = len(security_system.detection_history)
recent_detections = sum(1 for event in security_system.detection_history
if (datetime.now() - datetime.strptime(event['timestamp'], "%Y-%m-%d %H:%M:%S")).seconds < 3600)
return {
"Total Detections": total_detections,
"Last Hour": recent_detections,
"System Status": "Active" if security_system.is_monitoring else "Inactive",
"Sensitivity": f"{security_system.alarm_settings['sensitivity']:.0%}"
}
def toggle_monitoring(state: str) -> Tuple[str, str]:
"""Toggle monitoring state"""
security_system.is_monitoring = state == "Start Monitoring"
status = "Monitoring Active" if security_system.is_monitoring else "Monitoring Stopped"
color = "green" if security_system.is_monitoring else "red"
return status, color
with gr.Blocks(title="Security System Dashboard", theme=gr.themes.Soft()) as demo:
gr.HTML("""
<div style="text-align: center; margin-bottom: 20px;">
<h1>🔒 Security System Dashboard</h1>
<p>Real-time person detection and alarm management system</p>
<a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank" style="color: inherit; text-decoration: none;">
Built with anycoder
</a>
</div>
""")
with gr.Row():
with gr.Column(scale=2):
# Camera Feed Section
with gr.Group():
gr.Markdown("### 📹 Live Camera Feed")
with gr.Row():
camera_input = gr.Image(
sources=["webcam"],
streaming=True,
label="Camera Input",
height=400
)
processed_output = gr.Image(
label="Processed Feed (with Detections)",
height=400
)
with gr.Row():
enable_detection = gr.Checkbox(
label="Enable Person Detection",
value=True
)
monitor_btn = gr.Radio(
choices=["Start Monitoring", "Stop Monitoring"],
value="Stop Monitoring",
label="Monitoring Control"
)
status_display = gr.Textbox(
label="System Status",
value="System Idle",
interactive=False
)
alarm_display = gr.Textbox(
label="Alarm Status",
value="Monitoring Disabled",
interactive=False
)
with gr.Column(scale=1):
# Control Panel
with gr.Group():
gr.Markdown("### ⚙️ Alarm Settings")
sensitivity = gr.Slider(
minimum=0.1,
maximum=1.0,
value=0.5,
step=0.1,
label="Detection Sensitivity"
)
motion_threshold = gr.Slider(
minimum=10,
maximum=100,
value=30,
step=5,
label="Motion Threshold"
)
alarm_sound = gr.Checkbox(
label="Enable Alarm Sound",
value=True
)
email_alerts = gr.Checkbox(
label="Enable Email Alerts",
value=False
)
alert_cooldown = gr.Slider(
minimum=5,
maximum=60,
value=10,
step=5,
label="Alert Cooldown (seconds)"
)
update_btn = gr.Button("Update Settings", variant="primary")
settings_message = gr.Textbox(
label="Settings Status",
interactive=False
)
with gr.Row():
with gr.Column():
# Detection Log
with gr.Group():
gr.Markdown("### 📋 Detection Log")
detection_log = gr.Textbox(
label="Recent Events",
value="No detections recorded yet",
lines=8,
interactive=False
)
refresh_log_btn = gr.Button("Refresh Log")
with gr.Column():
# Statistics
with gr.Group():
gr.Markdown("### 📊 System Statistics")
stats_display = gr.JSON(
label="Live Statistics",
value=get_system_stats()
)
refresh_stats_btn = gr.Button("Refresh Stats")
# Event Handlers
def process_frame(frame, detection_enabled, monitor_state):
status, color = toggle_monitoring(monitor_state)
processed, status_text, alarm_text = process_camera_stream(frame, detection_enabled)
return processed, status_text, alarm_text
camera_input.stream(
process_frame,
inputs=[camera_input, enable_detection, monitor_btn],
outputs=[processed_output, status_display, alarm_display],
time_limit=30,
stream_every=0.5,
concurrency_limit=30
)
update_btn.click(
update_alarm_settings,
inputs=[sensitivity, motion_threshold, alarm_sound, email_alerts, alert_cooldown],
outputs=[settings_message]
)
refresh_log_btn.click(
get_detection_log,
outputs=[detection_log]
)
refresh_stats_btn.click(
get_system_stats,
outputs=[stats_display]
)
# Auto-refresh components
demo.load(
get_detection_log,
outputs=[detection_log]
)
demo.load(
get_system_stats,
outputs=[stats_display]
)
# Instructions
with gr.Accordion("📖 Instructions", open=False):
gr.Markdown("""
### How to Use the Security System:
1. **Camera Setup**: Allow camera access when prompted. The system will display the live feed.
2. **Enable Detection**: Check "Enable Person Detection" to start monitoring for people.
3. **Start Monitoring**: Click "Start Monitoring" to activate the security system.
4. **Configure Alarms**:
- Adjust sensitivity to control detection sensitivity
- Set motion threshold for movement detection
- Enable/disable alarm sounds and email alerts
- Configure alert cooldown to prevent spam
5. **Monitor Activity**:
- View processed feed with detection boxes
- Check system status and alarm status
- Review detection log for recent events
- Monitor system statistics
### Features:
- Real-time person detection with confidence scores
- Customizable alarm settings
- Detection event logging
- Live statistics dashboard
- Adjustable sensitivity and thresholds
**Note**: This is a demonstration system with simulated detection for testing purposes.
""")
if __name__ == "__main__":
demo.launch(share=True) |