File size: 2,575 Bytes
486cf4b
6936686
 
 
 
486cf4b
 
f692223
4d7986a
486cf4b
f692223
6936686
f692223
 
5ed03fa
f692223
4d7986a
3dad993
d9882d4
f692223
595de22
 
 
 
f692223
6936686
 
 
 
 
f692223
6936686
 
f692223
6936686
595de22
 
6936686
f692223
 
 
 
 
 
 
 
6936686
f692223
6936686
595de22
f692223
595de22
6936686
595de22
6936686
f692223
6936686
595de22
6936686
 
d32415e
6936686
 
 
 
d32415e
6936686
 
 
 
 
d32415e
6936686
 
 
d32415e
6936686
f692223
6936686
 
f692223
 
d32415e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import os
import sys
import tempfile
import cv2
import numpy as np
import streamlit as st

# Append src directory to import custom modules
sys.path.append(os.path.join(os.path.dirname(__file__), 'src'))

# Environment fixes for Hugging Face Spaces
os.environ["STREAMLIT_BROWSER_GATHER_USAGE_STATS"] = "false"
os.environ["XDG_CONFIG_HOME"] = "/tmp"
os.environ["HF_HUB_CACHE"] = "/tmp/huggingface"

# Local utility imports
from preprocess import preprocess_frame
from predict import run_prediction, load_trained_model

# Streamlit setup
st.set_page_config(layout="wide")
st.title("πŸ” Violence Detection in Video")
st.markdown("Upload a video and let the model detect violent scenes in real-time.")

# Load model with proper feedback
st.info("πŸ” Loading model...")
try:
    model = load_trained_model()
    st.success("βœ… Model loaded successfully.")
except Exception as e:
    st.error(f"❌ Model loading failed: {e}")
    st.stop()

# Upload video section
uploaded_file = st.file_uploader("πŸ“€ Upload a video", type=["mp4", "avi", "mpeg", "mov", "mpg"])

if uploaded_file is not None:
    try:
        st.info("πŸ“₯ Reading and saving uploaded file...")

        # Read file into memory first to avoid Hugging Face frontend 403 issues
        file_bytes = uploaded_file.read()
        if not file_bytes:
            st.error("❌ Uploaded file could not be read.")
            st.stop()

        with tempfile.NamedTemporaryFile(delete=False, dir='/tmp', suffix='.mp4') as tfile:
            tfile.write(file_bytes)
            video_path = tfile.name

        st.success("βœ… Video saved. Loading...")

        cap = cv2.VideoCapture(video_path)

        if not cap.isOpened():
            st.error("❌ Could not open video. Please try another format.")
            st.stop()

        stframe = st.empty()
        frame_count = 0

        while cap.isOpened():
            ret, frame = cap.read()
            if not ret:
                break

            frame_count += 1
            processed = preprocess_frame(frame)
            pred = run_prediction(model, processed)
            label = "Violent" if pred <= 0.5 else "Non-Violent"
            color = (0, 0, 255) if label == "Violent" else (0, 255, 0)

            cv2.putText(frame, f'{label} ({pred:.2f})', (10, 30),
                        cv2.FONT_HERSHEY_SIMPLEX, 1, color, 2)
            stframe.image(frame, channels="BGR")

        cap.release()
        st.success(f"βœ… Done! {frame_count} frames processed.")

    except Exception as e:
        st.error(f"❌ An unexpected error occurred:\n\n{e}")