LeemahLee commited on
Commit
3665fd0
·
verified ·
1 Parent(s): 1572bb3
Files changed (1) hide show
  1. app.py +0 -227
app.py CHANGED
@@ -8,23 +8,8 @@ from datetime import datetime
8
  import csv
9
  import os
10
  from huggingface_hub import hf_hub_download
11
- # import zipfile
12
 
13
 
14
- # # Step 1: Download the ZIP file from your Hugging Face repo
15
- # zip_path = hf_hub_download(
16
- # repo_id="LeemahLee/recycle", # Your model repo ID
17
- # filename="efficientnet_finetuned_2.keras" # Make sure this is the exact file name
18
- # )
19
-
20
- # # Step 2: Unzip only if not already extracted
21
- # if not os.path.exists("recycle_model_tf"):
22
- # with zipfile.ZipFile(zip_path, "r") as zip_ref:
23
- # zip_ref.extractall("recycle_model_tf")
24
-
25
- # Step 3: Load the model from the unzipped directory
26
- # model = load_model("recycle_model_tf/content/recycle_model_tf")
27
-
28
  model_path = hf_hub_download(
29
  repo_id="LeemahLee/recycle",
30
  filename="recycle_efficientnet_finetuned_2.keras"
@@ -32,212 +17,6 @@ model_path = hf_hub_download(
32
 
33
  model = load_model(model_path)
34
 
35
- # model = load_model("recycle/efficientnet_finetuned_2.keras")
36
- # print("✅ Model loaded successfully.")
37
- # print(model.summary()) # This will print the model architecture to confirm it's loaded.
38
-
39
-
40
- # # Class labels
41
- # class_names = ['batteries', 'clothes', 'e-waste', 'glass', 'light bulbs', 'metal', 'organic', 'paper', 'plastic']
42
-
43
- # # Descriptions
44
- # descriptions = {
45
- # 'batteries': 'Hazardous waste. Recycle at battery collection points.',
46
- # 'clothes': 'Reusable or recyclable textiles. Donate or use textile recycling bins.',
47
- # 'e-waste': 'Electronic waste. Contains toxic components. Use certified e-waste recyclers.',
48
- # 'glass': 'Non-biodegradable. Place in glass recycling containers.',
49
- # 'light bulbs': 'May contain mercury. Dispose at special light bulb collection points.',
50
- # 'metal': 'Recyclable material. Sort into metal recycling containers.',
51
- # 'organic': 'Biodegradable. Compost or dispose in organic waste bins.',
52
- # 'paper': 'Recyclable if clean. Place in paper recycling bins.',
53
- # 'plastic': 'Non-biodegradable. Sort into plastic recycling bins.'
54
- # }
55
-
56
- # # Sample images
57
- # sample_images = [
58
- # "sample_data/10537723_web1_M-Light-Bulb-EDH-180212.jpg",
59
- # "sample_data/bag-full-plastic-waste-bottle-plastic-ground-bag-full-plastic-waste-bottle-collect-around-river-145777987.jpg",
60
- # "sample_data/assorted-clothes-isolated-heap-colorful-white-36145930.jpg",
61
- # "sample_data/aa-batteries-energy-household-appliances-battery-recycling-used-alkaline-batteries-aa-size-format-207672475.jpg",
62
- # "sample_data/banana-peel-white-background-composting-organic-waste-banana-peel-white-background-composting-organic-waste-210728827.jpg"
63
-
64
- # ]
65
-
66
- # # Feedback log file
67
- # FEEDBACK_FILE = "user_feedback.csv"
68
-
69
- # # Prediction logic
70
- # # def predict(img):
71
- # # try:
72
- # # def predict(img):
73
- # # try:
74
- # # if img is None:
75
- # # return "❌ No image uploaded.", "", 0.0, ""
76
-
77
- # # img = img.convert("RGB")
78
- # # img = img.resize((224, 224))
79
- # # img_array = image.img_to_array(img)
80
- # # img_array = np.expand_dims(img_array, axis=0)
81
- # # img_array = preprocess_input(img_array)
82
-
83
- # # predictions = model.predict(img_array)
84
- # # predicted_index = np.argmax(predictions[0])
85
- # # predicted_label = class_names[predicted_index]
86
- # # confidence = float(np.max(predictions[0]))
87
- # # advice = descriptions[predicted_label]
88
-
89
- # # result_text = f"{predicted_label.upper()} ({confidence*100:.2f}%)\n\n{advice}"
90
- # # if confidence < 0.50:
91
- # # result_text += "\n\n⚠️ Low confidence. Try a clearer image or better lighting."
92
-
93
- # # return result_text, predicted_label, confidence, advice
94
- # # except Exception:
95
- # # return "❌ No image detected. Please upload or take a photo.", "", 0.0, ""
96
-
97
-
98
- # # def predict(img):
99
- # # try:
100
- # # if img is None:
101
- # # print("❌ No image received.")
102
- # # return "❌ No image uploaded.", "", 0.0, ""
103
-
104
- # # print("✅ Image received.")
105
- # # img = img.convert("RGB")
106
- # # img = img.resize((224, 224))
107
- # # img_array = image.img_to_array(img)
108
- # # img_array = np.expand_dims(img_array, axis=0)
109
- # # img_array = preprocess_input(img_array)
110
-
111
- # # print("✅ Image preprocessed. Shape:", img_array.shape)
112
-
113
- # # predictions = model.predict(img_array)
114
- # # print("✅ Model prediction completed:", predictions)
115
-
116
- # # predicted_index = np.argmax(predictions[0])
117
- # # predicted_label = class_names[predicted_index]
118
- # # confidence = float(np.max(predictions[0]))
119
- # # advice = descriptions[predicted_label]
120
-
121
- # # result_text = f"{predicted_label.upper()} ({confidence*100:.2f}%)\n\n{advice}"
122
- # # if confidence < 0.50:
123
- # # result_text += "\n\n⚠️ Low confidence. Try a clearer image or better lighting."
124
-
125
- # # return result_text, predicted_label, confidence, advice
126
-
127
- # # except Exception as e:
128
- # # print("❌ Error during prediction:", str(e))
129
- # # return "❌ Error during prediction.", "", 0.0, ""
130
-
131
- # def predict(img):
132
- # try:
133
- # if img is None:
134
- # return "❌ No image uploaded.", "", 0.0, ""
135
-
136
- # # Preprocess image
137
- # img = img.convert("RGB")
138
- # img = img.resize((224, 224))
139
- # img_array = image.img_to_array(img)
140
- # img_array = np.expand_dims(img_array, axis=0)
141
- # img_array = preprocess_input(img_array)
142
- # input_tensor = tf.convert_to_tensor(img_array, dtype=tf.float32)
143
-
144
- # # Use the model's serving function for inference
145
- # infer = model.signatures["serving_default"]
146
- # output = infer(input_tensor)
147
-
148
- # # Get the prediction from the output dictionary
149
- # predictions = list(output.values())[0].numpy()
150
- # predicted_index = np.argmax(predictions[0])
151
- # predicted_label = class_names[predicted_index]
152
- # confidence = float(np.max(predictions[0]))
153
- # advice = descriptions[predicted_label]
154
-
155
- # result_text = f"{predicted_label.upper()} ({confidence*100:.2f}%)\n\n{advice}"
156
- # if confidence < 0.50:
157
- # result_text += "\n\n⚠️ Low confidence. Try a clearer image or better lighting."
158
-
159
- # return result_text, predicted_label, confidence, advice
160
- # except Exception as e:
161
- # return f"❌ Prediction error: {str(e)}", "", 0.0, ""
162
-
163
-
164
-
165
- # # Save feedback
166
- # def save_feedback(label, confidence, advice, correct):
167
- # timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
168
- # file_exists = os.path.isfile(FEEDBACK_FILE)
169
-
170
- # with open(FEEDBACK_FILE, mode="a", newline="", encoding="utf-8") as file:
171
- # writer = csv.writer(file)
172
- # if not file_exists:
173
- # writer.writerow(["timestamp", "predicted_label", "confidence_percentage", "advice", "correct_prediction"])
174
- # writer.writerow([timestamp, label, f"{confidence*100:.2f}%", advice, correct])
175
- # return "✅ Feedback received! Thanks for helping us improve."
176
-
177
- # # 🚫 No extra background styles here
178
- # with gr.Blocks() as demo:
179
- # gr.Markdown("# ♻️ Waste Classifier")
180
- # gr.Markdown("Upload or take a photo of waste to classify it and receive disposal guidance.")
181
-
182
- # with gr.Row():
183
- # img_input = gr.Image(
184
- # label="📸 Take or Upload a Photo",
185
- # type="pil",
186
- # sources=["upload", "webcam"],
187
- # streaming=False
188
- # )
189
- # output_text = gr.Textbox(label="Prediction & Advice", lines=5)
190
-
191
- # predicted_label_state = gr.State()
192
- # confidence_state = gr.State()
193
- # advice_state = gr.State()
194
-
195
- # def handle_prediction(img):
196
- # text, label, confidence, advice = predict(img)
197
- # return text, label, confidence, advice
198
-
199
- # btn = gr.Button("🔍 Classify")
200
- # btn.click(
201
- # fn=handle_prediction,
202
- # inputs=img_input,
203
- # outputs=[output_text, predicted_label_state, confidence_state, advice_state]
204
- # )
205
-
206
- # gr.Markdown("### 📝 Was this prediction correct?")
207
- # feedback_status = gr.Textbox(label="", interactive=False)
208
-
209
- # with gr.Row():
210
- # yes_btn = gr.Button("👍 Yes")
211
- # no_btn = gr.Button("👎 No")
212
-
213
- # yes_btn.click(
214
- # fn=lambda label, conf, adv: save_feedback(label, conf, adv, "yes"),
215
- # inputs=[predicted_label_state, confidence_state, advice_state],
216
- # outputs=feedback_status
217
- # )
218
-
219
- # no_btn.click(
220
- # fn=lambda label, conf, adv: save_feedback(label, conf, adv, "no"),
221
- # inputs=[predicted_label_state, confidence_state, advice_state],
222
- # outputs=feedback_status
223
- # )
224
-
225
- # gr.Markdown("### 🌍 Try with Sample Images")
226
- # gr.Gallery(
227
- # value=sample_images,
228
- # label="Sample Waste Images",
229
- # columns=5,
230
- # object_fit="contain",
231
- # height=230 ,
232
- # interactive = False
233
- # )
234
-
235
- # gr.Markdown("**Note:** All predictions are currently in English. Multilingual support coming soon!")
236
-
237
- # demo.launch()
238
-
239
-
240
-
241
  # Class labels
242
  class_names = ['batteries', 'clothes', 'e-waste', 'glass', 'light blubs', 'metal', 'organic', 'paper', 'plastic']
243
 
@@ -256,12 +35,6 @@ descriptions = {
256
 
257
  # Sample images
258
  sample_images = [
259
- # "sample_data/10537723_web1_M-Light-Bulb-EDH-180212.jpg",
260
- # "sample_data/458-4583586_cardboard-recycling-png-paper-waste-clipart-transparent-png.png",
261
- # "sample_data/assorted-clothes-isolated-heap-colorful-white-36145930.jpg",
262
- # "sample_data/aa-batteries-energy-household-appliances-battery-recycling-used-alkaline-batteries-aa-size-format-207672475.jpg",
263
- # "sample_data/banana-peel-white-background-composting-organic-waste-banana-peel-white-background-composting-organic-waste-210728827.jpg"
264
-
265
  "sample_data/10537723_web1_M-Light-Bulb-EDH-180212.jpg",
266
  "sample_data/bag-full-plastic-waste-bottle-plastic-ground-bag-full-plastic-waste-bottle-collect-around-river-145777987.jpg",
267
  "sample_data/assorted-clothes-isolated-heap-colorful-white-36145930.jpg",
 
8
  import csv
9
  import os
10
  from huggingface_hub import hf_hub_download
 
11
 
12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  model_path = hf_hub_download(
14
  repo_id="LeemahLee/recycle",
15
  filename="recycle_efficientnet_finetuned_2.keras"
 
17
 
18
  model = load_model(model_path)
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  # Class labels
21
  class_names = ['batteries', 'clothes', 'e-waste', 'glass', 'light blubs', 'metal', 'organic', 'paper', 'plastic']
22
 
 
35
 
36
  # Sample images
37
  sample_images = [
 
 
 
 
 
 
38
  "sample_data/10537723_web1_M-Light-Bulb-EDH-180212.jpg",
39
  "sample_data/bag-full-plastic-waste-bottle-plastic-ground-bag-full-plastic-waste-bottle-collect-around-river-145777987.jpg",
40
  "sample_data/assorted-clothes-isolated-heap-colorful-white-36145930.jpg",