tstone87 commited on
Commit
86b94b7
·
verified ·
1 Parent(s): 10190b4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -92
app.py CHANGED
@@ -73,7 +73,7 @@ st.markdown("---")
73
  # Tabs
74
  tabs = st.tabs(["Upload", "Webcam"])
75
 
76
- # Tab 1: Upload (Output only analyzed frames)
77
  with tabs[0]:
78
  col1, col2 = st.columns(2)
79
  with col1:
@@ -95,12 +95,11 @@ with tabs[0]:
95
  with col2:
96
  frame_placeholder = st.empty()
97
  status_placeholder = st.empty()
98
- progress_placeholder = st.empty()
99
  download_placeholder = st.empty()
100
 
101
- if source_file:
102
- st.write(f"File size: {source_file.size / 1024 / 1024:.2f} MB")
103
- if st.button("Detect Wildfire", key="upload_detect"):
104
  file_type = source_file.type.split('/')[0]
105
  if file_type == 'image':
106
  uploaded_image = PIL.Image.open(source_file)
@@ -109,94 +108,64 @@ with tabs[0]:
109
  frame_placeholder.image(detected_image, use_column_width=True)
110
  status_placeholder.write(f"Objects detected: {len(res[0].boxes)}")
111
  elif file_type == 'video':
112
- try:
113
- # Save input video
114
- input_tfile = tempfile.NamedTemporaryFile(delete=False, suffix='.mp4')
115
- input_tfile.write(source_file.read())
116
- input_tfile.close()
117
-
118
- # Open video
119
- vidcap = cv2.VideoCapture(input_tfile.name)
120
- if not vidcap.isOpened():
121
- status_placeholder.error("Failed to open video file.")
122
- else:
123
- total_frames = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
124
- fps = int(vidcap.get(cv2.CAP_PROP_FPS)) or 30
125
- frame_width = int(vidcap.get(cv2.CAP_PROP_FRAME_WIDTH))
126
- frame_height = int(vidcap.get(cv2.CAP_PROP_FRAME_HEIGHT))
127
-
128
- # Calculate frame skip
129
- target_rate = sampling_options[sampling_rate]
130
- if target_rate == 0:
131
- frame_skip = 1
132
- elif target_rate <= 5:
133
- frame_skip = max(1, int(fps / target_rate))
134
- else:
135
- frame_skip = max(1, int(fps * target_rate))
136
-
137
- # Batch processing setup
138
- batch_size = 10
139
- frames_to_process = []
140
- frame_indices = []
141
-
142
- # Output video (only analyzed frames)
143
- output_tfile = tempfile.NamedTemporaryFile(delete=False, suffix='_detected.mp4')
144
- fourcc = cv2.VideoWriter_fourcc(*'mp4v')
145
- # Use 1 FPS for output to make it viewable, adjust as needed
146
- output_fps = 1
147
- out = cv2.VideoWriter(output_tfile.name, fourcc, output_fps, (frame_width, frame_height))
148
-
 
 
 
149
  success, frame = vidcap.read()
150
- frame_count = 0
151
- processed_count = 0
152
- last_ui_update = time.time()
153
-
154
- while success:
155
- if frame_count % frame_skip == 0:
156
- frames_to_process.append(frame)
157
- frame_indices.append(frame_count)
158
- processed_count += 1
159
-
160
- # Process batch when full or at end
161
- if len(frames_to_process) >= batch_size or (not success and frames_to_process):
162
- res = model.predict(frames_to_process, conf=confidence)
163
- for i, (result, idx) in enumerate(zip(res, frame_indices)):
164
- detected_frame = result.plot()[:, :, ::-1]
165
- # Update UI sparingly
166
- if time.time() - last_ui_update >= 1.0:
167
- frame_placeholder.image(detected_frame, use_column_width=True)
168
- status_placeholder.write(f"Frame {idx}: Objects detected: {len(result.boxes)}")
169
- last_ui_update = time.time()
170
- # Write only analyzed frames
171
- out.write(detected_frame[:, :, ::-1])
172
-
173
- # Progress
174
- if total_frames > 0:
175
- progress_percent = (frame_count + 1) / total_frames * 100
176
- progress_placeholder.write(f"Progress: {progress_percent:.1f}% (Analyzed {processed_count} frames)")
177
- else:
178
- progress_placeholder.write(f"Progress: {frame_count} frames processed")
179
-
180
- success, frame = vidcap.read()
181
- frame_count += 1
182
- if len(frames_to_process) >= batch_size:
183
- frames_to_process = []
184
- frame_indices = []
185
-
186
- vidcap.release()
187
- out.release()
188
-
189
- os.unlink(input_tfile.name)
190
- with open(output_tfile.name, 'rb') as f:
191
- download_placeholder.download_button(
192
- label="Download Analyzed Video",
193
- data=f,
194
- file_name="analyzed_video.mp4",
195
- mime="video/mp4"
196
- )
197
- status_placeholder.write(f"Video processing complete. Analyzed {processed_count} frames.")
198
- except Exception as e:
199
- status_placeholder.error(f"Error processing video: {str(e)}")
200
 
