mkhodary101 commited on
Commit
4e43aa1
Β·
verified Β·
1 Parent(s): ec496f6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -63
app.py CHANGED
@@ -6,45 +6,35 @@ import time
6
  from ultralytics import YOLO
7
  import spaces
8
  import os
9
- import logging
10
- @spaces.GPU
11
 
12
  class CrowdDetection:
13
  def __init__(self, model_path="yolov8n.pt"):
14
- logger.info(f"Initializing CrowdDetection with model: {model_path}")
15
- self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
16
- try:
17
- if not os.path.exists(model_path):
18
- logger.info(f"Model {model_path} not found, downloading...")
19
- self.model = YOLO("yolov8n.pt") # Downloads if not present
20
- self.model.save(model_path)
21
- else:
22
- self.model = YOLO(model_path)
23
- self.model.to(self.device)
24
- logger.info("CrowdDetection model loaded successfully")
25
- except Exception as e:
26
- logger.error(f"Failed to initialize model: {str(e)}")
27
- raise
28
 
 
29
  def detect_crowd(self, video_path):
30
- logger.info(f"Processing video for crowd detection: {video_path}")
31
  try:
 
 
 
 
 
 
 
 
32
  cap = cv2.VideoCapture(video_path)
33
  if not cap.isOpened():
34
- logger.error(f"Failed to open video: {video_path}")
35
  raise ValueError(f"❌ Failed to open video: {video_path}")
36
 
37
  fps = int(cap.get(cv2.CAP_PROP_FPS))
38
  width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
39
  height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
40
- logger.debug(f"Video specs - FPS: {fps}, Width: {width}, Height: {height}")
41
 
42
  output_path = "output_crowd.mp4"
43
  fourcc = cv2.VideoWriter_fourcc(*"mp4v")
44
  out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
45
  if not out.isOpened():
46
  cap.release()
47
- logger.error(f"Failed to initialize video writer for {output_path}")
48
  raise ValueError(f"❌ Failed to initialize video writer")
49
 
50
  CROWD_THRESHOLD = 10
@@ -56,9 +46,8 @@ class CrowdDetection:
56
  break
57
  frame_count += 1
58
 
59
- results = self.model(frame)
60
  person_count = sum(1 for result in results for cls in result.boxes.cls.cpu().numpy() if int(cls) == 0)
61
- logger.debug(f"Frame {frame_count}: Detected {person_count} people")
62
 
63
  for result in results:
64
  boxes = result.boxes.xyxy.cpu().numpy()
@@ -77,28 +66,26 @@ class CrowdDetection:
77
  cap.release()
78
  out.release()
79
  if frame_count == 0 or not os.path.exists(output_path):
80
- logger.error(f"Processing failed: Frames processed: {frame_count}, Output exists: {os.path.exists(output_path)}")
81
  raise ValueError("❌ Processing failed: No frames processed or output not created")
82
- logger.info(f"Crowd detection completed, output saved to: {output_path}")
83
  return output_path
84
  except Exception as e:
85
- logger.error(f"Error in detect_crowd: {str(e)}")
86
- raise
87
 
88
  class PeopleTracking:
89
  def __init__(self, yolo_model_path="yolov8n.pt"):
90
- logger.info(f"Initializing PeopleTracking with model: {yolo_model_path}")
91
- self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
92
- if not os.path.exists(yolo_model_path):
93
- self.model = YOLO("yolov8n.pt")
94
- self.model.save(yolo_model_path)
95
- else:
96
- self.model = YOLO(yolo_model_path)
97
- self.model.to(self.device)
98
 
 
99
  def track_people(self, video_path):
100
- logger.info(f"Tracking people in video: {video_path}")
101
  try:
 
 
 
 
 
 
 
 
102
  cap = cv2.VideoCapture(video_path)
103
  if not cap.isOpened():
104
  raise ValueError(f"❌ Failed to open video: {video_path}")
@@ -117,7 +104,7 @@ class PeopleTracking:
117
  if not ret:
118
  break
119
 
120
- results = self.model.track(frame, persist=True)
121
  for result in results:
122
  boxes = result.boxes.xyxy.cpu().numpy()
123
  classes = result.boxes.cls.cpu().numpy()
@@ -137,23 +124,23 @@ class PeopleTracking:
137
  raise ValueError("❌ Processing failed")
138
  return output_path
