Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,129 +1,65 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import json
|
| 3 |
-
import numpy as np
|
| 4 |
-
from PIL import Image
|
| 5 |
import tensorflow as tf
|
| 6 |
from tensorflow.keras import layers, models, regularizers
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
| 8 |
import gradio as gr
|
| 9 |
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
# Config and class labels
|
| 13 |
-
# -----------------------
|
| 14 |
-
cfg = {}
|
| 15 |
if os.path.exists("config.json"):
|
| 16 |
with open("config.json") as f:
|
| 17 |
cfg = json.load(f)
|
| 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 |
-
kernel_regularizer=regularizers.l2(0.001)),
|
| 46 |
-
layers.Dropout(0.3),
|
| 47 |
-
layers.Dense(128, activation="relu",
|
| 48 |
-
kernel_regularizer=regularizers.l2(0.001)),
|
| 49 |
-
layers.Dropout(0.3),
|
| 50 |
-
layers.Dense(num_classes, activation="softmax")
|
| 51 |
-
])
|
| 52 |
-
return model
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
# -----------------------
|
| 56 |
-
# Load model or weights
|
| 57 |
-
# -----------------------
|
| 58 |
-
model = None
|
| 59 |
-
_loaded_full = False
|
| 60 |
-
|
| 61 |
-
# Prefer a full saved model if available
|
| 62 |
-
for fname in ("model.keras", "model.h5"):
|
| 63 |
-
if os.path.exists(fname):
|
| 64 |
-
model = tf.keras.models.load_model(fname, compile=False)
|
| 65 |
-
_loaded_full = True
|
| 66 |
-
print(f"Loaded full model from {fname}")
|
| 67 |
-
break
|
| 68 |
-
|
| 69 |
-
if model is None:
|
| 70 |
-
# Fallback: rebuild and load weights
|
| 71 |
-
model = build_model(num_classes)
|
| 72 |
-
weights_path = "model_weights.h5" if os.path.exists("model_weights.h5") else "model.weights.h5"
|
| 73 |
-
if os.path.exists(weights_path):
|
| 74 |
-
model.load_weights(weights_path)
|
| 75 |
-
print(f"Weights loaded from {weights_path}.")
|
| 76 |
-
else:
|
| 77 |
-
print("No model file found: expected model.keras/model.h5 or model_weights.h5/model.weights.h5.")
|
| 78 |
-
print("Current directory:", os.listdir())
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
# -----------------------
|
| 82 |
-
# Preprocessing
|
| 83 |
-
# -----------------------
|
| 84 |
-
def _to_rgb(img: Image.Image) -> Image.Image:
|
| 85 |
-
"""Force 3-channel RGB to avoid grayscale/RGBA issues."""
|
| 86 |
-
return img.convert("RGB")
|
| 87 |
-
|
| 88 |
-
def preprocess(image: Image.Image) -> np.ndarray:
|
| 89 |
-
"""
|
| 90 |
-
Resize to 224, EfficientNet preprocess, add batch dimension.
|
| 91 |
-
"""
|
| 92 |
-
image = _to_rgb(image).resize((224, 224), Image.BILINEAR)
|
| 93 |
-
x = np.asarray(image, dtype=np.float32)
|
| 94 |
-
x = preprocess_input(x) # correct scaling for EfficientNet
|
| 95 |
-
x = np.expand_dims(x, axis=0) # (1, 224, 224, 3)
|
| 96 |
-
return x
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
# -----------------------
|
| 100 |
-
# Inference
|
| 101 |
-
# -----------------------
|
| 102 |
def predict(image: Image.Image):
|
| 103 |
-
"""
|
| 104 |
-
Returns (label, confidence) for Gradio.
|
| 105 |
-
"""
|
| 106 |
x = preprocess(image)
|
| 107 |
-
preds = model.predict(x
|
| 108 |
-
class_idx = int(np.argmax(preds))
|
| 109 |
-
confidence = float(preds
|
| 110 |
-
return
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
# --------
|
| 116 |
interface = gr.Interface(
|
| 117 |
fn=predict,
|
| 118 |
inputs=gr.Image(type="pil", label="Upload an image"),
|
| 119 |
outputs=[
|
| 120 |
-
gr.Label(label="Predicted class"),
|
| 121 |
gr.Number(label="Confidence")
|
| 122 |
],
|
| 123 |
title="NeuRecAI - Material Classifier",
|
| 124 |
-
description=
|
| 125 |
-
"paper, or plastic.")
|
| 126 |
)
|
| 127 |
|
|
|
|
| 128 |
if __name__ == "__main__":
|
| 129 |
interface.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import tensorflow as tf
|
| 2 |
from tensorflow.keras import layers, models, regularizers
|
| 3 |
+
import json
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import numpy as np
|
| 6 |
+
import os
|
| 7 |
import gradio as gr
|
| 8 |
|
| 9 |
+
# ---- Load config if present ----
|
| 10 |
+
cfg = None
|
|
|
|
|
|
|
|
|
|
| 11 |
if os.path.exists("config.json"):
|
| 12 |
with open("config.json") as f:
|
| 13 |
cfg = json.load(f)
|
| 14 |
|
| 15 |
+
# ---- Class labels ----
|
| 16 |
+
class_names = ['battery', 'glass', 'metal', 'organic', 'paper', 'plastic']
|
| 17 |
+
|
| 18 |
+
# ---- Build model architecture ----
|
| 19 |
+
base_model = tf.keras.applications.EfficientNetB7(weights=None)
|
| 20 |
+
model = models.Sequential([
|
| 21 |
+
base_model,
|
| 22 |
+
layers.GlobalAveragePooling2D(),
|
| 23 |
+
layers.Dense(256, activation='relu', kernel_regularizer=regularizers.l2(0.001)),
|
| 24 |
+
layers.Dropout(0.3),
|
| 25 |
+
layers.Dense(128, activation='relu', kernel_regularizer=regularizers.l2(0.001)),
|
| 26 |
+
layers.Dropout(0.3),
|
| 27 |
+
layers.Dense(6, activation='softmax')
|
| 28 |
+
])
|
| 29 |
+
|
| 30 |
+
# ---- Load trained weights ----
|
| 31 |
+
model.load_weights("model.weights.h5")
|
| 32 |
+
|
| 33 |
+
# ---- Preprocess image ----
|
| 34 |
+
def preprocess(image: Image.Image):
|
| 35 |
+
image = image.resize((224, 224))
|
| 36 |
+
image = np.array(image) / 255.0
|
| 37 |
+
image = np.expand_dims(image, axis=0)
|
| 38 |
+
return image
|
| 39 |
+
|
| 40 |
+
# ---- Prediction function ----
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
def predict(image: Image.Image):
|
|
|
|
|
|
|
|
|
|
| 42 |
x = preprocess(image)
|
| 43 |
+
preds = model.predict(x)
|
| 44 |
+
class_idx = int(np.argmax(preds, axis=1)[0])
|
| 45 |
+
confidence = float(np.max(preds))
|
| 46 |
+
return {
|
| 47 |
+
"class": class_names[class_idx],
|
| 48 |
+
"confidence": confidence
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
# ---- Gradio interface ----
|
| 52 |
interface = gr.Interface(
|
| 53 |
fn=predict,
|
| 54 |
inputs=gr.Image(type="pil", label="Upload an image"),
|
| 55 |
outputs=[
|
| 56 |
+
gr.Label(num_top_classes=1, label="Predicted class"),
|
| 57 |
gr.Number(label="Confidence")
|
| 58 |
],
|
| 59 |
title="NeuRecAI - Material Classifier",
|
| 60 |
+
description="Upload an image to classify it as battery, glass, metal, organic, paper, or plastic."
|
|
|
|
| 61 |
)
|
| 62 |
|
| 63 |
+
# ---- Launch ----
|
| 64 |
if __name__ == "__main__":
|
| 65 |
interface.launch()
|