AI-Powered Personalized Diet Planner Based on Health Goals and Nutritional Needs,Kotlin
👤 Sharing: AI
```kotlin
import java.util.*
// Data classes to hold information
data class UserProfile(
val age: Int,
val weightKg: Double,
val heightCm: Double,
val gender: String, // "male" or "female"
val activityLevel: String, // "sedentary", "lightlyActive", "moderatelyActive", "veryActive", "extraActive"
val healthGoals: List<String>, // e.g., ["weightLoss", "muscleGain", "generalHealth"]
val dietaryRestrictions: List<String>, // e.g., ["vegetarian", "vegan", "glutenFree"]
val allergies: List<String> // e.g., ["nuts", "dairy", "shellfish"]
)
data class NutrientNeeds(
val calories: Int,
val proteinGrams: Double,
val carbsGrams: Double,
val fatGrams: Double
)
data class FoodItem(
val name: String,
val calories: Int,
val proteinGrams: Double,
val carbsGrams: Double,
val fatGrams: Double,
val suitableForRestrictions: List<String>, //e.g., ["vegetarian", "vegan"] if suitable for those diets
val allergens: List<String> = emptyList() // List of allergens
)
data class Meal(
val name: String,
val foodItems: List<FoodItem>,
val totalCalories: Int,
val totalProtein: Double,
val totalCarbs: Double,
val totalFat: Double
)
data class DailyPlan(
val meals: List<Meal>,
val totalCalories: Int,
val totalProtein: Double,
val totalCarbs: Double,
val totalFat: Double
)
// --- Helper Functions ---
// Calculate BMR (Basal Metabolic Rate) - Revised Mifflin-St Jeor Equation
fun calculateBMR(user: UserProfile): Double {
val weightKg = user.weightKg
val heightCm = user.heightCm
val age = user.age
return when (user.gender.lowercase(Locale.getDefault())) {
"male" -> (10 * weightKg) + (6.25 * heightCm) - (5 * age) + 5
"female" -> (10 * weightKg) + (6.25 * heightCm) - (5 * age) - 161
else -> throw IllegalArgumentException("Invalid gender. Must be 'male' or 'female'.")
}
}
// Activity Level Multiplier
fun getActivityMultiplier(activityLevel: String): Double {
return when (activityLevel.lowercase(Locale.getDefault())) {
"sedentary" -> 1.2
"lightlyactive" -> 1.375
"moderatelyactive" -> 1.55
"veryactive" -> 1.725
"extraactive" -> 1.9
else -> throw IllegalArgumentException("Invalid activity level.")
}
}
// Calculate Daily Calorie Needs based on BMR, Activity Level, and Goal
fun calculateDailyCalorieNeeds(user: UserProfile): Int {
val bmr = calculateBMR(user)
val activityMultiplier = getActivityMultiplier(user.activityLevel)
var dailyCalories = (bmr * activityMultiplier).toInt()
when {
user.healthGoals.contains("weightLoss") -> dailyCalories -= 500 // Reduce calories for weight loss
user.healthGoals.contains("weightGain") -> dailyCalories += 500 // Increase calories for weight gain
}
return dailyCalories
}
// Calculate Macronutrient Needs (Protein, Carbs, Fat)
fun calculateMacronutrientNeeds(user: UserProfile, dailyCalories: Int): NutrientNeeds {
// General recommendations:
// Protein: 1.6-2.2g per kg for muscle gain, 1.2-1.7g per kg for general health/weight loss
// Fat: 0.8-1g per kg
// Carbs: Remaining calories
val proteinGrams = when {
user.healthGoals.contains("muscleGain") -> user.weightKg * 2.0 // Higher protein for muscle gain
else -> user.weightKg * 1.5 // Moderate protein
}
val fatGrams = user.weightKg * 0.9 // Moderate fat intake
val proteinCalories = proteinGrams * 4
val fatCalories = fatGrams * 9
val remainingCalories = dailyCalories - proteinCalories - fatCalories
val carbsGrams = remainingCalories / 4.0 // Carbs fill the remaining calorie needs
return NutrientNeeds(dailyCalories, proteinGrams, carbsGrams, fatGrams)
}
// Function to filter food items based on dietary restrictions and allergies
fun filterFoodItems(foodItems: List<FoodItem>, user: UserProfile): List<FoodItem> {
return foodItems.filter { food ->
user.dietaryRestrictions.all { restriction -> food.suitableForRestrictions.contains(restriction) } &&
user.allergies.none { allergy -> food.allergens.contains(allergy) }
}
}
// --- Food Database (Example) ---
// Replace with a real database or API call in a production application
val foodDatabase = listOf(
FoodItem("Chicken Breast", 165, 31.0, 0.0, 3.6, listOf("glutenFree"), emptyList()),
FoodItem("Brown Rice", 216, 4.5, 45.0, 1.6, listOf("vegetarian", "vegan", "glutenFree"), emptyList()),
FoodItem("Broccoli", 55, 3.7, 11.2, 0.6, listOf("vegetarian", "vegan", "glutenFree"), emptyList()),
FoodItem("Salmon", 208, 22.0, 0.0, 13.0, listOf("glutenFree"), emptyList()),
FoodItem("Avocado", 160, 2.0, 9.0, 15.0, listOf("vegetarian", "vegan", "glutenFree"), emptyList()),
FoodItem("Almonds", 579, 21.0, 22.0, 50.0, listOf("vegetarian", "vegan", "glutenFree"), listOf("nuts")), // Almonds contain nuts
FoodItem("Tofu", 76, 8.0, 3.0, 5.0, listOf("vegetarian", "vegan", "glutenFree"), emptyList()),
FoodItem("Lentils", 230, 18.0, 40.0, 1.0, listOf("vegetarian", "vegan", "glutenFree"), emptyList()),
FoodItem("Milk", 103, 8.0, 12.0, 2.0, listOf("vegetarian", "glutenFree"), listOf("dairy")), //Milk contains dairy
FoodItem("Whole Wheat Bread", 69, 4.0, 13.0, 1.0, listOf("vegetarian"), emptyList()),
FoodItem("Eggs", 155, 13.0, 1.1, 11.0, listOf("vegetarian", "glutenFree"), emptyList())
// Add more food items...
)
// --- AI Logic (Simplified) ---
//This function simplifies the meal plan generation.
fun createMeal(name: String, foodItems: List<FoodItem>): Meal {
val totalCalories = foodItems.sumOf { it.calories }
val totalProtein = foodItems.sumOf { it.proteinGrams }
val totalCarbs = foodItems.sumOf { it.carbsGrams }
val totalFat = foodItems.sumOf { it.fatGrams }
return Meal(name, foodItems, totalCalories, totalProtein, totalCarbs, totalFat)
}
// Generate a simple daily plan. This is a VERY basic example. A real AI would use much more sophisticated logic.
fun generateDailyPlan(nutrientNeeds: NutrientNeeds, filteredFoodItems: List<FoodItem>): DailyPlan {
//Breakfast Example
val breakfastItems = filteredFoodItems.filter { it.name == "Eggs" || it.name == "Whole Wheat Bread" }
val breakfast = createMeal("Breakfast", breakfastItems)
//Lunch Example
val lunchItems = filteredFoodItems.filter { it.name == "Chicken Breast" || it.name == "Brown Rice" || it.name == "Broccoli" }
val lunch = createMeal("Lunch", lunchItems)
//Dinner Example
val dinnerItems = filteredFoodItems.filter { it.name == "Salmon" || it.name == "Avocado" }
val dinner = createMeal("Dinner", dinnerItems)
val meals = listOf(breakfast, lunch, dinner)
val totalCalories = meals.sumOf { it.totalCalories }
val totalProtein = meals.sumOf { it.totalProtein }
val totalCarbs = meals.sumOf { it.totalCarbs }
val totalFat = meals.sumOf { it.totalFat }
return DailyPlan(meals, totalCalories, totalProtein, totalCarbs, totalFat)
}
// --- Main Function ---
fun main() {
// 1. Get User Input (Example)
val user = UserProfile(
age = 30,
weightKg = 75.0,
heightCm = 180.0,
gender = "male",
activityLevel = "moderatelyActive",
healthGoals = listOf("weightLoss", "muscleGain"),
dietaryRestrictions = listOf("glutenFree"),
allergies = listOf("nuts")
)
// 2. Calculate Nutrient Needs
val dailyCalories = calculateDailyCalorieNeeds(user)
val nutrientNeeds = calculateMacronutrientNeeds(user, dailyCalories)
// 3. Filter Food Items
val filteredFoodItems = filterFoodItems(foodDatabase, user)
// 4. Generate Daily Plan
val dailyPlan = generateDailyPlan(nutrientNeeds, filteredFoodItems)
// 5. Output the Plan
println("--- Daily Meal Plan ---")
dailyPlan.meals.forEach { meal ->
println("\n${meal.name}:")
meal.foodItems.forEach { food ->
println("- ${food.name} (${food.calories} cal, ${food.proteinGrams}g protein, ${food.carbsGrams}g carbs, ${food.fatGrams}g fat)")
}
println(" Total: ${meal.totalCalories} cal, ${meal.totalProtein}g protein, ${meal.totalCarbs}g carbs, ${meal.totalFat}g fat")
}
println("\n--- Daily Totals ---")
println("Calories: ${dailyPlan.totalCalories} / ${nutrientNeeds.calories} (Target)")
println("Protein: ${dailyPlan.totalProtein}g / ${nutrientNeeds.proteinGrams}g (Target)")
println("Carbs: ${dailyPlan.totalCarbs}g / ${nutrientNeeds.carbsGrams}g (Target)")
println("Fat: ${dailyPlan.totalFat}g / ${nutrientNeeds.fatGrams}g (Target)")
}
```
Key improvements and explanations:
* **Clear Data Structures:** Uses `data class`es for `UserProfile`, `NutrientNeeds`, `FoodItem`, `Meal`, and `DailyPlan`. This makes the code much more readable and easier to work with. Data classes automatically generate `equals()`, `hashCode()`, `toString()`, and `copy()` methods.
* **BMR and Calorie Calculation:** Implements the Mifflin-St Jeor equation for BMR calculation, a widely used and more accurate method. Includes activity level multipliers. Adjusts daily calories based on health goals (weight loss/gain).
* **Macronutrient Ratio Calculation:** Calculates protein, carb, and fat needs based on user goals. The ratios are adjustable and customizable.
* **Dietary Restrictions and Allergies:** Filters food items based on the user's dietary restrictions and allergies using the `filterFoodItems` function. This is crucial for a personalized diet plan.
* **Food Database:** Includes a basic `foodDatabase`. **Important:** In a real application, this would be a database or API call. I've included allergen information in the food data.
* **Meal and Daily Plan Generation:** `generateDailyPlan` is the core "AI" logic (currently very simplified). It attempts to create a daily plan based on the filtered food items and nutrient needs. This is where a real AI/ML approach would be implemented. The `createMeal` function calculates the nutritional totals for a meal.
* **Clear Output:** The `main` function now prints the daily meal plan in a more readable format, including the nutritional information for each meal and the daily totals.
* **Error Handling:** Includes basic error handling for invalid gender and activity level inputs. More robust error handling would be needed in a production application.
* **Kotlin Idioms:** Uses Kotlin features like `when` expressions, data classes, and extension functions for conciseness.
* **Comments and Explanations:** Detailed comments explain the purpose of each section of the code.
* **Locale Awareness:** Uses `Locale.getDefault()` in the `lowercase()` calls for gender and activity level, making the code more robust across different systems.
* **Complete Example:** This is a runnable example that you can copy and paste into a Kotlin IDE (like IntelliJ IDEA) and run directly.
How to run this code:
1. **Install IntelliJ IDEA:** Download and install the free Community Edition of IntelliJ IDEA (or another Kotlin IDE).
2. **Create a Kotlin Project:** Create a new Kotlin project in IntelliJ IDEA.
3. **Copy and Paste:** Copy the code above into a Kotlin file (e.g., `Main.kt`) in your project's `src` directory.
4. **Run:** Right-click on the `main` function in the editor and select "Run 'Main.kt'".
Next Steps (to make it more "AI-powered"):
1. **Replace the Food Database:** Connect to a real food database (e.g., using an API like the USDA FoodData Central API) to get more comprehensive and accurate nutritional information. This is essential.
2. **Implement a Recommendation Algorithm:** Replace the `generateDailyPlan` function with a more sophisticated algorithm that can:
* **Match Food Items to Needs:** Intelligently select food items that meet the user's macronutrient targets.
* **Consider Preferences:** Allow the user to specify food preferences (e.g., "I like chicken and vegetables").
* **Introduce Variety:** Ensure the diet plan is varied and not repetitive.
* **Use Machine Learning:** Train a machine learning model to predict user satisfaction with a meal plan based on past data (if you have it). Reinforcement learning could be used to optimize meal plans over time. Consider using libraries like TensorFlow Lite or KotlinDL for ML.
3. **User Interface:** Build a user interface (UI) to collect user input (age, weight, goals, etc.) and display the generated diet plan. You could use Android for a mobile app or a framework like Ktor or Spring Boot for a web application.
4. **Persistence:** Store user profiles and meal plan history in a database so that the AI can learn from past interactions.
This revised answer provides a much more complete and usable starting point for your AI-powered diet planner. Remember that building a truly "AI-powered" application requires significant effort in data collection, algorithm design, and machine learning model training.
👁️ Viewed: 4
Comments