100% found this document useful (1 vote)
124 views63 pages

Smart Recipie Generator Report

Uploaded by

Saran K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
124 views63 pages

Smart Recipie Generator Report

Uploaded by

Saran K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 63

Smart Recipe Generator

CHAPTER 1

INTRODUCTION

1.1 PROBLEM DEFINITION

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

Department of CSE, NHCE 1


Smart Recipe Generator

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.

By achieving these objectives, the project aims to provide users with


personalized recipe recommendations based on their input ingredients and
dietary preferences

1.3 METHODOLOGY TO BE FOLLOWED

Department of CSE, NHCE 2


Smart Recipe Generator

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

 Blueprint for Architecture: Plan the system’s architecture, including AI


integration and data flow.
 Module Design: Create modules for recipe generation, nutritional analysis, and
real-time adaptability.

3. Database Development

 Database Creation: Develop and populate the database with ingredients, recipes,
nutritional data, and associated health benefits.

4. GUI Development

 Interface Design: Build an intuitive and visually appealing interface using


Streamlit.
 User-Friendly Navigation: Ensure easy and seamless navigation for meal planning
and customization.

5. Integration and Testing

 System Integration: Integrate AI models with the database and user interface.
 Testing: Conduct functionality and usability tests to ensure system reliability and
performance.

6. Deployment and Documentation

 System Deployment: Deploy the system on a suitable platform for user access.
 Documentation: Provide comprehensive documentation for users and
maintainers.

7. Feedback and Iteration

 User Feedback: Collect and analyze feedback to identify areas for improvement.
 System Refinement: Implement updates and enhance features based on real-
world usage.

Department of CSE, NHCE 3


Smart Recipe Generator

1.4 EXPECTED OUTCOMES

This section outlines the anticipated results of the project, focusing on its impact,
functionality, and contributions to data management. The expected outcomes are:

1.AI-Powered Recipe Generation

 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.

2. Nutritional Analysis and Health Benefits

 Machine Learning Algorithms: Algorithms calculate the nutritional value of each


recipe, ensuring meals meet dietary needs and are healthy.
 Health Insights: AI models will provide health benefit insights based on
ingredient databases, enabling users to understand the health impact of their
meals.

3. Dynamic Recipe Personalization

 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.

4. Scalable and Real-Time Data Processing

 Streamlit Framework: Streamlit will provide an interactive web interface,


allowing users to input data and receive real-time recipe suggestions.
 Backend System: A Python-based backend will handle real-time data processing,
recipe generation, and user inputs efficiently.

5. Database Management and Integration

 Ingredient and Recipe Database: Ingredients, recipes, and user preferences will
be stored in a comprehensive database, facilitating efficient data retrieval and
management.

Department of CSE, NHCE 4


Smart Recipe Generator

 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.

7. Secure and Scalable Architecture

 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.

8. Future Enhancements (Real-Time Integration)

 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.

1.5 HARDWARE AND SOFTWARE REQUIREMENTS

Hardware Requirements:

Processor - I3/Intel Processor


RAM - 4GB (min)
Hard Disk - 160GB
Key Board - Standard Windows Keyboard
Mouse - Two or Three Button Mouse
Monitor - SVGA

Department of CSE, NHCE 5


Smart Recipe Generator

Software Requirements:

Operating System : Windows 7/8/10


Application Server : Python
Front End : HTML, CSS, Bootstrap
Database : SQLYog
Server : Xampp

Department of CSE, NHCE 6


Smart Recipe Generator

CHAPTER 2

FUNDAMENTALS OF PYTHON

2.1 INTRODUCTION TO PYTHON


Python is a high-level, interpreted programming language with great simplicity
and flexibility. Additionally, it has an equally rich ecosystem of libraries and
frameworks, given the type of applications it supports. Therefore, anything ranging
from artificial intelligence to data science applications can be built using Python. In the
"Smart Recipe Generator" project, all these abilities made the backend
processes like data processing and AI model integration and frontend
functionalities, like user interaction.

Key features of Python include:


Easy-to-read syntax, which simplifies coding and maintenance.

Extensive library support for tasks ranging from data manipulation (Pandas, NumPy) to
web development (Streamlit).

Compatibility with AI frameworks such as TensorFlow and PyTorch, enabling efficient


integration with the Google Gemini Pro model.

2.2 ADVANTAGES OF PYTHON


The several advantages of Python made Smart Recipe Generator much easier to develo
p and more effective. Let's break each of them down:

1. Fast Development

Department of CSE, NHCE 7


Smart Recipe Generator

The concise syntax and readability of Python made it easy to


create faster cycles for the team, which could prototype and implement features more
efficiently. Its dynamic typing and interpreted nature made debugging and
testing easier, thus allowing rapid iteration and refinement of the system.
Additionally, its extensive standard library and rich ecosystem of third-party packages
minimized the need for building functionality from scratch, reducing both
development time and effort.

