bug-detector / tests /analyze_sample.py
MuhammadTayyab0143's picture
UI Simplification: remove Single Frame Analyzer and System Guidelines tabs
12b970a
Raw
History Blame Contribute Delete
6.45 kB
"""
Analyze 'sample video.mp4' through the SimShieldAI suspicious behavior pipeline.
Prints detailed per-frame diagnostics for violence and running detection.
"""
import os
import sys
import time
import cv2
import numpy as np
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from suspicious_behavior.pipeline.frame_analyzer import FrameAnalyzer
from suspicious_behavior.pipeline.video_processor import VideoProcessor
def main():
video_path = r"C:\Users\Admin\Downloads\sample video.mp4"
print("=" * 70)
print("SimShieldAI — Suspicious Behavior Detection Analysis")
print(f"Video: {video_path}")
print("=" * 70)
# Get video metadata
processor = VideoProcessor(target_fps=10.0)
metadata = processor.get_metadata(video_path)
print(f"Resolution: {metadata['width']}x{metadata['height']}")
print(f"Duration: {metadata['duration']:.1f}s | Frames: {metadata['frame_count']} @ {metadata['fps']:.1f} FPS")
print(f"Processing at 10 FPS (every {int(metadata['fps']/10)} frames)")
print("=" * 70)
# Initialize analyzer
print("\n[Init] Loading models (YOLOv8n + VideoMAE + MediaPipe)...")
analyzer = FrameAnalyzer(camera_id="test_cam", violence_stride=4)
# Reset state
analyzer.frame_idx = 0
analyzer.violence_buffer.clear()
analyzer.alert_manager.reset_cooldowns()
# Process video
frames_processed = 0
violence_scores = []
running_detections = []
all_alerts = []
output_frames = []
start_time = time.time()
print("\n--- Per-Frame Analysis ---\n")
for f_idx, frame, timestamp in processor.extract_frames_generator(video_path):
annotated, frame_alerts, frame_meta = analyzer.analyze(frame, fps=10.0, output_base64=False)
frames_processed += 1
output_frames.append(annotated)
# Collect metrics
v_meta = frame_meta["violence_metrics"]
if v_meta["confidence"] > 0:
violence_scores.append({
"frame": f_idx,
"time": timestamp,
"label": v_meta["label"],
"conf": v_meta["confidence"]
})
for track in frame_meta["tracks"]:
running_detections.append({
"frame": f_idx,
"time": timestamp,
"track_id": track["track_id"],
"behavior": track["behavior"],
"conf": track["behavior_confidence"]
})
for alert in frame_alerts:
all_alerts.append({"time": timestamp, "alert": alert})
# Print frame details
tracks_info = ", ".join([
f"ID{t['track_id']}:{t['behavior']}({t['behavior_confidence']*100:.0f}%)"
for t in frame_meta["tracks"]
]) or "no people"
violence_info = ""
if v_meta['confidence'] > 0:
emoji = "🔴" if v_meta['detected'] else "🟢"
violence_info = f" | {emoji} Violence: {v_meta['label']}({v_meta['confidence']*100:.1f}%)"
alert_info = ""
if frame_meta['threats_detected']:
alert_info = f" | ⚠️ THREATS: {frame_meta['threats_detected']}"
print(f" [{f_idx:04d}] {timestamp:5.1f}s | {frame_meta['active_tracks_count']} people | "
f"[{tracks_info}]{violence_info}{alert_info}")
elapsed = time.time() - start_time
# Save annotated output
output_path = r"C:\Users\Admin\Downloads\sample_video_annotated.mp4"
processor.write_frames_to_video(
output_frames, output_path, fps=10.0,
frame_size=(metadata['width'], metadata['height'])
)
# Print summary
print("\n" + "=" * 70)
print("ANALYSIS SUMMARY")
print("=" * 70)
print(f"Frames processed: {frames_processed}")
print(f"Processing time: {elapsed:.1f}s ({frames_processed/elapsed:.1f} FPS)")
print(f"\n--- Violence Detection (VideoMAE) ---")
if violence_scores:
confs = [s["conf"] for s in violence_scores]
violence_detected = [s for s in violence_scores if s["label"] != "normal"]
normal_scores = [s for s in violence_scores if s["label"] == "normal"]
print(f"Total inference runs: {len(violence_scores)}")
if violence_detected:
print(f"🔴 VIOLENCE DETECTED in {len(violence_detected)} frames:")
for v in violence_detected:
print(f" Frame {v['frame']:04d} ({v['time']:.1f}s): {v['label']} at {v['conf']*100:.1f}%")
else:
print(f"🟢 No violence detected. All {len(normal_scores)} checks returned 'normal'")
if normal_scores:
normal_confs = [s["conf"] for s in normal_scores]
print(f" Normal confidence: min={min(normal_confs)*100:.1f}%, max={max(normal_confs)*100:.1f}%, avg={np.mean(normal_confs)*100:.1f}%")
else:
print("⚠️ VideoMAE never ran (need 16 frames + people in scene)")
print(f"\n--- Running Detection (MediaPipe) ---")
if running_detections:
running_found = [r for r in running_detections if r["behavior"] == "running"]
walking = [r for r in running_detections if r["behavior"] == "walking/standing"]
unknown = [r for r in running_detections if r["behavior"] == "unknown"]
print(f"Total person-frame analyses: {len(running_detections)}")
if running_found:
print(f"🟠 RUNNING DETECTED in {len(running_found)} person-frames:")
for r in running_found[:10]:
print(f" Frame {r['frame']:04d} ({r['time']:.1f}s): ID{r['track_id']} running at {r['conf']*100:.1f}%")
else:
print(f"🟢 No running detected. {len(walking)} walking/standing, {len(unknown)} unknown")
else:
print("⚠️ No people detected in any frame")
print(f"\n--- Alerts ---")
if all_alerts:
print(f"🚨 {len(all_alerts)} ALERTS TRIGGERED:")
for a in all_alerts:
alert = a["alert"]
print(f" [{a['time']:.1f}s] [{alert.severity}] {alert.threat_type} "
f"(confidence: {alert.confidence*100:.1f}%)")
else:
print("No alerts triggered")
print(f"\n--- Output ---")
print(f"Annotated video saved to: {os.path.abspath(output_path)}")
print("=" * 70)
if __name__ == "__main__":
main()