File size: 11,890 Bytes
e3dcdb3
74037f6
 
e3dcdb3
 
 
2ce327e
 
 
 
74037f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3dcdb3
74037f6
 
cbdf1e6
74037f6
 
 
e3dcdb3
74037f6
 
 
 
e3dcdb3
 
 
 
 
 
74037f6
 
 
 
e3dcdb3
 
74037f6
e3dcdb3
 
74037f6
 
 
 
e3dcdb3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74037f6
 
 
e3dcdb3
 
74037f6
 
 
 
 
 
e3dcdb3
 
74037f6
 
 
 
 
e3dcdb3
74037f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3dcdb3
74037f6
 
 
e3dcdb3
2ce327e
74037f6
 
 
e3dcdb3
 
 
2ce327e
e3dcdb3
 
 
 
 
 
 
2ce327e
 
e3dcdb3
74037f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3dcdb3
 
74037f6
 
 
e3dcdb3
74037f6
 
 
 
 
 
e3dcdb3
74037f6
 
 
 
 
 
 
 
 
 
 
e3dcdb3
74037f6
 
e3dcdb3
74037f6
 
 
e3dcdb3
74037f6
 
 
 
 
 
 
 
 
 
 
e3dcdb3
74037f6
e3dcdb3
74037f6
 
 
2ce327e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74037f6
 
 
 
 
 
e3dcdb3
 
74037f6
2ce327e
 
74037f6
 
2ce327e
74037f6
 
2ce327e
e3dcdb3
 
74037f6
e3dcdb3
 
74037f6
 
 
2ce327e
 
74037f6
2ce327e
 
74037f6
2ce327e
 
 
 
 
 
 
 
 
 
99926a2
cbdf1e6
2ce327e
cbdf1e6
 
 
2ce327e
74037f6
2ce327e
 
 
 
 
 
 
 
 
99926a2
cbdf1e6
2ce327e
 
 
cbdf1e6
2ce327e
cbdf1e6
2ce327e
 
74037f6
2ce327e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3dcdb3
 
 
 
 
 
 
 
 
74037f6
 
e3dcdb3
74037f6
 
 
 
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
# app.py - FoodVision Streamlit Web Application (Mobile-Optimized)
# ============================================================
# 
# IMPROVEMENTS:
# -------------
# βœ… Mobile-friendly single-column layout
# βœ… SIMPLIFIED: No session state complexity
# βœ… Direct processing on every upload
# βœ… Works reliably on mobile
# βœ… No unnecessary buttons
#
# ============================================================

import streamlit as st
import torch
import torch.nn.functional as F
from torchvision import transforms
from PIL import Image
import timm
from pathlib import Path

# ============================================================
# PAGE CONFIGURATION
# ============================================================

st.set_page_config(
    page_title="πŸ• FoodVision AI",
    page_icon="πŸ•",
    layout="centered",
    initial_sidebar_state="collapsed"
)

# ============================================================
# MINIMAL CSS (Mobile-First)
# ============================================================

st.markdown("""
<style>
    .block-container {
        padding-top: 2rem;
        padding-bottom: 2rem;
    }
    
    h1 {
        text-align: center;
        color: #FF6B6B;
        margin-bottom: 0.5rem;
    }
    
    .prediction-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        padding: 1.5rem;
        border-radius: 12px;
        color: white;
        text-align: center;
        margin: 1rem 0;
    }
    
    .prediction-card h2 {
        margin: 0;
        font-size: 1.8rem;
    }
    
    .prediction-card h3 {
        margin: 0.5rem 0 0 0;
        font-size: 1.2rem;
        opacity: 0.9;
    }
    
    .conf-bar {
        background: #f0f0f0;
        border-radius: 8px;
        height: 36px;
        margin: 0.5rem 0;
        overflow: hidden;
    }
    
    .conf-fill {
        height: 100%;
        background: linear-gradient(90deg, #4CAF50, #8BC34A);
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-weight: 600;
        font-size: 0.95rem;
    }
</style>
""", unsafe_allow_html=True)

# ============================================================
# FOOD CLASSES
# ============================================================

