Spaces:
Runtime error
Runtime error
| 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) |