Abubakar740 commited on
Commit
abd4c19
·
1 Parent(s): d266c69

initial commit

Browse files
Files changed (4) hide show
  1. app.py +119 -0
  2. models/best_slowfast_theft.pth +3 -0
  3. packages.txt +3 -0
  4. requirements.txt +11 -0
app.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import torch
4
+ import numpy as np
5
+ import uuid
6
+ import threading
7
+ import gradio as gr
8
+ from fastapi import FastAPI, UploadFile, File, BackgroundTasks, HTTPException
9
+ from fastapi.responses import FileResponse
10
+ from collections import deque
11
+ from pytorchvideo.models.hub import slowfast_r50
12
+ from ultralytics import YOLO
13
+ import torch.nn as nn
14
+
15
+ # --- SETUP & DIRECTORIES ---
16
+ UPLOAD_DIR = "uploads"
17
+ OUTPUT_DIR = "outputs"
18
+ MODEL_PATH = "models/best_slowfast_theft.pth"
19
+ os.makedirs(UPLOAD_DIR, exist_ok=True)
20
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
21
+
22
+ JOBS = {} # Track progress
23
+
24
+ # --- MODEL LOADING ---
25
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
26
+ yolo = YOLO("yolov8n.pt")
27
+
28
+ def load_slowfast():
29
+ model = slowfast_r50(pretrained=False)
30
+ in_features = model.blocks[-1].proj.in_features
31
+ model.blocks[-1].proj = nn.Sequential(
32
+ nn.Dropout(p=0.5),
33
+ nn.Linear(in_features, 2)
34
+ )
35
+ if os.path.exists(MODEL_PATH):
36
+ ckpt = torch.load(MODEL_PATH, map_location=DEVICE)
37
+ model.load_state_dict(ckpt["model"] if "model" in ckpt else ckpt)
38
+ model.to(DEVICE).eval()
39
+ return model
40
+
41
+ detector_model = load_slowfast()
42
+
43
+ # --- DETECTION LOGIC ---
44
+ def process_video_logic(job_id, input_path, output_path):
45
+ cap = cv2.VideoCapture(input_path)
46
+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
47
+ fps = int(cap.get(cv2.CAP_PROP_FPS))
48
+ w, h = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
49
+
50
+ out = cv2.VideoWriter(output_path, cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))
51
+ frame_buffer = deque(maxlen=32)
52
+
53
+ curr = 0
54
+ while cap.isOpened():
55
+ ret, frame = cap.read()
56
+ if not ret: break
57
+
58
+ curr += 1
59
+ JOBS[job_id]["progress"] = int((curr/total_frames)*100)
60
+
61
+ # Basic YOLO logic (Simplified for speed)
62
+ results = yolo(frame, verbose=False)
63
+ for r in results:
64
+ for box in r.boxes:
65
+ if int(box.cls[0]) == 0:
66
+ x1, y1, x2, y2 = map(int, box.xyxy[0])
67
+ cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
68
+
69
+ out.write(frame)
70
+
71
+ cap.release()
72
+ out.release()
73
+ JOBS[job_id]["status"] = "completed"
74
+
75
+ # --- FASTAPI ENDPOINTS ---
76
+ app = FastAPI()
77
+
78
+ @app.post("/api/detect")
79
+ async def api_detect(background_tasks: BackgroundTasks, file: UploadFile = File(...)):
80
+ job_id = str(uuid.uuid4())
81
+ in_p = os.path.join(UPLOAD_DIR, f"{job_id}.mp4")
82
+ out_p = os.path.join(OUTPUT_DIR, f"{job_id}.mp4")
83
+
84
+ with open(in_p, "wb") as f: f.write(await file.read())
85
+
86
+ JOBS[job_id] = {"progress": 0, "status": "processing", "file": out_p}
87
+ background_tasks.add_task(process_video_logic, job_id, in_p, out_p)
88
+ return {"job_id": job_id}
89
+
90
+ @app.get("/api/progress/{job_id}")
91
+ async def api_progress(job_id: str):
92
+ return JOBS.get(job_id, {"error": "not found"})
93
+
94
+ # --- GRADIO FRONTEND ---
95
+ def web_ui_process(video_input):
96
+ if video_input is None: return None
97
+ job_id = str(uuid.uuid4())
98
+ out_p = os.path.join(OUTPUT_DIR, f"{job_id}.mp4")
99
+
100
+ # Run the processing (Sync for Gradio UI to show progress)
101
+ JOBS[job_id] = {"progress": 0, "status": "processing"}
102
+ process_video_logic(job_id, video_input, out_p)
103
+ return out_p
104
+
105
+ with gr.Blocks(title="Theft Detection System") as demo:
106
+ gr.Markdown("# 🛡️ AI Theft Detection System")
107
+ with gr.Row():
108
+ video_in = gr.Video(label="Upload Video")
109
+ video_out = gr.Video(label="Processed Result")
110
+ btn = gr.Button("Detect Theft")
111
+ btn.click(web_ui_process, inputs=video_in, outputs=video_out)
112
+
113
+ # --- MOUNT FASTAPI TO GRADIO ---
114
+ # This allows both to run on the same port on Hugging Face
115
+ app = gr.mount_gradio_app(app, demo, path="/")
116
+
117
+ if __name__ == "__main__":
118
+ import uvicorn
119
+ uvicorn.run(app, host="0.0.0.0", port=7860)
models/best_slowfast_theft.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:267ce0e679450fb20400d7a03318c7b9e7d37a0356e396eac0051ba8fb0e2194
3
+ size 135113790
packages.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ libgl1
2
+ libglib2.0-0
3
+ ffmpeg
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn
3
+ gradio
4
+ ultralytics
5
+ torch
6
+ torchvision
7
+ pytorchvideo
8
+ opencv-python
9
+ fvcore
10
+ numpy<2.0.0
11
+ python-multipart