Spaces:
Runtime error
Runtime error
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899import gradio as grfrom transformers import AutoTokenizer, TFAutoModelForImageClassificationimport tensorflow as tffrom PIL import Imageimport onnxruntime as ort # Make sure to install onnxruntime (pip install onnxruntime)# 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_vggnet_path = './Models_onnx/vgg_16.onnx'onnx_resnet_path = './Models_onnx/resnet50.onnx'onnx_efficientnet_model = ort.InferenceSession(onnx_efficientnet_path)onnx_vggnet_model = ort.InferenceSession(onnx_vggnet_path)onnx_resnet_model = ort.InferenceSession(onnx_resnet_path)# Define class names corresponding to your datasetclass_names = ["Ajloun Castle", "Jeresh", "Petra", "Roman amphitheater", "Umm_Qais", "Wadi_Rum"] # Replace with your actual class names# Define the tokenize_and_preprocess functiondef tokenize_and_preprocess(img, model_choice):img = Image.fromarray((img * 255).astype('uint8'))img = img.resize((224, 224))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"return inputs# Define the classify_image functiondef classify_image(img, model_choice):inputs = tokenize_and_preprocess(img, model_choice)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()})passelif 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()})passelif 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()})passelse:return "Invalid model choice"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])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]"# 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",live=True)# Launch the Gradio interfaceiface.launch(share=True)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667import numpy as npimport osimport cv2import gradio as grimport onnxruntime as ortonnx_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'# 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)class_names = ["Ajloun Castle", "Jeresh", "Petra", "Roman amphitheater", "Umm_Qais", "Wadi_Rum"]def classify_image(img, model_choice):def preprocess_input(img, model):# Placeholder for preprocessing steps# Replace with actual preprocessing steps based on the modelprocessed_img = img / 255.0return processed_img# Keep the input size as (150, 150) since your model expects that sizeinput_size = (150, 150)img_resized = cv2.resize(img, input_size)# Preprocess the input imageimg_preprocessed = preprocess_input(img_resized, model_choice)# Run inference based on the selected modelmodel = {"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]# Get the top 3 predictionstop_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]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]}image_input = gr.Image()# Create a Gradio interface with a dropdown for model selectioniface = gr.Interface(fn=classify_image,inputs=[image_input, gr.Dropdown(["ResNet", "EfficientNet", "VGGNet", "InceptionV3"], label="Select Model")],outputs=["image", "image", "text", "text", "text"],live=True).launch(debug=True)
app.py+46-78