A-I4All commited on
Commit
57c2d64
·
verified ·
1 Parent(s): 7835e8d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +135 -132
app.py CHANGED
@@ -1,132 +1,135 @@
1
- import streamlit as st
2
- from PIL import Image
3
- import random
4
- import torch
5
- from transformers import AutoImageProcessor, SiglipForImageClassification
6
-
7
- # Model from Hugging Face Hub (open-source)
8
- MODEL_NAME = "prithivMLmods/Recycling-Net-11"
9
-
10
- # Sustainability Tips List
11
- TIPS = [
12
- "Rinse containers before recycling to avoid contamination.",
13
- "Avoid using plastic bags for recyclables – use bins or boxes.",
14
- "Compost your kitchen scraps instead of tossing them.",
15
- "Recycle electronics only at designated e-waste centers.",
16
- "Buy products made from recycled materials to close the loop.",
17
- "Don’t recycle greasy pizza boxes compost or trash them.",
18
- "Learn your local recycling rules they vary by region.",
19
- "Use reusable bags, bottles, and containers to reduce waste.",
20
- "Donate old clothes and furniture instead of throwing them away.",
21
- "Avoid single-use plastics whenever possible.",
22
- ]
23
-
24
- # Government Recycling Resources
25
- GOVERNMENT_LINKS = {
26
- "Pakistan": "https://environment.gov.pk/",
27
- "India": "https://www.cpcb.nic.in/",
28
- "China": "http://english.mee.gov.cn/",
29
- "Japan": "https://www.env.go.jp/en/",
30
- "USA": "https://www.epa.gov/recycle",
31
- "UK": "https://www.gov.uk/recycling-collections",
32
- "Canada": "https://www.canada.ca/en/services/environment/conservation/recycling.html",
33
- "Germany": "https://www.bmu.de/en/topics/water-waste-soil/waste-management",
34
- }
35
-
36
- # Load model and processor
37
- @st.cache_resource(show_spinner=False)
38
- def load_model():
39
- processor = AutoImageProcessor.from_pretrained(MODEL_NAME)
40
- model = SiglipForImageClassification.from_pretrained(MODEL_NAME)
41
- model.eval()
42
- return processor, model
43
-
44
- # Predict function
45
- def predict(image: Image.Image, processor, model):
46
- inputs = processor(images=image, return_tensors="pt")
47
- with torch.no_grad():
48
- outputs = model(**inputs)
49
- logits = outputs.logits
50
- probs = torch.nn.functional.softmax(logits, dim=-1)
51
- conf, idx = torch.max(probs, dim=-1)
52
- class_name = model.config.id2label[idx.item()]
53
- confidence = conf.item()
54
- return class_name, confidence
55
-
56
- # Suggest recycling action based on prediction
57
- def get_suggestion(label: str) -> str:
58
- tips = {
59
- "aluminium": "Rinse and recycle aluminum cans. They are infinitely recyclable.",
60
- "batteries": "Do not throw in the trash. Use proper e-waste collection centers.",
61
- "cardboard": "Flatten and keep dry. Avoid greasy pizza boxes.",
62
- "glass": "Rinse and remove lids. Separate by color if required.",
63
- "hard plastic": "Check recycling codes. Clean before recycling.",
64
- "paper": "Do not recycle shredded paper in curbside bins. Reuse or compost instead.",
65
- "paper towel": "Compost if clean. Trash if soiled.",
66
- "polystyrene": "Rarely accepted in curbside. Reuse or bring to special centers.",
67
- "soft plastics": "Often require store drop-off. Don’t mix with other recyclables.",
68
- "takeaway cups": "Check local rules. Many are lined and not recyclable curbside.",
69
- }
70
- return tips.get(label, "Please check your local rules for proper disposal of this item.")
71
-
72
- # Streamlit App
73
- def main():
74
- st.set_page_config(page_title="♻️ Recycling Helper AI", layout="centered")
75
- st.title("♻️ Recycling Helper AI")
76
- st.subheader("An AI-powered app to identify recyclable materials and promote sustainability.")
77
-
78
- st.markdown("---")
79
-
80
- # Sidebar Content
81
- with st.sidebar:
82
- st.header("📘 About This App")
83
- st.markdown(
84
- "This open-source app helps you identify recyclable materials from waste images "
85
- "using a machine learning model. It promotes proper disposal and reduces contamination "
86
- "in the recycling stream. Built for hackathons using Hugging Face + Streamlit."
87
- )
88
-
89
- st.markdown("---")
90
- st.header("🌐 Recycling Resources")
91
- st.markdown("For proper recycling and disposal of waste, refer to the following resources:")
92
- for country, url in GOVERNMENT_LINKS.items():
93
- st.markdown(f"- [{country}]({url})", unsafe_allow_html=True)
94
-
95
- st.markdown("---")
96
- st.header("🌱 Daily Sustainability Tip")
97
- tip = random.choice(TIPS)
98
- st.success(tip)
99
-
100
- # Load Model
101
- processor, model = load_model()
102
-
103
- # Image Upload
104
- st.markdown("### 📤 Upload Waste Image")
105
- uploaded_file = st.file_uploader("Upload an image of a recyclable item", type=["png", "jpg", "jpeg"])
106
-
107
- if uploaded_file is not None:
108
- try:
109
- image = Image.open(uploaded_file).convert("RGB")
110
- st.image(image, caption="Uploaded Image", use_column_width=True)
111
-
112
- with st.spinner("Analyzing with AI model..."):
113
- class_name, confidence = predict(image, processor, model)
114
-
115
- st.success(f"**Predicted Material:** `{class_name}` \n**Confidence:** `{confidence:.2%}`")
116
-
117
- suggestion = get_suggestion(class_name)
118
- st.info(f"**Tip:** {suggestion}")
119
-
120
- except Exception as e:
121
- st.error(f"Something went wrong: {e}")
122
-
123
- # Expandable section to show class labels
124
- with st.expander("🔍 Show Model Classes"):
125
- st.write(model.config.id2label)
126
-
127
- st.markdown("---")
128
- st.caption("Made with 💚 for a sustainable future. | Hackathon 2025")
129
-
130
- # Run app
131
- if __name__ == "__main__":
132
- main()
 
 
 
 
1
+ import os
2
+ os.environ["TRANSFORMERS_CACHE"] = "./hf_cache" # Fix for cache permission issue
3
+
4
+ import streamlit as st
5
+ from PIL import Image
6
+ import random
7
+ import torch
8
+ from transformers import AutoImageProcessor, SiglipForImageClassification
9
+
10
+ # --- Constants ---
11
+ MODEL_NAME = "prithivMLmods/Recycling-Net-11"
12
+
13
+ # Sustainability Tips
14
+ TIPS = [
15
+ "Rinse containers before recycling to avoid contamination.",
16
+ "Avoid using plastic bags for recyclables use bins or boxes.",
17
+ "Compost your kitchen scraps instead of tossing them.",
18
+ "Recycle electronics only at designated e-waste centers.",
19
+ "Buy products made from recycled materials to close the loop.",
20
+ "Don’t recycle greasy pizza boxes compost or trash them.",
21
+ "Learn your local recycling rules – they vary by region.",
22
+ "Use reusable bags, bottles, and containers to reduce waste.",
23
+ "Donate old clothes and furniture instead of throwing them away.",
24
+ "Avoid single-use plastics whenever possible.",
25
+ ]
26
+
27
+ # Government recycling resources
28
+ GOVERNMENT_LINKS = {
29
+ "Pakistan": "https://environment.gov.pk/",
30
+ "India": "https://www.cpcb.nic.in/",
31
+ "China": "http://english.mee.gov.cn/",
32
+ "Japan": "https://www.env.go.jp/en/",
33
+ "USA": "https://www.epa.gov/recycle",
34
+ "UK": "https://www.gov.uk/recycling-collections",
35
+ "Canada": "https://www.canada.ca/en/services/environment/conservation/recycling.html",
36
+ "Germany": "https://www.bmu.de/en/topics/water-waste-soil/waste-management",
37
+ }
38
+
39
+ # --- Load Model ---
40
+ @st.cache_resource(show_spinner=False)
41
+ def load_model():
42
+ processor = AutoImageProcessor.from_pretrained(MODEL_NAME)
43
+ model = SiglipForImageClassification.from_pretrained(MODEL_NAME)
44
+ model.eval()
45
+ return processor, model
46
+
47
+ # --- Predict Function ---
48
+ def predict(image: Image.Image, processor, model):
49
+ inputs = processor(images=image, return_tensors="pt")
50
+ with torch.no_grad():
51
+ outputs = model(**inputs)
52
+ logits = outputs.logits
53
+ probs = torch.nn.functional.softmax(logits, dim=-1)
54
+ conf, idx = torch.max(probs, dim=-1)
55
+ class_name = model.config.id2label[idx.item()]
56
+ confidence = conf.item()
57
+ return class_name, confidence
58
+
59
+ # --- Suggestion Function ---
60
+ def get_suggestion(label: str) -> str:
61
+ tips = {
62
+ "aluminium": "Rinse and recycle aluminum cans. They are infinitely recyclable.",
63
+ "batteries": "Do not throw in the trash. Use proper e-waste collection centers.",
64
+ "cardboard": "Flatten and keep dry. Avoid greasy pizza boxes.",
65
+ "glass": "Rinse and remove lids. Separate by color if required.",
66
+ "hard plastic": "Check recycling codes. Clean before recycling.",
67
+ "paper": "Do not recycle shredded paper in curbside bins. Reuse or compost instead.",
68
+ "paper towel": "Compost if clean. Trash if soiled.",
69
+ "polystyrene": "Rarely accepted in curbside. Reuse or bring to special centers.",
70
+ "soft plastics": "Often require store drop-off. Don’t mix with other recyclables.",
71
+ "takeaway cups": "Check local rules. Many are lined and not recyclable curbside.",
72
+ }
73
+ return tips.get(label, "Please check your local rules for proper disposal of this item.")
74
+
75
+ # --- Streamlit App ---
76
+ def main():
77
+ st.set_page_config(page_title="♻️ Recycling Helper AI", layout="centered")
78
+ st.title("♻️ Recycling Helper AI")
79
+ st.subheader("An AI-powered app to identify recyclable materials and promote sustainability.")
80
+
81
+ st.markdown("---")
82
+
83
+ # Sidebar content
84
+ with st.sidebar:
85
+ st.header("📘 About This App")
86
+ st.markdown(
87
+ "This open-source app helps you identify recyclable materials from waste images "
88
+ "using a machine learning model. It promotes proper disposal and reduces contamination "
89
+ "in the recycling stream. Built for hackathons using Hugging Face + Streamlit."
90
+ )
91
+
92
+ st.markdown("---")
93
+ st.header("🌐 Recycling Resources")
94
+ st.markdown("For proper recycling and disposal of waste, refer to the following resources:")
95
+ for country, url in GOVERNMENT_LINKS.items():
96
+ st.markdown(f"- [{country}]({url})", unsafe_allow_html=True)
97
+
98
+ st.markdown("---")
99
+ st.header("🌱 Daily Sustainability Tip")
100
+ tip = random.choice(TIPS)
101
+ st.success(tip)
102
+
103
+ # Load the model
104
+ processor, model = load_model()
105
+
106
+ # File upload
107
+ st.markdown("### 📤 Upload Waste Image")
108
+ uploaded_file = st.file_uploader("Upload an image of a recyclable item", type=["png", "jpg", "jpeg"])
109
+
110
+ if uploaded_file is not None:
111
+ try:
112
+ image = Image.open(uploaded_file).convert("RGB")
113
+ st.image(image, caption="Uploaded Image", use_column_width=True)
114
+
115
+ with st.spinner("Analyzing with AI model..."):
116
+ class_name, confidence = predict(image, processor, model)
117
+
118
+ st.success(f"**Predicted Material:** `{class_name}` \n**Confidence:** `{confidence:.2%}`")
119
+
120
+ suggestion = get_suggestion(class_name)
121
+ st.info(f"**Tip:** {suggestion}")
122
+
123
+ except Exception as e:
124
+ st.error(f"Something went wrong during prediction: {e}")
125
+
126
+ # Optional: Show class labels
127
+ with st.expander("🔍 Show Model Classes"):
128
+ st.write(model.config.id2label)
129
+
130
+ st.markdown("---")
131
+ st.caption("Made with 💚 for a sustainable future | Hackathon 2025")
132
+
133
+ # Run app
134
+ if __name__ == "__main__":
135
+ main()