Files changed (1) hide show
  1. app.py +59 -17
app.py CHANGED
@@ -2,7 +2,7 @@ import streamlit as st
2
  import tensorflow as tf
3
  from tensorflow.keras.preprocessing.image import ImageDataGenerator
4
  from tensorflow.keras.models import Sequential
5
- from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
6
  import numpy as np
7
  from PIL import Image, UnidentifiedImageError
8
  import os
@@ -14,12 +14,15 @@ DATASET_DIR = "dataset-resized"
14
  MODEL_PATH = "waste_classifier.h5"
15
  IMG_SIZE = (128, 128)
16
  BATCH_SIZE = 16
17
- EPOCHS = 3
18
 
19
  # -----------------------------
20
  # PAGE CONFIG
21
  # -----------------------------
22
- st.set_page_config(page_title="AI Waste Classifier", layout="centered")
 
 
 
23
 
24
  # -----------------------------
25
  # REMOVE CORRUPTED IMAGES
@@ -61,7 +64,10 @@ def train_model():
61
 
62
  datagen = ImageDataGenerator(
63
  rescale=1./255,
64
- validation_split=0.2
 
 
 
65
  )
66
 
67
  train_data = datagen.flow_from_directory(
@@ -69,7 +75,8 @@ def train_model():
69
  target_size=IMG_SIZE,
70
  batch_size=BATCH_SIZE,
71
  class_mode='categorical',
72
- subset='training'
 
73
  )
74
 
75
  val_data = datagen.flow_from_directory(
@@ -77,9 +84,12 @@ def train_model():
77
  target_size=IMG_SIZE,
78
  batch_size=BATCH_SIZE,
79
  class_mode='categorical',
80
- subset='validation'
 
81
  )
82
 
 
 
83
  model = Sequential([
84
  Conv2D(32, (3,3), activation='relu', input_shape=(128,128,3)),
85
  MaxPooling2D(2,2),
@@ -87,8 +97,13 @@ def train_model():
87
  Conv2D(64, (3,3), activation='relu'),
88
  MaxPooling2D(2,2),
89
 
 
 
 
90
  Flatten(),
91
- Dense(128, activation='relu'),
 
 
92
  Dense(train_data.num_classes, activation='softmax')
93
  ])
94
 
@@ -107,7 +122,7 @@ def train_model():
107
 
108
  model.save(MODEL_PATH)
109
 
110
- return model, list(train_data.class_indices.keys())
111
 
112
  # -----------------------------
113
  # LOAD OR TRAIN MODEL
@@ -117,10 +132,13 @@ if not os.path.exists(MODEL_PATH):
117
  model, classes = train_model()
118
  else:
119
  model = tf.keras.models.load_model(MODEL_PATH)
 
 
 
120
  classes = ['cardboard', 'glass', 'metal', 'paper', 'plastic', 'trash']
121
 
122
  # -----------------------------
123
- # UI
124
  # -----------------------------
125
  st.title("♻️ AI Smart Waste Classification")
126
  st.write("Upload an image to classify waste and support sustainable recycling.")
@@ -141,22 +159,39 @@ if uploaded_file is not None:
141
  use_container_width=True
142
  )
143
 
144
- # Preprocess
 
 
145
  img = image.resize(IMG_SIZE)
146
  img_array = np.array(img) / 255.0
147
  img_array = np.expand_dims(img_array, axis=0)
148
 
149
- # Predict
 
 
150
  with st.spinner("Analyzing waste type..."):
151
- prediction = model.predict(img_array)
152
 
153
- predicted_class = classes[np.argmax(prediction)]
154
- confidence = np.max(prediction) * 100
 
 
 
 
 
 
 
 
 
 
 
155
 
156
- # Output
157
  st.success(f"Predicted Type: {predicted_class.upper()}")
158
  st.info(f"Confidence: {confidence:.2f}%")
159
 
 
 
 
160
  tips = {
161
  'plastic': 'Recycle plastic properly to reduce pollution.',
162
  'paper': 'Reuse or recycle paper to save trees.',
@@ -167,10 +202,17 @@ if uploaded_file is not None:
167
  }
168
 
169
  st.subheader("🌱 Sustainability Suggestion")
170
- st.write(tips.get(predicted_class, "Dispose responsibly."))
 
 
 
 
 
171
 
172
  except UnidentifiedImageError:
173
- st.error("Invalid image file. Please upload a proper JPG, JPEG, or PNG image.")
 
 
174
 
175
  except Exception as e:
176
  st.error(f"Error processing image: {str(e)}")
 
2
  import tensorflow as tf
3
  from tensorflow.keras.preprocessing.image import ImageDataGenerator
4
  from tensorflow.keras.models import Sequential
5
+ from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
6
  import numpy as np
