saramneena's picture
Update app.py
014679a verified
import streamlit as st
import numpy as np
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.image import img_to_array
from PIL import Image
# ๐Ÿ”ง Configure Streamlit
st.set_page_config(
page_title="WildVision ๐Ÿพ | Animal Identifier",
layout="centered",
initial_sidebar_state="auto"
)
st.title("๐Ÿค– Smart Animal Identifier")
st.markdown("Upload up to **3 animal images** and discover what species they are!")
# โœ… Debug Check
st.write("๐Ÿ”ง App started successfully")
# ๐Ÿ“ฆ Load model and class labels with error handling
@st.cache_resource
def load_model_once():
return load_model("animal_model.keras")
@st.cache_data
def load_labels():
return np.load("class_labels.npy", allow_pickle=True).item()
try:
model = load_model_once()
st.success("โœ… Model loaded successfully")
except Exception as e:
st.error(f"โŒ Failed to load model: {e}")
st.stop()
try:
class_indices = load_labels()
st.success("โœ… Labels loaded successfully")
except Exception as e:
st.error(f"โŒ Failed to load label file: {e}")
st.stop()
# ๐Ÿ”„ Reverse index to get labels from prediction index
index_to_label = {v: k for k, v in class_indices.items()}
# ๐Ÿ“ค Upload Images
uploaded_files = st.file_uploader(
"๐Ÿ“ธ Upload your animal photos",
type=["jpg", "jpeg", "png"],
accept_multiple_files=True
)
if uploaded_files and len(uploaded_files) > 0:
uploaded_files = uploaded_files[:3] # Limit to 3 images
cols = st.columns(len(uploaded_files))
for idx, uploaded_file in enumerate(uploaded_files):
with cols[idx]:
st.markdown(f"#### ๐Ÿ“ท Image {idx + 1}")
# ๐Ÿ–ผ๏ธ Load and preview
try:
image = Image.open(uploaded_file).convert("RGB")
preview = image.copy()
preview.thumbnail((150, 150))
st.image(preview, caption="Image Preview", use_container_width=True)
except Exception as e:
st.error(f"โš ๏ธ Could not load image: {e}")
continue
# ๐Ÿงช Preprocess image
resized = image.resize((128, 128))
img_array = img_to_array(resized) / 255.0
img_array = np.expand_dims(img_array, axis=0)
# ๐Ÿ”ฎ Make prediction
try:
preds = model.predict(img_array)[0]
except Exception as e:
st.error(f"โŒ Prediction failed: {e}")
continue
if len(preds) != len(index_to_label):
st.error("โš ๏ธ Mismatch between model output and class labels.")
continue
# ๐Ÿ“Š Display predictions
top_indices = preds.argsort()[-3:][::-1]
top_labels = [index_to_label[i] for i in top_indices]
top_scores = [preds[i] for i in top_indices]
st.markdown("#### ๐Ÿง  Top Predictions:")
for label, score in zip(top_labels, top_scores):
st.write(f"โžก๏ธ **{label.capitalize()}**: {score:.2%}")
st.success(f"๐ŸŽฏ **Most Likely:** *{top_labels[0].capitalize()}*")
else:
st.info("๐Ÿ“ฅ Please upload 1 to 3 animal images to get started.")
# ๐Ÿ“ Footer
st.markdown("---")
st.caption("๐Ÿพ Developed by Neena | Powered by TensorFlow & Streamlit")