今天的任務就是要將使用者在 index.html 提供的資料,經過 Gemini 分析後,顯示在 result.html

AI_Nutri_Project/
├── app.py # Flask 應用程式主程式
├── credentials.json # Google OAuth 憑證
└── templates/
├── index.html # 輸入/首頁 UI
└── results.html # 分析結果 UI
由於 app.py 目前已經有個 Google Fit 了,如果 Gemini 再搬進去的話,有點兒擠...
與 Google Fit 相關的寫在 google_fit_service.py;與 Google Gemini 相關的寫在 gemini_service.py
AI_Nutri_Project/
├── app.py # Flask 應用程式主程式
├── credentials.json # Google OAuth 憑證
├── services/ # 服務層
│ ├── gemini_service.py # 處理 Gemini API 呼叫、JSON 處理
│ └── google_fit_service.py # 處理 Google Fit OAuth & 數據獲取
│
└── templates/ # UI
可以用來放 Gemini 的 Api Key,以及 Google Fit 的憑證 credentials.json
AI_Nutri_Project/
├── app.py # Flask主程式
├── config/ # 金鑰設定
│ ├── .env # GEMINI_API_KEY
│ └── credentials.json # Google Fit憑證
├── services/
│ ├── gemini_service.py # Gemini串接/JSON處理
│ └── google_fit_service.py
└── templates/
├── index.html # 用戶首頁
└── results.html # 結果頁UI
請確認目前的 Python 環境中安裝了所有必要的函式庫:
pip install google-genai pillow python-dotenv
# .env
GEMINI_API_KEY="YOUR_GEMINI_API_KEY"
import os
from dotenv import load_dotenv
from flask import Flask
load_dotenv() # 載入 .env 檔案
def create_app():
app = Flask(__name__)
# 將 API Key 載入到 app.config 中
app.config['GEMINI_API_KEY'] = os.environ.get("GEMINI_API_KEY")
# ...
return app
import os
from google.genai import Gemini
# 讀取 API Key(建議用 dotenv)
gemini_api_key = os.environ.get("GEMINI_API_KEY")
# 初始化 Gemini 客戶端
client = Gemini(api_key=gemini_api_key)
def analyze_nutrition(user_input):
try:
# 準備要送出的 JSON 資料(可根據專案規劃調整欄位)
payload = {
"question": user_input["question"],
"food_image_url": user_input.get("food_image_url", "")
}
# Gemini API 串接(假設官方用 analyze 方法)
response = client.analyze(data=payload)
# 通常回傳也是 JSON(請參考官方docs)
result = response.json()
return {"summary": result.get("summary", "無重點"),
"nutrients": result.get("nutrients", {}),
"advice": result.get("advice", [])}
except Exception as e:
# 簡明 error handling
return {"summary": "API出錯,請稍後再試", "nutrients": {}, "advice": [str(e)]}
user_input = {
"question": "今天午餐熱量多高?",
"food_image_url": "https://xxx.com/photo.jpg"
}
{
"summary": "今日午餐熱量偏高,蛋白質足夠。",
"nutrients": {"calories": 805, "protein": 32, "fat": 35},
"advice": ["多喝水", "明天加蔬菜"]
}
python app.py
