Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -6,14 +6,19 @@ import gradio as gr
|
|
6 |
from tensorflow import keras
|
7 |
from keras.models import load_model
|
8 |
|
9 |
-
# Load the
|
10 |
-
|
11 |
-
|
|
|
|
|
|
|
|
|
|
|
12 |
|
13 |
# Load the mineral detection model
|
14 |
mineral_detection_model = tf.keras.models.load_model("mineral_detection_model_Final_4_18_2024.h5")
|
15 |
|
16 |
-
#
|
17 |
class_labels = ['biotite', 'granite', 'olivine', 'plagioclase', 'staurolite']
|
18 |
mineral_facts = {
|
19 |
'biotite': "Hardness: 2.5-3\nMagnetism: None\nDensity: 2.7-3.3 g/cm³\nColors: Black, brown, green\nDescription: A phyllosilicate mineral of the mica group with a distinctive platy structure.",
|
@@ -22,8 +27,7 @@ mineral_facts = {
|
|
22 |
'plagioclase': "Hardness: 6-6.5\nMagnetism: None\nDensity: 2.6-2.8 g/cm³\nColors: White, gray, green\nDescription: A series of feldspar minerals ranging from sodium-rich albite to calcium-rich anorthite.",
|
23 |
'staurolite': "Hardness: 7-7.5\nMagnetism: None\nDensity: 3.6-3.8 g/cm³\nColors: Brown, reddish-brown, black\nDescription: A nesosilicate mineral with a distinctive cruciform twinning habit, commonly found in metamorphic rocks."
|
24 |
}
|
25 |
-
|
26 |
-
# function to preprocess the image for mineral detection
|
27 |
def preprocess_image_detection(img_array):
|
28 |
if img_array is None:
|
29 |
return None
|
@@ -33,7 +37,7 @@ def preprocess_image_detection(img_array):
|
|
33 |
img_array = np.expand_dims(img_array, axis=0) # Add batch dimension
|
34 |
return img_array
|
35 |
|
36 |
-
#
|
37 |
def preprocess_image_classification(img_array):
|
38 |
if img_array is None:
|
39 |
return None
|
@@ -43,46 +47,60 @@ def preprocess_image_classification(img_array):
|
|
43 |
img_array = np.expand_dims(img_array, axis=0) # Add batch dimension
|
44 |
return img_array
|
45 |
|
46 |
-
#
|
47 |
def detect_mineral(image):
|
48 |
if image is not None:
|
49 |
image = Image.fromarray(np.array(image).astype(np.uint8), 'RGB')
|
50 |
-
image =
|
|
|
|
|
51 |
image = np.array(image) / 255.0
|
52 |
-
image = np.expand_dims(image, axis=0)
|
53 |
-
|
54 |
# Make prediction
|
55 |
prediction = mineral_detection_model.predict(image)
|
56 |
is_mineral = prediction[0][0] < 0.5 # Assuming binary classification
|
57 |
return is_mineral
|
58 |
else:
|
|
|
59 |
return "No image provided."
|
60 |
|
61 |
-
#
|
62 |
def classify_image(image):
|
63 |
# Check if the input is a mineral
|
64 |
is_mineral = detect_mineral(image)
|
65 |
if not is_mineral:
|
66 |
-
return "Input is not a Microscopic mineral thin section
|
67 |
|
68 |
# Preprocess the image for classification
|
69 |
image = preprocess_image_classification(np.array(image))
|
70 |
if image is None:
|
71 |
return "Error preprocessing image.", "", ""
|
72 |
|
73 |
-
#
|
74 |
-
|
75 |
-
class_idx = np.argmax(prediction)
|
76 |
-
|
77 |
-
prediction_scores = prediction[0]
|
78 |
-
prediction_scores_percentages = [f"{score * 100:.2f}%" for score in prediction_scores]
|
79 |
|
|
|
|
|
|
|
80 |
predicted_class_name = class_labels[class_idx]
|
81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
82 |
mineral_key_facts = mineral_facts.get(predicted_class_name, "No key facts available for this mineral.")
|
83 |
|
84 |
return predicted_class_name, predicted_scores, mineral_key_facts
|
85 |
|
|
|
|
|
|
|
|
|
|
|
|
|
86 |
DESCRIPTION = '''
|
87 |
<div>
|
88 |
<h1 style="text-align: center;">Microscopic Mineral Identification App</h1>
|
@@ -92,11 +110,11 @@ DESCRIPTION = '''
|
|
92 |
</div>
|
93 |
'''
|
94 |
|
95 |
-
|
|
|
96 |
def welcome(name):
|
97 |
return f"Welcome to Gradio, {name}!"
|
98 |
|
99 |
-
# Custom JavaScript for an animation when opening the app
|
100 |
js = """
|
101 |
function createGradioAnimation() {
|
102 |
var container = document.createElement('div');
|
@@ -105,6 +123,7 @@ function createGradioAnimation() {
|
|
105 |
container.style.fontWeight = 'bold';
|
106 |
container.style.textAlign = 'center';
|
107 |
container.style.marginBottom = '20px';
|
|
|
108 |
var text = 'Welcome to Gradio!';
|
109 |
for (var i = 0; i < text.length; i++) {
|
110 |
(function(i){
|
@@ -113,36 +132,50 @@ function createGradioAnimation() {
|
|
113 |
letter.style.opacity = '0';
|
114 |
letter.style.transition = 'opacity 0.5s';
|
115 |
letter.innerText = text[i];
|
|
|
116 |
container.appendChild(letter);
|
|
|
117 |
setTimeout(function() {
|
118 |
letter.style.opacity = '1';
|
119 |
}, 50);
|
120 |
}, i * 250);
|
121 |
})(i);
|
122 |
}
|
|
|
123 |
var gradioContainer = document.querySelector('.gradio-container');
|
124 |
gradioContainer.insertBefore(container, gradioContainer.firstChild);
|
|
|
125 |
return 'Animation created';
|
126 |
}
|
127 |
"""
|
128 |
|
|
|
129 |
app_title = "Mineral Identification using AI"
|
130 |
app_description = "This application uses advanced machine learning models to accurately identify and classify different types of minerals from images. Simply upload an image, and the system will provide the predicted mineral class along with its key characteristics and properties."
|
131 |
|
132 |
custom_css = """
|
133 |
.gradio-container {display: flex; justify-content: center; align-items: center; height: 100vh;}
|
|
|
|
|
134 |
#title-container {
|
135 |
-
display: flex;
|
|
|
|
|
|
|
136 |
}
|
|
|
137 |
#app-title {
|
138 |
margin-right: 20px; /* Adjust the spacing between the title and logo */
|
139 |
}
|
|
|
140 |
#logo-img {
|
141 |
-
width: 50px; /* Adjust the logo size */
|
142 |
height: 50px;
|
143 |
}
|
|
|
144 |
"""
|
145 |
|
|
|
146 |
with gr.Blocks(
|
147 |
title=app_title,
|
148 |
css=custom_css,
|
@@ -151,20 +184,25 @@ with gr.Blocks(
|
|
151 |
) as demo:
|
152 |
gr.Markdown(DESCRIPTION)
|
153 |
|
154 |
-
#
|
155 |
with gr.Row():
|
156 |
image_input = gr.Image(elem_id="image_input", type="pil")
|
157 |
output_components = [
|
158 |
gr.Textbox(label="Mineral Name", elem_id="predicted_class_name"),
|
159 |
gr.Textbox(label="Prediction Scores of Model", elem_id="predicted_scores", lines=5),
|
160 |
-
gr.Textbox(label="Key Facts About Mineral", elem_id="mineral_key_facts", lines=8)
|
161 |
]
|
162 |
image_button = gr.Button("Classify Mineral")
|
163 |
image_button.click(classify_image, inputs=image_input, outputs=output_components)
|
164 |
|
|
|
|
|
|
|
|
|
165 |
gr.Examples(
|
166 |
-
examples=["Gradio
|
167 |
inputs=image_input,
|
168 |
-
|
169 |
|
170 |
-
|
|
|
|
6 |
from tensorflow import keras
|
7 |
from keras.models import load_model
|
8 |
|
9 |
+
# Load the CNN feature extractor model
|
10 |
+
from tensorflow.keras.models import load_model
|
11 |
+
loaded_feature_extractor = load_model("feature_extractor_model")
|
12 |
+
|
13 |
+
# Load the SVM model
|
14 |
+
import pickle
|
15 |
+
with open("svm_model.pkl", 'rb') as file:
|
16 |
+
loaded_svm_model = pickle.load(file)
|
17 |
|
18 |
# Load the mineral detection model
|
19 |
mineral_detection_model = tf.keras.models.load_model("mineral_detection_model_Final_4_18_2024.h5")
|
20 |
|
21 |
+
# Define the class labels
|
22 |
class_labels = ['biotite', 'granite', 'olivine', 'plagioclase', 'staurolite']
|
23 |
mineral_facts = {
|
24 |
'biotite': "Hardness: 2.5-3\nMagnetism: None\nDensity: 2.7-3.3 g/cm³\nColors: Black, brown, green\nDescription: A phyllosilicate mineral of the mica group with a distinctive platy structure.",
|
|
|
27 |
'plagioclase': "Hardness: 6-6.5\nMagnetism: None\nDensity: 2.6-2.8 g/cm³\nColors: White, gray, green\nDescription: A series of feldspar minerals ranging from sodium-rich albite to calcium-rich anorthite.",
|
28 |
'staurolite': "Hardness: 7-7.5\nMagnetism: None\nDensity: 3.6-3.8 g/cm³\nColors: Brown, reddish-brown, black\nDescription: A nesosilicate mineral with a distinctive cruciform twinning habit, commonly found in metamorphic rocks."
|
29 |
}
|
30 |
+
# Function to preprocess the image for mineral detection
|
|
|
31 |
def preprocess_image_detection(img_array):
|
32 |
if img_array is None:
|
33 |
return None
|
|
|
37 |
img_array = np.expand_dims(img_array, axis=0) # Add batch dimension
|
38 |
return img_array
|
39 |
|
40 |
+
# Function to preprocess the image for classification
|
41 |
def preprocess_image_classification(img_array):
|
42 |
if img_array is None:
|
43 |
return None
|
|
|
47 |
img_array = np.expand_dims(img_array, axis=0) # Add batch dimension
|
48 |
return img_array
|
49 |
|
50 |
+
# Define the function to detect if the input is a mineral
|
51 |
def detect_mineral(image):
|
52 |
if image is not None:
|
53 |
image = Image.fromarray(np.array(image).astype(np.uint8), 'RGB')
|
54 |
+
image = np.array(image)
|
55 |
+
image = Image.fromarray(image.astype(np.uint8), 'RGB')
|
56 |
+
image = image.resize((150, 150)) # Assuming the model expects 150x150 images
|
57 |
image = np.array(image) / 255.0
|
58 |
+
image = np.expand_dims(image, axis=0)
|
59 |
+
|
60 |
# Make prediction
|
61 |
prediction = mineral_detection_model.predict(image)
|
62 |
is_mineral = prediction[0][0] < 0.5 # Assuming binary classification
|
63 |
return is_mineral
|
64 |
else:
|
65 |
+
# Handle the case where no image is provided
|
66 |
return "No image provided."
|
67 |
|
68 |
+
# Define the function to make predictions
|
69 |
def classify_image(image):
|
70 |
# Check if the input is a mineral
|
71 |
is_mineral = detect_mineral(image)
|
72 |
if not is_mineral:
|
73 |
+
return "Input is not a Microscopic mineral thin section, Please Insert a thin section.", "", ""
|
74 |
|
75 |
# Preprocess the image for classification
|
76 |
image = preprocess_image_classification(np.array(image))
|
77 |
if image is None:
|
78 |
return "Error preprocessing image.", "", ""
|
79 |
|
80 |
+
# Extract features using the loaded CNN feature extractor
|
81 |
+
image_features = loaded_feature_extractor.predict(image)
|
|
|
|
|
|
|
|
|
82 |
|
83 |
+
# Make prediction using the loaded SVM model
|
84 |
+
predicted_label = loaded_svm_model.predict(image_features)
|
85 |
+
class_idx = predicted_label[0]
|
86 |
predicted_class_name = class_labels[class_idx]
|
87 |
+
|
88 |
+
# Get prediction scores for all classes
|
89 |
+
decision_values = loaded_svm_model.decision_function(image_features)
|
90 |
+
prediction_scores = [f"{label}: {score:.4f}" for label, score in zip(class_labels, decision_values[0])]
|
91 |
+
predicted_scores = "\n".join(prediction_scores)
|
92 |
+
|
93 |
+
# Get the mineral key facts
|
94 |
mineral_key_facts = mineral_facts.get(predicted_class_name, "No key facts available for this mineral.")
|
95 |
|
96 |
return predicted_class_name, predicted_scores, mineral_key_facts
|
97 |
|
98 |
+
|
99 |
+
|
100 |
+
|
101 |
+
|
102 |
+
|
103 |
+
|
104 |
DESCRIPTION = '''
|
105 |
<div>
|
106 |
<h1 style="text-align: center;">Microscopic Mineral Identification App</h1>
|
|
|
110 |
</div>
|
111 |
'''
|
112 |
|
113 |
+
|
114 |
+
# Welcome Message
|
115 |
def welcome(name):
|
116 |
return f"Welcome to Gradio, {name}!"
|
117 |
|
|
|
118 |
js = """
|
119 |
function createGradioAnimation() {
|
120 |
var container = document.createElement('div');
|
|
|
123 |
container.style.fontWeight = 'bold';
|
124 |
container.style.textAlign = 'center';
|
125 |
container.style.marginBottom = '20px';
|
126 |
+
|
127 |
var text = 'Welcome to Gradio!';
|
128 |
for (var i = 0; i < text.length; i++) {
|
129 |
(function(i){
|
|
|
132 |
letter.style.opacity = '0';
|
133 |
letter.style.transition = 'opacity 0.5s';
|
134 |
letter.innerText = text[i];
|
135 |
+
|
136 |
container.appendChild(letter);
|
137 |
+
|
138 |
setTimeout(function() {
|
139 |
letter.style.opacity = '1';
|
140 |
}, 50);
|
141 |
}, i * 250);
|
142 |
})(i);
|
143 |
}
|
144 |
+
|
145 |
var gradioContainer = document.querySelector('.gradio-container');
|
146 |
gradioContainer.insertBefore(container, gradioContainer.firstChild);
|
147 |
+
|
148 |
return 'Animation created';
|
149 |
}
|
150 |
"""
|
151 |
|
152 |
+
|
153 |
app_title = "Mineral Identification using AI"
|
154 |
app_description = "This application uses advanced machine learning models to accurately identify and classify different types of minerals from images. Simply upload an image, and the system will provide the predicted mineral class along with its key characteristics and properties."
|
155 |
|
156 |
custom_css = """
|
157 |
.gradio-container {display: flex; justify-content: center; align-items: center; height: 100vh;}
|
158 |
+
|
159 |
+
|
160 |
#title-container {
|
161 |
+
display: flex;
|
162 |
+
align-items: center;
|
163 |
+
justify-content: center;
|
164 |
+
margin-bottom: 20px;
|
165 |
}
|
166 |
+
|
167 |
#app-title {
|
168 |
margin-right: 20px; /* Adjust the spacing between the title and logo */
|
169 |
}
|
170 |
+
|
171 |
#logo-img {
|
172 |
+
width: 50px; /* Adjust the logo size as needed */
|
173 |
height: 50px;
|
174 |
}
|
175 |
+
|
176 |
"""
|
177 |
|
178 |
+
|
179 |
with gr.Blocks(
|
180 |
title=app_title,
|
181 |
css=custom_css,
|
|
|
184 |
) as demo:
|
185 |
gr.Markdown(DESCRIPTION)
|
186 |
|
187 |
+
# Your existing code for creating the interface components
|
188 |
with gr.Row():
|
189 |
image_input = gr.Image(elem_id="image_input", type="pil")
|
190 |
output_components = [
|
191 |
gr.Textbox(label="Mineral Name", elem_id="predicted_class_name"),
|
192 |
gr.Textbox(label="Prediction Scores of Model", elem_id="predicted_scores", lines=5),
|
193 |
+
gr.Textbox(label="Key Facts About Mineral", elem_id="mineral_key_facts", lines=8)
|
194 |
]
|
195 |
image_button = gr.Button("Classify Mineral")
|
196 |
image_button.click(classify_image, inputs=image_input, outputs=output_components)
|
197 |
|
198 |
+
with gr.Row():
|
199 |
+
gr.Textbox(label="Mineral Detection", elem_id="mineral_detection_output", lines=3)
|
200 |
+
gr.Textbox(label="Mineral Classification", elem_id="mineral_classification_output", lines=3)
|
201 |
+
gr.Textbox(label="Mineral Key Facts", elem_id="mineral_key_facts_output", lines=8)
|
202 |
gr.Examples(
|
203 |
+
examples=[r"C:\Users\nanom\OneDrive\Desktop\Gradio UI\pixlr-image-generator-29d31d6c-51c8-48ac-a157-d893fe98dec0.png"],
|
204 |
inputs=image_input,
|
205 |
+
|
206 |
|
207 |
+
)
|
208 |
+
demo.launch( auth_message="Welcome To Mineral Identification App.")
|