aa / app.py
bosayama's picture
Update app.py
45990d1 verified
import gradio as gr
import tensorflow as tf
from tensorflow.keras.preprocessing import image
import numpy as np
# Load the Teachable Machine Image Model
model_url = "https://teachablemachine.withgoogle.com/models/ZPfAhDYCh/"
model = tf.keras.models.load_model(model_url + "model.json")
# Function to preprocess the image before making predictions
def preprocess_image(img):
img = image.img_to_array(img)
img = np.expand_dims(img, axis=0)
img /= 255.0 # Normalize pixel values to be between 0 and 1
return img
# Function to make predictions using the loaded model
def predict_image(img):
img = preprocess_image(img)
prediction = model.predict(img)
return {class_name: float(prediction[0][i]) for i, class_name in enumerate(classes)}
# Fetch class labels from metadata.json
metadata_url = model_url + "metadata.json"
metadata = tf.keras.utils.get_file("metadata.json", metadata_url)
classes = tf.keras.utils.get_file("classes.txt", metadata_url.replace("metadata.json", "classes.txt")).read().splitlines()
# Create Gradio interface
iface = gr.Interface(fn=predict_image, inputs="image", outputs="label", live=True, capture_session=True)
# Launch Gradio interface
iface.launch()