DrishtiSharma's picture
Create interim.py
b7cebb5 verified
raw
history blame
6.89 kB
import gradio as gr
import matplotlib.pyplot as plt
import pandas as pd
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):
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 f"Your BMI is {bmi:.2f}, which is considered {status}."
except:
return "Invalid height or weight provided."
def calculate_calories(age, weight, height, activity_level):
try:
# Harris-Benedict Equation for calorie calculation
bmr = 10 * weight + 6.25 * height - 5 * age + 5 # Male (adjust for female by subtracting 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[activity_level]
return f"Your estimated daily calorie needs are {calories:.2f} kcal."
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_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 Section
chatbot = gr.Chatbot(label="Chat with FIT.AI")
text_input = gr.Textbox(placeholder="Type your question here...", label="Your Question")
submit_button = gr.Button("Submit")
clear_button = gr.Button("Clear Chat")
# Examples
examples = gr.Examples(
examples=[
"Create a personalized workout plan for me",
"What should I eat to lose 5 kg in two months?",
"Suggest a yoga routine for beginners",
"How much water should I drink daily based on my weight?",
],
inputs=text_input,
)
# Chat Logic
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
}
response = run_graph(message, history, user_details)
history.append(("User", message))
history.append(("FIT.AI", response))
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])
demo.launch(share=True)