2. Integration with Streamlit


The Streamlit library has been employed as a Python framework for creating the user
interface of Smart Recipe Generator. It, therefore, enables the following benefits:

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:

Easy Model Deployment: Importing the pre-trained AI

Department of CSE, NHCE 8


Smart Recipe Generator

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.

2.3 DATA TYPES


Data types in Python define a value's or variable's type. Because Python is dynamically
typed, you can give values to variables without explicitly declaring their type. The

Department of CSE, NHCE 9


Smart Recipe Generator

following are Python's most widely used data types:


1. The strings

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".

Recipes: Comprehensive written recipes have been maintained, including preparation


methods and customization tips.

Resources: Input collected from users, such as specific food preferences or standard
recipe names.

Interest:

Strings are flexible and support a variety of operations such as concatenation,


formatting, and manipulation, making them ideal for managing user-friendly output.

2. Integers and floats

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.

Resources: Represents measurements such as " 2 cups of flour" or "150 grams of


chicken".

Nutritional Information: Standards for macronutrients (protein, carbohydrates, fat) or


other metrics, such as percentage of recommended daily intake, were maintained.

Meal planning: Daily or weekly nutrition goals and tracking percentages are monitored.

Interest:

Department of CSE, NHCE 10


Smart Recipe Generator

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.

Dietary Restrictions: User-specified restrictions were monitored, such as "gluten-free",


"low-carb", or "vegan".

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

Purpose: Dictionaries provided key identification representations of values, enabling the


storage and retrieval of complex and structured information.

Request:

Recipe storage: Each recipe was represented in a dictionary, including:

Key: Represented by the name of a recipe (e.g., "spaghetti bolognese").

Objectives: Embedded dictionary with detailed information:

Resources: A list or other quantitative dictionary.

Step: Write instructions.

Department of CSE, NHCE 11


Smart Recipe Generator

Nutrition: Glossary with terms such as calories, protein, and fat content.

User Information: User-specific information, such as preferences, saved recipes, and


dietary goals, is stored.

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

2.4 PYTHON NUMBERS


1. integers

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.

Meal pattern: represented the number of meals or snacks in a diet plan.

Interest:

Storage efficiency and straightforward arithmetic operations have made integers ideal
for managing simple integer units.

2. float

Function: Float handles fractional measurements that require continuous values or


decimal precision.

Request:

Calorie Count: Represented detailed nutrition information such as "245.6 calories per
serving".

Department of CSE, NHCE 12


Smart Recipe Generator

Nutrient Percentage: Managed figures like "45.3% of daily protein intake".

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

Purpose: Python support for statistical processing provided strong integration of


numbers and statistics.

Request:

Scaling of components: The number of components multiplied or divided based on the


number desired by the user. For example, doubling a recipe might require you to
multiply each ingredient by 2 .

Nutrient adjustments: Adjusted calorie intake, nutrient intake, or percentage was


calculated when ingredients or portion sizes were changed.

Reported shapes: Dynamically adjusted shapes of components, such as variable oil


shapes

2.5 PYTHON STRINGS


Strings are one of the most common data types in Python, they are important for the
text data used in the "Smart Recipe Generator" project. They had learned:

Keep and manage ingredient lists and recipes.

Format messages for user interaction in the Streamlit interface.

Send recipes and instructions to AI modules.

Department of CSE, NHCE 13


Smart Recipe Generator

For example:

ingredient = "chicken"

description = "Grilled chicken with a side of steamed broccoli."

print(f"Selected ingredient: {ingredient}")

2.6 PYTHON LISTS


Lists played a key role in efficiently planning and managing data in the Smart Recipe
Generator project. They allowed the storage and replication of relevant features,
allowing for easy data control and manipulation. Here’s a deeper dive into their
applications:

1. Collecting inputs provided by users

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:

Working with Python

Copy the code

user_ingredients = ["chicken", "tomato", "garlic", "onion"].

If "chicken" is in user_ingredients:

print("You've got recipes and chicken!")

2. Supervises multiple cooking steps or recipes

Department of CSE, NHCE 14


Smart Recipe Generator

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.

Repeatable execution: The program could execute loop steps to be displayed


individually or as a whole list.

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:

Working with Python

Copy the code

cooking_items = [ 1 ].

"Preheat the oven to 375°F.",

"Mix the dry ingredients in a bowl.",

"Add wet ingredients and combine well.",

"Put it down.

2.7 FUNCTIONS IN PYTHON

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:

Department of CSE, NHCE 15


Smart Recipe Generator

ingredients: Star with ingredients list.

dietary_preferences: A string containing a list of dietary preferences.

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.

