File size: 1,943 Bytes
60f2d73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import tensorflow as tf
from tensorflow.keras.applications import EfficientNetV2L
from tensorflow.keras.applications.efficientnet_v2 import preprocess_input, decode_predictions
import numpy as np
from PIL import Image

# Lazy loading to optimize memory usage
model = None

def load_model():
    """Load the EfficientNetV2L model only when needed."""
    global model
    if model is None:
        model = EfficientNetV2L(weights="imagenet")

def preprocess_image(image):
    """Preprocess the image for EfficientNetV2L model inference."""
    image = image.resize((480, 480))  # Resize for EfficientNetV2L
    image_array = np.array(image)  # Convert to NumPy array
    image_array = preprocess_input(image_array)  # Normalize input
    image_array = np.expand_dims(image_array, axis=0)  # Add batch dimension
    return image_array

def predict_image(image):
    """
    Process the uploaded image and return the top 3 predictions.
    """
    try:
        load_model()  # Ensure the model is loaded
        image_array = preprocess_image(image)  # Preprocess image
        predictions = model.predict(image_array)  # Get predictions
        decoded_predictions = decode_predictions(predictions, top=3)[0]

        # Format predictions as a dictionary (label -> confidence)
        return {label: float(confidence) for _, label, confidence in decoded_predictions}

    except Exception as e:
        return {"Error": str(e)}

# Create the Gradio interface
interface = gr.Interface(
    fn=predict_image,
    inputs=gr.Image(type="pil"),  # Accepts an image input
    outputs=gr.Label(num_top_classes=3),  # Shows top 3 predictions
    title="EfficientNetV2L Image Classifier",
    description="Upload an image, and the model will predict its content with high accuracy.",
    allow_flagging="never"  # Disable flagging to avoid unnecessary logs
)

# Launch the Gradio app
if __name__ == "__main__":
    interface.launch()