kerzel commited on
Commit
9873374
·
1 Parent(s): f605f45

try a version from gemini

Browse files
Files changed (1) hide show
  1. app.py +78 -33
app.py CHANGED
@@ -2,33 +2,47 @@ import gradio as gr
2
  import numpy as np
3
  import pandas as pd
4
  from PIL import Image
 
5
 
6
- # Your helper imports and tensorflow models assumed to be loaded here:
 
7
  import clustering
8
  import utils
9
  from tensorflow import keras
10
- import logging
 
11
  logging.getLogger().setLevel(logging.INFO)
12
 
13
- # Paths to save outputs
14
  IMAGE_PATH = "classified_damage_sites.png"
15
  CSV_PATH = "classified_damage_sites.csv"
16
 
17
- # Load models once (adjust filenames as needed)
18
- model1 = keras.models.load_model('rwthmaterials_dp800_network1_inclusion.h5')
19
- model2 = keras.models.load_model('rwthmaterials_dp800_network2_damage.h5')
 
 
 
 
 
 
20
 
21
  damage_classes = {3: "Martensite", 2: "Interface", 0: "Notch", 1: "Shadowing"}
22
  model1_windowsize = [250, 250]
23
  model2_windowsize = [100, 100]
24
 
 
 
25
  def damage_classification(SEM_image, image_threshold, model1_threshold, model2_threshold):
 
 
 
 
26
  if SEM_image is None:
27
- logging.error("No image provided")
28
- return None, None, None
29
 
30
  damage_sites = {}
31
-
32
  # Step 1: Clustering to find damage centroids
