Spaces:
Sleeping
Sleeping
Update src/image_classifier_app.py
Browse files- src/image_classifier_app.py +90 -3
src/image_classifier_app.py
CHANGED
|
@@ -1,10 +1,97 @@
|
|
| 1 |
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
-
st.title("Upload Test")
|
| 4 |
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
| 6 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
st.write("uploaded_file value:", uploaded_file)
|
| 8 |
|
| 9 |
if uploaded_file:
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torchvision.transforms as transforms
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from torchvision.models import resnet18
|
| 7 |
|
|
|
|
| 8 |
|
| 9 |
+
# ---------------- Constants ----------------
|
| 10 |
+
CIFAR10_CLASSES = ['airplane', 'automobile', 'bird', 'cat', 'deer',
|
| 11 |
+
'dog', 'frog', 'horse', 'ship', 'truck']
|
| 12 |
+
MODEL_PATH = "resnet18_cifar10_finetuned.pth"
|
| 13 |
|
| 14 |
+
# ---------------- Model Loader ----------------
|
| 15 |
+
@st.cache_resource
|
| 16 |
+
def load_model():
|
| 17 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 18 |
+
st.write("Loading ResNet18...")
|
| 19 |
+
|
| 20 |
+
model = resnet18(pretrained=False)
|
| 21 |
+
|
| 22 |
+
st.write("Modifying model...")
|
| 23 |
+
model.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
|
| 24 |
+
model.maxpool = nn.Identity()
|
| 25 |
+
in_ftrs = model.fc.in_features
|
| 26 |
+
model.fc = nn.Sequential(
|
| 27 |
+
nn.Linear(in_ftrs, in_ftrs),
|
| 28 |
+
nn.ReLU(),
|
| 29 |
+
nn.Dropout(p=0.5),
|
| 30 |
+
nn.Linear(in_ftrs, 10)
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
st.write("Loading state_dict...")
|
| 34 |
+
model.load_state_dict(torch.load(MODEL_PATH, map_location=device))
|
| 35 |
+
model.to(device)
|
| 36 |
+
model.eval()
|
| 37 |
+
|
| 38 |
+
st.write("Model ready.")
|
| 39 |
+
return model, device
|
| 40 |
+
|
| 41 |
+
# ---------------- Preprocessing ----------------
|
| 42 |
+
def preprocess_image(image):
|
| 43 |
+
st.write('Preparing image...')
|
| 44 |
+
transform = transforms.Compose([
|
| 45 |
+
transforms.Resize((32, 32)),
|
| 46 |
+
transforms.ToTensor(),
|
| 47 |
+
transforms.Normalize(mean=[0.4914, 0.4822, 0.4465],
|
| 48 |
+
std=[0.2023, 0.1994, 0.2010])
|
| 49 |
+
])
|
| 50 |
+
st.write('Image preparation done.')
|
| 51 |
+
return transform(image).unsqueeze(0)
|
| 52 |
+
|
| 53 |
+
# ---------------- UI ----------------
|
| 54 |
+
st.title("🎯 CIFAR-10 Image Classifier")
|
| 55 |
+
st.write("Upload an image to classify it.")
|
| 56 |
+
|
| 57 |
+
uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
|
| 58 |
st.write("uploaded_file value:", uploaded_file)
|
| 59 |
|
| 60 |
if uploaded_file:
|
| 61 |
+
try:
|
| 62 |
+
st.write('Converting image...')
|
| 63 |
+
image = Image.open(uploaded_file).convert('RGB')
|
| 64 |
+
|
| 65 |
+
st.write('Showing image...')
|
| 66 |
+
st.image(image, caption="Uploaded Image", width=200)
|
| 67 |
+
|
| 68 |
+
st.write('skipping Loading model...')
|
| 69 |
+
model, device = load_model()
|
| 70 |
+
st.write('Model loaded.')
|
| 71 |
+
|
| 72 |
+
st.write("Classifying image...")
|
| 73 |
+
with st.spinner("Classifying..."):
|
| 74 |
+
tensor = preprocess_image(image).to(device)
|
| 75 |
+
with torch.no_grad():
|
| 76 |
+
outputs = model(tensor)
|
| 77 |
+
probabilities = torch.softmax(outputs, dim=1)
|
| 78 |
+
confidence, predicted = torch.max(probabilities, 1)
|
| 79 |
+
|
| 80 |
+
st.success(f"Predicted: {CIFAR10_CLASSES[predicted.item()]}")
|
| 81 |
+
st.info(f"Confidence: {confidence.item()*100:.2f}%")
|
| 82 |
+
|
| 83 |
+
except Exception as e:
|
| 84 |
+
import traceback
|
| 85 |
+
st.error("An error occurred:")
|
| 86 |
+
st.text(traceback.format_exc())
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
top5_probs, top5_indices = torch.topk(probabilities, 5)
|
| 90 |
+
st.subheader("Top 5 Predictions")
|
| 91 |
+
for i in range(5):
|
| 92 |
+
label = CIFAR10_CLASSES[top5_indices[0][i].item()]
|
| 93 |
+
prob = top5_probs[0][i].item() * 100
|
| 94 |
+
st.write(f"{i+1}. {label} – {prob:.2f}%")
|
| 95 |
+
|
| 96 |
+
st.write("Done.")
|
| 97 |
+
|