Spaces:
Sleeping
Sleeping
Update main.py
Browse files328 unmodified lines3293303313323333343353363373383393403413423432 unmodified lines346347348349350351352353698 unmodified lines10521053105410551056105731 unmodified lines10891090109110921093109410951096109710981099110046 unmodified lines1147114811491150115111521153108 unmodified lines1262126312641265126612671268589 unmodified lines185818591860186118621863186485 unmodified lines195019511952195319541955195671 unmodified lines2028202920302031203220332034203520362037203820392040328 unmodified lineselse:_groq_client = Groq(api_key=GROQ_API_KEY)def call_llm(prompt: str, max_tokens: int = 2500) -> str:"""LLM abstraction β tries Groq 70B first, falls back to 8B.Docs say: 'Abstract the LLM call behind an interface so if Groq diesyou swap one line of code, not the whole backend.'"""if not _groq_client:raise RuntimeError("GROQ_API_KEY not configured")for model in ["llama-3.3-70b-versatile", "llama-3.1-8b-instant"]:try:comp = _groq_client.chat.completions.create(model=model,2 unmodified linesmax_tokens=max_tokens,response_format={"type": "json_object"},)return comp.choices[0].message.contentexcept Exception as exc:logger.warning("LLM model %s failed: %s β trying next", model, exc)raise RuntimeError("All LLM models failed")698 unmodified linescached_result["scan_meta"] = scan_checkreturn JSONResponse(cached_result)# ββ Step 5: Web search βββββββββββββββββββββββββββββββββββββββweb_context = await asyncio.to_thread(get_live_search, f"health analysis ingredients {extracted_text[:120]}")31 unmodified linesblur_context = (f"IMAGE NOTE: scan was {blur_info['severity']}ly blurry ({verb}). "f"Only include nutrient values you can identify with confidence.")prompt = f"""[INST]You are an expert nutritional scientist and food safety auditor.CRITICAL: Respond ENTIRELY in {lang_name}. Every text field value must be in {lang_name}.Persona: {persona} | Age: {age_group} | Category: {product_category}{confidence_note}{blur_context}Label Text: "{extracted_text}"Web Context: "{web_context}"46 unmodified lines[/INST]"""# ββ Step 8: LLM call (via abstraction layer) βββββββββββββββββraw_json = await asyncio.to_thread(call_llm, prompt, 2500)result = json.loads(raw_json)# ββ Step 8.5: OpenFoodFacts Validation (P0 fix from PDP Framework) βββ108 unmodified lines@app.get("/health")async def health():return {"status": "ok", "version": APP_VERSION}@app.get("/scan-status")589 unmodified linesf"Respond in {lang_name} as valid JSON: product_name, score(1-10), verdict, "f"summary, nutrient_breakdown, pros, cons, age_warnings, better_alternative. [/INST]")try:raw = await asyncio.to_thread(call_llm, prompt, 2000)result = json.loads(raw)result["disclaimer"] = MEDICAL_DISCLAIMER85 unmodified lines[/INST]"""try:raw = await asyncio.to_thread(call_llm, prompt, 1500)result = json.loads(raw)result["disclaimer"] = MEDICAL_DISCLAIMERresult["is_voice_log"] = True71 unmodified linesweb_ctx = get_live_search(f"health ingredients {ocr_r['text'][:80]}")prompt = (f"5 bullet WhatsApp health summary of: \"{ocr_r['text'][:400]}\". "f"Start with score /10. Web: {web_ctx}")summary = await asyncio.to_thread(lambda: _groq_client.chat.completions.create(model="llama-3.1-8b-instant",messages=[{"role":"user","content":prompt}],temperature=0.1, max_tokens=400).choices[0].message.content.strip())msg.body(f"π *Eatlytic Analysis*\n\n{summary}\n\n"f"_{MEDICAL_DISCLAIMER[:80]}_\n_Full: eatlytic.com_")except Exception as exc:328 unmodified lines3293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653662 unmodified lines369370371372373374375376377378379380381382383384698 unmodified lines1083108410851086108710881089109010911092109310941095109610971098109911001101110231 unmodified lines1134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115646 unmodified lines1203120412051206120712081209108 unmodified lines131813191320132113221323132413251326132713281329133013311332133313341335589 unmodified lines192519261927192819291930193185 unmodified lines201720182019202020212022202371 unmodified lines20952096209720982099210021012102210321042105210621072108210921102111211221132114328 unmodified lineselse:_groq_client = Groq(api_key=GROQ_API_KEY)# ββ Cost-aware LLM pipeline (ECC: cost-aware-llm-pipeline skill) ββββββ# Route calls by task complexity to minimise cost without sacrificing# quality on high-stakes analyses.## TASK COMPLEXITY TIERS:# high β full nutrition analysis (70B β best accuracy)# medium β voice meal parse, B2B quick analysis (70B, lower max_tokens)# low β WhatsApp summary, simple tasks (8B β fast + cheap)## Token usage is tracked in _llm_token_budget (in-memory, resets on restart).# Expose via /health for monitoring._LLM_MODELS = {"high" : "llama-3.3-70b-versatile","medium": "llama-3.3-70b-versatile","low" : "llama-3.1-8b-instant",}_llm_token_budget: dict = {"prompt": 0, "completion": 0, "calls": 0, "errors": 0}def call_llm(prompt: str, max_tokens: int = 2500, complexity: str = "high") -> str:"""Cost-aware LLM abstraction.complexity: "high" | "medium" | "low"Falls back one tier on rate-limit / model error.Tracks token spend in _llm_token_budget."""if not _groq_client:raise RuntimeError("GROQ_API_KEY not configured")primary = _LLM_MODELS.get(complexity, _LLM_MODELS["high"])fallback = _LLM_MODELS["low"]models = [primary] if primary == fallback else [primary, fallback]for model in models:try:comp = _groq_client.chat.completions.create(model=model,2 unmodified linesmax_tokens=max_tokens,response_format={"type": "json_object"},)usage = getattr(comp, "usage", None)if usage:_llm_token_budget["prompt"] += getattr(usage, "prompt_tokens", 0)_llm_token_budget["completion"] += getattr(usage, "completion_tokens", 0)_llm_token_budget["calls"] += 1if model != primary:logger.info("LLM routed to fallback %s (primary=%s)", model, primary)return comp.choices[0].message.contentexcept Exception as exc:_llm_token_budget["errors"] += 1logger.warning("LLM model %s failed: %s β trying next", model, exc)raise RuntimeError("All LLM models failed")698 unmodified linescached_result["scan_meta"] = scan_checkreturn JSONResponse(cached_result)# ββ Step 4.5: Search-First β OpenFoodFacts pre-check ββββββββ# ECC search-first skill: look up structured data BEFORE burning# expensive LLM tokens. If OFF returns a confident match we use its# nutrient values as ground truth and skip the full 70B prompt,# falling back to a cheaper summary-only call instead.off_prefetch = await asyncio.to_thread(validate_with_openfoodfacts, "", extracted_text)off_nutrients_prefetch = {}if off_prefetch and off_prefetch.get("found"):off_nutrients_prefetch = off_prefetch.get("nutrients", {})logger.info("search-first: OFF match found for '%s' β nutrients pre-loaded",off_prefetch.get("product_name", "?"))# ββ Step 5: Web search βββββββββββββββββββββββββββββββββββββββweb_context = await asyncio.to_thread(get_live_search, f"health analysis ingredients {extracted_text[:120]}")31 unmodified linesblur_context = (f"IMAGE NOTE: scan was {blur_info['severity']}ly blurry ({verb}). "f"Only include nutrient values you can identify with confidence.")# Inject pre-fetched OFF nutrients as ground truth to reduce hallucinationoff_context = ""if off_nutrients_prefetch:off_lines = ", ".join(f"{k}: {round(v, 1)}" for k, v in off_nutrients_prefetch.items()if v and k in ("calories", "protein", "carbs", "fat", "sodium", "fiber", "sugar"))off_context = (f"VERIFIED NUTRIENT DATA (OpenFoodFacts β use as ground truth, "f"override label if discrepant): {off_lines}")prompt = f"""[INST]You are an expert nutritional scientist and food safety auditor.CRITICAL: Respond ENTIRELY in {lang_name}. Every text field value must be in {lang_name}.Persona: {persona} | Age: {age_group} | Category: {product_category}{confidence_note}{blur_context}{off_context}Label Text: "{extracted_text}"Web Context: "{web_context}"46 unmodified lines[/INST]"""# ββ Step 8: LLM call (via abstraction layer) βββββββββββββββββraw_json = await asyncio.to_thread(call_llm, prompt, 2500, "high")result = json.loads(raw_json)# ββ Step 8.5: OpenFoodFacts Validation (P0 fix from PDP Framework) βββ108 unmodified lines@app.get("/health")async def health():"""Health check + live cost/usage metrics for monitoring."""return {"status" : "ok","version": APP_VERSION,"llm_usage": {"calls" : _llm_token_budget["calls"],"prompt_tokens" : _llm_token_budget["prompt"],"completion_tokens": _llm_token_budget["completion"],"total_tokens" : _llm_token_budget["prompt"] + _llm_token_budget["completion"],"errors" : _llm_token_budget["errors"],},}@app.get("/scan-status")589 unmodified linesf"Respond in {lang_name} as valid JSON: product_name, score(1-10), verdict, "f"summary, nutrient_breakdown, pros, cons, age_warnings, better_alternative. [/INST]")try:raw = await asyncio.to_thread(call_llm, prompt, 2000, "medium")result = json.loads(raw)result["disclaimer"] = MEDICAL_DISCLAIMER85 unmodified lines[/INST]"""try:raw = await asyncio.to_thread(call_llm, prompt, 1500, "medium")result = json.loads(raw)result["disclaimer"] = MEDICAL_DISCLAIMERresult["is_voice_log"] = True71 unmodified linesweb_ctx = get_live_search(f"health ingredients {ocr_r['text'][:80]}")prompt = (f"5 bullet WhatsApp health summary of: \"{ocr_r['text'][:400]}\". "f"Start with score /10. Web: {web_ctx}")# WhatsApp summaries are low-complexity β use cheap 8B modeldef _wa_llm(p):comp = _groq_client.chat.completions.create(model=_LLM_MODELS["low"],messages=[{"role": "user", "content": p}],temperature=0.1, max_tokens=400)usage = getattr(comp, "usage", None)if usage:_llm_token_budget["prompt"] += getattr(usage, "prompt_tokens", 0)_llm_token_budget["completion"] += getattr(usage, "completion_tokens", 0)_llm_token_budget["calls"] += 1return comp.choices[0].message.content.strip()summary = await asyncio.to_thread(_wa_llm, prompt)msg.body(f"π *Eatlytic Analysis*\n\n{summary}\n\n"f"_{MEDICAL_DISCLAIMER[:80]}_\n_Full: eatlytic.com_")except Exception as exc:
main.py+89-15