DrishtiSharma commited on
Commit
3a9d36b
Β·
verified Β·
1 Parent(s): 73e596e

Create with_viz4.py

Browse files
Files changed (1) hide show
  1. mylab/with_viz4.py +210 -0
mylab/with_viz4.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ try:
63
+ height_m = height / 100
64
+ bmi = weight / (height_m ** 2)
65
+ if bmi < 18.5:
66
+ status = "underweight"
67
+ elif 18.5 <= bmi < 24.9:
68
+ status = "normal weight"
69
+ elif 25 <= bmi < 29.9:
70
+ status = "overweight"
71
+ else:
72
+ status = "obese"
73
+
74
+ return bmi, status
75
+ except Exception:
76
+ return None, "Invalid height or weight provided."
77
+
78
+
79
+ def visualize_bmi(bmi):
80
+ try:
81
+ categories = ["Underweight", "Normal Weight", "Overweight", "Obese"]
82
+ x_pos = np.arange(len(categories))
83
+ colors = ['blue', 'green', 'orange', 'red']
84
+
85
+ plt.figure(figsize=(8, 4))
86
+ plt.bar(categories, [18.5, 24.9, 29.9, 40], color=colors, alpha=0.6)
87
+ plt.axhline(y=bmi, color='purple', linestyle='--', linewidth=2, label=f"Your BMI: {bmi:.2f}")
88
+ plt.ylabel("BMI Value")
89
+ plt.title("BMI Visualization")
90
+ plt.legend(loc="upper left")
91
+ plt.tight_layout()
92
+
93
+ plt_path = "bmi_chart.png"
94
+ plt.savefig(plt_path)
95
+ plt.close()
96
+
97
+ return plt_path
98
+ except Exception as e:
99
+ return f"Error creating BMI visualization: {e}"
100
+
101
+
102
+ def calculate_calories(age, weight, height, activity_level, gender):
103
+ try:
104
+ # Base Metabolic Rate (BMR) calculation
105
+ if gender.lower() == "male":
106
+ bmr = 10 * weight + 6.25 * height - 5 * age + 5
107
+ else:
108
+ bmr = 10 * weight + 6.25 * height - 5 * age - 161
109
+
110
+ # Activity multiplier mapping
111
+ activity_multipliers = {
112
+ "Sedentary": 1.2,
113
+ "Lightly active": 1.375,
114
+ "Moderately active": 1.55,
115
+ "Very active": 1.725,
116
+ "Extra active": 1.9,
117
+ }
118
+
119
+ if activity_level in activity_multipliers:
120
+ calories = bmr * activity_multipliers[activity_level]
121
+ else:
122
+ raise ValueError("Invalid activity level")
123
+
124
+ return round(calories, 2)
125
+ except Exception as e:
126
+ return f"Error in calorie calculation: {e}"
127
+
128
+ # Interface Components
129
+ with gr.Blocks() as demo:
130
+ gr.Markdown("# FIT.AI - Your Fitness and Wellbeing Coach")
131
+
132
+ with gr.Tab("Chat with FIT.AI"):
133
+ with gr.Row():
134
+ with gr.Column():
135
+ user_name = gr.Textbox(placeholder="Enter your name", label="Name")
136
+ user_age = gr.Number(label="Age (years)", value=25, precision=0)
137
+ user_gender = gr.Dropdown(choices=["Male", "Female"], label="Gender", value="Male")
138
+ user_weight = gr.Number(label="Weight (kg)", value=70, precision=1)
139
+ user_height = gr.Number(label="Height (cm)", value=170, precision=1)
140
+ activity_level = gr.Dropdown(
141
+ choices=["Sedentary", "Lightly active", "Moderately active", "Very active", "Extra active"],
142
+ label="Activity Level",
143
+ value="Moderately active"
144
+ )
145
+
146
+ chatbot = gr.Chatbot(label="Chat with FIT.AI", type="messages")
147
+ text_input = gr.Textbox(placeholder="Type your question here...", label="Your Question")
148
+ submit_button = gr.Button("Submit")
149
+ clear_button = gr.Button("Clear Chat")
150
+
151
+ def submit_message(message, history=[]):
152
+ user_details = {
153
+ "name": user_name.value,
154
+ "age": user_age.value,
155
+ "weight": user_weight.value,
156
+ "height": user_height.value,
157
+ "activity_level": activity_level.value,
158
+ "gender": user_gender.value
159
+ }
160
+ bmi, status = calculate_bmi(user_details["height"], user_details["weight"], user_details["gender"])
161
+ if bmi:
162
+ bmi_path = visualize_bmi(bmi)
163
+ calories = calculate_calories(user_details["age"], user_details["weight"], user_details["height"], user_details["activity_level"], user_details["gender"])
164
+ response = run_graph(message, history, user_details)
165
+ history.append({"role": "user", "content": message})
166
+ history.append({"role": "assistant", "content": response + f"\nYour BMI is {bmi:.2f}, considered {status}.\nDaily calorie needs: {calories} kcal.", "image": bmi_path})
167
+ return history, ""
168
+ else:
169
+ history.append({"role": "assistant", "content": "Error in calculation."})
170
+ return history, ""
171
+
172
+ submit_button.click(submit_message, inputs=[text_input, chatbot], outputs=[chatbot, text_input])
173
+ clear_button.click(lambda: ([], ""), inputs=None, outputs=[chatbot, text_input])
174
+
175
+ with gr.Tab("BMI and Calorie Calculator"):
176
+ with gr.Row():
177
+ with gr.Column():
178
+ user_name = gr.Textbox(placeholder="Enter your name", label="Name")
179
+ user_age = gr.Number(label="Age (years)", value=25, precision=0)
180
+ user_gender = gr.Dropdown(choices=["Male", "Female"], label="Gender", value="Male")
181
+ user_weight = gr.Number(label="Weight (kg)", value=70, precision=1)
182
+ user_height = gr.Number(label="Height (cm)", value=170, precision=1)
183
+ activity_level = gr.Dropdown(
184
+ choices=["Sedentary", "Lightly active", "Moderately active", "Very active", "Extra active"],
185
+ label="Activity Level",
186
+ value="Moderately active"
187
+ )
188
+ calculate_button = gr.Button("Calculate")
189
+
190
+ with gr.Column():
191
+ bmi_output = gr.Label(label="BMI Result")
192
+ calorie_output = gr.Label(label="Calorie Needs")
193
+ bmi_chart = gr.Image(label="BMI Chart")
194
+
195
+ def calculate_metrics(age, weight, height, gender, activity_level):
196
+ bmi, status = calculate_bmi(height, weight, gender)
197
+ if bmi:
198
+ bmi_path = visualize_bmi(bmi)
199
+ calories = calculate_calories(age, weight, height, activity_level, gender)
200
+ return f"Your BMI is {bmi:.2f}, considered {status}.", f"Daily calorie needs: {calories} kcal", bmi_path
201
+ else:
202
+ return "Invalid inputs.", "", ""
203
+
204
+ calculate_button.click(
205
+ calculate_metrics,
206
+ inputs=[user_age, user_weight, user_height, user_gender, activity_level],
207
+ outputs=[bmi_output, calorie_output, bmi_chart]
208
+ )
209
+
210
+ demo.launch(share=True)