File size: 6,690 Bytes
e0a956c
 
 
 
 
 
b974ef0
e0a956c
 
 
 
 
b974ef0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0a956c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b974ef0
e0a956c
b974ef0
 
e0a956c
b974ef0
 
 
 
e0a956c
b974ef0
 
 
 
 
 
 
 
e0a956c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b974ef0
e0a956c
b974ef0
 
 
 
 
 
 
 
 
e0a956c
b974ef0
 
e0a956c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
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
        """)