FoodMacro / app.py
carsten12's picture
Update app.py
fb69776 verified
Raw History Blame Contribute Delete
6.41 kB
# app.py
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
import streamlit as st
import numpy as np
from PIL import Image
import tensorflow as tf
import traceback
import torch
# --- Constants ---
CALORIES_MAX = 9485.81543
MASS_MAX = 7975
FAT_MAX = 875.5410156
CARB_MAX = 844.5686035
PROTEIN_MAX = 147.491821
MACRO_MODEL_PATH = "inceptionv3_saved_model.h5"
MACRO_SIZE = (224, 224)
YOLO_MODEL_PATH = "yolov5s.pt"
YOLO_CLASSES_PATH = "classes.txt"
# --- Logging ---
def log(msg):
st.write(f"[LOG] {msg}")
# --- Food Name Mapping ---
FOOD_NAME_MAP = {
"Hamburger": "Burger", "Cheeseburger": "Burger", "Pulled pork sandwich": "Sandwich",
"Club sandwich": "Sandwich", "Grilled cheese sandwich": "Sandwich", "Banh mi": "Sandwich",
"Chicken wings": "Fried Chicken", "Tandoori chicken": "Fried Chicken", "Butter chicken": "Fried Chicken",
"French fries": "Fries", "Onion rings": "Fries", "Poutine": "Fries",
"Spaghetti bolognese": "Pasta", "Spaghetti carbonara": "Pasta", "Ravioli": "Pasta",
"Gnocchi": "Pasta", "Lasagna": "Pasta", "Mushroom risotto": "Pasta", "Risotto": "Pasta",
"Pad thai": "Noodles", "Ramen": "Noodles", "Pho": "Noodles", "Chow mein": "Noodles",
"Soba noodle": "Noodles", "Udon noodle": "Noodles",
"Hot dog": "Hot Dog", "Sausage": "Hot Dog",
"Chicken curry": "Curry", "Beef in oyster sauce": "Curry", "Green curry": "Curry", "Yellow curry": "Curry",
"Sashimi": "Sushi", "Gyoza": "Dumplings", "Spring rolls": "Dumplings", "Xiao long bao": "Dumplings",
"Dumplings": "Dumplings",
"Macaroni and cheese": "Mac and Cheese", "Cheese plate": "Mac and Cheese",
"French toast": "Toast", "Pancakes": "Pancakes", "Waffles": "Waffles", "Breakfast burrito": "Burrito",
"Apple pie": "Pie", "Red velvet cake": "Cake", "Carrot cake": "Cake", "Cheesecake": "Cake",
"Strawberry shortcake": "Cake", "Chocolate cake": "Cake", "Cup cakes": "Cake", "Donuts": "Cake",
"Chocolate mousse": "Dessert", "Macarons": "Dessert", "Ice cream": "Dessert", "Frozen yogurt": "Dessert",
"Tacos": "Taco", "Chicken quesadilla": "Quesadilla", "Nachos": "Nachos", "Enchiladas": "Burrito",
"Huevos rancheros": "Eggs", "Omelette": "Eggs", "Eggs benedict": "Eggs",
"Clam chowder": "Soup", "French onion soup": "Soup", "Lobster bisque": "Soup", "Hot and sour soup": "Soup",
"Coconut milk soup": "Soup", "Miso soup": "Soup", "Soup": "Soup",
"Pizza": "Pizza", "Steak": "Steak", "Filet mignon": "Steak", "Prime rib": "Steak",
"Crab cakes": "Seafood", "Lobster roll sandwich": "Seafood", "Fried calamari": "Seafood", "Shrimp and grits": "Seafood",
"Pozole": "Stew", "Paella": "Stew", "Coq au vin": "Stew", "Ratatouille": "Stew",
"Bibimbap": "Rice Dish", "Biryani": "Rice Dish", "Fried rice": "Rice Dish", "Com tam": "Rice Dish",
"Garlic bread": "Bread", "Naan": "Bread", "Bread pudding": "Dessert",
}
# --- Macro Model ---
def load_macro_model():
try:
model = tf.keras.models.load_model(MACRO_MODEL_PATH, compile=False)
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=1e-5), loss='mse')
return model
except Exception as e:
log(f"Failed to load macro model: {e}")
return None
def preprocess_macro_image(img):
img = img.resize(MACRO_SIZE).convert("RGB")
arr = np.array(img, dtype=np.float32) / 255.0
if arr.ndim != 3 or arr.shape[-1] != 3:
raise ValueError(f"Expected RGB image. Got shape {arr.shape}")
return np.expand_dims(arr, axis=0)
def predict_macros(img, model):
try:
tensor = preprocess_macro_image(img)
log(f"Tensor shape: {tensor.shape}")
output = np.array(model.predict(tensor)).squeeze()
log(f"Model raw output: {output}")
return {
"Calories": round(output[0] * CALORIES_MAX, 2),
"Mass": round(output[1] * MASS_MAX, 2),
"Fat": round(output[2] * FAT_MAX, 2),
"Carbs": round(output[3] * CARB_MAX, 2),
"Protein": round(output[4] * PROTEIN_MAX, 2),
}
except Exception as e:
log(f"Prediction error: {e}\n{traceback.format_exc()}")
return {"Error": str(e)}
# --- Food Type Detection ---
def load_yolo_model():
try:
model = torch.hub.load('ultralytics/yolov5', 'custom', path=YOLO_MODEL_PATH, force_reload=False)
return model
except Exception as e:
log(f"Failed to load YOLOv5 model: {e}")
return None
def load_class_names():
try:
with open(YOLO_CLASSES_PATH, "r") as f:
return [line.strip() for line in f.readlines()]
except Exception as e:
log(f"Failed to load class names: {e}")
return []
def detect_food_types(image, model, class_names):
try:
results = model(image)
df = results.pandas().xyxy[0]
detected = df['name'].value_counts().index.tolist()
mapped = [FOOD_NAME_MAP.get(name, name) for name in detected]
top2 = mapped[:2] + ["Unknown"] * (2 - len(mapped))
return top2
except Exception as e:
log(f"Detection error: {e}")
return ["Error", "Error"]
# --- Streamlit Interface ---
st.set_page_config(page_title="AminoPro Estimator", layout="centered")
st.title("AminoPro: Macronutrient Estimator")
st.write("Upload a food image to estimate calories, fat, carbs, protein, and detect food types.")
uploaded_file = st.file_uploader("Choose an image", type=["jpg", "jpeg", "png"], label_visibility="visible")
if uploaded_file is not None:
try:
image = Image.open(uploaded_file).convert("RGB")
st.image(image, caption="Uploaded Image", use_container_width=True)
log("Image uploaded and displayed.")
macro_model = load_macro_model()
yolo_model = load_yolo_model()
class_names = load_class_names()
macro_results = predict_macros(image, macro_model) if macro_model else {"Error": "Macro model not loaded"}
food_labels = detect_food_types(image, yolo_model, class_names) if yolo_model else ["Unknown", "Unknown"]
st.subheader("Detected Food Types")
st.write(f"Primary: **{food_labels[0]}**")
st.write(f"Secondary: **{food_labels[1]}**")
st.subheader("Macronutrient Estimates")
st.json(macro_results)
except Exception as e:
st.error(f"Error processing image: {e}")
log(f"Exception: {e}\n{traceback.format_exc()}")