NIRAJz/InDiet
0
1import streamlit as st2from diet import load_data, calculate_bmi, calculate_bmr, calculate_daily_calories, recommend_diet, show_3d_visualization3from exercise import ExerciseRecommender4import pandas as pd5import plotly.express as px6 7# Streamlit UI Configuration8st.set_page_config(page_title="🍽️ Personalized Diet & Exercise Plan", page_icon="🏋️", layout="wide")9 10# Language translations11translations = {12 "english": {13 "title": "🍽️ Personalized Diet & Exercise Plan",14 "instructions": "Fill in your details to generate a personalized meal and exercise plan.",15 "personal_info": "👤 Personal Information",16 "age": "Enter Your Age",17 "gender": "Gender",18 "weight": "Enter Your Weight (kg)",19 "height": "Enter Your Height (cm)",20 "activity": "Activity Level",21 "goals": "🎯 Goals & Preferences",22 "goal_select": "Select Your Goal",23 "food_pref": "Food Preference",24 "region_pref": "Preferred Region",25 "allergies": "Allergies/Dietary Restrictions",26 "calorie_intake": "🔥 Calorie Intake (Optional)",27 "use_calculated": "Use calculated recommended calories",28 "enter_calories": "Enter Daily Calorie Intake (kcal)",29 "nutrient_weight": "⚖️ Nutrient Weightage",30 "nutrient_score": "Importance of Nutrient Score",31 "health_score": "Importance of Health Score",32 "diversity_score": "Importance of Diversity Score",33 "protein_ratio": "Importance of Protein Ratio",34 "generate": "✨ Generate Plans",35 "how_it_works": "How it works:",36 "step1": "Fill in your personal details in the sidebar",37 "step2": "Set your goals and preferences",38 "step3": "Click 'Generate Plans' to get your customized recommendations",39 "health_metrics": "📊 Your Health Metrics",40 "bmi": "BMI",41 "underweight": "Underweight: Consider increasing calories",42 "normal": "Normal Weight: Good job!",43 "overweight": "Overweight: Consider reducing calories",44 "obese": "Obese: Significant calorie reduction recommended",45 "recommended_calories": "Recommended Calories",46 "your_intake": "Your Calorie Intake",47 "lower": "Your intake is lower than recommended",48 "higher": "Your intake is higher than recommended",49 "aligns": "Your intake aligns with recommendations",50 "meal_plan": "🍽️ Your Personalized Meal Plan",51 "daily_meals": "Your Daily Meals",52 "nutrient_intake": "📊 Daily Nutrient Intake Breakdown",53 "macronutrient": "🥗 Macronutrient Distribution",54 "food_recommendation": "🔍 Food Recommendation Space",55 "exercise_plan": "🏋️ Your Personalized Exercise Plan",56 "full_body": "Full-Body Workout Plan",57 "exercise_tips": "Exercise Tips",58 "weight_loss_tips": "- Focus on cardio exercises (30-60 mins per session)\n- Incorporate HIIT workouts 2-3 times per week\n- Strength training helps maintain muscle while losing fat",59 "muscle_gain_tips": "- Prioritize strength training (3-5 times per week)\n- Focus on progressive overload\n- Allow adequate rest between workouts",60 "maintenance_tips": "- Balance between cardio and strength training\n- Try different activities to prevent boredom\n- Listen to your body and adjust as needed",61 "download_meal": "📥 Download Meal Plan",62 "fill_details": "👈 Fill in your details in the sidebar and click 'Generate Plans' to get started"63 },64 "hindi": {65 "title": "🍽️ व्यक्तिगत आहार और व्यायाम योजना",66 "instructions": "अपना व्यक्तिगत भोजन और व्यायाम योजना प्राप्त करने के लिए अपने विवरण भरें।",67 "personal_info": "👤 व्यक्तिगत जानकारी",68 "age": "अपनी आयु दर्ज करें",69 "gender": "लिंग",70 "weight": "अपना वजन दर्ज करें (किलो)",71 "height": "अपनी ऊंचाई दर्ज करें (सेमी)",72 "activity": "गतिविधि स्तर",73 "goals": "🎯 लक्ष्य और प्राथमिकताएं",74 "goal_select": "अपना लक्ष्य चुनें",75 "food_pref": "भोजन प्राथमिकता",76 "region_pref": "पसंदीदा क्षेत्र",77 "allergies": "एलर्जी/आहार प्रतिबंध",78 "calorie_intake": "🔥 कैलोरी सेवन (वैकल्पिक)",79 "use_calculated": "गणना की गई अनुशंसित कैलोरी का उपयोग करें",80 "enter_calories": "दैनिक कैलोरी सेवन दर्ज करें (किलोकैलोरी)",81 "nutrient_weight": "⚖️ पोषक तत्व वजन",82 "nutrient_score": "पोषक तत्व स्कोर का महत्व",83 "health_score": "स्वास्थ्य स्कोर का महत्व",84 "diversity_score": "विविधता स्कोर का महत्व",85 "protein_ratio": "प्रोटीन अनुपात का महत्व",86 "generate": "✨ योजना बनाएं",87 "how_it_works": "यह कैसे काम करता है:",88 "step1": "साइडबार में अपनी व्यक्तिगत जानकारी भरें",89 "step2": "अपने लक्ष्य और प्राथमिकताएं निर्धारित करें",90 "step3": "अनुकूलित सिफारिशें प्राप्त करने के लिए 'योजना बनाएं' पर क्लिक करें",91 "health_metrics": "📊 आपके स्वास्थ्य मेट्रिक्स",92 "bmi": "बीएमआई",93 "underweight": "कम वजन: कैलोरी बढ़ाने पर विचार करें",94 "normal": "सामान्य वजन: अच्छा काम!",95 "overweight": "अधिक वजन: कैलोरी कम करने पर विचार करें",96 "obese": "मोटापा: कैलोरी में महत्वपूर्ण कमी की सिफारिश की गई",97 "recommended_calories": "अनुशंसित कैलोरी",98 "your_intake": "आपका कैलोरी सेवन",99 "lower": "आपका सेवन अनुशंसित से कम है",100 "higher": "आपका सेवन अनुशंसित से अधिक है",101 "aligns": "आपका सेवन सिफारिशों के अनुरूप है",102 "meal_plan": "🍽️ आपकी व्यक्तिगत भोजन योजना",103 "daily_meals": "आपके दैनिक भोजन",104 "nutrient_intake": "📊 दैनिक पोषक तत्व सेवन विवरण",105 "macronutrient": "🥗 मैक्रोन्यूट्रिएंट वितरण",106 "food_recommendation": "🔍 भोजन सिफारिश स्थान",107 "exercise_plan": "🏋️ आपकी व्यक्तिगत व्यायाम योजना",108 "full_body": "पूर्ण-शरीर वर्कआउट योजना",109 "exercise_tips": "व्यायाम सुझाव",110 "weight_loss_tips": "- कार्डियो व्यायाम पर ध्यान दें (30-60 मिनट प्रति सत्र)\n- सप्ताह में 2-3 बार HIIT वर्कआउट शामिल करें\n- मांसपेशियों को बनाए रखने के लिए स्ट्रेंथ ट्रेनिंग",111 "muscle_gain_tips": "- स्ट्रेंथ ट्रेनिंग को प्राथमिकता दें (सप्ताह में 3-5 बार)\n- प्रोग्रेसिव ओवरलोड पर ध्यान दें\n- वर्कआउट्स के बीच पर्याप्त आराम दें",112 "maintenance_tips": "- कार्डियो और स्ट्रेंथ ट्रेनिंग के बीच संतुलन बनाएं\n- ऊब से बचने के लिए विभिन्न गतिविधियों को आजमाएं\n- अपने शरीर की सुनें और आवश्यकतानुसार समायोजित करें",113 "download_meal": "📥 भोजन योजना डाउनलोड करें",114 "fill_details": "👈 शुरू करने के लिए साइडबार में अपना विवरण भरें और 'योजना बनाएं' पर क्लिक करें"115 },116 "marathi": {117 "title": "🍽️ वैयक्तिक आहार आणि व्यायाम योजना",118 "instructions": "तुमची वैयक्तिक आहार आणि व्यायाम योजना मिळविण्यासाठी तुमचे तपशील भरा.",119 "personal_info": "👤 वैयक्तिक माहिती",120 "age": "तुमचे वय प्रविष्ट करा",121 "gender": "लिंग",122 "weight": "तुमचे वजन प्रविष्ट करा (किलो)",123 "height": "तुमची उंची प्रविष्ट करा (सेमी)",124 "activity": "क्रियाकलाप स्तर",125 "goals": "🎯 उद्दिष्टे आणि प्राधान्ये",126 "goal_select": "तुमचे उद्दिष्ट निवडा",127 "food_pref": "अन्न प्राधान्य",128 "region_pref": "पसंतीचे प्रदेश",129 "allergies": "ॲलर्जी/आहार निर्बंध",130 "calorie_intake": "🔥 कॅलरी सेवन (पर्यायी)",131 "use_calculated": "गणना केलेल्या शिफारस केलेल्या कॅलरी वापरा",132 "enter_calories": "दैनंदिन कॅलरी सेवन प्रविष्ट करा (किलोकॅलरी)",133 "nutrient_weight": "⚖️ पोषक घटक वजन",134 "nutrient_score": "पोषक घटक स्कोरचे महत्त्व",135 "health_score": "आरोग्य स्कोरचे महत्त्व",136 "diversity_score": "विविधता स्कोरचे महत्त्व",137 "protein_ratio": "प्रथिने गुणोत्तराचे महत्त्व",138 "generate": "✨ योजना तयार करा",139 "how_it_works": "हे कसे कार्य करते:",140 "step1": "साइडबारमध्ये तुमचे वैयक्तिक तपशील भरा",141 "step2": "तुमची उद्दिष्टे आणि प्राधान्ये सेट करा",142 "step3": "सानुकूलित शिफारसी मिळविण्यासाठी 'योजना तयार करा' वर क्लिक करा",143 "health_metrics": "📊 तुमचे आरोग्य मेट्रिक्स",144 "bmi": "BMI",145 "underweight": "कमी वजन: कॅलरी वाढविण्याचा विचार करा",146 "normal": "सामान्य वजन: चांगले काम!",147 "overweight": "अधिक वजन: कॅलरी कमी करण्याचा विचार करा",148 "obese": "स्थूलता: कॅलरीमध्ये लक्षणीय घट करण्याची शिफारस",149 "recommended_calories": "शिफारस केलेल्या कॅलरी",150 "your_intake": "तुमचे कॅलरी सेवन",151 "lower": "तुमचे सेवन शिफारस केलेल्यापेक्षा कमी आहे",152 "higher": "तुमचे सेवन शिफारस केलेल्यापेक्षा जास्त आहे",153 "aligns": "तुमचे सेवन शिफारसींशी जुळते आहे",154 "meal_plan": "🍽️ तुमची वैयक्तिक आहार योजना",155 "daily_meals": "तुमचे दैनंदिन जेवण",156 "nutrient_intake": "📊 दैनंदिन पोषक घटक सेवन तपशील",157 "macronutrient": "🥗 मॅक्रोन्यूट्रिएंट वितरण",158 "food_recommendation": "🔍 अन्न शिफारस जागा",159 "exercise_plan": "🏋️ तुमची वैयक्तिक व्यायाम योजना",160 "full_body": "संपूर्ण-शरीर व्यायाम योजना",161 "exercise_tips": "व्यायाम टिपा",162 "weight_loss_tips": "- कार्डिओ व्यायामांवर लक्ष केंद्रित करा (30-60 मिनिटे प्रति सत्र)\n- आठवड्यातून 2-3 वेळा HIIT व्यायाम समाविष्ट करा\n- स्नायू टिकवून ठेवण्यासाठी स्ट्रेंथ ट्रेनिंग",163 "muscle_gain_tips": "- स्ट्रेंथ ट्रेनिंगला प्राधान्य द्या (आठवड्यातून 3-5 वेळा)\n- प्रगतीशील ओव्हरलोडवर लक्ष केंद्रित करा\n- व्यायामांदरम्यान पुरेसा विश्रांती घ्या",164 "maintenance_tips": "- कार्डिओ आणि स्ट्रेंथ ट्रेनिंगमध्ये संतुलन राखा\n- कंटाळा टाळण्यासाठी विविध क्रियाकलाप करा\n- तुमच्या शरीराचे ऐका आणि आवश्यकतेनुसार समायोजित करा",165 "download_meal": "📥 आहार योजना डाउनलोड करा",166 "fill_details": "👈 सुरू करण्यासाठी साइडबारमध्ये तुमचे तपशील भरा आणि 'योजना तयार करा' वर क्लिक करा"167 }168}169 170# Custom CSS for better UI171st.markdown(172 """173 <style>174 .sidebar .sidebar-content {175 background-color: #f8f9fa;176 }177 h1, h2, h3 {178 color: #2c3e50;179 }180 .stButton button {181 background-color: #4CAF50;182 color: white;183 border-radius: 5px;184 padding: 10px 20px;185 font-size: 16px;186 }187 .stButton button:hover {188 background-color: #45a049;189 }190 .stSlider {191 color: #4CAF50;192 }193 .stPlot {194 margin: 0;195 padding: 0;196 }197 .info-box {198 background-color: #2c3e50;199 color: white;200 border-radius: 10px;201 padding: 15px;202 margin-bottom: 20px;203 border-left: 5px solid #4CAF50;204 box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);205 }206 .info-box h4 {207 color: #4CAF50;208 margin-top: 0;209 }210 .info-box ol {211 padding-left: 20px;212 }213 .info-box li {214 margin-bottom: 8px;215 }216 .snack-container {217 background-color:#f0f8ff; 218 padding:10px; 219 border-radius:10px; 220 border-left: 5px solid #4CAF50; 221 margin-bottom:20px;222 }223 .snack-container h4 {224 color:#2c3e50;225 }226 </style>227 """,228 unsafe_allow_html=True229)230 231# Language selection232language = st.sidebar.selectbox("🌐 Language", ["English", "Hindi", "Marathi"], index=0).lower()233t = translations[language]234 235# Sidebar for User Inputs236st.sidebar.title(t["title"])237st.sidebar.write(t["instructions"])238 239# User Inputs240st.sidebar.header(t["personal_info"])241age = st.sidebar.number_input(t["age"], min_value=10, max_value=100, step=1)242gender = st.sidebar.radio(t["gender"], ["Male", "Female"])243weight_kg = st.sidebar.number_input(t["weight"], min_value=30, max_value=200, step=1)244height_cm = st.sidebar.number_input(t["height"], min_value=100, max_value=250, step=1)245activity_level = st.sidebar.selectbox(t["activity"], ["Sedentary", "Lightly Active", "Moderately Active", "Very Active", "Extra Active"])246 247st.sidebar.header(t["goals"])248goal = st.sidebar.selectbox(t["goal_select"], ["Weight Loss", "Maintenance", "Muscle Gain"])249food_pref = st.sidebar.radio(t["food_pref"], ["Any", "Vegetarian", "Non-Vegetarian"])250region_pref = st.sidebar.multiselect(t["region_pref"], options=load_data()["region"].unique(), default=load_data()["region"].unique())251allergies = st.sidebar.multiselect(t["allergies"], options=load_data()["allergies"].dropna().unique())252 253st.sidebar.header(t["calorie_intake"])254use_calculated = st.sidebar.checkbox(t["use_calculated"], value=True)255if not use_calculated:256 daily_calories = st.sidebar.number_input(t["enter_calories"], min_value=800, max_value=4000, step=50, value=2000)257else:258 daily_calories = None259 260st.sidebar.header(t["nutrient_weight"])261pref_nutrient = st.sidebar.slider(t["nutrient_score"], 0, 100, 40)262pref_health = st.sidebar.slider(t["health_score"], 0, 100, 30)263pref_diversity = st.sidebar.slider(t["diversity_score"], 0, 100, 20)264pref_protein = st.sidebar.slider(t["protein_ratio"], 0, 100, 10)265 266# Main Content Area267st.title(t["title"])268st.markdown(f"""269<div class="info-box">270 <h4>{t["how_it_works"]}</h4>271 <ol>272 <li>{t["step1"]}</li>273 <li>{t["step2"]}</li>274 <li>{t["step3"]}</li>275 </ol>276</div>277""", unsafe_allow_html=True)278 279# Generate Plans Button280if st.sidebar.button(t["generate"]):281 with st.spinner("Generating your personalized meal and exercise plan..."):282 # Calculate BMI and Recommended Calories283 bmi = calculate_bmi(weight_kg, height_cm)284 bmr = calculate_bmr(age, gender, weight_kg, height_cm)285 recommended_calories = calculate_daily_calories(bmr, activity_level, goal)286 287 # Use calculated calories if not manually specified288 if use_calculated:289 daily_calories = recommended_calories290 291 # Create Tabs for Diet and Exercise292 tab1, tab2 = st.tabs(["🍽️ " + t["meal_plan"], "🏋️ " + t["exercise_plan"]])293 294 # Diet Plan Tab295 with tab1:296 st.header(t["health_metrics"])297 col1, col2 = st.columns(2)298 299 with col1:300 st.metric("BMI", f"{bmi:.1f}")301 if bmi < 18.5:302 st.warning(t["underweight"])303 elif 18.5 <= bmi < 24.9:304 st.success(t["normal"])305 elif 25 <= bmi < 29.9:306 st.warning(t["overweight"])307 else:308 st.error(t["obese"])309 310 with col2:311 st.metric(t["recommended_calories"], f"{recommended_calories:.0f} kcal")312 if not use_calculated:313 st.metric(t["your_intake"], f"{daily_calories} kcal")314 if daily_calories < recommended_calories * 0.95:315 st.warning(t["lower"])316 elif daily_calories > recommended_calories * 1.05:317 st.warning(t["higher"])318 else:319 st.success(t["aligns"])320 321 st.header(t["meal_plan"])322 data = load_data()323 324 # Show diet recommendations325 meal_plans, total_nutrients = recommend_diet(326 daily_calories=daily_calories,327 pref_nutrient=pref_nutrient,328 pref_health=pref_health,329 pref_diversity=pref_diversity,330 pref_protein=pref_protein,331 region_pref=region_pref,332 food_pref=food_pref,333 allergies=allergies,334 data=data335 )336 337 # Create a DataFrame for the meal plan338 meal_plan_df = pd.DataFrame()339 for meal, plan in meal_plans.items():340 meal_df = pd.DataFrame(plan, columns=["Food Item", "Serving Size (g)", "Calories", "Protein (g)", "Carbs (g)", "Fats (g)"])341 meal_df["Meal"] = meal.capitalize()342 meal_plan_df = pd.concat([meal_plan_df, meal_df])343 344 # Add download button for meal plan345 csv = meal_plan_df.to_csv(index=False).encode('utf-8')346 st.download_button(347 label=t["download_meal"],348 data=csv,349 file_name='personalized_meal_plan.csv',350 mime='text/csv',351 )352 353 # Display all meals with special styling for snacks354 st.subheader(t["daily_meals"])355 for meal, plan in meal_plans.items():356 if meal == "snack":357 with st.container():358 st.markdown(359 f"""360 <div class="snack-container">361 <h4>🍎 {meal.capitalize()}</h4>362 {pd.DataFrame(plan, columns=["Food Item", "Serving Size (g)", "Calories", "Protein (g)", "Carbs (g)", "Fats (g)"]).to_html(index=False)}363 </div>364 """,365 unsafe_allow_html=True366 )367 else:368 with st.container():369 st.subheader(f"🍽️ {meal.capitalize()}")370 st.table(pd.DataFrame(plan, columns=["Food Item", "Serving Size (g)", "Calories", "Protein (g)", "Carbs (g)", "Fats (g)"]))371 372 # Daily Nutrient Intake Table373 st.header(t["nutrient_intake"])374 375 # Create a more detailed nutrient table376 nutrient_data = {377 "Nutrient": ["Calories", "Protein", "Carbohydrates", "Fats"],378 "Total Intake": [379 total_nutrients["Calories"],380 total_nutrients["Protein"],381 total_nutrients["Carbs"],382 total_nutrients["Fats"]383 ],384 "Recommended": [385 daily_calories,386 daily_calories * 0.3 / 4, # 30% of calories from protein (4 cal/g)387 daily_calories * 0.5 / 4, # 50% of calories from carbs (4 cal/g)388 daily_calories * 0.2 / 9 # 20% of calories from fats (9 cal/g)389 ],390 "Percentage": [391 f"{total_nutrients['Calories']/daily_calories*100:.1f}%",392 f"{total_nutrients['Protein']/(daily_calories*0.3/4)*100:.1f}%",393 f"{total_nutrients['Carbs']/(daily_calories*0.5/4)*100:.1f}%",394 f"{total_nutrients['Fats']/(daily_calories*0.2/9)*100:.1f}%"395 ]396 }397 398 # Display the nutrient table with conditional formatting399 df_nutrients = pd.DataFrame(nutrient_data)400 st.dataframe(401 df_nutrients.style.format({402 "Total Intake": "{:.1f}",403 "Recommended": "{:.1f}"404 }).applymap(lambda x: "color: green" if float(x[:-1]) > 90 else "color: orange" if x.endswith("%") and float(x[:-1]) < 70 else "", 405 subset=["Percentage"]),406 use_container_width=True407 )408 409 # Macronutrient Pie Chart410 st.header(t["macronutrient"])411 fig = px.pie(412 names=["Protein", "Carbs", "Fats"],413 values=[total_nutrients["Protein"]*4, total_nutrients["Carbs"]*4, total_nutrients["Fats"]*9],414 title="Calorie Contribution by Macronutrient",415 color=["Protein", "Carbs", "Fats"],416 color_discrete_map={"Protein": "#4CAF50", "Carbs": "#FFC107", "Fats": "#FF5722"}417 )418 fig.update_traces(textposition="inside", textinfo="percent+label")419 st.plotly_chart(fig, use_container_width=True, key="macronutrient_pie_chart")420 421 # Show visualization422 st.header(t["food_recommendation"])423 st.write("Visualizing how your preferences align with different food options:")424 show_3d_visualization(425 df=data,426 pref_nutrient=pref_nutrient,427 pref_health=pref_health,428 pref_diversity=pref_diversity,429 pref_protein=pref_protein,430 goal=goal431 )432 433 # Exercise Plan Tab434# In your Streamlit app, replace the exercise plan tab content with:435 436# Exercise Plan Tab437 with tab2:438 st.header("🏋️ Your Personalized Weekly Exercise Plan")439 440 # Initialize ExerciseRecommender441 recommender = ExerciseRecommender()442 443 # Show weekly plan overview444 st.subheader("📅 Weekly Workout Schedule")445 weekly_plan = recommender.get_weekly_plan()446 447 cols = st.columns(7)448 for i, (day, muscles) in enumerate(weekly_plan.items()):449 with cols[i]:450 st.markdown(f"**{day}**")451 if "Rest" in muscles[0]:452 st.write("🛌 Rest")453 st.write("or")454 st.write("🏃 Cardio")455 else:456 for muscle in muscles:457 st.write(f"💪 {muscle}")458 459 # Show detailed workouts for all days460 st.subheader("💡 Daily Workout Details")461 for day in weekly_plan:462 with st.expander(f"{day} Workout", expanded=True):463 day_workout = recommender.get_day_workout(day)464 465 if "Rest" in day_workout:466 st.markdown("### Rest Day Recommendations")467 st.write("""468 - Active recovery (light walking, stretching)469 - Focus on mobility work470 - Hydrate well471 - Optionally do light cardio (30 mins max)472 """)473 else:474 for muscle_group, exercises in day_workout.items():475 st.markdown(f"### {muscle_group} Exercises")476 st.table(exercises)477 st.markdown(f"**Expert Tip:** {recommender.get_expert_tips(muscle_group)}")478 479 # Add workout notes section480 st.text_area("Add your personal notes for this workout", 481 key=f"notes_{day}",482 height=100)483 484 # Add general exercise tips based on goal485 st.subheader("🎯 Goal-Specific Training Tips")486 if goal == "Weight Loss":487 st.write(t["weight_loss_tips"])488 elif goal == "Muscle Gain":489 st.write(t["muscle_gain_tips"])490 else: # Maintenance491 st.write(t["maintenance_tips"])492 493 # Add download option for workout plan494 st.download_button(495 label="📥 Download Weekly Workout Plan",496 data=pd.DataFrame.from_dict(weekly_plan, orient='index').to_csv(),497 file_name='weekly_workout_plan.csv',498 mime='text/csv'499 )500# Show instructions if not generated yet501else:502 st.info(t["fill_details"])503 st.image("https://images.unsplash.com/photo-1498837167922-ddd27525d352", caption="Healthy eating and exercise lead to better health")