NeuRecAI / app.py
BunkerMinecraft's picture
Update app.py
43f4a1b verified
Raw History Blame Contribute Delete
2.09 kB
from huggingface_hub import hf_hub_download
import tensorflow as tf
import numpy as np
from PIL import Image, ImageOps
import gradio as gr
# -----------------------
# CONFIG
# -----------------------
MODEL_REPO_ID = "BunkerMinecraft/neurecaiv2" # <-- change this
MODEL_FILENAME = "keras_model.h5"
LABELS_FILENAME = "labels.txt"
IMAGE_SIZE = (224, 224) # TM fixed size
# -----------------------
# DOWNLOAD MODEL + LABELS
# -----------------------
model_path = hf_hub_download(
repo_id=MODEL_REPO_ID,
filename=MODEL_FILENAME,
repo_type="model"
)
labels_path = hf_hub_download(
repo_id=MODEL_REPO_ID,
filename=LABELS_FILENAME,
repo_type="model"
)
# Load the Teachable Machine Keras .h5 model
model = tf.keras.models.load_model(model_path, compile=False)
print(f"Loaded model: {model_path}")
# Load labels
with open(labels_path, "r") as f:
class_names = [line.strip() for line in f.readlines()]
print("Loaded labels:", class_names)
# -----------------------
# PREPROCESS FUNCTION (matches TM)
# -----------------------
def preprocess(img: Image.Image):
img = img.convert("RGB")
img = ImageOps.fit(img, IMAGE_SIZE, Image.Resampling.LANCZOS)
image_array = np.asarray(img).astype(np.float32)
# TM normalization:
normalized = (image_array / 127.5) - 1.0
return np.expand_dims(normalized, axis=0)
# -----------------------
# PREDICT FUNCTION
# -----------------------
def predict(image: Image.Image):
x = preprocess(image)
preds = model.predict(x, verbose=0)[0]
idx = int(np.argmax(preds))
conf = float(preds[idx])
return class_names[idx], conf
# -----------------------
# UI (Gradio)
# -----------------------
interface = gr.Interface(
fn=predict,
inputs=gr.Image(type="pil", label="Upload an image"),
outputs=[gr.Label(label="Predicted class"), gr.Number(label="Confidence")],
title="Teachable Machine Classifier",
description="Upload an image to classify using your keras_Model.h5 Teachable Machine model."
)
if __name__ == "__main__":
interface.launch()