Spaces:
Runtime error
Runtime error
Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849import torchimport torchvision.transforms as transformsfrom PIL import Imageimport gradio as gr# Load your PyTorch InceptionV3 modelmodel_path = "./inceptionv3_-saved-model-59-val_accuracy-0.94.hdf5" # Update with your model pathmodel = torch.load(model_path, map_location=torch.device('cpu'))model.eval()# Load the image transformertransform = transforms.Compose([transforms.Resize((150, 150)),transforms.ToTensor(),])# Define class names corresponding to your datasetclass_names = ["Ajloun Castle", "Jeresh", "Petra", "Roman amphitheater", "Umm_Qais", "Wadi_Rum"]# Define the classify_image functiondef classify_image(img):# Preprocess the imageimg = Image.fromarray((img * 255).astype('uint8')) # Assuming img is a NumPy arrayimg = transform(img)img = img.unsqueeze(0) # Add batch dimension# Make predictions using the PyTorch modelwith torch.no_grad():logits = model(img)# Get predicted class indexclass_idx = torch.argmax(logits[0]).item()# Map class index to class nameclass_name = class_names[class_idx]# Return the predicted class name as a stringreturn f"Predicted class: {class_name}"# Create a Gradio interfaceiface = gr.Interface(fn=classify_image,inputs=["image"],outputs="text",live=True)# Launch the Gradio interfaceiface.launch(share=True,debug=True)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950import gradio as grimport cv2import onnxruntime as ortimport numpy as npclass_folders = ["Ajloun Castle", "Jeresh", "Petra", "Roman amphitheater", "Umm_Qais", "Wadi_Rum"]# Define paths for the ONNX modelsmodel_paths = {"InceptionV3": '/Models_onnx/inceptionv3.onnx',"VGGNet": './Models_onnx/vgg_16.onnx',"ResNet": './Models_onnx/resnet50.onnx',"EfficientNet": '/Models_onnx/efficientnet.onnx'}def classify_selected_model(image, model_name):try:img = cv2.imread(image)img = cv2.resize(img, (150, 150))img = np.expand_dims(img, axis=0)img = img.astype(np.float32) / 255.0onnx_model = ort.InferenceSession(model_paths[model_name])input_name = onnx_model.get_inputs()[0].nameoutput_name = onnx_model.get_outputs()[0].namepredictions = onnx_model.run(None, {input_name: img})class_index = np.argmax(predictions[0])class_name = class_folders[class_index]probability = max(predictions[0])print(f'Predicted class index: {class_index}')print(f'Predicted class name: {class_name}')print(f'Probability: {probability}')return {"class_name": class_name, "probability": probability}except Exception as e:return {"error": str(e)}# Create Gradio interfaceimage_input = gr.Image(type='filepath', label="Input Image")model_dropdown = gr.Dropdown(model_paths.keys(), label="Select Model")gr.Interface(fn=classify_selected_model,inputs=[image_input, model_dropdown],outputs="json",live=True).launch(debug=True)
app.py+48-47