kamcio1989's picture
Create app.py
aee643c verified
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)