mkhodary101 commited on
Commit
966c0a8
·
verified ·
1 Parent(s): eaf5124

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -87
app.py CHANGED
@@ -1,107 +1,93 @@
1
  import gradio as gr
2
- import torch
3
  import cv2
 
4
  import os
 
5
  from ultralytics import YOLO
6
- import spaces
7
-
8
- @spaces.GPU # Ensures GPU is allocated for this function
9
-
10
- class CrowdDetection:
11
- def __init__(self, yolo_model_path="yolov8n.pt", crowd_threshold=10):
12
- # Determine the best available device
13
- if torch.cuda.is_available():
14
- self.device = torch.device("cuda")
15
- print(f"Using CUDA Device: {torch.cuda.get_device_name(0)}")
16
- else:
17
- self.device = torch.device("cpu")
18
- print("Using CPU as no CUDA device is available")
19
-
20
- try:
21
- # Load the YOLO model on the selected device
22
- self.model = YOLO(yolo_model_path).to(self.device)
23
- except Exception as e:
24
- print(f"Error loading YOLO model: {e}")
25
- self.model = None
26
-
27
- self.crowd_threshold = crowd_threshold
28
 
29
- def detect_crowd(self, video_path):
30
- if self.model is None:
31
- raise ValueError("YOLO model failed to load")
32
-
33
- cap = cv2.VideoCapture(video_path)
34
-
35
- # Ensure video is opened successfully
36
- if not cap.isOpened():
37
- raise ValueError(f"Failed to open video: {video_path}")
38
 
39
- output_path = "output_crowd.mp4"
40
- output_full_path = os.path.abspath(output_path) # Convert to absolute path
41
-
42
- fourcc = cv2.VideoWriter_fourcc(*"mp4v")
43
- out = cv2.VideoWriter(output_full_path, fourcc, int(cap.get(cv2.CAP_PROP_FPS)),
44
- (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))))
45
-
46
- while cap.isOpened():
47
- ret, frame = cap.read()
48
- if not ret:
49
- break
50
-
51
- # Perform detection
52
- results = self.model(frame)
53
- person_count = 0
54
-
55
- for result in results:
56
- boxes = result.boxes.xyxy.cpu().numpy()
57
- classes = result.boxes.cls.cpu().numpy()
58
-
59
- for box, cls in zip(boxes, classes):
60
- if int(cls) == 0: # YOLO class ID 0 = "person"
61
- person_count += 1
62
- x1, y1, x2, y2 = map(int, box)
63
- cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
64
- cv2.putText(frame, "Person", (x1, y1 - 10),
65
- cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
66
-
67
- alert_text = "Crowd Alert!" if person_count > self.crowd_threshold else f"People: {person_count}"
68
- cv2.putText(frame, alert_text, (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1,
69
- (0, 0, 255) if person_count > self.crowd_threshold else (0, 255, 0), 2)
70
-
71
- out.write(frame)
72
-
73
- cap.release()
74
- out.release()
75
 
76
- # Ensure output file exists before returning
77
- if not os.path.exists(output_full_path):
78
- raise FileNotFoundError(f"Output video not found: {output_full_path}")
79
 
80
- print(f"Processed video saved at: {output_full_path}")
81
- return output_full_path
82
 
83
- def process_video(video):
84
- try:
85
- print(f"Received video: {video}")
 
 
 
 
 
 
 
 
 
86
 
87
- detector = CrowdDetection()
88
- output_video = detector.detect_crowd(video)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
- if not os.path.exists(output_video): # Ensure output file exists
91
- raise FileNotFoundError(f"Output video does not exist: {output_video}")
92
 
93
- print(f"Returning processed video: {output_video}")
94
- return output_video
95
- except Exception as e:
96
- print(f"Video processing error: {e}")
97
- return None # Prevent crashing the app
98
 
99
- # Gradio Interface for Hugging Face Spaces
100
  interface = gr.Interface(
101
  fn=process_video,
102
  inputs=gr.Video(label="Upload Video"),
103
  outputs=gr.Video(label="Processed Video"),
104
- title="Crowd Detection using YOLOv8"
 
105
  )
106
 
107
  if __name__ == "__main__":
 
1
  import gradio as gr
 
2
  import cv2
3
+ import numpy as np
4
  import os
5
+ import torch
6
  from ultralytics import YOLO
7
+ import spaces # Import ZeroGPU for Hugging Face Spaces
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
+ @spaces.GPU # Ensures GPU is allocated during execution
10
+ def process_video(video_path):
11
+ """Process video using YOLOv8 for crowd detection."""
12
+
13
+ # Check if CUDA is available
14
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
15
+ print(f"🔍 Using device: {device}")
 
 
16
 
17
+ # Load YOLOv8 model on GPU
18
+ model = YOLO("yolov8n.pt").to(device)
19
+
20
+ # Read input video
21
+ cap = cv2.VideoCapture(video_path)
22
+ if not cap.isOpened():
23
+ raise ValueError(f"❌ Failed to open video: {video_path}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
+ fps = int(cap.get(cv2.CAP_PROP_FPS))
26
+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
27
+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
28
 
29
+ print(f"🎥 Video details - FPS: {fps}, Width: {width}, Height: {height}")
 
30
 
31
+ # Define output video path
32
+ output_path = "output_crowd.mp4"
33
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
34
+ out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
35
+
36
+ CROWD_THRESHOLD = 10 # Define crowd limit for alerts
37
+ frame_count = 0
38
+
39
+ while cap.isOpened():
40
+ ret, frame = cap.read()
41
+ if not ret:
42
+ break # End of video
43
 
44
+ frame_count += 1
45
+
46
+ # Run YOLO inference on the frame
47
+ results = model(frame)
48
+
49
+ # Count detected persons
50
+ person_count = 0
51
+ for result in results:
52
+ boxes = result.boxes.xyxy.cpu().numpy()
53
+ classes = result.boxes.cls.cpu().numpy()
54
+
55
+ for box, cls in zip(boxes, classes):
56
+ if int(cls) == 0: # YOLO class ID 0 = "person"
57
+ person_count += 1
58
+ x1, y1, x2, y2 = map(int, box)
59
+
60
+ # Draw bounding box for persons
61
+ cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
62
+ cv2.putText(frame, "Person", (x1, y1 - 10),
63
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
64
+
65
+ # Display count on frame
66
+ alert_text = "Crowd Alert!" if person_count > CROWD_THRESHOLD else f"People: {person_count}"
67
+ cv2.putText(frame, alert_text, (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1,
68
+ (0, 0, 255) if person_count > CROWD_THRESHOLD else (0, 255, 0), 2)
69
+
70
+ out.write(frame) # Save frame to output video
71
+
72
+ cap.release()
73
+ out.release()
74
+
75
+ if frame_count == 0:
76
+ raise ValueError("❌ No frames were processed!")
77
 
78
+ if not os.path.exists(output_path):
79
+ raise FileNotFoundError(f"Output video not found: {output_path}")
80
 
81
+ print(f" Processed video saved at: {output_path}")
82
+ return output_path
 
 
 
83
 
84
+ # Gradio Interface
85
  interface = gr.Interface(
86
  fn=process_video,
87
  inputs=gr.Video(label="Upload Video"),
88
  outputs=gr.Video(label="Processed Video"),
89
+ title="Crowd Detection with YOLOv8",
90
+ description="Upload a video, and YOLOv8 will detect and count people. If the crowd exceeds 10 people, a warning will be displayed."
91
  )
92
 
93
  if __name__ == "__main__":