Creating a Calorie Advisor App Using Generative AI

 In this project, we will build a Calorie Advisor app using Generative AI. The app will allow users to upload images of their meals, and the AI will provide a detailed analysis of the food items, including the total calories, nutritional content, and whether the food is healthy. This app can be a valuable tool for anyone looking to maintain a balanced diet and improve their health.

Project Overview

  1. Introduction to the Calorie Advisor App
  2. Setting Up the Environment
  3. Creating the Requirements File
  4. Writing the Code Step-by-Step
  5. Additional Improvements and Considerations

Introduction to the Calorie Advisor App

The Calorie Advisor app will take images of meals as input and use a large image model (LIM) to analyze the food items in the image. The AI will then provide information about the total calories, the nutritional content, and whether the food is healthy. This app can help users make informed decisions about their diet and ensure they are getting the right balance of nutrients.

Setting Up the Environment

First, we need to set up a virtual environment to manage our project dependencies.

conda create -n calorie_advisor_env python=3.10
conda activate calorie_advisor_env

Next, create a .env file to store your API key:

GOOGLE_API_KEY=your_api_key_here

Creating the Requirements File

Create a requirements.txt file with the following content:

streamlit
google-generativeai
python-dotenv
Pillow

Install the dependencies:

pip install -r requirements.txt

Writing the Code Step-by-Step

Now, let’s start writing the code. Create a file named app.py and add the following code:

Import Libraries and Load Environment Variables

import streamlit as st
import google.generativeai as genai
import os
from PIL import Image
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))

Function to Load the Generative AI Model and Get Responses

def get_gemini_response(input, image, prompt):
    model = genai.GenerativeModel('gemini-pro-vision')
    response = model.generate_content([input, image[0], prompt])
    return response.text

Function to Process Uploaded Image

def input_image_setup(uploaded_file):
    if uploaded_file is not None:
        # Read the file into bytes
        bytes_data = uploaded_file.getvalue()

        image_parts = [
            {
                "mime_type": uploaded_file.type,  # Get the mime type of the uploaded file
                "data": bytes_data
            }
        ]
        return image_parts
    else:
        raise FileNotFoundError("No file uploaded")

Streamlit App Setup

# Initialize Streamlit app
st.set_page_config(page_title="Calorie Advisor App")

st.header("Calorie Advisor App")

# File uploader for meal images
uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])

# Display the uploaded image
if uploaded_file is not None:
    image = Image.open(uploaded_file)
    st.image(image, caption="Uploaded Image.", use_column_width=True)

# Input prompt for the AI model
input_prompt = """
You are an expert nutritionist. Analyze the food items in the image and calculate the total calories.
Provide details of each food item with its calorie intake in the following format:

1. Item 1 - no of calories
2. Item 2 - no of calories
---
---
"""

# Submit button
submit = st.button("Tell me the total calories")

# Handling the submit button
if submit and uploaded_file is not None:
    image_data = input_image_setup(uploaded_file)
    response = get_gemini_response(input_prompt, image_data, input_prompt)
    st.subheader("The Response is")
    st.write(response)

Running the Application

To start the application, run the following command:

streamlit run app.py

This will open a web interface where you can upload images of your meals, and the AI will provide a detailed analysis of the food items, including the total calories, nutritional content, and whether the food is healthy.

Additional Improvements and Considerations

While the basic functionality is now in place, there are several improvements and additional features you could consider:

  1. Error Handling: Add more robust error handling to manage issues like unsupported file formats or missing API keys.
  2. Advanced Analysis: Enhance the app to provide more detailed analysis and feedback on the nutritional content of the meals.
  3. UI/UX Enhancements: Improve the user interface for better user experience, perhaps by adding more descriptive labels or progress indicators.
  4. Meal History: Store the analysis results so users can track their meals over time.
  5. Nutritional Suggestions: Provide suggestions for healthier meal alternatives based on the analysis.

Conclusion

Congratulations! You've built a complete end-to-end Calorie Advisor app using Generative AI. This project showcases how powerful AI can be in analyzing food images and providing detailed nutritional information, making it a valuable tool for anyone looking to maintain a balanced diet and improve their health.

If you have any questions or suggestions, feel free to leave a comment. Happy coding!

Comments

Popular posts from this blog

Crew AI & Google Gemini: Real-World AI Solutions at Work

Step-by-Step Crew AI: Turn YouTube Videos into Blog Gems

Understanding the Basics of Generative AI and Its Applications