Twinkle19 commited on
Commit
a0b61a3
Β·
verified Β·
1 Parent(s): e5240d4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -108
app.py CHANGED
@@ -1,108 +1,52 @@
1
- import streamlit as st
2
- from tensorflow.keras.models import load_model
3
- from tensorflow.keras.layers import DepthwiseConv2D
4
- from PIL import Image, ImageOps
5
- import numpy as np
6
-
7
- # ----------------------------- Model Setup -----------------------------
8
- # Optional patch for custom DepthwiseConv2D
9
- class PatchedDepthwiseConv2D(DepthwiseConv2D):
10
- def __init__(self, *args, groups=1, **kwargs):
11
- super().__init__(*args, **kwargs)
12
-
13
- # Load pre-trained model
14
- model = load_model(
15
- r"C:\Users\rani ghangare\OneDrive\Documents\Python Skill4Future Session\🌱 Smart Waste Classifier & R-Method Recommender\Smart Waste Classifier & R-Method Recommender\keras_model.h5",
16
- compile=False,
17
- custom_objects={"DepthwiseConv2D": PatchedDepthwiseConv2D}
18
- )
19
-
20
- # Load class labels and clean them (remove number prefixes)
21
- with open(r"C:\Users\rani ghangare\OneDrive\Documents\Python Skill4Future Session\🌱 Smart Waste Classifier & R-Method Recommender\Smart Waste Classifier & R-Method Recommender\labels.txt", "r") as f:
22
- class_names = [label.strip().split(" ", 1)[-1] for label in f.readlines()]
23
-
24
- # Mapping of waste types to R-methods
25
- r_method_map = {
26
- "plastic": "Recycle ♻️",
27
- "paper": "Reuse πŸ“„",
28
- "glass": "Recycle πŸ§ͺ",
29
- "metal": "Recycle πŸ› οΈ",
30
- "organic": "Reduce 🌿",
31
- "e-waste": "Recycle ⚑",
32
- "textile": "Reuse πŸ‘•",
33
- "cardboard": "Reuse πŸ“¦",
34
- "hazardous": "Reduce 🚫",
35
- "other": "Reduce/Reuse ♻️"
36
- }
37
-
38
- # ----------------------------- Streamlit UI -----------------------------
39
- st.set_page_config(page_title="🌱 Smart Waste Classifier & R-Method Recommender", page_icon="♻️", layout="centered")
40
-
41
- # Sidebar information
42
- with st.sidebar:
43
- st.title("🧭 About This Tool")
44
- st.markdown("""
45
- Upload an image of waste to identify its type using an AI model and receive a suitable action recommendation:
46
-
47
- - ♻️ Recycle
48
- - πŸ‘• Reuse
49
- - 🌿 Reduce
50
-
51
- This tool helps promote **environmentally responsible disposal**.
52
- """)
53
-
54
- # Title and subtitle (updated)
55
- st.markdown("<h1 style='text-align: center;'>🌱 Smart Waste Classifier & R-Method Recommender</h1>", unsafe_allow_html=True)
56
- st.markdown("<h4 style='text-align: center; color: grey;'>An AI-based tool for waste type prediction and sustainable action guidance</h4>", unsafe_allow_html=True)
57
- st.markdown("---")
58
-
59
- # Upload image
60
- uploaded_file = st.file_uploader("πŸ“€ Upload an image of the waste item", type=["jpg", "jpeg", "png"])
61
-
62
- # Predict button
63
- if st.button("πŸ” Analyze Image"):
64
- if uploaded_file is not None:
65
- try:
66
- # Open and display image
67
- image = Image.open(uploaded_file)
68
- st.image(image, caption="Uploaded Image", use_container_width=True)
69
-
70
- # Preprocess image for model
71
- image = image.convert("RGB")
72
- image = ImageOps.fit(image, (224, 224), Image.Resampling.LANCZOS)
73
- image_array = np.asarray(image)
74
- normalized_image_array = (image_array.astype(np.float32) / 127.5) - 1
75
- data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
76
- data[0] = normalized_image_array
77
-
78
- # Make prediction
79
- with st.spinner("Analyzing..."):
80
- prediction = model.predict(data)
81
- index = np.argmax(prediction)
82
- predicted_label = class_names[index].strip()
83
- confidence = prediction[0][index]
84
-
85
- # Get R-method (safe fallback)
86
- label_key = predicted_label.lower().strip()
87
- r_method = r_method_map.get(label_key, "Dispose Responsibly ♻️")
88
-
89
- # Display result
90
- st.success("βœ… Prediction Successful")
91
- col1, col2 = st.columns(2)
92
- col1.metric("Waste Type", predicted_label.title())
93
- col2.metric("Confidence", f"{confidence * 100:.2f}%")
94
-
95
- st.markdown(f"### 🧭 Recommended Action: <span style='color:green; background:#111;padding:5px;border-radius:4px;'> {r_method} </span>", unsafe_allow_html=True)
96
- st.info("Please dispose of this waste responsibly according to local regulations.")
97
-
98
- except Exception as e:
99
- st.error(f"❌ Error: Unable to process the image.\n\nDetails: {e}")
100
- else:
101
- st.warning("⚠️ Please upload an image first.")
102
-
103
- # ----------------------------- Footer -----------------------------
104
- st.markdown("---")
105
- st.markdown(
106
- "<p style='text-align: center;'>Developed with ❀️ by <strong>Twinkle Ghangare</strong> | Supported by EDUNET FOUNDATION</p>",
107
- unsafe_allow_html=True
108
- )
 
