Update app.py
Browse files
app.py
CHANGED
|
@@ -4,19 +4,26 @@ Abnormal-Behaviour Detector (VideoMAE)
|
|
| 4 |
|
| 5 |
Tabs
|
| 6 |
ββββ
|
| 7 |
-
1.
|
| 8 |
-
2. Live
|
|
|
|
| 9 |
"""
|
| 10 |
|
| 11 |
-
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
matplotlib.use("Agg")
|
| 13 |
import matplotlib.pyplot as plt
|
| 14 |
from collections import deque
|
| 15 |
|
| 16 |
-
import torch
|
|
|
|
|
|
|
| 17 |
from transformers import VideoMAEForVideoClassification, AutoImageProcessor
|
| 18 |
|
| 19 |
-
# ββ Load
|
| 20 |
MODEL_DIR = "./model"
|
| 21 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 22 |
|
|
@@ -25,12 +32,12 @@ processor = AutoImageProcessor.from_pretrained(MODEL_DIR, use_fast=False)
|
|
| 25 |
model.eval()
|
| 26 |
|
| 27 |
# ββ Constants βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 28 |
-
CLIP = 16
|
| 29 |
-
STRIDE = 1
|
| 30 |
-
STREAM_FPS = 15
|
| 31 |
-
HIST_LEN = 90
|
| 32 |
|
| 33 |
-
# ββ
|
| 34 |
def sliding_window(path, clip_len=CLIP, stride=STRIDE):
|
| 35 |
cap, frames = cv2.VideoCapture(path), []
|
| 36 |
fps = cap.get(cv2.CAP_PROP_FPS) or 25
|
|
@@ -43,57 +50,64 @@ def sliding_window(path, clip_len=CLIP, stride=STRIDE):
|
|
| 43 |
|
| 44 |
probs = []
|
| 45 |
for s in range(0, len(frames) - clip_len + 1, stride):
|
| 46 |
-
clip = [cv2.resize(frames[i], (224,224)) for i in range(s, s+clip_len)]
|
| 47 |
-
inp
|
| 48 |
with torch.no_grad():
|
| 49 |
-
|
|
|
|
| 50 |
return frames, probs, fps
|
| 51 |
|
| 52 |
|
| 53 |
def make_outputs(frames, probs, fps, thresh):
|
| 54 |
h, w = frames[0].shape[:2]
|
| 55 |
-
|
|
|
|
| 56 |
if p > thresh:
|
| 57 |
-
for
|
| 58 |
-
cv2.rectangle(frames[
|
| 59 |
|
| 60 |
-
|
| 61 |
-
|
|
|
|
| 62 |
for f in frames:
|
| 63 |
vw.write(cv2.cvtColor(f, cv2.COLOR_RGB2BGR))
|
| 64 |
vw.release()
|
| 65 |
|
|
|
|
| 66 |
t = np.arange(len(probs)) / fps
|
| 67 |
-
fig, ax = plt.subplots(figsize=(5,2))
|
| 68 |
-
colors = [
|
| 69 |
-
ax.bar(t, probs,
|
| 70 |
-
ax.set_ylim(0,1); ax.set_xlabel(
|
| 71 |
fig.tight_layout()
|
| 72 |
-
plot_out = tempfile.NamedTemporaryFile(suffix=
|
| 73 |
-
fig.savefig(plot_out, dpi=120)
|
|
|
|
| 74 |
|
|
|
|
| 75 |
alarm = None
|
| 76 |
-
if any(p>thresh for p in probs):
|
| 77 |
sr = 16000
|
| 78 |
-
t_beep = np.linspace(0,0.5,int(sr*0.5),endpoint=False)
|
| 79 |
-
alarm = tempfile.NamedTemporaryFile(suffix=
|
| 80 |
-
sf.write(alarm, 0.2*np.sin(2*np.pi*440*t_beep), sr)
|
| 81 |
|
| 82 |
return vid_out, plot_out, alarm
|
| 83 |
|
| 84 |
|
| 85 |
-
def run_pipeline(
|
| 86 |
-
if not
|
| 87 |
return None, None, None
|
| 88 |
-
frames, probs, fps = sliding_window(
|
| 89 |
return make_outputs(frames, probs, fps, thresh)
|
| 90 |
|
| 91 |
-
# ββ Live
|
| 92 |
-
def plot_history(
|
| 93 |
-
fig, ax = plt.subplots(figsize=(5,2))
|
| 94 |
-
colors = [
|
| 95 |
-
ax.bar(np.arange(len(
|
| 96 |
-
ax.set_ylim(0,1)
|
|
|
|
| 97 |
fig.tight_layout(); return fig
|
| 98 |
|
| 99 |
|
|
@@ -102,41 +116,62 @@ def live_handler(frame, state, history, thresh):
|
|
| 102 |
if len(state) < CLIP:
|
| 103 |
return state, frame, history, plot_history(history, thresh), 0.0
|
| 104 |
|
|
|
|
| 105 |
clip = [cv2.resize(f, (224,224)) for f in list(state)]
|
| 106 |
-
inp
|
| 107 |
-
with torch.no_grad():
|
|
|
|
|
|
|
| 108 |
history.append(p)
|
| 109 |
-
if len(history) > HIST_LEN:
|
|
|
|
| 110 |
|
|
|
|
| 111 |
disp = frame.copy(); h, w = disp.shape[:2]
|
| 112 |
-
if p > thresh:
|
| 113 |
-
|
| 114 |
-
|
|
|
|
| 115 |
|
| 116 |
return state, disp, history, plot_history(history, thresh), p
|
| 117 |
|
| 118 |
-
# ββ
|
| 119 |
-
with gr.Blocks(title=
|
| 120 |
-
thresh_slider = gr.Slider(
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
gr.
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
frame_state = gr.State(value=deque(maxlen=CLIP))
|
| 136 |
-
prob_state
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
|
|
|
|
|
|
|
|
|
| 141 |
|
| 142 |
demo.queue().launch()
|
|
|
|
| 4 |
|
| 5 |
Tabs
|
| 6 |
ββββ
|
| 7 |
+
1. Upload / Recorded Video β annotate entire clip with static bar plot.
|
| 8 |
+
2. Live Stream β real-time webcam, red-border overlay, rolling bar plot & numeric prob.
|
| 9 |
+
**Bug fixed**: include `thresh_slider` as input to `live_handler` and default to 0.0.
|
| 10 |
"""
|
| 11 |
|
| 12 |
+
import os
|
| 13 |
+
import cv2
|
| 14 |
+
import tempfile
|
| 15 |
+
import numpy as np
|
| 16 |
+
import matplotlib
|
| 17 |
matplotlib.use("Agg")
|
| 18 |
import matplotlib.pyplot as plt
|
| 19 |
from collections import deque
|
| 20 |
|
| 21 |
+
import torch
|
| 22 |
+
import gradio as gr
|
| 23 |
+
import soundfile as sf
|
| 24 |
from transformers import VideoMAEForVideoClassification, AutoImageProcessor
|
| 25 |
|
| 26 |
+
# ββ Model Load βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 27 |
MODEL_DIR = "./model"
|
| 28 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 29 |
|
|
|
|
| 32 |
model.eval()
|
| 33 |
|
| 34 |
# ββ Constants βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 35 |
+
CLIP = 16 # number of frames per clip
|
| 36 |
+
STRIDE = 1 # evaluate every frame
|
| 37 |
+
STREAM_FPS = 15 # ~15 polls per second
|
| 38 |
+
HIST_LEN = 90 # history length for rolling plot
|
| 39 |
|
| 40 |
+
# ββ Upload / Recorded Video Helpers βββββββββββββββββββββββββββββββββββ
|
| 41 |
def sliding_window(path, clip_len=CLIP, stride=STRIDE):
|
| 42 |
cap, frames = cv2.VideoCapture(path), []
|
| 43 |
fps = cap.get(cv2.CAP_PROP_FPS) or 25
|
|
|
|
| 50 |
|
| 51 |
probs = []
|
| 52 |
for s in range(0, len(frames) - clip_len + 1, stride):
|
| 53 |
+
clip = [cv2.resize(frames[i], (224, 224)) for i in range(s, s + clip_len)]
|
| 54 |
+
inp = processor(clip, return_tensors="pt").to(DEVICE)
|
| 55 |
with torch.no_grad():
|
| 56 |
+
p = torch.softmax(model(**inp).logits, dim=1)[0,1].item()
|
| 57 |
+
probs.append(p)
|
| 58 |
return frames, probs, fps
|
| 59 |
|
| 60 |
|
| 61 |
def make_outputs(frames, probs, fps, thresh):
|
| 62 |
h, w = frames[0].shape[:2]
|
| 63 |
+
# annotate frames where p > thresh
|
| 64 |
+
for i, p in enumerate(probs):
|
| 65 |
if p > thresh:
|
| 66 |
+
for fidx in range(i, min(i + CLIP, len(frames))):
|
| 67 |
+
cv2.rectangle(frames[fidx], (0,0), (w-1,h-1), (255,0,0), 6)
|
| 68 |
|
| 69 |
+
# save annotated video
|
| 70 |
+
vid_out = tempfile.NamedTemporaryFile(suffix='.mp4', delete=False).name
|
| 71 |
+
vw = cv2.VideoWriter(vid_out, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
|
| 72 |
for f in frames:
|
| 73 |
vw.write(cv2.cvtColor(f, cv2.COLOR_RGB2BGR))
|
| 74 |
vw.release()
|
| 75 |
|
| 76 |
+
# static bar plot
|
| 77 |
t = np.arange(len(probs)) / fps
|
| 78 |
+
fig, ax = plt.subplots(figsize=(5, 2))
|
| 79 |
+
colors = ['red' if p > thresh else 'blue' for p in probs]
|
| 80 |
+
ax.bar(t, probs, width=1/fps, color=colors)
|
| 81 |
+
ax.set_ylim(0, 1); ax.set_xlabel('sec'); ax.set_ylabel('fight prob')
|
| 82 |
fig.tight_layout()
|
| 83 |
+
plot_out = tempfile.NamedTemporaryFile(suffix='.png', delete=False).name
|
| 84 |
+
fig.savefig(plot_out, dpi=120)
|
| 85 |
+
plt.close(fig)
|
| 86 |
|
| 87 |
+
# optional alarm
|
| 88 |
alarm = None
|
| 89 |
+
if any(p > thresh for p in probs):
|
| 90 |
sr = 16000
|
| 91 |
+
t_beep = np.linspace(0, 0.5, int(sr*0.5), endpoint=False)
|
| 92 |
+
alarm = tempfile.NamedTemporaryFile(suffix='.wav', delete=False).name
|
| 93 |
+
sf.write(alarm, 0.2 * np.sin(2*np.pi*440*t_beep), sr)
|
| 94 |
|
| 95 |
return vid_out, plot_out, alarm
|
| 96 |
|
| 97 |
|
| 98 |
+
def run_pipeline(video_path, thresh):
|
| 99 |
+
if not video_path or not os.path.exists(video_path):
|
| 100 |
return None, None, None
|
| 101 |
+
frames, probs, fps = sliding_window(video_path)
|
| 102 |
return make_outputs(frames, probs, fps, thresh)
|
| 103 |
|
| 104 |
+
# ββ Live Stream Helpers βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 105 |
+
def plot_history(history, thresh):
|
| 106 |
+
fig, ax = plt.subplots(figsize=(5, 2))
|
| 107 |
+
colors = ['red' if p > thresh else 'blue' for p in history]
|
| 108 |
+
ax.bar(np.arange(len(history)), history, color=colors)
|
| 109 |
+
ax.set_ylim(0, 1)
|
| 110 |
+
ax.set_xlabel('recent clips'); ax.set_ylabel('fight prob')
|
| 111 |
fig.tight_layout(); return fig
|
| 112 |
|
| 113 |
|
|
|
|
| 116 |
if len(state) < CLIP:
|
| 117 |
return state, frame, history, plot_history(history, thresh), 0.0
|
| 118 |
|
| 119 |
+
# model inference on each new frame
|
| 120 |
clip = [cv2.resize(f, (224,224)) for f in list(state)]
|
| 121 |
+
inp = processor(clip, return_tensors='pt').to(DEVICE)
|
| 122 |
+
with torch.no_grad():
|
| 123 |
+
p = torch.softmax(model(**inp).logits, dim=1)[0,1].item()
|
| 124 |
+
|
| 125 |
history.append(p)
|
| 126 |
+
if len(history) > HIST_LEN:
|
| 127 |
+
history.pop(0)
|
| 128 |
|
| 129 |
+
# overlay border and text
|
| 130 |
disp = frame.copy(); h, w = disp.shape[:2]
|
| 131 |
+
if p > thresh:
|
| 132 |
+
cv2.rectangle(disp, (0,0), (w-1,h-1), (255,0,0), 6)
|
| 133 |
+
cv2.putText(disp, f'fight prob: {p:.2f}', (10, h-15),
|
| 134 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255,255,255), 2, cv2.LINE_AA)
|
| 135 |
|
| 136 |
return state, disp, history, plot_history(history, thresh), p
|
| 137 |
|
| 138 |
+
# ββ Build Gradio App ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 139 |
+
with gr.Blocks(title='Abnormal Behaviour Detection') as demo:
|
| 140 |
+
thresh_slider = gr.Slider(
|
| 141 |
+
label='Sensitivity threshold (lower β more sensitive)',
|
| 142 |
+
minimum=0.0, maximum=1.0, step=0.01, value=0.0
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
with gr.Tab('Video file'):
|
| 146 |
+
gr.Markdown('Upload or record a video, set threshold, then Analyze.')
|
| 147 |
+
file_in = gr.Video(format='mp4', webcam_options=gr.WebcamOptions())
|
| 148 |
+
vid_out = gr.Video(label='Annotated video')
|
| 149 |
+
plot_out = gr.Image(label='Fight probability curve')
|
| 150 |
+
beep_out = gr.Audio(label='Alarm')
|
| 151 |
+
gr.Button('Analyze').click(
|
| 152 |
+
run_pipeline,
|
| 153 |
+
inputs=[file_in, thresh_slider],
|
| 154 |
+
outputs=[vid_out, plot_out, beep_out]
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
with gr.Tab('Live stream'):
|
| 158 |
+
gr.Markdown(
|
| 159 |
+
'Live webcam. A red border & red bars appear when `prob > threshold`.\n'
|
| 160 |
+
'Numeric `Current prob` shows the exact model score.'
|
| 161 |
+
)
|
| 162 |
+
cam_in = gr.Image(sources='webcam', streaming=True, type='numpy', label='Webcam')
|
| 163 |
+
cam_out = gr.Image(streaming=True, label='Live annotated')
|
| 164 |
+
plot_live = gr.Plot(label='Fight probability (rolling)')
|
| 165 |
+
num_prob = gr.Number(label='Current prob', precision=2)
|
| 166 |
+
|
| 167 |
frame_state = gr.State(value=deque(maxlen=CLIP))
|
| 168 |
+
prob_state = gr.State(value=[])
|
| 169 |
+
|
| 170 |
+
cam_in.stream(
|
| 171 |
+
live_handler,
|
| 172 |
+
inputs=[cam_in, frame_state, prob_state, thresh_slider],
|
| 173 |
+
outputs=[frame_state, cam_out, prob_state, plot_live, num_prob],
|
| 174 |
+
stream_every=1/STREAM_FPS
|
| 175 |
+
)
|
| 176 |
|
| 177 |
demo.queue().launch()
|