File size: 7,557 Bytes
7ef4406 2f4845d ead176c 2f4845d 7ef4406 c35a92d 7ef4406 2f4845d 7ef4406 2f4845d 7910ed2 7ef4406 283abe0 7ef4406 283abe0 7ef4406 283abe0 ed01b26 7ef4406 a63e4ff 7ef4406 e1eb457 7910ed2 7ef4406 7910ed2 7ef4406 7910ed2 7ef4406 7910ed2 7ef4406 7910ed2 0b73cd5 c299d0e 0b73cd5 c299d0e 0b73cd5 c299d0e 0b73cd5 c299d0e 5da5a3e c299d0e 5da5a3e c299d0e 2f4845d 5da5a3e 2f4845d c299d0e 7910ed2 e1eb457 c299d0e aa5b4bf c299d0e 252f4df c299d0e 252f4df 2e7fe93 0b73cd5 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 |
import gradio as gr
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from datetime import datetime
from langchain_core.messages import HumanMessage
from tools import tools
from agents import *
from config import *
from workflow import create_workflow
# Initialize workflow
graph = create_workflow()
# Helper Functions
def run_graph(input_message, history, user_details):
try:
# Relevant fitness-related keywords to handle irrelevant user prompts
relevant_keywords = [
"workout", "training", "exercise", "cardio", "strength training", "hiit (high-intensity interval training)",
"flexibility", "yoga", "pilates", "aerobics", "crossfit", "bodybuilding", "endurance", "running",
"cycling", "swimming", "martial arts", "stretching", "warm-up", "cool-down",
"diet plan", "meal plan", "macronutrients", "micronutrients", "vitamins", "minerals", "protein",
"carbohydrates", "fats", "calories", "calorie", "daily", "nutrition", "supplements", "hydration", "weightloss",
"weight gain", "healthy eating", "health", "fitness", "intermittent fasting", "keto diet", "vegan diet", "paleo diet",
"mediterranean diet", "gluten-free", "low-carb", "high-protein", "bmi", "calculate", "body mass index", "calculator",
"mental health", "mindfulness", "meditation", "stress management", "anxiety relief", "depression",
"positive thinking", "motivation", "self-care", "relaxation", "sleep hygiene", "therapy",
"counseling", "cognitive-behavioral therapy (cbt)", "mood tracking", "mental", "emotional well-being",
"healthy lifestyle", "fitness goals", "health routines", "daily habits", "ergonomics",
"posture", "work-life balance", "workplace", "habit tracking", "goal setting", "personal growth",
"injury prevention", "recovery", "rehabilitation", "physical therapy", "sports injuries",
"pain management", "recovery techniques", "foam rolling", "stretching exercises",
"injury management", "injuries", "apps", "health tracking", "wearable technology", "equipment",
"home workouts", "gym routines", "outdoor activities", "sports", "wellness tips", "water", "adult", "adults",
"child", "children", "infant", "sleep", "habit", "habits", "routine", "weight", "fruits", "vegetables", "lose", "lost weight", "weight-loss",
"chicken", "veg", "vegetarian", "non-veg", "non-vegetarian", "plant", "plant-based", "plant based", "fat", "resources",
"help", "cutting", "bulking", "link", "links", "website", "online", "websites", "peace", "mind", "equipments", "equipment",
"watch", "tracker", "watch", "band", "height", "injured", "quick", "remedy", "solution", "solutions", "pain", "male", "female", "kilograms", "kg", "Pounds",
"lbs"
]
greetings = ["hello", "hi", "how are you doing"]
if any(keyword in input_message.lower() for keyword in relevant_keywords):
response = graph.invoke({
"messages": [HumanMessage(content=input_message)],
"user_details": user_details # Pass user-specific data for customization
})
return response['messages'][1].content
elif any(keyword in input_message.lower() for keyword in greetings):
return "Hi there, I am FIT bot, your personal wellbeing coach! Let me know your fitness goals or questions."
else:
return "I'm here to assist with fitness, nutrition, mental health, and related topics. Please ask questions related to these areas."
except Exception as e:
return f"An error occurred while processing your request: {e}"
def calculate_bmi(height, weight, gender):
"""
Calculate BMI and determine the category based on height, weight, and gender.
"""
try:
height_m = height / 100
bmi = weight / (height_m ** 2)
if bmi < 18.5:
status = "underweight"
elif 18.5 <= bmi < 24.9:
status = "normal weight"
elif 25 <= bmi < 29.9:
status = "overweight"
else:
status = "obese"
return bmi, status
except:
return None, "Invalid height or weight provided."
def visualize_bmi(bmi):
"""
Create a visualization for BMI, showing the user's value against standard categories.
"""
categories = ["Underweight", "Normal Weight", "Overweight", "Obese"]
bmi_ranges = [18.5, 24.9, 29.9, 40]
x_pos = np.arange(len(categories))
user_position = min(len(bmi_ranges), sum(bmi > np.array(bmi_ranges)))
plt.figure(figsize=(8, 4))
plt.bar(x_pos, bmi_ranges, color=['blue', 'green', 'orange', 'red'], alpha=0.6, label="BMI Categories")
plt.axhline(y=bmi, color='purple', linestyle='--', linewidth=2, label=f"Your BMI: {bmi:.2f}")
plt.xticks(x_pos, categories)
plt.ylabel("BMI Value")
plt.title("BMI Visualization")
plt.legend()
plt.tight_layout()
plt_path = "bmi_chart.png"
plt.savefig(plt_path)
plt.close()
return plt_path
def calculate_calories(age, weight, height, activity_level, gender):
"""
Estimate daily calorie needs based on user inputs.
"""
try:
if gender.lower() == "male":
bmr = 10 * weight + 6.25 * height - 5 * age + 5
else:
bmr = 10 * weight + 6.25 * height - 5 * age - 161
activity_multipliers = {
"Sedentary": 1.2,
"Lightly active": 1.375,
"Moderately active": 1.55,
"Very active": 1.725,
"Extra active": 1.9,
}
calories = bmr * activity_multipliers.get(activity_level, 1.2)
return calories
except Exception:
return "Invalid inputs for calorie calculation."
# Interface Components
with gr.Blocks() as demo:
gr.Markdown("<strong>FIT.AI - Your Fitness and Wellbeing Coach</strong>")
# User Info
with gr.Row():
user_name = gr.Textbox(placeholder="Enter your name", label="Name")
user_age = gr.Number(label="Age (years)", value=25, precision=0)
user_gender = gr.Dropdown(choices=["Male", "Female"], label="Gender", value="Male")
user_weight = gr.Number(label="Weight (kg)", value=70, precision=1)
user_height = gr.Number(label="Height (cm)", value=170, precision=1)
activity_level = gr.Dropdown(
choices=["Sedentary", "Lightly active", "Moderately active", "Very active", "Extra active"],
label="Activity Level",
value="Moderately active"
)
# Outputs
bmi_output = gr.Label(label="BMI Result")
calorie_output = gr.Label(label="Calorie Needs")
bmi_chart = gr.Image(label="BMI Chart")
# Actions
calculate_button = gr.Button("Calculate")
def calculate_metrics(age, weight, height, gender, activity_level):
bmi, status = calculate_bmi(height, weight, gender)
if bmi:
bmi_path = visualize_bmi(bmi)
calories = calculate_calories(age, weight, height, activity_level, gender)
return f"Your BMI is {bmi:.2f}, considered {status}.", f"Daily calorie needs: {calories:.2f} kcal", bmi_path
else:
return "Invalid inputs.", "", ""
calculate_button.click(
calculate_metrics,
inputs=[user_age, user_weight, user_height, user_gender, activity_level],
outputs=[bmi_output, calorie_output, bmi_chart]
)
demo.launch(share=True) |