# -*- coding: utf-8 -*- """WebApp.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1zfkfRAvXz7HSYttTtBF19_Y2IfkHFxqK """ import tensorflow as tf import tensorflow_hub as hub import numpy as np from PIL import Image import gradio as gr # Load your trained model model = tf.keras.models.load_model('model.h5', custom_objects={'KerasLayer': hub.KerasLayer}) # Define the image size IMG_SIZE = 224 # Load class names from the text file with open('class_names.txt', 'r') as file: class_names = [line.strip() for line in file] # Define a function to preprocess the image def preprocess_image(image): img = tf.image.resize(image, (IMG_SIZE, IMG_SIZE)) img = img / 255.0 # Normalize pixel values to [0, 1] return img.numpy() # Define the prediction function def predict_image(img): img = Image.fromarray(img.astype('uint8'), 'RGB') img = preprocess_image(np.array(img)) img = np.expand_dims(img, axis=0) # Add batch dimension prediction = model.predict(img) predicted_class = np.argmax(prediction) confidence = np.max(prediction) class_name = class_names[predicted_class] if predicted_class < len(class_names) else "Unknown" return f"Class: {class_name}, Confidence: {confidence:.4f}" # Create Gradio interface iface = gr.Interface( fn=predict_image, # Prediction function inputs=gr.inputs.Image(shape=(IMG_SIZE, IMG_SIZE)), # Define input type and shape outputs="text", # Define output type live=True # Enable live mode for real-time predictions ) # Launch the interface iface.launch(share=True)