Update app.py
Browse files
app.py
CHANGED
@@ -51,7 +51,11 @@ def run_graph(input_message, history, user_details):
|
|
51 |
logger.debug("Invoking workflow with messages: %s", messages)
|
52 |
response = graph.invoke({"messages": messages})
|
53 |
logger.debug("Workflow response: %s", response)
|
54 |
-
|
|
|
|
|
|
|
|
|
55 |
except Exception as e:
|
56 |
logger.error("Error in run_graph: %s", str(e))
|
57 |
q.put(f"An error occurred while processing your request: {e}")
|
@@ -60,11 +64,11 @@ def run_graph(input_message, history, user_details):
|
|
60 |
q = queue.Queue()
|
61 |
thread = threading.Thread(target=invoke_workflow, args=(q,))
|
62 |
thread.start()
|
63 |
-
thread.join(timeout=300) #
|
64 |
|
65 |
if thread.is_alive():
|
66 |
logger.error("Workflow timed out.")
|
67 |
-
return "The request is taking longer than expected. Please try again later
|
68 |
return q.get()
|
69 |
|
70 |
|
@@ -83,21 +87,20 @@ def calculate_bmi(height, weight):
|
|
83 |
|
84 |
|
85 |
def visualize_bmi_and_calories(bmi, calories):
|
86 |
-
# Create a combined visualization
|
87 |
categories = ["Underweight", "Normal Weight", "Overweight", "Obese"]
|
88 |
bmi_values = [18.5, 24.9, 29.9, 40]
|
89 |
calorie_range = [1500, 2000, 2500, 3000]
|
90 |
|
91 |
fig, ax1 = plt.subplots(figsize=(10, 6))
|
92 |
|
93 |
-
# BMI
|
94 |
ax1.bar(categories, bmi_values, color=['blue', 'green', 'orange', 'red'], alpha=0.6, label="BMI Ranges")
|
95 |
ax1.axhline(y=bmi, color='purple', linestyle='--', linewidth=2, label=f"Your BMI: {bmi:.2f}")
|
96 |
ax1.set_ylabel("BMI Value")
|
97 |
ax1.set_title("BMI and Caloric Needs Visualization")
|
98 |
ax1.legend(loc="upper left")
|
99 |
|
100 |
-
# Calorie
|
101 |
ax2 = ax1.twinx()
|
102 |
ax2.plot(categories, calorie_range, 'o-', color='magenta', label="Calorie Ranges")
|
103 |
ax2.axhline(y=calories, color='cyan', linestyle='--', linewidth=2, label=f"Your Calorie Needs: {calories:.2f} kcal")
|
@@ -106,7 +109,7 @@ def visualize_bmi_and_calories(bmi, calories):
|
|
106 |
|
107 |
plt.tight_layout()
|
108 |
|
109 |
-
# Save to a temporary file
|
110 |
temp_file = tempfile.NamedTemporaryFile(suffix=".png", delete=False)
|
111 |
plt.savefig(temp_file.name)
|
112 |
plt.close()
|
@@ -136,7 +139,7 @@ with gr.Blocks() as demo:
|
|
136 |
|
137 |
with gr.Tabs():
|
138 |
with gr.Tab("Visualization + Chat"):
|
139 |
-
# User
|
140 |
with gr.Row():
|
141 |
user_name = gr.Textbox(placeholder="Enter your name", label="Name")
|
142 |
user_age = gr.Number(label="Age (years)", value=25, precision=0)
|
@@ -177,11 +180,6 @@ with gr.Blocks() as demo:
|
|
177 |
)
|
178 |
chart_path = visualize_bmi_and_calories(bmi, calories)
|
179 |
|
180 |
-
# Compose input for the LLM dynamically
|
181 |
-
system_prompt = (
|
182 |
-
"You are a fitness and health assistant. Provide detailed advice based on the user's metrics, including BMI and caloric needs."
|
183 |
-
)
|
184 |
-
|
185 |
user_prompt = (
|
186 |
f"User Details:\n"
|
187 |
f"- Name: {user_details['name']}\n"
|
@@ -195,38 +193,29 @@ with gr.Blocks() as demo:
|
|
195 |
f"\nProvide tailored advice based on these metrics."
|
196 |
)
|
197 |
|
198 |
-
messages = [
|
199 |
-
{"role": "system", "content": system_prompt},
|
200 |
-
{"role": "user", "content": user_prompt}
|
201 |
-
]
|
202 |
-
|
203 |
-
logger.debug("Submitting messages to LLM: %s", messages)
|
204 |
response = run_graph(message, history, user_details)
|
205 |
-
logger.debug("Received LLM response: %s", response)
|
206 |
-
|
207 |
history.append((f"User", message))
|
208 |
history.append(("FIT.AI", response))
|
209 |
return history, chart_path
|
210 |
|
211 |
except Exception as e:
|
212 |
logger.error("Error in submit_message: %s", str(e))
|
213 |
-
return history + [("FIT.AI", "An error occurred
|
214 |
|
215 |
submit_button.click(submit_message, inputs=[text_input, chatbot], outputs=[chatbot, bmi_chart])
|
216 |
clear_button.click(lambda: ([], ""), inputs=None, outputs=[chatbot, bmi_chart])
|
217 |
|
|
|
218 |
with gr.Tab("Calculator + Visualization"):
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
value="Moderately active"
|
229 |
-
)
|
230 |
|
231 |
bmi_output = gr.Label(label="BMI Result")
|
232 |
calorie_output = gr.Label(label="Calorie Needs")
|
@@ -237,9 +226,9 @@ with gr.Blocks() as demo:
|
|
237 |
def calculate_metrics(age, weight, height, gender, activity_level):
|
238 |
try:
|
239 |
bmi, status = calculate_bmi(height, weight)
|
240 |
-
bmi_path = visualize_bmi_and_calories(bmi, calculate_calories(age, weight, height, activity_level, gender))
|
241 |
calories = calculate_calories(age, weight, height, activity_level, gender)
|
242 |
-
|
|
|
243 |
except Exception as e:
|
244 |
logger.error("Error in calculate_metrics: %s", str(e))
|
245 |
return "An error occurred.", "", None
|
|
|
51 |
logger.debug("Invoking workflow with messages: %s", messages)
|
52 |
response = graph.invoke({"messages": messages})
|
53 |
logger.debug("Workflow response: %s", response)
|
54 |
+
# Check for proper response structure
|
55 |
+
if "messages" in response and len(response["messages"]) > 1:
|
56 |
+
q.put(response["messages"][1].get("content", "No content in response."))
|
57 |
+
else:
|
58 |
+
q.put("The workflow did not return a valid response. Please try again.")
|
59 |
except Exception as e:
|
60 |
logger.error("Error in run_graph: %s", str(e))
|
61 |
q.put(f"An error occurred while processing your request: {e}")
|
|
|
64 |
q = queue.Queue()
|
65 |
thread = threading.Thread(target=invoke_workflow, args=(q,))
|
66 |
thread.start()
|
67 |
+
thread.join(timeout=300) # Increased timeout to 60 seconds
|
68 |
|
69 |
if thread.is_alive():
|
70 |
logger.error("Workflow timed out.")
|
71 |
+
return "The request is taking longer than expected. Please try again later."
|
72 |
return q.get()
|
73 |
|
74 |
|
|
|
87 |
|
88 |
|
89 |
def visualize_bmi_and_calories(bmi, calories):
|
|
|
90 |
categories = ["Underweight", "Normal Weight", "Overweight", "Obese"]
|
91 |
bmi_values = [18.5, 24.9, 29.9, 40]
|
92 |
calorie_range = [1500, 2000, 2500, 3000]
|
93 |
|
94 |
fig, ax1 = plt.subplots(figsize=(10, 6))
|
95 |
|
96 |
+
# BMI Visualization
|
97 |
ax1.bar(categories, bmi_values, color=['blue', 'green', 'orange', 'red'], alpha=0.6, label="BMI Ranges")
|
98 |
ax1.axhline(y=bmi, color='purple', linestyle='--', linewidth=2, label=f"Your BMI: {bmi:.2f}")
|
99 |
ax1.set_ylabel("BMI Value")
|
100 |
ax1.set_title("BMI and Caloric Needs Visualization")
|
101 |
ax1.legend(loc="upper left")
|
102 |
|
103 |
+
# Calorie Visualization
|
104 |
ax2 = ax1.twinx()
|
105 |
ax2.plot(categories, calorie_range, 'o-', color='magenta', label="Calorie Ranges")
|
106 |
ax2.axhline(y=calories, color='cyan', linestyle='--', linewidth=2, label=f"Your Calorie Needs: {calories:.2f} kcal")
|
|
|
109 |
|
110 |
plt.tight_layout()
|
111 |
|
112 |
+
# Save visualization to a temporary file
|
113 |
temp_file = tempfile.NamedTemporaryFile(suffix=".png", delete=False)
|
114 |
plt.savefig(temp_file.name)
|
115 |
plt.close()
|
|
|
139 |
|
140 |
with gr.Tabs():
|
141 |
with gr.Tab("Visualization + Chat"):
|
142 |
+
# User Input
|
143 |
with gr.Row():
|
144 |
user_name = gr.Textbox(placeholder="Enter your name", label="Name")
|
145 |
user_age = gr.Number(label="Age (years)", value=25, precision=0)
|
|
|
180 |
)
|
181 |
chart_path = visualize_bmi_and_calories(bmi, calories)
|
182 |
|
|
|
|
|
|
|
|
|
|
|
183 |
user_prompt = (
|
184 |
f"User Details:\n"
|
185 |
f"- Name: {user_details['name']}\n"
|
|
|
193 |
f"\nProvide tailored advice based on these metrics."
|
194 |
)
|
195 |
|
|
|
|
|
|
|
|
|
|
|
|
|
196 |
response = run_graph(message, history, user_details)
|
|
|
|
|
197 |
history.append((f"User", message))
|
198 |
history.append(("FIT.AI", response))
|
199 |
return history, chart_path
|
200 |
|
201 |
except Exception as e:
|
202 |
logger.error("Error in submit_message: %s", str(e))
|
203 |
+
return history + [("FIT.AI", "An error occurred. Please try again.")], None
|
204 |
|
205 |
submit_button.click(submit_message, inputs=[text_input, chatbot], outputs=[chatbot, bmi_chart])
|
206 |
clear_button.click(lambda: ([], ""), inputs=None, outputs=[chatbot, bmi_chart])
|
207 |
|
208 |
+
# Calculator + Visualization Tab
|
209 |
with gr.Tab("Calculator + Visualization"):
|
210 |
+
user_age_calc = gr.Number(label="Age (years)", value=25, precision=0)
|
211 |
+
user_gender_calc = gr.Dropdown(choices=["Male", "Female"], label="Gender", value="Male")
|
212 |
+
user_weight_calc = gr.Number(label="Weight (kg)", value=70, precision=1)
|
213 |
+
user_height_calc = gr.Number(label="Height (cm)", value=170, precision=1)
|
214 |
+
activity_level_calc = gr.Dropdown(
|
215 |
+
choices=["Sedentary", "Lightly active", "Moderately active", "Very active", "Extra active"],
|
216 |
+
label="Activity Level",
|
217 |
+
value="Moderately active"
|
218 |
+
)
|
|
|
|
|
219 |
|
220 |
bmi_output = gr.Label(label="BMI Result")
|
221 |
calorie_output = gr.Label(label="Calorie Needs")
|
|
|
226 |
def calculate_metrics(age, weight, height, gender, activity_level):
|
227 |
try:
|
228 |
bmi, status = calculate_bmi(height, weight)
|
|
|
229 |
calories = calculate_calories(age, weight, height, activity_level, gender)
|
230 |
+
chart_path = visualize_bmi_and_calories(bmi, calories)
|
231 |
+
return f"Your BMI is {bmi:.2f}, considered {status}.", f"Daily calorie needs: {calories:.2f} kcal", chart_path
|
232 |
except Exception as e:
|
233 |
logger.error("Error in calculate_metrics: %s", str(e))
|
234 |
return "An error occurred.", "", None
|