File size: 14,815 Bytes
7d1f745
329c034
 
 
 
 
82ed089
aca5f43
35960dd
cdec70d
7a2e724
3d44b76
7ef0fcc
4e43aa1
3d44b76
35960dd
4e43aa1
 
 
 
 
 
 
 
35960dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e43aa1
35960dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7ef0fcc
35960dd
 
 
 
 
3d44b76
7ef0fcc
329c034
 
4e43aa1
aca5f43
4e43aa1
3d44b76
35960dd
4e43aa1
 
 
 
 
 
 
 
35960dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e43aa1
35960dd
 
 
 
 
 
 
 
 
 
 
 
aca5f43
35960dd
 
 
 
 
 
3d44b76
329c034
 
 
4e43aa1
aca5f43
4e43aa1
3d44b76
35960dd
4e43aa1
 
 
 
 
 
 
 
35960dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e43aa1
35960dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aca5f43
35960dd
 
 
 
 
3d44b76
329c034
 
 
4e43aa1
aca5f43
4e43aa1
3d44b76
35960dd
4e43aa1
 
 
 
 
 
 
 
35960dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e43aa1
35960dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aca5f43
35960dd
 
 
 
 
3d44b76
35960dd
40068e9
 
 
 
 
 
6bc6c86
40068e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35960dd
329c034
 
cdec70d
329c034
 
40068e9
324be48
329c034
aca5f43
 
324be48
aca5f43
35960dd
aca5f43
35960dd
329c034
35960dd
329c034
 
 
40068e9
329c034
 
35960dd
 
 
 
aca5f43
 
329c034
 
 
aca5f43
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import gradio as gr
import torch
import cv2
import numpy as np
import time
from ultralytics import YOLO
import spaces
import os

