Spaces:
Running
Running
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() |