Spaces:
Sleeping
Sleeping
File size: 3,114 Bytes
fdc2693 b938416 fdc2693 cb8b92c fdc2693 cb8b92c fdc2693 cb8b92c fdc2693 cb8b92c fdc2693 |
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 |
from datetime import datetime
from typing import List, Dict, Any, Optional
from sqlalchemy.orm import Session
from models.meal_log import MealLog
class MealService:
def __init__(self, db: Session):
self.db = db
def create_meal_log(
self,
food_name: str,
meal_type: str,
portion_size: str,
nutrition: Dict[str, float],
meal_date: datetime,
image_url: Optional[str] = None,
ai_analysis: Optional[Dict[str, Any]] = None
) -> MealLog:
"""ๅตๅปบๆฐ็็จ้ค่จ้"""
meal_log = MealLog(
food_name=food_name,
meal_type=meal_type,
portion_size=portion_size,
calories=float(nutrition.get('calories', 0)),
protein=float(nutrition.get('protein', 0)),
carbs=float(nutrition.get('carbs', 0)),
fat=float(nutrition.get('fat', 0)),
fiber=float(nutrition.get('fiber', 0)),
meal_date=meal_date,
image_url=image_url,
ai_analysis=ai_analysis,
created_at=datetime.utcnow()
)
self.db.add(meal_log)
self.db.commit()
self.db.refresh(meal_log)
return meal_log
def get_meal_logs(
self,
start_date: Optional[datetime] = None,
end_date: Optional[datetime] = None,
meal_type: Optional[str] = None
) -> List[MealLog]:
"""็ฒๅ็จ้ค่จ้"""
query = self.db.query(MealLog)
if start_date:
query = query.filter(MealLog.meal_date >= start_date)
if end_date:
query = query.filter(MealLog.meal_date <= end_date)
if meal_type:
query = query.filter(MealLog.meal_type == meal_type)
return query.order_by(MealLog.meal_date.desc()).all()
def get_nutrition_summary(
self,
start_date: datetime,
end_date: datetime
) -> Dict[str, float]:
"""็ฒๅๆๅฎๆ้็ฏๅๅ
ง็็้คๆๅ
ฅ็ธฝ็ต"""
meals = self.get_meal_logs(start_date, end_date)
summary: Dict[str, float] = {
'total_calories': 0.0,
'total_protein': 0.0,
'total_carbs': 0.0,
'total_fat': 0.0,
'total_fiber': 0.0
}
for meal in meals:
portion_size = getattr(meal, 'portion_size', 'medium')
calories = getattr(meal, 'calories', 0.0)
protein = getattr(meal, 'protein', 0.0)
carbs = getattr(meal, 'carbs', 0.0)
fat = getattr(meal, 'fat', 0.0)
fiber = getattr(meal, 'fiber', 0.0)
multiplier = {
'small': 0.7,
'medium': 1.0,
'large': 1.3
}.get(portion_size, 1.0)
summary['total_calories'] += float(calories) * multiplier
summary['total_protein'] += float(protein) * multiplier
summary['total_carbs'] += float(carbs) * multiplier
summary['total_fat'] += float(fat) * multiplier
summary['total_fiber'] += float(fiber) * multiplier
return summary
|