Spaces:
Runtime error
Runtime error
File size: 2,094 Bytes
d1ba352 8362209 0933310 b82a801 ff6148b b82a801 de8e670 43f4a1b b82a801 d1ba352 b82a801 0933310 b82a801 0933310 b82a801 d1ba352 b82a801 436fc42 b82a801 ed74430 b82a801 ff6148b b82a801 436fc42 ed74430 b82a801 ff6148b 436fc42 b82a801 ff6148b 436fc42 | 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 71 72 73 74 75 76 77 78 79 80 | 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()
|