1
+ import streamlit as st
2
+ from tensorflow.keras.models import load_model
3
+ from tensorflow.keras.layers import DepthwiseConv2D
4
+ from PIL import Image, ImageOps
5
+ import numpy as np
6
+
7
+ # Optional: Patch DepthwiseConv2D if needed
8
+ class PatchedDepthwiseConv2D(DepthwiseConv2D):
9
+ def _init_(self, *args, groups=1, **kwargs):
10
+ super()._init_(*args, **kwargs)
11
+
12
+ # Load model
13
+ model = load_model(r"keras_model.h5", compile=False, custom_objects={"DepthwiseConv2D": PatchedDepthwiseConv2D})
14
+
15
+ # Load class labels
16
+ with open(r"labels.txt", "r") as f:
17
+ class_names = f.readlines()
18
+
19
+ st.title("β™» Garbage Classification Predictor")
20
+
21
+ # Upload image
22
+ uploaded_file = st.file_uploader("Upload a waste image (jpg, png)", type=["jpg", "jpeg", "png"])
23
+
24
+ if st.button("πŸ§ͺ Predict Waste Type"):
25
+ if uploaded_file is not None:
26
+ image = Image.open(uploaded_file)
27
+ st.image(image, use_container_width=True)
28
+
29
+
30
+ # Preprocess image
31
+ image = image.convert("RGB")
32
+ image = ImageOps.fit(image, (224, 224), Image.Resampling.LANCZOS)
33
+ image_array = np.asarray(image)
34
+ normalized_image_array = (image_array.astype(np.float32) / 127.5) - 1
35
+ data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
36
+ data[0] = normalized_image_array
37
+
38
+ # Make prediction
39
+ prediction = model.predict(data)
40
+ index = np.argmax(prediction)
41
+ predicted_label = class_names[index].strip()
42
+ confidence = prediction[0][index]
43
+
44
+ # Display result
45
+ st.success(f"Predicted Waste Type: *{predicted_label.upper()}*")
46
+ st.write(f"Confidence Score: *{confidence:.2f}*")
47
+ st.write("β™» Dispose responsibly!")
48
+ else:
49
+ st.warning("⚠ Please upload an image before predicting.")
50
+ # πŸ”š Footer
51
+ st.markdown("---")
52
+ st.markdown("<p style='text-align: center; font-size: 18px;'>Developed with ❀ By Twinkle Ghangare for EDUNET FOUNDATION </p>", unsafe_allow_html=True)