Phase 2
Phase 2
PROJECT REPORT
PHASE II
Submitted by
RATCHAYA R [21CS135]
SUJAY B K [21CS161]
SURENDHAR A [21CS162]
VINEETH K [21CS179]
BACHELOR OF ENGINEERING
in
COMPUTER SCIENCE AND ENGINEERING
(AUTONOMOUS)
APRIL 2025
MUTHAYAMMAL ENGINEERING COLLEGE
(AUTONOMOUS)
RASIPURAM
BONAFIDE CERTIFICATE
SIGNATURE SIGNATURE
Dr.G.KAVITHA, M.S (By Research), Ph.D., Mrs. S.NAZEEMA, M.E.,
PROFESSOR ASSISTANT PROFESSOR
HEAD OF THE DEPARTMENT SUPERVISOR
Department of Computer Science and Department of Computer Science and
Engineering, Engineering,
Muthayammal Engineering College Muthayammal Engineering College
(Autonomous), Rasipuram-637 408. (Autonomous), Rasipuram-637 408.
activities.
We here like to record our deep sense of gratitude to our beloved Principal
We extend our sincere thanks and gratitude to our Head of the Department
Science and Engineering for his efforts to complete our project successfully.
We are very much thankful to our Parents, Friends and all Faculty Members of the
iii
Vision of the Institute
To be a Centre of excellence in Engineering, Technology and Management on par with
International standards
Mission of the Institute
To prepare the students with high professional skills and ethical values
To impart knowledge through best practices
To instill spirit of innovation through training, research and development
To undertake continuous assessment and remedial measures
To achieve academic excellence through intellectual, emotional and social
stimulation
iv
Program Outcomes (POs)
PO1 - Engineering knowledge: Apply the knowledge of mathematics, science,
engineering fundamentals, and an engineering specialization to the solution of complex
engineering problems.
PO2 - Problem analysis: Identify, formulate, review research literature, and analyze
complex engineering problems reaching substantiated conclusions using first principles
of mathematics, natural sciences, and engineering sciences.
PO3 - Design/development of solutions: Design solutions for complex engineering
problems and design system components or processes that meet the specified needs
with appropriate consideration for the public health and safety, and the cultural,
societal, and environmental considerations.
PO4 - Conduct investigations of complex problems: Use research-based knowledge
and research methods including design of experiments, analysis and interpretation of
data, and synthesis of the information to provide valid conclusions.
PO5 - Modern tool usage: Create, select, and apply appropriate techniques, resources,
and modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.
PO6 - The engineer and society: Apply reasoning informed by the contextual
knowledge to assess societal, health, safety, legal and cultural issues and the
consequent responsibilities relevant to the professional engineering practice.
PO7 - Environment and sustainability: Understand the impact of the professional
engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.
PO8 - Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
v
PO9 - Individual and team work: Function effectively as an individual, and as a
member or leader in diverse teams, and in multidisciplinary settings.
PO10 - Communication: Communicate effectively on complex engineering activities
with the engineering community and with society at large, such as, being able to
comprehend and write effective reports and design documentation, make effective
presentations, and give and receive clear instructions.
PO11 - Project management and finance: Demonstrate knowledge and
understanding of the engineering and management principles and apply these to one’s
own work, as a member and leader in a team, to manage projects and in
multidisciplinary environments.
PO12 - Life-long learning: Recognize the need for, and have the preparation and
ability to engage in independent and life-long learning in the broadest context of
technological change.
Program Specific Outcomes (PSOs)
PSO1: Graduates should be able to design and analyze the algorithms to develop an
Intelligent Systems
PSO2: Graduates should be able to apply the acquired skills to provide efficient
solutions for real time problems
PSO3: Graduates should be able to exhibit an understanding of System Architecture,
Networking and Information Security
vi
COURSE OUTCOMES:
At the end of the course, the student will able to
21CSP02.CO1 Understand the technical concepts of project area.
21CSP02.CO2 Identify the problem and formulation
21CSP02.CO3 Design the Problem Statement
21CSP02.CO4 Formulate the algorithm by using the design
21CSP02.CO5 Develop the Module
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3
✔ ✔ ✔ ✔ ✔ ✔ ✔ ✔ ✔ ✔ ✔ ✔ ✔ ✔ ✔
vii
INDEX
viii
5. PROJECT DESIGN 18
5.1 BLOCK DIAGRAM FOR FOOD DETECTION 18
5.2 DATASET 18
5.3 PREPROCESSING 20
5.4 EXPLORATORY DATA ANALYSIS 23
5.5 MODEL IMPLEMENTATION 23
5.6 CONVOLUTIONAL NEURAL NETWORKS 24
6. MODULE LIST 27
6.1 FOOD DATA GATHERING 27
6.2 FOOD IMAGE ENHANCEMENT 27
6.3 FOOD RECOGNITION MODEL DEPLOYMENT 28
6.4 FINAL IMPLEMENTATION AND DEPLOYMENT 28
7. CONCLUSION AND FUTURE ENHANCEMENT 29
7.1 CONCLUSION 29
7.2 FUTURE ENHANCEMENT 29
APPENDIX 30
A.1 SOURCE CODE 30
A.1.1 MAIN FILE 30
A.1.2 DATABASE 35
A.2 SCREENSHOTS 36
REFERENCES 39
PUBLICATIONS 41
ix
ABSTRACT
SmartBite utilizes deep learning techniques with Python and the MobileNet
architecture to identify food items and estimate calorie content in real-time. It offers
users intelligent and personalized diet monitoring, enabling healthier eating habits.
By analyzing images within seconds on a web framework, the system achieves high
precision in food recognition and calorie estimation. SmartBite empowers users to
monitor daily food intake, gain insights into nutritional patterns, and set
personalized health objectives. With its advanced food recognition algorithm, it can
distinguish between a wide variety of dishes, snacks, and beverages, providing
detailed calorie breakdowns for each. The platform also supports meal logging,
enabling users to track their eating habits over time. The system equips users with
essential dietary information, fostering well-informed decisions about food choices.
Additionally, it integrates recommendations for portion control and balanced
nutrition based on individual health goals, such as weight management or
maintaining a specific diet plan. With its advanced capabilities and user-friendly
interface, SmartBite encourages healthier lifestyles and supports balanced nutrition.
Its real-time analysis and feedback mechanisms make it a valuable tool for those
looking to adopt mindful eating practices, improve their dietary habits, and enhance
overall health outcomes.
x
LIST OF FIGURES
xi
LIST OF ABBREVIATIONS
TERM ABBREVIATIONS
AI Artificial Intelligence
DL Deep Learning
ML Machine Learning
IEEE Institute of Electrical and Electronics Engineers
RAD Rapid Application Development
PyPI Python Package Index
PyPL Python Programming Language
RELU Rectified Linear Unit
CNN Convolution Neural Network
FIC Food Image Dataset
USDA United States Department of Agriculture
SGD Stochastic Gradient Descent
NLP Natural Language Processing
LifeTech Life Sciences and Technologies
EDA Exploratory Data Analysis
MSE Mean Squared Error
Glove Global Vectors for Word Representation
xii
CHAPTER 1
INTRODUCTION
The platform processes food images uploaded by users, instantly identifying the
food items and breaking down their calorie content with high precision. SmartBite
caters to individuals with varying health goals, such as weight management,
maintaining specific dietary plans, or simply improving their overall nutrition. By
offering detailed insights into daily food intake and nutritional patterns, the system
allows users to track their progress toward health objectives effectively.
1
smooth user experience. Additionally, the platform’s database is enriched with a wide
variety of food items, ensuring comprehensive recognition capabilities.
1.2 OBJECTIVE
Deep learning plays a pivotal role in the SmartBite project, enabling real-time food
recognition and accurate calorie estimation. By leveraging advanced algorithms and
architectures, such as the MobileNet framework, the system can process and analyze
food images with high precision and efficiency. MobileNet, known for its lightweight
and efficient deep learning model, is particularly well-suited for real-time
applications, as it provides fast inference without compromising accuracy. This
2
ensures that users can receive instant feedback on their food intake, making the system
practical and user-friendly.
The core of the project revolves around Convolutional Neural Networks (CNNs),
which are highly effective for image recognition tasks. These networks extract
meaningful features from food images, such as shape, color, and texture, enabling the
system to identify various food items accurately. By training the CNNs on a vast and
diverse dataset of labeled food images, the model learns to recognize a wide array of
dishes and ingredients, from simple fruits to complex multi-component meals
1.4 ADVANTAGES
Real-time food recognition and feedback1
Accurate calorie estimation with minimal input
Lightweight MobileNet ensures fast processing
Supports diverse food items and cuisines
Streamlined user experience on all devices
3
CHAPTER 2
LITERATURE SURVEY
2.1 REVIEW I
TECHNIQUES
PUBLISHER : IEEE
VOLUME NO : 11
YEAR : 2023
4
2.2 REVIEW- II
DETECTION
VOLUME NO : 116
YEAR : 2020
The Automated skin cancer detection has significantly advanced with the rise
of artificial intelligence (AI) and deep learning techniquesThis research examines the
impact of incorporating patient metadata into machine learning models for skin cancer
detection. The study utilizes diverse datasets, comparing model performance with and
without additional clinical information. Findings indicate that AI-driven diagnostic
systems, when supplemented with contextual patient data, achieve higher sensitivity
and specificity, reducing false positives and false negatives. The study highlights that
patient demographics and medical history contribute to refining risk assessment
models, leading to more personalized and precise diagnoses.
Future advancements in automated skin cancer detection should focus on real-
time patient monitoring, federated learning approaches for secure data sharing, and AI
models capable of self-learning from continuous patient interactions. Additionally,
integrating electronic health records (EHRs) with dermatological imaging can further
enhance decision-making capabilities, paving the way for more robust, patient-
centered skin cancer diagnosis and treatment planning.
This research underscores the critical role of patient clinical information in
bridging the gap between AI-driven diagnostics and precision medicine, fostering a
more holistic approach to skin cancer detection and management.
5
2.3 REVIEW- III
ENGINEERING
VOLUME NO : 29
YEAR : 2022
6
2.4 REVIEW- IV
VOLUME NO : 11
YEAR : 2023
7
2.5 REVIEW- V
DIETARY ASSESSMENT
VOLUME NO : 16
YEAR : 2022
SYSTEM ANALYSIS
9
personalized, and user-friendly approach to food intake and nutrition estimation.
Addressing these limitations is crucial to building a next-generation solution that
seamlessly integrates accuracy, personalization, and usability.
3.1.1 LIMITATIONS
Current models achieve only around 73.29% accuracy during training and
78.7% during testing, leading to potential errors in food identification.
The system struggles with complex or mixed dishes where multiple food items
are present, reducing its ability to provide accurate calorie estimations.
Current systems rely on assumptions or user input for portion sizes, leading to
significant errors in calorie calculation.
Existing systems do not integrate personalized health data such as user-specific
dietary needs, allergies, or fitness goals, limiting their effectiveness for
individualized diet management.
The system's performance is sensitive to variations in lighting, image angles,
and food presentation styles, which can negatively impact recognition accuracy.
The system may perform well with common foods but show reduced accuracy
with less frequently encountered or unusual food items.
The computational demands of current systems often hinder real-time
processing, affecting their usability in everyday, on-the-go scenarios.
Many existing systems lack intuitive user interfaces, making it difficult for non-
tech-savvy users to navigate and effectively use the system.
Achieving high accuracy requires access to large and diverse food image
datasets for training, which can be time-consuming and difficult to acquire.
10
3.2 PROPOSED SYSTEM
This project aims to develop an expert system to provide personalized nutrition advice.
By analysing user’s health profiles and dietary needs, the system generates tailored
recommendations on nutrient intake, meal planning, and exercise routines. It aims to
improve nutritional awareness, reduce consultation time with nutritionists, and
promote healthier lifestyles.
The system's accuracy and precision are ensured by a vast dataset of food types,
nutritional information, and health parameters. It provides insights into general
wellness and nutrition, but future iterations can incorporate specific needs, such as
pregnancy or lactation.
Ultimately, this expert system offers a user-friendly platform for accessing reliable
nutrition advice and making informed decisions about dietary choices.
11
CHAPTER 4
SYSTEM REQUIREMENTS
RAM : 6 GB
Processor : I5 and Above
Hard disk space : 2 GB (minimum) free space available
Screen resolution : 1024 x 768 or higher
Mouse : Logitech Mouse
Keyboard : Standard Keyboard
12
4.3 HARDWARE DESCRIPTION
A well-structured hardware setup is crucial for ensuring the smooth operation
and efficiency of any system. The performance of a system largely depends on its
hardware configuration, which plays a key role in handling various tasks seamlessly.
One of the primary components is memory (RAM), which directly impacts the
system’s ability to manage multiple processes simultaneously. In this case, 6 GB RAM
ensures that applications run smoothly without lag or interruption, providing a stable
working environment.Another important aspect is processing power. A Core i5
processor or higher allows for faster execution of instructions, ensuring quick
responsiveness and improved system efficiency. A powerful processor enhances
computational capabilities, making the system more suitable for handling resource-
intensive applications and multitasking.
Storage capacity is another critical factor. The system requires at least 2 GB of free
disk space to accommodate essential software installations, updates, and file storage,
ensuring smooth operation without space limitations.Display quality also contributes
to a better user experience. A screen resolution of 1024 x 768 or higher ensures clarity
and sharpness, making it easier to view data, graphics, and other visual elements
effectively.
Additionally, peripherals like input devices play a crucial role in user interaction. A
Logitech mouse and a standard keyboard provide a comfortable and reliable input
experience, ensuring ease of navigation and efficient workflow.A well-optimized
hardware setup not only enhances productivity but also prevents performance
bottlenecks. By meeting these essential hardware requirements, the system can
function effectively, ensuring reliability, speed, and overall operational excellence.
13
4.4 SOFTWARE DESCRIPTION
Python
Python Features
Python
Python is commonly used for developing websites and software, task
automation, data analysis, and data visualization. Since it’s relatively easy to learn,
Python has been adopted by many non-programmers, such as accountants and
scientists, for a variety of everyday tasks, like organizing finances.
"Writing programs is a very creative and rewarding activity," says
University of Michigan and Coursers instructor Charles R Severance in his book
Python for Everybody. “You can write programs for many reasons, ranging from
making living to solving a difficult data analysis problem to having fun to helping
someone else solve a problem."
Uses:
• Data analysis and machine learning
• Web development
• Automation or scripting
• Software testing and prototyping
• Everyday tasks
What is Python? Executive Summary
Python is a versatile, high-level programming language known for its simplicity and
readability. Its dynamic typing and dynamic binding, combined with high-level data
structures, make it ideal for rapid application development and scripting. Python's
modularity and extensive standard library promote code reuse and efficient
14
development.
Python's interpreted nature simplifies the development process, as there's no
compilation step. Debugging is straightforward, with exceptions and stack traces
providing clear error information. The interactive interpreter and debugger further
enhance the debugging experience.
Python's combination of productivity, readability, and powerful features makes it a
popular choice for a wide range of applications.
Fast prototyping
15
Raspberry Pi,and others
Python Flexibility
Python, a dynamically typed language, is especially flexible, eliminating
hard rules for building features and offering more problem-solving flexibility with a
variety of methods. It also allows uses to compile and run programs right up to a
problematic area because it uses run-time type checking rather than compile-time
checking.
The Less Great Parts of Python
On the down side, Python isn’t easy to maintain. One command can have
multiple meanings depending on context because Python is a dynamically typed
language. And, maintaining a Python app as it grows in size and complexity can be
increasingly difficult, especially finding and fixing errors. Users will need experience
to design code or write unit tests that make maintenance easier.
Python and AI
AI researchers are fans of Python. Google TensorFlow, as well as other
libraries (scikit- learn, Keras), establish a foundation for AI development because of
the usability and it offers Python users. These libraries, and their availability, are
critical because they enable developers to focus on growth and building.
16
Good to Know
The Python Package Index (PyPI) is a repository of software for the Python
programming language. PyPI helps users find and install software developed and
shared by the Python community.
Applications
The Python Package Index (pypi) hosts thousands of third-party modules for
Python. Both Python's standard library and the community-contributed modules allow
for endless possibilities.
17
CHAPTER 5
PROJECT DESIGN
For the SmartBite AI-powered food recognition and calorie estimation system,
an essential component is the dataset used to train and evaluate the deep learning
model. The dataset should contain images of various food items along with their
associated nutritional information such as calorie content, macronutrients (proteins,
fats, carbohydrates), and micronutrients (vitamins, minerals). A diverse,
comprehensive dataset is critical for achieving high accuracy in food recognition and
calorie estimation.
18
A comprehensive food dataset for the SmartBite system should cover a wide range of
food categories, including fruits, vegetables, grains, dairy, proteins (meat, fish, tofu,
etc.), and beverages, ensuring representation of different cuisines and food
preparations. The dataset must feature high-quality, well-labeled images with
variations in lighting conditions, angles, and presentations to enhance the deep
learning model’s generalization to real-world scenarios. Each image should be
accurately annotated with the food name, serving size, and detailed nutritional
information, including calories, carbohydrates, fats, proteins, and micronutrient
content. To ensure diversity, food images should be sourced from different
geographical regions and cultures, incorporating datasets such as Food-101, UCI
Food-50, FIC, and ETHZ Food-101. Data augmentation techniques, including random
rotations, flipping, and scaling, will be applied to increase diversity and improve
model robustness. The dataset should also integrate nutritional information from
reputable sources like the USDA Food Database, Nutritionix, or MyFitnessPal for
precise calorie and macronutrient estimations. Additionally, real-time image data from
users, captured through a mobile app, can enhance the dataset by incorporating food
images taken from different angles and lighting conditions, along with user-provided
serving size information. The dataset will be systematically split into training,
validation, and test sets to optimize model accuracy and robustness. Crowdsourced
data, where users contribute images of their meals along with nutritional details, will
further enrich the dataset, ensuring broad coverage of food items. Ethical
considerations must be prioritized by obtaining user consent for data collection and
anonymizing personal information. By leveraging this extensive and continuously
updated dataset, the SmartBite system can employ deep learning techniques to
accurately recognize food items and estimate their nutritional values, adapting to
19
emerging food trends and user-generated content for improved functionality and
precision.
5.3 PREPROCESSING
1. Image Resizing: Images from the dataset are resized to a consistent resolution,
typically 224x224 or 299x299 pixels, depending on the architecture (e.g.,
20
MobileNet). This ensures uniformity in input size, which is essential for model
training.
2. Data Normalization: Image pixel values are scaled to a range of 0 to 1, or -1
to 1, by dividing by 255 or using a normalization technique like mean
subtraction. This helps standardize the input data and speeds up the
convergence of the model during training.
3. Image Augmentation: To enhance the robustness of the model, various
augmentation techniques are applied, such as random rotations, flips,
translations, and zooms. This simulates different scenarios, helping the model
generalize better by exposing it to a variety of food presentations, angles, and
lighting conditions.
4. Label Encoding: The food items in the images are labeled with their
corresponding nutritional information. For multi-class classification, the labels
are encoded into a one-hot format, where each food category is represented by
a binary vector. For regression tasks like calorie estimation, labels are treated
as continuous values.
5. Noise Reduction: To improve the quality of the images, preprocessing may
include techniques like image denoising or removing unwanted artifacts (such
as borders, watermarks, or irrelevant backgrounds). This ensures the food item
is the focus of the image, making it easier for the model to recognize.
6. Bounding Box Detection: If the food items are not isolated in the image, object
detection techniques may be used to identify the food’s region using bounding
boxes. This step involves detecting and cropping the food items from the
background, making it easier for the model to focus on the relevant portions of
the image.
7. Data Augmentation: Techniques like rotation, flipping, and zooming are
applied to create multiple variations of the same image, which increases the
21
diversity of the training set. This helps the model learn better and become more
robust to different viewing angles, food preparations, and lighting conditions.
8. Feature Extraction (for NLP/Hybrid Models): In cases where text data is
involved (e.g., food descriptions or ingredient lists), natural language
processing (NLP) techniques may be applied to extract relevant features.
Tokenization, word embeddings (like Word2Vec or GloVe), and sentiment
analysis are common methods used to preprocess textual data for the system.
By applying these preprocessing steps, the SmartBite system ensures that the
input data is clean, consistent, and ready for model training, leading to improved
performance in food recognition and calorie estimation tasks. Proper preprocessing
also aids in reducing overfitting, improving generalization, and accelerating the
training process.
22
5.4 EXPLORATORY DATA ANALYSIS (EDA)
Through EDA, the SmartBite system can refine features, select relevant
information, and improve the accuracy and robustness of its food recognition and
calorie estimation models.
The model implementation for the SmartBite AI-powered food recognition and
calorie estimation system leverages deep learning techniques, particularly
Convolutional Neural Networks (CNNs), for image classification and feature
extraction. The overall goal of the model is to identify food items from images and
accurately estimate their nutritional values, specifically the calorie content.
The model architecture begins with preprocessing, where input images are
resized and normalized to ensure consistency and improve the training efficiency. The
images are then passed through a series of convolutional layers that extract key
features from the images, such as edges, textures, and shapes, which are important for
23
food identification. These convolutional layers are followed by pooling layers to
reduce dimensionality and retain only the most essential features. The CNN model
typically employs activation functions like ReLU (Rectified Linear Unit) to introduce
non-linearity, allowing the model to learn complex patterns.
The extracted features are flattened and passed through fully connected layers
for food category prediction and nutritional value estimation. A softmax layer handles
multi-class classification, while regression techniques provide continuous calorie
estimates.The model is trained on a diverse dataset of labeled food images, including
food categories and nutritional values. Parameters are updated using backpropagation
and optimizers like Adam or SGD to minimize the loss between predicted and actual
calorie values.
After training, the model is validated and tested using a separate set of images
to evaluate its performance. Metrics such as accuracy, precision, recall, and Mean
Squared Error (MSE) are calculated to assess both the food classification accuracy
and the effectiveness of calorie estimation.
24
consists of multiple layers that work together to process the input image. The key
layers include:
25
model then selects the class with the highest probability as the predicted food
item.
6. In the SmartBite project, the CNN is trained on a large dataset of labeled food
images. Additionally, the CNN helps estimate the calorie content of the food
based on learned associations between food categories and their typical
nutritional values.
7. CNNs are highly effective for food recognition due to their ability to
automatically learn hierarchical features from raw pixel data.
26
CHAPTER 6
MODULE LIST
28
CHAPTER 7
7.1 CONCLUSION
Food detection and calorie estimation are two important tasks in the fields of
computer vision and health, with significant implications for dietary monitoring,
weight management, and healthcare. Recent advances in deep learning, particularly
the use of convolutional neural networks, have shown promising results in
accurately detecting food types and estimating their calorie content from images.
There are challenges in food image analysis, including variations in portion size,
lighting, and presentation. Inconsistent color representation and varying portion
sizes can hinder accurate recognition and calorie estimation. Incorporating
contextual information like ingredient lists, serving sizes, and user data can improve
accuracy and personalization. Future models could combine image, text, and sensor
data for even more precise predictions.
7.2 FUTURE ENHANCEMENT
To further enhance the SmartBite system, future developments could focus on multi-
modal inputs, improved food variations handling, and personalized health data
integration. By combining image, text, and sensor data, the system can achieve more
precise calorie estimation and tailored recommendations. Advanced techniques like
3D image reconstruction and data augmentation can improve the system's ability to
recognize food variations. Incorporating personalized health data can lead to more
customized and effective dietary advice.With these enhancements, SmartBite can
become a comprehensive and accurate tool for promoting healthy eating habits and
improving overall well-being.
29
APPENDIX
A.1 SOURCE CODE
A.1.1 MAIN FILE
from flask import Flask, request, jsonify, render_template, url_for
import tensorflow as tf
import numpy as np
import pickle
from tensorflow.keras.preprocessing.image import load_img, img_to_array
import io
import os
from flask import Flask, request, render_template
import contextlib
import joblib
import re
import sqlite3
import pandas as pd
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
from create_database import setup_database
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.image import img_to_array, load_img
from tensorflow.keras.applications.vgg16 import preprocess_input
from utils import login_required, set_session
from flask import (
30
Flask, render_template,
request, session, redirect
)
app = Flask(__name__)
# Load the trained model
model = tf.keras.models.load_model('models/food_classifier.h5
database = "users.db"
setup_database(name=database)
app.secret_key = 'xpSm7p5bgJY8rNoBjGWiz5yjxM-NEBlW6SIBI62OkLc='
# Load class labels
with open('models/class_labels.pkl', 'rb') as f:
class_labels = pickle.load(f)
# Calorie dictionary
calorie_dict = {
'Apple': 52, # Calories per 100g
'Banana': 89,
'Peanuts': 567,
'Pizza': 266,
# Add more classes as needed
@app.route('/')
def index():
return render_template('index.html')
31
# Homepage route
@app.route('/')
def home():
return render_template('index.html')
@app.route('/about')
def about():
return render_template('about.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'GET':
return render_template('login.html')
# Set data to variables
username = request.form.get('username')
password = request.form.get('password')
# Attempt to query associated user data
query = 'select username, password, email from users where username =
:username'
with contextlib.closing(sqlite3.connect(database)) as conn:
with conn:
account = conn.execute(query, {'username': username}).fetchone()
if not account:
return render_template('login.html', error='Username does not exist')
# Verify password
Try
32
ph = PasswordHasher()
ph.verify(account[1], password)
except VerifyMismatchError:
return render_template('login.html', error='Incorrect password')
# Check if password hash needs to be updated
# Set cookie for user session
set_session(
username=account[0],
email=account[2],
remember_me='remember-me' in request.form
)
return redirect('/predict_page')
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'GET':
return render_template('register.html')
# Store data to variables
password = request.form.get('password')
confirm_password = request.form.get('confirm-password')
username = request.form.get('username')
email = request.form.get('email')
# Verify data
if len(password) < 8:
return render_template('register.html', error='Your password must be 8 or more
33
characters')
if password != confirm_password:
if not re.match(r'^[a-zA-Z0-9]+$', username):
return render_template('register.html', error='Username must only be letters
and numbers')
query = 'select username from users where username = :username;'
if result:
return render_template('register.html', error='Username already exists')
# Create password hash
pw = PasswordHasher()
hashed_password = pw.hash(password)
query = 'insert into users(username, password, email) values (:username,
:password, :email);'
params = {
'username': username,
'password': hashed_password,
'email': email
}
with contextlib.closing(sqlite3.connect(database)) as conn:
with conn:
def predict_food_and_calories():
return render_template('result.html', food=food, calories=calories)
if __name__ == '__main__':
app.run(debug=True)
34
A.1.2 DATABASE
import sqlite3
import contextlib
from pathlib import Path
def create_connection(db_file: str) -> None:
""" Create a database connection to a SQLite database """
Try :conn = sqlite3.connect(db_file)
finally:
conn.close()
def create_table(db_file: str) -> None:
""" Create a table for users """
query = '''
CREATE TABLE IF NOT EXISTS users (
username TEXT PRIMARY KEY,
password TEXT NOT NULL,
email TEXT
) ; with contextlib.closing(sqlite3.connect(db_file)) as conn:
with conn : conn.execute(query)
def setup_database(name: str) -> None:
if Path(name).exists():
return
create_connection(name)
create_table(name)
print('\033[91m', 'Creating new example database "users.db"', '\033[0m')
35
A.2 SCREENSHOTS
36
Figure A.2.3 Register page
37
Figure A.2.5 Image upload page
38
REFERENCES
1. A.G.C. Pacheco and R. A. Krohling, ‘‘The impact of patient clinical
information on automated skin cancer detection,’’ Comput. Biol. Med., vol.
116, Jan. 2020, Art. no. 103545.
39
7. L. M. König, M. Van Emmenis, J. Nurmi, A. Kassavou, and S. Sutton,
‘‘Characteristics of smartphone-based dietary assessment tools: A
systematic review,’’ Health Psychol. Rev., vol. 16, no. 4, pp. 526–550, Oct.
2022.
12. Yessi Jusman, Indah Monisa Firdiantika, Dhimas Arief Dharmawan and Kunnu
Purwanto, "Performance of multi layer perceptron and deep neural
networks in skin cancer classification", 2021 IEEE 3rd Global Conference
on Life Sciences and Technologies (LifeTech), pp. 534-538, 2021.
40
PUBLICATIONS
41