Spaces:
Running
Running
File size: 27,213 Bytes
a3540f6 6b2d096 32142a3 6b2d096 32142a3 6b2d096 a3540f6 6b2d096 32142a3 a3540f6 be7e871 6b2d096 32142a3 a3540f6 6b2d096 be7e871 6b2d096 a3540f6 be7e871 6b2d096 32142a3 6b2d096 32142a3 6b2d096 32142a3 be7e871 6b2d096 32142a3 6b2d096 32142a3 be7e871 32142a3 a3540f6 32142a3 6b2d096 32142a3 be7e871 6b2d096 a3540f6 6b2d096 a3540f6 32142a3 6b2d096 32142a3 6b2d096 32142a3 6b2d096 a3540f6 be7e871 a3540f6 be7e871 a3540f6 be7e871 32142a3 be7e871 a3540f6 be7e871 32142a3 be7e871 32142a3 be7e871 32142a3 be7e871 32142a3 6b2d096 a3540f6 3272329 a3540f6 6b2d096 a3540f6 32142a3 a3540f6 1a08db2 a3540f6 6b2d096 a3540f6 be7e871 a3540f6 6b2d096 a3540f6 6b2d096 a3540f6 6b2d096 a3540f6 be7e871 6b2d096 a3540f6 6b2d096 a3540f6 6b2d096 a3540f6 6b2d096 a3540f6 6b2d096 a3540f6 1a08db2 6b2d096 a3540f6 1a08db2 a3540f6 6b2d096 a3540f6 32142a3 6b2d096 a3540f6 6b2d096 a3540f6 6b2d096 a3540f6 32142a3 6b2d096 a3540f6 32142a3 6b2d096 a3540f6 32142a3 6b2d096 a3540f6 32142a3 a3540f6 32142a3 a3540f6 32142a3 a3540f6 32142a3 a3540f6 32142a3 a3540f6 32142a3 a3540f6 32142a3 a3540f6 32142a3 a3540f6 32142a3 d0122da 32142a3 6b2d096 a3540f6 32142a3 a3540f6 be7e871 32142a3 a3540f6 32142a3 a3540f6 32142a3 be7e871 32142a3 a3540f6 32142a3 a3540f6 1a08db2 a3540f6 32142a3 a3540f6 32142a3 a3540f6 6b2d096 32142a3 6b2d096 a3540f6 be7e871 32142a3 6b2d096 a3540f6 32142a3 1a08db2 6b2d096 a3540f6 d0122da 6b2d096 a3540f6 6b2d096 a3540f6 6b2d096 a3540f6 32142a3 6b2d096 a3540f6 1a08db2 a3540f6 32142a3 6b2d096 a3540f6 be7e871 |
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 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 |
# -*- coding: utf-8 -*-
import streamlit as st
from streamlit.runtime.uploaded_file_manager import UploadedFile
import tensorflow as tf
import pandas as pd
from PIL import Image
# 🔹 Expand the Page Layout
st.set_page_config(layout="wide")
# 2. Inject CSS to override the default max-width and set it to 90%
st.markdown(
"""
<style>
/* Target the main block container */
.block-container {
/* Set the max-width to 90% of the viewport */
max-width: 90% !important;
/* Optional: Adjust padding if needed */
/* padding-left: 2rem !important; */
/* padding-right: 2rem !important; */
/* padding-top: 1rem !important; */ /* Adjust top padding */
/* padding-bottom: 1rem !important; */
/* Ensure it remains centered */
margin: auto !important;
}
</style>
""",
unsafe_allow_html=True
)
# --- Constants and Data ---
current_model = "Model Mini"
new_model = "Food Vision"
# ... (class_names, top_ten_dict, last_ten_dict remain the same) ...
class_names = ['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']
top_ten_dict = {
"class_name": ["edamame", "macarons", "oysters", "pho", "mussels",
"sashimi", "seaweed_salad", "dumplings", "guacamole", "onion_rings"],
"f1-score": [0.964427, 0.900433, 0.853119, 0.852652, 0.850622,
0.844794, 0.834356, 0.833006, 0.83209, 0.831967]
}
last_ten_dict = {
"class_name": ["chocolate_mousse", "tuna_tartare", "scallops", "huevos_rancheros",
"foie_gras", "steak", "bread_pudding", "ravioli", "pork_chop", "apple_pie"],
"f1-score": [0.413793, 0.399254, 0.383693, 0.367698, 0.354497,
0.340426, 0.340045, 0.339785, 0.324826, 0.282407]
}
# 🔹 Custom CSS for Alignment and Spacing
st.markdown(
"""
<style>
/* Center content H, align V top, reduce padding/min-height */
.centered {
display: flex;
flex-direction: column;
align-items: center; /* Keep horizontal centering */
justify-content: flex-start; /* Align content to the top by default */
text-align: center;
width: 100%;
min-height: 100px; /* Reduced minimum height */
padding-top: 5px; /* Reduced padding */
padding-bottom: 10px;
height: 100%; /* Allow div to take full column height if needed */
}
/* Ensure subheaders within columns have less top margin */
.centered h3 { /* Targets the subheaders like "1. Provide Image" */
margin-top: 0px !important;
padding-top: 0px !important;
margin-bottom: 15px !important; /* Add space below subheader */
}
/* Style file uploader (ensure consistent padding) */
div[data-testid="stFileUploader"] > section {
padding: 0;
display: flex; /* Use flex for centering button inside */
justify-content: center;
}
div[data-testid="stFileUploader"] label { /* Style the button-like label */
margin-bottom: 10px; /* Space below uploader */
}
div[data-testid="stCameraInput"] label { /* Style the camera input label */
margin-bottom: 10px; /* Space below camera input */
}
/* Center images and standardize size */
.centered img {
display: block;
margin-left: auto;
margin-right: auto;
max-width: 200px;
max-height: 200px;
width: auto;
height: auto;
object-fit: contain;
border-radius: 20px;
margin-bottom: 10px; /* Reduced space below image */
}
/* Align the TOPS of the columns (This might be overridden by .centered justify-content) */
div[data-testid="stVerticalBlock"] div[data-testid="stHorizontalBlock"] {
align-items: flex-start !important; /* Align column tops */
}
/* Style the radio buttons */
div[data-testid="stRadio"] > label {
font-weight: bold;
margin-bottom: 5px !important; /* Reduced margin */
padding-top: 0 !important;
}
div[data-testid="stRadio"] > div {
display: flex;
justify-content: center;
gap: 10px; /* Reduced gap */
margin-bottom: 10px; /* Add space below radio group */
}
/* Style the button */
div[data-testid="stButton"] > button {
width: 80%;
margin-top: 15px; /* Reduced margin */
}
/* Reduce space BELOW the caption ABOVE the columns */
div[data-testid="stCaptionContainer"] {
padding-bottom: 0px !important;
margin-bottom: -10px !important; /* Negative margin pulls following elements up */
}
/* Reduce space ABOVE the main H2 header for the demo section */
h2[data-testid="stHeading"]:has(+ div[data-testid="stCaptionContainer"]) {
margin-bottom: 5px !important; /* Space between header and caption */
}
/* Reduce space below the final divider before the demo H2 header */
hr[data-testid="stDivider"] + h2[data-testid="stHeading"] {
margin-top: -15px !important; /* Pull header closer to divider */
}
/* --- NEW CSS for Larger Centered Arrows --- */
.arrow-indicator {
font-size: 3em; /* Make the arrow much bigger */
display: block; /* Ensure it takes up its own line */
text-align: center; /* Center the arrow horizontally within its container */
line-height: 1; /* Adjust line height if needed */
margin: auto; /* Center the block element itself if needed */
}
/* Explicitly center the content vertically for the arrow columns */
/* Using :has() is modern CSS, may need alternative for older browsers */
.centered:has(.arrow-indicator) {
justify-content: center !important; /* Explicitly center content vertically */
padding-top: 0 !important; /* Remove any unwanted top padding */
min-height: 150px; /* Ensure enough height for centering relative to image */
}
</style>
""",
unsafe_allow_html=True
)
# --- Page Title and Intro ---
st.divider()
st.title("Food Vision Demo App 🍔🧠")
st.header("A food vision app using a CNN model fine-tuned on EfficientNet.")
st.divider()
# --- Explanations (Collapsible) ---
# ... (Keep the expanders as they were) ...
with st.expander("Learn More: What is a CNN?"):
st.write("""
A Neural Network is a system inspired by the human brain, composed of interconnected nodes (neurons) organized in layers: an input layer, one or more hidden layers, and an output layer.
Data (like text, numbers, images) is fed into the input layer, encoded as numbers. This information flows through the network, undergoing mathematical transformations at each node based on learned 'weights'.
The network 'learns' by adjusting these weights during training to minimize the difference between its classifications and the actual outcomes.
""")
# Consider adding a simple diagram URL if available
# st.image("url_to_neural_network_diagram.png")
st.write("""
A **Convolutional Neural Network (CNN)** is a specialized type of neural network particularly effective for processing grid-like data, such as images and videos.
CNNs use special layers called 'convolutional layers' that apply filters to input images to automatically learn hierarchical patterns, like edges, textures, and shapes. This makes them excellent for visual recognition tasks.
""")
with st.expander("Learn More: Sample CNN Code Snippet (TensorFlow/Keras)"):
st.write("This is a simplified example showing key components like using a pre-trained base model (EfficientNet), adding custom layers, enabling mixed precision (for faster training), and compiling the model.")
code = """
import tensorflow as tf
from tensorflow.keras import layers, models, applications
from tensorflow.keras import mixed_precision
# --- Configuration ---
IMAGE_SHAPE = (224, 224, 3)
NUM_CLASSES = 101 # Example number of food classes
# --- Enable Mixed Precision (Optional but recommended for speed) ---
# mixed_precision.set_global_policy("mixed_float16")
# --- Data Augmentation Layer ---
# Define data augmentation transformations here
data_augmentation = tf.keras.Sequential([
layers.RandomFlip("horizontal"),
layers.RandomRotation(0.2),
layers.RandomZoom(0.2),
layers.RandomHeight(0.2),
layers.RandomWidth(0.2),
# Rescaling might be part of EfficientNet preprocessing, check docs
], name="data_augmentation")
# --- Build the Model using Functional API ---
# 1. Input Layer
inputs = layers.Input(shape=IMAGE_SHAPE, name="input_layer")
# 2. Data Augmentation (applied during training)
# x = data_augmentation(inputs) # Apply augmentation first
# 3. Base Model (EfficientNetB0) - Transfer Learning
base_model = applications.EfficientNetB0(include_top=False, # Don't include the final classification layer
weights='imagenet', # Load pre-trained weights
input_shape=IMAGE_SHAPE)
base_model.trainable = False # Freeze the base model initially
# Pass input through base model (ensure correct preprocessing if not done before)
# EfficientNet often has a preprocessing function or handles rescaling internally
x = base_model(inputs, training=False) # Use inputs directly if augmentation is after base_model
# 4. Pooling Layer
x = layers.GlobalAveragePooling2D(name="global_average_pooling")(x)
# 5. Output Layer (Dense)
# The number of units must match the number of classes
# Use float32 for the final layer for numerical stability with mixed precision
logits = layers.Dense(NUM_CLASSES, name="dense_logits")(x)
outputs = layers.Activation("softmax", dtype=tf.float32, name="softmax_output")(logits)
# 6. Create the Model
model = models.Model(inputs=inputs, outputs=outputs)
# --- Compile the Model ---
# Use Adam optimizer (common choice)
optimizer = tf.keras.optimizers.Adam()
# If using mixed precision, wrap the optimizer
# optimizer = mixed_precision.LossScaleOptimizer(optimizer)
model.compile(loss="categorical_crossentropy", # Use if labels are one-hot encoded
optimizer=optimizer,
metrics=["accuracy"])
# --- Model Summary ---
# model.summary()
# --- Train the Model (Example) ---
# history = model.fit(train_data,
# epochs=5,
# validation_data=test_data,
# ...)
"""
st.code(code, language="python")
with st.expander("Learn More: What is EfficientNet?"):
st.write("""
EfficientNet is a family of Convolutional Neural Networks (CNNs) developed by Google Brain.
Its key innovation is a method called **compound scaling**. Instead of arbitrarily increasing just the depth (number of layers), width (number of channels), or input image resolution, EfficientNet scales all three dimensions simultaneously using a fixed set of scaling coefficients.
This balanced scaling approach allows EfficientNet models (like EfficientNetB0, B1, ..., B7) to achieve state-of-the-art accuracy on image classification tasks while being significantly smaller and faster (more computationally efficient) than previous models with similar accuracy.
""")
with st.expander("Learn More: What is Fine-Tuning?"):
st.write("""
**Fine-tuning** is a transfer learning technique where you take a model pre-trained on a large dataset (like ImageNet, which contains millions of general images) and train it further on a smaller, specific dataset (like our Food-101 dataset).
**Why Fine-Tune?**
1. **Leverage Existing Knowledge:** The pre-trained model has already learned general visual features (edges, textures, shapes) from the large dataset.
2. **Faster Training:** You don't need to train the entire network from scratch, saving significant time and computational resources.
3. **Better Performance on Small Datasets:** It often leads to better results than training from scratch, especially when your specific dataset is relatively small.
**Process:**
1. **Load Pre-trained Model:** Load a model (like EfficientNet) with its pre-trained weights, typically excluding its final classification layer.
2. **Freeze Base Layers:** Initially, keep the weights of the pre-trained layers frozen (`trainable = False`).
3. **Add New Layers:** Add new layers on top (e.g., Pooling, Dense layers) suitable for your specific task (e.g., classifying 101 food types).
4. **Train Top Layers:** Train *only* the new layers on your dataset for a few epochs.
5. **(Optional but common) Unfreeze Some Layers:** Unfreeze some of the later layers of the base model (`trainable = True`).
6. **Train with Low Learning Rate:** Continue training the entire network (or the unfrozen parts) with a very low learning rate. This allows the pre-trained weights to adapt slightly to the nuances of your specific dataset without drastically changing the learned general features.
""")
with st.expander("Learn More: Fine-Tuning Code Snippet (TensorFlow/Keras)"):
st.write("This snippet shows how to unfreeze layers and re-compile the model for fine-tuning, typically done *after* initial feature extraction training.")
tune_code = """
# --- Load weights from initial training phase (where base_model was frozen) ---
# model.load_weights(checkpoint_path_feature_extraction)
# --- Unfreeze some or all layers of the base model ---
base_model.trainable = True
# --- Optional: Freeze earlier layers again (fine-tune only later layers) ---
# print(f"Number of layers in base model: {len(base_model.layers)}")
# Fine-tune from this layer onwards
# fine_tune_at = 100 # Example: Unfreeze layers from index 100 onwards
# for layer in base_model.layers[:fine_tune_at]:
# layer.trainable = False
# --- Re-compile the Model with a Lower Learning Rate ---
# Lowering the learning rate is crucial for fine-tuning to avoid
# destroying the pre-trained weights.
LOW_LEARNING_RATE = 0.0001 # Example: 10x smaller than initial LR
optimizer = tf.keras.optimizers.Adam(learning_rate=LOW_LEARNING_RATE)
# If using mixed precision:
# optimizer = mixed_precision.LossScaleOptimizer(tf.keras.optimizers.Adam(learning_rate=LOW_LEARNING_RATE))
model.compile(loss="categorical_crossentropy",
optimizer=optimizer, # Use the optimizer with the low learning rate
metrics=["accuracy"])
# --- Continue Training (Fine-tuning) ---
# history_fine_tune = model.fit(train_data,
# epochs=initial_epochs + 5, # Train for a few more epochs
# initial_epoch=history.epoch[-1], # Start where previous training left off
# validation_data=test_data,
# ...)
"""
st.code(tune_code, language="python")
st.divider()
# --- Model Build Details ---
st.subheader("Model Building Details")
formatted_class_names = [food.replace("_", " ").title() for food in class_names]
st.write(f"The model was built using the **Food-101 dataset**.")
with st.expander("View All 101 Food Classes"):
st.write(f"The dataset consists of 101 classes of food: {', '.join(formatted_class_names)}")
st.info("When Classifying, please provide an image belonging to one of these 101 classes. The model has not been trained on other types of food or objects.")
st.divider()
# --- Model Performance ---
st.subheader("Model Performance Insights")
st.write("""
After training, some food classes are classified more accurately than others.
This can be due to factors like the number of training images available for each class, visual similarity between classes, and image quality.
We use the **F1-score** to evaluate performance per class, as it balances precision and recall.
""")
with st.expander("What is the F1-Score?"):
st.write("""
The **F1-score** is a metric used to evaluate a model's accuracy on classification tasks, especially when dealing with imbalanced datasets (where some classes have many more samples than others). It's the harmonic mean of **Precision** and **Recall**.
* **Precision:** Out of all the times the model predicted a specific class (e.g., "Pizza"), what proportion were actually correct?
$$ \text{Precision} = \\frac{\\text{True Positives}}{\\text{True Positives} + \\text{False Positives}} $$
* **Recall (Sensitivity):** Out of all the actual instances of a specific class (e.g., all the real Pizza images), what proportion did the model correctly identify?
$$ \text{Recall} = \\frac{\\text{True Positives}}{\\text{True Positives} + \\text{False Negatives}} $$
The F1-score combines these two:
""")
st.latex(r"F_1 = 2 \times \frac{\text{Precision} \times \text{Recall}}{\text{Precision} + \text{Recall}}")
st.write("An F1-score ranges from 0 (worst) to 1 (best - perfect precision and recall).")
# --- Top/Last 10 Charts ---
st.subheader("Top and Least Performing Classes (by F1-Score)")
with st.container():
top_ten_df = pd.DataFrame(top_ten_dict).sort_values("f1-score", ascending=False)
last_ten_df = pd.DataFrame(last_ten_dict).sort_values("f1-score", ascending=True)
top_ten_df['class_name_display'] = top_ten_df['class_name'].str.replace('_', ' ').str.title()
last_ten_df['class_name_display'] = last_ten_df['class_name'].str.replace('_', ' ').str.title()
col1, col2 = st.columns(2)
with col1:
st.write("**Top 10 Classes**")
st.bar_chart(top_ten_df.set_index('class_name_display')['f1-score'], use_container_width=True)
with col2:
st.write("**Bottom 10 Classes**")
st.bar_chart(last_ten_df.set_index('class_name_display')['f1-score'], use_container_width=True, color="#ff748c")
st.divider() # Divider before the interactive section
# --- Helper Functions ---
@st.cache_resource
def load_model(filepath):
"""Loads a Tensorflow Keras Model."""
st.write(f"Cache miss: Loading model from {filepath}")
try:
model = tf.keras.models.load_model(filepath)
return model
except Exception as e:
st.error(f"Error loading model from {filepath}: {e}")
return None
def load_prep_image(image_input: UploadedFile, img_shape=224):
"""Reads and preprocesses an image for EfficientNet prediction."""
try:
bytes_data = image_input.getvalue()
image_tensor = tf.io.decode_image(bytes_data, channels=3)
image_tensor_resized = tf.image.resize(image_tensor, [img_shape, img_shape])
image_tensor_expanded = tf.expand_dims(image_tensor_resized, axis=0)
return image_tensor_expanded
except Exception as e:
st.error(f"Error processing image: {e}")
return None
def predict_using_model(image_input: UploadedFile, model_path: str) -> tuple[str | None, float | None]:
"""Predicts the class name and probability for an image."""
if image_input is None:
st.warning("No image provided for prediction.")
return None, None
processed_image = load_prep_image(image_input)
if processed_image is None:
return None, None
model = load_model(model_path)
if model is None:
return None, None
try:
with st.spinner("🤖 Model is predicting..."):
pred_prob = model.predict(processed_image)
predicted_index = tf.argmax(pred_prob, axis=1).numpy()[0]
predicted_class_name = class_names[predicted_index]
predicted_probability = float(tf.reduce_max(pred_prob).numpy())
return predicted_class_name, predicted_probability
except Exception as e:
st.error(f"Prediction failed: {e}")
return None, None
# --- Interactive Demo Section ---
# Header and Caption for the interactive section
st.header(f"Try the Models: :blue[{current_model}] & :blue[{new_model}]")
st.caption("_Model performance may vary. Models are periodically updated._")
# Initialize session state keys if they don't exist
if "prediction_result" not in st.session_state:
st.session_state.prediction_result = None
if "predicted_image_bytes" not in st.session_state:
st.session_state.predicted_image_bytes = None
if "predicted_prob" not in st.session_state:
st.session_state.predicted_prob = None
# Use columns for layout
cols = st.columns([3, 0.5, 2, 0.5, 3], gap="medium") # Keep original column ratios
# --- Column 1: Image Input ---
with cols[0]:
st.markdown('<div class="centered">', unsafe_allow_html=True) # Apply centering
st.subheader("1. Provide an Image") # H3 targeted by CSS
image_source = st.radio(
"Choose image source:",
("Upload Image", "Use Camera"),
key="image_source",
horizontal=True,
label_visibility="collapsed"
)
uploaded_image = None
image_bytes_for_state = None
if image_source == "Upload Image":
uploaded_image = st.file_uploader(
"Upload (.png, .jpg, .jpeg)",
type=["png", "jpg", "jpeg"],
accept_multiple_files=False,
key="uploader",
label_visibility="collapsed"
)
elif image_source == "Use Camera":
uploaded_image = st.camera_input(
"Take a picture",
key="camera_input",
label_visibility="collapsed"
)
# Display uploaded image preview
if uploaded_image:
image_bytes_for_state = uploaded_image.getvalue()
st.image(image_bytes_for_state, caption="Your image", width=200)
# Removed success message to save space
else:
st.info("Upload or take a picture.")
st.markdown('</div>', unsafe_allow_html=True)
# --- Column 2: Arrow 1 ---
with cols[1]:
# Use inline style to center content vertically
st.markdown('<div class="centered" style="justify-content: center;">', unsafe_allow_html=True)
st.markdown('<span class="arrow-indicator">➡️</span>', unsafe_allow_html=True) # Apply arrow-indicator class
st.markdown('</div>', unsafe_allow_html=True)
# --- Column 3: Model Selection & Prediction ---
with cols[2]:
st.markdown('<div class="centered">', unsafe_allow_html=True)
st.subheader("2. Select Model") # H3 targeted by CSS
chosen_model = st.radio(
"Pick a Model:",
(current_model, new_model),
key="model_choice",
horizontal=True,
label_visibility="collapsed"
)
model_path_to_use = ""
model_image_path = ""
if chosen_model == current_model:
model_image_path = "content/brain.png"
model_path_to_use = "model_mini_Food101.keras"
elif chosen_model == new_model:
model_image_path = "content/creativity_15557951.png"
model_path_to_use = "FoodVision.keras"
try:
if model_image_path:
st.image(model_image_path, width=150) # Keep model image
except Exception as e:
st.warning(f"Could not load model image: {model_image_path}")
# Prediction Button
predict_button = st.button(
label="Classify Food!",
icon="⚛️",
type="primary",
use_container_width=True,
disabled=not uploaded_image or not model_path_to_use
)
if predict_button:
if uploaded_image and model_path_to_use:
result_class, result_prob = predict_using_model(uploaded_image, model_path=model_path_to_use)
st.session_state.prediction_result = result_class
st.session_state.predicted_prob = result_prob
st.session_state.predicted_image_bytes = image_bytes_for_state
else:
st.warning("Please provide an image and select a valid model.")
st.markdown('</div>', unsafe_allow_html=True)
# --- Column 4: Arrow 2 ---
with cols[3]:
# Use inline style to center content vertically
st.markdown('<div class="centered" style="justify-content: center;">', unsafe_allow_html=True)
st.markdown('<span class="arrow-indicator">➡️</span>', unsafe_allow_html=True) # Apply arrow-indicator class
st.markdown('</div>', unsafe_allow_html=True)
# --- Column 5: Output ---
with cols[4]:
st.markdown('<div class="centered">', unsafe_allow_html=True)
st.subheader("3. Classification Result") # H3 targeted by CSS
if st.session_state.prediction_result and st.session_state.predicted_image_bytes:
st.image(st.session_state.predicted_image_bytes, caption="Image Analyzed", width=200)
result_class = st.session_state.prediction_result
probability = st.session_state.predicted_prob
if "_" in result_class:
modified_class = result_class.replace("_", " ").title()
else:
modified_class = result_class.title()
st.success(f"Prediction: **:blue[{modified_class}]**")
if probability:
st.write(f"Confidence: {probability:.1%}") # Slightly less verbose confidence
elif predict_button:
st.error("Classification failed or image invalid.")
else:
st.info("Result will appear here.")
st.markdown('</div>', unsafe_allow_html=True)
# --- Footer or Final Divider ---
st.divider() # Optional: remove if you want less space at the bottom |