139
  except Exception as e:
140
- logger.error(f"Error in track_people: {str(e)}")
141
- raise
142
 
143
  class FallDetection:
144
  def __init__(self, yolo_model_path="yolov8l.pt"):
145
- logger.info(f"Initializing FallDetection with model: {yolo_model_path}")
146
- self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
147
- if not os.path.exists(yolo_model_path):
148
- self.model = YOLO("yolov8l.pt")
149
- self.model.save(yolo_model_path)
150
- else:
151
- self.model = YOLO(yolo_model_path)
152
- self.model.to(self.device)
153
 
 
154
  def detect_fall(self, video_path):
155
- logger.info(f"Detecting falls in video: {video_path}")
156
  try:
 
 
 
 
 
 
 
 
157
  cap = cv2.VideoCapture(video_path)
158
  if not cap.isOpened():
159
  raise ValueError(f"❌ Failed to open video: {video_path}")
@@ -172,7 +159,7 @@ class FallDetection:
172
  if not ret:
173
  break
174
 
175
- results = self.model(frame)
176
  for result in results:
177
  boxes = result.boxes.xyxy.cpu().numpy()
178
  classes = result.boxes.cls.cpu().numpy()
@@ -202,23 +189,23 @@ class FallDetection:
202
  raise ValueError("❌ Processing failed")
203
  return output_path
204
  except Exception as e:
205
- logger.error(f"Error in detect_fall: {str(e)}")
206
- raise
207
 
208
  class FightDetection:
209
  def __init__(self, yolo_model_path="yolov8n-pose.pt"):
210
- logger.info(f"Initializing FightDetection with model: {yolo_model_path}")
211
- self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
212
- if not os.path.exists(yolo_model_path):
213
- self.model = YOLO("yolov8n-pose.pt")
214
- self.model.save(yolo_model_path)
215
- else:
216
- self.model = YOLO(yolo_model_path)
217
- self.model.to(self.device)
218
 
 
219
  def detect_fight(self, video_path):
220
- logger.info(f"Detecting fights in video: {video_path}")
221
  try:
 
 
 
 
 
 
 
 
222
  cap = cv2.VideoCapture(video_path)
223
  if not cap.isOpened():
224
  raise ValueError(f"❌ Failed to open video: {video_path}")
@@ -237,7 +224,7 @@ class FightDetection:
237
  if not ret:
238
  break
239
 
240
- results = self.model.track(frame, persist=True)
241
  fight_detected = False
242
  person_count = 0
243
 
@@ -267,8 +254,7 @@ class FightDetection:
267
  raise ValueError("❌ Processing failed")
268
  return output_path
269
  except Exception as e:
270
- logger.error(f"Error in detect_fight: {str(e)}")
271
- raise
272
 
273
  # Unified processing function with status output
274
  def process_video(feature, video):
@@ -284,7 +270,6 @@ def process_video(feature, video):
284
  output_path = getattr(detector, method_name)(video)
285
  return f"{feature} completed successfully", output_path
286
  except Exception as e:
287
- logger.error(f"Error processing video with {feature}: {str(e)}")
288
  return f"Error: {str(e)}", None
289
 
290
  # Gradio Interface with dual outputs
 
6
  from ultralytics import YOLO
7
  import spaces
8
  import os
 
 
9
 
10
  class CrowdDetection:
11
  def __init__(self, model_path="yolov8n.pt"):
12
+ self.model_path = model_path # Store path, load model later
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ @spaces.GPU
15
  def detect_crowd(self, video_path):
 
16
  try:
17
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
18
+ if not os.path.exists(self.model_path):
19
+ model = YOLO("yolov8n.pt")
20
+ model.save(self.model_path)
21
+ else:
22
+ model = YOLO(self.model_path)
23
+ model.to(device)
24
+
25
  cap = cv2.VideoCapture(video_path)
26
  if not cap.isOpened():
 
27
  raise ValueError(f"❌ Failed to open video: {video_path}")
28
 
29
  fps = int(cap.get(cv2.CAP_PROP_FPS))
30
  width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
31
  height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
 
32
 
33
  output_path = "output_crowd.mp4"
34
  fourcc = cv2.VideoWriter_fourcc(*"mp4v")
35
  out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
36
  if not out.isOpened():
37
  cap.release()
 
38
  raise ValueError(f"❌ Failed to initialize video writer")
39
 
