Smart Recipie Generator Report
Smart Recipie Generator Report
CHAPTER 1
INTRODUCTION
The "Smart Recipe Generator" project aims to address the significant limitations of
current recipe recommendation systems, which are often generic and fail to meet users'
specific needs. Traditional systems, relying on static algorithms or basic ingredient-
matching techniques, lack the sophistication to accommodate modern dietary
preferences, health conditions, and fitness goals such as weight loss, muscle gain, or
managing chronic illnesses. Additionally, these platforms are inflexible in adapting to
diverse cultural cuisines, dietary restrictions, and evolving health trends, often providing
minimal or no information about the nutritional value or health benefits of
recommended meals. This leaves users ill-equipped to make informed dietary choices,
rendering such systems unsuitable for those with wellness objectives or aspirations for
healthier lifestyles. Another critical gap is the inability to dynamically adapt to changing
user preferences or real-time inputs, such as considering available ingredients or
providing unique recipe combinations. Furthermore, these systems often lack engaging
interfaces, making meal planning tedious and uninspiring. The "Smart Recipe Generator"
addresses these challenges by leveraging advanced AI capabilities, specifically the
Google Gemini Pro model, paired with an intuitive user interface built on the Streamlit
platform. It offers personalized recipes based on user-provided ingredients, dietary
preferences, and health goals, along with detailed cooking instructions and actionable
insights into the health benefits of each meal. By bridging these gaps, the project seeks
to revolutionize meal planning, promote healthier eating habits, and assist users in
achieving their wellness goals with minimal effort and maximum efficiency.
1.2 OBJECTIVES
The objective of the "Smart Recipe Generator" project is to provide users with
personalized recipe recommendations based on their input ingredients and
dietary preferences. Key objectives include:
1. Personalized Recipes
o Develop a system that delivers customized recipes based on
individualized information, including accessible ingredients, preferences,
and health goals.
2. Nutrition Emphasis
o Provide extensive nutrition details and real-life applications of the health
benefits for each recommended recipe to enable informed nutritional
choices.
3. Cultural and Dietary Sensitivity
o Ensure that the service accommodates diverse cultural foods and dietary
restrictions, catering to the requirements of a global user base.
4. Flexible Responsiveness
o Integrate real-time user inputs, such as ingredients available in the house
or changing preferences, for dynamic recipe adaptation.
5. User Experience
o Create an intuitive and visually appealing interface to make meal planning
enjoyable and inspire users to cook.
6. AI-Driven Efficiency
o Utilize advanced AI models, such as Google Gemini Pro, to enhance the
accuracy, relevance, and creativity of recipe recommendations.
7. Promotion of Healthy Lifestyles
o Support users in achieving their wellness goals, such as weight
management, muscle gain, or managing chronic conditions, with minimal
effort and maximum efficiency.
8. Seamless Integration with Modern Trends
o Keep up with emerging dietary trends and health practices to ensure the
system remains relevant and beneficial to users.
9. Simplify Meal Planning
o Minimize the complexity of meal preparation by providing clear cooking
instructions and actionable guidance for users.
1. Requirement Analysis
Understand User Needs: Identify dietary preferences, health goals, and cultural
sensitivities.
Define System Functionalities: Specify system requirements and AI model
capabilities, such as Google Gemini Pro.
2. System Design
3. Database Development
Database Creation: Develop and populate the database with ingredients, recipes,
nutritional data, and associated health benefits.
4. GUI Development
System Integration: Integrate AI models with the database and user interface.
Testing: Conduct functionality and usability tests to ensure system reliability and
performance.
System Deployment: Deploy the system on a suitable platform for user access.
Documentation: Provide comprehensive documentation for users and
maintainers.
User Feedback: Collect and analyze feedback to identify areas for improvement.
System Refinement: Implement updates and enhance features based on real-
world usage.
This section outlines the anticipated results of the project, focusing on its impact,
functionality, and contributions to data management. The expected outcomes are:
Google Gemini Pro Integration: The system utilizes Google Gemini Pro AI to
process user inputs and generate personalized recipes based on available
ingredients and health goals.
Convolutional Neural Networks (CNNs): Future enhancements may involve
integrating CNNs for image-based ingredient recognition, allowing for more
interactive and dynamic recipe generation.
Feedback Loop: The system will adapt to user preferences through continuous
feedback, refining recipe suggestions to meet individual needs and health goals.
Reinforcement Learning: This technique will further optimize recipe
recommendations by learning from user interactions and refining its suggestions
over time.
Ingredient and Recipe Database: Ingredients, recipes, and user preferences will
be stored in a comprehensive database, facilitating efficient data retrieval and
management.
API Integration: External APIs will provide additional nutritional and ingredient
information, enhancing the system’s accuracy and expanding its database.
6. Multi-Goal Optimization
AI-Based Optimization: Recipes will be optimized for multiple dietary and health
goals, considering factors like nutrition, taste, and specific user requirements.
The AI will utilize advanced algorithms to balance these goals effectively.
Cloud Hosting: The system will be hosted on the cloud, ensuring scalability and
reliability as the user base grows.
User Authentication: Secure authentication protocols will protect user data while
personalizing the experience based on individual preferences.
Data Visualization: Interactive features such as step-by-step recipes and
nutritional breakdowns will enhance the user experience.
Nutritional Visualizations: Graphical representations, such as pie charts, will help
users easily comprehend the nutritional content of their meals.
Wearable Integration: Future versions of the system may integrate with fitness
trackers to adjust meal recommendations based on real-time health metrics.
Grocery Delivery Integration: The system could later allow users to order
ingredients directly from the suggested recipes, streamlining the process of meal
preparation.
Hardware Requirements:
Software Requirements:
CHAPTER 2
FUNDAMENTALS OF PYTHON
Extensive library support for tasks ranging from data manipulation (Pandas, NumPy) to
web development (Streamlit).
1. Fast Development
Ease of Use: The Streamlit declarative API allows developers to build the
interface without much boilerplate code.
Real-time Interaction: Features such as sliders, dropdowns, and text inputs allow users
to input their requirements of diet constraints, ingredient constraints, and
customization interactively in real time.
Effortless Deployment: Streamlit enables the application to be deployed on the
web with minimal difficulty, thereby guaranteeing user accessibility without the need
for intricate setup procedures. This efficient methodology permitted the team
to concentrate on essential functionality without being hindered by
the challenges associated with conventional UI development.
3. Support for AI Models
With TensorFlow, PyTorch, and the integration libraries Hugging Face, among others,
in its solid AI framework, Python assured seamless integration with the best of
advanced AI models. In this project, the Google Gemini Pro model was utilized for
personalized recipe generation. With these frameworks compatible with Python, this
offered:
models effortlessly and then fine-tuning and including them in the application pipeline.
Boosted Scalability: Python's flexibility enabled the tailoring and fine-tuning of AI-
based solutions to achieve the specific project requirements.
Extensive Community Support: Python's widespread usage in AI and machine learning
ensured comprehensive documentation, tutorials, and community
resources, which minimized the learning curve and troubleshooting time.
4. Data Management
Successful management of user inputs, ingredient lists, and dietary preferences
was vital to the system's functionality. Python's strong libraries for data
manipulation, especially Pandas, provided
Streamlined Data Processing: It deals with a large number of data sets, like recipe
databases, nutritional information regarding ingredients, and input records from the
users.
Advanced
Filtering: It is capable of filtering and classifying recipes in terms of allergy, availability
of certain ingredients, or caloric needs.
Interoperability: The ability to work with other libraries, such as NumPy and
Matplotlib, enables further development of data processing and visualization
capabilities. With this, the data was well arranged and processed to ensure the
generator produced accurate and relevant recipes.
Conclusion
The flexibility of Python and the availability of specific libraries made it the best choice
for building the Smart Recipe Generator, which laid a solid foundation for rapid
development, interactivity, artificial intelligence, and good data handling.
Purpose: String was needed for managing text data, ensuring representation and user-
friendly communication.
Request:
Ingredient Names: Hides and displays the names of ingredients such as "tomato",
"chicken breast", or "olive oil".
Resources: Input collected from users, such as specific food preferences or standard
recipe names.
Interest:
Purpose: Statistical data sets addressed all quantitative aspects of the project, and
ensured accurate accounting and representation.
Request:
Calorie counts: All calorie counts in a recipe or meal plan are stored in integers or floats.
Meal planning: Daily or weekly nutrition goals and tracking percentages are monitored.
Interest:
Floats enabled accuracy in fractional measurements (e.g. 0.5 cup or 3.25 ounces), while
integers ensured clarity for all values, increasing data accuracy
3. The list
Purpose: The data set provided a structured framework for grouping and replicating
related items on related items.
Request:
Ingredients: All the ingredients for a particular recipe are stored, making it easy to
repeat and change.
Recipe Phasing: A set of step-by-step instructions that allows for sequential execution
and presentation.
Meal Plan: Many meals were gathered into daily or weekly meal plans.
Interest:
The scripts are very versatile, support indexing, slicing, and repetition, and made it
easier to manage and manage data collections.
4. Dictionaries
Request:
Nutrition: Glossary with terms such as calories, protein, and fat content.
Meal Plan: The days of the week are mapped on a meal plan or follow the breakdown of
nutrients at meals.
Interest:
The basic value structure of the dictionaries provided a fast, natural hierarchy, making it
perfect for the storage and retrieval of detailed expressions
Function: Used integers for whole number data without requiring precision beyond
decimal points.
Request:
Resources: Used to represent quantities such as "2 eggs", "1 cup sugar", or "5 carrots".
Utilities: A discrete inventory that indicates the amount of food served in the kitchen.
Interest:
Storage efficiency and straightforward arithmetic operations have made integers ideal
for managing simple integer units.
2. float
Request:
Calorie Count: Represented detailed nutrition information such as "245.6 calories per
serving".
Measuring fractions: Quantities such as "0.5 cup of olive oil" or "3.75 pounds of butter"
were represented.
Scaling Recipes: Floats were needed to scale ingredient amounts when users changed
serving sizes (e.g., doubled or halved).
Interest:
The float accurately represented the data, allowing for accurate calculation of nutrients
and ingredients.
3. Arthematic operations
Request:
For example:
ingredient = "chicken"
Purpose: Used lists to store and manage user inputs to the system.
Request:
Component Input When users entered the ingredients on hand (e.g. "chicken,"
"tomato", "garlic"), these were stored as lists for easier processing
Recipe filtering: The system could re-sort user-supplied ingredients to match recipes
using those ingredients.
Dynamic updates: Users could add, remove, or change items, and the list system
allowed for real-time updates.
Sample code:
If "chicken" is in user_ingredients:
Purpose: Used lists to organize the sequence of steps needed to make food, ensuring
clarity and sequence.
Request:
Step-by-step instructions: Each cooking step was stored as a separate item in the list,
making it easy for users to navigate and display.
Step rearrangement: If the optimized recipe required changing the sequence of steps
(e.g. cooking vegetables before eating meat), the list allowed for direct modification
Sample code:
cooking_items = [ 1 ].
"Put it down.
1. generate_detailed_recipes function
purpose:
This service uses the Google Gemini AI model to create detailed recipes based on the
ingredients and food preferences of the user.
Scale:
How to use:
The program creates the prompt with the input parameters and calls the
model.generate_content method to load the AI-generated content.
st.sidebar.text_field: .
st.sidebar.burn:1.
st.spinner: 1 .
This service handles processes for creating downloadable recipe files in PDF and Word
format.
PDF generation:
SimpleDocumentTemplate: Template:
Article:
document.add_subject: .
Documentation.ad_section: 1.1.
He includes paragraphs.
Documents.save: 1.1.
dotenv.load_dotenv: load_dotenv.
Carefully load the Google API key from the .env file to prevent sensitive information
from being revealed in the code.
CHAPTER 3
FUNDAMENTALS OF DBMS
3.1 INTRODUCTION
Software called a database management system (DBMS) makes it easier for users to
store, retrieve, and modify data in an orderly and structured way, which promotes
effective data management. It serves as a go-between for the database and its users or
application programs, guaranteeing the consistency, security, and accessibility of the
data. DBMS is a dependable tool for managing massive volumes of data because it offers
a number of capabilities, including data abstraction, integrity, concurrent access, and
backup and recovery techniques. The Relational DBMS (RDBMS), one of the most
popular varieties of DBMS, stores data in tables and enables manipulation through the
use of SQL (Structured Query Language). In this project, a popular RDBMS called MySQL
is used to administer a database called voice assistance. The table instructions in this
database is intended to hold voice commands that the application recognizes, together
with their timestamps and unique identities. The system effectively logs and processes
commands by integrating MySQL with the Python program, allowing for real-time voice
interaction and offering a structured method of analyzing user inputs.
Data Protection:
The business uses secure systems to store and process user-provided information such
as ingredient and food preferences. Effective handling of delicate food preferences
ensures confidentiality and avoids intrusion.
Data integrity:
The DBMS ensures that all input data, such as components, preferences, and generated
expressions are stored and retrieved accurately. This prevents data duplication or
corruption during operation.
Using database management principles, the system can quickly capture vocabulary and
user preferences, ensuring real-time delivery of results.
The service can handle data conflicts without requests from multiple users
simultaneously, ensuring a smooth user experience even in the presence of multiple
users.
How to change:
The system’s DBMS is designed to scale with increasing user data and recipes. This
ensures that it remains efficient as the number of users and reserved passwords
increases.
Appropriate data structures such as normalization are used to reduce redundancy in the
collected data. This is important for proper storage and management of ingredients and
recipes.
The DBMS is seamlessly integrated with the Python backend, enabling real-time data
processors to create recipes and synchronization with an AI model
The DBMS supports flexible queries to match user input, such as filtering specific
ingredients or food preferences.
Consistency of data:
The system ensures that the inputs (content and preferences) and outputs (products)
are consistent, avoiding any inconsistencies or errors.
1. User
o UserID (Primary Key): Unique identifier for each user.
o Name: Full name of the user.
o Email: Email address for communication.
o DietaryPreferences: List of dietary preferences (e.g., vegetarian, keto).
o CreatedAt: Timestamp of user registration.
2. Ingredient
o IngredientID (Primary Key): Unique identifier for each ingredient.
o Name: Name of the ingredient (e.g., chicken, spinach).
o NutritionalValue: JSON object or structured data (e.g., calories, protein,
fat content).
o Category: Category of the ingredient (e.g., vegetable, protein, dairy).
3. Recipe
4. RecipeIngredient
o RecipeIngredientID (Primary Key): Unique identifier for the relation.
o RecipeID (Foreign Key): Links to the Recipe entity.
o IngredientID (Foreign Key): Links to the Ingredient entity.
o Quantity: Amount of the ingredient used in the recipe.
o Unit: Measurement unit (e.g., grams, cups).
5. UserHistory
o HistoryID (Primary Key): Unique identifier for each user activity.
o UserID (Foreign Key): Links to the User entity.
o RecipeID (Foreign Key): Links to the Recipe entity.
o GeneratedAt: Timestamp when the recipe was generated.
o Downloaded: Boolean indicating if the recipe was downloaded.
The External Schema defines how users interact with the system, offering customized
views and connections for various user roles.
Users:
1. Streamlit UI:
o User-friendly interface for ingredient input, recipe generation, and recipe
display.
o Download functionality for generated recipes in desired formats.
The Conceptual Schema defines the logical structure of the database, organizing and
interrelating data without focusing on physical storage.
1. Users Table:
o user_id: Unique identifier for each user.
o name: User's name.
o email: User's email address.
o created_at: Timestamp of user registration.
2. Recipes Table:
o recipe_id: Unique identifier for each recipe.
o user_id: Foreign key linking the recipe to a specific user.
o recipe_name: Name of the recipe.
o ingredients: Ingredients used in the recipe.
o instructions: Step-by-step cooking instructions.
o dietary_suggestions: Specific dietary preferences addressed.
o benefits: Health benefits of the recipe.
o created_at: Timestamp of recipe creation.
Relationships:
Data Validation:
Ensure all required fields (e.g., user email, recipe name) are not null.
The Internal Schema defines how the data is physically stored and accessed on the
database server.
1. Primary Indexing:
o Indexes on user_id in the users table for fast lookups.
o Indexes on recipe_id in the recipes table for quicker recipe retrieval.
2. Secondary Indexing:
o Optional indexes on email and recipe_name for improved search
capabilities.
3. Partitioning (For Scalability):
o Partition the recipes table by user_id to optimize queries for large-scale
data.
Database Security:
1. User Authentication:
o Ensure secure login with hashed passwords (e.g., bcrypt).
2. Role-Based Access Control:
o Grant read-only access to recipes for end-users.
o Provide admin privileges for managing data.
CHAPTER 4
FUNDAMENTALS OF SQL
4.1 INTRODUCTION
With the help of the robust programming language Structured Query Language (SQL),
users may effectively generate, maintain, and manipulate data in relational databases. A
fundamental part of the majority of contemporary database systems, it offers a
standardized method for carrying out tasks including creating database structures,
adding new entries, retrieving data that has been stored, and controlling access
permissions. SQL plays a key role in processing voice commands in the speech
recognition project. While the commands table arranges data into rows and columns
with features like id (a unique identifier), command (the voice command text), and
timestamp (the time of command logging), the voice_assistant database is designed to
store recognized commands. The structure is defined using SQL statements like CREATE
TABLE, and additional commands are dynamically stored using INSERT INTO. As they are
acknowledged. Data integrity is guaranteed by this relational approach, enabling
effective storage and instantaneous retrieval. SQL is a crucial part of the program since it
allows the project to grow to accommodate more data, offer strong querying
capabilities, and preserve dependable data organization.
The CREATE DATABASE command is used to create a new database to store and
maintain data. This defines a logical container for tables, views, and other database
objects.
2. Select a Database
The USE command is used to select a specific database to work on. This ensures that all
subsequent commands are executed in the context of the selected database.
3. Create a table
The CREATE TABLE command defines the structure of the table, specifying its columns,
data types, and constraints. Tables store data in rows and columns, and form the
backbone of a relational database.
4. Insert Data
The INSERT INTO command is used to add new data (rows) to a table. Each row
corresponds to a record with a specific value for its columns.
The SELECT command retrieves data from a table. It can filter, organize and classify data
based on specified conditions, delivering desired results from the database.
1. Create Database
This command is used to create a database where all project-related tables and data are
stored.
Example:
sql
Copy code
CREATE DATABASE RecipeDatabase;
2. Use Database
This command is used to select the created database for subsequent operations.
Example:
sql
Copy code
USE RecipeDatabase;
3. Create Table
Tables are created to store data such as ingredients, dietary preferences, and recipes.
Examples:
o Ingredients Table:
sql
Copy code
CREATE TABLE Ingredients (
ingredient_id INT AUTO_INCREMENT PRIMARY KEY,
ingredient_name VARCHAR(100) NOT NULL
);
o Recipes Table:
sql
Copy code
CREATE TABLE Recipes (
recipe_id INT AUTO_INCREMENT PRIMARY KEY,
recipe_name VARCHAR(200) NOT NULL,
ingredients TEXT NOT NULL,
instructions TEXT NOT NULL,
dietary_recommendations TEXT,
health_benefits TEXT
);
4. Alter Table
Used to modify the structure of an existing table, such as adding new columns or
changing constraints.
Example:
sql
Copy code
ALTER TABLE Recipes ADD preparation_time INT;
5. Drop Table
If required, this command removes a table from the database along with its data.
Example:
sql
Copy code
DROP TABLE Ingredients;
These DDL commands define and manage the database structure for storing and
retrieving data in the "Smart Recipe Generator" project.
The INSERT INTO command is used to feature new facts into the database tables.
Examples:
square
'Grill the hen, toss with spinach and olive oil, serve clean.',
'Low-carb, High-protein',
2. Update Data
UPDATE Recipes
WHERE recipe_id = 1;
3. Delete Data
4. Select Data
The SELECT command retrieves information from the database based on particular
situations.
Examples:
FROM Recipes
SELECT ingredient_name
FROM Ingredients;
These DML commands allow for the insertion, updating, deletion, and retrieval of facts,
forming the center operations of the "Smart Recipe Generator" task.
A subset of SQL called Data Control Language (DCL) is used to control database access. It
helps to preserve the security and integrity of the data by making sure that only
authorized users or apps are able to carry out particular tasks. Even though the provided
code for the speech recognition project does not specifically employ DCL commands,
they are crucial for protecting the database against unwanted changes or illegal access.
• DCL makes sure that voice commands in the commands database may only be added
and managed by the program or authorized users.It stops unauthorized users from
purposefully or unintentionally altering sensitive data.
Data Control Language (DCL) commands are used to manage access permissions and
security for the database in the "Smart Recipe Generator" project. They ensure that only
authorized users can perform specific operations, enhancing the overall security and
integrity of the system.
1. Granting Permissions
The GRANT command is used to provide specific privileges to users or roles, such
as the ability to read data, insert new records, or modify existing ones.
o Example:
sql
Copy code
GRANT SELECT, INSERT, UPDATE ON RecipeDatabase.* TO
'app_user'@'localhost' IDENTIFIED BY 'password123';
This grants the user app_user permission to view, insert, and update data
in all tables within the RecipeDatabase.
2. Revoking Permissions
The REVOKE command removes previously granted permissions to restrict
unauthorized access or actions.
o Example:
sql
Copy code
REVOKE INSERT, UPDATE ON RecipeDatabase.* FROM
'app_user'@'localhost';
This revokes the ability of app_user to insert or update data while still
allowing them to view the data.
By using DCL commands, the project maintains a secure and controlled database
environment, protecting user data and ensuring system integrity.
CHAPTER 5
DESIGN
2. Recipe Personalization:
o The code leverages Google Gemini Pro to generate tailored recipes, ensuring
alignment with individual dietary needs and health goals.
3. Health Focus:
o Recipes include detailed cooking instructions, health benefits, and dietary
recommendations.
4. Convenient Output:
o Users can download generated recipes in PDF or Word formats for convenience.
2. Health-Centric Approach:
o It emphasizes the health benefits of personalized meal suggestions, targeting
specific health goals like weight loss or muscle gain.
3. AI-Driven Insights:
o The use of AI models like Google Gemini Pro ensures the generation of accurate
and relevant recipe recommendations.
4. Accessible Interface:
o A user-friendly interface built on Streamlit facilitates easy navigation and quick
recipe generation.
1. Users Table
Columns:
o UserID: Unique identifier for each user (Primary Key).
o Username: User's name.
o Email: User's email address (unique).
o PasswordHash: Encrypted password for login.
o DietaryPreferences: User's preferred dietary styles (e.g., vegan, gluten-
free).
o CreatedAt: Timestamp when the user account was created.
2. Ingredients Table
Columns:
o IngredientID: Unique identifier for each ingredient (Primary Key).
o Name: Name of the ingredient.
o Category: Type of ingredient (e.g., vegetable, protein, spice).
3. Recipes Table
Columns:
o RecipeID: Unique identifier for each recipe (Primary Key).
o Name: Recipe name.
o Description: Brief description of the recipe.
o HealthBenefits: Health benefits associated with the recipe.
o CookingInstructions: Step-by-step cooking instructions.
o DietarySuitability: Dietary categories the recipe is suitable for (e.g., keto,
vegan).
o CreatedAt: Timestamp when the recipe was created.
4. RecipeIngredients Table
Columns:
o RecipeIngredientID: Unique identifier (Primary Key).
o RecipeID: Foreign Key linking to the Recipes table.
o IngredientID: Foreign Key linking to the Ingredients table.
o Quantity: Quantity of the ingredient required.
o Unit: Unit of measurement (e.g., grams, cups).
5. UserSavedRecipes Table
Columns:
o UserSavedRecipeID: Unique identifier (Primary Key).
o UserID: Foreign Key linking to the Users table.
o RecipeID: Foreign Key linking to the Recipes table.
o SavedAt: Timestamp when the recipe was saved.
6. DietaryPreferences Table
Columns:
o DietaryPreferenceID: Unique identifier (Primary Key).
o PreferenceName: Name of the dietary preference (e.g., low-carb, sugar-
free).
7. RecipeDietaryPreference Table
Columns:
o RecipeDietaryPreferenceID: Unique identifier (Primary Key).
o RecipeID: Foreign Key linking to the Recipes table.
o DietaryPreferenceID: Foreign Key linking to the DietaryPreferences table.
8. Feedback Table
Columns:
o FeedbackID: Unique identifier (Primary Key).
o UserID: Foreign Key linking to the Users table.
o RecipeID: Foreign Key linking to the Recipes table.
o Rating: User rating for the recipe (1 to 5).
o Comments: User comments about the recipe.
o SubmittedAt: Timestamp when the feedback was submitted.
1. Users (UserID)
2. Ingredients (IngredientID)
3. Recipes (RecipeID)
4. RecipeIngredients (RecipeIngredientID)
5. UserSavedRecipes (UserSavedRecipeID)
6. DietaryPreferences (DietaryPreferenceID)
7. RecipeDietaryPreference (RecipeDietaryPreferenceID)
8. Feedback (FeedbackID)
The schema for the "Smart Recipe Generator" is designed to handle personalized recipe
generation efficiently. It involves several interconnected tables to manage user data,
ingredients, recipes, dietary preferences, and feedback. Here's an overview:
Key Components
1. User Management
2. Ingredients Management
3. Recipe Management
4. Dietary Preferences
5. Feedback System
Schema Relationships
One-to-Many Relationships
Many-to-Many Relationships
Schema Flow
1. User Input:
o Users input ingredients and dietary preferences through the interface.
o The system validates these inputs using the Ingredients and
DietaryPreferences tables.
2. Recipe Generation:
o AI generates recipes based on the inputs.
o Recipes are stored in the Recipes table, with ingredients mapped in the
RecipeIngredients table and dietary preferences in the
RecipeDietaryPreference table.
3. User Interaction:
o Users can save recipes in the UserSavedRecipes table.
o Feedback is collected in the Feedback table for future recipe refinement.
The graphical user interface (GUI) of the "Smart Recipe Generator" is designed to be
intuitive, user-friendly, and aesthetically pleasing, ensuring users can easily input data,
generate recipes, and access other features. Below is a detailed description of the GUI
structure:
Cooking Instructions
Health Benefits
Dietary Suitability
Recipes are formatted clearly with sections for easy readability.
o Spinner:
A loading spinner appears while recipes are being generated.
o Error Messages:
If recipe generation fails, a clear error message is displayed (e.g.,
"Unable to generate recipes. Please check your inputs.").
Visual Design
Theme:
o A modern, clean, and professional look with neutral colors (e.g., white,
gray, and blue) and accents in green (to signify health and nutrition).
Background:
Navigation Flow
1. Open App:
o The user is greeted with the app's name and a brief description in the
header and sidebar.
2. Input Data:
o The user enters ingredients and dietary preferences in the sidebar and
clicks "Generate Recipes."
3. View Recipes:
o Recipes are displayed in the main area with options to save or download.
4. Download Recipes:
o The user selects the desired format and downloads the recipes.
5. Exit or Reset:
o Users can reset inputs or log out (optional).
CHAPTER 6
IMPLEMENTATION
Key Features:
3. Modularity: The design is modular, with separate tables for users, recipes, and
(optionally) ingredients.
Database Limitations
4. Concurrency Issues:
o High traffic (e.g., thousands of users accessing or generating recipes
simultaneously) may require additional performance tuning or database
replication.
5. Dependency on AI Outputs:
o AI outputs (e.g., recipe generation) are stored directly, but this approach
does not allow dynamic updates to recipes based on new dietary
preferences.
Scalability Considerations
1. Horizontal Scaling:
o Use database sharding to distribute data across multiple servers for
handling larger volumes of recipes and users.
2. Vertical Scaling:
o Increase the capacity of the database server (e.g., more RAM, faster
processors) to handle heavier loads.
4. Caching:
5. Database Partitioning:
o Partition tables like recipes based on user_id or creation date to improve
query performance.
bash
Copy code
pip install mysql-connector-python
python
Copy code
import mysql.connector
import os
from mysql.connector import Error
def create_connection():
"""Creates and returns a connection to the MySQL database."""
try:
connection = mysql.connector.connect(
host="localhost", # Change to your database host
user="your_username", # Your MySQL username
password="your_password", # Your MySQL password
database="recipe_generator" # Database name
)
if connection.is_connected():
print("Connected to the database successfully!")
return connection
except Error as e:
print(f"Error while connecting to the database: {e}")
return None
When users register through the app, store their data in the users table:
python
Copy code
def insert_user(name, email):
"""Inserts a new user into the users table."""
connection = create_connection()
if connection:
try:
cursor = connection.cursor()
cursor.execute("INSERT INTO users (name, email) VALUES (%s, %s)", (name,
email))
connection.commit()
user_id = cursor.lastrowid # Get the auto-incremented user_id
print(f"User inserted with ID: {user_id}")
return user_id
except Error as e:
print(f"Error inserting user: {e}")
finally:
cursor.close()
connection.close()
Save recipes into the recipes table after they are generated:
python
Copy code
Integrate these database functions into the Streamlit app for real-time user interaction.
In the sidebar:
python
Copy code
st.sidebar.header("User Registration")
user_name = st.sidebar.text_input("Name")
user_email = st.sidebar.text_input("Email")
if st.sidebar.button("Register"):
user_id = insert_user(user_name, user_email)
if user_id:
st.sidebar.success(f"Registered successfully with User ID: {user_id}")
else:
st.sidebar.error("Registration failed. Please try again.")
python
Copy code
if recipes: # Assuming `recipes` contains the generated recipe details
user_id = 1 # Replace with actual user ID from login/registration
for recipe in recipes.split("\n\n"): # Assuming recipes are separated by two newlines
insert_recipe(
user_id=user_id,
recipe_name="Sample Recipe Name", # Replace with actual recipe name
ingredients="Sample Ingredients", # Replace with parsed ingredients
instructions="Sample Instructions", # Replace with parsed instructions
dietary_suggestions="Sample Dietary Suggestions", # Replace with suggestions
benefits="Sample Benefits" # Replace with actual health benefits
)
st.success("Recipes saved to the database successfully!")
python
Copy code
def fetch_recipes_by_user(user_id):
"""Fetches recipes for a specific user from the recipes table."""
connection = create_connection()
if connection:
try:
cursor = connection.cursor(dictionary=True)
cursor.execute("SELECT * FROM recipes WHERE user_id = %s", (user_id,))
recipes = cursor.fetchall()
return recipes
except Error as e:
print(f"Error fetching recipes: {e}")
finally:
cursor.close()
connection.close()
python
Copy code
if st.sidebar.button("View My Recipes"):
1. Register a user.
2. Generate recipes.
3. Save recipes to the database.
4. Fetch and display saved recipes.
Future Enhancements
1. Authentication:
o Add secure login with hashed passwords.
o Use libraries like bcrypt for password hashing.
2. Pagination:
o Implement pagination for large recipe data.
3. Scalable Database Options:
o Consider migrating to cloud-based solutions (AWS RDS, Google Cloud
SQL).
import os
load_dotenv()
GOOGLE_API_KEY = os.getenv("AIzaSyBkctcF-VuTbCls2ROawt-jQHRNL-wUIqo")
genai.configure(api_key=GOOGLE_API_KEY)
model = genai.GenerativeModel('gemini-pro')
prompt = f"""
- Recipe Name
- Diet Suggestions
"""
try:
response = model.generate_content(prompt)
return response.text.strip()
except Exception as e:
return None
# Streamlit UI setup
st.set_page_config(page_title="BITERIGHT", layout="wide")
st.markdown("""
<style>
body {
background-image: url("D:/mini/recipe/assets/images/writing-pad-
3193199_640.jpg"); /* Adjust this to your image path */
background-size: cover;
background-position: center;
background-repeat: no-repeat;
height: 100vh;
margin: 0;
.sticky-header {
position: sticky;
top: 0;
color: white;
padding: 20px 0;
text-align: center;
font-size: 3em;
font-weight: bold;
z-index: 100;
width: 100%;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3); /* Optional: adds shadow for better
visibility */
</style>
""", unsafe_allow_html=True)
# Sidebar controls
st.sidebar.header("Input Details")
# Input fields
"chicken, spinach, olive oil, garlic, lemon, onion, rice, ginger, coconut
milk, tomatoes")
if st.sidebar.button("Generate Recipes"):
if recipes:
st.subheader("Recipe Suggestions")
st.write(recipes)
if download_format == "PDF":
elements = []
styles = getSampleStyleSheet()
elements.append(Paragraph(recipes, styles['BodyText']))
pdf_file.build(elements)
st.download_button(
data=open('detailed_recipes.pdf', 'rb').read(),
file_name="detailed_recipes.pdf",
mime="application/pdf",
document = Document()
document.add_paragraph(recipes)
document.save('detailed_recipes.docx')
st.download_button(
data=open('detailed_recipes.docx', 'rb').read(),
file_name="detailed_recipes.docx",
mime="application/vnd.openxmlformats-
officedocument.wordprocessingml.document",
else:
st.error("Unable to generate recipes. Please check your inputs and try again.")
st.sidebar.markdown("---")
st.sidebar.header("About")
st.sidebar.info("""
This app allows you to enter ingredients and dietary preferences to get detailed recipe
suggestions
and benefits powered by Google's Gemini AI. You can also download the
recommendations as a PDF or Word document.
""")
CHAPTER 7
RESULTS
CHAPTER 8
Department of CSE, NHCE 60
Smart Recipe Generator
CONCLUSION
In conclusion, the Smart Recipe Generator not only empowers users to make informed
dietary choices but also redefines the approach to meal preparation by fostering
healthier eating habits. This innovative solution holds the potential to revolutionize
personalized nutrition and meal planning, making it a valuable asset in achieving a
balanced and sustainable lifestyle.
REFERENCES
6. Kim, J., & Lee, H. (2023). "Personalized Nutrition: Leveraging AI to Tailor Meal
Plans Based on Dietary Preferences." Journal of Artificial Intelligence in
Nutrition, 15(3), 101-113.
7. Patel, A., & Gupta, R. (2023). "AI-based Recipe Generation Using Ingredient
Input and Health Data." International Journal of Food Technology and AI, 18(2),
45-58.
8. Zhang, T., & Yang, Q. (2023). "Smart Meal Planning for Weight Management:
AI-Powered Personalized Recipes." Nutrition Science and AI Applications, 27(1),
67-82.
9. Chavez, S., & Li, M. (2024). "Streamlining Nutrition with AI: Personalized
Recipes Based on Ingredients and Preferences." Food and AI Systems Journal,
11(1), 92-108.
10. https://developer.mozilla.org
11. https://stackoverflow.com