MogensR commited on
Commit
fa50134
·
verified ·
1 Parent(s): 8bd1b94

Update streamlit_app.py

Browse files
Files changed (1) hide show
  1. streamlit_app.py +63 -34
streamlit_app.py CHANGED
@@ -85,20 +85,23 @@ def custom_excepthook(type, value, tb):
85
  # --- Session State Initialization ---
86
  def initialize_session_state():
87
  """Initialize all session state variables"""
88
- if 'uploaded_video' not in st.session_state:
89
- st.session_state.uploaded_video = None
90
- if 'bg_image' not in st.session_state:
91
- st.session_state.bg_image = None
92
- if 'bg_color' not in st.session_state:
93
- st.session_state.bg_color = "#00FF00"
94
- if 'processed_video_path' not in st.session_state:
95
- st.session_state.processed_video_path = None
96
- if 'processing' not in st.session_state:
97
- st.session_state.processing = False
98
- if 'progress' not in st.session_state:
99
- st.session_state.progress = 0
100
- if 'progress_text' not in st.session_state:
101
- st.session_state.progress_text = "Ready"
 
 
 
102
 
103
  # --- Video Upload Handling ---
104
  def handle_video_upload():
@@ -108,17 +111,21 @@ def handle_video_upload():
108
  type=["mp4", "mov", "avi"],
109
  key="video_uploader"
110
  )
111
- if uploaded is not None:
 
112
  st.session_state.uploaded_video = uploaded
 
113
 
114
  # --- Video Preview ---
115
  def show_video_preview():
116
  """Show video preview in the UI"""
117
  st.markdown("### Video Preview")
118
  if st.session_state.uploaded_video is not None:
119
- video_bytes = st.session_state.uploaded_video.getvalue()
120
- st.video(video_bytes)
121
- st.session_state.uploaded_video.seek(0)
 
 
122
 
123
  # --- Background Selection ---
124
  def handle_background_selection():
@@ -128,7 +135,8 @@ def handle_background_selection():
128
  "Select Background Type:",
129
  ["Image", "Color", "Blur"],
130
  horizontal=True,
131
- index=0
 
132
  )
133
 
134
  if bg_type == "Image":
@@ -137,10 +145,17 @@ def handle_background_selection():
137
  type=["jpg", "png", "jpeg"],
138
  key="bg_image_uploader"
139
  )
 
140
  if bg_image is not None:
141
- st.session_state.bg_image = Image.open(bg_image)
 
 
 
 
 
 
142
  st.image(
143
- st.session_state.bg_image,
144
  caption="Selected Background",
145
  use_container_width=True
146
  )
@@ -148,12 +163,19 @@ def handle_background_selection():
148
  elif bg_type == "Color":
149
  st.session_state.bg_color = st.color_picker(
150
  "🎨 Choose Background Color",
151
- st.session_state.bg_color
 
152
  )
153
- color_rgb = tuple(int(st.session_state.bg_color.lstrip('#')[i:i+2], 16) for i in (0, 2, 4))
154
- color_display = np.zeros((100, 100, 3), dtype=np.uint8)
155
- color_display[:, :] = color_rgb[::-1] # RGB to BGR for OpenCV
156
- st.image(color_display, caption="Selected Color", width=200)
 
 
 
 
 
 
157
 
158
  return bg_type.lower()
159
 
@@ -194,9 +216,11 @@ def process_video(input_file, background, bg_type="image"):
194
  logger.info(f"Background color image written to {bg_path}")
195
 
196
  logger.info(f"Disk free before processing: {os.popen('df -h / | tail -1').read().strip()}")
 
197
  # Set up progress placeholders
198
  progress_placeholder = st.empty()
199
  status_placeholder = st.empty()
 
200
  def progress_callback(progress, message):
201
  progress = max(0, min(1, float(progress)))
202
  progress_placeholder.progress(progress)
@@ -268,30 +292,34 @@ def main():
268
  with col2:
269
  st.header("2. Background Settings")
270
  bg_type = handle_background_selection()
 
271
  st.header("3. Process & Download")
