fruit-classifier / app_ui.py
nahinfarhan's picture
Update app_ui.py
b974ef0 verified
Raw History Blame Contribute Delete
6.69 kB
import streamlit as st
from PIL import Image
import io
import cv2
import numpy as np
import time
import tensorflow as tf
st.set_page_config(page_title="Fruit Classifier", page_icon="🍎")
st.title("🍎 Fresh vs Rotten Fruit Classifier")
# Load model
@st.cache_resource
def load_model():
try:
return tf.keras.models.load_model('multi_task_resnet152.keras')
except:
st.warning("Model file not found. Using dummy predictions.")
return None
model = load_model()
FRUIT_CLASSES = ['apple', 'banana', 'orange', 'mixed']
def predict_image(img):
"""Make prediction on image"""
img = img.convert('RGB')
img = img.resize((224, 224))
img_array = np.array(img) / 255.0
img_array = np.expand_dims(img_array, axis=0)
if model is None:
import random
fruit_class = random.choice(FRUIT_CLASSES)
fruit_confidence = random.uniform(0.7, 0.95)
freshness_prob = random.uniform(0.1, 0.8)
freshness = 'Rotten' if freshness_prob > 0.5 else 'Fresh'
else:
predictions = model.predict(img_array)
fruit_class_probs = predictions[0][0]
fruit_class_idx = np.argmax(fruit_class_probs)
fruit_class = FRUIT_CLASSES[fruit_class_idx] if fruit_class_idx < len(FRUIT_CLASSES) else f"Class_{fruit_class_idx}"
fruit_confidence = float(np.max(fruit_class_probs))
freshness_prob = float(predictions[1][0][0])
freshness = 'Rotten' if freshness_prob > 0.5 else 'Fresh'
return {
'fruit_class': fruit_class,
'freshness': freshness,
'fruit_confidence': fruit_confidence,
'freshness_prob': freshness_prob
}
# Mode selection
mode = st.radio("Choose classification mode:", ["πŸ“ Upload Image", "πŸ“Ή Live Camera Feed"])
if mode == "πŸ“ Upload Image":
st.write("Upload an image to classify the fruit type and freshness")
uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
if uploaded_file is not None:
# Display uploaded image
image = Image.open(uploaded_file)
st.image(image, caption="Uploaded Image", use_column_width=True)
# Make prediction
if st.button("Classify"):
with st.spinner("Analyzing image..."):
try:
result = predict_image(image)
# Display results
col1, col2 = st.columns(2)
with col1:
st.subheader("πŸ“ Fruit Type")
st.success(f"**{result['fruit_class'].title()}**")
st.write(f"Confidence: {result['fruit_confidence']:.2%}")
with col2:
st.subheader("✨ Freshness")
if result['freshness'] == 'Fresh':
st.success(f"**{result['freshness']}**")
else:
st.error(f"**{result['freshness']}**")
st.write(f"Rotten probability: {result['freshness_prob']:.2%}")
except Exception as e:
st.error(f"An error occurred: {str(e)}")
else: # Live Camera Feed mode
st.write("Use your camera to classify fruits in real-time")
# Camera controls
col1, col2 = st.columns(2)
with col1:
start_camera = st.button("πŸ“Ή Start Camera")
with col2:
stop_camera = st.button("⏹️ Stop Camera")
# Initialize session state
if 'camera_active' not in st.session_state:
st.session_state.camera_active = False
if start_camera:
st.session_state.camera_active = True
if stop_camera:
st.session_state.camera_active = False
if st.session_state.camera_active:
# Create placeholders for live feed
frame_placeholder = st.empty()
result_placeholder = st.empty()
try:
cap = cv2.VideoCapture(0)
if not cap.isOpened():
st.error("Cannot access camera. Please check camera permissions.")
else:
while st.session_state.camera_active:
ret, frame = cap.read()
if not ret:
st.error("Failed to capture frame")
break
# Convert BGR to RGB
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# Display frame
frame_placeholder.image(frame_rgb, caption="Live Feed", use_column_width=True)
# Process frame for prediction
img_pil = Image.fromarray(frame_rgb)
try:
result = predict_image(img_pil)
# Display results
with result_placeholder.container():
col1, col2 = st.columns(2)
with col1:
st.metric("πŸ“ Fruit Type", result['fruit_class'].title(),
f"{result['fruit_confidence']:.1%} confidence")
with col2:
st.metric("✨ Freshness", result['freshness'],
f"{result['freshness_prob']:.1%} rotten prob")
except Exception as e:
result_placeholder.warning(f"Prediction error: {str(e)}")
# Small delay to prevent overwhelming the API
time.sleep(0.5)
cap.release()
except Exception as e:
st.error(f"Camera error: {str(e)}")
st.session_state.camera_active = False
# Instructions
with st.expander("ℹ️ How to use"):
if mode == "πŸ“ Upload Image":
st.write("""
1. Upload an image of a fruit (apple, banana, orange, etc.)
2. Click 'Classify' to get predictions
3. View the fruit type and freshness results
**Supported formats:** JPG, JPEG, PNG
""")
else:
st.write("""
1. Click 'Start Camera' to begin live feed
2. Point camera at fruits for real-time classification
3. Results update automatically every 0.5 seconds
4. Click 'Stop Camera' to end the session
**Requirements:** Working webcam and camera permissions
""")