bmi_calculator / app.py
lola1126's picture
Create app.py
ed76656 verified
import gradio as gr
import csv
import os
def calculate_bmi(name, age, weight, height):
try:
age = int(age)
weight = float(weight)
height = float(height)
bmi = weight / (height ** 2)
if bmi < 18.5:
status = "Underweight"
advice = "Consider a balanced diet to gain healthy weight."
elif 18.5 <= bmi < 25:
status = "Normal weight"
advice = "Great! Maintain your healthy lifestyle."
elif 25 <= bmi < 30:
status = "Overweight"
advice = "Try regular exercise and a balanced diet."
else:
status = "Obese"
advice = "Consult a healthcare professional for guidance."
# ุญูุธ ุงู„ุจูŠุงู†ุงุช ููŠ ู…ู„ู CSV
with open("bmi_records.csv", mode="a", newline="") as file:
writer = csv.writer(file)
writer.writerow([name, age, weight, height, round(bmi, 2), status])
return f"""โœ… Name: {name}, Age: {age}
๐Ÿ“Š BMI: {bmi:.2f}
๐Ÿ“Œ Status: {status}
๐Ÿ’ก Advice: {advice}"""
except ValueError:
return "โš  Please enter valid numbers!"
def view_records():
if not os.path.exists("bmi_records.csv"):
return "โš  No records found. Please calculate BMI first."
table = "Name | Age | Weight | Height | BMI | Status\n"
table += "-"*50 + "\n"
with open("bmi_records.csv", mode="r") as file:
reader = csv.reader(file)
for row in reader:
table += " | ".join(row) + "\n"
return table
with gr.Blocks() as demo:
gr.Markdown("## ๐Ÿ’ช BMI Calculator - Alaa")
with gr.Row():
name = gr.Textbox(label="Name")
age = gr.Number(label="Age", value=20)
with gr.Row():
weight = gr.Number(label="Weight (kg)", value=70)
height = gr.Number(label="Height (m)", value=1.70)
output = gr.Textbox(label="Result")
btn_calc = gr.Button("Calculate BMI")
btn_view = gr.Button("View Records")
btn_calc.click(fn=calculate_bmi, inputs=[name, age, weight, height], outputs=output)
btn_view.click(fn=view_records, inputs=None, outputs=output)
demo.launch()