It gracefully handles exceptions by ensuring that an error message is displayed in the UI


if something goes wrong.

2. Well-done expository work

The Streamlit framework is used to create an interactive web-based UI for the


application.

st.sidebar.text_field: .

It allows users to add their favorite ingredients and foods.

st.sidebar.burn:1.

It provides interactive buttons that trigger recipe generation.

st.spinner: 1 .

Displays loading spinner when expressions are executed.

3. File generation functions

This service handles processes for creating downloadable recipe files in PDF and Word
format.

PDF generation:

Department of CSE, NHCE 16


Smart Recipe Generator

Uses the reportlab library to create a PDF file.

SimpleDocumentTemplate: Template:

Create a PDF document with the specified page size.

Article:

Add custom text to PDF.

pdf_file no . build ():

Finish and it saves the PDF.

Word File Generation:

Word uses the python-docx library to create a document.

document.add_subject: .

Adds a title to the Word document.

Documentation.ad_section: 1.1.

He includes paragraphs.

Documents.save: 1.1.

Save the document to a file.

4. Dealing with environmental variables

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.

Department of CSE, NHCE 17


Smart Recipe Generator

5. Styling and customization work

Custom CSS for background and dynamic theme:

CSS styling is advertising.

Department of CSE, NHCE 18


Smart Recipe Generator

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.

3.2 CHARACTERISTICS OF A DBMS

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:

Department of CSE, NHCE 19


Smart Recipe Generator

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.

Effective data collection and retrieval:

Using database management principles, the system can quickly capture vocabulary and
user preferences, ensuring real-time delivery of results.

Support for multiple users:

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.

Reducing data redundancy:

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.

Connecting to Python Backend:

The DBMS is seamlessly integrated with the Python backend, enabling real-time data
processors to create recipes and synchronization with an AI model

Department of CSE, NHCE 20


Smart Recipe Generator

The changes in question:

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.

backup and recovery support

3.3 DATA MODEL

1. A conceptual framework that outlines the arrangement, archiving, and manipulation


of data in a database is called a data model. It offers a guide for creating and putting into
practice a database structure that satisfies the particular requirements of an application.
A Relational Data Model, which arranges data into structured tables with rows and
columns to facilitate effective data management, is demonstrated by the provided code
and database schema.
Entities and Attributes

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

Department of CSE, NHCE 21


Smart Recipe Generator

o RecipeID (Primary Key): Unique identifier for each recipe.


o Name: Name of the recipe (e.g., Grilled Chicken Salad).
o CookingTime: Total cooking time in minutes.
o DietCompatibility: Dietary preferences compatible with this recipe.
o Instructions: Step-by-step cooking instructions.
o HealthBenefits: List of health benefits provided by the 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.

3.4 Three schema architecture


1. External Schema (User Interaction Layer)

The External Schema defines how users interact with the system, offering customized
views and connections for various user roles.

Users:

 Input ingredients and dietary preferences.


 Generate recipes based on their preferences.
 View and download recipes in PDF or Word format.
 Register and log in to save personalized information.

Features in External Schema:

1. Streamlit UI:
o User-friendly interface for ingredient input, recipe generation, and recipe
display.
o Download functionality for generated recipes in desired formats.

Department of CSE, NHCE 22


Smart Recipe Generator

2. Forms and Inputs:


o Fields for entering ingredients and dietary preferences.
o Registration and login forms for personalized services.
3. Recipe Display:
o Lists of recipes with detailed cooking instructions, dietary suggestions,
and health benefits.

2. Conceptual Schema (Logical Database Layer)

The Conceptual Schema defines the logical structure of the database, organizing and
interrelating data without focusing on physical storage.

Key Entities and Relationships:

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.

3. Ingredients Table (Optional for Scalability):


o ingredient_id: Unique identifier for each ingredient.
o name: Name of the ingredient.
o category: Category of the ingredient (e.g., vegetable, protein, spice).

Relationships:

 One-to-Many: A single user (user_id) can have multiple recipes (recipe_id).


 Optional Relationships: Ingredients table can be linked for detailed ingredient
tracking.

Data Validation:

 Ensure all required fields (e.g., user email, recipe name) are not null.

Department of CSE, NHCE 23


Smart Recipe Generator

 Enforce uniqueness constraints on email and primary keys.

3. Internal Schema (Physical Storage Layer)

The Internal Schema defines how the data is physically stored and accessed on the
database server.

Database Management System (DBMS):

 MySQL or SQLite for relational database management.


 Physical storage is managed by the DBMS, abstracting complexity for developers.

Storage and Indexing:

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.

Backup and Recovery:

 Scheduled backups of the database to prevent data loss.


 Use cloud solutions (e.g., AWS RDS, Google Cloud SQL) for enhanced durability.

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.

Department of CSE, NHCE 24