FOOD_CLASSES = [
    "apple_pie", "baby_back_ribs", "baklava", "beef_carpaccio", "beef_tartare",
    "beet_salad", "beignets", "bibimbap", "bread_pudding", "breakfast_burrito",
    "bruschetta", "caesar_salad", "cannoli", "caprese_salad", "carrot_cake",
    "ceviche", "cheese_plate", "cheesecake", "chicken_curry", "chicken_quesadilla",
    "chicken_wings", "chocolate_cake", "chocolate_mousse", "churros", "clam_chowder",
    "club_sandwich", "crab_cakes", "creme_brulee", "croque_madame", "cup_cakes",
    "deviled_eggs", "donuts", "dumplings", "edamame", "eggs_benedict",
    "escargots", "falafel", "filet_mignon", "fish_and_chips", "foie_gras",
    "french_fries", "french_onion_soup", "french_toast", "fried_calamari", "fried_rice",
    "frozen_yogurt", "garlic_bread", "gnocchi", "greek_salad", "grilled_cheese_sandwich",
    "grilled_salmon", "guacamole", "gyoza", "hamburger", "hot_and_sour_soup",
    "hot_dog", "huevos_rancheros", "hummus", "ice_cream", "lasagna",
    "lobster_bisque", "lobster_roll_sandwich", "macaroni_and_cheese", "macarons", "miso_soup",
    "mussels", "nachos", "omelette", "onion_rings", "oysters",
    "pad_thai", "paella", "pancakes", "panna_cotta", "peking_duck",
    "pho", "pizza", "pork_chop", "poutine", "prime_rib",
    "pulled_pork_sandwich", "ramen", "ravioli", "red_velvet_cake", "risotto",
    "samosa", "sashimi", "scallops", "seaweed_salad", "shrimp_and_grits",
    "spaghetti_bolognese", "spaghetti_carbonara", "spring_rolls", "steak", "strawberry_shortcake",
    "sushi", "tacos", "takoyaki", "tiramisu", "tuna_tartare", "waffles"
]

# ============================================================
# MODEL LOADING
# ============================================================

@st.cache_resource
def load_model():
    """Loads model from local file or Hugging Face Hub."""
    try:
        device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
        
        local_path = Path("model1_best.pth")
        
        if local_path.exists():
            checkpoint = torch.load(local_path, map_location=device, weights_only=False)
        else:
            try:
                from huggingface_hub import hf_hub_download
                model_path = hf_hub_download(
                    repo_id="doozer21/FoodVision",
                    filename="model1_best.pth"
                )
                checkpoint = torch.load(model_path, map_location=device, weights_only=False)
            except Exception:
                return None, None, None
        
        model_config = checkpoint.get('model_config', {
            'model_id': 'convnextv2_base.fcmae_ft_in22k_in1k_384'
        })
        
        model = timm.create_model(
            model_config['model_id'],
            pretrained=False,
            num_classes=101
        )
        
        model.load_state_dict(checkpoint['model_state_dict'])
        model.to(device)
        model.eval()
        
        accuracy = checkpoint.get('best_val_acc', 0)
        return model, device, accuracy
        
    except Exception as e:
        st.error(f"❌ Error loading model: {str(e)}")
        return None, None, None

# ============================================================
# IMAGE PREPROCESSING
# ============================================================

def preprocess_image(image):
    """Preprocess image for model input."""
    transform = transforms.Compose([
        transforms.Resize(256),
        transforms.CenterCrop(224),
        transforms.ToTensor(),
        transforms.Normalize(
            mean=[0.485, 0.456, 0.406],
            std=[0.229, 0.224, 0.225]
        )
    ])
    
    image = image.convert('RGB')
    return transform(image).unsqueeze(0)

# ============================================================
# PREDICTION
# ============================================================

def predict(model, image_tensor, device, top_k=3):
    """Make prediction on image."""
    with torch.no_grad():
        image_tensor = image_tensor.to(device)
        outputs = model(image_tensor)
        probabilities = F.softmax(outputs, dim=1)
        
        top_probs, top_indices = torch.topk(probabilities, top_k)
        top_probs = top_probs.cpu().numpy()[0]
        top_indices = top_indices.cpu().numpy()[0]
        
        results = []
        for prob, idx in zip(top_probs, top_indices):
            class_name = FOOD_CLASSES[idx].replace('_', ' ').title()
            confidence = float(prob) * 100
            results.append((class_name, confidence))
        
        return results

# ============================================================
# DISPLAY RESULTS
# ============================================================