40
  CROWD_THRESHOLD = 10
 
46
  break
47
  frame_count += 1
48
 
49
+ results = model(frame)
50
  person_count = sum(1 for result in results for cls in result.boxes.cls.cpu().numpy() if int(cls) == 0)
 
51
 
52
  for result in results:
53
  boxes = result.boxes.xyxy.cpu().numpy()
 
66
  cap.release()
67
  out.release()
68
  if frame_count == 0 or not os.path.exists(output_path):
 
69
  raise ValueError("❌ Processing failed: No frames processed or output not created")
 
70
  return output_path
71
  except Exception as e:
72
+ raise ValueError(f"Error in detect_crowd: {str(e)}")
 
73
 
74
  class PeopleTracking:
75
  def __init__(self, yolo_model_path="yolov8n.pt"):
76
+ self.model_path = yolo_model_path
 
 
 
 
 
 
 
77
 
78
+ @spaces.GPU
79
  def track_people(self, video_path):
 
80
  try:
81
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
82
+ if not os.path.exists(self.model_path):
83
+ model = YOLO("yolov8n.pt")
84
+ model.save(self.model_path)
85
+ else:
86
+ model = YOLO(self.model_path)
87
+ model.to(device)
88
+
89
  cap = cv2.VideoCapture(video_path)
90
  if not cap.isOpened():
91
  raise ValueError(f"❌ Failed to open video: {video_path}")
 
104
  if not ret:
105
  break
106
 
107
+ results = model.track(frame, persist=True)
108
  for result in results:
109
  boxes = result.boxes.xyxy.cpu().numpy()
110
  classes = result.boxes.cls.cpu().numpy()
 
124
  raise ValueError("❌ Processing failed")
125
  return output_path
126
  except Exception as e:
127
+ raise ValueError(f"Error in track_people: {str(e)}")
 
128
 
129
  class FallDetection:
130
  def __init__(self, yolo_model_path="yolov8l.pt"):
131
+ self.model_path = yolo_model_path
 
 
 
 
 
 
 
132
 
133
+ @spaces.GPU
134
  def detect_fall(self, video_path):
 
135
  try:
136
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
137
+ if not os.path.exists(self.model_path):
138
+ model = YOLO("yolov8l.pt")
139
+ model.save(self.model_path)
140
+ else:
141
+ model = YOLO(self.model_path)
142
+ model.to(device)
143
+
144
  cap = cv2.VideoCapture(video_path)
145
  if not cap.isOpened():
146
  raise ValueError(f"❌ Failed to open video: {video_path}")
 
159
  if not ret:
160
  break
161
 
162
+ results = model(frame)
163
  for result in results:
164
  boxes = result.boxes.xyxy.cpu().numpy()
165
  classes = result.boxes.cls.cpu().numpy()
 
189
  raise ValueError("❌ Processing failed")
190
  return output_path
191
  except Exception as e:
192
+ raise ValueError(f"Error in detect_fall: {str(e)}")
 
193
 
194
  class FightDetection:
195
  def __init__(self, yolo_model_path="yolov8n-pose.pt"):
196
+ self.model_path = yolo_model_path
 
 
 
 
 
 
 
197
 
198
+ @spaces.GPU
199
  def detect_fight(self, video_path):
 
200
  try:
201
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
202
+ if not os.path.exists(self.model_path):
203
+ model = YOLO("yolov8n-pose.pt")
204
+ model.save(self.model_path)
205
+ else:
206
+ model = YOLO(self.model_path)
207
+ model.to(device)
208
+
209
  cap = cv2.VideoCapture(video_path)
210
  if not cap.isOpened():
211
  raise ValueError(f"❌ Failed to open video: {video_path}")
 
224
  if not ret:
225
  break
226
 
227
+ results = model.track(frame, persist=True)
228
  fight_detected = False
229
  person_count = 0
230
 
 
254
  raise ValueError("❌ Processing failed")
255
  return output_path
256
  except Exception as e:
257
+ raise ValueError(f"Error in detect_fight: {str(e)}")
 
258
 
259
  # Unified processing function with status output
260
  def process_video(feature, video):
 
270
  output_path = getattr(detector, method_name)(video)
271
  return f"{feature} completed successfully", output_path
272
  except Exception as e:
 
273
  return f"Error: {str(e)}", None
274
 
275
  # Gradio Interface with dual outputs