hb-setosys's picture
Create app.py
60f2d73 verified
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()