-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlambda_function.py
More file actions
455 lines (369 loc) · 12.6 KB
/
Copy pathlambda_function.py
File metadata and controls
455 lines (369 loc) · 12.6 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
import json
import boto3
import base64
# -------------------------------
# AWS Clients
# -------------------------------
bedrock = boto3.client("bedrock-runtime", region_name="us-west-2")
# -------------------------------
# Extract dishes using Vision
# -------------------------------
def extract_dishes_from_image(image_bytes):
"""
Uses Claude's vision to directly extract dishes from menu image
"""
image_b64 = base64.b64encode(image_bytes).decode('utf-8')
prompt = """Analyze this restaurant menu image and extract all actual food and drink items that customers can order.
INCLUDE:
- Specific dishes (e.g., "Breakfast Sandwich", "Caesar Salad", "Margherita Pizza")
- Beverages (e.g., "Coffee", "Orange Juice", "Coca-Cola")
- Appetizers, entrees, desserts, sides
EXCLUDE:
- Section headers (e.g., "BREAKFAST", "LUNCH", "APPETIZERS")
- Marketing slogans (e.g., "GETS YOU RUNNING")
- Combo deal names (e.g., "COFFEE COMBOS")
- Prices and price modifiers
- Descriptions or ingredients lists
Return ONLY valid JSON with no other text:
{"dishes": ["Item 1", "Item 2", "Item 3"]}"""
body = json.dumps({
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": 2000,
"temperature": 0,
"messages": [{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/jpeg",
"data": image_b64
}
},
{
"type": "text",
"text": prompt
}
]
}]
})
try:
response = bedrock.invoke_model(
modelId="anthropic.claude-3-5-sonnet-20241022-v2:0", # CHANGED: Use Sonnet for vision
body=body,
contentType="application/json",
accept="application/json"
)
result = json.loads(response["body"].read())
text_output = result["content"][0]["text"]
print(f"Dishes extraction response: {text_output}")
# Parse JSON response
text_output = text_output.strip()
if "```json" in text_output:
text_output = text_output.split("```json")[1].split("```")[0]
elif "```" in text_output:
text_output = text_output.split("```")[1].split("```")[0]
text_output = text_output.strip()
parsed = json.loads(text_output)
return parsed.get("dishes", [])
except Exception as e:
print(f"Error extracting dishes: {str(e)}")
import traceback
traceback.print_exc()
return []
'''
# -------------------------------
# Get ingredients for a dish
# -------------------------------
def get_ingredients_json(dish_name):
"""
Gets ingredients for a specific dish
"""
prompt = f"""List the main ingredients needed to prepare "{dish_name}".
Include only the core ingredients (e.g., for "Caesar Salad": romaine lettuce, parmesan cheese, croutons, Caesar dressing, lemon).
Return ONLY valid JSON with no other text:
{{
"dish": "{dish_name}",
"ingredients": ["ingredient1", "ingredient2", "ingredient3"]
}}"""
body = json.dumps({
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": 500,
"temperature": 0,
"messages": [{
"role": "user",
"content": [{"type": "text", "text": prompt}]
}]
})
try:
response = bedrock.invoke_model(
modelId="anthropic.claude-3-haiku-20240307-v1:0", # Haiku is fine for text-only
body=body,
contentType="application/json",
accept="application/json"
)
result = json.loads(response["body"].read())
text_output = result["content"][0]["text"]
print(f"Ingredients for {dish_name}: {text_output}")
# Parse JSON response
text_output = text_output.strip()
if "```json" in text_output:
text_output = text_output.split("```json")[1].split("```")[0]
elif "```" in text_output:
text_output = text_output.split("```")[1].split("```")[0]
text_output = text_output.strip()
return json.loads(text_output)
except Exception as e:
print(f"Error getting ingredients for {dish_name}: {str(e)}")
return {"dish": dish_name, "ingredients": []}
# -------------------------------
# AI → Allergen Safety Analysis
# -------------------------------
def analyze_allergen_safety(dishes_with_ingredients, allergens_to_avoid):
"""
Uses AI to classify dishes as:
- Safe
- Unsafe
- Can be Modified
"""
prompt = f"""
You are a food allergen safety assistant.
User wants to avoid these allergens:
{allergens_to_avoid}
You are given dishes with ingredients.
Classify each dish into ONE of:
SAFE → No allergen present
UNSAFE → Contains allergen
MODIFIABLE → Can remove or substitute allergen
Return ONLY JSON:
{{
"safe": [{{"dish":"name"}}],
"unsafe": [{{"dish":"name","reason":"contains milk"}}],
"modifiable": [{{"dish":"name","suggestion":"remove cheese"}}]
}}
Dishes data:
{json.dumps(dishes_with_ingredients, indent=2)}
"""
body = json.dumps({
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": 1500,
"temperature": 0,
"messages": [
{
"role": "user",
"content": [{"type": "text", "text": prompt}]
}
]
})
response = bedrock.invoke_model(
modelId="anthropic.claude-3-haiku-20240307-v1:0",
body=body,
contentType="application/json",
accept="application/json"
)
result = json.loads(response["body"].read())
text_output = result["content"][0]["text"].strip()
# Remove markdown if present
if "```json" in text_output:
text_output = text_output.split("```json")[1].split("```")[0]
elif "```" in text_output:
text_output = text_output.split("```")[1].split("```")[0]
return json.loads(text_output)
'''
# -------------------------------
# AI → Ingredients + Allergen Safety (Combined)
# -------------------------------
def get_ingredients_and_safety(dish_name, allergens_to_avoid):
"""
Single AI call that returns:
- Ingredients
- Safety classification
"""
prompt = f"""
You are a food allergen safety assistant.
User wants to avoid:
{allergens_to_avoid}
For the dish: "{dish_name}"
Return:
1) Main ingredients
2) Safety classification:
- SAFE
- UNSAFE
- MODIFIABLE
Return ONLY JSON:
{{
"dish": "{dish_name}",
"ingredients": ["ingredient1","ingredient2"],
"safety": {{
"status": "SAFE | UNSAFE | MODIFIABLE",
"reason": "if unsafe",
"suggestion": "if modifiable"
}}
}}
"""
body = json.dumps({
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": 600,
"temperature": 0,
"messages": [{
"role": "user",
"content": [{"type": "text", "text": prompt}]
}]
})
try:
response = bedrock.invoke_model(
modelId="anthropic.claude-3-haiku-20240307-v1:0",
body=body,
contentType="application/json",
accept="application/json"
)
result = json.loads(response["body"].read())
text_output = result["content"][0]["text"].strip()
# Remove markdown if present
if "```json" in text_output:
text_output = text_output.split("```json")[1].split("```")[0]
elif "```" in text_output:
text_output = text_output.split("```")[1].split("```")[0]
return json.loads(text_output)
except Exception as e:
print(f"Error analyzing {dish_name}: {str(e)}")
return {
"dish": dish_name,
"ingredients": [],
"safety": {
"status": "UNKNOWN"
}
}
# -------------------------------
# Lambda Handler
# -------------------------------
def lambda_handler(event, context):
"""
Main Lambda handler
"""
try:
# Parse API Gateway body
if "body" in event:
body = json.loads(event["body"])
else:
body = event
# Validate input
if "image_base64" not in body:
return {
"statusCode": 400,
"body": json.dumps({"error": "Missing image_base64 in request body"})
}
# Decode image
try:
image_bytes = base64.b64decode(body["image_base64"])
except Exception as e:
return {
"statusCode": 400,
"body": json.dumps({"error": f"Invalid base64 image: {str(e)}"})
}
# -------------------------------
# Allergens from POST body
# -------------------------------
try:
allergens_to_avoid = body.get("allergens_to_avoid", [])
if not isinstance(allergens_to_avoid, list):
raise ValueError("allergens_to_avoid must be a list")
allergens_to_avoid = [
a.lower().strip()
for a in allergens_to_avoid
]
print("Allergens received:", allergens_to_avoid)
except Exception as e:
return {
"statusCode": 400,
"body": json.dumps({
"error": "Invalid allergens_to_avoid format",
"details": str(e)
})
}
print(f"Processing image of size: {len(image_bytes)} bytes")
# -------------------------------
# Extract dishes using vision
# -------------------------------
dishes = extract_dishes_from_image(image_bytes)
print(f"Extracted {len(dishes)} dishes: {dishes}")
if not dishes:
return {
"statusCode": 200,
"body": json.dumps({
"message": "No dishes detected in the menu image",
"dishes_detected": [],
"ingredients": []
})
}
# -------------------------------
# Get ingredients for each dish
# -------------------------------
'''ingredients_results = []
for dish in dishes:
ingredients_data = get_ingredients_json(dish)
ingredients_results.append(ingredients_data)'''
ingredients_results = []
for dish in dishes:
data = get_ingredients_and_safety(
dish,
allergens_to_avoid
)
ingredients_results.append(data)
# -------------------------------
# Build Safety Summary (No AI call)
# -------------------------------
safety_results = {
"safe": [],
"unsafe": [],
"modifiable": []
}
for item in ingredients_results:
status = item.get("safety", {}).get("status", "UNKNOWN")
if status == "SAFE":
safety_results["safe"].append({
"dish": item["dish"]
})
elif status == "UNSAFE":
safety_results["unsafe"].append({
"dish": item["dish"],
"reason": item["safety"].get("reason", "")
})
elif status == "MODIFIABLE":
safety_results["modifiable"].append({
"dish": item["dish"],
"suggestion": item["safety"].get("suggestion", "")
})
'''# -------------------------------
# AI Safety Analysis
# -------------------------------
safety_results = analyze_allergen_safety(
ingredients_results,
allergens_to_avoid
)'''
# -------------------------------
# Final Response
# -------------------------------
response_data = {
"dishes_count": len(dishes),
"dishes_detected": dishes,
"ingredients": ingredients_results,
"allergens_to_avoid": allergens_to_avoid,
"safety_analysis": safety_results
}
return {
"statusCode": 200,
"body": json.dumps(response_data, indent=2)
}
except Exception as e:
print(f"Lambda error: {str(e)}")
import traceback
traceback.print_exc()
return {
"statusCode": 500,
"body": json.dumps({
"error": "Internal server error",
"details": str(e)
})
}