Scoutyx / app.py
Myteam's picture
Update app.py
7f8c49a verified
Raw History Blame Contribute Delete
2.86 kB
import gradio as gr
import cv2
import numpy as np
import onnxruntime as ort
from collections import deque
# === Config ===
SEQUENCE_LENGTH = 16
IMAGE_HEIGHT, IMAGE_WIDTH = 64, 64
CLASSES_LIST = ["Non-violence", "Violence"]
MODEL_PATH = "./Model/model.onnx" # Ensure this path is correct in Hugging Face Spaces
# === ONNX Session Initialization ===
session_options = ort.SessionOptions()
session_options.log_severity_level = 3 # Reduce logging for performance
session_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL # Optimize graph
session = ort.InferenceSession(
MODEL_PATH,
providers=["CUDAExecutionProvider", "CPUExecutionProvider"], # Use CPU for Hugging Face Spaces (no CUDA unless GPU plan)
sess_options=session_options
)
input_name = session.get_inputs()[0].name
output_name = session.get_outputs()[0].name
# === Frame buffer for sequence ===
frames_queue = deque(maxlen=SEQUENCE_LENGTH)
def preprocess_frame(frame):
"""Preprocess frame with minimal overhead."""
frame = cv2.resize(frame, (IMAGE_WIDTH, IMAGE_HEIGHT))
frame = frame.astype(np.float32) / 255.0 # Normalize in one step
return frame
def inference(frame):
"""Process webcam frame and run inference."""
global frames_queue
# Preprocess and add frame to queue
frame_processed = preprocess_frame(frame)
frames_queue.append(frame_processed)
predicted_class_name = "Gathering frames..."
if len(frames_queue) == SEQUENCE_LENGTH:
# Prepare input for ONNX model
input_frames = np.array(frames_queue, dtype=np.float32)
input_frames = np.expand_dims(input_frames, axis=0) # Shape: (1, 16, 64, 64, 3)
output = session.run([output_name], {input_name: input_frames})[0][0]
predicted_label = np.argmax(output)
predicted_class_name = CLASSES_LIST[predicted_label]
# Draw prediction text on frame
color = (0, 0, 255) if predicted_class_name == "Violence" else (0, 255, 0)
frame_out = frame.copy()
cv2.putText(
frame_out, predicted_class_name, (5, 50), # Smaller text for faster rendering
cv2.FONT_HERSHEY_SIMPLEX, 1, color, 2
)
# Convert BGR to RGB for Gradio
frame_out = cv2.cvtColor(frame_out, cv2.COLOR_BGR2RGB)
return frame_out, predicted_class_name
# Gradio interface
with gr.Blocks() as demo:
gr.Markdown("# Real-time Violence Detection")
webcam_input = gr.Image(type="numpy", label="Webcam Input", webcam=True)
output_image = gr.Image(label="Processed Feed", type="numpy")
output_text = gr.Textbox(label="Prediction")
# Use change event for real-time updates
webcam_input.change(
fn=inference,
inputs=webcam_input,
outputs=[output_image, output_text],
_js="() => { return { continuous: true } }" # Enable continuous updates
)
demo.launch()