201
  # Tab 2: Webcam (Unchanged)
202
  with tabs[1]:
 
73
  # Tabs
74
  tabs = st.tabs(["Upload", "Webcam"])
75
 
76
+ # Tab 1: Upload (Simplified to match original, with new features)
77
  with tabs[0]:
78
  col1, col2 = st.columns(2)
79
  with col1:
 
95
  with col2:
96
  frame_placeholder = st.empty()
97
  status_placeholder = st.empty()
 
98
  download_placeholder = st.empty()
99
 
100
+ if source_file and st.button("Detect Wildfire", key="upload_detect"):
101
+ try:
102
+ st.write(f"File size: {source_file.size / 1024 / 1024:.2f} MB") # Diagnostic
103
  file_type = source_file.type.split('/')[0]
104
  if file_type == 'image':
105
  uploaded_image = PIL.Image.open(source_file)
 
108
  frame_placeholder.image(detected_image, use_column_width=True)
109
  status_placeholder.write(f"Objects detected: {len(res[0].boxes)}")
110
  elif file_type == 'video':
111
+ # Save input video
112
+ tfile = tempfile.NamedTemporaryFile(delete=False, suffix='.mp4')
113
+ tfile.write(source_file.read())
114
+ tfile.close()
115
+
116
+ # Open video
117
+ vidcap = cv2.VideoCapture(tfile.name)
118
+ if not vidcap.isOpened():
119
+ status_placeholder.error("Failed to open video file.")
120
+ else:
121
+ total_frames = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
122
+ fps = int(vidcap.get(cv2.CAP_PROP_FPS)) or 30
123
+ frame_width = int(vidcap.get(cv2.CAP_PROP_FRAME_WIDTH))
124
+ frame_height = int(vidcap.get(cv2.CAP_PROP_FRAME_HEIGHT))
125
+
126
+ # Frame sampling
127
+ target_rate = sampling_options[sampling_rate]
128
+ frame_skip = 1 if target_rate == 0 else max(1, int(fps / target_rate) if target_rate <= 5 else int(fps * target_rate))
129
+
130
+ # Output video (only analyzed frames)
131
+ output_tfile = tempfile.NamedTemporaryFile(delete=False, suffix='_detected.mp4')
132
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
133
+ output_fps = 1 # Fixed for short compilation
134
+ out = cv2.VideoWriter(output_tfile.name, fourcc, output_fps, (frame_width, frame_height))
135
+
136
+ success, frame = vidcap.read()
137
+ frame_count = 0
138
+ processed_count = 0
139
+
140
+ while success:
141
+ if frame_count % frame_skip == 0:
142
+ res = model.predict(frame, conf=confidence)
143
+ detected_frame = res[0].plot()[:, :, ::-1]
144
+ frame_placeholder.image(detected_frame, use_column_width=True)
145
+ status_placeholder.write(f"Frame {frame_count}: Objects detected: {len(res[0].boxes)}")
146
+ out.write(detected_frame[:, :, ::-1])
147
+ processed_count += 1
148
+ if total_frames > 0:
149
+ progress = (frame_count + 1) / total_frames * 100
150
+ st.write(f"Progress: {progress:.1f}% (Analyzed {processed_count} frames)")
151
  success, frame = vidcap.read()
152
+ frame_count += 1
153
+ time.sleep(0.05)
154
+
155
+ vidcap.release()
156
+ out.release()
157
+
158
+ os.unlink(tfile.name)
159
+ with open(output_tfile.name, 'rb') as f:
160
+ download_placeholder.download_button(
161
+ label="Download Analyzed Video",
162
+ data=f,
163
+ file_name="analyzed_video.mp4",
164
+ mime="video/mp4"
165
+ )
166
+ status_placeholder.write(f"Video processing complete. Analyzed {processed_count} frames.")
167
+ except Exception as e:
168
+ status_placeholder.error(f"Error: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
 
170
  # Tab 2: Webcam (Unchanged)
171
  with tabs[1]: