BMI-Calculator / app.py
Umar4321's picture
Create app.py
00554d3 verified
import gradio as gr
# Function to calculate BMI
def calculate_bmi(weight, height, unit, precision):
try:
if weight <= 0 or height <= 0:
return "โŒ Please enter positive numbers."
# Convert height and weight depending on unit system
if unit == "Metric (kg, cm)":
weight_kg = weight
height_m = height / 100 # convert cm โ†’ m
else: # Imperial (lbs, inches)
weight_kg = weight * 0.45359237
height_m = height * 0.0254
bmi = weight_kg / (height_m ** 2)
bmi = round(bmi, precision)
# WHO classification
if bmi < 18.5:
category = "Underweight ๐ŸŸก"
advice = "You may need to gain some healthy weight."
elif 18.5 <= bmi < 25:
category = "Normal โœ…"
advice = "Great! Maintain your healthy lifestyle."
elif 25 <= bmi < 30:
category = "Overweight ๐ŸŸ "
advice = "Consider balanced diet and exercise."
else:
category = "Obese ๐Ÿ”ด"
advice = "Seek medical advice for weight management."
return f"๐Ÿ“Š BMI: {bmi}\n๐Ÿ“Œ Category: {category}\n๐Ÿ’ก Advice: {advice}"
except Exception as e:
return f"Error: {str(e)}"
# Gradio UI
with gr.Blocks() as demo:
gr.Markdown("# ๐Ÿงฎ BMI Calculator")
with gr.Row():
unit = gr.Radio(["Metric (kg, cm)", "Imperial (lbs, inches)"], value="Metric (kg, cm)", label="Unit System")
with gr.Row():
weight = gr.Number(label="Weight (kg or lbs)")
height = gr.Number(label="Height (cm or inches)")
precision = gr.Slider(0, 4, value=2, step=1, label="Decimal Precision")
calc_btn = gr.Button("Calculate BMI")
result = gr.Textbox(label="Result", lines=4)
calc_btn.click(calculate_bmi, [weight, height, unit, precision], result)
# Run
demo.launch()