Spaces:
Sleeping
Sleeping
Yasiru Chamuditha commited on
Commit ·
3e4e43d
1
Parent(s): 94a52b2
initial commit
Browse files- app.py +82 -0
- class_indices.txt +3 -0
- garbage_classifier.h5 +3 -0
- requirements.txt +4 -0
app.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import numpy as np
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import tensorflow as tf
|
| 5 |
+
import logging
|
| 6 |
+
import os
|
| 7 |
+
|
| 8 |
+
# Set up logging to capture errors
|
| 9 |
+
logging.basicConfig(level=logging.INFO)
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
logger.info("Starting application initialization")
|
| 13 |
+
|
| 14 |
+
# Load class names from class_indices.txt
|
| 15 |
+
try:
|
| 16 |
+
logger.info("Loading class names from class_indices.txt")
|
| 17 |
+
with open("class_indices.txt", "r") as f:
|
| 18 |
+
class_names = [line.strip() for line in f.readlines() if line.strip()]
|
| 19 |
+
logger.info(f"Class names loaded: {class_names}")
|
| 20 |
+
except Exception as e:
|
| 21 |
+
logger.error(f"Failed to load class_indices.txt: {str(e)}")
|
| 22 |
+
raise Exception(f"Failed to load class_indices.txt: {str(e)}")
|
| 23 |
+
|
| 24 |
+
# Load the Keras .h5 model
|
| 25 |
+
try:
|
| 26 |
+
logger.info("Loading model: garbage_classifier.h5")
|
| 27 |
+
model = tf.keras.models.load_model("garbage_classifier.h5", compile=False)
|
| 28 |
+
logger.info("Model loaded successfully")
|
| 29 |
+
except Exception as e:
|
| 30 |
+
logger.error(f"Failed to load model: {str(e)}")
|
| 31 |
+
raise Exception(f"Failed to load model: {str(e)}")
|
| 32 |
+
|
| 33 |
+
def predict_image(image: Image.Image):
|
| 34 |
+
try:
|
| 35 |
+
logger.info("Processing image for prediction")
|
| 36 |
+
# Preprocess the image
|
| 37 |
+
img = image.convert("RGB").resize((128, 128))
|
| 38 |
+
arr = np.array(img).astype("float32") / 255.0
|
| 39 |
+
arr = np.expand_dims(arr, axis=0)
|
| 40 |
+
|
| 41 |
+
# Make prediction
|
| 42 |
+
preds = model.predict(arr)[0]
|
| 43 |
+
logger.info("Prediction completed")
|
| 44 |
+
|
| 45 |
+
# Get predicted class and confidence
|
| 46 |
+
pred_class_idx = np.argmax(preds)
|
| 47 |
+
pred_class = class_names[pred_class_idx]
|
| 48 |
+
confidence = float(preds[pred_class_idx])
|
| 49 |
+
|
| 50 |
+
# Format per-class probabilities
|
| 51 |
+
prob_text = "\n".join([f"{class_names[i]}: {float(preds[i]):.2f}" for i in range(len(class_names))])
|
| 52 |
+
|
| 53 |
+
# Return formatted output
|
| 54 |
+
output = f"Prediction\nClass: {pred_class}\nConfidence: {confidence:.2f}\n\nPer-class probabilities\n{prob_text}"
|
| 55 |
+
return output
|
| 56 |
+
except Exception as e:
|
| 57 |
+
logger.error(f"Error during prediction: {str(e)}")
|
| 58 |
+
return f"Error during prediction: {str(e)}"
|
| 59 |
+
|
| 60 |
+
# Create Gradio interface
|
| 61 |
+
logger.info("Initializing Gradio interface")
|
| 62 |
+
with gr.Blocks() as iface:
|
| 63 |
+
gr.Markdown("# ♻️ Garbage Classification Application")
|
| 64 |
+
gr.Markdown("Upload an image of garbage (plastic, organic, or metal):")
|
| 65 |
+
img_input = gr.Image(type="pil")
|
| 66 |
+
output = gr.Textbox(label="Prediction Result")
|
| 67 |
+
gr.Button("Classify").click(
|
| 68 |
+
fn=predict_image,
|
| 69 |
+
inputs=img_input,
|
| 70 |
+
outputs=output
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
# Queue the interface for serving (important for Spaces)
|
| 74 |
+
iface.queue(api_open=False) # Disable public API for simplicity
|
| 75 |
+
|
| 76 |
+
logger.info("Gradio interface queued and ready for serving")
|
| 77 |
+
|
| 78 |
+
# Block to keep the process alive (Spaces handles serving)
|
| 79 |
+
if __name__ == "__main__":
|
| 80 |
+
logger.info("Entering blocking mode for Spaces serving")
|
| 81 |
+
while True:
|
| 82 |
+
pass
|
class_indices.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
metal
|
| 2 |
+
organic
|
| 3 |
+
plastic
|
garbage_classifier.h5
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4939524ee92a9e43cf0f73e0bf2f5ffda76f626a037e0fc818c1daf755af811c
|
| 3 |
+
size 26340920
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio==5.46.0
|
| 2 |
+
numpy==1.26.4
|
| 3 |
+
Pillow==10.3.0
|
| 4 |
+
tensorflow==2.16.1
|