|
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 |
|
|
|
|
|
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)) |
|
image_array = np.array(image) |
|
image_array = preprocess_input(image_array) |
|
image_array = np.expand_dims(image_array, axis=0) |
|
return image_array |
|
|
|
def predict_image(image): |
|
""" |
|
Process the uploaded image and return the top 3 predictions. |
|
""" |
|
try: |
|
load_model() |
|
image_array = preprocess_image(image) |
|
predictions = model.predict(image_array) |
|
decoded_predictions = decode_predictions(predictions, top=3)[0] |
|
|
|
|
|
return {label: float(confidence) for _, label, confidence in decoded_predictions} |
|
|
|
except Exception as e: |
|
return {"Error": str(e)} |
|
|
|
|
|
interface = gr.Interface( |
|
fn=predict_image, |
|
inputs=gr.Image(type="pil"), |
|
outputs=gr.Label(num_top_classes=3), |
|
title="EfficientNetV2L Image Classifier", |
|
description="Upload an image, and the model will predict its content with high accuracy.", |
|
allow_flagging="never" |
|
) |
|
|
|
|
|
if __name__ == "__main__": |
|
interface.launch() |
|
|