Files changed (1) hide show
  1. app.py +70 -45
app.py CHANGED
@@ -13,36 +13,47 @@ import os
13
  DATASET_DIR = "dataset-resized"
14
  MODEL_PATH = "waste_classifier.h5"
15
  IMG_SIZE = (128, 128)
16
- BATCH_SIZE = 32
17
- EPOCHS = 5
 
 
 
 
 
18
 
19
  # -----------------------------
20
  # REMOVE CORRUPTED IMAGES
21
  # -----------------------------
22
  def clean_dataset(dataset_path):
23
  valid_extensions = (".jpg", ".jpeg", ".png")
24
-
25
  removed = 0
 
26
  for root, dirs, files in os.walk(dataset_path):
27
  for file in files:
28
  file_path = os.path.join(root, file)
29
 
30
  if not file.lower().endswith(valid_extensions):
31
- os.remove(file_path)
32
- removed += 1
 
 
 
33
  continue
34
 
35
  try:
36
  with Image.open(file_path) as img:
37
  img.verify()
38
  except (UnidentifiedImageError, OSError):
39
- os.remove(file_path)
40
- removed += 1
 
 
 
41
 
42
  return removed
43
 
44
  # -----------------------------
45
- # TRAIN MODEL FUNCTION
46
  # -----------------------------
47
  def train_model():
48
  removed_files = clean_dataset(DATASET_DIR)
@@ -87,11 +98,12 @@ def train_model():
87
  metrics=['accuracy']
88
  )
89
 
90
- model.fit(
91
- train_data,
92
- validation_data=val_data,
93
- epochs=EPOCHS
94
- )
 
95
 
96
  model.save(MODEL_PATH)
97
 
@@ -108,47 +120,60 @@ else:
108
  classes = ['cardboard', 'glass', 'metal', 'paper', 'plastic', 'trash']
109
 
110
  # -----------------------------
111
- # STREAMLIT UI
112
  # -----------------------------
113
- st.set_page_config(page_title="AI Waste Classifier")
114
  st.title("♻️ AI Smart Waste Classification")
115
  st.write("Upload an image to classify waste and support sustainable recycling.")
116
 
117
  uploaded_file = st.file_uploader(
118
  "Upload Waste Image",
119
- type=["jpg", "jpeg", "png"]
 
120
  )
121
 
122
  if uploaded_file is not None:
123
- image = Image.open(uploaded_file).convert("RGB")
124
- st.image(image, caption="Uploaded Image", use_column_width=True)
125
-
126
- # Preprocess image
127
- img = image.resize(IMG_SIZE)
128
- img_array = np.array(img) / 255.0
129
- img_array = np.expand_dims(img_array, axis=0)
130
-
131
- # Predict
132
- prediction = model.predict(img_array)
133
- predicted_class = classes[np.argmax(prediction)]
134
- confidence = np.max(prediction) * 100
135
-
136
- # Display Results
137
- st.success(f"Predicted Type: {predicted_class.upper()}")
138
- st.info(f"Confidence: {confidence:.2f}%")
139
-
140
- # Sustainability Tips
141
- tips = {
142
- 'plastic': 'Recycle plastic properly to reduce pollution.',
143
- 'paper': 'Reuse or recycle paper to save trees.',
144
- 'metal': 'Metal can be recycled efficiently.',
145
- 'glass': 'Glass is reusable and recyclable.',
146
- 'trash': 'Dispose responsibly to reduce environmental damage.',
147
- 'cardboard': 'Recycle cardboard to reduce waste.'
148
- }
149
-
150
- st.subheader("🌱 Sustainability Suggestion")
151
- st.write(tips.get(predicted_class, "Dispose responsibly."))
 
 
 
 
 
 
 
 
 
 
 
 
 
152
 
153
  # -----------------------------
154
  # FOOTER
 
13
  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
26
  # -----------------------------
27
  def clean_dataset(dataset_path):
28
  valid_extensions = (".jpg", ".jpeg", ".png")
 
29
  removed = 0
30
+
31
  for root, dirs, files in os.walk(dataset_path):
32
  for file in files:
33
  file_path = os.path.join(root, file)
34
 
35
  if not file.lower().endswith(valid_extensions):
36
+ try:
37
+ os.remove(file_path)
38
+ removed += 1
39
+ except:
40
+ pass
41
  continue
42
 
43
  try:
44
  with Image.open(file_path) as img:
45
  img.verify()
46
  except (UnidentifiedImageError, OSError):
47
+ try:
48
+ os.remove(file_path)
49
+ removed += 1
50
+ except:
51
+ pass
52
 
53
  return removed
54
 
55
  # -----------------------------
56
+ # TRAIN MODEL
57
  # -----------------------------
58
  def train_model():
59
  removed_files = clean_dataset(DATASET_DIR)
 
98
  metrics=['accuracy']
99
  )
100
 
101
+ with st.spinner("Training AI model... Please wait."):
102
+ model.fit(
103
+ train_data,
104
+ validation_data=val_data,
105
+ epochs=EPOCHS
106
+ )
107
 
108
  model.save(MODEL_PATH)
109
 
 
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.")
127
 
128
  uploaded_file = st.file_uploader(
129
  "Upload Waste Image",
130
+ type=["jpg", "jpeg", "png"],
131
+ accept_multiple_files=False
132
  )
133
 
134
  if uploaded_file is not None:
135
+ try:
136
+ image = Image.open(uploaded_file).convert("RGB")
137
+
138
+ st.image(
139
+ image,
140
+ caption="Uploaded Image",
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.',
163
+ 'metal': 'Metal can be recycled efficiently.',
164
+ 'glass': 'Glass is reusable and recyclable.',
165
+ 'trash': 'Dispose responsibly to reduce environmental damage.',
166
+ 'cardboard': 'Recycle cardboard to reduce waste.'
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)}")
177
 
178
  # -----------------------------
179
  # FOOTER