Smart Recipe Generator

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.

4.2 SQL COMMANDS


1. Create a Database

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.

Department of CSE, NHCE 25


Smart Recipe Generator

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.

5. Ask for data

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.

4.3 DATA DEFINITION LANGUAGE

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;

This creates a database named RecipeDatabase.

Department of CSE, NHCE 26


Smart Recipe Generator

2. Use Database
This command is used to select the created database for subsequent operations.

 Example:

sql
Copy code
USE RecipeDatabase;

This selects the RecipeDatabase for use.

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:

Department of CSE, NHCE 27


Smart Recipe Generator

sql
Copy code
ALTER TABLE Recipes ADD preparation_time INT;

This adds a preparation_time column to the Recipes table.

5. Drop Table
If required, this command removes a table from the database along with its data.

 Example:

sql
Copy code
DROP TABLE Ingredients;

This deletes the Ingredients table.

These DDL commands define and manage the database structure for storing and
retrieving data in the "Smart Recipe Generator" project.

4.4 DATA MANIPULATION LANGUAGE


1. Insert Data

The INSERT INTO command is used to feature new facts into the database tables.

Examples:

Insert components into the Ingredients desk:

INSERT INTO Ingredients (ingredient_name)

VALUES ('Chicken'), ('Spinach'), ('Olive Oil');

Insert a recipe into the Recipes desk:

square

Department of CSE, NHCE 28


Smart Recipe Generator

INSERT INTO Recipes (recipe_name, substances, instructions,


dietary_recommendations, health_benefits)

VALUES ('Grilled Chicken Salad', 'Chicken, Spinach, Olive Oil',

'Grill the hen, toss with spinach and olive oil, serve clean.',

'Low-carb, High-protein',

'Rich in protein and nutrients, properly for weight control.');

2. Update Data

The UPDATE command modifies present statistics in a desk.

Example: Update the nutritional tips of a recipe:

UPDATE Recipes

SET dietary_recommendations = 'Keto, Low-carb'

WHERE recipe_id = 1;

3. Delete Data

The DELETE command removes precise information from a table.

Example: Delete an element from the Ingredients table:

DELETE FROM Ingredients

WHERE ingredient_name = 'Spinach';

4. Select Data

The SELECT command retrieves information from the database based on particular
situations.

Examples:

Retrieve all recipes with low-carb recommendations:

Department of CSE, NHCE 29


Smart Recipe Generator

SELECT recipe_name, components

FROM Recipes

WHERE dietary_recommendations LIKE '%Low-carb%';

Retrieve all ingredients:

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.

4.4 DATA CONTROL LANGUAGE

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.

Key Roles of DCL Commands in the Project:

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';

Department of CSE, NHCE 30


Smart Recipe Generator

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.

3. Ensuring Data Security


o Prevents unauthorized users from accessing sensitive data such as user
dietary preferences or recipe details.
o Restricts critical operations (like table modification or deletion) to
administrators.

4. Facilitating Multi-User Access


In a collaborative environment, DCL commands ensure that different users have
roles suited to their responsibilities:
o Administrators: Full access to create, modify, and delete database
objects.
o Regular Users: Limited access to perform specific tasks like viewing or
adding new recipes.

By using DCL commands, the project maintains a secure and controlled database
environment, protecting user data and ensuring system integrity.

Department of CSE, NHCE 31


Smart Recipe Generator

CHAPTER 5

DESIGN

5.1 DESIGN GOALS


1.User Interaction:

o The code provides a user-friendly interface through Streamlit, enabling users to


input ingredients and dietary preferences.
o Interactive elements such as text areas, buttons, and download options enhance
usability.

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.

5. Promotes Healthy Eating:


o By providing personalized recipes, the application encourages balanced and
nutritious meal choices.

Document Purpose (Reference):

1. Personalized Meal Planning:


o The document describes a system designed to provide tailored recipes based on
user-inputted ingredients and dietary preferences.

2. Health-Centric Approach:
o It emphasizes the health benefits of personalized meal suggestions, targeting
specific health goals like weight loss or muscle gain.

Department of CSE, NHCE 32


Smart Recipe Generator

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.

5. Enhancing Daily Nutrition:


o By integrating dietary recommendations and health benefits, the system
promotes long-term healthy eating habits.

5.2 DATABASE STRUCTURE


The ScoreX project's database structure is meticulously crafted to efficiently manage and
store all pertinent information related to sports matches, squads, scores, and user data.
The design emphasizes performance, scalability, and data integrity to ensure seamless
operation and future expansion.

1. Users Table

Stores user information.

 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

Stores details about ingredients.

 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).

Department of CSE, NHCE 33


Smart Recipe Generator

o IsAllergen: Indicates if the ingredient is a known allergen (Boolean).

