콘텐츠로 이동

BMI 등급판정 만들기

실습) 키와 몸무게를 입력받아 BMI 등급을 표시하고 건강 가이드 문구를 출력하는 App을 개발하시오.

1) 키와 몸무게를 입력받고 BMI를 계산하는 버튼이 있는 UI를 구현하시오.
2) 버튼 아래에 결과를 표시하는 결과 창을 추가하시오.

필요한 모듈 설치

!pip install gradio
import gradio as gr

def bmi(h, w):
    h2 = h / 100.0
    res = int(w / (h2 * h2))
    return res, '정상'


with gr.Blocks() as demo:

    gr.Markdown(
    """
    # BMI 계산기
    개발자: 홍길동
    본 프로그램은 AI로 계산되는 BMI 계산입니다.
    """)

    with gr.Row():
        n1 = gr.Number(label="키(cm)")
        n2 = gr.Number(label="몸무게(Kg)")   

    with gr.Row():
        r1 = gr.Textbox(label="BMI")
        r2 = gr.Textbox(label="비만도")

    bmi_btn = gr.Button("BMI 계산하기")

    bmi_btn.click(fn=bmi, inputs=[n1, n2], outputs=[r1, r2])

demo.launch()
import gradio as gr


def bmi(h, w):
    h2 = h / 100.0
    res = int(w / (h2 * h2))
    review = "정상입니다. 운동을 열심히 하세요."
    return res, '정상', review

with gr.Blocks() as demo:

    gr.Markdown(
    """
    # BMI 계산기
    개발자: 홍길동
    본 프로그램은 AI로 계산되는 BMI 계산입니다.
    """)

    with gr.Row():
        n1 = gr.Number(label="키(cm)")
        n2 = gr.Number(label="몸무게(Kg)")   

    with gr.Row():
        r1 = gr.Textbox(label="BMI")
        r2 = gr.Textbox(label="비만도")

    r3 = gr.Textbox(label="분석결과")

    bmi_btn = gr.Button("BMI 계산하기")

    bmi_btn.click(fn=bmi, inputs=[n1, n2], outputs=[r1, r2, r3])

demo.launch()
import gradio as gr

# BMI 계산 함수
def calculate_bmi(height, weight):
    # BMI 계산 (BMI = weight(kg) / (height(m)^2))
    height_in_meters = height / 100  # cm를 meter로 변환
    bmi = weight / (height_in_meters ** 2)

    # BMI 결과를 정수로 반환
    bmi_value = int(bmi)

    # BMI 기준에 따른 체중 상태 판별
    if bmi < 18.5:
        bmi_status = "저체중"
        food_recommendation = "추천 음식: 고단백 식사 (예: 계란, 닭가슴살, 두부 등)"
        exercise_recommendation = "추천 운동: 근육량 증가를 위한 웨이트 트레이닝"
    elif 18.5 <= bmi < 24.9:
        bmi_status = "정상 체중"
        food_recommendation = "추천 음식: 균형 잡힌 식사 (예: 샐러드, 통곡물, 생선 등)"
        exercise_recommendation = "추천 운동: 유산소 운동 (예: 조깅, 자전거 타기)"
    elif 25 <= bmi < 29.9:
        bmi_status = "과체중"
        food_recommendation = "추천 음식: 저칼로리 식사 (예: 채소, 닭가슴살, 두부 등)"
        exercise_recommendation = "추천 운동: 유산소 운동 + 근력 운동 (예: 걷기, 수영, 웨이트 트레이닝)"
    else:
        bmi_status = "비만"
        food_recommendation = "추천 음식: 저칼로리, 고단백 식사 (예: 채소, 생선, 닭가슴살 등)"
        exercise_recommendation = "추천 운동: 유산소 운동 (예: 달리기, 수영, 사이클링) + 근력 운동"

    return bmi_value, bmi_status, food_recommendation, exercise_recommendation

# Gradio Blocks 레이아웃 구성
with gr.Blocks() as demo:
    # HTML로 직접 CSS 삽입하여 스타일을 지정
    gr.HTML("""    
    <style>
        body {
            background-color: #001f3d;  /* dark blue */
            color: white;               /* 텍스트 색상 흰색 */
            font-family: 'Helvetica', sans-serif;
        }
        h1 {
            text-align: center;         /* 제목 중앙 정렬 */
            font-size: 3em;
            margin-top: 50px;
        }
        .gradio-container {
            background-color: #001f3d;  /* 전체 컨테이너 배경 색상 */
            color: white;               /* 텍스트 색상 흰색 */
        }
    </style>
    """)
    # HTML로 제목 추가
    gr.HTML("<h1 style='color: white'>AI BMI 계산기</h1>")

    # 입력 폼 구성
    with gr.Row():
        height_input = gr.Number(label="키 (cm)")
        weight_input = gr.Number(label="몸무게 (kg)")

    # 결과 출력
    with gr.Row():
        bmi_result = gr.Textbox(label="BMI", interactive=False)
        bmi_status = gr.Textbox(label="체중 상태", interactive=False)
        food_recommendation = gr.Textbox(label="추천 음식", interactive=False)
        exercise_recommendation = gr.Textbox(label="추천 운동", interactive=False)

    # 버튼 클릭 시 BMI 계산 함수 실행
    calculate_button = gr.Button("BMI 계산")
    calculate_button.click(fn=calculate_bmi, inputs=[height_input, weight_input],
                           outputs=[bmi_result, bmi_status, food_recommendation, exercise_recommendation])

# 인터페이스 실행
demo.launch()