Files changed (1) hide show
  1. app.py +129 -0
app.py CHANGED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 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
8
+ import os
9
+
10
+ # -----------------------------
11
+ # CONFIGURATION
12
+ # -----------------------------
13
+ DATASET_DIR = "dataset"
14
+ MODEL_PATH = "waste_classifier.h5"
15
+ IMG_SIZE = (128, 128)
16
+ BATCH_SIZE = 32
17
+ EPOCHS = 5
18
+
19
+ # -----------------------------
20
+ # TRAIN MODEL FUNCTION
21
+ # -----------------------------
22
+ def train_model():
23
+ datagen = ImageDataGenerator(
24
+ rescale=1./255,
25
+ validation_split=0.2
26
+ )
27
+
28
+ train_data = datagen.flow_from_directory(
29
+ DATASET_DIR,
30
+ target_size=IMG_SIZE,
31
+ batch_size=BATCH_SIZE,
32
+ class_mode='categorical',
33
+ subset='training'
34
+ )
35
+
36
+ val_data = datagen.flow_from_directory(
37
+ DATASET_DIR,
38
+ target_size=IMG_SIZE,
39
+ batch_size=BATCH_SIZE,
40
+ class_mode='categorical',
41
+ subset='validation'
42
+ )
43
+
44
+ model = Sequential([
45
+ Conv2D(32, (3,3), activation='relu', input_shape=(128,128,3)),
46
+ MaxPooling2D(2,2),
47
+
48
+ Conv2D(64, (3,3), activation='relu'),
49
+ MaxPooling2D(2,2),
50
+
51
+ Flatten(),
52
+ Dense(128, activation='relu'),
53
+ Dense(train_data.num_classes, activation='softmax')
54
+ ])
55
+
56
+ model.compile(
57
+ optimizer='adam',
58
+ loss='categorical_crossentropy',
59
+ metrics=['accuracy']
60
+ )
61
+
62
+ model.fit(
63
+ train_data,
64
+ validation_data=val_data,
65
+ epochs=EPOCHS
66
+ )
67
+
68
+ model.save(MODEL_PATH)
69
+
70
+ return model, list(train_data.class_indices.keys())
71
+
72
+ # -----------------------------
73
+ # LOAD MODEL
74
+ # -----------------------------
75
+ if not os.path.exists(MODEL_PATH):
76
+ st.warning("Training model for first-time use. Please wait...")
77
+ model, classes = train_model()
78
+ else:
79
+ model = tf.keras.models.load_model(MODEL_PATH)
80
+ classes = ['cardboard', 'glass', 'metal', 'paper', 'plastic', 'trash']
81
+
82
+ # -----------------------------
83
+ # STREAMLIT UI
84
+ # -----------------------------
85
+ st.set_page_config(page_title="AI Waste Classifier")
86
+ st.title("♻️ AI Smart Waste Classification")
87
+ st.write("Upload an image to classify waste and support sustainable recycling.")
88
+
89
+ uploaded_file = st.file_uploader(
90
+ "Upload Waste Image",
91
+ type=["jpg", "jpeg", "png"]
92
+ )
93
+
94
+ if uploaded_file is not None:
95
+ image = Image.open(uploaded_file).convert("RGB")
96
+ st.image(image, caption="Uploaded Image", use_column_width=True)
97
+
98
+ # Preprocess image
99
+ img = image.resize(IMG_SIZE)
100
+ img_array = np.array(img) / 255.0
101
+ img_array = np.expand_dims(img_array, axis=0)
102
+
103
+ # Predict
104
+ prediction = model.predict(img_array)
105
+ predicted_class = classes[np.argmax(prediction)]
106
+ confidence = np.max(prediction) * 100
107
+
108
+ # Display Results
109
+ st.success(f"Predicted Type: {predicted_class.upper()}")
110
+ st.info(f"Confidence: {confidence:.2f}%")
111
+
112
+ # Sustainability Tips
113
+ tips = {
114
+ 'plastic': 'Recycle plastic properly to reduce pollution.',
115
+ 'paper': 'Reuse or recycle paper to save trees.',
116
+ 'metal': 'Metal can be recycled efficiently.',
117
+ 'glass': 'Glass is reusable and recyclable.',
118
+ 'trash': 'Dispose responsibly to reduce environmental damage.',
119
+ 'cardboard': 'Recycle cardboard to reduce waste.'
120
+ }
121
+
122
+ st.subheader("🌱 Sustainability Suggestion")
123
+ st.write(tips.get(predicted_class, "Dispose responsibly."))
124
+
125
+ # -----------------------------
126
+ # FOOTER
127
+ # -----------------------------
128
+ st.markdown("---")
129
+ st.caption("Built using TensorFlow + Streamlit for Sustainable AI")