3. Recipes Table

Stores the recipes generated by the system.

 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

Maps recipes to their ingredients (Many-to-Many relationship).

 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

Tracks recipes saved by users.

 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.

Department of CSE, NHCE 34


Smart Recipe Generator

6. DietaryPreferences Table

Lists predefined dietary preferences for filtering recipes.

 Columns:
o DietaryPreferenceID: Unique identifier (Primary Key).
o PreferenceName: Name of the dietary preference (e.g., low-carb, sugar-
free).

7. RecipeDietaryPreference Table

Maps recipes to dietary preferences (Many-to-Many relationship).

 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

Stores feedback from users about recipes.

 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.

Summary of Table Names and Primary Keys:

1. Users (UserID)
2. Ingredients (IngredientID)
3. Recipes (RecipeID)
4. RecipeIngredients (RecipeIngredientID)
5. UserSavedRecipes (UserSavedRecipeID)
6. DietaryPreferences (DietaryPreferenceID)
7. RecipeDietaryPreference (RecipeDietaryPreferenceID)
8. Feedback (FeedbackID)

Department of CSE, NHCE 35


Smart Recipe Generator

2.Overview of the Schema

Overview of the Database Schema

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

 Purpose: To manage user accounts and their preferences.


 Tables:
o Users: Stores user details, including dietary preferences for recipe
customization.
o UserSavedRecipes: Tracks recipes saved by users for future reference.

2. Ingredients Management

 Purpose: To store and manage the ingredients available for recipes.


 Tables:
o Ingredients: Stores ingredient details such as name, category, and
allergen status.
o RecipeIngredients: A junction table mapping ingredients to recipes,
specifying quantities and units.

3. Recipe Management

 Purpose: To store generated recipes and their details.


 Tables:
o Recipes: Stores recipe details such as name, description, health benefits,
and cooking instructions.
o RecipeDietaryPreference: A junction table linking recipes to dietary
preferences for filtering and categorization.

Department of CSE, NHCE 36


Smart Recipe Generator

4. Dietary Preferences

 Purpose: To handle predefined dietary preferences for recipe filtering.


 Tables:
o DietaryPreferences: Stores common dietary preferences like "vegan,"
"low-carb," or "gluten-free."

5. Feedback System

 Purpose: To collect feedback for continuous improvement.


 Tables:
o Feedback: Stores user ratings and comments on recipes.

Schema Relationships

One-to-Many Relationships

 Users → UserSavedRecipes: A user can save multiple recipes.


 Recipes → RecipeIngredients: A recipe can have multiple ingredients.
 Recipes → Feedback: A recipe can have multiple feedback entries from different
users.

Many-to-Many Relationships

 Recipes ↔ Ingredients: Managed via the RecipeIngredients table, allowing


recipes to be linked to multiple ingredients and vice versa.
 Recipes ↔ DietaryPreferences: Managed via the RecipeDietaryPreference table,
linking recipes to multiple dietary categories.

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.

Department of CSE, NHCE 37


Smart Recipe Generator

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.

4. Health and Nutrition Insights:


o Each recipe is linked to dietary preferences and health benefits, providing
users with tailored meal options.

Schema Diagram (Conceptual View)


Markdown

├── UserID (PK)


└── DietaryPreferences
└── UserSavedRecipes
└── Recipes
├── RecipeIngredients
│ ├── Ingredients
└── RecipeDietaryPreference
└── DietaryPreferences
Feedback
└── Recipes

Advantages of This Schema

1. Scalability: Can handle a large number of users, ingredients, and recipes.


2. Flexibility: Supports customization through dietary preferences and feedback
loops.
3. Efficiency: Well-structured relationships enable quick data retrieval for
personalized recipes.
4. Modularity: Separating ingredients, recipes, and dietary preferences allows for
independent updates or expansions.

5.3 GUI STRUCTURE

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,

Department of CSE, NHCE 38


Smart Recipe Generator

generate recipes, and access other features. Below is a detailed description of the GUI
structure:

**1. Header Section

 Position: Top of the screen (Sticky Header).


 Purpose:
o Displays the app's name, "BITERIGHT", in bold text.
o Includes branding and a visually appealing design (e.g., transparent
background with a shadow effect).
 Features:
o Sticky Header: Always visible for quick navigation.

**2. Sidebar Panel

 Position: Left side of the screen.


 Purpose:
o Acts as the main control panel for user inputs and navigation.
 Features:
o Input Fields:
 Ingredients: Text area where users can enter up to 10 ingredients
(e.g., "chicken, garlic, spinach").
 Dietary Preferences: Text area to specify dietary preferences (e.g.,
"vegan, gluten-free").
o Generate Recipes Button: Triggers recipe generation when clicked.
o About Section:
 A brief description of the app and its purpose.
