Overview
FitGenius AI is a Streamlit-based web app powered by the Meta-Llama-3.3-70B-Instruct model via SambaNova Cloud. It provides:
- Personalized fitness insights
- Detailed fitness reports
- Customized exercise and meal plans
All based on user inputs such as personal details, fitness goals, and diet preferences.
Features
- Personalized Fitness Analysis:
Calculates BMI, BMR, and TDEE for accurate fitness assessment. - AI-Generated Reports:
Produces structured fitness, diet, and exercise plans based on goals and preferences. - Multiple Plan Options:
Users can independently generate:Fitness Reports
Exercise Plans
Meal Plans
- Custom Instructions:
Add personal notes to adjust AI responses. - Downloadable Reports:
Export plans as .txt files for offline viewing or sharing. - User-Friendly Interface:
Styled with dark mode, live progress feedback, and robust error handling. - Input Flexibility:
Fully customizable using the following fields:
Input Field | Supported Values |
---|---|
Age | Numeric (years) |
Gender | Male, Female, Other |
Height | cm |
Weight | kg |
Activity Level | Sedentary, Lightly Active, Moderately Active, Very Active, Extra Active |
Fitness Goal | Lose Weight, Maintain Weight, Gain Muscle, Improve Endurance |
Diet Preference | No Preference, Vegetarian, Vegan, Keto, Paleo, Mediterranean, Low Carb, High Protein |
Medical History / Health Conditions | Users can input allergies, operations, or chronic illnesses to tailor fitness plans. |
Usage Guide
- Enter Personal Information
Fill in your age, gender, height, weight, and preferences using the sidebar. - Choose a Plan Type
Use the dropdown to select one of:
- Fitness Report
- Exercise Plan
- Meal Plan
- Generate Your Plan
Click the “Generate” button. - View and Interact
Your plan will be shown with AI-generated suggestions. - Ask Follow-ups
You can input questions or clarification prompts for more detail.
Troubleshooting
Issue | Recommendation |
---|---|
Invalid Input | Ensure all entries are within reasonable, real ranges. |
AI Timeout or No Response | Retry; consider shortening inputs or checking API key. |
API Errors | Confirm internet access and valid API credentials. |
UI Glitch / Display Issue | Refresh your browser page. |
User Experience Preview: Sample User Inputs and Results
Meal plan Generated
Introduction to Personalized Diet Plan
Based on your provided information, this diet plan is tailored to help you achieve your weight loss goal while considering your vegetarian diet preference, lactose intolerance, and peanut allergy.
Calorie Intake Recommendations
To lose weight, a calorie deficit is necessary. Given your TDEE of 2006.0 calories, a daily calorie intake of 1700-1800 calories is recommended to create a deficit that promotes weight loss without sacrificing nutrition.
Macronutrient Breakdown
The recommended macronutrient breakdown for weight loss, considering your sedentary activity level and vegetarian diet, is as follows:
Protein: 1.6-2.2 grams per kg body weight. For you, this would be approximately 112-154 grams of protein per day.
Fat: 0.5-1 gram per kg body weight. For you, this would be approximately 35-70 grams of fat per day.
Carbohydrates: 2-3 grams per kg body weight. For you, this would be approximately 140-210 grams of carbohydrates per day.
Meal Frequency and Suggestions
Meal Frequency: 5 meals per day (3 main meals and 2 snacks) to keep your metabolism active and prevent excessive hunger.
Breakfast:
Oatmeal with fruits and nuts (excluding peanuts)
Whole grain toast with avocado and scrambled eggs or tofu
Lunch:
Whole grain wraps with vegetarian fillings (hummus, cucumber, tomato, lettuce)
Quinoa or brown rice bowls with roasted vegetables and a source of protein (beans, lentils, tofu)
Dinner:
Grilled tofu or tempeh with roasted vegetables and quinoa or brown rice
Vegetable stir-fries with tofu, served with brown rice or whole grain noodles
Snacks:
Fresh fruits
Carrot sticks with hummus
Lactose-free yogurt with honey and nuts (excluding peanuts)
Hydration Recommendations
Drink at least 8-10 glasses of water per day.
Limit sugary drinks and caffeine.
Tips on Meal Preparation and Portion Control
Meal Preparation: Plan your meals for the week, and prep ingredients in advance to save time and ensure you stick to your diet plan.
Portion Control: Use a food scale or measuring cups to measure your food portions. Eat slowly and stop when you feel satisfied, rather than stuffed.
Recommendations for Supplements
Protein Powder: A plant-based protein powder (pea, hemp, or brown rice protein) can be helpful for meeting your daily protein needs, especially post-workout.
Multivitamin: A daily multivitamin can help fill any nutritional gaps in your diet.
Omega-3 Fatty Acids: Consider an algae oil supplement for omega-3 fatty acids, which are important for heart health and can be lacking in a vegetarian diet.
How AI Analyzes User Preferences, Restrictions, and Goals
AI analyzes your:
Age, Gender, Height, Weight, and Activity Level to calculate your BMR and TDEE.
Diet Preference (vegetarian) to suggest appropriate protein sources and meal ideas.
Medical History/Health Conditions (lactose intolerance, peanut allergy) to avoid harmful foods and suggest alternatives.
Goal (weight loss) to determine the calorie deficit needed and the macronutrient breakdown that will support weight loss while maintaining nutrition.
By following this personalized diet plan and incorporating regular physical activity, you can work towards achieving your weight loss goal in a healthy and sustainable manner. Remember, consistency and patience are key. Regularly track your progress and adjust your diet plan as needed to ensure you're on the right path to reaching your goals.
Fitness Analysis Report Generated
Fitness Analysis Report
Introduction
Based on the provided data, this report will analyze your current fitness status and provide personalized recommendations to help you achieve your weight loss goal. Our analysis takes into account your age, gender, height, weight, activity level, dietary preferences, and health conditions to create a tailored plan.
Current Status
Age: 30
Gender: Male
Height: 170 cm
Weight: 70 kg
Activity Level: Sedentary (little or no exercise)
Goal: Lose Weight
BMI: 24.22, which falls into the "Normal weight" category. A BMI between 18.5 and 24.9 is considered normal. However, since your goal is to lose weight, we will focus on achieving a healthier body composition.
BMR (Basal Metabolic Rate): 1671.67 calories. BMR is the number of calories your body needs to perform basic life-sustaining functions like breathing, circulation, cell production, nutrient processing, and temperature regulation.
TDEE (Total Daily Energy Expenditure): 2006.0 calories. TDEE is an estimate of how many calories you burn per day, taking into account your BMR and activity level. Given your sedentary lifestyle, your TDEE is relatively low.
Diet Plan
To achieve weight loss, we recommend a calorie deficit diet. Aim for a daily calorie intake of 1500-1700 calories, which is below your TDEE to promote weight loss while still providing enough energy for basic functions and some physical activity.
Macronutrient Breakdown:
Protein: 1.6 grams/kg body weight (about 112 grams for you) to support muscle health.
Fat: 0.5-1 gram/kg body weight (about 35-70 grams for you) for energy and nutrient absorption.
Carbohydrates: 2-3 grams/kg body weight (about 140-210 grams for you) for energy.
Meal Frequency: 4-5 main meals and 2-3 snacks in between, spaced out to keep your metabolism active and prevent excessive hunger.
Hydration: Aim for at least 2 liters of water per day, adjusting according to your activity level and climate.
Detailed Meal Plan Suggestions
Breakfast: Oatmeal with fruits and nuts (avoid peanuts due to allergy), or tofu scramble with whole-grain toast.
Lunch: Whole-grain wraps with vegetarian fillings like hummus, avocado, and vegetables, or lentil soup with a side of whole-grain bread.
Dinner: Grilled tofu or tempeh with roasted vegetables and quinoa or brown rice.
Snacks: Fresh fruits, carrot sticks with hummus, or energy made from oats and nuts (peanut-free).
Tips:
Prepare meals in advance to avoid last-minute unhealthy choices.
Control portions by using smaller plates and measuring utensils.
Avoid lactose-containing products due to lactose intolerance; opt for lactose-free or plant-based alternatives instead.
Supplements: Consider a daily multivitamin to ensure you're getting all necessary nutrients, especially if you're struggling to get them from your diet alone. Always consult with a healthcare professional before starting any supplements.
Exercise Routine
Given your sedentary lifestyle, we recommend starting with low-intensity exercises and gradually increasing the intensity and duration.
Exercise Duration and Frequency: Begin with 20-30 minutes of moderate-intensity exercise, 3 times a week, and aim to increase to 30-40 minutes, 5 times a week.
Types of Exercises:
Aerobic: Brisk walking, cycling, or swimming for cardiovascular health.
Strength Training: Bodyweight exercises like push-ups, squats, and lunges, or resistance band exercises to build muscle.
Examples of Exercises:
Squats: 3 sets of 10 reps
Push-ups: 3 sets of as many reps as possible
Brisk walking: 30 minutes, aiming for 5,000-7,000 steps
Progress Tracking and Improvement Suggestions
Weight Tracking: Weigh yourself once a week, on the same day and time, to monitor progress.
Food and Activity Logging: Keep a diary or use an app to track your daily food intake and physical activity to identify patterns and areas for improvement.
Adjusting Diet and Exercise: Based on your progress, you may need to adjust your calorie intake or exercise intensity. Consult with a healthcare professional or a fitness expert for personalized advice.
Tips for Increasing Activity:
Start small, like taking the stairs instead of the elevator.
Incorporate more movement into your daily routine, such as walking to work or doing household chores.
Healthy Weight Loss Rate: Aim for a weight loss of 0.5-1 kg per week for a sustainable and healthy weight loss journey.
Consult Healthcare Professionals: Always consult with a healthcare professional before starting any new diet or exercise program, especially with pre-existing health conditions like lactose intolerance and peanut allergy.
Remember, losing weight too quickly is not healthy. Focus on making sustainable lifestyle changes that you can maintain in the long term. Stay consistent, and with time, you will achieve your weight loss goal and improve your overall health and fitness.
Exercise Plan Generated
Introduction to Exercise Plan
As a sedentary individual with a goal to lose weight, it's essential to start with a manageable and progressive exercise plan. Considering your lactose intolerance and peanut allergy, we'll focus on exercises that don't require special dietary supplements and can be adapted to your vegetarian diet preference.
Exercise Duration and Frequency
Given your sedentary activity level, we'll begin with:
Duration: 20-30 minutes per session, 3 times a week
Frequency: Gradually increase to 4-5 times a week as your fitness level improves
Types of Exercises
To achieve weight loss and overall fitness, we'll incorporate a mix of:
Cardio: Improves heart health and burns calories
Strength Training: Builds muscle mass, which helps in burning more calories at rest
HIIT (High-Intensity Interval Training): Efficient for calorie burn and improving cardiovascular health
Yoga: Enhances flexibility, balance, and mental well-being
Examples of Exercises
Cardio (20-30 minutes, 2 times a week)
Brisk Walking: 30 minutes, aim for 5,000-7,000 steps
Jogging/Running: Start with intervals of 2 minutes jogging + 3 minutes walking
Cycling: Stationary bike or outdoor cycling, 20-30 minutes
Strength Training (2 times a week)
Squats: 3 sets of 8-12 reps, rest for 60-90 seconds between sets
Push-ups: 3 sets of 8-12 reps, rest for 60-90 seconds between sets
Lunges: 3 sets of 8-12 reps (per leg), rest for 60-90 seconds between sets
Planks: 3 sets, hold for 30-60 seconds, rest for 60-90 seconds between sets
HIIT (1 time a week)
Burpees: 3 sets of 12 reps, rest for 90 seconds between sets
Jumping Jacks: 3 sets of 30 seconds, rest for 60 seconds between sets
Mountain Climbers: 3 sets of 30 seconds, rest for 60 seconds between sets
Yoga (1-2 times a week)
Downward-Facing Dog: 3 sets, hold for 30 seconds
Warrior Pose: 3 sets, hold for 30 seconds per leg
Tree Pose: 3 sets, hold for 30 seconds per leg
Child’s Pose: 3 sets, hold for 30 seconds
Full-Day Routine Example
Given your sedentary activity level, let's start with a simple full-day routine that can be adjusted as you progress:
Monday (Cardio Day): Brisk walking or jogging for 20-30 minutes
Tuesday (Strength Training Day): Squats, push-ups, lunges, planks
Wednesday (Rest Day)
Thursday (Yoga Day): Focus on basic yoga poses for flexibility and balance
Friday (HIIT Day): Burpees, jumping jacks, mountain climbers
Saturday and Sunday (Rest or Active Recovery Days): Light activities like walking or gentle stretching
Split-Week Routine
As you become more comfortable, we can transition to a split-week routine focusing on different muscle groups each day:
Monday (Chest and Triceps): Push-ups, tricep dips (using a chair or bench), planks
Tuesday (Back and Biceps): Bodyweight rows (using a resistance band), bicep curls (using light dumbbells or water bottles), lunges
Wednesday (Rest Day)
Thursday (Legs): Squats, calf raises, leg raises (hanging leg raises or using a bench)
Friday (Shoulders and Abs): Shoulder press (using light dumbbells), lateral raises, Russian twists
Saturday (Cardio Day): Choose any cardio activity for 30 minutes
Sunday (Yoga or Rest Day): Focus on recovery and flexibility
Progress Tracking and Improvement Suggestions
Keep a Fitness Journal: Record your workouts, including the exercises, sets, reps, and how you feel.
Monitor Your Weight and Measurements: Regularly track your weight, body fat percentage, and measurements to see progress.
Adjust Your Diet: Ensure you're in a calorie deficit for weight loss, focusing on vegetarian, lactose-free, and peanut-free options.
Increase Intensity and Duration: As you get more comfortable, increase the intensity of your workouts and the duration of your sessions.
Remember, consistency and patience are key. It's also crucial to listen to your body and rest when needed. Stay hydrated, and consider consulting with a healthcare professional or a dietitian for personalized advice.
Configuration (Required Before Use)
Important: Before using the app, you must update your API key and (optionally) the model name.
Setting | Location | Details |
---|---|---|
API Key | get_client() in streamlit_app.py | Replace the hardcoded SambaNova key with your own key. |
Model Name | call_ai() in streamlit_app.py | Update the model parameter to use a different AI model if desired. |
How to run
Run the app using a simple command:
streamlit run streamlit_app.py
Code Reference
- Main File: streamlit_app.py
import streamlit as st
import time
import base64
import pandas as pd
from datetime import datetime
from openai import OpenAI
import re
# App configuration
st.set_page_config(
page_title="AI-Powered Fitness Analyzer",
page_icon=None,
layout="wide",
initial_sidebar_state="expanded",
menu_items={
'Get Help': 'https://www.streamlit.io/community',
'Report a bug': "https://github.com/streamlit/streamlit/issues",
'About': "# AI-Powered Fitness Analyzer\nAnalyze your fitness data and get personalized recommendations."
}
)
# Custom CSS for styling
st.markdown("""
<style>
.stApp {
max-width: 100%;
}
.main-header {
font-size: 2.3rem;
color: #FFFFFF;
margin-bottom: 0.8rem;
font-weight: 700;
}
.sub-header {
font-size: 1.4rem;
color: #CCCCCC;
margin-top: 0.8rem;
margin-bottom: 0.5rem;
font-weight: 500;
}
.info-text {
font-size: 1rem;
color: #424242;
line-height: 1.5;
}
.highlight {
background-color: #E8F5E9;
padding: 1rem;
border-radius: 0.5rem;
border-left: 0.5rem solid #2E7D32;
margin: 1rem 0;
overflow-wrap: break-word;
}
.stButton > button {
background-color: #2E7D32;
color: white;
font-weight: 500;
border: none;
padding: 0.5rem 1rem;
border-radius: 0.3rem;
transition: all 0.3s ease;
}
.stButton > button:hover {
background-color: #1B5E20;
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}
.footer {
margin-top: 2rem;
text-align: center;
color: #9E9E9E;
padding: 1rem;
font-size: 0.9rem;
}
</style>
""", unsafe_allow_html=True)
@st.cache_resource(ttl=3600)
def get_client():
SAMBANOVA_API_URL = "https://api.sambanova.ai/v1"
SAMBANOVA_API_KEY = "your-api-key"
return OpenAI(
base_url=SAMBANOVA_API_URL,
api_key=SAMBANOVA_API_KEY,
)
client = get_client()
# System prompt for fitness analysis
SYSTEM_PROMPT = """
You are a professional fitness assistant.
Your job is to analyze user fitness data and provide personalized recommendations including:
- BMI, BMR, TDEE calculations
- Diet plans tailored to fitness goals
- Exercise routines based on fitness level and equipment
- Progress tracking and improvement suggestions
Format the report in clear markdown with sections and bullet points.
"""
def call_ai(prompt, custom_instructions=""):
try:
progress_placeholder = st.empty()
status_text = st.empty()
progress_bar = progress_placeholder.progress(0)
status_text.text("⏳ Initializing request...")
for i in range(1, 11):
progress_bar.progress(i * 0.1)
time.sleep(0.1)
final_prompt = SYSTEM_PROMPT
if custom_instructions:
final_prompt += f"\n\nAdditional instructions: {custom_instructions}"
status_text.text("🔄 Sending request to AI model...")
for i in range(11, 31):
progress_bar.progress(i * 0.01)
time.sleep(0.05)
completion = client.chat.completions.create(
model="Meta-Llama-3.3-70B-Instruct",
messages=[
{"role": "system", "content": final_prompt},
{"role": "user", "content": prompt}
],
stream=False,
timeout=60
)
status_text.text("🧠 Processing response...")
for i in range(31, 71):
progress_bar.progress(i * 0.01)
time.sleep(0.03)
status_text.text("✨ Formatting report...")
for i in range(71, 100):
progress_bar.progress(i * 0.01)
time.sleep(0.02)
progress_bar.progress(100)
status_text.text("✅ Report generated successfully!")
time.sleep(0.5)
progress_placeholder.empty()
status_text.empty()
return completion.choices[0].message.content
except Exception as e:
progress_placeholder.empty()
status_text.empty()
st.error(f"❌ Error: {str(e)}")
return f"❌ Error: {str(e)}"
def calculate_bmi(weight_kg, height_cm):
height_m = height_cm / 100
bmi = weight_kg / (height_m ** 2)
return round(bmi, 2)
def calculate_bmr(weight_kg, height_cm, age, gender):
if gender.lower() == "male":
bmr = 88.362 + (13.397 * weight_kg) + (4.799 * height_cm) - (5.677 * age)
else:
bmr = 447.593 + (9.247 * weight_kg) + (3.098 * height_cm) - (4.330 * age)
return round(bmr, 2)
def calculate_tdee(bmr, activity_level):
activity_multipliers = {
"sedentary": 1.2,
"lightly active": 1.375,
"moderately active": 1.55,
"very active": 1.725,
"extra active": 1.9
}
multiplier = activity_multipliers.get(activity_level.lower(), 1.2)
tdee = bmr * multiplier
return round(tdee, 2)
def main():
st.markdown('<h1 class="main-header">🏋️ FitGenius AI</h1>', unsafe_allow_html=True)
st.markdown('<p class="info-text">Input your personal details to get personalized fitness insights and plans.</p>', unsafe_allow_html=True)
with st.sidebar:
st.markdown("# ⚙️ Settings")
st.markdown("### Personal Details")
age = st.number_input("Age (years)", min_value=1, max_value=120, value=30)
gender = st.selectbox("Gender", options=["Male", "Female", "Other"])
height_cm = st.number_input("Height (cm)", min_value=50, max_value=250, value=170)
weight_kg = st.number_input("Weight (kg)", min_value=20, max_value=300, value=70)
activity_level = st.selectbox("Activity Level", options=[
"Sedentary (little or no exercise)",
"Lightly Active (light exercise 1-3 days/week)",
"Moderately Active (moderate exercise 3-5 days/week)",
"Very Active (hard exercise 6-7 days/week)",
"Extra Active (very hard exercise & physical job)"
])
goal = st.selectbox("Fitness Goal", options=["Lose Weight", "Maintain Weight", "Gain Muscle", "Improve Endurance"])
st.markdown("### Diet Preference")
diet_preference = st.selectbox("Select your diet preference", options=[
"No Preference",
"Vegetarian",
"Vegan",
"Keto",
"Paleo",
"Mediterranean",
"Low Carb",
"High Protein"
])
st.markdown("### Medical History / Health Conditions")
medical_history = st.text_area(
"Please list any allergies, operations, or chronic illnesses (optional)",
placeholder="E.g., Allergic to peanuts, previous knee surgery, asthma",
height=100
)
st.markdown("### Custom Instructions")
custom_instructions = st.text_area(
"Add custom instructions for the AI",
placeholder="E.g., Focus on diet plan, Emphasize strength training, etc.",
height=100
)
bmi = calculate_bmi(weight_kg, height_cm)
bmr = calculate_bmr(weight_kg, height_cm, age, gender)
tdee = calculate_tdee(bmr, activity_level)
st.markdown(f"### Your Calculated Metrics")
st.markdown("""
- **BMI (Body Mass Index):** A measure of body fat based on your height and weight, calculated as weight (kg) divided by height (m) squared, used to categorize underweight, normal, overweight, or obesity.
- **BMR (Basal Metabolic Rate):** The number of calories your body requires to maintain basic physiological functions while at rest, calculated using the Harris-Benedict equation based on age, gender, height, and weight.
- **TDEE (Total Daily Energy Expenditure):** The estimated total calories you burn in a day, including all physical activities and bodily functions, calculated by multiplying BMR by an activity level factor.
""")
st.write(f"- BMI: {bmi}")
st.write(f"- BMR: {bmr} kcal/day")
st.write(f"- TDEE: {tdee} kcal/day")
# Additional helpful insights
st.markdown("### Additional Insights")
if bmi < 18.5:
st.info("Your BMI indicates you are underweight. Consider consulting a healthcare professional for advice.")
elif 18.5 <= bmi < 25:
st.success("Your BMI is within the normal range. Keep up the good work!")
elif 25 <= bmi < 30:
st.warning("Your BMI indicates you are overweight. Consider a balanced diet and regular exercise.")
else:
st.error("Your BMI indicates obesity. It is recommended to seek medical advice.")
if goal == "Lose Weight":
st.info("Focus on a calorie deficit diet and increased physical activity.")
elif goal == "Maintain Weight":
st.info("Maintain your current calorie intake and activity level.")
elif goal == "Gain Muscle":
st.info("Increase protein intake and strength training exercises.")
elif goal == "Improve Endurance":
st.info("Incorporate cardio and aerobic exercises into your routine.")
prompt = f"""
Age: {age}
Gender: {gender}
Height: {height_cm} cm
Weight: {weight_kg} kg
Activity Level: {activity_level}
Goal: {goal}
Diet Preference: {diet_preference}
BMI: {bmi}
BMR: {bmr}
TDEE: {tdee}
"""
option = st.selectbox("Select an option to generate", options=["Fitness Report", "Exercise Plan", "Meal Plan"])
# Append medical history to prompt if provided
if medical_history and medical_history.strip():
prompt += f"\nMedical History / Health Conditions: {medical_history.strip()}"
if option == "Fitness Report":
if st.button("Generate Fitness Report"):
with st.spinner("Generating fitness report..."):
extended_prompt = prompt + """
Please generate a Fitness Analysis Report with the following structure:
# Fitness Analysis Report
## Introduction
Based on the provided data, this report will analyze your current fitness status and provide personalized recommendations to help you achieve your weight loss goal.
## Current Status
Include:
- Age
- Gender
- Height
- Weight
- Activity Level
- Goal
- BMI with classification and explanation
- BMR with explanation
- TDEE with explanation
## Diet Plan
Provide:
- Calorie intake recommendations (e.g., calorie deficit for weight loss)
- Macronutrient breakdown (protein, fat, carbohydrates) with grams per kg body weight
- Meal frequency suggestions
- Hydration recommendations
Include detailed meal plan suggestions:
- What to eat and what to avoid for breakfast, lunch, dinner, and snacks
- Tips on meal preparation and portion control
- Recommendations for hydration and supplements
- Points on how AI analyzes user preferences, restrictions, and goals to tailor the diet plan
## Exercise Routine
Recommend:
- Exercise duration and frequency based on activity level
- Types of exercises (e.g., aerobic, strength training)
- Examples of exercises with sets and reps
## Progress Tracking and Improvement Suggestions
Advise on:
- Weight tracking frequency
- Food and activity logging
- Adjusting diet and exercise based on progress
- Tips for increasing activity and intensity safely
- Cautions about healthy weight loss rates
- Encouragement to consult healthcare professionals
Format the report in clear markdown with sections and bullet points.
"""
report = call_ai(extended_prompt, custom_instructions)
st.markdown('<div class="highlight">', unsafe_allow_html=True)
st.markdown(report, unsafe_allow_html=True)
b64 = base64.b64encode(report.encode('utf-8')).decode()
filename = f"fitness_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
href = f'<a href="data:file/txt;base64,{b64}" download="{filename}" style="display:inline-block;background-color:#4CAF50;color:white;padding:10px 20px;border-radius:5px;text-decoration:none;font-weight:bold;margin:10px 0;">📥 Download Report as TXT</a>'
st.markdown(href, unsafe_allow_html=True)
st.markdown('</div>', unsafe_allow_html=True)
elif option == "Exercise Plan":
if st.button("Generate Exercise Plan"):
with st.spinner("Generating exercise plan..."):
extended_prompt = prompt + """
Please generate a detailed exercise plan including:
- Exercise duration and frequency based on activity level
- Types of exercises (e.g., cardio, strength training, HIIT, yoga)
- Examples of exercises with sets, reps, and rest periods
- Full-day or split-week routines tailored to the user's fitness level and equipment access
Format the plan in clear markdown with sections and bullet points.
"""
report = call_ai(extended_prompt, custom_instructions)
st.markdown('<div class="highlight">', unsafe_allow_html=True)
st.markdown(report, unsafe_allow_html=True)
st.markdown('</div>', unsafe_allow_html=True)
elif option == "Meal Plan":
if st.button("Generate Meal Plan"):
with st.spinner("Generating meal plan..."):
extended_prompt = prompt + """
Please generate a detailed meal plan including:
- Calorie intake recommendations (e.g., calorie deficit for weight loss)
- Macronutrient breakdown (protein, fat, carbohydrates) with grams per kg body weight
- Meal frequency: number of meals and snacks per day
- Specific meal suggestions: what to eat and what to avoid for breakfast, lunch, dinner, and snacks
- Hydration recommendations
- Tips on meal preparation and portion control
- Recommendations for supplements
- Points on how AI analyzes user preferences, restrictions, and goals to tailor the diet plan
Format the plan in clear markdown with sections and bullet points.
"""
report = call_ai(extended_prompt, custom_instructions)
st.markdown('<div class="highlight">', unsafe_allow_html=True)
st.markdown(report, unsafe_allow_html=True)
st.markdown('</div>', unsafe_allow_html=True)
st.markdown('<div class="footer">Last updated: 2025</div>', unsafe_allow_html=True)
if __name__ == "__main__":
main()
Disclaimer
This app is for educational and entertainment purposes only. Please consult with a qualified fitness trainer or dietician before implementing any fitness or diet plans generated by this app.