LiangLabUMB commited on
Commit
f3f8a59
·
verified ·
1 Parent(s): a9ef4e2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -35
app.py CHANGED
@@ -281,7 +281,48 @@ def run_segmentation_editor(editor_data, model_choice):
281
 
282
  except Exception as e:
283
  return 0, None, f"Error during segmentation: {str(e)}", gr.update(visible=False), None, None, 0.0
284
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
285
 
286
  def update_viability_realtime(blue_threshold, stored_masks, stored_image_np):
287
  # avoid unpacking None (e.g. slider moved before segmentation)
@@ -310,28 +351,30 @@ def update_viability_realtime(blue_threshold, stored_masks, stored_image_np):
310
  return None, 0, 0, 0.0, f"Error updating viability: {str(e)}"
311
 
312
 
313
- # PWA Head HTML - Updated for nested zip structure
314
- pwa_head = """
315
- <link rel="manifest" href="/file=static.zip/static/manifest.json">
316
- <meta name="apple-mobile-web-app-capable" content="yes">
317
- <meta name="apple-mobile-web-app-status-bar-style" content="default">
318
- <meta name="apple-mobile-web-app-title" content="Cellpose Cell Counter">
319
- <meta name="viewport" content="width=device-width, initial-scale=1">
320
- <link rel="apple-touch-icon" href="/file=favicon.png">
321
- <link rel="icon" type="image/png" sizes="192x192" href="/file=favicon.png">
322
- <script>
323
- if ('serviceWorker' in navigator) {
324
- window.addEventListener('load', function() {
325
- navigator.serviceWorker.register('/file=static.zip/static/service-worker.js')
326
- .then(function(registration) {
327
- console.log('ServiceWorker registration successful');
328
- }, function(err) {
329
- console.log('ServiceWorker registration failed: ', err);
330
- });
331
- });
332
- }
333
- </script>
334
- """
 
 
335
 
336
 
337
  def pack_array(arr):
