Download app.py from PavanKumarD/Fish_Image_Classification: direct link, hf CLI and curl.
- Browser
- Download file 3.38 kB
-
https://huggingface.co/spaces/PavanKumarD/Fish_Image_Classification/resolve/cd3538ae214f534d0225ea4339b0eab07f83e87f/app.py
- Command line
-
hf download hf://spaces/PavanKumarD/Fish_Image_Classification@cd3538ae214f534d0225ea4339b0eab07f83e87f/app.py
-
curl -L -o app.py https://huggingface.co/spaces/PavanKumarD/Fish_Image_Classification/resolve/cd3538ae214f534d0225ea4339b0eab07f83e87f/app.py
3.38 kB
| import streamlit as st | |
| import torch | |
| import torch.nn as nn | |
| import torchvision.models as models | |
| from PIL import Image | |
| from torchvision import transforms | |
| import gradio as gr | |
| import plotly.graph_objects as go | |
| # Device setup | |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| # Image transformations | |
| transform = transforms.Compose([ | |
| transforms.Resize((224, 224)), | |
| transforms.ToTensor(), | |
| transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) # ImageNet standard | |
| ]) | |
| # Initialize models | |
| def load_models(): | |
| # Load models (ResNet, MobileNetV2) | |
| resnet18 = models.resnet18(pretrained=False) | |
| resnet18.fc = nn.Linear(resnet18.fc.in_features, 11) # Modify output layer for 11 classes | |
| resnet18.load_state_dict(torch.load('models/resnet18_fish_classification_model.pth')) | |
| resnet18.to(device) | |
| mobilenet_v2 = models.mobilenet_v2(pretrained=False) | |
| mobilenet_v2.classifier[1] = nn.Linear(1280, 11) # Modify output layer for 11 classes | |
| mobilenet_v2.load_state_dict(torch.load('models/mobilenetv2_fish_classification_model.pth')) | |
| mobilenet_v2.to(device) | |
| models_dict = { | |
| 'ResNet18': resnet18, | |
| 'MobileNetV2': mobilenet_v2 | |
| } | |
| return models_dict | |
| # Image prediction function | |
| def predict_image(image): | |
| models_dict = load_models() | |
| image = transform(image).unsqueeze(0).to(device) | |
| predictions = {} | |
| for model_name, model in models_dict.items(): | |
| model.eval() | |
| with torch.no_grad(): | |
| outputs = model(image) | |
| probabilities = torch.nn.functional.softmax(outputs, dim=1) | |
| _, predicted_class = torch.max(probabilities, 1) | |
| confidence = probabilities[0, predicted_class].item() | |
| predictions[model_name] = {'predicted_class': predicted_class.item(), 'confidence': confidence} | |
| return predictions | |
| # Confidence chart creation | |
| def create_confidence_chart(confidence, label): | |
| fig = go.Figure(go.Bar( | |
| x=[confidence, 100-confidence], | |
| y=[label, 'Other'], | |
| orientation='h', | |
| marker_color=['#667eea', '#e0e0e0'], | |
| text=[f'{confidence:.1f}%', f'{100-confidence:.1f}%'], | |
| textposition='inside', | |
| textfont=dict(color='white', size=14) | |
| )) | |
| fig.update_layout( | |
| title=f"Prediction Confidence: {label}", | |
| xaxis_title="Confidence (%)", | |
| height=200, | |
| margin=dict(l=0, r=0, t=40, b=0), | |
| showlegend=False, | |
| plot_bgcolor='rgba(0,0,0,0)', | |
| paper_bgcolor='rgba(0,0,0,0)' | |
| ) | |
| return fig | |
| # Gradio Interface | |
| def gradio_interface(): | |
| # This will load the models and use Gradio's interface to interact | |
| models_dict = load_models() | |
| gradio_interface = gr.Interface( | |
| fn=predict_image, | |
| inputs=gr.inputs.Image(type="pil"), | |
| outputs=gr.outputs.JSON(), | |
| live=True, | |
| title="Fish Image Classification", | |
| description="Classify fish images using AI models (ResNet18, MobileNetV2).", | |
| ) | |
| return gradio_interface | |
| # Streamlit UI | |
| st.title("Fish Image Classification with AI") | |
| st.markdown(""" | |
| This app allows you to upload a fish image, and it will classify the fish into one of the categories using two different AI models: | |
| - **ResNet18** | |
| - **MobileNetV2** | |
| Upload an image below to get predictions. | |
| """) | |
| gradio_interface().launch(inline=True) | |