Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,7 +4,8 @@
|
|
| 4 |
# IMPROVEMENTS:
|
| 5 |
# -------------
|
| 6 |
# β
Mobile-friendly single-column layout
|
| 7 |
-
# β
|
|
|
|
| 8 |
# β
Simplified, responsive CSS
|
| 9 |
# β
Better error handling
|
| 10 |
# β
Loads model from Hugging Face Hub OR local file
|
|
@@ -20,6 +21,7 @@ from torchvision import transforms
|
|
| 20 |
from PIL import Image
|
| 21 |
import timm
|
| 22 |
from pathlib import Path
|
|
|
|
| 23 |
|
| 24 |
# ============================================================
|
| 25 |
# PAGE CONFIGURATION
|
|
@@ -29,9 +31,20 @@ st.set_page_config(
|
|
| 29 |
page_title="π FoodVision AI",
|
| 30 |
page_icon="π",
|
| 31 |
layout="centered",
|
| 32 |
-
initial_sidebar_state="collapsed"
|
| 33 |
)
|
| 34 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
# ============================================================
|
| 36 |
# MINIMAL CSS (Mobile-First)
|
| 37 |
# ============================================================
|
|
@@ -93,8 +106,13 @@ st.markdown("""
|
|
| 93 |
font-size: 0.95rem;
|
| 94 |
}
|
| 95 |
|
| 96 |
-
/*
|
| 97 |
-
.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
margin-top: 1rem;
|
| 99 |
}
|
| 100 |
</style>
|
|
@@ -127,6 +145,14 @@ FOOD_CLASSES = [
|
|
| 127 |
"sushi", "tacos", "takoyaki", "tiramisu", "tuna_tartare", "waffles"
|
| 128 |
]
|
| 129 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
# ============================================================
|
| 131 |
# MODEL LOADING
|
| 132 |
# ============================================================
|
|
@@ -257,106 +283,142 @@ def main():
|
|
| 257 |
uploaded_file = st.file_uploader(
|
| 258 |
"Choose a food image",
|
| 259 |
type=['jpg', 'jpeg', 'png', 'webp'],
|
| 260 |
-
|
| 261 |
)
|
| 262 |
|
| 263 |
# Camera input (below uploader)
|
| 264 |
st.markdown("**Or use your camera:**")
|
| 265 |
camera_photo = st.camera_input(
|
| 266 |
"Take a picture",
|
| 267 |
-
|
| 268 |
)
|
| 269 |
|
| 270 |
# Determine which image to use
|
| 271 |
image_source = None
|
| 272 |
source_name = ""
|
|
|
|
| 273 |
|
| 274 |
if camera_photo is not None:
|
| 275 |
image_source = camera_photo
|
| 276 |
source_name = "camera"
|
|
|
|
| 277 |
elif uploaded_file is not None:
|
| 278 |
image_source = uploaded_file
|
| 279 |
source_name = "upload"
|
|
|
|
| 280 |
|
| 281 |
-
# Process image
|
| 282 |
-
if image_source is not None:
|
| 283 |
try:
|
| 284 |
-
#
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
# Show image preview
|
| 288 |
-
st.image(image, caption=f"Image from {source_name}", use_column_width=True)
|
| 289 |
-
|
| 290 |
-
# Auto-predict with spinner
|
| 291 |
-
with st.spinner("π§ Analyzing your food..."):
|
| 292 |
-
img_tensor = preprocess_image(image)
|
| 293 |
-
predictions = predict(model, img_tensor, device, top_k=3)
|
| 294 |
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 306 |
|
| 307 |
-
#
|
| 308 |
-
st.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 309 |
|
| 310 |
-
|
| 311 |
-
|
|
|
|
|
|
|
|
|
|
| 312 |
|
| 313 |
-
st.markdown(f"**{emoji} {food}**")
|
| 314 |
st.markdown(f"""
|
| 315 |
-
<div class="
|
| 316 |
-
<
|
| 317 |
-
|
| 318 |
-
</div>
|
| 319 |
</div>
|
| 320 |
""", unsafe_allow_html=True)
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 332 |
|
| 333 |
except Exception as e:
|
| 334 |
st.error(f"β Error: {str(e)}")
|
| 335 |
st.info("Try a different image or check if the file is corrupted")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
|
| 337 |
else:
|
| 338 |
-
# Instructions
|
| 339 |
-
st.
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
st.
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
st.
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
|
|
|
| 360 |
|
| 361 |
# Footer
|
| 362 |
st.markdown("---")
|
|
|
|
| 4 |
# IMPROVEMENTS:
|
| 5 |
# -------------
|
| 6 |
# β
Mobile-friendly single-column layout
|
| 7 |
+
# β
Fixed mobile upload issues with session state
|
| 8 |
+
# β
Persistent predictions across reruns
|
| 9 |
# β
Simplified, responsive CSS
|
| 10 |
# β
Better error handling
|
| 11 |
# β
Loads model from Hugging Face Hub OR local file
|
|
|
|
| 21 |
from PIL import Image
|
| 22 |
import timm
|
| 23 |
from pathlib import Path
|
| 24 |
+
import hashlib
|
| 25 |
|
| 26 |
# ============================================================
|
| 27 |
# PAGE CONFIGURATION
|
|
|
|
| 31 |
page_title="π FoodVision AI",
|
| 32 |
page_icon="π",
|
| 33 |
layout="centered",
|
| 34 |
+
initial_sidebar_state="collapsed"
|
| 35 |
)
|
| 36 |
|
| 37 |
+
# ============================================================
|
| 38 |
+
# SESSION STATE INITIALIZATION
|
| 39 |
+
# ============================================================
|
| 40 |
+
|
| 41 |
+
if 'predictions' not in st.session_state:
|
| 42 |
+
st.session_state.predictions = None
|
| 43 |
+
if 'processed_image' not in st.session_state:
|
| 44 |
+
st.session_state.processed_image = None
|
| 45 |
+
if 'last_image_hash' not in st.session_state:
|
| 46 |
+
st.session_state.last_image_hash = None
|
| 47 |
+
|
| 48 |
# ============================================================
|
| 49 |
# MINIMAL CSS (Mobile-First)
|
| 50 |
# ============================================================
|
|
|
|
| 106 |
font-size: 0.95rem;
|
| 107 |
}
|
| 108 |
|
| 109 |
+
/* Make file uploader more visible */
|
| 110 |
+
.stFileUploader {
|
| 111 |
+
margin-bottom: 1rem;
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
/* Make camera input more visible */
|
| 115 |
+
.stCameraInput {
|
| 116 |
margin-top: 1rem;
|
| 117 |
}
|
| 118 |
</style>
|
|
|
|
| 145 |
"sushi", "tacos", "takoyaki", "tiramisu", "tuna_tartare", "waffles"
|
| 146 |
]
|
| 147 |
|
| 148 |
+
# ============================================================
|
| 149 |
+
# HELPER FUNCTIONS
|
| 150 |
+
# ============================================================
|
| 151 |
+
|
| 152 |
+
def get_image_hash(image_bytes):
|
| 153 |
+
"""Create a hash of image bytes to detect if it's a new image."""
|
| 154 |
+
return hashlib.md5(image_bytes).hexdigest()
|
| 155 |
+
|
| 156 |
# ============================================================
|
| 157 |
# MODEL LOADING
|
| 158 |
# ============================================================
|
|
|
|
| 283 |
uploaded_file = st.file_uploader(
|
| 284 |
"Choose a food image",
|
| 285 |
type=['jpg', 'jpeg', 'png', 'webp'],
|
| 286 |
+
key="file_uploader"
|
| 287 |
)
|
| 288 |
|
| 289 |
# Camera input (below uploader)
|
| 290 |
st.markdown("**Or use your camera:**")
|
| 291 |
camera_photo = st.camera_input(
|
| 292 |
"Take a picture",
|
| 293 |
+
key="camera_input"
|
| 294 |
)
|
| 295 |
|
| 296 |
# Determine which image to use
|
| 297 |
image_source = None
|
| 298 |
source_name = ""
|
| 299 |
+
image_bytes = None
|
| 300 |
|
| 301 |
if camera_photo is not None:
|
| 302 |
image_source = camera_photo
|
| 303 |
source_name = "camera"
|
| 304 |
+
image_bytes = camera_photo.getvalue()
|
| 305 |
elif uploaded_file is not None:
|
| 306 |
image_source = uploaded_file
|
| 307 |
source_name = "upload"
|
| 308 |
+
image_bytes = uploaded_file.getvalue()
|
| 309 |
|
| 310 |
+
# Process image if we have one
|
| 311 |
+
if image_source is not None and image_bytes is not None:
|
| 312 |
try:
|
| 313 |
+
# Check if this is a new image
|
| 314 |
+
current_hash = get_image_hash(image_bytes)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 315 |
|
| 316 |
+
# Only process if it's a new image
|
| 317 |
+
if current_hash != st.session_state.last_image_hash:
|
| 318 |
+
# Load image
|
| 319 |
+
image = Image.open(image_source)
|
| 320 |
+
|
| 321 |
+
# Store image in session state
|
| 322 |
+
st.session_state.processed_image = image
|
| 323 |
+
st.session_state.last_image_hash = current_hash
|
| 324 |
+
|
| 325 |
+
# Show loading indicator
|
| 326 |
+
with st.spinner("π§ Analyzing your food..."):
|
| 327 |
+
# Preprocess and predict
|
| 328 |
+
img_tensor = preprocess_image(image)
|
| 329 |
+
predictions = predict(model, img_tensor, device, top_k=3)
|
| 330 |
+
|
| 331 |
+
# Store predictions in session state
|
| 332 |
+
st.session_state.predictions = predictions
|
| 333 |
|
| 334 |
+
# Display results (from session state)
|
| 335 |
+
if st.session_state.processed_image is not None:
|
| 336 |
+
# Show image preview
|
| 337 |
+
st.image(
|
| 338 |
+
st.session_state.processed_image,
|
| 339 |
+
caption=f"Image from {source_name}",
|
| 340 |
+
use_column_width=True
|
| 341 |
+
)
|
| 342 |
|
| 343 |
+
if st.session_state.predictions is not None:
|
| 344 |
+
st.markdown("---")
|
| 345 |
+
|
| 346 |
+
# Display top prediction prominently
|
| 347 |
+
top_food, top_conf = st.session_state.predictions[0]
|
| 348 |
|
|
|
|
| 349 |
st.markdown(f"""
|
| 350 |
+
<div class="prediction-card">
|
| 351 |
+
<h2>π {top_food}</h2>
|
| 352 |
+
<h3>{top_conf:.1f}% Confidence</h3>
|
|
|
|
| 353 |
</div>
|
| 354 |
""", unsafe_allow_html=True)
|
| 355 |
+
|
| 356 |
+
# Show all top-3 predictions
|
| 357 |
+
st.markdown("### π Top 3 Predictions")
|
| 358 |
+
|
| 359 |
+
for i, (food, conf) in enumerate(st.session_state.predictions, 1):
|
| 360 |
+
emoji = "π₯" if i == 1 else "π₯" if i == 2 else "π₯"
|
| 361 |
+
|
| 362 |
+
st.markdown(f"**{emoji} {food}**")
|
| 363 |
+
st.markdown(f"""
|
| 364 |
+
<div class="conf-bar">
|
| 365 |
+
<div class="conf-fill" style="width: {conf}%">
|
| 366 |
+
{conf:.1f}%
|
| 367 |
+
</div>
|
| 368 |
+
</div>
|
| 369 |
+
""", unsafe_allow_html=True)
|
| 370 |
+
|
| 371 |
+
# Feedback based on confidence
|
| 372 |
+
st.markdown("---")
|
| 373 |
+
if top_conf > 90:
|
| 374 |
+
st.success("π **Very confident!** The model is very sure about this prediction.")
|
| 375 |
+
elif top_conf > 70:
|
| 376 |
+
st.success("π **Good confidence!** This looks like a solid prediction.")
|
| 377 |
+
elif top_conf > 50:
|
| 378 |
+
st.warning("π€ **Moderate confidence.** The food might be ambiguous or partially visible.")
|
| 379 |
+
else:
|
| 380 |
+
st.warning("π **Low confidence.** Try a clearer photo with better lighting.")
|
| 381 |
+
|
| 382 |
+
# Add a clear button to reset
|
| 383 |
+
if st.button("π Analyze Another Image", use_container_width=True):
|
| 384 |
+
st.session_state.predictions = None
|
| 385 |
+
st.session_state.processed_image = None
|
| 386 |
+
st.session_state.last_image_hash = None
|
| 387 |
+
st.rerun()
|
| 388 |
|
| 389 |
except Exception as e:
|
| 390 |
st.error(f"β Error: {str(e)}")
|
| 391 |
st.info("Try a different image or check if the file is corrupted")
|
| 392 |
+
|
| 393 |
+
# Reset state on error
|
| 394 |
+
st.session_state.predictions = None
|
| 395 |
+
st.session_state.processed_image = None
|
| 396 |
+
st.session_state.last_image_hash = None
|
| 397 |
|
| 398 |
else:
|
| 399 |
+
# Instructions (only show if no predictions)
|
| 400 |
+
if st.session_state.predictions is None:
|
| 401 |
+
st.info("π Upload a food image or take a photo to get started!")
|
| 402 |
+
|
| 403 |
+
with st.expander("π‘ Tips for Best Results"):
|
| 404 |
+
st.markdown("""
|
| 405 |
+
- Use clear, well-lit photos
|
| 406 |
+
- Make sure food is the main subject
|
| 407 |
+
- Avoid heavily filtered images
|
| 408 |
+
- Try different angles if confidence is low
|
| 409 |
+
- Works best with common dishes
|
| 410 |
+
""")
|
| 411 |
+
|
| 412 |
+
with st.expander("π½οΈ What can it recognize?"):
|
| 413 |
+
st.markdown("""
|
| 414 |
+
The model can identify **101 popular dishes** including:
|
| 415 |
+
- π Pizza, Pasta, Burgers
|
| 416 |
+
- π£ Sushi, Ramen, Pad Thai
|
| 417 |
+
- π₯ Salads, Sandwiches
|
| 418 |
+
- π° Desserts (cakes, ice cream, etc.)
|
| 419 |
+
- π³ Breakfast foods
|
| 420 |
+
- And many more!
|
| 421 |
+
""")
|
| 422 |
|
| 423 |
# Footer
|
| 424 |
st.markdown("---")
|