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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 3 |
+
β CROWD ANALYSIS & THREAT DETECTION SYSTEM β
|
| 4 |
+
β Hugging Face Deployment β
|
| 5 |
+
β Detects: Ambulance Stuck | Fighting | Fire | Smoke | Weapon β
|
| 6 |
+
β Features: Real-time Alerts | Incident Log | RAG Summary β
|
| 7 |
+
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
# ββ Standard Library ββββββββββββββββββββββββββββββββββββββββββ
|
| 11 |
+
import os
|
| 12 |
+
import cv2
|
| 13 |
+
import time
|
| 14 |
+
import tempfile
|
| 15 |
+
import threading
|
| 16 |
+
import numpy as np
|
| 17 |
+
from datetime import datetime
|
| 18 |
+
from collections import Counter
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
# ββ ML / Detection ββββββββββββββββββββββββββββββββββββββββββββ
|
| 22 |
+
import torch
|
| 23 |
+
from PIL import Image
|
| 24 |
+
from ultralytics import YOLO
|
| 25 |
+
|
| 26 |
+
# ββ Document Storage ββββββββββββββββββββββββββββββββββββββββββ
|
| 27 |
+
from docx import Document as DocxDocument
|
| 28 |
+
from docx.shared import RGBColor, Pt
|
| 29 |
+
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
| 30 |
+
|
| 31 |
+
# ββ RAG Pipeline ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 32 |
+
from langchain_community.document_loaders import Docx2txtLoader
|
| 33 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 34 |
+
from langchain_community.vectorstores import FAISS
|
| 35 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
| 36 |
+
from langchain.chains import RetrievalQA
|
| 37 |
+
from langchain_community.llms import HuggingFacePipeline
|
| 38 |
+
from transformers import pipeline as hf_pipeline
|
| 39 |
+
|
| 40 |
+
# ββ Gradio UI βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 41 |
+
import gradio as gr
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 45 |
+
# CONFIGURATION
|
| 46 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 47 |
+
|
| 48 |
+
FINAL_CLASSES = ['ambulance', 'fighting', 'fire', 'smoke', 'weapon']
|
| 49 |
+
CONF_THRESHOLD = 0.25
|
| 50 |
+
LOG_PATH = 'incident_log.docx'
|
| 51 |
+
MODEL_PATH = 'best.pt'
|
| 52 |
+
|
| 53 |
+
ALERT_CONFIG = {
|
| 54 |
+
'ambulance': {
|
| 55 |
+
'level': 'HIGH',
|
| 56 |
+
'emoji': 'π',
|
| 57 |
+
'msg' : 'AMBULANCE STUCK IN CROWD β Clear the path immediately!',
|
| 58 |
+
'color': (0, 165, 255),
|
| 59 |
+
'hex' : '#FFA500',
|
| 60 |
+
},
|
| 61 |
+
'fire': {
|
| 62 |
+
'level': 'CRITICAL',
|
| 63 |
+
'emoji': 'π₯',
|
| 64 |
+
'msg' : 'FIRE DETECTED β Evacuate area, call fire brigade!',
|
| 65 |
+
'color': (0, 0, 255),
|
| 66 |
+
'hex' : '#FF2222',
|
| 67 |
+
},
|
| 68 |
+
'smoke': {
|
| 69 |
+
'level': 'HIGH',
|
| 70 |
+
'emoji': 'π¨',
|
| 71 |
+
'msg' : 'SMOKE DETECTED β Possible fire, investigate immediately!',
|
| 72 |
+
'color': (180, 180, 180),
|
| 73 |
+
'hex' : '#AAAAAA',
|
| 74 |
+
},
|
| 75 |
+
'weapon': {
|
| 76 |
+
'level': 'CRITICAL',
|
| 77 |
+
'emoji': 'π«',
|
| 78 |
+
'msg' : 'WEAPON DETECTED β Alert security forces immediately!',
|
| 79 |
+
'color': (255, 0, 0),
|
| 80 |
+
'hex' : '#FF0055',
|
| 81 |
+
},
|
| 82 |
+
'fighting': {
|
| 83 |
+
'level': 'HIGH',
|
| 84 |
+
'emoji': 'βοΈ',
|
| 85 |
+
'msg' : 'FIGHTING DETECTED β Deploy crowd control!',
|
| 86 |
+
'color': (0, 200, 0),
|
| 87 |
+
'hex' : '#00CC44',
|
| 88 |
+
},
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 93 |
+
# MODEL LOADER
|
| 94 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 95 |
+
|
| 96 |
+
def load_model():
|
| 97 |
+
if not os.path.exists(MODEL_PATH):
|
| 98 |
+
raise FileNotFoundError(
|
| 99 |
+
f'Model not found: {MODEL_PATH}\n'
|
| 100 |
+
'Please upload best.pt to this Space.'
|
| 101 |
+
)
|
| 102 |
+
model = YOLO(MODEL_PATH)
|
| 103 |
+
print(f'β
YOLOv8m loaded | GPU: {torch.cuda.is_available()}')
|
| 104 |
+
return model
|
| 105 |
+
|
| 106 |
+
model = load_model()
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 110 |
+
# DETECTION UTILITIES
|
| 111 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 112 |
+
|
| 113 |
+
def draw_boxes(img_bgr, results):
|
| 114 |
+
"""Draw bounding boxes with labels on image."""
|
| 115 |
+
for r in results:
|
| 116 |
+
for box in r.boxes:
|
| 117 |
+
cls_idx = int(box.cls)
|
| 118 |
+
conf = float(box.conf)
|
| 119 |
+
name = FINAL_CLASSES[cls_idx]
|
| 120 |
+
color = ALERT_CONFIG[name]['color']
|
| 121 |
+
x1,y1,x2,y2 = map(int, box.xyxy[0])
|
| 122 |
+
label = f'{name} {conf:.2f}'
|
| 123 |
+
cv2.rectangle(img_bgr, (x1,y1),(x2,y2), color, 2)
|
| 124 |
+
cv2.rectangle(img_bgr, (x1,y1-30),(x1+len(label)*12,y1), color, -1)
|
| 125 |
+
cv2.putText(img_bgr, label, (x1+3,y1-8),
|
| 126 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.65, (255,255,255), 2)
|
| 127 |
+
return img_bgr
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def extract_detections(results):
|
| 131 |
+
"""Extract list of detection dicts from results."""
|
| 132 |
+
return [
|
| 133 |
+
{'class': FINAL_CLASSES[int(box.cls)], 'conf': float(box.conf)}
|
| 134 |
+
for r in results for box in r.boxes
|
| 135 |
+
]
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def build_alert_html(detections):
|
| 139 |
+
"""Build HTML alert panel from detections."""
|
| 140 |
+
triggered = {}
|
| 141 |
+
for det in detections:
|
| 142 |
+
name = det['class']
|
| 143 |
+
if name not in triggered:
|
| 144 |
+
triggered[name] = {**ALERT_CONFIG[name], 'conf': det['conf']}
|
| 145 |
+
|
| 146 |
+
if not triggered:
|
| 147 |
+
return '''
|
| 148 |
+
<div style="background:#0a2a0a;border:1px solid #00ff44;
|
| 149 |
+
border-radius:8px;padding:16px;
|
| 150 |
+
font-family:'Courier New',monospace;">
|
| 151 |
+
<span style="color:#00ff44;font-size:16px;">
|
| 152 |
+
β
SYSTEM CLEAR β No threats detected
|
| 153 |
+
</span>
|
| 154 |
+
</div>'''
|
| 155 |
+
|
| 156 |
+
sorted_alerts = sorted(
|
| 157 |
+
triggered.values(),
|
| 158 |
+
key=lambda x: 0 if x['level'] == 'CRITICAL' else 1
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
html = '<div style="display:flex;flex-direction:column;gap:8px;">'
|
| 162 |
+
for alert in sorted_alerts:
|
| 163 |
+
bg = '#2a0000' if alert['level'] == 'CRITICAL' else '#2a1500'
|
| 164 |
+
border = alert['hex']
|
| 165 |
+
html += f'''
|
| 166 |
+
<div style="background:{bg};border-left:4px solid {border};
|
| 167 |
+
border-radius:4px;padding:12px 16px;
|
| 168 |
+
font-family:'Courier New',monospace;">
|
| 169 |
+
<div style="color:{border};font-size:15px;font-weight:bold;letter-spacing:1px;">
|
| 170 |
+
{alert["emoji"]} [{alert["level"]}] {alert["msg"]}
|
| 171 |
+
</div>
|
| 172 |
+
<div style="color:#888;font-size:12px;margin-top:4px;">
|
| 173 |
+
Confidence: {alert["conf"]:.2f} | Time: {datetime.now().strftime("%H:%M:%S")}
|
| 174 |
+
</div>
|
| 175 |
+
</div>'''
|
| 176 |
+
html += '</div>'
|
| 177 |
+
return html
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 181 |
+
# INCIDENT LOG (.docx)
|
| 182 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 183 |
+
|
| 184 |
+
_log_lock = threading.Lock()
|
| 185 |
+
|
| 186 |
+
def append_to_log(source, detections, triggered_alerts):
|
| 187 |
+
"""Append incident entry to docx log (thread-safe)."""
|
| 188 |
+
with _log_lock:
|
| 189 |
+
if os.path.exists(LOG_PATH):
|
| 190 |
+
doc = DocxDocument(LOG_PATH)
|
| 191 |
+
else:
|
| 192 |
+
doc = DocxDocument()
|
| 193 |
+
title = doc.add_heading('CROWD ANALYSIS β INCIDENT LOG', 0)
|
| 194 |
+
title.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
| 195 |
+
doc.add_paragraph(
|
| 196 |
+
f'System : Crowd Analysis & Threat Detection\n'
|
| 197 |
+
f'Model : YOLOv8m (V1)\n'
|
| 198 |
+
f'Classes : {", ".join(FINAL_CLASSES)}\n'
|
| 199 |
+
f'Created : {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}'
|
| 200 |
+
)
|
| 201 |
+
doc.add_paragraph('β' * 60)
|
| 202 |
+
|
| 203 |
+
doc.add_heading(
|
| 204 |
+
f'INCIDENT β {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}',
|
| 205 |
+
level=1
|
| 206 |
+
)
|
| 207 |
+
doc.add_paragraph(f'Source : {source}')
|
| 208 |
+
doc.add_paragraph(f'Total detections : {len(detections)}')
|
| 209 |
+
doc.add_paragraph(f'Alerts triggered : {len(triggered_alerts)}')
|
| 210 |
+
doc.add_paragraph('')
|
| 211 |
+
|
| 212 |
+
doc.add_heading('Alerts', level=2)
|
| 213 |
+
if triggered_alerts:
|
| 214 |
+
for alert in triggered_alerts:
|
| 215 |
+
p = doc.add_paragraph(style='List Bullet')
|
| 216 |
+
run = p.add_run(
|
| 217 |
+
f"{alert['emoji']} [{alert['level']}] "
|
| 218 |
+
f"{alert['msg']} (conf: {alert['conf']:.2f})"
|
| 219 |
+
)
|
| 220 |
+
run.bold = True
|
| 221 |
+
run.font.size = Pt(11)
|
| 222 |
+
run.font.color.rgb = (
|
| 223 |
+
RGBColor(200,0,0)
|
| 224 |
+
if alert['level'] == 'CRITICAL'
|
| 225 |
+
else RGBColor(200,100,0)
|
| 226 |
+
)
|
| 227 |
+
else:
|
| 228 |
+
doc.add_paragraph('No threats detected.')
|
| 229 |
+
|
| 230 |
+
doc.add_paragraph('')
|
| 231 |
+
doc.add_heading('All Detections', level=2)
|
| 232 |
+
if detections:
|
| 233 |
+
table = doc.add_table(rows=1, cols=3)
|
| 234 |
+
table.style = 'Table Grid'
|
| 235 |
+
hdr = table.rows[0].cells
|
| 236 |
+
hdr[0].text, hdr[1].text, hdr[2].text = 'Class','Confidence','Alert Level'
|
| 237 |
+
for det in detections:
|
| 238 |
+
row = table.add_row().cells
|
| 239 |
+
row[0].text = det['class']
|
| 240 |
+
row[1].text = f"{det['conf']:.2f}"
|
| 241 |
+
row[2].text = ALERT_CONFIG[det['class']]['level']
|
| 242 |
+
else:
|
| 243 |
+
doc.add_paragraph('No objects detected.')
|
| 244 |
+
|
| 245 |
+
doc.add_paragraph('')
|
| 246 |
+
doc.add_paragraph('β' * 60)
|
| 247 |
+
doc.add_paragraph('')
|
| 248 |
+
doc.save(LOG_PATH)
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 252 |
+
# RAG β INCIDENT SUMMARY
|
| 253 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 254 |
+
|
| 255 |
+
_rag_chain = None
|
| 256 |
+
_embeddings = None
|
| 257 |
+
|
| 258 |
+
def get_embeddings():
|
| 259 |
+
global _embeddings
|
| 260 |
+
if _embeddings is None:
|
| 261 |
+
_embeddings = HuggingFaceEmbeddings(
|
| 262 |
+
model_name='sentence-transformers/all-MiniLM-L6-v2'
|
| 263 |
+
)
|
| 264 |
+
return _embeddings
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def build_rag_chain():
|
| 268 |
+
global _rag_chain
|
| 269 |
+
if not os.path.exists(LOG_PATH):
|
| 270 |
+
return None, 'β οΈ No incident log found. Run detections first!'
|
| 271 |
+
try:
|
| 272 |
+
loader = Docx2txtLoader(LOG_PATH)
|
| 273 |
+
docs = loader.load()
|
| 274 |
+
splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
|
| 275 |
+
chunks = splitter.split_documents(docs)
|
| 276 |
+
if not chunks:
|
| 277 |
+
return None, 'β οΈ Incident log is empty.'
|
| 278 |
+
vectorstore = FAISS.from_documents(chunks, get_embeddings())
|
| 279 |
+
llm_pipe = hf_pipeline(
|
| 280 |
+
'text2text-generation',
|
| 281 |
+
model='google/flan-t5-base',
|
| 282 |
+
max_length=512,
|
| 283 |
+
truncation=True,
|
| 284 |
+
)
|
| 285 |
+
llm = HuggingFacePipeline(pipeline=llm_pipe)
|
| 286 |
+
_rag_chain = RetrievalQA.from_chain_type(
|
| 287 |
+
llm=llm,
|
| 288 |
+
chain_type='stuff',
|
| 289 |
+
retriever=vectorstore.as_retriever(search_kwargs={'k': 4}),
|
| 290 |
+
return_source_documents=False,
|
| 291 |
+
)
|
| 292 |
+
return _rag_chain, 'β
RAG ready β ask questions about incidents!'
|
| 293 |
+
except Exception as e:
|
| 294 |
+
return None, f'β Error: {str(e)}'
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def query_rag(question, history):
|
| 298 |
+
global _rag_chain
|
| 299 |
+
if not question.strip():
|
| 300 |
+
return history, ''
|
| 301 |
+
if _rag_chain is None:
|
| 302 |
+
_rag_chain, status = build_rag_chain()
|
| 303 |
+
if _rag_chain is None:
|
| 304 |
+
history.append((question, status))
|
| 305 |
+
return history, ''
|
| 306 |
+
try:
|
| 307 |
+
result = _rag_chain.invoke({'query': question})
|
| 308 |
+
answer = result.get('result', 'No answer found.')
|
| 309 |
+
answer = f'π {answer}\n\n_Answer based on incident log only β zero hallucination_'
|
| 310 |
+
except Exception as e:
|
| 311 |
+
answer = f'β Error: {str(e)}'
|
| 312 |
+
history.append((question, answer))
|
| 313 |
+
return history, ''
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 317 |
+
# INFERENCE FUNCTIONS
|
| 318 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 319 |
+
|
| 320 |
+
def detect_image(image):
|
| 321 |
+
if image is None:
|
| 322 |
+
return None, '<div class="alert-panel"><span style="color:#5a7a9a">No image uploaded.</span></div>', None
|
| 323 |
+
img_bgr = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
|
| 324 |
+
results = model.predict(img_bgr, conf=CONF_THRESHOLD, verbose=False)
|
| 325 |
+
img_out = draw_boxes(img_bgr.copy(), results)
|
| 326 |
+
img_rgb = cv2.cvtColor(img_out, cv2.COLOR_BGR2RGB)
|
| 327 |
+
detections = extract_detections(results)
|
| 328 |
+
triggered = [
|
| 329 |
+
{**ALERT_CONFIG[n], 'conf': c, 'class': n}
|
| 330 |
+
for n, c in {d['class']: d['conf'] for d in detections}.items()
|
| 331 |
+
]
|
| 332 |
+
alert_html = build_alert_html(detections)
|
| 333 |
+
threading.Thread(
|
| 334 |
+
target=append_to_log,
|
| 335 |
+
args=('image_upload', detections, triggered),
|
| 336 |
+
daemon=True
|
| 337 |
+
).start()
|
| 338 |
+
return Image.fromarray(img_rgb), alert_html, LOG_PATH
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def detect_video(video_path):
|
| 342 |
+
if video_path is None:
|
| 343 |
+
return None, '<div class="alert-panel"><span style="color:#5a7a9a">No video uploaded.</span></div>', None
|
| 344 |
+
cap = cv2.VideoCapture(video_path)
|
| 345 |
+
fps = cap.get(cv2.CAP_PROP_FPS) or 25
|
| 346 |
+
w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
| 347 |
+
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
| 348 |
+
total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 349 |
+
tmp = tempfile.NamedTemporaryFile(delete=False, suffix='.mp4')
|
| 350 |
+
writer = cv2.VideoWriter(
|
| 351 |
+
tmp.name, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h)
|
| 352 |
+
)
|
| 353 |
+
all_detections = []
|
| 354 |
+
frame_n = 0
|
| 355 |
+
while cap.isOpened():
|
| 356 |
+
ret, frame = cap.read()
|
| 357 |
+
if not ret:
|
| 358 |
+
break
|
| 359 |
+
if frame_n % 3 == 0:
|
| 360 |
+
results = model.predict(frame, conf=CONF_THRESHOLD, verbose=False)
|
| 361 |
+
frame = draw_boxes(frame, results)
|
| 362 |
+
all_detections.extend(extract_detections(results))
|
| 363 |
+
cv2.putText(frame, f'Frame {frame_n}/{total}',
|
| 364 |
+
(10,30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255,255,255), 2)
|
| 365 |
+
writer.write(frame)
|
| 366 |
+
frame_n += 1
|
| 367 |
+
cap.release()
|
| 368 |
+
writer.release()
|
| 369 |
+
triggered = [
|
| 370 |
+
{**ALERT_CONFIG[n], 'conf': c, 'class': n}
|
| 371 |
+
for n, c in {d['class']: d['conf'] for d in all_detections}.items()
|
| 372 |
+
]
|
| 373 |
+
alert_html = build_alert_html(all_detections)
|
| 374 |
+
threading.Thread(
|
| 375 |
+
target=append_to_log,
|
| 376 |
+
args=(f'video_upload ({frame_n} frames)', all_detections, triggered),
|
| 377 |
+
daemon=True
|
| 378 |
+
).start()
|
| 379 |
+
return tmp.name, alert_html, LOG_PATH
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def detect_live(frame):
|
| 383 |
+
if frame is None:
|
| 384 |
+
return None, '<div class="alert-panel"><span style="color:#5a7a9a">No feed.</span></div>'
|
| 385 |
+
img_bgr = cv2.cvtColor(np.array(frame), cv2.COLOR_RGB2BGR)
|
| 386 |
+
results = model.predict(img_bgr, conf=CONF_THRESHOLD, verbose=False)
|
| 387 |
+
img_out = draw_boxes(img_bgr.copy(), results)
|
| 388 |
+
img_rgb = cv2.cvtColor(img_out, cv2.COLOR_BGR2RGB)
|
| 389 |
+
detections = extract_detections(results)
|
| 390 |
+
alert_html = build_alert_html(detections)
|
| 391 |
+
if detections:
|
| 392 |
+
triggered = [
|
| 393 |
+
{**ALERT_CONFIG[n], 'conf': c, 'class': n}
|
| 394 |
+
for n, c in {d['class']: d['conf'] for d in detections}.items()
|
| 395 |
+
]
|
| 396 |
+
threading.Thread(
|
| 397 |
+
target=append_to_log,
|
| 398 |
+
args=('live_feed', detections, triggered),
|
| 399 |
+
daemon=True
|
| 400 |
+
).start()
|
| 401 |
+
return Image.fromarray(img_rgb), alert_html
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 405 |
+
# GRADIO UI
|
| 406 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 407 |
+
|
| 408 |
+
CSS = """
|
| 409 |
+
@import url('https://fonts.googleapis.com/css2?family=Rajdhani:wght@400;600;700&family=Share+Tech+Mono&family=Exo+2:wght@300;400;600&display=swap');
|
| 410 |
+
|
| 411 |
+
:root {
|
| 412 |
+
--bg-dark : #050a0f;
|
| 413 |
+
--bg-panel : #0a1520;
|
| 414 |
+
--bg-card : #0d1e2e;
|
| 415 |
+
--red : #ff2244;
|
| 416 |
+
--blue : #00aaff;
|
| 417 |
+
--gold : #ffaa00;
|
| 418 |
+
--text : #c8d8e8;
|
| 419 |
+
--dim : #5a7a9a;
|
| 420 |
+
--border : #1a3a5a;
|
| 421 |
+
}
|
| 422 |
+
|
| 423 |
+
body, .gradio-container {
|
| 424 |
+
background: var(--bg-dark) !important;
|
| 425 |
+
font-family: 'Exo 2', sans-serif !important;
|
| 426 |
+
color: var(--text) !important;
|
| 427 |
+
}
|
| 428 |
+
|
| 429 |
+
.sys-header {
|
| 430 |
+
background: linear-gradient(135deg, #050a0f, #0a1a2e, #050a0f);
|
| 431 |
+
border-bottom: 2px solid var(--red);
|
| 432 |
+
padding: 32px 24px 24px;
|
| 433 |
+
text-align: center;
|
| 434 |
+
}
|
| 435 |
+
|
| 436 |
+
.sys-title {
|
| 437 |
+
font-family: 'Rajdhani', sans-serif !important;
|
| 438 |
+
font-size: 44px !important;
|
| 439 |
+
font-weight: 700 !important;
|
| 440 |
+
letter-spacing: 10px !important;
|
| 441 |
+
color: #fff !important;
|
| 442 |
+
text-shadow: 0 0 30px rgba(255,34,68,0.8), 0 0 60px rgba(255,34,68,0.3) !important;
|
| 443 |
+
margin: 0 !important;
|
| 444 |
+
}
|
| 445 |
+
|
| 446 |
+
.sys-sub {
|
| 447 |
+
font-family: 'Share Tech Mono', monospace;
|
| 448 |
+
font-size: 12px;
|
| 449 |
+
color: var(--blue);
|
| 450 |
+
letter-spacing: 4px;
|
| 451 |
+
margin-top: 8px;
|
| 452 |
+
}
|
| 453 |
+
|
| 454 |
+
.sys-badges {
|
| 455 |
+
display: flex;
|
| 456 |
+
justify-content: center;
|
| 457 |
+
gap: 10px;
|
| 458 |
+
margin-top: 14px;
|
| 459 |
+
flex-wrap: wrap;
|
| 460 |
+
}
|
| 461 |
+
|
| 462 |
+
.badge {
|
| 463 |
+
background: rgba(0,170,255,0.08);
|
| 464 |
+
border: 1px solid rgba(0,170,255,0.25);
|
| 465 |
+
border-radius: 3px;
|
| 466 |
+
padding: 3px 10px;
|
| 467 |
+
font-family: 'Share Tech Mono', monospace;
|
| 468 |
+
font-size: 10px;
|
| 469 |
+
color: var(--blue);
|
| 470 |
+
letter-spacing: 1px;
|
| 471 |
+
}
|
| 472 |
+
|
| 473 |
+
.badge.red {
|
| 474 |
+
background: rgba(255,34,68,0.08);
|
| 475 |
+
border-color: rgba(255,34,68,0.25);
|
| 476 |
+
color: var(--red);
|
| 477 |
+
}
|
| 478 |
+
|
| 479 |
+
.tab-nav button {
|
| 480 |
+
background: var(--bg-panel) !important;
|
| 481 |
+
border: 1px solid var(--border) !important;
|
| 482 |
+
color: var(--dim) !important;
|
| 483 |
+
font-family: 'Rajdhani', sans-serif !important;
|
| 484 |
+
font-size: 13px !important;
|
| 485 |
+
font-weight: 600 !important;
|
| 486 |
+
letter-spacing: 2px !important;
|
| 487 |
+
text-transform: uppercase !important;
|
| 488 |
+
transition: all 0.2s !important;
|
| 489 |
+
}
|
| 490 |
+
|
| 491 |
+
.tab-nav button.selected {
|
| 492 |
+
background: var(--bg-card) !important;
|
| 493 |
+
border-color: var(--red) !important;
|
| 494 |
+
color: #fff !important;
|
| 495 |
+
box-shadow: 0 0 15px rgba(255,34,68,0.25) !important;
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
.section-lbl {
|
| 499 |
+
font-family: 'Share Tech Mono', monospace;
|
| 500 |
+
font-size: 11px;
|
| 501 |
+
color: var(--blue);
|
| 502 |
+
letter-spacing: 3px;
|
| 503 |
+
text-transform: uppercase;
|
| 504 |
+
padding: 14px 0 8px;
|
| 505 |
+
}
|
| 506 |
+
|
| 507 |
+
.alert-panel {
|
| 508 |
+
background: var(--bg-card);
|
| 509 |
+
border: 1px solid var(--border);
|
| 510 |
+
border-radius: 8px;
|
| 511 |
+
padding: 16px;
|
| 512 |
+
min-height: 60px;
|
| 513 |
+
}
|
| 514 |
+
|
| 515 |
+
.gr-button {
|
| 516 |
+
font-family: 'Rajdhani', sans-serif !important;
|
| 517 |
+
font-weight: 700 !important;
|
| 518 |
+
letter-spacing: 2px !important;
|
| 519 |
+
text-transform: uppercase !important;
|
| 520 |
+
}
|
| 521 |
+
|
| 522 |
+
label {
|
| 523 |
+
font-family: 'Share Tech Mono', monospace !important;
|
| 524 |
+
font-size: 11px !important;
|
| 525 |
+
letter-spacing: 1px !important;
|
| 526 |
+
color: var(--dim) !important;
|
| 527 |
+
}
|
| 528 |
+
|
| 529 |
+
.footer-bar {
|
| 530 |
+
background: var(--bg-panel);
|
| 531 |
+
border-top: 1px solid var(--border);
|
| 532 |
+
padding: 10px 24px;
|
| 533 |
+
display: flex;
|
| 534 |
+
justify-content: space-between;
|
| 535 |
+
font-family: 'Share Tech Mono', monospace;
|
| 536 |
+
font-size: 10px;
|
| 537 |
+
color: var(--dim);
|
| 538 |
+
margin-top: 16px;
|
| 539 |
+
}
|
| 540 |
+
"""
|
| 541 |
+
|
| 542 |
+
HEADER = """
|
| 543 |
+
<div class="sys-header">
|
| 544 |
+
<div class="sys-title">β‘ CROWD SHIELD</div>
|
| 545 |
+
<div class="sys-sub">REAL-TIME THREAT DETECTION & INCIDENT MANAGEMENT SYSTEM</div>
|
| 546 |
+
<div class="sys-badges">
|
| 547 |
+
<span class="badge red">π΄ LIVE SYSTEM</span>
|
| 548 |
+
<span class="badge">YOLOv8m</span>
|
| 549 |
+
<span class="badge">5 THREAT CLASSES</span>
|
| 550 |
+
<span class="badge">AUTO INCIDENT LOG</span>
|
| 551 |
+
<span class="badge red">RAG REPORTING</span>
|
| 552 |
+
</div>
|
| 553 |
+
</div>
|
| 554 |
+
"""
|
| 555 |
+
|
| 556 |
+
RAG_INFO = """
|
| 557 |
+
<div style="background:#0a1520;border:1px solid #1a3a5a;border-radius:8px;
|
| 558 |
+
padding:16px;font-family:'Share Tech Mono',monospace;">
|
| 559 |
+
<div style="color:#00aaff;font-size:11px;letter-spacing:2px;margin-bottom:12px;">
|
| 560 |
+
βΈ RAG SYSTEM INFO
|
| 561 |
+
</div>
|
| 562 |
+
<div style="color:#5a7a9a;font-size:11px;line-height:2.2;">
|
| 563 |
+
EMBEDDINGS:<br>
|
| 564 |
+
<span style="color:#c8d8e8;">all-MiniLM-L6-v2</span><br>
|
| 565 |
+
VECTOR STORE:<br>
|
| 566 |
+
<span style="color:#c8d8e8;">FAISS (CPU)</span><br>
|
| 567 |
+
LLM:<br>
|
| 568 |
+
<span style="color:#c8d8e8;">Flan-T5-Base</span><br>
|
| 569 |
+
METHOD:<br>
|
| 570 |
+
<span style="color:#c8d8e8;">RetrievalQA</span><br>
|
| 571 |
+
SOURCE:<br>
|
| 572 |
+
<span style="color:#c8d8e8;">incident_log.docx</span><br>
|
| 573 |
+
HALLUCINATION:<br>
|
| 574 |
+
<span style="color:#00ff44;">ZERO β
</span>
|
| 575 |
+
</div>
|
| 576 |
+
</div>
|
| 577 |
+
"""
|
| 578 |
+
|
| 579 |
+
AWAIT_HTML = '<div class="alert-panel"><span style="color:#5a7a9a;font-family:\'Share Tech Mono\',monospace;font-size:13px;">// AWAITING INPUT //</span></div>'
|
| 580 |
+
|
| 581 |
+
with gr.Blocks(css=CSS, title='CrowdShield β Threat Detection') as app:
|
| 582 |
+
|
| 583 |
+
gr.HTML(HEADER)
|
| 584 |
+
|
| 585 |
+
with gr.Tabs():
|
| 586 |
+
|
| 587 |
+
# ββ Tab 1: Image ββββββββββββββββββββββββββββββββββββββ
|
| 588 |
+
with gr.Tab('π· IMAGE'):
|
| 589 |
+
gr.HTML('<div class="section-lbl">βΈ Upload Image for Threat Analysis</div>')
|
| 590 |
+
with gr.Row():
|
| 591 |
+
with gr.Column():
|
| 592 |
+
img_input = gr.Image(type='pil', label='INPUT FEED', height=380)
|
| 593 |
+
img_btn = gr.Button('β‘ ANALYZE THREAT', variant='primary')
|
| 594 |
+
with gr.Column():
|
| 595 |
+
img_output = gr.Image(type='pil', label='DETECTION OUTPUT', height=380)
|
| 596 |
+
gr.HTML('<div class="section-lbl">βΈ Alert Status</div>')
|
| 597 |
+
img_alert = gr.HTML(value=AWAIT_HTML)
|
| 598 |
+
img_log = gr.File(label='π DOWNLOAD INCIDENT LOG (.docx)')
|
| 599 |
+
img_btn.click(
|
| 600 |
+
fn=detect_image, inputs=[img_input],
|
| 601 |
+
outputs=[img_output, img_alert, img_log]
|
| 602 |
+
)
|
| 603 |
+
|
| 604 |
+
# ββ Tab 2: Video ββββββββββββββββββββββββββββββββββββββ
|
| 605 |
+
with gr.Tab('π₯ VIDEO'):
|
| 606 |
+
gr.HTML('<div class="section-lbl">βΈ Upload Video for Threat Analysis</div>')
|
| 607 |
+
with gr.Row():
|
| 608 |
+
with gr.Column():
|
| 609 |
+
vid_input = gr.Video(label='INPUT FEED', height=380)
|
| 610 |
+
vid_btn = gr.Button('β‘ ANALYZE THREAT', variant='primary')
|
| 611 |
+
with gr.Column():
|
| 612 |
+
vid_output = gr.Video(label='DETECTION OUTPUT', height=380)
|
| 613 |
+
gr.HTML('<div class="section-lbl">βΈ Alert Status</div>')
|
| 614 |
+
vid_alert = gr.HTML(value=AWAIT_HTML)
|
| 615 |
+
vid_log = gr.File(label='π DOWNLOAD INCIDENT LOG (.docx)')
|
| 616 |
+
vid_btn.click(
|
| 617 |
+
fn=detect_video, inputs=[vid_input],
|
| 618 |
+
outputs=[vid_output, vid_alert, vid_log]
|
| 619 |
+
)
|
| 620 |
+
|
| 621 |
+
# ββ Tab 3: Live βββββββββββββββββββββββββββββββββββββββ
|
| 622 |
+
with gr.Tab('π‘ LIVE FEED'):
|
| 623 |
+
gr.HTML('<div class="section-lbl">βΈ Connect Live Camera Feed</div>')
|
| 624 |
+
with gr.Row():
|
| 625 |
+
with gr.Column():
|
| 626 |
+
live_input = gr.Image(
|
| 627 |
+
sources=['webcam'], type='pil',
|
| 628 |
+
label='LIVE INPUT', streaming=True, height=380
|
| 629 |
+
)
|
| 630 |
+
with gr.Column():
|
| 631 |
+
live_output = gr.Image(type='pil', label='DETECTION OUTPUT', height=380)
|
| 632 |
+
gr.HTML('<div class="section-lbl">βΈ Alert Status</div>')
|
| 633 |
+
live_alert = gr.HTML(value=AWAIT_HTML)
|
| 634 |
+
live_input.stream(
|
| 635 |
+
fn=detect_live, inputs=[live_input],
|
| 636 |
+
outputs=[live_output, live_alert]
|
| 637 |
+
)
|
| 638 |
+
|
| 639 |
+
# ββ Tab 4: RAG ββββββββββββββββββββββββββββββββββββββββ
|
| 640 |
+
with gr.Tab('οΏ½οΏ½ INCIDENT REPORT'):
|
| 641 |
+
gr.HTML('''
|
| 642 |
+
<div style="background:#0a1520;border:1px solid #1a3a5a;
|
| 643 |
+
border-left:4px solid #00aaff;border-radius:8px;
|
| 644 |
+
padding:16px 20px;margin:16px 0;
|
| 645 |
+
font-family:'Share Tech Mono',monospace;">
|
| 646 |
+
<div style="color:#00aaff;font-size:12px;letter-spacing:2px;margin-bottom:8px;">
|
| 647 |
+
βΈ RAG INCIDENT QUERY β ZERO HALLUCINATION
|
| 648 |
+
</div>
|
| 649 |
+
<div style="color:#5a7a9a;font-size:11px;line-height:1.9;">
|
| 650 |
+
Ask questions about logged incidents. Answers come from incident_log.docx ONLY.<br>
|
| 651 |
+
Try: "Summarize all CRITICAL incidents" | "Generate official report" | "How many weapon detections?"
|
| 652 |
+
</div>
|
| 653 |
+
</div>
|
| 654 |
+
''')
|
| 655 |
+
with gr.Row():
|
| 656 |
+
with gr.Column(scale=3):
|
| 657 |
+
chatbot = gr.Chatbot(
|
| 658 |
+
label='INCIDENT QUERY INTERFACE',
|
| 659 |
+
height=440,
|
| 660 |
+
bubble_full_width=False,
|
| 661 |
+
)
|
| 662 |
+
with gr.Row():
|
| 663 |
+
query_box = gr.Textbox(
|
| 664 |
+
placeholder='Ask about incidents... e.g. "Generate official report for authorities"',
|
| 665 |
+
label='', scale=4, container=False,
|
| 666 |
+
)
|
| 667 |
+
ask_btn = gr.Button('β‘ ASK', variant='primary', scale=1)
|
| 668 |
+
gr.Examples(
|
| 669 |
+
examples=[
|
| 670 |
+
['Summarize all incidents for the officials'],
|
| 671 |
+
['How many CRITICAL alerts were triggered?'],
|
| 672 |
+
['Which incidents involved fire or smoke?'],
|
| 673 |
+
['List all weapon detections with timestamps'],
|
| 674 |
+
['Generate a complete incident report'],
|
| 675 |
+
['What was the most dangerous incident?'],
|
| 676 |
+
],
|
| 677 |
+
inputs=[query_box],
|
| 678 |
+
label='QUICK QUERIES',
|
| 679 |
+
)
|
| 680 |
+
|
| 681 |
+
with gr.Column(scale=1):
|
| 682 |
+
gr.HTML(RAG_INFO)
|
| 683 |
+
rag_status = gr.Textbox(
|
| 684 |
+
label='SYSTEM STATUS',
|
| 685 |
+
value='Click LOAD to initialize RAG',
|
| 686 |
+
interactive=False, lines=2,
|
| 687 |
+
)
|
| 688 |
+
load_btn = gr.Button('π LOAD INCIDENT LOG', variant='secondary')
|
| 689 |
+
log_upload = gr.File(
|
| 690 |
+
label='β Or upload incident_log.docx',
|
| 691 |
+
file_types=['.docx'],
|
| 692 |
+
)
|
| 693 |
+
|
| 694 |
+
def load_rag(uploaded=None):
|
| 695 |
+
global _rag_chain
|
| 696 |
+
_rag_chain = None
|
| 697 |
+
if uploaded:
|
| 698 |
+
import shutil
|
| 699 |
+
shutil.copy(uploaded.name, LOG_PATH)
|
| 700 |
+
_, status = build_rag_chain()
|
| 701 |
+
return status
|
| 702 |
+
|
| 703 |
+
load_btn.click(fn=load_rag, inputs=[log_upload], outputs=[rag_status])
|
| 704 |
+
ask_btn.click(fn=query_rag, inputs=[query_box, chatbot], outputs=[chatbot, query_box])
|
| 705 |
+
query_box.submit(fn=query_rag, inputs=[query_box, chatbot], outputs=[chatbot, query_box])
|
| 706 |
+
|
| 707 |
+
# Footer
|
| 708 |
+
gr.HTML('''
|
| 709 |
+
<div class="footer-bar">
|
| 710 |
+
<span>CROWDSHIELD v1.0 | YOLOv8m | mAP50: 0.603</span>
|
| 711 |
+
<span>π΄ CRITICAL: Fire, Weapon | π HIGH: Ambulance, Fighting, Smoke</span>
|
| 712 |
+
<span>ALL INCIDENTS AUTO-LOGGED TO .DOCX</span>
|
| 713 |
+
</div>
|
| 714 |
+
''')
|
| 715 |
+
|
| 716 |
+
if __name__ == '__main__':
|
| 717 |
+
app.launch()
|
best.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f349b6f6ce0abd5a1f81f23ebb47b041c8b864920d3c5b1bf66b4e2ce4c46082
|
| 3 |
+
size 52040978
|
requirements.txt
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
ultralytics
|
| 2 |
+
gradio
|
| 3 |
+
opencv-python-headless
|
| 4 |
+
python-docx
|
| 5 |
+
Pillow
|
| 6 |
+
torch
|
| 7 |
+
torchvision
|
| 8 |
+
langchain
|
| 9 |
+
langchain-community
|
| 10 |
+
faiss-cpu
|
| 11 |
+
sentence-transformers
|
| 12 |
+
transformers
|
| 13 |
+
accelerate
|
| 14 |
+
docx2txt
|