Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from transformers import ViTForImageClassification, ViTFeatureExtractor
|
3 |
+
from PIL import Image
|
4 |
+
import torch
|
5 |
+
import matplotlib.pyplot as plt
|
6 |
+
|
7 |
+
# Define the repository ID
|
8 |
+
repo_id = "Hammad712/5-Flower-Types-Classification-VIT-Model"
|
9 |
+
|
10 |
+
# Load the model and feature extractor
|
11 |
+
model = ViTForImageClassification.from_pretrained(repo_id)
|
12 |
+
feature_extractor = ViTFeatureExtractor.from_pretrained(repo_id)
|
13 |
+
|
14 |
+
# Define the class names dictionary
|
15 |
+
class_names = {0: 'Lilly', 1: 'Lotus', 2: 'Orchid', 3: 'Sunflower', 4: 'Tulip'}
|
16 |
+
|
17 |
+
# Define the inference function
|
18 |
+
def predict(image):
|
19 |
+
inputs = feature_extractor(images=image, return_tensors="pt")
|
20 |
+
with torch.no_grad():
|
21 |
+
outputs = model(**inputs)
|
22 |
+
logits = outputs.logits
|
23 |
+
probabilities = torch.nn.functional.softmax(logits, dim=-1).squeeze().tolist()
|
24 |
+
predicted_class_idx = logits.argmax(-1).item()
|
25 |
+
predicted_class_name = class_names[predicted_class_idx]
|
26 |
+
return probabilities, predicted_class_name
|
27 |
+
|
28 |
+
# Streamlit app
|
29 |
+
st.title("Flower Type Classification")
|
30 |
+
st.write("Upload an image of a flower to classify its type.")
|
31 |
+
|
32 |
+
# Upload image
|
33 |
+
uploaded_file = st.sidebar.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
|
34 |
+
|
35 |
+
if uploaded_file is not None:
|
36 |
+
# Display the uploaded image
|
37 |
+
image = Image.open(uploaded_file).convert("RGB")
|
38 |
+
st.image(image, caption='Uploaded Image.', use_column_width=True)
|
39 |
+
|
40 |
+
# Predict the class of the image
|
41 |
+
probabilities, predicted_class = predict(image)
|
42 |
+
|
43 |
+
# Display the probabilities in a bar chart
|
44 |
+
fig, ax = plt.subplots()
|
45 |
+
ax.bar(class_names.values(), probabilities)
|
46 |
+
ax.set_ylabel('Probability')
|
47 |
+
ax.set_xlabel('Class')
|
48 |
+
ax.set_title('Class Probabilities')
|
49 |
+
st.pyplot(fig)
|
50 |
+
|
51 |
+
# Display the predicted class
|
52 |
+
st.write(f"Predicted class: **{predicted_class}**")
|