sparsh007 commited on
Commit
ec84a0f
Β·
verified Β·
1 Parent(s): 49f651b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -43
app.py CHANGED
@@ -16,14 +16,14 @@ AZURE_CONFIG = {
16
  "account_name": "assentian",
17
  "sas_token": "sv=2024-11-04&ss=bfqt&srt=sco&sp=rwdlacupiytfx&se=2025-04-30T04:25:22Z&st=2025-04-16T20:25:22Z&spr=https&sig=HYrJBoOYc4PRe%2BoqBMl%2FmoL5Kz4ZYugbTLuEh63sbeo%3D",
18
  "container_name": "logs",
19
- "max_size_mb": 500 # 500MB file size limit
20
  }
21
 
22
  # YOLO Model Configuration
23
  MODEL_CONFIG = {
24
  "model_path": "./best_yolov11 (1).pt",
25
  "conf_threshold": 0.5,
26
- "frame_skip": 1 # Process every frame (0 = no skipping)
27
  }
28
 
29
  # Initialize YOLO Model
@@ -66,7 +66,6 @@ def download_video(blob_name):
66
  blob=blob_name
67
  )
68
 
69
- # Validate video size
70
  validate_video_size(blob)
71
 
72
  with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as f:
@@ -87,8 +86,9 @@ def process_video(input_path, progress=gr.Progress()):
87
  if not cap.isOpened():
88
  raise RuntimeError("Failed to open video file")
89
 
90
- # Get video properties
91
- frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
 
92
  fps = cap.get(cv2.CAP_PROP_FPS)
93
  width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
94
  height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
@@ -100,36 +100,27 @@ def process_video(input_path, progress=gr.Progress()):
100
  fps,
101
  (width, height))
102
 
103
- # Processing parameters
104
- frame_skip = MODEL_CONFIG["frame_skip"]
105
  processed_frames = 0
106
  total_processed = 0
107
 
108
- progress(0, desc="Initializing video processing...")
109
  start_time = time.time()
110
 
111
- while cap.isOpened():
112
  ret, frame = cap.read()
113
  if not ret:
114
  break
115
 
116
- # Frame skipping logic
117
- if total_processed % (frame_skip + 1) != 0:
118
- total_processed += 1
119
- continue
120
-
121
- # YOLO inference
122
  results = MODEL(frame, verbose=False)
123
  class_counts = {}
124
 
125
  for result in results:
126
  for box in result.boxes:
127
- # Convert tensor to Python scalar
128
  conf = box.conf.item()
129
  if conf < MODEL_CONFIG["conf_threshold"]:
130
  continue
131
 
132
- # Get detection coordinates
133
  x1, y1, x2, y2 = map(int, box.xyxy[0].tolist())
134
  class_id = int(box.cls.item())
135
  class_name = MODEL.names[class_id]
@@ -137,23 +128,20 @@ def process_video(input_path, progress=gr.Progress()):
137
  # Draw bounding box
138
  cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
139
 
140
- # Create label with proper float conversion
141
  label = f"{class_name} {conf:.2f}"
142
  cv2.putText(frame, label, (x1, y1 - 10),
143
  cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
144
-
145
- # Update counts
146
- class_counts[class_name] = class_counts.get(class_name, 0) + 1
147
 
148
  # Write frame to output
149
  writer.write(frame)
150
  processed_frames += 1
151
  total_processed += 1
152
 
153
- # Update progress
154
- if processed_frames % 10 == 0:
155
  progress(processed_frames / frame_count,
156
- desc=f"Processed {processed_frames}/{frame_count} frames")
157
 
158
  # Calculate statistics
159
  duration = time.time() - start_time
@@ -172,31 +160,30 @@ def process_video(input_path, progress=gr.Progress()):
172
 
173
  # Gradio Interface
174
  with gr.Blocks(theme=gr.themes.Soft(), title="PRISM Video Analyzer") as app:
175
- gr.Markdown("# πŸ—οΈ PRISM Site Diary - Construction Video Analysis")
176
 
177
  with gr.Row():
178
  with gr.Column(scale=1):
179
  gr.Markdown("## Video Selection")
180
  video_select = gr.Dropdown(
181
- label="Available Videos from Azure",
182
  choices=list_videos(),
183
- filterable=False,
184
- interactive=True
185
  )
186
  refresh_btn = gr.Button("πŸ”„ Refresh List", variant="secondary")
187
- process_btn = gr.Button("πŸš€ Process Selected Video", variant="primary")
188
 
189
  with gr.Column(scale=2):
190
- gr.Markdown("## Analysis Results")
191
  video_output = gr.Video(
192
- label="Processed Video Output",
193
  format="mp4",
194
  interactive=False
195
  )
196
  status = gr.Textbox(
197
- label="Processing Status",
198
- interactive=False,
199
- value="Ready to process videos"
200
  )
201
 
202
  def refresh_video_list():
@@ -209,7 +196,7 @@ with gr.Blocks(theme=gr.themes.Soft(), title="PRISM Video Analyzer") as app:
209
  try:
210
  local_path = download_video(blob_name)
211
  if not local_path:
212
- return None, "Video download failed"
213
 
214
  result, message = process_video(local_path)
215
  return result, message
@@ -218,15 +205,9 @@ with gr.Blocks(theme=gr.themes.Soft(), title="PRISM Video Analyzer") as app:
218
  logger.error(f"Processing error: {e}")
219
  return None, f"Error: {str(e)}"
220
 
221
- # Event handlers
222
- refresh_btn.click(
223
- fn=refresh_video_list,
224
- outputs=video_select,
225
- queue=False
226
- )
227
-
228
  process_btn.click(
229
- fn=handle_video_processing,
230
  inputs=video_select,
231
  outputs=[video_output, status],
232
  queue=True
 
16
  "account_name": "assentian",
17
  "sas_token": "sv=2024-11-04&ss=bfqt&srt=sco&sp=rwdlacupiytfx&se=2025-04-30T04:25:22Z&st=2025-04-16T20:25:22Z&spr=https&sig=HYrJBoOYc4PRe%2BoqBMl%2FmoL5Kz4ZYugbTLuEh63sbeo%3D",
18
  "container_name": "logs",
19
+ "max_size_mb": 500
20
  }
21
 
22
  # YOLO Model Configuration
23
  MODEL_CONFIG = {
24
  "model_path": "./best_yolov11 (1).pt",
25
  "conf_threshold": 0.5,
26
+ "frame_skip": 0 # Process every frame for testing
27
  }
28
 
29
  # Initialize YOLO Model
 
66
  blob=blob_name
67
  )
