DrishtiSharma commited on
Commit
a958eb2
Β·
verified Β·
1 Parent(s): ead176c

Create with_viz.py

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