Update app.py
Browse files
app.py
CHANGED
@@ -1,7 +1,6 @@
|
|
1 |
import gradio as gr
|
2 |
import matplotlib.pyplot as plt
|
3 |
-
import pandas as
|
4 |
-
import numpy as np
|
5 |
from datetime import datetime
|
6 |
from langchain_core.messages import HumanMessage
|
7 |
from tools import tools
|
@@ -15,89 +14,77 @@ graph = create_workflow()
|
|
15 |
# Helper Functions
|
16 |
def run_graph(input_message, history, user_details):
|
17 |
try:
|
18 |
-
|
19 |
-
|
20 |
-
"
|
21 |
-
"
|
22 |
-
"
|
23 |
-
"
|
24 |
-
"
|
25 |
-
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
44 |
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
return response['messages'][1].content
|
51 |
|
52 |
-
|
53 |
-
|
|
|
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
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
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 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
plt.tight_layout()
|
99 |
|
100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
101 |
plt.savefig(plt_path)
|
102 |
plt.close()
|
103 |
|
@@ -105,27 +92,20 @@ def visualize_bmi(bmi):
|
|
105 |
|
106 |
|
107 |
def calculate_calories(age, weight, height, activity_level, gender):
|
108 |
-
""
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
"Moderately active": 1.55,
|
121 |
-
"Very active": 1.725,
|
122 |
-
"Extra active": 1.9,
|
123 |
-
}
|
124 |
|
125 |
-
|
126 |
-
return calories
|
127 |
-
except Exception:
|
128 |
-
return "Invalid inputs for calorie calculation."
|
129 |
|
130 |
# Interface Components
|
131 |
with gr.Blocks() as demo:
|
@@ -147,19 +127,52 @@ with gr.Blocks() as demo:
|
|
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
|
157 |
-
|
158 |
-
|
159 |
-
|
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,
|
|
|
1 |
import gradio as gr
|
2 |
import matplotlib.pyplot as plt
|
3 |
+
import pandas as np
|
|
|
4 |
from datetime import datetime
|
5 |
from langchain_core.messages import HumanMessage
|
6 |
from tools import tools
|
|
|
14 |
# Helper Functions
|
15 |
def run_graph(input_message, history, user_details):
|
16 |
try:
|
17 |
+
system_prompt = (
|
18 |
+
"You are a fitness and health assistant. "
|
19 |
+
"Provide advice based on the user's personal details and goals. "
|
20 |
+
"If user details like weight, height, and activity level are provided, prioritize personalized advice. "
|
21 |
+
"Incorporate metrics such as BMI and daily caloric needs directly into your suggestions. "
|
22 |
+
"Visualize the user's metrics and provide actionable advice tailored to their needs. "
|
23 |
+
"If details are missing, provide general advice but encourage users to share their metrics for tailored guidance."
|
24 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
|
26 |
+
# Compose input for the LLM
|
27 |
+
user_details_summary = (
|
28 |
+
f"Name: {user_details.get('name', 'Unknown')}, "
|
29 |
+
f"Age: {user_details.get('age', 'Unknown')}, "
|
30 |
+
f"Gender: {user_details.get('gender', 'Unknown')}, "
|
31 |
+
f"Weight: {user_details.get('weight', 'Unknown')} kg, "
|
32 |
+
f"Height: {user_details.get('height', 'Unknown')} cm, "
|
33 |
+
f"Activity Level: {user_details.get('activity_level', 'Unknown')}"
|
34 |
+
)
|
35 |
|
36 |
+
messages = [
|
37 |
+
{"role": "system", "content": system_prompt},
|
38 |
+
{"role": "user", "content": f"User details: {user_details_summary}"},
|
39 |
+
{"role": "user", "content": input_message}
|
40 |
+
]
|
|
|
41 |
|
42 |
+
# Generate the response
|
43 |
+
response = graph.invoke({"messages": messages})
|
44 |
+
return response["messages"][1]["content"]
|
45 |
|
|
|
|
|
46 |
except Exception as e:
|
47 |
return f"An error occurred while processing your request: {e}"
|
48 |
|
49 |
|
50 |
+
def calculate_bmi(height, weight):
|
51 |
+
height_m = height / 100
|
52 |
+
bmi = weight / (height_m ** 2)
|
53 |
+
if bmi < 18.5:
|
54 |
+
status = "underweight"
|
55 |
+
elif 18.5 <= bmi < 24.9:
|
56 |
+
status = "normal weight"
|
57 |
+
elif 25 <= bmi < 29.9:
|
58 |
+
status = "overweight"
|
59 |
+
else:
|
60 |
+
status = "obese"
|
61 |
+
return bmi, status
|
62 |
+
|
63 |
+
|
64 |
+
def visualize_bmi_and_calories(bmi, calories):
|
65 |
+
# Create a combined visualization
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
66 |
categories = ["Underweight", "Normal Weight", "Overweight", "Obese"]
|
67 |
+
bmi_values = [18.5, 24.9, 29.9, 40]
|
68 |
+
calorie_range = [1500, 2000, 2500, 3000]
|
69 |
+
|
70 |
+
fig, ax1 = plt.subplots(figsize=(10, 6))
|
71 |
+
|
72 |
+
# BMI visualization
|
73 |
+
ax1.bar(categories, bmi_values, color=['blue', 'green', 'orange', 'red'], alpha=0.6, label="BMI Ranges")
|
74 |
+
ax1.axhline(y=bmi, color='purple', linestyle='--', linewidth=2, label=f"Your BMI: {bmi:.2f}")
|
75 |
+
ax1.set_ylabel("BMI Value")
|
76 |
+
ax1.set_title("BMI and Caloric Needs Visualization")
|
77 |
+
ax1.legend(loc="upper left")
|
|
|
78 |
|
79 |
+
# Calorie visualization
|
80 |
+
ax2 = ax1.twinx()
|
81 |
+
ax2.plot(categories, calorie_range, 'o-', color='magenta', label="Calorie Ranges")
|
82 |
+
ax2.axhline(y=calories, color='cyan', linestyle='--', linewidth=2, label=f"Your Calorie Needs: {calories:.2f} kcal")
|
83 |
+
ax2.set_ylabel("Calories")
|
84 |
+
ax2.legend(loc="upper right")
|
85 |
+
|
86 |
+
plt.tight_layout()
|
87 |
+
plt_path = "bmi_calorie_chart.png"
|
88 |
plt.savefig(plt_path)
|
89 |
plt.close()
|
90 |
|
|
|
92 |
|
93 |
|
94 |
def calculate_calories(age, weight, height, activity_level, gender):
|
95 |
+
if gender.lower() == "male":
|
96 |
+
bmr = 10 * weight + 6.25 * height - 5 * age + 5
|
97 |
+
else:
|
98 |
+
bmr = 10 * weight + 6.25 * height - 5 * age - 161
|
99 |
+
|
100 |
+
activity_multipliers = {
|
101 |
+
"Sedentary": 1.2,
|
102 |
+
"Lightly active": 1.375,
|
103 |
+
"Moderately active": 1.55,
|
104 |
+
"Very active": 1.725,
|
105 |
+
"Extra active": 1.9,
|
106 |
+
}
|
|
|
|
|
|
|
|
|
107 |
|
108 |
+
return bmr * activity_multipliers.get(activity_level, 1.2)
|
|
|
|
|
|
|
109 |
|
110 |
# Interface Components
|
111 |
with gr.Blocks() as demo:
|
|
|
127 |
# Outputs
|
128 |
bmi_output = gr.Label(label="BMI Result")
|
129 |
calorie_output = gr.Label(label="Calorie Needs")
|
130 |
+
bmi_chart = gr.Image(label="BMI and Calorie Chart")
|
131 |
+
|
132 |
+
chatbot = gr.Chatbot(label="Chat with FIT.AI")
|
133 |
+
text_input = gr.Textbox(placeholder="Type your question here...", label="Your Question")
|
134 |
+
submit_button = gr.Button("Submit")
|
135 |
+
clear_button = gr.Button("Clear Chat")
|
136 |
+
|
137 |
+
def submit_message(message, history=[]):
|
138 |
+
user_details = {
|
139 |
+
"name": user_name.value,
|
140 |
+
"age": user_age.value,
|
141 |
+
"weight": user_weight.value,
|
142 |
+
"height": user_height.value,
|
143 |
+
"activity_level": activity_level.value,
|
144 |
+
"gender": user_gender.value
|
145 |
+
}
|
146 |
+
bmi, status = calculate_bmi(user_details['height'], user_details['weight'])
|
147 |
+
calories = calculate_calories(
|
148 |
+
user_details['age'], user_details['weight'], user_details['height'], user_details['activity_level'], user_details['gender']
|
149 |
+
)
|
150 |
+
chart_path = visualize_bmi_and_calories(bmi, calories)
|
151 |
+
|
152 |
+
# Append metrics to response
|
153 |
+
personalized_metrics = (
|
154 |
+
f"Based on your metrics:\n"
|
155 |
+
f"- BMI: {bmi:.2f} ({status})\n"
|
156 |
+
f"- Daily Caloric Needs: {calories:.2f} kcal\n"
|
157 |
+
f"Visualized metrics are displayed alongside."
|
158 |
+
)
|
159 |
+
|
160 |
+
response = run_graph(f"{message}\n\n{personalized_metrics}", history, user_details)
|
161 |
+
history.append((f"{user_details['name']}", message))
|
162 |
+
history.append(("FIT.AI", response))
|
163 |
+
return history, ""
|
164 |
+
|
165 |
+
submit_button.click(submit_message, inputs=[text_input, chatbot], outputs=[chatbot, text_input])
|
166 |
+
clear_button.click(lambda: ([], ""), inputs=None, outputs=[chatbot, text_input])
|
167 |
|
168 |
# Actions
|
169 |
calculate_button = gr.Button("Calculate")
|
170 |
|
171 |
def calculate_metrics(age, weight, height, gender, activity_level):
|
172 |
+
bmi, status = calculate_bmi(height, weight)
|
173 |
+
bmi_path = visualize_bmi_and_calories(bmi, calculate_calories(age, weight, height, activity_level, gender))
|
174 |
+
calories = calculate_calories(age, weight, height, activity_level, gender)
|
175 |
+
return f"Your BMI is {bmi:.2f}, considered {status}.", f"Daily calorie needs: {calories:.2f} kcal", bmi_path
|
|
|
|
|
|
|
176 |
|
177 |
calculate_button.click(
|
178 |
calculate_metrics,
|