Hammad712 commited on
Commit
50f57cc
·
verified ·
1 Parent(s): c6d8729

Upload recipe_app(1).py

Browse files
Files changed (1) hide show
  1. recipe_app(1).py +397 -0
recipe_app(1).py ADDED
@@ -0,0 +1,397 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel
2
+ from pymongo import MongoClient
3
+ from urllib.parse import quote_plus
4
+ import uuid
5
+ from typing import List
6
+ import json
7
+ from fastapi import FastAPI, File, UploadFile, HTTPException
8
+ import os
9
+ import base64
10
+ from groq import Groq
11
+ import time
12
+
13
+ api_keys = ['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', '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']
14
+
15
+ # MongoDB connection setup
16
+ def get_mongo_client():
17
+ password = quote_plus("momimaad@123") # Change this to your MongoDB password
18
+ mongo_uri = f"mongodb+srv://hammad:{password}@cluster0.2a9yu.mongodb.net/"
19
+ return MongoClient(mongo_uri)
20
+
21
+ db_client = get_mongo_client()
22
+ db = db_client["recipe"]
23
+ user_collection = db["user_info"]
24
+
25
+ # Pydantic models for user data
26
+ class User(BaseModel):
27
+ first_name: str
28
+ last_name: str
29
+ email: str
30
+ password: str
31
+
32
+ class UserData(BaseModel):
33
+ email: str
34
+ password: str
35
+
36
+ class UserToken(BaseModel):
37
+ token: str
38
+
39
+ class RecipeData(BaseModel):
40
+ name: str
41
+
42
+ class AltrecipeData(BaseModel):
43
+ recipe_name: str
44
+ dietary_restrictions: str
45
+ allergies: List
46
+
47
+ class Ingredient(BaseModel):
48
+ name: str
49
+ quantity: str
50
+
51
+
52
+ class Recipe(BaseModel):
53
+ recipe_name: str
54
+ ingredients: List[Ingredient]
55
+ directions: List[str]
56
+
57
+
58
+ class get_recipe_name(BaseModel):
59
+ recipe_name: List[str]
60
+ ingredients: List[List[str]]
61
+
62
+ # Data model for LLM to generate
63
+ class Alternative_Ingredient(BaseModel):
64
+ name: str
65
+ quantity: str
66
+
67
+ class Alternative_Recipe(BaseModel):
68
+ recipe_name: str
69
+ alternative_ingredients: List[Alternative_Ingredient]
70
+ alternative_directions: List[str]
71
+
72
+ def encode_image(image_path):
73
+ with open(image_path, "rb") as image_file:
74
+ return base64.b64encode(image_file.read()).decode('utf-8')
75
+ class RecipeGenerationError(Exception):
76
+ """Custom exception for recipe generation errors."""
77
+ pass
78
+
79
+ def get_recipe(recipe_name: str) -> Recipe:
80
+
81
+ groq_models = ["llama3-groq-70b-8192-tool-use-preview", "llama-3.1-70b-versatile", "llama3-70b-8192"]
82
+
83
+ for api_key in api_keys:
84
+ try:
85
+ client = Groq(api_key=api_key)
86
+ for groq_model in groq_models:
87
+ try:
88
+ chat_completion = client.chat.completions.create(
89
+ messages=[
90
+ {
91
+ "role": "system",
92
+ "content": f"""Your are an expert agent to generate a recipes with proper and corrected ingredients and direction. Your directions should be concise and to the point and dont explain any irrelevant text.
93
+ You are a recipe database that outputs recipes in JSON.\n
94
+ The JSON object must use the schema: {json.dumps(Recipe.model_json_schema(), indent=2)}""",
95
+ },
96
+ {
97
+ "role": "user",
98
+ "content": f"Fetch a recipe for {recipe_name}",
99
+ },
100
+ ],
101
+ model=groq_model,
102
+ temperature=0,
103
+ # Streaming is not supported in JSON mode
104
+ stream=False,
105
+ # Enable JSON mode by setting the response format
106
+ response_format={"type": "json_object"},
107
+ )
108
+ return Recipe.model_validate_json(chat_completion.choices[0].message.content)
109
+
110
+ except Exception as e:
111
+ time.sleep(2)
112
+ continue
113
+
114
+
115
+ except Exception as e:
116
+ time.sleep(2)
117
+ continue
118
+ raise RecipeGenerationError("Server Error Try after some time.")
119
+
120
+
121
+ def Suggest_ingredient_alternatives(recipe_name: str, dietary_restrictions: str, allergies: List) -> Alternative_Recipe:
122
+ groq_models = ["llama3-groq-70b-8192-tool-use-preview", "llama-3.1-70b-versatile", "llama3-70b-8192"]
123
+
124
+ for api_key in api_keys:
125
+ try:
126
+ client = Groq(api_key=api_key)
127
+
128
+ for groq_model in groq_models:
129
+ try:
130
+ chat_completion = client.chat.completions.create(
131
+ messages=[
132
+ {
133
+ "role": "system",
134
+ "content": f"""
135
+ You are an expert agent to suggest alternatives for specific allergies ingredients for the provided recipe {recipe_name}.
136
+
137
+ Please take the following into account:
138
+ - If the user has dietary restrictions, suggest substitutes that align with their needs (e.g., vegan, gluten-free, etc.) in alternative_directions and your alternative_directions should be concise and to the point.
139
+ -In ingredient you will recommend the safe ingredient for avoid any allergy and dietary restriction.
140
+ - Consider the following allergies {allergies} and recommend the safe ingredient to avoid this allergies.
141
+
142
+ recipe_name: {recipe_name}
143
+ Dietary Restrictions: {dietary_restrictions}
144
+ Allergies: {', '.join(allergies)}
145
+
146
+ You are a recipe database that outputs alternative recipes to avoid allergy and dietary_restrictions in JSON.\n
147
+ The JSON object must use the schema: {json.dumps(Alternative_Recipe.model_json_schema(), indent=2)}""",
148
+ },
149
+ {
150
+ "role": "user",
151
+ "content": f"""Fetch a alternative recipe for recipe_name: {recipe_name}
152
+ Dietary Restrictions: {dietary_restrictions}
153
+ Allergies: {', '.join(allergies)}""",
154
+ },
155
+ ],
156
+ model=groq_model,
157
+ temperature=0,
158
+ # Streaming is not supported in JSON mode
159
+ stream=False,
160
+ # Enable JSON mode by setting the response format
161
+ response_format={"type": "json_object"},
162
+ )
163
+ return Alternative_Recipe.model_validate_json(chat_completion.choices[0].message.content)
164
+ except Exception as e:
165
+ time.sleep(2)
166
+ continue
167
+ except Exception as e:
168
+ time.sleep(2)
169
+ continue
170
+
171
+ raise RecipeGenerationError("Server Error Try after some time.")
172
+
173
+
174
+ def get_explanation(base64_image):
175
+
176
+ api_keys = [
177
+ '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',
178
+ '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',
179
+ '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',
180
+ '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',
181
+ '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'
182
+ ]
183
+
184
+ for api_key in api_keys:
185
+ try:
186
+ client = Groq(api_key=api_key)
187
+ completion = client.chat.completions.create(
188
+ model="llama-3.2-90b-vision-preview",
189
+ messages=[
190
+ {
191
+ "role": "user",
192
+ "content": [
193
+ {
194
+ "type": "text",
195
+ "text": """Explain the following image in detail with the recipes names if it were present in images with expanation of ingredients. If there is one rcipe kindly mention it and if there are many then mention the total number of recipes and also mention their names and i want correct explanation."""
196
+ },
197
+ {
198
+ "type": "image_url",
199
+ "image_url": {
200
+ "url": f"data:image/jpeg;base64,{base64_image}"
201
+ }
202
+ }
203
+ ]
204
+ }
205
+ ],
206
+ temperature=1,
207
+ max_tokens=1024,
208
+ top_p=1,
209
+ stream=False,
210
+ stop=None,
211
+ )
212
+
213
+ return completion.choices[0].message.content
214
+
215
+ except Exception as e:
216
+ time.sleep(2)
217
+ continue
218
+ raise RecipeGenerationError("Server Error Try after some time.")
219
+
220
+
221
+ def generate_recipe_info(context):
222
+ groq_models = ["llama3-groq-70b-8192-tool-use-preview", "llama-3.1-70b-versatile", "llama3-70b-8192"]
223
+ output_format = '''
224
+ Kindly generate the following json output format and iwant this format same to same dont change anything and add irrelevant text
225
+ Generate a output according to json format:
226
+
227
+ {'recipes': [it can be empty if there is no data about recipes in context and it conatin many recipes if there are multiple etc for example
228
+ {'recipe_name': '',
229
+ 'ingredients':[only three to four just or minimum]},
230
+ {'recipe_name': '',
231
+ 'ingredients':[only three to four just or minimum]},
232
+ {'recipe_name': '',
233
+ 'ingredients':[only three to four just or minimum]},
234
+ so on
235
+
236
+ ]
237
+ }
238
+ '''
239
+
240
+ for api_key in api_keys:
241
+ try:
242
+ client = Groq(api_key=api_key)
243
+ for groq_model in groq_models:
244
+ try:
245
+ chat_completion = client.chat.completions.create(
246
+ messages=[
247
+ {
248
+ "role": "user",
249
+ "content": f'''
250
+ Kindly analyze if there is one recipe then mention one recipe in json if multiple then according to it generate a json.
251
+ You are an expert agent to analyze the following context and find out recipes name with proper ingredients and i want the out[ut according to following json format and dont need to change anything.
252
+ JSON OUTPUT FORMAT: {output_format}
253
+ Consider the followng contexto answer to answer
254
+ Context:
255
+ {context}
256
+ ''' + output_format
257
+ }
258
+ ],
259
+ temperature=0,
260
+ # Streaming is not supported in JSON mode
261
+ stream=False,
262
+ # Enable JSON mode by setting the response format
263
+ response_format={"type": "json_object"},
264
+ model=groq_model,
265
+ )
266
+
267
+ return chat_completion.choices[0].message.content
268
+ except Exception as e:
269
+ time.sleep(2)
270
+ continue
271
+
272
+
273
+ except Exception as e:
274
+ time.sleep(2)
275
+ continue
276
+ raise RecipeGenerationError("Server Error Try after some time.")
277
+
278
+
279
+ app = FastAPI()
280
+
281
+ @app.post("/get_recipe/{token}")
282
+ async def get_recipe_response(token: str, recipe_user: RecipeData):
283
+ try:
284
+ user = user_collection.find_one({"token": token})
285
+ if not user:
286
+ raise HTTPException(status_code=401, detail="Invalid token")
287
+
288
+ # Find user by email
289
+ recipe_name = recipe_user.name
290
+ response = get_recipe(recipe_name)
291
+ return {
292
+ "Response": response
293
+ }
294
+ except RecipeGenerationError as e:
295
+ # Return a custom error response if the RecipeGenerationError is raised
296
+ raise HTTPException(status_code=500, detail=str(e))
297
+
298
+
299
+ @app.post("/get_recipe_alternative/{token}")
300
+ async def get_alternative_recipe_response(token: str, altrecipe_user: AltrecipeData):
301
+ try:
302
+ user = user_collection.find_one({"token": token})
303
+ if not user:
304
+ raise HTTPException(status_code=401, detail="Invalid token")
305
+
306
+ response = Suggest_ingredient_alternatives(altrecipe_user.recipe_name, altrecipe_user.dietary_restrictions, altrecipe_user.allergies)
307
+ return {
308
+ "Response": response
309
+ }
310
+ except RecipeGenerationError as e:
311
+ # Return a custom error response if the RecipeGenerationError is raised
312
+ raise HTTPException(status_code=500, detail=str(e))
313
+
314
+
315
+
316
+ # Directory to save uploaded images
317
+ UPLOAD_DIR = "uploads"
318
+
319
+ # Ensure the upload directory exists
320
+ os.makedirs(UPLOAD_DIR, exist_ok=True)
321
+
322
+
323
+ # Endpoint to upload an image
324
+ @app.post("/upload-image/{token}")
325
+ async def upload_image(token: str, file: UploadFile = File(...)):
326
+ try:
327
+
328
+ user = user_collection.find_one({"token": token})
329
+ if not user:
330
+ raise HTTPException(status_code=401, detail="Invalid token")
331
+
332
+ # Validate the file type
333
+ if not file.filename.lower().endswith(('.png', '.jpg', '.jpeg')):
334
+ raise HTTPException(status_code=400, detail="Invalid file type. Only PNG, JPG, and JPEG are allowed.")
335
+
336
+ # Create a file path for saving the uploaded file
337
+ file_path = os.path.join(UPLOAD_DIR, file.filename)
338
+
339
+ # Save the file
340
+ with open(file_path, "wb") as buffer:
341
+ buffer.write(await file.read())
342
+
343
+ base64_image = encode_image(file_path)
344
+ context = get_explanation(base64_image)
345
+ result = generate_recipe_info(context)
346
+ json_result = json.loads(result)
347
+
348
+ return {
349
+ "Response": json_result
350
+ }
351
+ except RecipeGenerationError as e:
352
+ # Return a custom error response if the RecipeGenerationError is raised
353
+ raise HTTPException(status_code=500, detail=str(e))
354
+
355
+
356
+ # Endpoint to register a new user
357
+ @app.post("/register")
358
+ async def register_user(user: User):
359
+ # Check if user already exists
360
+ existing_user = user_collection.find_one({"email": user.email})
361
+ if existing_user:
362
+ raise HTTPException(status_code=400, detail="Email already registered")
363
+
364
+ # Create user data
365
+ user_data = {
366
+ "first_name": user.first_name,
367
+ "last_name": user.last_name,
368
+ "email": user.email,
369
+ "password": user.password, # Store plaintext password (not recommended in production)
370
+ }
371
+
372
+ # Insert the user data into the user_info collection
373
+ result = user_collection.insert_one(user_data)
374
+ return {"msg": "User registered successfully", "user_id": str(result.inserted_id)}
375
+
376
+ # Endpoint to check user credentials and generate a token
377
+ @app.post("/get_token")
378
+ async def check_credentials(user: UserData):
379
+ # Find user by email
380
+ existing_user = user_collection.find_one({"email": user.email})
381
+
382
+ # Check if user exists and password matches
383
+ if not existing_user or existing_user["password"] != user.password:
384
+ raise HTTPException(status_code=401, detail="Invalid email or password")
385
+
386
+ # Generate a UUID token
387
+ token = str(uuid.uuid4())
388
+
389
+ # Update the user document with the token
390
+ user_collection.update_one({"email": user.email}, {"$set": {"token": token}})
391
+
392
+ return {
393
+ "first_name": existing_user["first_name"],
394
+ "last_name": existing_user["last_name"],
395
+ "token": token,
396
+ }
397
+