7
  from PIL import Image, UnidentifiedImageError
8
  import os
 
14
  MODEL_PATH = "waste_classifier.h5"
15
  IMG_SIZE = (128, 128)
16
  BATCH_SIZE = 16
17
+ EPOCHS = 5
18
 
19
  # -----------------------------
20
  # PAGE CONFIG
21
  # -----------------------------
22
+ st.set_page_config(
23
+ page_title="AI Waste Classifier",
24
+ layout="centered"
25
+ )
26
 
27
  # -----------------------------
28
  # REMOVE CORRUPTED IMAGES
 
64
 
65
  datagen = ImageDataGenerator(
66
  rescale=1./255,
67
+ validation_split=0.2,
68
+ rotation_range=20,
69
+ zoom_range=0.2,
70
+ horizontal_flip=True
71
  )
72
 
73
  train_data = datagen.flow_from_directory(
 
75
  target_size=IMG_SIZE,
76
  batch_size=BATCH_SIZE,
77
  class_mode='categorical',
78
+ subset='training',
79
+ shuffle=True
80
  )
81
 
82
  val_data = datagen.flow_from_directory(
 
84
  target_size=IMG_SIZE,
85
  batch_size=BATCH_SIZE,
86
  class_mode='categorical',
87
+ subset='validation',
88
+ shuffle=False
89
  )
90
 
91
+ classes = list(train_data.class_indices.keys())
92
+
93
  model = Sequential([
94
  Conv2D(32, (3,3), activation='relu', input_shape=(128,128,3)),
95
  MaxPooling2D(2,2),
 
97
  Conv2D(64, (3,3), activation='relu'),
98
  MaxPooling2D(2,2),
99
 
100
+ Conv2D(128, (3,3), activation='relu'),
101
+ MaxPooling2D(2,2),
102
+
103
  Flatten(),
104
+ Dense(256, activation='relu'),
105
+ Dropout(0.5),
106
+
107
  Dense(train_data.num_classes, activation='softmax')
108
  ])
109
 
 
122
 
123
  model.save(MODEL_PATH)
124
 
125
+ return model, classes
126
 
127
  # -----------------------------
128
  # LOAD OR TRAIN MODEL
 
132
  model, classes = train_model()
133
  else:
134
  model = tf.keras.models.load_model(MODEL_PATH)
135
+
136
+ # IMPORTANT:
137
+ # Ensure this matches dataset folder order exactly
138
  classes = ['cardboard', 'glass', 'metal', 'paper', 'plastic', 'trash']
139
 
140
  # -----------------------------
141
+ # STREAMLIT UI
142
  # -----------------------------
143
  st.title("♻️ AI Smart Waste Classification")
144
  st.write("Upload an image to classify waste and support sustainable recycling.")
 
159
  use_container_width=True
160
  )
161
 
162
+ # -----------------------------
163
+ # PREPROCESS IMAGE
164
+ # -----------------------------
165
  img = image.resize(IMG_SIZE)
166
  img_array = np.array(img) / 255.0
167
  img_array = np.expand_dims(img_array, axis=0)
168
 
169
+ # -----------------------------
170
+ # PREDICT
171
+ # -----------------------------
172
  with st.spinner("Analyzing waste type..."):
173
+ prediction = model.predict(img_array, verbose=0)
174
 
175
+ probabilities = prediction[0]
176
+
177
+ predicted_index = np.argmax(probabilities)
178
+ predicted_class = classes[predicted_index]
179
+ confidence = probabilities[predicted_index] * 100
180
+
181
+ # -----------------------------
182
+ # DISPLAY RESULTS
183
+ # -----------------------------
184
+ st.subheader("📊 Prediction Scores")
185
+
186
+ for i, class_name in enumerate(classes):
187
+ st.write(f"{class_name.upper()}: {probabilities[i]*100:.2f}%")
188
 
 
189
  st.success(f"Predicted Type: {predicted_class.upper()}")
190
  st.info(f"Confidence: {confidence:.2f}%")
191
 
192
+ # -----------------------------
193
+ # SUSTAINABILITY TIPS
194
+ # -----------------------------
195
  tips = {
196
  'plastic': 'Recycle plastic properly to reduce pollution.',
197
  'paper': 'Reuse or recycle paper to save trees.',
 
202
  }
203
 
204
  st.subheader("🌱 Sustainability Suggestion")
205
+ st.write(
206
+ tips.get(
207
+ predicted_class,
208
+ "Dispose responsibly."
209
+ )
210
+ )
211
 
212
  except UnidentifiedImageError:
213
+ st.error(
214
+ "Invalid image file. Please upload a valid JPG, JPEG, or PNG image."
215
+ )
216
 
217
  except Exception as e:
218
  st.error(f"Error processing image: {str(e)}")