Spaces:
Runtime error
Runtime error
Download app.py from trs/Image_Classification_with_pre-traind_Models: direct link, hf CLI and curl.
- Browser
- Download file 2.23 kB
-
https://huggingface.co/spaces/trs/Image_Classification_with_pre-traind_Models/resolve/aa14aeb4bf67f01ccf74b35657ca76f347b1847b/app.py
- Command line
-
hf download hf://spaces/trs/Image_Classification_with_pre-traind_Models@aa14aeb4bf67f01ccf74b35657ca76f347b1847b/app.py
-
curl -L -o app.py https://huggingface.co/spaces/trs/Image_Classification_with_pre-traind_Models/resolve/aa14aeb4bf67f01ccf74b35657ca76f347b1847b/app.py
2.23 kB
| import torch | |
| import torchvision.transforms as transforms | |
| import gradio as gr | |
| from PIL import Image | |
| # Assuming you have the PyTorch models saved in the specified paths | |
| pytorch_efficientnet_path = './Models_pytorch/efficientnet.pth' | |
| pytorch_inception_path = './Models_pytorch/inceptionv3.pth' | |
| pytorch_vggnet_path = './Models_pytorch/vgg_16.pth' | |
| pytorch_resnet_path = './Models_pytorch/resnet50.pth' | |
| # Load PyTorch models | |
| pytorch_efficientnet_model = torch.load(pytorch_efficientnet_path) | |
| pytorch_inception_model = torch.load(pytorch_inception_path) | |
| pytorch_vggnet_model = torch.load(pytorch_vggnet_path) | |
| pytorch_resnet_model = torch.load(pytorch_resnet_path) | |
| 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 dimension | |
| return img | |
| def classify_image(img, model_choice): | |
| img = Image.fromarray(img) # Convert to PIL Image | |
| if 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 name | |
| class_name = class_names[class_idx] | |
| # Return the predicted class name as a string | |
| return f"Predicted class using {model_choice}: {class_name}" | |
| image_input = gr.Image() | |
| # Create a Gradio interface with a dropdown for model selection | |
| iface = gr.Interface( | |
| fn=classify_image, | |
| inputs=[image_input, gr.Dropdown(["ResNet", "EfficientNet", "VGGNet", "InceptionV3"], label="Select Model")], | |
| outputs=["json"], | |
| live=True | |
| ).launch(share=True) | |