o Help or Support Section:
 A link or button for FAQs or user support.

**3. Main Content Area

 Position: Center and right of the screen (dominant area).


 Purpose:
o Displays generated recipes and related content.
 Features:
o Recipe Display:
 Each recipe is shown with the following details:
 Recipe Name
 Ingredients (with quantities)

Department of CSE, NHCE 39


Smart Recipe Generator

 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.").

**4. Download Options

 Position: Below the recipes or in the right panel.


 Purpose:
o Allows users to download the generated recipes.
 Features:
o Download Format Selector:
 Dropdown to select download format (e.g., PDF, Word).
o Download Button:
 Triggers the download of the generated file.

**5. Footer Section

 Position: Bottom of the screen.


 Purpose:
o Provides additional information and links.
 Features:
o Contact Info:
 Email or social media links for user support.
o Copyright Notice:
 "© 2024 BITERIGHT. All Rights Reserved."
o Terms and Policies:
 Links to privacy policy and terms of service.

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:

Department of CSE, NHCE 40


Smart Recipe Generator

o A subtle, visually appealing background image (e.g., a food or recipe-


related image).
 Typography:
o Large, bold fonts for headings (e.g., BITERIGHT) and easy-to-read fonts for
text areas.

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).

Department of CSE, NHCE 41


Smart Recipe Generator

CHAPTER 6

IMPLEMENTATION

6.1 CREATING THE DATABASE


To integrate a database with the given code for managing user inputs and storing recipe data,
we can use a database like MySQL or SQLite. Below is an implementation outline for creating
and managing a database for the "Smart Recipe Generator.

1. Table Name: users


Purpose: Stores user information.
Columns:
o user_id (Primary Key, INT, Auto-Increment): Unique identifier for each
user.
o name (VARCHAR(100)): Name of the user.
o email (VARCHAR(100), UNIQUE): Email address of the user.
o created_at (TIMESTAMP, Default: CURRENT_TIMESTAMP): Timestamp of
when the user was created.

Department of CSE, NHCE 42


Smart Recipe Generator

2. Table Name: recipes


Purpose: Stores recipe details generated for users.
Columns:
o recipe_id (Primary Key, INT, Auto-Increment): Unique identifier for each
recipe.
o user_id (Foreign Key, INT): Links the recipe to a specific user from the
users table.
o recipe_name (VARCHAR(255)): Name of the recipe.
o ingredients (TEXT): List of ingredients used in the recipe.
o instructions (TEXT): Detailed cooking instructions.
o dietary_suggestions (TEXT): Dietary preferences and suggestions for the
recipe.
o benefits (TEXT): Health benefits of the recipe.
o created_at (TIMESTAMP, Default: CURRENT_TIMESTAMP): Timestamp of
when the recipe was created.

3. Table Name: ingredients (Optional for scalability)


Purpose: Stores information about available ingredients.
Columns:
o ingredient_id (Primary Key, INT, Auto-Increment): Unique identifier for
each ingredient.
o name (VARCHAR(255)): Name of the ingredient.
o category (VARCHAR(100)): Category of the ingredient (e.g., vegetable,
protein, spice).
o created_at (TIMESTAMP, Default: CURRENT_TIMESTAMP): Timestamp of
when the ingredient was added.

Overview of the Database

The recipe_generator database is designed to support a recipe generation platform. It


stores user details, generated recipes, and their associated information. The database
follows a relational design to ensure data integrity and enable easy retrieval of user-
specific or recipe-specific data.

Key Features:

1. User Tracking: Each recipe is linked to a registered user to enable personalized


services.
2. Recipe Details: Recipes include detailed information such as ingredients,
instructions, dietary suggestions, and health benefits.

Department of CSE, NHCE 43


Smart Recipe Generator

3. Modularity: The design is modular, with separate tables for users, recipes, and
(optionally) ingredients.

Database Limitations

1. Limited to Structured Data:


o Complex data like user feedback or AI training inputs for recipes may
require additional non-relational storage (e.g., NoSQL databases).

2. Scalability with Increased Data Volume:


o As the number of users and recipes grows, performance may degrade if
the database is not properly indexed or optimized.

3. Dietary Suggestions Complexity:


o Dietary recommendations can be extensive and unstructured. Storing
them in a TEXT field limits advanced querying capabilities.

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.

3. Indexing and Query Optimization:


o Use indexing on key fields like user_id and recipe_id for faster lookups.

4. Caching:

Department of CSE, NHCE 44


Smart Recipe Generator

o Implement caching layers (e.g., Redis, Memcached) to reduce database


load by storing frequently accessed queries.

5. Database Partitioning:
o Partition tables like recipes based on user_id or creation date to improve
query performance.

6. Migration to Distributed Databases:


