FINAL YEAR PROJECT REPORT
Algorithm Analysis
AI-Powered Calorie & Diet Tracker
Built with Django · TensorFlow · Machine Learning
Date: June 14, 2026
Department of Computer Science & Engineering
Table of Contents
1. BMI Calculation Algorithm
2. Calorie & Nutrient Aggregation Algorithm
3. Rule-Based Insight Engine
4. Smart Meal Suggestion Engine
5. Time-Based Meal Reminder Algorithm
6. Weekly Calorie Trend Aggregation
7. Machine Learning — Calorie Prediction Model
8. CNN-Based Food Image Recognition
9. Summary Table
1. BMI Calculation Algorithm
Overview
The Body Mass Index (BMI) algorithm is applied during user registration to classify the user's body
composition. It is one of the most widely accepted medical screening tools for identifying weight
categories that may lead to health problems.
Formula
Formula BMI = weight(kg) / (height(m))²
Where Weight is in kilograms; Height is converted from centimetres to metres
Location [Link] → register() function
Type Mathematical / Biomedical Formula
Code Implementation
bmi = weight / ((height / 100) ** 2)
# height is in cm, divide by 100 to convert to metres
# result is stored in UserProfile model
Interpretation
BMI Range Category
Below 18.5 Underweight
18.5 – 24.9 Normal weight
25.0 – 29.9 Overweight
30.0 and above Obese
Note: The computed BMI is stored in the UserProfile model and can be used in future versions to personalise
calorie goals based on clinical thresholds.
2. Calorie & Nutrient Aggregation Algorithm
Overview
This algorithm computes the total caloric and macronutrient intake for a selected day. All nutritional
values stored in the database are expressed per 100g; the algorithm scales them linearly
according to the actual quantity consumed by the user. This is a proportional weighted summation.
Algorithm Details
Type Weighted Summation / Linear Scaling
Inputs [Link], [Link], [Link], [Link], [Link],
[Link]
Output total_calories, total_carbs, total_protein, total_fat, total_fiber
Location [Link] → dashboard() function
Code Implementation
total_calories = 0
total_carbs = total_protein = total_fat = total_fiber = 0
for meal in meals:
total_calories += [Link]
if [Link]:
food = [Link]
qty = [Link]
total_carbs += ([Link] * qty) / 100
total_protein += ([Link] * qty) / 100
total_fat += ([Link] * qty) / 100
total_fiber += ([Link] * qty) / 100
Mathematical Basis
For each nutrient N with per-100g value n and quantity q grams consumed:
Total_N = (n * q) / 100
This scales the stored nutritional value from per-100g to the actual gram weight eaten, making the tracking
accurate for any portion size.
3. Rule-Based Insight Engine
Overview
The insight engine mimics a simple expert system by encoding nutritionist knowledge as a
prioritised chain of if-else rules. It evaluates the day's total calorie intake against the user's
personalised calorie goal and produces a human-readable dietary message.
Algorithm Details
Type Rule-Based Expert System / Decision Logic
Inputs total_calories, goal (user's calorie target)
Output insight (string message displayed on dashboard)
Location [Link] → dashboard() function
Decision Rules
Priority Condition Insight Displayed
1 (highest) total_calories == 0 No meals logged for this day.
You exceeded your goal by X
2 total_calories > goal
kcal.
You're far below your goal.
3 total_calories < goal × 0.5
Add a proper meal.
You need X kcal to reach your
4 total_calories < goal
goal.
You're doing well. Keep
5 (default) total_calories ≈ goal
maintaining balance!
Code Implementation
if total_calories == 0:
insight = 'No meals logged for this day.'
elif total_calories > goal:
extra = round(total_calories - goal, 2)
insight = f'You exceeded your goal by {extra} kcal.'
elif total_calories < goal * 0.5:
insight = 'You are far below your goal. Add a proper meal.'
elif total_calories < goal:
remaining = round(goal - total_calories, 2)
insight = f'You need {remaining} kcal to reach your goal.'
else:
insight = 'You are doing well. Keep maintaining balance!'
This approach is computationally lightweight and deterministic — ideal for real-time feedback without
requiring model inference.
4. Smart Meal Suggestion Engine
Overview
This algorithm provides context-aware food recommendations by combining rule-based conditions
with a history-based frequency analysis. It evaluates multiple nutritional signals and user
preferences to suggest appropriate meals in real time.
Algorithm Details
Type Multi-condition Rule Engine + Frequency-Based Recommendation
Inputs profile (diet_type), total_calories, total_protein, goal, meals queryset
Output List of suggested food items with estimated calories
Location [Link] → generate_meal_suggestions() function
Decision Flow (Priority Order)
Priority Condition Suggestions Rationale
Calories exceeded Cucumber Salad,
1 Reduce further intake
goal Green Tea, Fruit Bowl
Protein < 50g Paneer Bhurji, Dal Diet-aware protein
2a
(Vegetarian) Tadka boost
Protein < 50g Boiled Eggs, Grilled High-protein non-veg
2b
(Non-veg) Chicken options
Calories < 50% of Rice + Dal, Chapati + Calorie-dense staple
3
goal Sabzi foods
Top 3 most-eaten
Personalised
4 History-based fallback foods from user
recurrence
history
Balanced Meal, Generic healthy
5 Default
Protein Shake fallback
History-Based Recommendation (Frequency Analysis)
When no primary condition is triggered, the algorithm queries the user's meal history and ranks
foods by consumption frequency using Django ORM aggregation. This is a simplified form of
collaborative filtering — recommending items the user has historically preferred.
frequent_foods = (
[Link]('food__name')
.annotate(count=[Link]('food__name'))
.order_by('-count')[:3]
)
suggestions = [
{'name': f"{food['food__name']} (Your Favourite)", 'cal': 'Repeat Meal'}
for food in frequent_foods
]
5. Time-Based Meal Reminder Algorithm
Overview
This algorithm monitors the current system time and checks whether the expected meal for that
time-of-day has been logged. It uses a time-window classification approach to assign meal types to
time slots and triggers a reminder if the relevant meal is absent.
Algorithm Details
Type Time-Window Classification / Rule-Based Alerting
Inputs current_hour (int), meals queryset (filtered by meal_type)
Output meal_reminder (string displayed on dashboard)
Location [Link] → dashboard() function
Time Window Classification
Hour Range Time of Day Meal Checked Reminder if Missing
■■ Breakfast not
00:00 – 10:59 Morning Breakfast
logged today.
■■ Lunch not logged
11:00 – 15:59 Afternoon Lunch
today.
■■ Dinner not logged
16:00 – 23:59 Evening Dinner
today.
Code Implementation
current_hour = [Link]().hour
if current_hour < 11:
if not [Link](meal_type='breakfast').exists():
meal_reminder = '■■ Breakfast not logged today.'
elif current_hour < 16:
if not [Link](meal_type='lunch').exists():
meal_reminder = '■■ Lunch not logged today.'
else:
if not [Link](meal_type='dinner').exists():
meal_reminder = '■■ Dinner not logged today.'
if meal_reminder == '':
meal_reminder = '■ Great job! Stay healthy.'
6. Weekly Calorie Trend Aggregation
Overview
This algorithm computes the total caloric intake for each of the past 7 days and packages the data
for rendering a weekly trend chart on the dashboard. It uses a sliding window approach, iterating
backwards from today to produce a chronologically ordered dataset.
Algorithm Details
Type Sliding Window Temporal Aggregation
Inputs [Link](), Meal queryset filtered by user and date
Output week_days (list of labels), week_calories (list of totals)
Location [Link] → dashboard() function
Chart Use Rendered as a bar/line chart using JavaScript on the frontend
Code Implementation
week_days = []
week_calories = []
for i in range(6, -1, -1): # i = 6,5,4,...,0
day = [Link]() - timedelta(days=i)
day_meals = [Link](user=[Link], date=day)
total_day_calories = sum([Link] for m in day_meals)
week_days.append([Link]('%a')) # e.g. 'Mon'
week_calories.append(round(total_day_calories, 2))
The loop runs from offset 6 (6 days ago) down to 0 (today), ensuring the output list is in ascending
chronological order — oldest day first, today last.
7. Machine Learning — Calorie Prediction Model
Overview
A supervised machine learning regression model is used to independently predict the total calorie
content from the day's macronutrient profile. This prediction acts as a cross-validation layer —
comparing the ML-predicted value against the manually aggregated total to detect inconsistencies
or logging errors.
Algorithm Details
Type Supervised Regression (ML)
Input Features Total Carbohydrates (g), Total Protein (g), Total Fat (g), Total Fiber (g)
Output Predicted calorie total (float, in kcal)
Module tracker/ml/model_loader.py → predict_calories()
Framework Likely scikit-learn or TensorFlow (saved model loaded at runtime)
Training Offline on a labelled nutrition dataset; model serialised and loaded for
inference
How It Works
The model is trained using known relationships between macronutrients and caloric content. The
standard thermodynamic values are: Carbohydrates = 4 kcal/g, Protein = 4 kcal/g, Fat = 9 kcal/g,
Fiber ≈ 2 kcal/g. The model learns these weights (and any non-linear interactions) from the training
data.
Code Implementation
from [Link].model_loader import predict_calories
if [Link]():
predicted_calories = predict_calories(
total_carbs,
total_protein,
total_fat,
total_fiber
)
else:
predicted_calories = 0
Possible Model Architectures
Model Type Approach Suitable For
Fits a linear equation to Simple linear calorie
Linear Regression
feature-target pairs relationships
Ensemble of decision trees;
Random Forest Regressor Non-linear nutrient interactions
averages predictions
Fully connected layers; learns
Neural Network (MLP) Large nutrition datasets
complex feature mappings
Sequential weak learners; High accuracy with tabular
Gradient Boosting
minimises residual error data
8. CNN-Based Food Image Recognition
Overview
A Convolutional Neural Network (CNN) is used to classify food items from user-uploaded images.
This is the most computationally advanced component of the system, enabling users to log meals
simply by photographing their food — the model predicts the food name, which is then used to look
up calorie information from the database.
Algorithm Details
Type Deep Learning — Image Classification (CNN)
Framework TensorFlow / Keras
Input User-uploaded food image (JPEG/PNG)
Output Predicted food class name (string)
Module tracker/ml/cnn_predictor.py → predict_food()
Integration scan_food() view in [Link]
CNN Architecture — How It Works
Layer Type Function
Input Layer Accepts resized image (e.g. 224×224×3 RGB)
Extract spatial features: edges, textures,
Convolutional Layers
shapes using learnable filters
Introduces non-linearity; suppresses negative
Activation (ReLU)
activations
Reduces spatial dimensions; retains dominant
Pooling Layers (MaxPooling)
features
Converts 2D feature maps to 1D vector for
Flatten Layer
classification
Fully Connected (Dense) Layers Learns high-level combinations of features
Outputs probability distribution over all food
Softmax Output Layer
classes
Code Implementation
from [Link] import image
from .ml.cnn_predictor import predict_food
# STEP 1: Predict food from image
if step == 'predict':
image_file = [Link]('food_image')
predicted_food = predict_food(image_file)
food = [Link](name__icontains=predicted_food).first()
if food:
calories = [Link]
# STEP 2: Save meal with user-confirmed quantity
elif step == 'save':
total_calories = ([Link] * quantity) / 100
[Link](user=[Link], ...)
Two-Step Prediction Workflow
Step Action Actor
User uploads image → CNN
1 — Predict predicts food class → calorie System (CNN Model)
shown
User reviews prediction, enters
2 — Confirm quantity → meal saved to User + System
database
This two-step design improves accuracy by allowing the user to correct incorrect CNN predictions before
committing a meal entry to the database.
9. Summary of All Algorithms
The table below provides a consolidated reference of all algorithms implemented in the AI-Powered
Calorie and Diet Tracker project:
# Algorithm Type Purpose
Compute user body
1 BMI Calculation Mathematical Formula
index at registration
Track daily calorie &
2 Nutrient Aggregation Weighted Summation
macro intake
Generate
Rule-Based Expert
3 Insight Engine personalised dietary
System
feedback
Meal Suggestion Rule-Based + Recommend suitable
4
Engine Frequency CF foods contextually
Time-Window Prompt user to log
5 Meal Reminder
Classification missing meals
Weekly Trend Sliding Window Compute 7-day
6
Aggregation Aggregation calorie trend for chart
Calorie Prediction Supervised Predict calories from
7
(ML) Regression (ML) macronutrients
Food Image Deep Learning Identify food from
8
Recognition (CNN) Classification camera image
This report was auto-generated for Final Year Project documentation purposes.