-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
133 lines (103 loc) · 4.19 KB
/
app.py
File metadata and controls
133 lines (103 loc) · 4.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
import streamlit as st
import torch
import torch.nn as nn
from torchvision import models, transforms
from PIL import Image
import requests
import base64
import io
CLASS_NAMES = ['butterfly', 'cat', 'chicken', 'cow', 'dog',
'elephant', 'horse', 'sheep', 'spider', 'squirrel']
@st.cache_resource
def load_model():
model = models.resnet50(weights = None)
num_features = model.fc.in_features
model.fc = nn.Linear(num_features, 10)
model.load_state_dict(torch.load('animal_classifier_resnet50.pth', map_location='cpu'))
model.eval()
return model
def preprocess_image(image):
image_transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]
)
])
image_tensor = image_transform(image)
image_tensor = image_tensor.unsqueeze(0)
return image_tensor
def predict(model, image_tensor):
with torch.no_grad():
outputs = model(image_tensor)
probabilities = torch.nn.functional.softmax(outputs[0], dim = 0)
confidence , predicted_class = torch.max(probabilities, 0)
predicted_class = predicted_class.item()
confidence = confidence.item() * 100
probabilities = probabilities.tolist()
return predicted_class, probabilities, confidence
def main():
st.set_page_config(
page_title='Animal Classifier',
layout='centered'
)
st.title("Animal Classifier")
st.write("Upload an image and I'll identify which animal it is!")
st.write("**I can recognize:** Butterfly, Cat, Chicken, Cow, Dog, Elephant, Horse, Sheep, Spider, Squirrel")
model = load_model()
tab1, tab2 = st.tabs(['Upload File', 'Image URL'])
image = None
with tab1:
uploaded_file = st.file_uploader(
"Choose an image",
type = ['jpg', 'jpeg', 'png']
)
if uploaded_file is not None:
image = Image.open(uploaded_file).convert('RGB')
with tab2:
st.write("Paste an image URL from the web:")
image_url = st.text_input(
"Image URL",
placeholder= "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTOGx4ockyX9wbBLEn2GOHV94mxfs0PYz9y8FyhETQFD7BeNvmJNJgL2tI&s"
)
if image_url:
try:
if image_url.startswith("data:image"):
image_data = image_url.split(',')[1]
image_bytes = base64.b64decode(image_data)
image = Image.open(io.BytesIO(image_bytes)).convert('RGB')
st.success("Image loaded successfully")
else:
response = requests.get(image_url, timeout=5)
image = Image.open(io.BytesIO(response.content)).convert('RGB')
st.success("Image loaded successfully")
except Exception as e:
st.error("Could not load image. Please check the URL and try again.")
image = None
# if uploaded_file is not None:
# image = Image.open(uploaded_file).convert('RGB')
if image is not None:
st.image(image, caption = 'Input Image', width = 400)
with st.spinner('Analyzing...'):
image_tensor = preprocess_image(image)
predicted_class, probabilities, confidence = predict(model, image_tensor)
animal_name = CLASS_NAMES[predicted_class]
st.success(f" Prediction: **{animal_name.upper()}**")
st.info(f"**Confidence**: {confidence:.2f}%")
st.write("### All Class Probabilities:")
# Create a nice display of probabilities
prob_data = []
for i, prob in enumerate(probabilities):
prob_data.append({
'Animal': CLASS_NAMES[i].capitalize(),
'Probability': f"{prob * 100:.2f}%"
})
# Sort by probability (highest first)
prob_data.sort(key=lambda x: float(x['Probability'].strip('%')), reverse=True)
# Display as a table
for item in prob_data:
st.write(f"**{item['Animal']}:** {item['Probability']}")
if __name__ == "__main__":
main()