Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,19 +1,16 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
from PIL import Image
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
# Set up a title for the app
|
| 6 |
st.title("Image Recognition App")
|
| 7 |
|
| 8 |
-
# Load the pre-trained
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
try:
|
| 12 |
-
learn = load_learner(model_path)
|
| 13 |
-
except Exception as e:
|
| 14 |
-
st.error("Error loading the model. Make sure 'model.pkl' is available in your Hugging Face Space.")
|
| 15 |
-
st.error(str(e))
|
| 16 |
-
st.stop()
|
| 17 |
|
| 18 |
# Upload an image
|
| 19 |
uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "png", "jpeg"])
|
|
@@ -23,11 +20,20 @@ if uploaded_file is not None:
|
|
| 23 |
image = Image.open(uploaded_file).convert("RGB")
|
| 24 |
st.image(image, caption='Uploaded Image.', use_column_width=True)
|
| 25 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
# Run the model to make predictions
|
| 27 |
st.write("Classifying...")
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
from PIL import Image
|
| 3 |
+
import torch
|
| 4 |
+
from torchvision import transforms
|
| 5 |
+
from torchvision.models import resnet50
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
|
| 8 |
# Set up a title for the app
|
| 9 |
st.title("Image Recognition App")
|
| 10 |
|
| 11 |
+
# Load the pre-trained PyTorch model
|
| 12 |
+
model = resnet50(pretrained=True)
|
| 13 |
+
model.eval() # Set the model to evaluation mode
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
# Upload an image
|
| 16 |
uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "png", "jpeg"])
|
|
|
|
| 20 |
image = Image.open(uploaded_file).convert("RGB")
|
| 21 |
st.image(image, caption='Uploaded Image.', use_column_width=True)
|
| 22 |
|
| 23 |
+
# Preprocess the image
|
| 24 |
+
preprocess = transforms.Compose([
|
| 25 |
+
transforms.Resize(256),
|
| 26 |
+
transforms.CenterCrop(224),
|
| 27 |
+
transforms.ToTensor(),
|
| 28 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
| 29 |
+
])
|
| 30 |
+
image_tensor = preprocess(image).unsqueeze(0) # Add a batch dimension
|
| 31 |
+
|
| 32 |
# Run the model to make predictions
|
| 33 |
st.write("Classifying...")
|
| 34 |
+
with torch.no_grad():
|
| 35 |
+
outputs = model(image_tensor)
|
| 36 |
+
probabilities = F.softmax(outputs[0], dim=0)
|
| 37 |
+
top3_prob, top3_classes = torch.topk(probabilities, 3)
|
| 38 |
+
for i in range(3):
|
| 39 |
+
st.write(f"Label: {top3_classes[i].item()}, Confidence: {top3_prob[i].item():.2f}")
|