DL_model / src /streamlit_app.py
pratik1000's picture
Update src/streamlit_app.py
6f99ef0 verified
Raw History Blame Contribute Delete
7.73 kB
# import streamlit as st
# from tensorflow.keras.models import load_model
# from tensorflow.keras.preprocessing import image
# import numpy as np
# from PIL import Image
# # ================================================================
# # STEP 1: Load Model
# # ================================================================
# @st.cache_resource
# def load_trained_model():
# model = load_model('src/dhoni_vs_kohli_final_model.h5')
# return model
# model = load_trained_model()
# # ================================================================
# # STEP 2: App UI
# # ================================================================
# st.set_page_config(page_title="Dhoni vs Kohli Classifier 🏏", layout="centered")
# st.title("🏏 Dhoni vs Kohli Image Classifier")
# st.markdown("Upload an image, and the model will tell whether it's **MS Dhoni**, **Virat Kohli**, or someone **else**,the model accuracy is 85% so some time it make mistakeπŸ‘‡")
# uploaded_file = st.file_uploader("πŸ“Έ Choose an image...", type=["jpg", "jpeg", "png"])
# # ================================================================
# # STEP 3: Prediction Logic
# # ================================================================
# if uploaded_file is not None:
# # Show uploaded image
# img = Image.open(uploaded_file)
# st.image(img, caption="Uploaded Image", use_column_width=True)
# st.write("πŸ” Analyzing...")
# # Preprocess
# img = img.resize((150, 150))
# x = image.img_to_array(img)
# x = np.expand_dims(x, axis=0) / 255.0
# # Predict
# pred = model.predict(x)[0][0]
# # Define confidence thresholds
# dhoni_conf = 1 - pred
# kohli_conf = pred
# st.write(f"Raw Prediction Value: {pred:.4f}")
# # Decision Logic
# if kohli_conf > 0.75:
# st.success(f"🏏 Predicted: **Virat Kohli** (Confidence: {kohli_conf:.2f})")
# st.progress(float(kohli_conf))
# elif dhoni_conf > 0.75:
# st.success(f"🏏 Predicted: **MS Dhoni** (Confidence: {dhoni_conf:.2f})")
# st.progress(float(dhoni_conf))
# else:
# st.warning("πŸ€” The model is **not confident enough**. This might be **someone else (Unknown Person)**.")
# st.progress(0.5)
# else:
# st.info("Please upload an image to get started.")
# import streamlit as st
# from tensorflow.keras.models import load_model
# from tensorflow.keras.preprocessing import image
# import numpy as np
# from PIL import Image
# import os
# # ================================================================
# # STEP 1: Load Model
# # ================================================================
# @st.cache_resource
# def load_trained_model():
# MODEL_PATH = os.path.join(os.path.dirname(__file__), "dhoni_vs_kohli_model.h5")
# model = load_model(MODEL_PATH)
# return model
# model = load_trained_model()
# # ================================================================
# # STEP 2: App UI
# # ================================================================
# st.set_page_config(page_title="Dhoni vs Kohli Classifier 🏏", layout="centered")
# st.title("🏏 Dhoni vs Kohli Image Classifier")
# st.markdown(
# """
# Upload an image, and the model will tell whether it's **MS Dhoni**, **Virat Kohli**, or someone **else**.
# Model accuracy β‰ˆ 85%, so it may sometimes make mistakes.πŸ‘‡
# """
# )
# uploaded_file = st.file_uploader("πŸ“Έ Choose an image...", type=["jpg", "jpeg", "png"])
# # ================================================================
# # STEP 3: Prediction Logic
# # ================================================================
# if uploaded_file is not None:
# try:
# # Show uploaded image
# img = Image.open(uploaded_file).convert("RGB")
# st.image(img, caption="Uploaded Image", use_container_width=True)
# st.write("πŸ” Analyzing...")
# # Preprocess
# img = img.resize((150, 150)) # βœ… same size as training
# x = image.img_to_array(img)
# x = np.expand_dims(x, axis=0) / 255.0
# # Predict
# pred = model.predict(x)[0][0]
# # Confidence calculation
# dhoni_conf = 1 - pred
# kohli_conf = pred
# st.write(f"**Raw Prediction Value:** {pred:.4f}")
# # Decision logic
# if kohli_conf > 0.65:
# st.success(f"🏏 Predicted: **Virat Kohli** (Confidence: {kohli_conf:.2f})")
# st.progress(float(kohli_conf))
# elif dhoni_conf > 0.65:
# st.success(f"🏏 Predicted: **MS Dhoni** (Confidence: {dhoni_conf:.2f})")
# st.progress(float(dhoni_conf))
# else:
# st.warning("πŸ€” The model is **not confident enough**. Might be someone **else**.")
# st.progress(0.5)
# except Exception as e:
# st.error(f"❌ Error during prediction: {e}")
# else:
# st.info("Please upload an image to get started.")
import streamlit as st
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image
import numpy as np
from PIL import Image
import os
# ================================================================
# STEP 1: Load Model
# ================================================================
@st.cache_resource
def load_trained_model():
MODEL_PATH = os.path.join(os.path.dirname(__file__), "dhoni_vs_kohli_final_model.h5")
model = load_model(MODEL_PATH)
return model
model = load_trained_model()
# ================================================================
# STEP 2: App UI
# ================================================================
st.set_page_config(page_title="Dhoni vs Kohli Classifier 🏏", layout="centered")
st.title("🏏 Dhoni vs Kohli Image Classifier")
st.markdown(
"""
Upload an image, and the model will tell whether it's **MS Dhoni**, **Virat Kohli**, or someone **else**.
Model accuracy β‰ˆ 85%, so it may sometimes make mistakes.πŸ‘‡
"""
)
uploaded_file = st.file_uploader("πŸ“Έ Choose an image...", type=["jpg", "jpeg", "png"])
# ================================================================
# STEP 3: Prediction Logic with Unknown Handling
# ================================================================
if uploaded_file is not None:
try:
# Show uploaded image
img = Image.open(uploaded_file).convert("RGB")
st.image(img, caption="Uploaded Image", use_container_width=True)
st.write("πŸ” Analyzing...")
# Preprocess
img = img.resize((150, 150)) # βœ… same size as training
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0) / 255.0
# Predict
pred = model.predict(x)[0][0]
# Confidence distance from midpoint (0.5)
confidence_distance = abs(pred - 0.5) * 2 # 0 β†’ uncertain, 1 β†’ confident
# Show raw prediction for debugging
st.write(f"**Raw Prediction Value:** {pred:.4f}")
st.write(f"**Confidence Distance:** {confidence_distance:.2f}")
# Decision logic
if confidence_distance < 0.4:
st.warning("πŸ€” Not confident β€” This might not be Dhoni or Kohli.")
st.progress(0.4)
elif pred > 0.5:
kohli_conf = pred
st.success(f"🏏 Predicted: **Virat Kohli** (Confidence: {kohli_conf:.2f})")
st.progress(float(kohli_conf))
else:
dhoni_conf = 1 - pred
st.success(f"🏏 Predicted: **MS Dhoni** (Confidence: {dhoni_conf:.2f})")
st.progress(float(dhoni_conf))
except Exception as e:
st.error(f"❌ Error during prediction: {e}")
else:
st.info("Please upload an image to get started.")