MyEnny commited on
Commit
31fcce1
·
verified ·
1 Parent(s): d617fcc

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +131 -0
app.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ from PIL import Image
4
+ from tensorflow.keras.models import load_model
5
+ from tensorflow.keras.applications.efficientnet import preprocess_input as efficientnet_preprocess
6
+ import pandas as pd
7
+ import os
8
+ from datetime import datetime
9
+
10
+ # Waste classes
11
+ class_names = ['BATTERIES', 'CLOTHES', 'E-WASTE', 'GLASS', 'LIGHT-BULBS', 'METAL', 'ORGANIC', 'PAPER', 'PLASTIC']
12
+
13
+ # Advice dictionary
14
+ waste_advice = {
15
+ "PAPER": "Recycle clean paper. Avoid recycling greasy or food-stained paper.",
16
+ "CLOTHES": "Donate if usable. Otherwise, check textile recycling centres.",
17
+ "BATTERIES": "Take to hazardous waste collection or battery drop-off locations.",
18
+ "GLASS": "Rinse and recycle glass containers separately from ceramics.",
19
+ "PLASTIC": "Recycle plastics labelled with numbers 1 and 2. Check local rules for others.",
20
+ "ORGANIC": "Compost organic waste like food scraps and garden waste.",
21
+ "LIGHT-BULBS": "Take to a special collection point for bulbs and fluorescents.",
22
+ "E-WASTE": "Recycle at designated e-waste centres or electronics stores.",
23
+ "METAL": "Recycle metals in designated metal bins. Rinse before disposal."
24
+ }
25
+
26
+ # Load model with error handling
27
+ try:
28
+ model = load_model("model_efnet.keras")
29
+ print("Model loaded successfully!")
30
+ except FileNotFoundError:
31
+ print("Error: 'model_efnet.keras' not found. Please upload the model file.")
32
+ model = None
33
+
34
+ img_size = (224, 224)
35
+
36
+ # CSV for logging predictions and feedback
37
+ log_file = "prediction_log.csv"
38
+ if not os.path.exists(log_file):
39
+ pd.DataFrame(columns=["Timestamp", "Prediction", "Confidence", "Feedback"]).to_csv(log_file, index=False)
40
+
41
+ # Prediction function
42
+ def predict(image):
43
+ if model is None:
44
+ return "Error: Model not loaded.", "", None, None, {}
45
+
46
+ img = image.convert("RGB").resize(img_size)
47
+ img_array = np.array(img)
48
+ img_array = efficientnet_preprocess(img_array)
49
+ img_array = np.expand_dims(img_array, axis=0)
50
+
51
+ prediction = model.predict(img_array)[0]
52
+ predicted_index = np.argmax(prediction)
53
+ predicted_class = class_names[predicted_index]
54
+ confidence = prediction[predicted_index]
55
+
56
+ result = f" {predicted_class} ( Probability {confidence:.2f})"
57
+ probabilities = {class_names[i]: float(prediction[i]) for i in range(len(class_names))}
58
+ advice = waste_advice.get(predicted_class, "No advice available.")
59
+
60
+ return result, advice, predicted_class, confidence, probabilities
61
+
62
+ # Feedback function
63
+ def save_feedback(predicted_class, confidence, feedback):
64
+ timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
65
+ df = pd.read_csv(log_file)
66
+ new_row = pd.DataFrame({
67
+ "Timestamp": [timestamp],
68
+ "Prediction": [predicted_class],
69
+ "Confidence": [round(confidence, 2)],
70
+ "Feedback": [feedback]
71
+ })
72
+ df = pd.concat([df, new_row], ignore_index=True)
73
+ df.to_csv(log_file, index=False)
74
+ return "Feedback saved. Thank you!"
75
+
76
+ # Handle feedback visibility
77
+ def handle_feedback(feedback):
78
+ if feedback == "👎":
79
+ return gr.update(visible=True), gr.update(visible=True), ""
80
+ else:
81
+ return gr.update(visible=False), gr.update(visible=False), "✅ Thank you"
82
+
83
+ # Clear all
84
+ def clear_all():
85
+ return None, "", "", None, None, {}, None, gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
86
+
87
+ # Gradio UI
88
+ with gr.Blocks() as demo:
89
+ gr.Markdown("## ♻️ Waste Management Classifier")
90
+
91
+ with gr.Row():
92
+ image_input = gr.Image(label="Upload or Use Webcam", sources=["upload", "webcam"], type="pil")
93
+ with gr.Column():
94
+ result = gr.Label(label="Prediction")
95
+ advice_output = gr.Textbox(label="Waste Disposal Advice", lines=2)
96
+
97
+ pred_class = gr.State()
98
+ pred_conf = gr.State()
99
+ probabilities = gr.State()
100
+
101
+ with gr.Row():
102
+ predict_button = gr.Button("Predict")
103
+ clear_btn = gr.Button("Clear")
104
+
105
+ predict_button.click(
106
+ fn=predict,
107
+ inputs=image_input,
108
+ outputs=[result, advice_output, pred_class, pred_conf, probabilities]
109
+ )
110
+
111
+ gr.Markdown("### How accurate was the prediction?")
112
+ with gr.Row():
113
+ thumbs = gr.Radio(["👍", "👎"], label="Prediction Status")
114
+ feedback_box = gr.Textbox(lines=2, placeholder="What should the model have predicted?", visible=False, label="Your Feedback")
115
+ submit_feedback = gr.Button("Submit Feedback", visible=False)
116
+ feedback_ack = gr.Textbox(visible=False, label="", interactive=False)
117
+
118
+ clear_btn.click(
119
+ fn=clear_all,
120
+ outputs=[image_input, result, advice_output, pred_class, pred_conf, probabilities, thumbs, feedback_box, submit_feedback, feedback_ack]
121
+ )
122
+ thumbs.change(
123
+ fn=handle_feedback,
124
+ inputs=[thumbs],
125
+ outputs=[feedback_box, submit_feedback, feedback_ack]
126
+ )
127
+ submit_feedback.click(
128
+ fn=save_feedback,
129
+ inputs=[pred_class, pred_conf, feedback_box],
130
+ outputs=feedback_ack
131
+ )