File size: 2,319 Bytes
34f0dc8
 
c1a7e1d
34f0dc8
c1a7e1d
203b6f8
32448f7
 
 
34f0dc8
32448f7
f8e17cc
34f0dc8
 
32448f7
 
 
 
 
 
 
 
203b6f8
f8e17cc
 
 
94d5bed
 
34f0dc8
 
c1a7e1d
203b6f8
 
c1a7e1d
 
32448f7
 
 
 
 
 
 
 
 
 
 
 
203b6f8
 
 
 
 
 
 
c1a7e1d
203b6f8
 
32448f7
f8e17cc
32448f7
f8e17cc
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import gradio as gr
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.image import img_to_array
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import csv
import os
from datetime import datetime

# Load model
model = load_model("waste_classification(Mobilenetv2).h5", compile=False)
class_names = ['cardboard', 'glass', 'metal', 'paper', 'plastic', 'trash']

# CSV header
csv_file = "predictions.csv"
if not os.path.exists(csv_file):
    with open(csv_file, mode='w', newline='') as file:
        writer = csv.writer(file)
        writer.writerow(["timestamp", "predicted_class", "confidence", "probabilities", "source"])

# Prediction + save to CSV
def predict_with_chart(image):
    if image is None:
        return "No image received", None

    image = image.resize((224, 224))
    img_array = img_to_array(image) / 255.0
    img_array = np.expand_dims(img_array, axis=0)

    prediction = model.predict(img_array)[0]
    pred_index = np.argmax(prediction)
    pred_label = class_names[pred_index]
    confidence = float(np.max(prediction))

    # Log prediction to CSV
    with open(csv_file, mode='a', newline='') as file:
        writer = csv.writer(file)
        writer.writerow([
            datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            pred_label,
            round(confidence, 4),
            [round(p, 4) for p in prediction.tolist()],
            "upload_or_webcam"
        ])

    # Plot class probabilities
    fig, ax = plt.subplots(figsize=(6, 4))
    ax.bar(class_names, prediction, color='skyblue')
    ax.set_ylabel('Probability')
    ax.set_ylim(0, 1)
    ax.set_title('Class Probabilities')
    plt.xticks(rotation=45)
    plt.tight_layout()

    return f"Prediction: {pred_label} ({confidence*100:.1f}%)", fig

# Gradio UI
with gr.Blocks() as demo:
    gr.Markdown("## 🗑️ Waste Classifier — Upload or Webcam\nAutomatically logs predictions to CSV.")
    with gr.Row():
        image_input = gr.Image(type="pil", label="Upload or Webcam (click camera icon)")
    with gr.Row():
        label_output = gr.Textbox(label="Predicted Class")
        plot_output = gr.Plot(label="Class Probability Chart")

    image_input.change(fn=predict_with_chart, inputs=image_input, outputs=[label_output, plot_output])

demo.launch()