33
  all_centroids = clustering.get_centroids(
34
  SEM_image,
@@ -36,18 +50,17 @@ def damage_classification(SEM_image, image_threshold, model1_threshold, model2_t
36
  fill_holes=True,
37
  filter_close_centroids=True,
38
  )
39
-
40
  for c in all_centroids:
41
  damage_sites[(c[0], c[1])] = "Not Classified"
42
 
43
  # Step 2: Model 1 to identify inclusions
44
- images_model1 = utils.prepare_classifier_input(SEM_image, all_centroids, window_size=model1_windowsize)
45
- y1_pred = model1.predict(np.asarray(images_model1, dtype=float))
46
- inclusions = np.where(y1_pred[:, 0] > model1_threshold)[0]
47
-
48
- for idx in inclusions:
49
- coord = all_centroids[idx]
50
- damage_sites[(coord[0], coord[1])] = "Inclusion"
51
 
52
  # Step 3: Model 2 to classify remaining damage types
53
  centroids_model2 = [list(k) for k, v in damage_sites.items() if v == "Not Classified"]
@@ -55,7 +68,6 @@ def damage_classification(SEM_image, image_threshold, model1_threshold, model2_t
55
  images_model2 = utils.prepare_classifier_input(SEM_image, centroids_model2, window_size=model2_windowsize)
56
  y2_pred = model2.predict(np.asarray(images_model2, dtype=float))
57
  damage_index = np.asarray(y2_pred > model2_threshold).nonzero()
58
-
59
  for i in range(len(damage_index[0])):
60
  sample_idx = damage_index[0][i]
61
  class_idx = damage_index[1][i]
@@ -64,6 +76,7 @@ def damage_classification(SEM_image, image_threshold, model1_threshold, model2_t
64
  damage_sites[(coord[0], coord[1])] = label
65
 
66
  # Step 4: Draw boxes on image and save output image
 
67
  image_with_boxes = utils.show_boxes(SEM_image, damage_sites, save_image=True, image_path=IMAGE_PATH)
68
 
69
  # Step 5: Export CSV file
@@ -74,24 +87,56 @@ def damage_classification(SEM_image, image_threshold, model1_threshold, model2_t
74
  return image_with_boxes, IMAGE_PATH, CSV_PATH
75
 
76
 
 
77
  with gr.Blocks() as app:
78
  gr.Markdown("# Damage Classification in Dual Phase Steels")
79
-
80
- image_input = gr.Image(label="Upload SEM Image")
81
- cluster_threshold_input = gr.Number(value=20, label="Cluster Threshold")
82
- model1_threshold_input = gr.Number(value=0.7, label="Model 1 Threshold")
83
- model2_threshold_input = gr.Number(value=0.5, label="Model 2 Threshold")
84
-
85
- output_image = gr.Image(label="Classified Image")
86
- download_image_btn = gr.DownloadButton(label="Download Image")
87
- download_csv_btn = gr.DownloadButton(label="Download CSV")
88
-
89
- classify_btn = gr.Button("Run Classification")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  classify_btn.click(
91
- damage_classification,
92
- inputs=[image_input, cluster_threshold_input, model1_threshold_input, model2_threshold_input],
93
- outputs=[output_image, download_image_btn, download_csv_btn],
 
 
 
 
 
 
 
 
 
94
  )
95
 
96
  if __name__ == "__main__":
97
- app.launch()
 
2
  import numpy as np
3
  import pandas as pd
4
  from PIL import Image
5
+ import logging
6
 
7
+ # Your helper imports and tensorflow models are assumed to be in the same directory.
8
+ # Ensure 'clustering.py' and 'utils.py' are present in your HuggingFace Space.
9
  import clustering
10
  import utils
11
  from tensorflow import keras
12
+
13
+ # --- Basic Setup ---
14
  logging.getLogger().setLevel(logging.INFO)
15
 
16
+ # --- Constants and Model Loading ---
17
  IMAGE_PATH = "classified_damage_sites.png"
18
  CSV_PATH = "classified_damage_sites.csv"
19
 
20
+ # Load models once at startup to improve performance
21
+ try:
22
+ model1 = keras.models.load_model('rwthmaterials_dp800_network1_inclusion.h5')
23
+ model2 = keras.models.load_model('rwthmaterials_dp800_network2_damage.h5')
24
+ except Exception as e:
25
+ logging.error(f"Error loading models: {e}")
26
+ # If models can't load, you might want to stop the app from launching
27
+ # or display an error message in the UI.
28
+ raise
29
 
30
  damage_classes = {3: "Martensite", 2: "Interface", 0: "Notch", 1: "Shadowing"}
31
  model1_windowsize = [250, 250]
32
  model2_windowsize = [100, 100]
33
 
34
+
35
+ # --- Core Processing Function (Your original logic) ---
36
  def damage_classification(SEM_image, image_threshold, model1_threshold, model2_threshold):
37
+ """
38
+ This function contains the core scientific logic for classifying damage sites.
39
+ It returns the classified image and paths to the output files.
40
+ """
41
  if SEM_image is None:
42
+ # This error will be displayed nicely in the Gradio interface
43
+ raise gr.Error("Please upload an SEM Image before running classification.")
44
 
45
  damage_sites = {}
 
46
  # Step 1: Clustering to find damage centroids
47
  all_centroids = clustering.get_centroids(
48
  SEM_image,
 
50
  fill_holes=True,
51
  filter_close_centroids=True,
52
  )
 
53
  for c in all_centroids:
54
  damage_sites[(c[0], c[1])] = "Not Classified"
55
 
56
  # Step 2: Model 1 to identify inclusions
57
+ if len(all_centroids) > 0:
58
+ images_model1 = utils.prepare_classifier_input(SEM_image, all_centroids, window_size=model1_windowsize)
59
+ y1_pred = model1.predict(np.asarray(images_model1, dtype=float))
60
+ inclusions = np.where(y1_pred[:, 0] > model1_threshold)[0]
61
+ for idx in inclusions:
62
+ coord = all_centroids[idx]
63
+ damage_sites[(coord[0], coord[1])] = "Inclusion"
64
 
65
  # Step 3: Model 2 to classify remaining damage types
66
  centroids_model2 = [list(k) for k, v in damage_sites.items() if v == "Not Classified"]
 
68
  images_model2 = utils.prepare_classifier_input(SEM_image, centroids_model2, window_size=model2_windowsize)
69
  y2_pred = model2.predict(np.asarray(images_model2, dtype=float))
70
  damage_index = np.asarray(y2_pred > model2_threshold).nonzero()
 
71
  for i in range(len(damage_index[0])):
72
  sample_idx = damage_index[0][i]
73
  class_idx = damage_index[1][i]
 
76
  damage_sites[(coord[0], coord[1])] = label
77
 
78
  # Step 4: Draw boxes on image and save output image
79
+ # The utils.show_boxes function is assumed to return a PIL Image object
80
  image_with_boxes = utils.show_boxes(SEM_image, damage_sites, save_image=True, image_path=IMAGE_PATH)
81
 
82
  # Step 5: Export CSV file
 
87
  return image_with_boxes, IMAGE_PATH, CSV_PATH
88
 
89
 
90
+ # --- Gradio Interface Definition ---
91
  with gr.Blocks() as app:
92
  gr.Markdown("# Damage Classification in Dual Phase Steels")
93
+ gr.Markdown("Upload a Scanning Electron Microscope (SEM) image and set the thresholds to classify material damage.")
94
+
95
+ with gr.Row():
96
+ with gr.Column(scale=1):
97
+ image_input = gr.Image(type="pil", label="Upload SEM Image")
98
+ cluster_threshold_input = gr.Number(value=20, label="Image Binarization Threshold")
99
+ model1_threshold_input = gr.Number(value=0.7, label="Inclusion Model Certainty (0-1)")
100
+ model2_threshold_input = gr.Number(value=0.5, label="Damage Model Certainty (0-1)")
101
+ classify_btn = gr.Button("Run Classification", variant="primary")
102
+
103
+ with gr.Column(scale=2):
104
+ output_image = gr.Image(label="Classified Image")
105
+ # Initialize DownloadButtons as hidden. They will become visible after a successful run.
106
+ download_image_btn = gr.DownloadButton(label="Download Image", visible=False)
107
+ download_csv_btn = gr.DownloadButton(label="Download CSV", visible=False)
108
+
109
+ # This wrapper function handles the UI updates, which is the robust way to use Gradio.
110
+ def run_classification_and_update_ui(sem_image, cluster_thresh, m1_thresh, m2_thresh):
111
+ """
112
+ Calls the core logic and then returns updates for the Gradio UI components.
113
+ """
114
+ # Call the main processing function
115
+ classified_img, img_path, csv_path = damage_classification(sem_image, cluster_thresh, m1_thresh, m2_thresh)
116
+
117
+ # Return the results in the correct order to update the output components.
118
+ # Use gr.update to change properties of a component, like visibility.
119
+ return (
120
+ classified_img,
121
+ gr.update(value=img_path, visible=True),
122
+ gr.update(value=csv_path, visible=True)
123
+ )
124
+
125
+ # Connect the button's click event to the wrapper function
126
  classify_btn.click(
127
+ fn=run_classification_and_update_ui,
128
+ inputs=[
129
+ image_input,
130
+ cluster_threshold_input,
131
+ model1_threshold_input,
132
+ model2_threshold_input
133
+ ],
134
+ outputs=[
135
+ output_image,
136
+ download_image_btn,
137
+ download_csv_btn
138
+ ],
139
  )
140
 
141
  if __name__ == "__main__":
142
+ app.launch()