def display_results(predictions):
    """Display prediction results."""
    st.markdown("---")
    
    # Top prediction
    top_food, top_conf = predictions[0]
    
    st.markdown(f"""
    <div class="prediction-card">
        <h2>πŸ† {top_food}</h2>
        <h3>{top_conf:.1f}% Confidence</h3>
    </div>
    """, unsafe_allow_html=True)
    
    # Top 3 predictions
    st.markdown("### πŸ“Š Top 3 Predictions")
    
    for i, (food, conf) in enumerate(predictions, 1):
        emoji = "πŸ₯‡" if i == 1 else "πŸ₯ˆ" if i == 2 else "πŸ₯‰"
        
        st.markdown(f"**{emoji} {food}**")
        st.markdown(f"""
        <div class="conf-bar">
            <div class="conf-fill" style="width: {conf}%">
                {conf:.1f}%
            </div>
        </div>
        """, unsafe_allow_html=True)
    
    # Feedback
    st.markdown("---")
    if top_conf > 90:
        st.success("πŸŽ‰ **Very confident!** The model is very sure.")
    elif top_conf > 70:
        st.success("πŸ‘ **Good confidence!** Solid prediction.")
    elif top_conf > 50:
        st.warning("πŸ€” **Moderate confidence.** Food might be ambiguous.")
    else:
        st.warning("πŸ˜• **Low confidence.** Try a clearer photo.")

# ============================================================
# MAIN APP
# ============================================================

def main():
    # Header
    st.title("πŸ• FoodVision AI")
    st.markdown("**Identify 101 food dishes instantly**")
    
    # Load model
    model, device, accuracy = load_model()
    
    if model is None:
        st.error("❌ Could not load model. Check if model1_best.pth exists.")
        st.stop()
    
    # Model info
    with st.expander("ℹ️ Model Info"):
        st.write(f"**Architecture:** ConvNeXt V2 Base")
        st.write(f"**Accuracy:** {accuracy:.2f}%")
        st.write(f"**Device:** {'GPU' if device.type == 'cuda' else 'CPU'}")
        st.write(f"**Classes:** 101 food categories")
    
    st.markdown("---")
    
    # Input section
    st.subheader("πŸ“Έ Choose Your Input Method")
    
    # Tab-based approach (better for mobile)
    tab1, tab2 = st.tabs(["πŸ“ Upload Image", "πŸ“· Take Photo"])
    
    with tab1:
        uploaded_file = st.file_uploader(
            "Select a food image",
            type=['jpg', 'jpeg', 'png', 'webp'],
            label_visibility="collapsed"
        )
        
        if uploaded_file is not None:
            try:
                image = Image.open(uploaded_file)
                st.image(image, caption="Uploaded Image", use_container_width=True)
                
                with st.spinner("🧠 Analyzing..."):
                    img_tensor = preprocess_image(image)
                    predictions = predict(model, img_tensor, device, top_k=3)
                
                display_results(predictions)
                
            except Exception as e:
                st.error(f"❌ Error: {str(e)}")
    
    with tab2:
        camera_photo = st.camera_input("Take a picture", label_visibility="collapsed")
        
        if camera_photo is not None:
            try:
                image = Image.open(camera_photo)
                st.image(image, caption="Camera Photo", use_container_width=True)
                
                with st.spinner("🧠 Analyzing..."):
                    img_tensor = preprocess_image(image)
                    predictions = predict(model, img_tensor, device, top_k=3)
                
                display_results(predictions)
                
            except Exception as e:
                st.error(f"❌ Error: {str(e)}")
    
    # Instructions (show at bottom when no image)
    if uploaded_file is None and camera_photo is None:
        st.info("πŸ‘† Choose a tab above to get started!")
        
        with st.expander("πŸ’‘ Tips for Best Results"):
            st.markdown("""
            - Use clear, well-lit photos
            - Make sure food is the main subject
            - Avoid heavily filtered images
            - Try different angles if confidence is low
            """)
        
        with st.expander("🍽️ What can it recognize?"):
            st.markdown("""
            **101 popular dishes** including:
            - πŸ• Pizza, Pasta, Burgers
            - 🍣 Sushi, Ramen, Pad Thai
            - πŸ₯— Salads, Sandwiches
            - 🍰 Desserts (cakes, ice cream)
            - 🍳 Breakfast foods
            - And many more!
            """)
    
    # Footer
    st.markdown("---")
    st.markdown(
        "<div style='text-align: center; color: #666; font-size: 0.9rem;'>"
        "Built with Streamlit β€’ ConvNeXt V2 β€’ Food-101 Dataset"
        "</div>",
        unsafe_allow_html=True
    )

# ============================================================
# RUN
# ============================================================

if __name__ == "__main__":
    main()