Spaces:
e
Sleeping

Shaikhsarib commited on
Commit
bf53025
·
verified ·
1 Parent(s): 1e40fc1

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +86 -83
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
- # Setup Rate Limiter (In-Memory, No Redis needed)
26
  limiter = Limiter(key_func=get_remote_address)
27
- app = FastAPI(title="Eatlytic: Startup Scale")
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
- # Setup Cache & Models
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
- # API Keys
39
- GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
 
40
 
41
- # Prevent crash if key is missing
42
- if not GROQ_API_KEY:
43
- logger.warning("⚠️ GROQ_API_KEY missing! App will fail.")
44
- client = None
45
- else:
46
- client = Groq(api_key=GROQ_API_KEY)
47
 
48
- reader = easyocr.Reader(['en'], gpu=False, model_storage_directory=MODEL_DIR)
 
 
 
49
 
50
- # --- OPTIMIZED FUNCTIONS ---
 
51
 
52
- @lru_cache(maxsize=128)
53
- def cached_ocr(image_hash: str, image_bytes: bytes):
54
- """Caches OCR results so re-scanning the same image is instant"""
55
- try:
56
- img = Image.open(BytesIO(image_bytes)).convert("RGB")
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 get_live_search(query: str):
 
 
 
 
 
 
 
 
 
 
 
 
 
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("10/minute")
83
  async def analyze_product(
84
  request: Request,
85
  persona: str = Form(...),
 
86
  image: UploadFile = File(...)
87
  ):
88
- # Safety check
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
- # Read & Hash Image for Caching
96
- content = await image.read()
97
- image_hash = hashlib.md5(content).hexdigest()
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
- except Exception as e: return {"error": f"Processing Failed: {e}"}
106
-
107
- # Live Research
108
- web_context = get_live_search(f"ingredients health facts {extracted_text[:100]}")
109
-
110
- # The "Startup Gold" Prompt
111
- prompt = f"""
112
- Role: Expert Health Auditor.
113
- User Persona: {persona}
114
- Label: "{extracted_text}"
115
- Web Context: "{web_context}"
116
-
117
- Analyze strictly returning JSON.
118
- CRITICAL: "chart_data" must be [Safe%, Moderate%, Risky%] summing to 100.
119
-
120
- {{
121
- "product_name": "Short Name",
122
- "score": 1-10,
123
- "chart_data": [70, 20, 10],
124
- "verdict": "2-word verdict",
125
- "summary": "Professional summary (2 sentences).",
126
- "molecular_insight": "Explain ONE key chemical reaction in the body.",
127
- "eli5_explanation": "Explain for a 5-year old using emojis.",
128
- "pros": ["Benefit 1", "Benefit 2"],
129
- "cons": ["Risk 1", "Risk 2"],
130
- "better_alternative": "A healthier option."
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"} # Groq JSON Mode
141
  )
142
- return json.loads(completion.choices[0].message.content)
 
 
 
 
 
 
 
143
  except Exception as e:
144
- logger.error(f"Groq Error: {e}")
145
- return {"error": "AI is overloaded. Try again in 5s."}
 
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."}