trs's picture
Update app.py
73076fa verified
Raw History Blame
2.55 kB
import gradio as gr
import cv2
import numpy as np
from transformers import TFAutoModelForImageClassification, AutoTokenizer
# Define class names corresponding to your dataset
class_names = ["Ajloun Castle", "Jeresh", "Petra", "Roman amphitheater", "Umm_Qais", "Wadi_Rum"] # Replace with your actual class names
# Define the Hugging Face Model Hub names for your models
resnet_model_name = './resnet50-saved-model-79-val_acc-1.00.hdf5'
efficientnet_model_name = './efficientnet-saved-model-06-val_acc-0.98.hdf5'
vggnet_model_name = './vgg_16_-saved-model-89-acc-0.93.hdf5'
inceptionv3_model_name = './inceptionv3_-saved-model-59-val_accuracy-0.94.hdf5'
# Load models from Hugging Face Model Hub
tokenizer = AutoTokenizer.from_pretrained
resnet_model = TFAutoModelForImageClassification.from_pretrained(resnet_model_name)
efficientnet_model = TFAutoModelForImageClassification.from_pretrained(efficientnet_model_name)
vggnet_model = TFAutoModelForImageClassification.from_pretrained(vggnet_model_name)
inceptionv3_model = TFAutoModelForImageClassification.from_pretrained(inceptionv3_model_name)
# Define the classify_image function
def classify_image(img, model_choice):
try:
img = cv2.resize(img, (150, 150))
img = np.expand_dims(img, axis=0)
img = img.astype(np.float32) / 255.0
if model_choice == "ResNet":
inputs = tokenizer(images=img, return_tensors="tf")
predictions = resnet_model(**inputs).logits
elif model_choice == "EfficientNet":
inputs = tokenizer(images=img, return_tensors="tf")
predictions = efficientnet_model(**inputs).logits
elif model_choice == "VGGNet":
inputs = tokenizer(images=img, return_tensors="tf")
predictions = vggnet_model(**inputs).logits
elif model_choice == "InceptionV3":
inputs = tokenizer(images=img, return_tensors="tf")
predictions = inceptionv3_model(**inputs).logits
else:
return "Invalid model choice"
class_idx = np.argmax(predictions[0])
class_name = class_names[class_idx]
return f"Predicted class using {model_choice}: {class_name}"
except Exception as e:
return f"Error: {str(e)}"
# Create a Gradio interface with a dropdown for model selection
iface = gr.Interface(
fn=classify_image,
inputs=["image", gr.Dropdown(["ResNet", "EfficientNet", "VGGNet", "InceptionV3"], label="Select Model")],
outputs="text",
live=True
)
# Launch the Gradio interface
iface.launch()