Darshan03 commited on
Commit
b2a315d
·
verified ·
1 Parent(s): 87e156b

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +180 -37
src/streamlit_app.py CHANGED
@@ -1,40 +1,183 @@
1
- import altair as alt
2
  import numpy as np
3
- import pandas as pd
 
 
 
 
4
  import streamlit as st
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
  import numpy as np
3
+ import tensorflow as tf
4
+ from PIL import Image
5
+ import logging
6
+ from pathlib import Path
7
+ from tensorflow.keras.applications import ConvNeXtLarge
8
  import streamlit as st
9
+ import io
10
 
11
+ def setup_logging():
12
+ logging.basicConfig(
13
+ level=logging.INFO,
14
+ format='%(asctime)s - %(levelname)s - %(message)s'
15
+ )
16
+
17
+ def create_convnext_model(input_shape=(512, 512, 3)):
18
+ base_model = ConvNeXtLarge(
19
+ include_top=False,
20
+ weights='imagenet',
21
+ input_shape=input_shape
22
+ )
23
+ base_model.trainable = False
24
+ model = tf.keras.Sequential([
25
+ base_model,
26
+ tf.keras.layers.GlobalAveragePooling2D(),
27
+ tf.keras.layers.Dropout(0.3),
28
+ tf.keras.layers.Dense(512, activation='relu'),
29
+ tf.keras.layers.Dropout(0.3),
30
+ tf.keras.layers.Dense(256, activation='relu'),
31
+ tf.keras.layers.Dropout(0.3),
32
+ tf.keras.layers.Dense(1, activation='sigmoid')
33
+ ])
34
+ return model
35
+
36
+ @st.cache_resource
37
+ def load_model(model_path):
38
+ try:
39
+ # First create the model architecture
40
+ model = create_convnext_model()
41
+
42
+ # Then load the weights
43
+ model.load_weights(model_path)
44
+ logging.info(f"Model loaded successfully from {model_path}")
45
+ return model
46
+ except Exception as e:
47
+ logging.error(f"Error loading model: {str(e)}")
48
+ raise
49
+
50
+ def preprocess_image(image, target_size=(512, 512)):
51
+ try:
52
+ # Resize image
53
+ img = image.resize(target_size, Image.BILINEAR)
54
+
55
+ # Convert to numpy array and normalize
56
+ img_array = np.array(img)
57
+ img_array = img_array.astype(float) / 255.
58
+ img_array = np.clip(img_array, 0., 1.)
59
+
60
+ # Apply the same normalization as in training
61
+ img_array -= np.array([0.44101639, 0.45513914, 0.40195001])
62
+ img_array /= np.array([0.28792392, 0.29775171, 0.29840153])
63
+
64
+ # Add batch dimension
65
+ img_array = np.expand_dims(img_array, axis=0)
66
+
67
+ return img_array
68
+ except Exception as e:
69
+ logging.error(f"Error preprocessing image: {str(e)}")
70
+ raise
71
+
72
+ def predict_volcano(model, image):
73
+ try:
74
+ # Preprocess the image
75
+ processed_image = preprocess_image(image)
76
+
77
+ # Make prediction
78
+ prediction = model.predict(processed_image)
79
+ probability = prediction[0][0]
80
+
81
+ # Determine result
82
+ result = "Volcanic Eruption" if probability > 0.5 else "No Volcanic Eruption"
83
+ confidence = probability if probability > 0.5 else 1 - probability
84
+
85
+ return {
86
+ "result": result,
87
+ "confidence": float(confidence),
88
+ "probability": float(probability)
89
+ }
90
+ except Exception as e:
91
+ logging.error(f"Error making prediction: {str(e)}")
92
+ raise
93
+
94
+ def get_sample_images():
95
+ # Create sample images directory if it doesn't exist
96
+ sample_dir = Path(__file__).parent / 'sample_images'
97
+ sample_dir.mkdir(exist_ok=True)
98
+
99
+ # Return a dictionary of sample images
100
+ return {
101
+ "Select an image": None,
102
+ "Upload new image": "upload",
103
+ "Sample Volcano 1": str(sample_dir / "volcano1.jpg"),
104
+ "Sample Volcano 2": str(sample_dir / "volcano2.jpg"),
105
+ "Sample No Volcano 1": str(sample_dir / "no_volcano1.jpg"),
106
+ "Sample No Volcano 2": str(sample_dir / "no_volcano2.jpg")
107
+ }
108
+
109
+ def main():
110
+ st.set_page_config(
111
+ page_title="Volcano Detection",
112
+ page_icon="🌋",
113
+ layout="centered"
114
+ )
115
+
116
+ st.title("🌋 Volcano Detection")
117
+ st.write("Select or upload an image to detect if it contains a volcanic eruption.")
118
+
119
+ # Get the base directory
120
+ base_dir = Path(__file__).parent.absolute()
121
+ model_path = base_dir / 'model.h5'
122
+
123
+ # Check if model exists
124
+ if not model_path.exists():
125
+ st.error(f"Model not found at {model_path}")
126
+ return
127
+
128
+ # Load the model
129
+ try:
130
+ model = load_model(str(model_path))
131
+ except Exception as e:
132
+ st.error(f"Error loading model: {str(e)}")
133
+ return
134
+
135
+ # Get sample images
136
+ sample_images = get_sample_images()
137
+
138
+ # Create the image selection interface
139
+ selected_option = st.selectbox("Choose an image", list(sample_images.keys()))
140
+
141
+ # Handle image selection
142
+ image = None
143
+ if selected_option == "Upload new image":
144
+ uploaded_file = st.file_uploader("Upload your image", type=["jpg", "jpeg", "png"])
145
+ if uploaded_file is not None:
146
+ image = Image.open(uploaded_file)
147
+ elif selected_option != "Select an image":
148
+ try:
149
+ image = Image.open(sample_images[selected_option])
150
+ except Exception as e:
151
+ st.error(f"Error loading sample image: {str(e)}")
152
+
153
+ if image is not None:
154
+ # Display the image
155
+ st.image(image, caption="Selected Image", use_column_width=True)
156
+
157
+ # Add a predict button
158
+ if st.button("Detect Volcano"):
159
+ with st.spinner("Analyzing image..."):
160
+ try:
161
+ result = predict_volcano(model, image)
162
+
163
+ # Display results in a nice format
164
+ st.markdown("### Results")
165
+
166
+ # Create columns for the results
167
+ col1, col2 = st.columns(2)
168
+
169
+ with col1:
170
+ st.metric("Prediction", result["result"])
171
+
172
+ with col2:
173
+ st.metric("Confidence", f"{result['confidence']:.2%}")
174
+
175
+ # Add a progress bar for the probability
176
+ st.progress(result["probability"])
177
+ st.write(f"Raw Probability: {result['probability']:.4f}")
178
+
179
+ except Exception as e:
180
+ st.error(f"Error during prediction: {str(e)}")
181
+
182
+ if __name__ == "__main__":
183
+ main()