import os os.environ["OPENCV_IO_ENABLE_OPENEXR"] = "1" import streamlit as st from ultralytics import YOLO import cv2 import numpy as np from PIL import Image import urllib.request st.set_page_config( page_title="🔫 Weapon Detection + Thermal", page_icon="🔫", layout="wide" ) # Custom CSS st.markdown(""" """, unsafe_allow_html=True) @st.cache_resource def load_model(): """Load weapon detection model with caching and priority""" weapon_model_url = "https://github.com/Musawer1214/Weapon-Detection-YOLO/raw/main/weapon_detection_best.pt" weapon_model_path = "weapon_best.pt" custom_model_path = "custom_model_v2.pt" model = None model_source = "None" # Priority 1: Custom Trained Model (Local) if os.path.exists(custom_model_path): try: model = YOLO(custom_model_path) model_source = "Custom Trained Model (Verified)" except Exception as e: st.warning(f"Failed to load custom model: {e}") # Priority 2: Pre-trained GitHub Model if model is None: if not os.path.exists(weapon_model_path): with st.spinner("📥 Downloading specialized weapon detection model..."): try: urllib.request.urlretrieve(weapon_model_url, weapon_model_path) except: pass if os.path.exists(weapon_model_path): try: model = YOLO(weapon_model_path) model_source = "GitHub Pre-trained Model" except: pass # Priority 3: Fallback YOLOv8n if model is None: st.warning("⚠️ Using standard YOLOv8n fallback model (Low Accuracy for Weapons)") model = YOLO('yolov8n.pt') model_source = "YOLOv8n Fallback" return model, model_source def convert_to_thermal(image): """Convert normal image to thermal-style image (Simulated)""" img_array = np.array(image) if len(img_array.shape) == 2: # Already grayscale gray = img_array else: gray = cv2.cvtColor(img_array, cv2.COLOR_RGB2GRAY) blurred = cv2.GaussianBlur(gray, (9, 9), 0) clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8)) enhanced = clahe.apply(blurred) thermal = cv2.applyColorMap(enhanced, cv2.COLORMAP_JET) thermal_rgb = cv2.cvtColor(thermal, cv2.COLOR_BGR2RGB) return thermal_rgb def detect_weapons_hybrid(model, image, confidence_threshold=0.3): """Run Hybrid (AI + OpenCV) detection""" # AI Detection results = model(image, conf=confidence_threshold) ai_annotated = results[0].plot() ai_detections = [] for box in results[0].boxes: cls_id = int(box.cls[0]) class_name = results[0].names[cls_id] detection = { 'class': class_name, 'confidence': float(box.conf[0]), 'bbox': box.xyxy[0].tolist(), 'source': 'AI' } ai_detections.append(detection) return ai_annotated, ai_detections # Main UI st.markdown('

🔫 Weapon Detection System

', unsafe_allow_html=True) # Load model model, source_name = load_model() st.caption(f"🤖 Active Model: **{source_name}**") # Sidebar st.sidebar.header("⚙️ Settings") confidence = st.sidebar.slider("Confidence Threshold", 0.05, 1.0, 0.25, 0.05) enable_opencv = st.sidebar.checkbox("Enable OpenCV Fallback", value=True, help="Use Computer Vision to detect anomalies if AI fails") uploaded_file = st.file_uploader("Upload Image or Video", type=['jpg', 'jpeg', 'png'], label_visibility="visible") if uploaded_file: # Image Processing image = Image.open(uploaded_file) st.image(image, caption="Uploaded Image", use_container_width=True) # Process with st.spinner("Running detection algorithms..."): thermal_img = convert_to_thermal(image) annotated_img, detections = detect_weapons_hybrid(model, thermal_img, confidence) st.markdown("### 🎯 Results") st.image(annotated_img, caption=f"Processed Image ({len(detections)} detections)", use_container_width=True) if detections: st.error(f"🚨 FOUND {len(detections)} POTENTIAL THREATS") for d in detections: source_badge = "🤖 AI" if d.get('source') == 'AI' else "👁️ CV" st.write(f"**{source_badge}**: {d['class']} ({d['confidence']:.2f})") else: st.success("✅ Area Clear")