File size: 1,709 Bytes
b981a4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# -*- coding: utf-8 -*-
"""WebApp.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1zfkfRAvXz7HSYttTtBF19_Y2IfkHFxqK
"""

!pip install gradio

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('/content/model.h5', custom_objects={'KerasLayer': hub.KerasLayer})

# Define the image size
IMG_SIZE = 224

# Load class names from the text file
with open('/content/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)

!pip freeze > requirements.txt