272
- # ------- FORM WRAP START --------
273
  with st.form("process_form"):
274
  submitted = st.form_submit_button(
275
  "🚀 Process Video",
276
  disabled=not st.session_state.uploaded_video or st.session_state.processing
277
  )
278
  process_status = st.empty()
 
279
  if submitted and not st.session_state.processing:
280
  st.session_state.processing = True
281
  with st.spinner("Processing video (this may take a few minutes)..."):
282
  try:
283
  # Prepare background based on type
284
  background = None
285
- if bg_type == "image" and 'bg_image' in st.session_state and st.session_state.bg_image is not None:
286
- background = st.session_state.bg_image
287
  elif bg_type == "color" and 'bg_color' in st.session_state:
288
  background = st.session_state.bg_color
 
289
  # Process the video
290
  output_path = process_video(
291
  st.session_state.uploaded_video,
292
  background,
293
  bg_type=bg_type
294
  )
 
295
  if output_path and os.path.exists(output_path):
296
  st.session_state.processed_video_path = output_path
297
  process_status.success("✅ Video processing complete!")
@@ -302,9 +330,9 @@ def main():
302
  logger.exception("Video processing failed")
303
  finally:
304
  st.session_state.processing = False
305
- # ------- FORM WRAP END --------
306
- # Show processed video if available (outside form, stable)
307
- if 'processed_video_path' in st.session_state and st.session_state.processed_video_path:
308
  st.markdown("### Processed Video")
309
  try:
310
  with open(st.session_state.processed_video_path, 'rb') as f:
@@ -315,7 +343,8 @@ def main():
315
  data=video_bytes,
316
  file_name="processed_video.mp4",
317
  mime="video/mp4",
318
- use_container_width=True
 
319
  )
320
  except Exception as e:
321
  st.error(f"Error displaying video: {str(e)}")
@@ -323,4 +352,4 @@ def main():
323
 
324
  # --- Entry Point ---
325
  if __name__ == "__main__":
326
- main()
 
85
  # --- Session State Initialization ---
86
  def initialize_session_state():
87
  """Initialize all session state variables"""
88
+ defaults = {
89
+ 'uploaded_video': None,
90
+ 'video_bytes_cache': None,
91
+ 'bg_image': None,
92
+ 'bg_image_cache': None,
93
+ 'bg_image_name': None,
94
+ 'bg_color': "#00FF00",
95
+ 'cached_color': None,
96
+ 'color_display_cache': None,
97
+ 'processed_video_path': None,
98
+ 'processing': False,
99
+ 'progress': 0,
100
+ 'progress_text': "Ready"
101
+ }
102
+ for key, value in defaults.items():
103
+ if key not in st.session_state:
104
+ st.session_state[key] = value
105
 
106
  # --- Video Upload Handling ---
107
  def handle_video_upload():
 
111
  type=["mp4", "mov", "avi"],
112
  key="video_uploader"
113
  )
114
+ # Only update if actually changed
115
+ if uploaded is not None and uploaded != st.session_state.uploaded_video:
116
  st.session_state.uploaded_video = uploaded
117
+ st.session_state.video_bytes_cache = None # Clear cache when new video uploaded
118
 
119
  # --- Video Preview ---
120
  def show_video_preview():
121
  """Show video preview in the UI"""
122
  st.markdown("### Video Preview")
123
  if st.session_state.uploaded_video is not None:
124
+ # Cache video bytes in session state to prevent reloading
125
+ if st.session_state.video_bytes_cache is None:
126
+ st.session_state.video_bytes_cache = st.session_state.uploaded_video.getvalue()
127
+ st.session_state.uploaded_video.seek(0)
128
+ st.video(st.session_state.video_bytes_cache)
129
 
130
  # --- Background Selection ---
131
  def handle_background_selection():
 
135
  "Select Background Type:",
136
  ["Image", "Color", "Blur"],
137
  horizontal=True,
138
+ index=0,
139
+ key="bg_type_radio"
140
  )
141
 
142
  if bg_type == "Image":
 
145
  type=["jpg", "png", "jpeg"],