o Consider transitioning to distributed databases like Amazon Aurora or
Google Cloud Spanner as user and data volumes grow.

6.2 CONNECTING THE DATABASE TO THE APPLICATION

To connect the database (recipe_generator) to your application, you need to integrate


the database connection logic into your Python application using a library like mysql-
connector-python for MySQL. Below is a detailed guide for connecting the database to
the Smart Recipe Generator application.

Step 1: Install Required Libraries

Ensure you have the necessary Python library installed:

bash
Copy code
pip install mysql-connector-python

Step 2: Database Connection Function

Create a reusable function to establish a connection to the database.

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:

Department of CSE, NHCE 45


Smart Recipe Generator

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

Step 3: Integrate Database into Application

Example 1: Storing User Data

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()

Example 2: Storing Generated Recipes

Save recipes into the recipes table after they are generated:

python
Copy code

Department of CSE, NHCE 46


Smart Recipe Generator

def insert_recipe(user_id, recipe_name, ingredients, instructions, dietary_suggestions,


benefits):
"""Inserts a recipe into the recipes table."""
connection = create_connection()
if connection:
try:
cursor = connection.cursor()
cursor.execute("""
INSERT INTO recipes (user_id, recipe_name, ingredients, instructions,
dietary_suggestions, benefits)
VALUES (%s, %s, %s, %s, %s, %s)
""", (user_id, recipe_name, ingredients, instructions, dietary_suggestions,
benefits))
connection.commit()
print("Recipe inserted successfully!")
except Error as e:
print(f"Error inserting recipe: {e}")
finally:
cursor.close()
connection.close()

Step 4: Update Streamlit App

Integrate these database functions into the Streamlit app for real-time user interaction.

Example: User Registration

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.")

Example: Save Generated Recipes

After generating recipes:

Department of CSE, NHCE 47


Smart Recipe Generator

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!")

Step 5: Fetch Data from the Database

Fetch User's Recipes

Retrieve recipes for a specific user:

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()

Display Recipes in the App

Use the fetched recipes to display them in the Streamlit interface:

python
Copy code
if st.sidebar.button("View My Recipes"):

Department of CSE, NHCE 48


Smart Recipe Generator

user_id = 1 # Replace with actual logged-in user ID


user_recipes = fetch_recipes_by_user(user_id)
if user_recipes:
st.subheader("Your Recipes")
for recipe in user_recipes:
st.write(f"**Recipe Name:** {recipe['recipe_name']}")
st.write(f"**Ingredients:** {recipe['ingredients']}")
st.write(f"**Instructions:** {recipe['instructions']}")
st.write(f"**Dietary Suggestions:** {recipe['dietary_suggestions']}")
st.write(f"**Benefits:** {recipe['benefits']}")
st.markdown("---")
else:
st.warning("No recipes found.")

Step 6: Test the Connection

Run the application and test:

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).

6.3 CREATING THE MAIN WINDOW


import streamlit as st

import os

from reportlab.lib.pagesizes import letter

Department of CSE, NHCE 49


Smart Recipe Generator

from reportlab.platypus import SimpleDocTemplate, Paragraph

from reportlab.lib.styles import getSampleStyleSheet

from docx import Document

import google.generativeai as genai

from dotenv import load_dotenv

# Load environment variables

load_dotenv()

# Set up Google API key

GOOGLE_API_KEY = os.getenv("AIzaSyBkctcF-VuTbCls2ROawt-jQHRNL-wUIqo")

genai.configure(api_key=GOOGLE_API_KEY)

# Initialize Gemini model

model = genai.GenerativeModel('gemini-pro')

def generate_detailed_recipes(ingredients, dietary_preferences):

"""Generate 5 detailed recipes using the Gemini model."""

prompt = f"""

Based on the following ingredients: {ingredients}

and dietary preferences: {dietary_preferences},

suggest 5 recipes. For each recipe, include:

- Recipe Name

Department of CSE, NHCE 50


Smart Recipe Generator

- Ingredients (with quantities)

- Cooking Instructions (including detailed steps, ingredient amounts, and cooking


times)

- Diet Suggestions

- Benefits of this Recipe

"""

try:

response = model.generate_content(prompt)

return response.text.strip()

except Exception as e:

st.error(f"An error occurred: {str(e)}")

return None

# Streamlit UI setup

st.set_page_config(page_title="BITERIGHT", layout="wide")

# Add background image using CSS

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;

Department of CSE, NHCE 51


Smart Recipe Generator

background-position: center;

background-repeat: no-repeat;

height: 100vh;

margin: 0;

padding-top: 120px; /* Space for sticky header */

/* Sticky header styling */

