File size: 4,741 Bytes
0e2d637
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
import gradio as gr
import openai
import base64
import os
# ✅ 輸入你的 OpenAI API 金鑰
openai.api_key = os.environ.get("OPENAI_API_KEY")

# ✅ 圖片轉 base64
def image_to_base64(image_path):
    with open(image_path, "rb") as img_file:
        return base64.b64encode(img_file.read()).decode("utf-8")

# ✅ GPT-4o 分析餐點圖片
def analyze_diet(image_path, goal, gender, age):
    try:
        img_b64 = image_to_base64(image_path)
        messages = [
            {
                "role": "user",
                "content": [
                    {
                        "type": "text",
                        "text": f"這是使用者的餐點圖片。性別:{gender},年齡:{age} 歲,目標:{goal}。請根據圖片中的內容,給出健康分析與一句鼓勵話。格式如下:\n建議:...\n鼓勵:..."
                    },
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": f"data:image/jpeg;base64,{img_b64}"
                        }
                    }
                ]
            }
        ]

        response = openai.ChatCompletion.create(
            model="gpt-4o",
            messages=messages,
            temperature=0.7
        )
        result = response.choices[0].message.content.strip()

        if "建議:" in result and "鼓勵:" in result:
            suggestion = result.split("建議:")[1].split("鼓勵:")[0].strip()
            encouragement = result.split("鼓勵:")[1].strip()
        else:
            suggestion = result
            encouragement = "你的飲食選擇很棒!繼續保持~"

        return suggestion, encouragement

    except Exception as e:
        return "❌ 分析失敗:" + str(e), ""

# ✅ 運動分析(仍為文字輸入)
def analyze_workout(text, goal, gender, age):
    prompt = f"""
你是一位健身教練,使用者性別為 {gender},年齡 {age} 歲,目標是「{goal}」。
以下是他的運動紀錄:
{text}
請給出運動分析與一句鼓勵話,格式如下:
建議:...
鼓勵:...
"""
    try:
        response = openai.ChatCompletion.create(
            model="gpt-4o",
            messages=[
                {"role": "system", "content": "你是一位健身教練"},
                {"role": "user", "content": prompt}
            ],
            temperature=0.7
        )
        result = response.choices[0].message.content.strip()

        if "建議:" in result and "鼓勵:" in result:
            suggestion = result.split("建議:")[1].split("鼓勵:")[0].strip()
            encouragement = result.split("鼓勵:")[1].strip()
        else:
            suggestion = result
            encouragement = "保持運動習慣,健康就靠你!"

        return suggestion, encouragement

    except Exception as e:
        return "❌ 分析失敗:" + str(e), ""

# ✅ Gradio UI
with gr.Blocks() as health_ai:
    gr.Markdown("# 🧠 我的健康管家 AI")
    gr.Markdown("上傳你的餐點圖片或輸入運動內容,AI 幫你分析健康狀況並給鼓勵 💪")

    with gr.Tabs():
        with gr.Tab("🍱 飲食分析(圖片)"):
            diet_input = gr.Image(label="上傳你的餐點圖片", type="filepath")
            diet_goal = gr.Radio(["減脂", "增肌", "維持體態"], label="你的目標")
            diet_gender = gr.Radio(["男", "女"], label="你的性別")
            diet_age = gr.Textbox(label="你的年齡", placeholder="例如:22")
            diet_button = gr.Button("開始分析")
            diet_output = gr.Textbox(label="AI 分析建議")
            diet_encourage = gr.Textbox(label="AI 鼓勵語")

        with gr.Tab("🏃‍♂️ 運動分析(文字)"):
            workout_input = gr.Textbox(lines=5, placeholder="例如:慢跑30分鐘,核心訓練15分鐘...")
            workout_goal = gr.Radio(["減脂", "增肌", "維持體態"], label="你的目標")
            workout_gender = gr.Radio(["男", "女"], label="你的性別")
            workout_age = gr.Textbox(label="你的年齡", placeholder="例如:22")
            workout_button = gr.Button("開始分析")
            workout_output = gr.Textbox(label="AI 評估與建議")
            workout_encourage = gr.Textbox(label="AI 鼓勵語")

    diet_button.click(analyze_diet,
                      inputs=[diet_input, diet_goal, diet_gender, diet_age],
                      outputs=[diet_output, diet_encourage])

    workout_button.click(analyze_workout,
                         inputs=[workout_input, workout_goal, workout_gender, workout_age],
                         outputs=[workout_output, workout_encourage])

health_ai.launch()