146
  key="bg_image_uploader"
147
  )
148
+ # Only process if new image uploaded
149
  if bg_image is not None:
150
+ if (st.session_state.bg_image_cache is None or
151
+ st.session_state.get('bg_image_name') != bg_image.name):
152
+ st.session_state.bg_image = Image.open(bg_image)
153
+ st.session_state.bg_image_cache = st.session_state.bg_image
154
+ st.session_state.bg_image_name = bg_image.name
155
+
156
+ # Display cached image
157
  st.image(
158
+ st.session_state.bg_image_cache,
159
  caption="Selected Background",
160
  use_container_width=True
161
  )
 
163
  elif bg_type == "Color":
164
  st.session_state.bg_color = st.color_picker(
165
  "🎨 Choose Background Color",
166
+ st.session_state.bg_color,
167
+ key="color_picker"
168
  )
169
+ # Cache color display to prevent regeneration
170
+ if (st.session_state.color_display_cache is None or
171
+ st.session_state.get('cached_color') != st.session_state.bg_color):
172
+ color_rgb = tuple(int(st.session_state.bg_color.lstrip('#')[i:i+2], 16) for i in (0, 2, 4))
173
+ color_display = np.zeros((100, 100, 3), dtype=np.uint8)
174
+ color_display[:, :] = color_rgb[::-1] # RGB to BGR for OpenCV
175
+ st.session_state.color_display_cache = color_display
176
+ st.session_state.cached_color = st.session_state.bg_color
177
+
178
+ st.image(st.session_state.color_display_cache, caption="Selected Color", width=200)
179
 
180
  return bg_type.lower()
181
 
 
216
  logger.info(f"Background color image written to {bg_path}")
217
 
218
  logger.info(f"Disk free before processing: {os.popen('df -h / | tail -1').read().strip()}")
219
+
220
  # Set up progress placeholders
221
  progress_placeholder = st.empty()
222
  status_placeholder = st.empty()
223
+
224
  def progress_callback(progress, message):
225
  progress = max(0, min(1, float(progress)))
226
  progress_placeholder.progress(progress)
 
292
  with col2:
293
  st.header("2. Background Settings")
294
  bg_type = handle_background_selection()
295
+
296
  st.header("3. Process & Download")
297
+ # Form wrap to prevent reruns during processing
298
  with st.form("process_form"):
299
  submitted = st.form_submit_button(
300
  "🚀 Process Video",
301
  disabled=not st.session_state.uploaded_video or st.session_state.processing
302
  )
303
  process_status = st.empty()
304
+
305
  if submitted and not st.session_state.processing:
306
  st.session_state.processing = True
307
  with st.spinner("Processing video (this may take a few minutes)..."):
308
  try:
309
  # Prepare background based on type
310
  background = None
311
+ if bg_type == "image" and st.session_state.bg_image_cache is not None:
312
+ background = st.session_state.bg_image_cache
313
  elif bg_type == "color" and 'bg_color' in st.session_state:
314
  background = st.session_state.bg_color
315
+
316
  # Process the video
317
  output_path = process_video(
318
  st.session_state.uploaded_video,
319
  background,
320
  bg_type=bg_type
321
  )
322
+
323
  if output_path and os.path.exists(output_path):
324
  st.session_state.processed_video_path = output_path
325
  process_status.success("✅ Video processing complete!")
 
330
  logger.exception("Video processing failed")
331
  finally:
332
  st.session_state.processing = False
333
+
334
+ # Show processed video if available (outside form for stability)
335
+ if st.session_state.processed_video_path:
336
  st.markdown("### Processed Video")
337
  try:
338
  with open(st.session_state.processed_video_path, 'rb') as f:
 
343
  data=video_bytes,
344
  file_name="processed_video.mp4",
345
  mime="video/mp4",
346
+ use_container_width=True,
347
+ key="download_button"
348
  )
349
  except Exception as e:
350
  st.error(f"Error displaying video: {str(e)}")
 
352
 
353
  # --- Entry Point ---
354
  if __name__ == "__main__":
355
+ main()