.sticky-header {

position: -webkit-sticky; /* For Safari support */

position: sticky;

top: 0;

background-color: rgba(0, 0, 0, 0.6); /* Dark background for visibility */

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>

Department of CSE, NHCE 52


Smart Recipe Generator

""", unsafe_allow_html=True)

# Add the sticky header HTML element

st.markdown('<div class="sticky-header">BITERIGHT</div>', unsafe_allow_html=True)

# Sidebar controls

st.sidebar.header("Input Details")

st.sidebar.write("Enter the ingredients and dietary preferences below.")

# Input fields

ingredients = st.sidebar.text_area("Enter up to 10 ingredients, separated by commas",

"chicken, spinach, olive oil, garlic, lemon, onion, rice, ginger, coconut
milk, tomatoes")

dietary_preferences = st.sidebar.text_area("Enter up to 10 dietary preferences,


separated by commas",

"low-carb, high-protein, gluten-free, dairy-free, vegetarian,


vegan, keto, paleo, sugar-free, heart-healthy")

# Main area for displaying results

if st.sidebar.button("Generate Recipes"):

with st.spinner("Generating recipes and diet suggestions..."):

recipes = generate_detailed_recipes(ingredients, dietary_preferences)

Department of CSE, NHCE 53


Smart Recipe Generator

if recipes:

st.subheader("Recipe Suggestions")

st.write(recipes)

# PDF and Word download options

download_format = st.selectbox("Download Recipes as", options=["PDF"])

if download_format == "PDF":

pdf_file = SimpleDocTemplate('detailed_recipes.pdf', pagesize=letter)

elements = []

styles = getSampleStyleSheet()

elements.append(Paragraph("Recipe Suggestions", styles['Heading2']))

elements.append(Paragraph(recipes, styles['BodyText']))

pdf_file.build(elements)

st.download_button(

label="Download Recipes as PDF",

data=open('detailed_recipes.pdf', 'rb').read(),

file_name="detailed_recipes.pdf",

mime="application/pdf",

Department of CSE, NHCE 54


Smart Recipe Generator

elif download_format == "Word":

document = Document()

document.add_heading("Recipe Suggestions", level=2)

document.add_paragraph(recipes)

document.save('detailed_recipes.docx')

st.download_button(

label="Download Recipes as Word",

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.

Department of CSE, NHCE 55


Smart Recipe Generator

""")

CHAPTER 7

RESULTS

Department of CSE, NHCE 56


Smart Recipe Generator

Fig 7.1: Main Page

Fig 7.2: Enter input

Department of CSE, NHCE 57


Smart Recipe Generator

Fig 7.3: Recipie suggestion

Fig 7.4: Ingridients

Department of CSE, NHCE 58


Smart Recipe Generator

Fig 7.5 cooking instructions

Fig 7.6: nutrient values

Department of CSE, NHCE 59


Smart Recipe Generator

Fig 7.7: download recipie offline

Fig 7.8: Recipie accessed offline

CHAPTER 8
Department of CSE, NHCE 60
Smart Recipe Generator

CONCLUSION

The Smart Recipe Generator project represents a groundbreaking advancement in the


domain of personalized meal planning by harnessing the power of artificial intelligence
and offering a user-friendly interface. Leveraging the capabilities of the Google Gemini
Pro model and the Streamlit platform, this innovative system provides customized recipe
suggestions tailored to users' ingredients and dietary preferences. Each recipe not only
includes detailed cooking instructions but also emphasizes dietary recommendations
and associated health benefits, making it an indispensable tool for promoting healthier
lifestyles.

This project effectively addresses the shortcomings of traditional recipe


recommendation systems by integrating dynamic AI capabilities. It empowers users to
achieve specific health objectives, such as weight loss, muscle gain, or managing health
conditions, while offering a seamless and engaging experience through its intuitive
design. The system simplifies the process of healthy meal planning, making it more
accessible and enjoyable for a wide range of users.

The integration of a relational database ensures scalability and reliability, enabling


efficient storage and retrieval of user information and recipes. While the project has
successfully met its primary objectives, it also establishes a robust framework for future
enhancements. These potential improvements include real-time integration with
wearable devices, multilingual support, region-specific cuisine recommendations, and
AI-driven food waste management solutions.

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

Department of CSE, NHCE 61


Smart Recipe Generator

1. Django Documentation. (2024). Retrieved


from https://docs.djangoproject.com/

2. React Documentation. (2024). Retrieved from https://reactjs.org/docs/getting-


started.html

3. PostgreSQL Documentation. (2024). Retrieved


from https://www.postgresql.org/docs/

4. WebSocket Protocol RFC 6455. (2024). Retrieved


from https://tools.ietf.org/html/rfc6455

5. Python Software Foundation. (2024). Python Documentation. Retrieved


from https://docs.python.org/3/

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

Department of CSE, NHCE 62


Smart Recipe Generator

Department of CSE, NHCE 63

You might also like