Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -8,7 +8,6 @@ import cv2
|
|
| 8 |
import numpy as np
|
| 9 |
from PIL import Image
|
| 10 |
from io import BytesIO
|
| 11 |
-
from functools import lru_cache
|
| 12 |
from fastapi import FastAPI, File, UploadFile, Form, Request
|
| 13 |
from fastapi.middleware.cors import CORSMiddleware
|
| 14 |
from fastapi.responses import FileResponse
|
|
@@ -18,128 +17,132 @@ from slowapi import Limiter, _rate_limit_exceeded_handler
|
|
| 18 |
from slowapi.util import get_remote_address
|
| 19 |
from slowapi.errors import RateLimitExceeded
|
| 20 |
|
| 21 |
-
# --- CONFIGURATION ---
|
| 22 |
logging.basicConfig(level=logging.INFO)
|
| 23 |
logger = logging.getLogger(__name__)
|
| 24 |
|
| 25 |
-
#
|
| 26 |
limiter = Limiter(key_func=get_remote_address)
|
| 27 |
-
app = FastAPI(title="Eatlytic:
|
| 28 |
app.state.limiter = limiter
|
| 29 |
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
|
| 30 |
-
|
| 31 |
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
|
| 32 |
|
| 33 |
-
#
|
| 34 |
CACHE_DIR = os.environ.get("HF_HOME", "/app/.cache")
|
| 35 |
MODEL_DIR = os.path.join(CACHE_DIR, "easyocr_models")
|
|
|
|
|
|
|
| 36 |
if not os.path.exists(MODEL_DIR): os.makedirs(MODEL_DIR)
|
|
|
|
| 37 |
|
| 38 |
-
#
|
| 39 |
-
|
|
|
|
| 40 |
|
| 41 |
-
|
| 42 |
-
if
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
-
|
|
|
|
| 51 |
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
img.thumbnail((800, 800)) # Optimize size for speed
|
| 58 |
-
img_np = np.array(img)
|
| 59 |
-
|
| 60 |
-
# Blur check inside cache logic to save compute
|
| 61 |
-
gray = cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)
|
| 62 |
-
if cv2.Laplacian(gray, cv2.CV_64F).var() < 100:
|
| 63 |
-
return "BLURRY_ERROR"
|
| 64 |
-
|
| 65 |
-
return " ".join(reader.readtext(img_np, detail=0))
|
| 66 |
-
except Exception as e:
|
| 67 |
-
return str(e)
|
| 68 |
|
| 69 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
try:
|
| 71 |
with DDGS() as ddgs:
|
| 72 |
results = [f"{r['title']}: {r['body']}" for r in ddgs.text(query, max_results=2)]
|
| 73 |
return "\n".join(results)
|
| 74 |
except: return "No web data."
|
| 75 |
|
| 76 |
-
# --- API ENDPOINTS ---
|
| 77 |
-
|
| 78 |
@app.get("/")
|
| 79 |
async def home(): return FileResponse('index.html')
|
| 80 |
|
| 81 |
@app.post("/analyze")
|
| 82 |
-
@limiter.limit("
|
| 83 |
async def analyze_product(
|
| 84 |
request: Request,
|
| 85 |
persona: str = Form(...),
|
|
|
|
| 86 |
image: UploadFile = File(...)
|
| 87 |
):
|
| 88 |
-
|
| 89 |
-
if not client:
|
| 90 |
-
return {"error": "Server Error: GROQ_API_KEY is missing in Settings."}
|
| 91 |
-
|
| 92 |
-
# ... rest of your existing code ...
|
| 93 |
|
| 94 |
try:
|
| 95 |
-
#
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
# Get OCR Result (Cached)
|
| 100 |
-
extracted_text = cached_ocr(image_hash, content)
|
| 101 |
-
|
| 102 |
-
if extracted_text == "BLURRY_ERROR":
|
| 103 |
-
return {"error": "Image is too blurry. Please hold steady!"}
|
| 104 |
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
|
| 134 |
-
try:
|
| 135 |
completion = client.chat.completions.create(
|
| 136 |
model="llama-3.1-70b-versatile",
|
| 137 |
messages=[{"role": "user", "content": prompt}],
|
| 138 |
temperature=0.1,
|
| 139 |
max_tokens=1000,
|
| 140 |
-
response_format={"type": "json_object"}
|
| 141 |
)
|
| 142 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
except Exception as e:
|
| 144 |
-
logger.error(f"
|
| 145 |
-
return {"error": "
|
|
|
|
| 8 |
import numpy as np
|
| 9 |
from PIL import Image
|
| 10 |
from io import BytesIO
|
|
|
|
| 11 |
from fastapi import FastAPI, File, UploadFile, Form, Request
|
| 12 |
from fastapi.middleware.cors import CORSMiddleware
|
| 13 |
from fastapi.responses import FileResponse
|
|
|
|
| 17 |
from slowapi.util import get_remote_address
|
| 18 |
from slowapi.errors import RateLimitExceeded
|
| 19 |
|
|
|
|
| 20 |
logging.basicConfig(level=logging.INFO)
|
| 21 |
logger = logging.getLogger(__name__)
|
| 22 |
|
| 23 |
+
# --- RATE LIMITER ---
|
| 24 |
limiter = Limiter(key_func=get_remote_address)
|
| 25 |
+
app = FastAPI(title="Eatlytic: Scale")
|
| 26 |
app.state.limiter = limiter
|
| 27 |
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
|
|
|
|
| 28 |
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
|
| 29 |
|
| 30 |
+
# --- PERSISTENT STORAGE ---
|
| 31 |
CACHE_DIR = os.environ.get("HF_HOME", "/app/.cache")
|
| 32 |
MODEL_DIR = os.path.join(CACHE_DIR, "easyocr_models")
|
| 33 |
+
DATA_DIR = "/data" # Persistent storage on HF Spaces
|
| 34 |
+
|
| 35 |
if not os.path.exists(MODEL_DIR): os.makedirs(MODEL_DIR)
|
| 36 |
+
if not os.path.exists(DATA_DIR): os.makedirs(DATA_DIR)
|
| 37 |
|
| 38 |
+
# --- CACHE FUNCTIONS ---
|
| 39 |
+
OCR_CACHE_FILE = os.path.join(DATA_DIR, "ocr_cache.json")
|
| 40 |
+
AI_CACHE_FILE = os.path.join(DATA_DIR, "ai_cache.json")
|
| 41 |
|
| 42 |
+
def load_cache(file_path):
|
| 43 |
+
if os.path.exists(file_path):
|
| 44 |
+
try:
|
| 45 |
+
with open(file_path, "r") as f: return json.load(f)
|
| 46 |
+
except: return {}
|
| 47 |
+
return {}
|
| 48 |
|
| 49 |
+
def save_cache(cache, file_path):
|
| 50 |
+
try:
|
| 51 |
+
with open(file_path, "w") as f: json.dump(cache, f)
|
| 52 |
+
except: pass
|
| 53 |
|
| 54 |
+
ocr_cache = load_cache(OCR_CACHE_FILE)
|
| 55 |
+
ai_cache = load_cache(AI_CACHE_FILE)
|
| 56 |
|
| 57 |
+
# --- INIT ---
|
| 58 |
+
GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
|
| 59 |
+
if not GROQ_API_KEY: logger.warning("⚠️ GROQ_API_KEY missing!")
|
| 60 |
+
client = Groq(api_key=GROQ_API_KEY) if GROQ_API_KEY else None
|
| 61 |
+
reader = easyocr.Reader(['en'], gpu=False, model_storage_directory=MODEL_DIR)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
+
def get_server_ocr(content):
|
| 64 |
+
img_hash = hashlib.md5(content).hexdigest()
|
| 65 |
+
if img_hash in ocr_cache: return ocr_cache[img_hash]
|
| 66 |
+
|
| 67 |
+
img = Image.open(BytesIO(content)).convert("RGB")
|
| 68 |
+
img.thumbnail((800, 800))
|
| 69 |
+
img_np = np.array(img)
|
| 70 |
+
text = " ".join(reader.readtext(img_np, detail=0))
|
| 71 |
+
|
| 72 |
+
ocr_cache[img_hash] = text
|
| 73 |
+
save_cache(ocr_cache, OCR_CACHE_FILE)
|
| 74 |
+
return text
|
| 75 |
+
|
| 76 |
+
def get_live_search(query):
|
| 77 |
try:
|
| 78 |
with DDGS() as ddgs:
|
| 79 |
results = [f"{r['title']}: {r['body']}" for r in ddgs.text(query, max_results=2)]
|
| 80 |
return "\n".join(results)
|
| 81 |
except: return "No web data."
|
| 82 |
|
|
|
|
|
|
|
| 83 |
@app.get("/")
|
| 84 |
async def home(): return FileResponse('index.html')
|
| 85 |
|
| 86 |
@app.post("/analyze")
|
| 87 |
+
@limiter.limit("15/minute")
|
| 88 |
async def analyze_product(
|
| 89 |
request: Request,
|
| 90 |
persona: str = Form(...),
|
| 91 |
+
extracted_text: str = Form(None), # Client OCR text
|
| 92 |
image: UploadFile = File(...)
|
| 93 |
):
|
| 94 |
+
if not client: return {"error": "Server Error: Missing API Key"}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
try:
|
| 97 |
+
# Fallback to Server OCR if client failed
|
| 98 |
+
if not extracted_text:
|
| 99 |
+
content = await image.read()
|
| 100 |
+
extracted_text = get_server_ocr(content)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
+
# Check AI Cache
|
| 103 |
+
cache_key = f"{persona}:{extracted_text[:50]}"
|
| 104 |
+
if cache_key in ai_cache:
|
| 105 |
+
return ai_cache[cache_key]
|
| 106 |
+
|
| 107 |
+
web_context = get_live_search(f"ingredients health analysis {extracted_text[:100]}")
|
| 108 |
+
|
| 109 |
+
prompt = f"""
|
| 110 |
+
[INST] Role: Expert Health Auditor.
|
| 111 |
+
Target Persona: {persona} (Adjust risk tolerance accordingly).
|
| 112 |
+
Label: "{extracted_text}" | Web: "{web_context}"
|
| 113 |
+
|
| 114 |
+
Analyze strictly returning JSON.
|
| 115 |
+
CRITICAL: "chart_data" must be [Safe%, Moderate%, Risky%] summing to 100.
|
| 116 |
+
|
| 117 |
+
{{
|
| 118 |
+
"product_name": "Short Name",
|
| 119 |
+
"score": 1-10,
|
| 120 |
+
"chart_data": [70, 20, 10],
|
| 121 |
+
"verdict": "2-word verdict",
|
| 122 |
+
"summary": "Professional summary (2 sentences).",
|
| 123 |
+
"eli5_explanation": "Explain it simply for a 5-year-old child using emojis.",
|
| 124 |
+
"molecular_insight": "Explain the chemical impact (e.g. Insulin spike).",
|
| 125 |
+
"pros": ["Benefit 1", "Benefit 2"],
|
| 126 |
+
"cons": ["Risk 1", "Risk 2"],
|
| 127 |
+
"better_alternative": "A healthier option."
|
| 128 |
+
}} [/INST]
|
| 129 |
+
"""
|
| 130 |
|
|
|
|
| 131 |
completion = client.chat.completions.create(
|
| 132 |
model="llama-3.1-70b-versatile",
|
| 133 |
messages=[{"role": "user", "content": prompt}],
|
| 134 |
temperature=0.1,
|
| 135 |
max_tokens=1000,
|
| 136 |
+
response_format={"type": "json_object"}
|
| 137 |
)
|
| 138 |
+
result = json.loads(completion.choices[0].message.content)
|
| 139 |
+
|
| 140 |
+
# Save to Cache
|
| 141 |
+
ai_cache[cache_key] = result
|
| 142 |
+
save_cache(ai_cache, AI_CACHE_FILE)
|
| 143 |
+
|
| 144 |
+
return result
|
| 145 |
+
|
| 146 |
except Exception as e:
|
| 147 |
+
logger.error(f"Error: {e}")
|
| 148 |
+
return {"error": "Analysis failed. Please try again."}
|