class CrowdDetection:
    def __init__(self, model_path="yolov8n.pt"):
        self.model_path = model_path

    @spaces.GPU
    def crowd_detection(self, video_path):
        try:
            device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
            if not os.path.exists(self.model_path):
                model = YOLO("yolov8n.pt")
                model.save(self.model_path)
            else:
                model = YOLO(self.model_path)
            model.to(device)

            cap = cv2.VideoCapture(video_path)
            if not cap.isOpened():
                raise ValueError(f"❌ Failed to open video: {video_path}")

            fps = int(cap.get(cv2.CAP_PROP_FPS))
            width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
            height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

            output_path = "output_crowd.mp4"
            fourcc = cv2.VideoWriter_fourcc(*"mp4v")
            out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
            if not out.isOpened():
                cap.release()
                raise ValueError(f"❌ Failed to initialize video writer")

            CROWD_THRESHOLD = 10
            frame_count = 0

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

                results = model(frame)
                person_count = sum(1 for result in results for cls in result.boxes.cls.cpu().numpy() if int(cls) == 0)

                for result in results:
                    boxes = result.boxes.xyxy.cpu().numpy()
                    classes = result.boxes.cls.cpu().numpy()
                    for box, cls in zip(boxes, classes):
                        if int(cls) == 0:
                            x1, y1, x2, y2 = map(int, box)
                            cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
                            cv2.putText(frame, "Person", (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

                alert_text = "Crowd Alert!" if person_count > CROWD_THRESHOLD else f"People: {person_count}"
                cv2.putText(frame, alert_text, (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1,
                            (0, 0, 255) if person_count > CROWD_THRESHOLD else (0, 255, 0), 2)
                out.write(frame)

            cap.release()
            out.release()
            if frame_count == 0 or not os.path.exists(output_path):
                raise ValueError("❌ Processing failed: No frames processed or output not created")
            return output_path
        except Exception as e:
            raise ValueError(f"Error in crowd_detection: {str(e)}")

class PeopleTracking:
    def __init__(self, yolo_model_path="yolov8n.pt"):
        self.model_path = yolo_model_path

    @spaces.GPU
    def people_tracking(self, video_path):
        try:
            device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
            if not os.path.exists(self.model_path):
                model = YOLO("yolov8n.pt")
                model.save(self.model_path)
            else:
                model = YOLO(self.model_path)
            model.to(device)

            cap = cv2.VideoCapture(video_path)
            if not cap.isOpened():
                raise ValueError(f"❌ Failed to open video: {video_path}")

            fps = int(cap.get(cv2.CAP_PROP_FPS))
            width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
            height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
            output_path = "output_tracking.mp4"
            out = cv2.VideoWriter(output_path, cv2.VideoWriter_fourcc(*"mp4v"), fps, (width, height))
            if not out.isOpened():
                cap.release()
                raise ValueError(f"❌ Failed to initialize video writer")

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

                results = model.track(frame, persist=True)
                for result in results:
                    boxes = result.boxes.xyxy.cpu().numpy()
                    classes = result.boxes.cls.cpu().numpy()
                    ids = result.boxes.id.cpu().numpy() if result.boxes.id is not None else np.arange(len(boxes))

                    for box, cls, obj_id in zip(boxes, classes, ids):
                        if int(cls) == 0:
                            x1, y1, x2, y2 = map(int, box)
                            cv2.rectangle(frame, (x1, y1), (x2, y2), (255, 0, 0), 2)
                            cv2.putText(frame, f"ID {int(obj_id)}", (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)

                out.write(frame)

            cap.release()
            out.release()
            if not os.path.exists(output_path):
                raise ValueError("❌ Processing failed")
            return output_path
        except Exception as e:
            raise ValueError(f"Error in people_tracking: {str(e)}")

class FallDetection:
    def __init__(self, yolo_model_path="yolov8l.pt"):
        self.model_path = yolo_model_path

    @spaces.GPU
    def fall_detection(self, video_path):
        try:
            device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
            if not os.path.exists(self.model_path):
                model = YOLO("yolov8l.pt")
                model.save(self.model_path)
            else:
                model = YOLO(self.model_path)
            model.to(device)

            cap = cv2.VideoCapture(video_path)
            if not cap.isOpened():
                raise ValueError(f"❌ Failed to open video: {video_path}")

            fps = int(cap.get(cv2.CAP_PROP_FPS))
            width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
            height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
            output_path = "output_fall.mp4"
            out = cv2.VideoWriter(output_path, cv2.VideoWriter_fourcc(*"mp4v"), fps, (width, height))
            if not out.isOpened():
                cap.release()
                raise ValueError(f"❌ Failed to initialize video writer")

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

                results = model(frame)
                for result in results:
                    boxes = result.boxes.xyxy.cpu().numpy()
                    classes = result.boxes.cls.cpu().numpy()

                    for box, cls in zip(boxes, classes):
                        if int(cls) == 0:
                            x1, y1, x2, y2 = map(int, box)
                            width = x2 - x1
                            height = y2 - y1
                            aspect_ratio = width / height if height > 0 else float('inf')

                            if aspect_ratio > 0.55:
                                color = (0, 0, 255)
                                label = "FALL DETECTED"
                            else:
                                color = (0, 255, 0)
                                label = "Standing"
                            
                            cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2)
                            cv2.putText(frame, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)

                out.write(frame)

            cap.release()
            out.release()
            if not os.path.exists(output_path):
                raise ValueError("❌ Processing failed")
            return output_path
        except Exception as e:
            raise ValueError(f"Error in fall_detection: {str(e)}")

class FightDetection:
    def __init__(self, yolo_model_path="yolov8n-pose.pt"):
        self.model_path = yolo_model_path

    @spaces.GPU
    def fight_detection(self, video_path):
        try:
            device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
            if not os.path.exists(self.model_path):
                model = YOLO("yolov8n-pose.pt")
                model.save(self.model_path)
            else:
                model = YOLO(self.model_path)
            model.to(device)

            cap = cv2.VideoCapture(video_path)
            if not cap.isOpened():
                raise ValueError(f"❌ Failed to open video: {video_path}")

            fps = int(cap.get(cv2.CAP_PROP_FPS))
            width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
            height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
            output_path = "output_fight.mp4"
            out = cv2.VideoWriter(output_path, cv2.VideoWriter_fourcc(*"mp4v"), fps, (width, height))
            if not out.isOpened():
                cap.release()
                raise ValueError(f"❌ Failed to initialize video writer")

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

                results = model.track(frame, persist=True)
                fight_detected = False
                person_count = 0

                for result in results:
                    keypoints = result.keypoints.xy.cpu().numpy() if result.keypoints else []
                    boxes = result.boxes.xyxy.cpu().numpy() if result.boxes else []
                    classes = result.boxes.cls.cpu().numpy() if result.boxes else []

                    for box, kp, cls in zip(boxes, keypoints, classes):
                        if int(cls) == 0:
                            person_count += 1
                            x1, y1, x2, y2 = map(int, box)
                            if len(kp) > 7 and (kp[5][1] < y1 + (y2 - y1) * 0.3 or kp[7][1] < y1 + (y2 - y1) * 0.3):
                                fight_detected = True
                            cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 0, 255) if fight_detected else (0, 255, 0), 2)
                            label = "FIGHT DETECTED" if fight_detected else "Person"
                            cv2.putText(frame, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, 
                                        (0, 0, 255) if fight_detected else (0, 255, 0), 2)

                if fight_detected and person_count > 1:
                    cv2.putText(frame, "FIGHT ALERT!", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
                out.write(frame)

            cap.release()
            out.release()
            if not os.path.exists(output_path):
                raise ValueError("❌ Processing failed")
            return output_path
        except Exception as e:
            raise ValueError(f"Error in fight_detection: {str(e)}")

class IntrusionDetection:
    def __init__(self, model_path="yolov8n.pt", max_intrusion_time=300, iou_threshold=0.5, conf_threshold=0.5):
        self.model_path = model_path
        self.max_intrusion_time = max_intrusion_time
        self.iou_threshold = iou_threshold
        self.conf_threshold = conf_threshold
        @spaces.GPU

    def detect_intrusion(self, video_path):
        try:
            device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
            if not os.path.exists(self.model_path):
                model = YOLO("yolov8n.pt")
                model.save(self.model_path)
            else:
                model = YOLO(self.model_path)
            model.to(device)

            cap = cv2.VideoCapture(video_path)
            if not cap.isOpened():
                raise ValueError(f"❌ Failed to open video: {video_path}")

            fps = int(cap.get(cv2.CAP_PROP_FPS))
            width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
            height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

            output_path = "output_intrusion.mp4"
            fourcc = cv2.VideoWriter_fourcc(*"mp4v")
            out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
            if not out.isOpened():
                cap.release()
                raise ValueError(f"❌ Failed to initialize video writer")

            frame_count = 0

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

                results = model(frame)
                for result in results:
                    boxes = result.boxes.xyxy.cpu().numpy()
                    classes = result.boxes.cls.cpu().numpy()
                    confidences = result.boxes.conf.cpu().numpy()
                    for box, cls, conf in zip(boxes, classes, confidences):
                        if int(cls) == 0 and conf > self.conf_threshold:  # Person class with confidence filter
                            x1, y1, x2, y2 = map(int, box)
                            label = "Intruder"
                            color = (0, 0, 255)
                            cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2)
                            cv2.putText(frame, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
                
                out.write(frame)

            cap.release()
            out.release()
            if frame_count == 0 or not os.path.exists(output_path):
                raise ValueError("❌ Processing failed: No frames processed or output not created")
            return output_path
        except Exception as e:
            raise ValueError(f"Error in detect_intrusion: {str(e)}")

# Unified processing function with status output
def process_video(feature, video):
    detectors = {
        "Crowd Detection": CrowdDetection,
        "People Tracking": PeopleTracking,
        "Fall Detection": FallDetection,
        "Fight Detection": FightDetection,
        "Intrusion Detection" : IntrusionDetection
    }
    try:
        detector = detectors[feature]()
        method_name = "detect_intrusion" if feature == "Intrusion Detection" else feature.lower().replace(" ", "_")
        output_path = getattr(detector, method_name)(video)
        return f"{feature} completed successfully", output_path
    except Exception as e:
        return f"Error: {str(e)}", None

# Gradio Interface with dual outputs
interface = gr.Interface(
    fn=process_video,
    inputs=[
        gr.Dropdown(choices=["Crowd Detection", "People Tracking", "Fall Detection", "Fight Detection", "Intrusion Detection"], label="Select Feature"),
        gr.Video(label="Upload Video")
    ],
    outputs=[
        gr.Textbox(label="Status"),
        gr.Video(label="Processed Video")
    ],
    title="YOLOv8 Multitask Video Processing",
    description="Select a feature to process your video: Crowd Detection, People Tracking, Fall Detection, or Fight Detection."
)

if __name__ == "__main__":
    interface.launch(debug=True)