main.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. import json
  2. import logging
  3. import httpx
  4. import bcrypt
  5. from contextlib import asynccontextmanager
  6. from fastapi import FastAPI, HTTPException, Depends, Header
  7. from database import create_tables, create_user, get_user_by_username, create_session, get_user_from_token, delete_session, search_foods_by_name, save_chat_message, get_user_chat_history, get_user_profile, get_food_by_id, get_foods_by_ids
  8. from fastapi.responses import HTMLResponse, StreamingResponse
  9. from fastapi.staticfiles import StaticFiles
  10. from pydantic import BaseModel
  11. from typing import List, Generator, Optional
  12. logging.basicConfig(level=logging.INFO)
  13. logger = logging.getLogger(__name__)
  14. @asynccontextmanager
  15. async def lifespan(app: FastAPI):
  16. create_tables()
  17. yield
  18. app = FastAPI(title="LocalFoodAI Chat", lifespan=lifespan)
  19. # Use direct bcrypt for better environment compatibility
  20. def get_password_hash(password: str):
  21. # Hash requires bytes
  22. pwd_bytes = password.encode('utf-8')
  23. salt = bcrypt.gensalt()
  24. hashed = bcrypt.hashpw(pwd_bytes, salt)
  25. return hashed.decode('utf-8')
  26. def verify_password(plain_password: str, hashed_password: str):
  27. # bcrypt.checkpw handles verification
  28. return bcrypt.checkpw(plain_password.encode('utf-8'), hashed_password.encode('utf-8'))
  29. class UserCreate(BaseModel):
  30. username: str
  31. password: str
  32. class UserLogin(BaseModel):
  33. username: str
  34. password: str
  35. async def get_current_user(authorization: Optional[str] = Header(None)):
  36. if not authorization or not authorization.startswith("Bearer "):
  37. raise HTTPException(status_code=401, detail="Authentication required")
  38. token = authorization.split(" ")[1]
  39. user = get_user_from_token(token)
  40. if not user:
  41. raise HTTPException(status_code=401, detail="Invalid or expired session")
  42. return user
  43. OLLAMA_URL = "http://localhost:11434/api/chat"
  44. MODEL_NAME = "llama3.1:8b"
  45. # Common stopwords to strip before searching the food database
  46. _STOPWORDS = {
  47. 'how', 'many', 'much', 'calories', 'does', 'have', 'has', 'is', 'are',
  48. 'in', 'the', 'a', 'an', 'of', 'for', 'with', 'what', 'tell', 'me',
  49. 'about', 'nutritional', 'value', 'nutrition', 'macro', 'macros',
  50. 'protein', 'fat', 'carbs', 'fiber', 'can', 'you', 'i', 'want', 'need',
  51. 'eat', 'eating', 'food', 'meal', 'diet', 'healthy', 'make', 'cook',
  52. 'recipe', 'per', '100g', 'gram', 'grams', 'serving'
  53. }
  54. def extract_food_context(messages: list) -> str | None:
  55. """Scan the last user message for food keywords and enrich with local DB data."""
  56. # Find the last user message
  57. last_user_msg = None
  58. for msg in reversed(messages):
  59. role = msg.get('role', '') if isinstance(msg, dict) else msg.role
  60. content = msg.get('content', '') if isinstance(msg, dict) else msg.content
  61. if role == 'user':
  62. last_user_msg = content
  63. break
  64. if not last_user_msg:
  65. return None
  66. # Extract meaningful keywords by removing stopwords
  67. words = last_user_msg.lower().replace('?', '').replace(',', '').split()
  68. keywords = [w for w in words if w not in _STOPWORDS and len(w) > 2]
  69. if not keywords:
  70. return None
  71. # Try each keyword against the local food database, collect unique results
  72. found_items = {}
  73. # Optimization: Only use the first 2 most relevant keywords to keep context small on CPU
  74. for kw in keywords[:2]:
  75. results = search_foods_by_name(kw, limit=2)
  76. for item in results:
  77. # Truncate extremely long USDA names for performance
  78. short_name = item['name'][:100] + ("..." if len(item['name']) > 100 else "")
  79. if short_name not in found_items:
  80. found_items[short_name] = item
  81. if len(found_items) >= 3:
  82. break
  83. if not found_items:
  84. return None
  85. # Build a structured context block for the system prompt
  86. lines = [
  87. "[SYSTEM: NUTRITIONAL ANALYST MODE]",
  88. "You are the LocalFoodAI Analyst. Use ONLY verified local data for values.",
  89. "For each food discussed, you MUST follow this structure:",
  90. "1. Header: ### 🥗 [Name] (per 100g)",
  91. "2. Macros: A markdown table for Cal, P, F, C, Fib, Sug, Chol.",
  92. "3. Micros: A bulleted list for Na, Ca, Fe, K, VitA, VitC.",
  93. "4. Insight: A 1-sentence analysis of the food's nutritional profile.",
  94. "Always prioritize local data over training memory. If a nutrient is missing, say 'Data not available'.",
  95. ""
  96. ]
  97. for name, item in found_items.items():
  98. # Compact, token-efficient format for the LLM
  99. line = (
  100. f"- {name}: {item['calories']}kcal | P:{item['protein_g']}g | F:{item['fat_g']}g | C:{item['carbs_g']}g | "
  101. f"Fib:{item['fiber_g']}g | Sug:{item['sugar_g']}g | Chol:{item['cholesterol_mg']}mg | "
  102. f"Na:{item['sodium_mg']}mg | Ca:{item['calcium_mg']}mg | Fe:{item['iron_mg']}mg | "
  103. f"K:{item['potassium_mg']}mg | VitA:{item['vitamin_a_iu']}IU | VitC:{item['vitamin_c_mg']}mg"
  104. )
  105. lines.append(line)
  106. return "\n".join(lines)
  107. # Mount static files to serve the frontend
  108. app.mount("/static", StaticFiles(directory="static"), name="static")
  109. class ChatMessage(BaseModel):
  110. role: str
  111. content: str
  112. class ChatRequest(BaseModel):
  113. messages: List[ChatMessage]
  114. class MealItemInput(BaseModel):
  115. food_id: int
  116. amount_g: float
  117. class MealCalculateRequest(BaseModel):
  118. items: List[MealItemInput]
  119. @app.get("/", response_class=HTMLResponse)
  120. async def read_root():
  121. """Serve the chat interface HTML"""
  122. try:
  123. with open("static/index.html", "r", encoding="utf-8") as f:
  124. return HTMLResponse(content=f.read())
  125. except FileNotFoundError:
  126. return HTMLResponse(content="<h1>Welcome to LocalFoodAI</h1><p>static/index.html not found. Please create the frontend.</p>")
  127. @app.post("/api/register")
  128. async def register_user(user: UserCreate):
  129. if len(user.username.strip()) < 3:
  130. raise HTTPException(status_code=400, detail="Username must be at least 3 characters")
  131. if len(user.password.strip()) < 6:
  132. raise HTTPException(status_code=400, detail="Password must be at least 6 characters")
  133. hashed_password = get_password_hash(user.password)
  134. user_id = create_user(user.username.strip(), hashed_password)
  135. if not user_id:
  136. raise HTTPException(status_code=400, detail="Username already exists")
  137. # Auto-login after registration
  138. token = create_session(user_id)
  139. return {"message": "User registered successfully", "token": token, "username": user.username.strip()}
  140. @app.post("/api/login")
  141. async def login_user(user: UserLogin):
  142. db_user = get_user_by_username(user.username.strip())
  143. if not db_user:
  144. raise HTTPException(status_code=401, detail="Invalid username or password")
  145. if not verify_password(user.password, db_user["password_hash"]):
  146. raise HTTPException(status_code=401, detail="Invalid username or password")
  147. token = create_session(db_user["id"])
  148. return {"status": "success", "username": db_user["username"], "token": token}
  149. @app.post("/api/logout")
  150. async def logout(authorization: Optional[str] = Header(None)):
  151. if authorization and authorization.startswith("Bearer "):
  152. token = authorization.split(" ")[1]
  153. delete_session(token)
  154. return {"message": "Logged out successfully"}
  155. @app.get("/api/macros/targets")
  156. async def get_macro_targets(current_user: dict = Depends(get_current_user)):
  157. """API endpoint to securely fetch the user's current macronutrient targets"""
  158. profile = get_user_profile(current_user['id'])
  159. if not profile:
  160. # Fallback to defaults in case database insertion failed
  161. return {
  162. "calories": 2000,
  163. "protein_g": 150,
  164. "carbs_g": 200,
  165. "fat_g": 65
  166. }
  167. return {
  168. "calories": profile.get("target_calories", 2000),
  169. "protein_g": profile.get("target_protein_g", 150),
  170. "carbs_g": profile.get("target_carbs_g", 200),
  171. "fat_g": profile.get("target_fat_g", 65)
  172. }
  173. @app.post("/chat")
  174. async def chat_endpoint(request: ChatRequest, current_user: dict = Depends(get_current_user)):
  175. """Proxy chat requests to the local Ollama instance with streaming support.
  176. Automatically enriches prompts with verified local SQLite nutritional data.
  177. """
  178. # Keep only the last 6 messages for context window performance on CPU
  179. all_messages = [msg.model_dump() for msg in request.messages]
  180. messages = all_messages[-6:]
  181. # Save the latest user message to DB
  182. if messages and messages[-1]['role'] == 'user':
  183. save_chat_message(current_user['id'], 'user', messages[-1]['content'])
  184. # --- TG-35: Local SQL RAG Enrichment ---
  185. db_context = extract_food_context(messages)
  186. if db_context:
  187. # Prepend as a system message so it acts as grounded knowledge
  188. # We ensure it's a short, concise instruction to prevent context bloat
  189. messages = [{"role": "system", "content": db_context}] + messages
  190. logger.info(f"[Chat] User '{current_user['username']}' is chatting. Context items: {'Yes' if db_context else 'No'}. Message count: {len(messages)}")
  191. payload = {
  192. "model": MODEL_NAME,
  193. "messages": messages,
  194. "stream": True
  195. }
  196. async def generate_response():
  197. try:
  198. bot_full_response = ""
  199. async with httpx.AsyncClient(timeout=300.0) as client:
  200. # Use a combined timeout for the entire request
  201. async with client.stream("POST", OLLAMA_URL, json=payload, timeout=300.0) as response:
  202. if response.status_code != 200:
  203. error_detail = await response.aread()
  204. logger.error(f"Ollama returned error {response.status_code}: {error_detail}")
  205. yield f"data: {json.dumps({'error': f'LLM Error ({response.status_code})'})}\n\n"
  206. return
  207. async for line in response.aiter_lines():
  208. if line:
  209. try:
  210. data = json.loads(line)
  211. if "message" in data and "content" in data["message"]:
  212. content = data["message"]["content"]
  213. bot_full_response += content
  214. yield f"data: {json.dumps({'content': content})}\n\n"
  215. if data.get("done"):
  216. break
  217. except json.JSONDecodeError:
  218. continue
  219. # Save final bot response to DB
  220. if bot_full_response.strip():
  221. save_chat_message(current_user['id'], 'assistant', bot_full_response)
  222. except Exception as e:
  223. logger.exception(f"Unexpected error during chat stream: {e}")
  224. yield f"data: {json.dumps({'error': 'A technical error occurred while generating the response.'})}\n\n"
  225. return StreamingResponse(generate_response(), media_type="text/event-stream")
  226. @app.get("/api/chat/history")
  227. async def get_history(current_user: dict = Depends(get_current_user)):
  228. """Fetch the chat history for the authenticated user"""
  229. history = get_user_chat_history(current_user['id'])
  230. return {"history": history}
  231. @app.get("/api/food/search")
  232. async def search_food(q: str, current_user: dict = Depends(get_current_user)):
  233. """API endpoint to search for food items securely using token authentication"""
  234. if not q or len(q.strip()) < 1:
  235. return {"results": []}
  236. logger.info(f"User {current_user['username']} searched for [{q}]")
  237. results = search_foods_by_name(q.strip(), limit=15)
  238. return {"results": results}
  239. @app.get("/api/food/{food_id}")
  240. async def get_food_detail(food_id: int, current_user: dict = Depends(get_current_user)):
  241. """API endpoint to fetch structured nutritional details for a specific food item"""
  242. food = get_food_by_id(food_id)
  243. if not food:
  244. raise HTTPException(status_code=404, detail="Food item not found")
  245. # Structure the data as proposed in the implementation plan
  246. structured_data = {
  247. "id": food["id"],
  248. "name": food["name"],
  249. "category": food["category"],
  250. "base_weight_g": food["base_weight_g"],
  251. "macros": {
  252. "calories": food["calories"],
  253. "protein_g": food["protein_g"],
  254. "fat_g": food["fat_g"],
  255. "carbs_g": food["carbs_g"]
  256. },
  257. "extended": {
  258. "fiber_g": food["fiber_g"],
  259. "sugar_g": food["sugar_g"],
  260. "cholesterol_mg": food["cholesterol_mg"]
  261. },
  262. "vitamins": {
  263. "vitamin_a_iu": food["vitamin_a_iu"],
  264. "vitamin_c_mg": food["vitamin_c_mg"]
  265. },
  266. "minerals": {
  267. "calcium_mg": food["calcium_mg"],
  268. "iron_mg": food["iron_mg"],
  269. "potassium_mg": food["potassium_mg"],
  270. "sodium_mg": food["sodium_mg"]
  271. },
  272. "source": food["source"]
  273. }
  274. return structured_data
  275. @app.post("/api/meal/calculate")
  276. async def calculate_meal(request: MealCalculateRequest, current_user: dict = Depends(get_current_user)):
  277. """Calculate the total nutritional value for a combined list of foods and their custom weights."""
  278. if not request.items:
  279. return {"error": "Meal is empty"}
  280. # Validation: Cast to floats and ensure > 0
  281. items = []
  282. for item in request.items:
  283. try:
  284. amount = float(item.amount_g)
  285. if amount <= 0:
  286. raise HTTPException(status_code=400, detail="Quantity must be greater than 0g for all items.")
  287. items.append({"food_id": item.food_id, "amount_g": amount})
  288. except ValueError:
  289. raise HTTPException(status_code=400, detail=f"Invalid amount for food ID {item.food_id}")
  290. # Bulk fetch from DB
  291. requested_ids = list(set(item["food_id"] for item in items))
  292. foods_data = get_foods_by_ids(requested_ids)
  293. # Map for easy lookup
  294. foods_map = {food["id"]: food for food in foods_data}
  295. # Fail-fast: Check if all requested IDs exist
  296. found_ids = set(foods_map.keys())
  297. missing_ids = [fid for fid in requested_ids if fid not in found_ids]
  298. if missing_ids:
  299. raise HTTPException(status_code=400, detail=f"Invalid food IDs provided: {missing_ids}")
  300. # Initialize aggregator
  301. totals = {
  302. "total_weight_g": 0.0,
  303. "macros": {"calories": 0.0, "protein_g": 0.0, "fat_g": 0.0, "carbs_g": 0.0},
  304. "extended": {"fiber_g": 0.0, "sugar_g": 0.0, "cholesterol_mg": 0.0},
  305. "vitamins": {"vitamin_a_iu": 0.0, "vitamin_c_mg": 0.0},
  306. "minerals": {"calcium_mg": 0.0, "iron_mg": 0.0, "potassium_mg": 0.0, "sodium_mg": 0.0}
  307. }
  308. def safe_val(val):
  309. return float(val) if val is not None else 0.0
  310. for item in items:
  311. food = foods_map[item["food_id"]]
  312. ratio = item["amount_g"] / 100.0
  313. totals["total_weight_g"] += item["amount_g"]
  314. totals["macros"]["calories"] += safe_val(food.get("calories")) * ratio
  315. totals["macros"]["protein_g"] += safe_val(food.get("protein_g")) * ratio
  316. totals["macros"]["fat_g"] += safe_val(food.get("fat_g")) * ratio
  317. totals["macros"]["carbs_g"] += safe_val(food.get("carbs_g")) * ratio
  318. totals["extended"]["fiber_g"] += safe_val(food.get("fiber_g")) * ratio
  319. totals["extended"]["sugar_g"] += safe_val(food.get("sugar_g")) * ratio
  320. totals["extended"]["cholesterol_mg"] += safe_val(food.get("cholesterol_mg")) * ratio
  321. totals["vitamins"]["vitamin_a_iu"] += safe_val(food.get("vitamin_a_iu")) * ratio
  322. totals["vitamins"]["vitamin_c_mg"] += safe_val(food.get("vitamin_c_mg")) * ratio
  323. totals["minerals"]["calcium_mg"] += safe_val(food.get("calcium_mg")) * ratio
  324. totals["minerals"]["iron_mg"] += safe_val(food.get("iron_mg")) * ratio
  325. totals["minerals"]["potassium_mg"] += safe_val(food.get("potassium_mg")) * ratio
  326. totals["minerals"]["sodium_mg"] += safe_val(food.get("sodium_mg")) * ratio
  327. # Rounding to 2 decimal places
  328. totals["total_weight_g"] = round(totals["total_weight_g"], 2)
  329. for category in ["macros", "extended", "vitamins", "minerals"]:
  330. for key in totals[category]:
  331. totals[category][key] = round(totals[category][key], 2)
  332. return totals
  333. if __name__ == "__main__":
  334. import uvicorn
  335. uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True)