Spaces:
Runtime error
Runtime error
Update app.py
Browse files1234234556789101112131415161718197891011241213141516172829181931323334202122232425263637383940414243444527282930473132334950513435363738394041424344455354555657585960616263646566676869707172737446474849507677785152535455565758808182838485868759606162639293646566959697989967import numpy as npimport osimport cv2import gradio as grfrom transformers import AutoTokenizer, TFAutoModelForImageClassificationimport tensorflow as tffrom PIL import Imageimport onnxruntime as ort # Make sure to install onnxruntime (pip install onnxruntime)import onnxruntime as ort
# Load the pre-trained modelsefficientnet_model = TFAutoModelForImageClassification.from_pretrained("efficientnet/b0")resnet_model = TFAutoModelForImageClassification.from_pretrained("resnet50")vggnet_model = TFAutoModelForImageClassification.from_pretrained("vgg16")inceptionv3_model = TFAutoModelForImageClassification.from_pretrained("inception_v3")
# Load the corresponding tokenizersefficientnet_tokenizer = AutoTokenizer.from_pretrained("efficientnet/b0")resnet_tokenizer = AutoTokenizer.from_pretrained("resnet50")vggnet_tokenizer = AutoTokenizer.from_pretrained("vgg16")inceptionv3_tokenizer = AutoTokenizer.from_pretrained("inception_v3")
# ONNX modelsonnx_efficientnet_path = './Models_onnx/efficientnet.onnx'#onnx_inception_path = './Models_onnx/inceptionv3.onnx'onnx_vggnet_path = './Models_onnx/vgg_16.onnx'onnx_resnet_path = './Models_onnx/resnet50.onnx'
onnx_efficientnet_model = ort.InferenceSession(onnx_efficientnet_path)# Uncomment or remove the following line based on your needs# onnx_inception_model = ort.InferenceSession(onnx_inception_path)onnx_vggnet_model = ort.InferenceSession(onnx_vggnet_path)onnx_resnet_model = ort.InferenceSession(onnx_resnet_path)onnx_efficientnet_model = ort.InferenceSession(onnx_efficientnet_path)
# Define class names corresponding to your datasetclass_names = ["Ajloun Castle", "Jeresh", "Petra", "Roman amphitheater", "Umm_Qais", "Wadi_Rum"] # Replace with your actual class namesclass_names = ["Ajloun Castle", "Jeresh", "Petra", "Roman amphitheater", "Umm_Qais", "Wadi_Rum"]
# Define the tokenize_and_preprocess functiondef tokenize_and_preprocess(img, model_choice): img = Image.fromarray((img * 255).astype('uint8')) img = img.resize((224, 224))def classify_image(img, model_choice): def preprocess_input(img, model): # Placeholder for preprocessing steps # Replace with actual preprocessing steps based on the model processed_img = img / 255.0 return processed_img
if model_choice == "ResNet": inputs = resnet_tokenizer(img, return_tensors="tf") elif model_choice == "EfficientNet": inputs = efficientnet_tokenizer(img, return_tensors="tf") elif model_choice == "VGGNet": inputs = vggnet_tokenizer(img, return_tensors="tf") elif model_choice == "InceptionV3": inputs = inceptionv3_tokenizer(img, return_tensors="tf") else: return "Invalid model choice" # Keep the input size as (150, 150) since your model expects that size input_size = (150, 150) img_resized = cv2.resize(img, input_size)
return inputs # Preprocess the input image img_preprocessed = preprocess_input(img_resized, model_choice)
# Define the classify_image functiondef classify_image(img, model_choice): inputs = tokenize_and_preprocess(img, model_choice) # Run inference based on the selected model model = { "ResNet": onnx_resnet_model, "EfficientNet": onnx_efficientnet_model, "VGGNet": onnx_vggnet_model, #"InceptionV3": onnx_inception_model # Uncomment or remove based on your needs }[model_choice]
predictions = model.run(None, {"input": img_preprocessed}) class_idx = np.argmax(predictions) class_name = class_names[class_idx]
if model_choice == "ResNet": outputs = resnet_model(**inputs) elif model_choice == "EfficientNet": outputs = efficientnet_model(**inputs) elif model_choice == "VGGNet": outputs = vggnet_model(**inputs) elif model_choice == "InceptionV3": outputs = inceptionv3_model(**inputs) elif model_choice == "ONNX_ResNet": # Modify this part to use the ONNX model for prediction # Example: predictions = onnx_resnet_model.run(None, {'input_name': inputs['input_name'].numpy()}) pass elif model_choice == "ONNX_EfficientNet": # Modify this part to use the ONNX model for prediction # Example: predictions = onnx_efficientnet_model.run(None, {'input_name': inputs['input_name'].numpy()}) pass elif model_choice == "ONNX_VGGNet": # Modify this part to use the ONNX model for prediction # Example: predictions = onnx_vggnet_model.run(None, {'input_name': inputs['input_name'].numpy()}) pass else: return "Invalid model choice" # Get the top 3 predictions top_predictions = sorted(enumerate(predictions[0]), key=lambda x: x[1], reverse=True)[:3] top_classes = [class_names[idx] for idx, _ in top_predictions] top_probs = [round(prob * 100, 2) for _, prob in top_predictions]
if model_choice not in ["ONNX_ResNet", "ONNX_EfficientNet", "ONNX_VGGNet"]: predictions = tf.nn.softmax(outputs.logits, axis=-1) class_idx = tf.argmax(predictions[0]) return { "Original Image": img, "Resized Image": img_resized, "Predicted class using {}: {}".format(model_choice, class_name), "Top 3 Predictions": list(zip(top_classes, top_probs)), "Confidence Scores": predictions[0] }
class_name = class_names[class_idx] return f"Predicted class using {model_choice}: {class_name}" else: # Process predictions for ONNX models # Example: class_idx = np.argmax(predictions) # class_name = class_names[class_idx] # return f"Predicted class using {model_choice}: {class_name}" return f"Predicted class using {model_choice}: [Modify this part for ONNX model]"image_input = gr.Image()
# Create a Gradio interface with a dropdown for model selectioniface = gr.Interface( fn=classify_image, inputs=["image", gr.Image(), gr.Dropdown(["ResNet", "EfficientNet", "VGGNet", "InceptionV3", "ONNX_ResNet", "ONNX_EfficientNet", "ONNX_VGGNet"], label="Select Model")], outputs="text", inputs=[image_input, gr.Dropdown(["ResNet", "EfficientNet", "VGGNet", "InceptionV3"], label="Select Model")], outputs=["image", "image", "text", "text", "text"], live=True)
# Launch the Gradio interfaceiface.launch(share=True)
).launch(debug=True)app.py+46-78