68
 
 
69
  validate_video_size(blob)
70
 
71
  with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as f:
 
86
  if not cap.isOpened():
87
  raise RuntimeError("Failed to open video file")
88
 
89
+ # Get video properties with 200 frame limit
90
+ original_frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
91
+ frame_count = min(original_frame_count, 200) # TESTING LIMIT
92
  fps = cap.get(cv2.CAP_PROP_FPS)
93
  width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
94
  height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
 
100
  fps,
101
  (width, height))
102
 
 
 
103
  processed_frames = 0
104
  total_processed = 0
105
 
106
+ progress(0, desc="Processing first 200 frames...")
107
  start_time = time.time()
108
 
109
+ while cap.isOpened() and total_processed < 200: # FRAME LIMIT
110
  ret, frame = cap.read()
111
  if not ret:
112
  break
113
 
114
+ # Process every frame (frame_skip = 0)
 
 
 
 
 
115
  results = MODEL(frame, verbose=False)
116
  class_counts = {}
117
 
118
  for result in results:
119
  for box in result.boxes:
 
120
  conf = box.conf.item()
121
  if conf < MODEL_CONFIG["conf_threshold"]:
122
  continue
123
 
 
124
  x1, y1, x2, y2 = map(int, box.xyxy[0].tolist())
125
  class_id = int(box.cls.item())
126
  class_name = MODEL.names[class_id]
 
128
  # Draw bounding box
129
  cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
130
 
131
+ # Create label
132
  label = f"{class_name} {conf:.2f}"
133
  cv2.putText(frame, label, (x1, y1 - 10),
134
  cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
 
 
 
135
 
136
  # Write frame to output
137
  writer.write(frame)
138
  processed_frames += 1
139
  total_processed += 1
140
 
141
+ # Update progress every frame
142
+ if processed_frames % 5 == 0:
143
  progress(processed_frames / frame_count,
144
+ desc=f"Processed {processed_frames}/200 frames")
145
 
146
  # Calculate statistics
147
  duration = time.time() - start_time
 
160
 
161
  # Gradio Interface
162
  with gr.Blocks(theme=gr.themes.Soft(), title="PRISM Video Analyzer") as app:
163
+ gr.Markdown("# πŸ—οΈ PRISM Site Diary - Video Analysis (TEST MODE: 200 Frames)")
164
 
165
  with gr.Row():
166
  with gr.Column(scale=1):
167
  gr.Markdown("## Video Selection")
168
  video_select = gr.Dropdown(
169
+ label="Available Videos",
170
  choices=list_videos(),
171
+ filterable=False
 
172
  )
173
  refresh_btn = gr.Button("πŸ”„ Refresh List", variant="secondary")
174
+ process_btn = gr.Button("πŸš€ Process First 200 Frames", variant="primary")
175
 
176
  with gr.Column(scale=2):
177
+ gr.Markdown("## Results")
178
  video_output = gr.Video(
179
+ label="Processed Video",
180
  format="mp4",
181
  interactive=False
182
  )
183
  status = gr.Textbox(
184
+ label="Status",
185
+ value="Ready to process first 200 frames",
186
+ interactive=False
187
  )
188
 
189
  def refresh_video_list():
 
196
  try:
197
  local_path = download_video(blob_name)
198
  if not local_path:
199
+ return None, "Download failed"
200
 
201
  result, message = process_video(local_path)
202
  return result, message
 
205
  logger.error(f"Processing error: {e}")
206
  return None, f"Error: {str(e)}"
207
 
208
+ refresh_btn.click(refresh_video_list, outputs=video_select)
 
 
 
 
 
 
209
  process_btn.click(
210
+ handle_video_processing,
211
  inputs=video_select,
212
  outputs=[video_output, status],
213
  queue=True