@@ -364,19 +407,30 @@ with gr.Blocks(
364
  with gr.Row():
365
  with gr.Column():
366
  image_editor = gr.ImageEditor(
367
- label="Draw selection on image",
368
- type="pil",
369
- image_mode="RGB",
370
- height=512, # limit canvas size on client (important for mobile)
371
- brush=gr.Brush(colors=["#ff0000"], color_mode="fixed", default_size=20),
372
- eraser=gr.Eraser(default_size=20)
 
 
 
 
 
 
 
 
 
373
  )
374
- model_dropdown1 = gr.Dropdown(
375
- choices=list(MODEL_OPTIONS.keys()),
376
- label="Select Model",
377
- value="Hemocytometer Model"
 
378
  )
379
- segment_btn1 = gr.Button("🔬 Run Segmentation", variant="primary", size="lg")
 
380
 
381
  with gr.Column():
382
  cell_count_output1 = gr.Number(label="Total Cells Detected", precision=0)
@@ -455,4 +509,9 @@ with gr.Blocks(
455
  """)
456
 
457
  if __name__ == "__main__":
458
- demo.launch()
 
 
 
 
 
 
281
 
282
  except Exception as e:
283
  return 0, None, f"Error during segmentation: {str(e)}", gr.update(visible=False), None, None, 0.0
284
+
285
+ def run_segmentation_with_cleanup(func):
286
+ def wrapper(*args, **kwargs):
287
+ try:
288
+ return func(*args, **kwargs)
289
+ except Exception as e:
290
+ # Force garbage collection on error
291
+ import gc
292
+ gc.collect()
293
+ return 0, None, f"Error: {str(e)}", gr.update(visible=False), None, None, 0.0
294
+ return wrapper
295
+
296
+ run_segmentation_editor = run_segmentation_with_cleanup(run_segmentation_editor)
297
+
298
+ def validate_and_prepare_image(image_np, max_side=384, max_pixels=384*384):
299
+ """
300
+ Validate image and prepare for processing with strict size limits
301
+ Returns: (processed_image, error_message)
302
+ """
303
+ if image_np is None:
304
+ return None, "No image provided"
305
+
306
+ # Check if image is too small
307
+ h, w = image_np.shape[:2]
308
+ if h < 50 or w < 50:
309
+ return None, "Image too small (minimum 50x50 pixels)"
310
+
311
+ # Check file size before processing
312
+ if h * w > 4000 * 4000: # Reject images over 16 megapixels before resize
313
+ return None, "Image too large. Please resize to under 4000x4000 before uploading."
314
+
315
+ # Apply safe resize
316
+ resized = safe_resize(image_np)
317
+
318
+ # Ensure RGB format
319
+ if len(resized.shape) == 2:
320
+ resized = cv2.cvtColor(resized, cv2.COLOR_GRAY2RGB)
321
+ elif len(resized.shape) == 3 and resized.shape[2] == 4:
322
+ resized = cv2.cvtColor(resized, cv2.COLOR_RGBA2RGB)
323
+
324
+ return resized, None
325
+
326
 
327
  def update_viability_realtime(blue_threshold, stored_masks, stored_image_np):
328
  # avoid unpacking None (e.g. slider moved before segmentation)
 
351
  return None, 0, 0, 0.0, f"Error updating viability: {str(e)}"
352
 
353
 
354
+ def diagnose_image_upload(image):
355
+ """Helper function to diagnose upload issues"""
356
+ try:
357
+ if image is None:
358
+ return "No image received"
359
+
360
+ img_np = np.array(image)
361
+ h, w = img_np.shape[:2]
362
+ channels = img_np.shape[2] if len(img_np.shape) == 3 else 1
363
+ dtype = img_np.dtype
364
+ size_mb = img_np.nbytes / (1024 * 1024)
365
+
366
+ info = f"Image received successfully!\n"
367
+ info += f"Dimensions: {w}x{h}\n"
368
+ info += f"Channels: {channels}\n"
369
+ info += f"Data type: {dtype}\n"
370
+ info += f"Memory size: {size_mb:.2f} MB\n"
371
+
372
+ if size_mb > 10:
373
+ info += "\n⚠️ WARNING: Image is large and may cause issues on mobile"
374
+
375
+ return info
376
+ except Exception as e:
377
+ return f"Error analyzing image: {str(e)}"
378
 
379
 
380
  def pack_array(arr):
 
407
  with gr.Row():
408
  with gr.Column():
409
  image_editor = gr.ImageEditor(
410
+ label="Draw selection on image",
411
+ type="pil",
412
+ image_mode="RGB",
413
+ height=384, # Reduced from 512
414
+ width=384, # ADD explicit width
415
+ brush=gr.Brush(colors=["#ff0000"], color_mode="fixed", default_size=20),
416
+ eraser=gr.Eraser(default_size=20)
417
+ )
418
+
419
+ image_input = gr.Image(
420
+ type="pil",
421
+ label="Microscopy Image",
422
+ image_mode="RGB",
423
+ height=384, # Reduced from 512
424
+ width=384 # ADD explicit width
425
  )
426
+
427
+ model_dropdown1 = gr.Dropdown(
428
+ choices=list(MODEL_OPTIONS.keys()),
429
+ label="Select Model",
430
+ value="Hemocytometer Model"
431
  )
432
+
433
+ segment_btn1 = gr.Button("🔬 Run Segmentation", variant="primary", size="lg")
434
 
435
  with gr.Column():
436
  cell_count_output1 = gr.Number(label="Total Cells Detected", precision=0)
 
509
  """)
510
 
511
  if __name__ == "__main__":
512
+ demo.launch(
513
+ share=False,
514
+ show_error=True, # Show detailed errors
515
+ max_file_size="10mb", # Limit upload size
516
+ favicon_path="favicon.png"
517
+ )