osherr commited on
Commit
7fe897d
Β·
verified Β·
1 Parent(s): 862a0c0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -43
app.py CHANGED
@@ -4,11 +4,11 @@ import numpy as np
4
  from PIL import Image
5
  import os
6
 
7
- # === Fix font/matplotlib warnings for Hugging Face ===
8
  os.environ["MPLCONFIGDIR"] = "/tmp/matplotlib"
9
  os.environ["XDG_CACHE_HOME"] = "/tmp"
10
 
11
- # === Custom loss and metrics ===
12
  def weighted_dice_loss(y_true, y_pred):
13
  smooth = 1e-6
14
  y_true_f = tf.reshape(y_true, [-1])
@@ -27,12 +27,11 @@ def iou_metric(y_true, y_pred):
27
  def bce_loss(y_true, y_pred):
28
  return tf.keras.losses.binary_crossentropy(y_true, y_pred)
29
 
30
- # === Load model ===
31
- model_path = "final_model_after_third_iteration_WDL0.07_0.5155/"
32
  @st.cache_resource
33
  def load_model():
34
  return tf.keras.models.load_model(
35
- model_path,
36
  custom_objects={
37
  "weighted_dice_loss": weighted_dice_loss,
38
  "iou_metric": iou_metric,
@@ -42,57 +41,52 @@ def load_model():
42
 
43
  model = load_model()
44
 
45
- # === Title ===
46
  st.title("πŸ•³οΈ Sinkhole Segmentation with EffV2-UNet")
47
 
48
- # === Confidence threshold and predict trigger ===
49
- st.sidebar.header("Segmentation Settings")
50
- threshold = st.sidebar.slider("Confidence Threshold", 0.0, 1.0, 0.5, step=0.01)
51
 
52
- # === Image input section ===
53
- uploaded_image = st.file_uploader("πŸ“€ Upload an image", type=["png", "jpg", "jpeg", "tif", "tiff"])
54
-
55
- # === Example selector with preview ===
56
  example_dir = "examples"
57
  example_files = sorted([
58
  f for f in os.listdir(example_dir)
59
  if f.lower().endswith((".jpg", ".jpeg", ".png", ".tif", ".tiff"))
60
  ])
61
 
62
- selected_example_path = None
 
63
 
64
  if example_files:
65
- st.subheader("πŸ–ΌοΈ Try with an Example Image")
66
- cols = st.columns(min(len(example_files), 4))
67
- for i, file in enumerate(example_files):
68
- img_path = os.path.join(example_dir, file)
69
- img_preview = Image.open(img_path).convert("RGB").resize((128, 128))
70
- with cols[i % len(cols)]:
71
- st.image(img_preview, caption=file, use_column_width=True)
72
- if st.button(f"Use {file}", key=file):
73
- selected_example_path = img_path
74
-
75
- # === Set image to process ===
76
- if selected_example_path:
77
- uploaded_image = selected_example_path
78
-
79
- # === Run prediction if button clicked ===
80
- if uploaded_image:
81
- if isinstance(uploaded_image, str):
82
- image = Image.open(uploaded_image).convert("RGB")
83
- else:
84
- image = Image.open(uploaded_image).convert("RGB")
85
-
86
- st.image(image, caption="Input Image", use_column_width=True)
87
-
88
- if st.button("Run Segmentation"):
89
- resized = image.resize((512, 512))
90
  x = np.expand_dims(np.array(resized), axis=0)
91
  y = model.predict(x)[0, :, :, 0]
92
 
93
  st.text(f"Prediction min/max: {y.min():.5f} / {y.max():.5f}")
94
 
95
- mask_bin = (y > threshold).astype(np.uint8) * 255
96
- mask_image = Image.fromarray(mask_bin)
97
-
98
- st.image(mask_image, caption=f"Segmentation Mask (Threshold = {threshold:.2f})", use_column_width=True)
 
4
  from PIL import Image
5
  import os
6
 
7
+ # Fix font/matplotlib warnings for Hugging Face
8
  os.environ["MPLCONFIGDIR"] = "/tmp/matplotlib"
9
  os.environ["XDG_CACHE_HOME"] = "/tmp"
10
 
11
+ # Custom loss and metrics
12
  def weighted_dice_loss(y_true, y_pred):
13
  smooth = 1e-6
14
  y_true_f = tf.reshape(y_true, [-1])
 
27
  def bce_loss(y_true, y_pred):
28
  return tf.keras.losses.binary_crossentropy(y_true, y_pred)
29
 
30
+ # Load model
 
31
  @st.cache_resource
32
  def load_model():
33
  return tf.keras.models.load_model(
34
+ "final_model_after_third_iteration_WDL0.07_0.5155/",
35
  custom_objects={
36
  "weighted_dice_loss": weighted_dice_loss,
37
  "iou_metric": iou_metric,
 
41
 
42
  model = load_model()
43
 
44
+ # App title
45
  st.title("πŸ•³οΈ Sinkhole Segmentation with EffV2-UNet")
46
 
47
+ # Sidebar: Upload or select image
48
+ st.sidebar.header("πŸ“ Image Input")
49
+ uploaded_file = st.sidebar.file_uploader("Upload your image", type=["jpg", "jpeg", "png", "tif", "tiff"])
50
 
 
 
 
 
51
  example_dir = "examples"
52
  example_files = sorted([
53
  f for f in os.listdir(example_dir)
54
  if f.lower().endswith((".jpg", ".jpeg", ".png", ".tif", ".tiff"))
55
  ])
56
 
57
+ if "selected_example" not in st.session_state:
58
+ st.session_state.selected_example = None
59
 
60
  if example_files:
61
+ st.sidebar.markdown("Or select from examples:")
62
+ for file in example_files:
63
+ path = os.path.join(example_dir, file)
64
+ image = Image.open(path)
65
+ st.sidebar.image(image, caption=file, width=120)
66
+ if st.sidebar.button(f"Use {file}"):
67
+ st.session_state.selected_example = path
68
+ uploaded_file = None # clear uploaded file
69
+
70
+ # Load image for display and processing
71
+ input_image = None
72
+ if uploaded_file is not None:
73
+ input_image = Image.open(uploaded_file).convert("RGB")
74
+ elif st.session_state.selected_example is not None:
75
+ input_image = Image.open(st.session_state.selected_example).convert("RGB")
76
+
77
+ if input_image:
78
+ st.image(input_image, caption="Input Image", use_column_width=True)
79
+
80
+ threshold = st.slider("Confidence Threshold", 0.0, 1.0, 0.5, step=0.01)
81
+
82
+ if st.button("πŸ” Run Segmentation"):
83
+ resized = input_image.resize((512, 512))
 
 
84
  x = np.expand_dims(np.array(resized), axis=0)
85
  y = model.predict(x)[0, :, :, 0]
86
 
87
  st.text(f"Prediction min/max: {y.min():.5f} / {y.max():.5f}")
88
 
89
+ # Threshold and visualize
90
+ mask = (y > threshold).astype(np.uint8) * 255
91
+ mask_image = Image.fromarray(mask)
92
+ st.image(mask_image, caption=f"Segmentation (Threshold = {threshold:.2f})", use_column_width=True)