DrishtiSharma commited on
Commit
c299d0e
Β·
verified Β·
1 Parent(s): 252f4df

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -78
app.py CHANGED
@@ -1,4 +1,3 @@
1
- # add tab 3 --> workflow diagram
2
  import gradio as gr
3
  import matplotlib.pyplot as plt
4
  import pandas as pd
@@ -60,6 +59,9 @@ def run_graph(input_message, history, user_details):
60
 
61
 
62
  def calculate_bmi(height, weight, gender):
 
 
 
63
  try:
64
  height_m = height / 100
65
  bmi = weight / (height_m ** 2)
@@ -71,31 +73,41 @@ def calculate_bmi(height, weight, gender):
71
  status = "overweight"
72
  else:
73
  status = "obese"
 
74
  return bmi, status
75
- except Exception:
76
  return None, "Invalid height or weight provided."
77
 
 
78
  def visualize_bmi(bmi):
79
- try:
80
- categories = ["Underweight", "Normal Weight", "Overweight", "Obese"]
81
- colors = ['blue', 'green', 'orange', 'red']
82
-
83
- plt.figure(figsize=(8, 4))
84
- plt.bar(categories, [18.5, 24.9, 29.9, 40], color=colors, alpha=0.6)
85
- plt.axhline(y=bmi, color='purple', linestyle='--', linewidth=2, label=f"Your BMI: {bmi:.2f}")
86
- plt.ylabel("BMI Value")
87
- plt.title("BMI Visualization")
88
- plt.legend(loc="upper left")
89
- plt.tight_layout()
90
-
91
- plt_path = "bmi_chart.png"
92
- plt.savefig(plt_path)
93
- plt.close()
94
- return plt_path
95
- except Exception as e:
96
- return f"Error creating BMI visualization: {e}"
 
 
 
 
 
97
 
98
  def calculate_calories(age, weight, height, activity_level, gender):
 
 
 
99
  try:
100
  if gender.lower() == "male":
101
  bmr = 10 * weight + 6.25 * height - 5 * age + 5
@@ -109,69 +121,50 @@ def calculate_calories(age, weight, height, activity_level, gender):
109
  "Very active": 1.725,
110
  "Extra active": 1.9,
111
  }
112
- return round(bmr * activity_multipliers[activity_level], 2)
113
- except Exception as e:
114
- return f"Error in calorie calculation: {e}"
 
 
115
 
116
  # Interface Components
117
  with gr.Blocks() as demo:
118
- gr.Markdown("# FIT.AI - Your Fitness and Wellbeing Coach")
119
 
 
120
  with gr.Row():
121
- with gr.Column():
122
- user_name = gr.Textbox(placeholder="Enter your name", label="Name")
123
- user_age = gr.Number(label="Age (years)", value=25, precision=0)
124
- user_gender = gr.Dropdown(choices=["Male", "Female"], label="Gender", value="Male")
125
- user_weight = gr.Number(label="Weight (kg)", value=70, precision=1)
126
- user_height = gr.Number(label="Height (cm)", value=170, precision=1)
127
- activity_level = gr.Dropdown(
128
- choices=["Sedentary", "Lightly active", "Moderately active", "Very active", "Extra active"],
129
- label="Activity Level",
130
- value="Moderately active"
131
- )
132
- with gr.Column():
133
- chatbot = gr.Chatbot(label="Chat with FIT.AI", type="messages", height=500)
134
- text_input = gr.Textbox(placeholder="Type your question here...", label="Your Question")
135
- bmi_result = gr.Label(label="BMI Result")
136
- calorie_result = gr.Label(label="Calorie Needs")
137
- bmi_chart = gr.Image(label="BMI Chart")
138
- submit_button = gr.Button("Submit")
139
- clear_button = gr.Button("Clear Chat")
140
-
141
- def submit_message(message, history=[]):
142
- user_details = {
143
- "name": user_name.value,
144
- "age": user_age.value,
145
- "weight": user_weight.value,
146
- "height": user_height.value,
147
- "activity_level": activity_level.value,
148
- "gender": user_gender.value
149
- }
150
- try:
151
- bmi, status = calculate_bmi(user_details["height"], user_details["weight"], user_details["gender"])
152
- if bmi:
153
- bmi_path = visualize_bmi(bmi)
154
- calories = calculate_calories(
155
- user_details["age"], user_details["weight"], user_details["height"], user_details["activity_level"], user_details["gender"]
156
- )
157
- response = run_graph(message, history, user_details)
158
- history.append({"role": "user", "content": message})
159
- history.append({
160
- "role": "assistant",
161
- "content": f"{response}\n\nYour BMI is {bmi:.2f}, considered {status}.\nDaily calorie needs: {calories} kcal.",
162
- "image": bmi_path
163
- })
164
- return history, "", f"Your BMI is {bmi:.2f}, considered {status}.", f"Daily calorie needs: {calories} kcal.", bmi_path
165
- else:
166
- return history, "", "Invalid input for BMI.", "", ""
167
- except Exception as e:
168
- return history, "", f"Error occurred: {e}", "", ""
169
-
170
- submit_button.click(
171
- submit_message,
172
- inputs=[text_input, chatbot],
173
- outputs=[chatbot, text_input, bmi_result, calorie_result, bmi_chart]
174
  )
175
- clear_button.click(lambda: ([], "", "", "", ""), inputs=None, outputs=[chatbot, text_input, bmi_result, calorie_result, bmi_chart])
176
 
177
  demo.launch(share=True)
 
 
1
  import gradio as gr
2
  import matplotlib.pyplot as plt
3
  import pandas as pd
 
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)
 
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
 
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)