sailakshmi123 commited on
Commit
df7ac7a
ยท
verified ยท
1 Parent(s): 7b16f1c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -0
app.py CHANGED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import numpy as np
3
+ from tensorflow.keras.models import load_model
4
+ from tensorflow.keras.preprocessing.image import img_to_array
5
+ from PIL import Image, UnidentifiedImageError
6
+
7
+ # ๐Ÿ”ง Configure Streamlit
8
+ st.set_page_config(
9
+ page_title="Animal Classifier",
10
+ layout="centered",
11
+ initial_sidebar_state="auto"
12
+ )
13
+
14
+ # ๐Ÿ“ฆ Load model and class labels
15
+ @st.cache_resource
16
+ def load_model_once():
17
+ return load_model("animal_model.keras")
18
+
19
+ @st.cache_data
20
+ def load_labels():
21
+ return np.load("class_labels.npy", allow_pickle=True).item()
22
+
23
+ model = load_model_once()
24
+ class_indices = load_labels()
25
+ class_labels = list(class_indices.keys())
26
+
27
+ # ๐Ÿท App Title
28
+ st.title("๐Ÿพ Animal Image Classifier")
29
+ st.markdown("Upload up to **3 images** and get predictions")
30
+
31
+ # ๐Ÿ“ค Upload Images
32
+ uploaded_files = st.file_uploader(
33
+ "Upload animal images",
34
+ type=["jpg", "jpeg", "png"],
35
+ accept_multiple_files=True
36
+ )
37
+
38
+ if uploaded_files:
39
+ uploaded_files = uploaded_files[:3] # Limit to 3
40
+ cols = st.columns(len(uploaded_files))
41
+
42
+ for idx, uploaded_file in enumerate(uploaded_files):
43
+ with cols[idx]:
44
+ st.markdown(f"### Image {idx + 1}")
45
+ try:
46
+ # ๐Ÿ–ผ๏ธ Load & preview image
47
+ image = Image.open(uploaded_file).convert("RGB")
48
+ preview = image.copy()
49
+ preview.thumbnail((150, 150))
50
+ st.image(preview, caption="Preview", use_container_width=True)
51
+
52
+ # ๐Ÿงช Preprocess image
53
+ resized = image.resize((128, 128)) # Adjust size as per your model
54
+ img_array = img_to_array(resized) / 255.0
55
+ img_array = np.expand_dims(img_array, axis=0)
56
+
57
+ # ๐Ÿ”ฎ Predict
58
+ preds = model.predict(img_array)[0]
59
+ top_indices = preds.argsort()[-3:][::-1]
60
+ top_labels = [class_labels[i] for i in top_indices]
61
+ top_scores = [preds[i] for i in top_indices]
62
+
63
+ # โœ… Display Predictions
64
+ st.success(f"**๐Ÿ”ฎ Top Prediction:** {top_labels[0].capitalize()}")
65
+ st.markdown("##### ๐Ÿ“Š Top 3 Predictions:")
66
+ for label, score in zip(top_labels, top_scores):
67
+ st.write(f"**{label.capitalize()}** โ€” {score:.4f}")
68
+
69
+ except UnidentifiedImageError:
70
+ st.error("โŒ Error: Invalid image file.")
71
+
72
+ # ๐Ÿ“Œ Footer message
73
+ st.sidebar.markdown("---")
74
+ st.sidebar.markdown("Built with โค๏ธ using Streamlit and Keras.")