yuting111222 commited on
Commit
07a86d7
·
1 Parent(s): 523d6cd

fix: use USDA API for nutrition, update Dockerfile for Hugging Face

Browse files
Files changed (5) hide show
  1. Dockerfile +9 -0
  2. env_example.txt +8 -0
  3. init_db.py +7 -64
  4. main.py +2 -2
  5. services/nutrition_api_service.py +2 -2
Dockerfile CHANGED
@@ -7,4 +7,13 @@ RUN pip install --no-cache-dir -r requirements.txt
7
 
8
  COPY . .
9
 
 
 
 
 
 
 
 
 
 
10
  CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
 
7
 
8
  COPY . .
9
 
10
+ # Create data directory
11
+ RUN mkdir -p /tmp/data
12
+
13
+ # Initialize database
14
+ RUN python init_db.py
15
+
16
+ # Expose port 7860 for Hugging Face Spaces
17
+ EXPOSE 7860
18
+
19
  CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
env_example.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # USDA API Key for nutrition data (get from https://fdc.nal.usda.gov/api-key-signup.html)
2
+ USDA_API_KEY=your_usda_api_key_here
3
+
4
+ # Database configuration (optional, defaults to SQLite)
5
+ DATABASE_URL=sqlite:///tmp/data/health_assistant.db
6
+
7
+ # Hugging Face Spaces configuration
8
+ HF_SPACE_ID=your_space_id
init_db.py CHANGED
@@ -1,70 +1,13 @@
1
- from .database import Base, engine, SessionLocal
2
- from .models.meal_log import MealLog
3
- from .models.nutrition import Nutrition
4
- import json
5
 
6
- def init_db():
7
- """初始化資料庫並填入初始營養數據"""
8
  print("Creating database tables...")
9
- # 根據模型建立所有表格
10
  Base.metadata.create_all(bind=engine)
 
11
  print("Database tables created successfully!")
12
 
13
- # 檢查是否已有資料,避免重複新增
14
- db = SessionLocal()
15
- if db.query(Nutrition).count() == 0:
16
- print("Populating nutrition table with initial data...")
17
-
18
- # 從 main.py 移植過來的模擬資料
19
- mock_nutrition_data = [
20
- {
21
- "food_name": "hamburger", "chinese_name": "漢堡", "calories": 540, "protein": 25, "fat": 31, "carbs": 40,
22
- "fiber": 3, "sugar": 6, "sodium": 1040, "health_score": 45,
23
- "recommendations": ["脂肪和鈉含量過高,建議減少食用頻率。"],
24
- "warnings": ["高熱量", "高脂肪", "高鈉"]
25
- },
26
- {
27
- "food_name": "pizza", "chinese_name": "披薩", "calories": 266, "protein": 11, "fat": 10, "carbs": 33,
28
- "fiber": 2, "sugar": 4, "sodium": 598, "health_score": 65,
29
- "recommendations": ["可搭配沙拉以增加纖維攝取。"],
30
- "warnings": ["高鈉"]
31
- },
32
- {
33
- "food_name": "sushi", "chinese_name": "壽司", "calories": 200, "protein": 12, "fat": 8, "carbs": 20,
34
- "fiber": 1, "sugar": 2, "sodium": 380, "health_score": 85,
35
- "recommendations": ["優質的蛋白質和碳水化合物來源。"],
36
- "warnings": []
37
- },
38
- {
39
- "food_name": "fried rice", "chinese_name": "炒飯", "calories": 238, "protein": 8, "fat": 12, "carbs": 26,
40
- "fiber": 2, "sugar": 3, "sodium": 680, "health_score": 60,
41
- "recommendations": ["注意油脂和鈉含量。"],
42
- "warnings": ["高鈉"]
43
- },
44
- {
45
- "food_name": "chicken wings", "chinese_name": "雞翅", "calories": 203, "protein": 18, "fat": 14, "carbs": 0,
46
- "fiber": 0, "sugar": 0, "sodium": 380, "health_score": 70,
47
- "recommendations": ["蛋白質的良好來源。"],
48
- "warnings": []
49
- },
50
- {
51
- "food_name": "salad", "chinese_name": "沙拉", "calories": 33, "protein": 3, "fat": 0.2, "carbs": 6,
52
- "fiber": 3, "sugar": 3, "sodium": 65, "health_score": 95,
53
- "recommendations": ["低熱量高纖維,是健康的選擇。"],
54
- "warnings": []
55
- }
56
- ]
57
-
58
- for food_data in mock_nutrition_data:
59
- db_item = Nutrition(**food_data)
60
- db.add(db_item)
61
-
62
- db.commit()
63
- print(f"{len(mock_nutrition_data)} items populated.")
64
- else:
65
- print("Nutrition table already contains data. Skipping population.")
66
-
67
- db.close()
68
-
69
  if __name__ == "__main__":
70
- init_db()
 
1
+ from database import engine
2
+ from models.nutrition import Base
3
+ from models.meal_log import Base as MealBase
 
4
 
5
+ def init_database():
6
+ """Initialize database tables"""
7
  print("Creating database tables...")
 
8
  Base.metadata.create_all(bind=engine)
9
+ MealBase.metadata.create_all(bind=engine)
10
  print("Database tables created successfully!")
11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  if __name__ == "__main__":
13
+ init_database()
main.py CHANGED
@@ -206,5 +206,5 @@ def generate_warnings(nutrition: Dict[str, Any]) -> List[str]:
206
  return warnings
207
 
208
  if __name__ == "__main__":
209
- # It's better to run with `uvicorn backend.main:app --reload` from the project root.
210
- uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
 
206
  return warnings
207
 
208
  if __name__ == "__main__":
209
+ # For Hugging Face Spaces deployment
210
+ uvicorn.run("main:app", host="0.0.0.0", port=7860, reload=False)
services/nutrition_api_service.py CHANGED
@@ -12,7 +12,7 @@ logger = logging.getLogger(__name__)
12
  load_dotenv()
13
 
14
  # 從環境變數中獲取 API 金鑰
15
- USDA_API_KEY = os.getenv("USDA_API_KEY", "DEMO_KEY")
16
  USDA_API_URL = "https://api.nal.usda.gov/fdc/v1/foods/search"
17
 
18
  # 我們關心的主要營養素及其在 USDA API 中的名稱或編號
@@ -35,7 +35,7 @@ def fetch_nutrition_data(food_name: str):
35
  :return: 包含營養資訊的字典,如果找不到則返回 None。
36
  """
37
  if not USDA_API_KEY:
38
- logger.error("USDA_API_KEY 未設定,無法查詢營養資訊。")
39
  return None
40
 
41
  params = {
 
12
  load_dotenv()
13
 
14
  # 從環境變數中獲取 API 金鑰
15
+ USDA_API_KEY = os.getenv("USDA_API_KEY")
16
  USDA_API_URL = "https://api.nal.usda.gov/fdc/v1/foods/search"
17
 
18
  # 我們關心的主要營養素及其在 USDA API 中的名稱或編號
 
35
  :return: 包含營養資訊的字典,如果找不到則返回 None。
36
  """
37
  if not USDA_API_KEY:
38
+ logger.error("USDA_API_KEY 未設定,無法查詢營養資訊。請在環境變數中設定 USDA_API_KEY")
39
  return None
40
 
41
  params = {