Spaces:
Runtime error
Runtime error
File size: 10,236 Bytes
3a9d36b |
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 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 |
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):
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 Exception:
return None, "Invalid height or weight provided."
def visualize_bmi(bmi):
try:
categories = ["Underweight", "Normal Weight", "Overweight", "Obese"]
x_pos = np.arange(len(categories))
colors = ['blue', 'green', 'orange', 'red']
plt.figure(figsize=(8, 4))
plt.bar(categories, [18.5, 24.9, 29.9, 40], color=colors, alpha=0.6)
plt.axhline(y=bmi, color='purple', linestyle='--', linewidth=2, label=f"Your BMI: {bmi:.2f}")
plt.ylabel("BMI Value")
plt.title("BMI Visualization")
plt.legend(loc="upper left")
plt.tight_layout()
plt_path = "bmi_chart.png"
plt.savefig(plt_path)
plt.close()
return plt_path
except Exception as e:
return f"Error creating BMI visualization: {e}"
def calculate_calories(age, weight, height, activity_level, gender):
try:
# Base Metabolic Rate (BMR) calculation
if gender.lower() == "male":
bmr = 10 * weight + 6.25 * height - 5 * age + 5
else:
bmr = 10 * weight + 6.25 * height - 5 * age - 161
# Activity multiplier mapping
activity_multipliers = {
"Sedentary": 1.2,
"Lightly active": 1.375,
"Moderately active": 1.55,
"Very active": 1.725,
"Extra active": 1.9,
}
if activity_level in activity_multipliers:
calories = bmr * activity_multipliers[activity_level]
else:
raise ValueError("Invalid activity level")
return round(calories, 2)
except Exception as e:
return f"Error in calorie calculation: {e}"
# Interface Components
with gr.Blocks() as demo:
gr.Markdown("# FIT.AI - Your Fitness and Wellbeing Coach")
with gr.Tab("Chat with FIT.AI"):
with gr.Row():
with gr.Column():
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"
)
chatbot = gr.Chatbot(label="Chat with FIT.AI", type="messages")
text_input = gr.Textbox(placeholder="Type your question here...", label="Your Question")
submit_button = gr.Button("Submit")
clear_button = gr.Button("Clear Chat")
def submit_message(message, history=[]):
user_details = {
"name": user_name.value,
"age": user_age.value,
"weight": user_weight.value,
"height": user_height.value,
"activity_level": activity_level.value,
"gender": user_gender.value
}
bmi, status = calculate_bmi(user_details["height"], user_details["weight"], user_details["gender"])
if bmi:
bmi_path = visualize_bmi(bmi)
calories = calculate_calories(user_details["age"], user_details["weight"], user_details["height"], user_details["activity_level"], user_details["gender"])
response = run_graph(message, history, user_details)
history.append({"role": "user", "content": message})
history.append({"role": "assistant", "content": response + f"\nYour BMI is {bmi:.2f}, considered {status}.\nDaily calorie needs: {calories} kcal.", "image": bmi_path})
return history, ""
else:
history.append({"role": "assistant", "content": "Error in calculation."})
return history, ""
submit_button.click(submit_message, inputs=[text_input, chatbot], outputs=[chatbot, text_input])
clear_button.click(lambda: ([], ""), inputs=None, outputs=[chatbot, text_input])
with gr.Tab("BMI and Calorie Calculator"):
with gr.Row():
with gr.Column():
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"
)
calculate_button = gr.Button("Calculate")
with gr.Column():
bmi_output = gr.Label(label="BMI Result")
calorie_output = gr.Label(label="Calorie Needs")
bmi_chart = gr.Image(label="BMI Chart")
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} 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) |