Spaces:
Runtime error
Runtime error
Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970711 unmodified line737475767778import torchimport torchvision.transforms as transformsimport gradio as grfrom PIL import Imageimport onnximport torchimport onnxonnx_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'# Load ONNX modelsefficientnet_model = onnx.load(onnx_efficientnet_path)inceptionv3_model = onnx.load(onnx_inception_path)vggnet_model = onnx.load(onnx_vggnet_path)resnet_model = onnx.load(onnx_resnet_path)# Export ONNX models to PyTorch modelspytorch_efficientnet_model = torch.onnx.export(efficientnet_model, torch.randn(1, 3, 150, 150), verbose=True)pytorch_inceptionv3_model = torch.onnx.export(inceptionv3_model, torch.randn(1, 3, 150, 150), verbose=True)pytorch_vggnet_model = torch.onnx.export(vggnet_model, torch.randn(1, 3, 150, 150), verbose=True)pytorch_resnet_model = torch.onnx.export(resnet_model, torch.randn(1, 3, 150, 150), verbose=True)# Load PyTorch modelspytorch_efficientnet_model = torch.jit.load(pytorch_efficientnet_model)pytorch_inceptionv3_model = torch.jit.load(pytorch_inceptionv3_model)pytorch_vggnet_model = torch.jit.load(pytorch_vggnet_model)pytorch_resnet_model = torch.jit.load(pytorch_resnet_model)class_names = ["Ajloun Castle", "Jerash", "Petra", "Roman amphitheater", "Umm Qais", "Wadi Rum"]def preprocess_image_pil(img):img = transforms.Resize((150, 150))(img)img = transforms.ToTensor()(img)img = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])(img)img = img.unsqueeze(0) # Add batch dimensionreturn imgdef classify_image(img, model_choice):img = Image.fromarray(img) # Convert to PIL Imageif model_choice == "ResNet":img = preprocess_image_pil(img)predictions = pytorch_resnet_model(img)elif model_choice == "EfficientNet":img = preprocess_image_pil(img)predictions = pytorch_efficientnet_model(img)elif model_choice == "VGGNet":img = preprocess_image_pil(img)predictions = pytorch_vggnet_model(img)elif model_choice == "InceptionV3":img = preprocess_image_pil(img)predictions = pytorch_inception_model(img)else:return "Invalid model choice"class_idx = torch.argmax(predictions[0])# Map class index to class nameclass_name = class_names[class_idx]# Return the predicted class name as a stringreturn f"Predicted class using {model_choice}: {class_name}"image_input = gr.Image()1 unmodified lineiface = gr.Interface(fn=classify_image,inputs=[image_input, gr.Dropdown(["ResNet", "EfficientNet", "VGGNet", "InceptionV3"], label="Select Model")],outputs=["json"],live=True).launch(share=True)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364651 unmodified line6768697071727374import onnxruntime as ortimport numpy as npimport gradio as grimport cv2onnx_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 needsonnx_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]input_name = model.get_inputs()[0].nametry:predictions = model.run(None, {input_name: 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]result = {"Original Image": img.tolist(), # Convert to list for compatibility with Gradio"Resized Image": img_resized.tolist(),f"Predicted class using {model_choice}": class_name,"Top 3 Predictions": list(zip(top_classes, top_probs)),"Confidence Scores": predictions[0].tolist()}except Exception as e:result = {"Error": str(e)}return resultimage_input = gr.Image()1 unmodified lineiface = gr.Interface(fn=classify_image,inputs=[image_input, gr.Dropdown(["ResNet", "EfficientNet", "VGGNet", "InceptionV3"], label="Select Model")],outputs="json",live=True)iface.launch(share=True)
app.py+56-60