-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
367 lines (294 loc) · 9.94 KB
/
main.py
File metadata and controls
367 lines (294 loc) · 9.94 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
from fastapi import FastAPI, UploadFile, File
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from typing import List
from dotenv import load_dotenv
import os
import json
import re
from groq import Groq
import google.generativeai as genai
# --------------------------------------------------
# ENV + APP SETUP
# --------------------------------------------------
load_dotenv()
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # hackathon friendly
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# --------------------------------------------------
# CLIENTS
# --------------------------------------------------
groq_client = Groq(api_key=os.getenv("GROQ_API_KEY"))
genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
vision_model = genai.GenerativeModel("gemini-2.5-flash-lite")
# --------------------------------------------------
# MODELS
# --------------------------------------------------
class RecipeRequest(BaseModel):
ingredients: List[str]
diet: str
cuisine: str
count: int
class RecommendRequest(BaseModel):
goal: str
diet: str
cuisine: str
count: int
class FusionRequest(BaseModel):
base_dish: str
target_cuisine: str
# --------------------------------------------------
# COMMON PROMPT (SINGLE SOURCE OF TRUTH)
# --------------------------------------------------
def build_recipe_prompt(context: str) -> str:
return f"""
You are a professional chef and certified nutrition expert.
Context:
{context}
STRICT RULES (DO NOT BREAK):
- You MAY use basic cooking essentials (oil, salt, spices, water)
- Mention such items explicitly as extra ingredients
- Do NOT invent rare or fancy ingredients
- Recipe must be realistic and cookable at home
- Minimum 4 clear cooking steps
- Dish MUST have a proper name
Nutrition rules:
- Nutrition values must be PER ONE SERVING / ONE PLATE
- Provide calories, protein, carbs, and fat
- Values must be realistic (not exaggerated)
Return ONLY valid JSON.
No markdown. No explanation.
JSON format:
{{
"recipe_name": "",
"serving_size": "1 plate",
"nutrition": {{
"calories_kcal": 0,
"protein_g": 0,
"carbs_g": 0,
"fat_g": 0
}},
"ingredients": [
{{
"item": "",
"quantity": ""
}}
],
"steps": [
""
]
}}
"""
# --------------------------------------------------
# RECIPE GENERATION (PIC2PLATE)
# --------------------------------------------------
@app.post("/generate-recipes")
def generate_recipes(data: RecipeRequest):
count = min(max(data.count, 1), 5)
recipes: List[dict] = []
for i in range(count):
context = f"""
Main ingredients: {', '.join(data.ingredients)}
Diet preference: {data.diet}
Cuisine preference: {data.cuisine}
"""
prompt = build_recipe_prompt(context)
try:
response = groq_client.chat.completions.create(
model="llama-3.1-8b-instant",
messages=[{"role": "user", "content": prompt}],
temperature=0.35
)
raw = response.choices[0].message.content.strip()
raw = raw.replace("```json", "").replace("```", "").strip()
match = re.search(r"\{[\s\S]*\}", raw)
if not match:
raise ValueError("No JSON found")
recipe = json.loads(match.group())
recipes.append(recipe)
except Exception as e:
print("⚠️ Recipe generation error:", e)
recipes.append({
"recipe_name": "Cheesy Potato Bread Fritters",
"serving_size": "1 plate",
"nutrition": {
"calories_kcal": 420,
"protein_g": 14,
"carbs_g": 48,
"fat_g": 18
},
"ingredients": [
{"item": "Bread", "quantity": "1 cup, cubed"},
{"item": "Potato", "quantity": "1 medium, grated"},
{"item": "Cheese", "quantity": "1/2 cup, shredded"},
{"item": "Butter", "quantity": "2 tbsp"},
{"item": "Oil", "quantity": "1 tbsp"},
{"item": "Salt", "quantity": "to taste"},
{"item": "Black pepper", "quantity": "to taste"}
],
"steps": [
"Mix bread, grated potato, and cheese in a bowl.",
"Season with salt and pepper.",
"Heat oil and butter in a pan over medium heat.",
"Shape mixture into fritters and cook until golden on both sides."
]
})
return JSONResponse(content={"recipes": recipes})
# --------------------------------------------------
# INGREDIENT IDENTIFICATION (VISION)
# --------------------------------------------------
@app.post("/identify-ingredients")
async def identify_ingredients(image: UploadFile = File(...)):
try:
image_bytes = await image.read()
prompt = """
List all food ingredients visible in this image.
Return ONLY a comma-separated list.
Do NOT explain.
"""
response = vision_model.generate_content([
prompt,
{
"mime_type": image.content_type,
"data": image_bytes
}
])
raw = response.text.strip()
print("👁️ VISION RAW OUTPUT:", raw)
ingredients = [
item.strip().lower()
for item in raw.split(",")
if item.strip()
]
return {"ingredients": ingredients}
except Exception as e:
print("❌ Vision error:", e)
return {"ingredients": []}
# --------------------------------------------------
# RECOMMENDATION ENGINE
# --------------------------------------------------
@app.post("/recommend-recipes")
def recommend_recipes(data: RecommendRequest):
context = f"""
User goal: {data.goal}
Diet preference: {data.diet}
Cuisine preference: {data.cuisine}
Generate {data.count} recipes.
"""
prompt = f"""
You are a professional dietician and chef.
User goal: {data.goal}
Diet preference: {data.diet}
Cuisine preference: {data.cuisine}
STRICT RULES (DO NOT BREAK):
- Recipes MUST strictly satisfy the goal
- If goal is "High Protein", protein must be high (>= 35g per plate)
- If goal is "Weight Loss", calories must be low (< 500 kcal)
- If goal is "Diabetic", avoid high-carb ingredients
- Diet and cuisine preferences must be respected
- You MAY use basic cooking essentials (oil, salt, spices)
- Ingredients must have proper quantities
- Steps must be detailed (minimum 4)
Generate exactly {data.count} recipes.
Return ONLY valid JSON.
No markdown. No explanation.
JSON format:
{{
"recipes": [
{{
"recipe_name": "",
"serving_size": "1 plate",
"nutrition": {{
"calories_kcal": 0,
"protein_g": 0,
"carbs_g": 0,
"fat_g": 0
}},
"ingredients": [
{{
"item": "",
"quantity": ""
}}
],
"steps": [
""
]
}}
]
}}
"""
try:
response = groq_client.chat.completions.create(
model="llama-3.1-8b-instant",
messages=[{"role": "user", "content": prompt}],
temperature=0.3
)
raw = response.choices[0].message.content.strip()
raw = raw.replace("```json", "").replace("```", "").strip()
match = re.search(r"\{[\s\S]*\}", raw)
if not match:
raise ValueError("Invalid JSON")
return JSONResponse(content=json.loads(match.group()))
except Exception as e:
print("Recommendation error:", e)
return {
"recipes": [
{
"recipe_name": f"{data.goal} Healthy Meal",
"serving_size": "1 plate",
"calories_per_serving": 350,
"ingredients": [],
"steps": [
"Prepare fresh ingredients.",
"Cook using minimal oil.",
"Serve warm."
]
}
]
}
# --------------------------------------------------
# FUSION LAB
# --------------------------------------------------
@app.post("/fusion-recipe")
def generate_fusion_recipe(data: FusionRequest):
context = f"""
Base dish: {data.base_dish}
Target cuisine: {data.target_cuisine}
Reimagine the dish as a fusion recipe.
"""
prompt = build_recipe_prompt(context)
try:
response = groq_client.chat.completions.create(
model="llama-3.1-8b-instant",
messages=[{"role": "user", "content": prompt}],
temperature=0.4
)
raw = response.choices[0].message.content.strip()
raw = raw.replace("```json", "").replace("```", "").strip()
match = re.search(r"\{[\s\S]*\}", raw)
if not match:
raise ValueError("Invalid JSON")
return JSONResponse(content={"recipes": [json.loads(match.group())]})
except Exception as e:
print("Fusion error:", e)
return {
"recipes": [
{
"recipe_name": f"{data.target_cuisine} Style {data.base_dish}",
"serving_size": "1 plate",
"calories_per_serving": 450,
"ingredients": [],
"steps": [
"Adapt base dish using target cuisine techniques.",
"Cook carefully to balance flavors.",
"Serve hot."
]
}
]
}