Spaces:
Runtime error
Runtime error
Update app.py
Browse files123156789101112131415161718192021222324252627282930313233343536373839404142434423456789101112131415161718192021222324252627282930313233343536373839404142434445464748494647484950import 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 image img = Image.fromarray((img * 255).astype('uint8')) # Assuming img is a NumPy array img = transform(img) img = img.unsqueeze(0) # Add batch dimension
# Make predictions using the PyTorch model with torch.no_grad(): logits = model(img)
# Get predicted class index class_idx = torch.argmax(logits[0]).item()
# Map class index to class name class_name = class_names[class_idx]
# Return the predicted class name as a string return f"Predicted class: {class_name}"
# Create a Gradio interfaceiface = gr.Interface( fn=classify_image, inputs=["image"], outputs="text",import cv2import onnxruntime as ortimport numpy as np
class_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.0
onnx_model = ort.InferenceSession(model_paths[model_name])
input_name = onnx_model.get_inputs()[0].name output_name = onnx_model.get_outputs()[0].name
predictions = 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 the Gradio interfaceiface.launch(share=True,debug=True)).launch(debug=True)app.py+48-47