Ritesh-hf commited on
Commit
3746b33
·
1 Parent(s): 99490d9
Files changed (2) hide show
  1. app.py +378 -49
  2. requirements.txt +2 -1
app.py CHANGED
@@ -20,38 +20,39 @@ import spaces
20
  from langchain_core.output_parsers import StrOutputParser
21
  from langchain_core.prompts import ChatPromptTemplate
22
  from langchain_groq import ChatGroq
 
 
 
 
 
 
 
23
 
24
 
25
  # GROQ_API_KEY = os.getenv("GROQ_API_KEY")
26
- GROQ_API_KEY = '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'
 
 
 
 
 
 
27
  os.environ["GROQ_API_KEY"] = GROQ_API_KEY
 
 
 
28
 
29
  # Initialize LLM
30
  llm = ChatGroq(model="llama-3.1-8b-instant", temperature=0, max_tokens=1024, max_retries=2)
31
 
32
- # QA system prompt and chain
33
- qa_system_prompt = """
34
- Prompt:
35
- You are a highly intelligent assistant. Use the following context to answer user questions. Analyze the data carefully and generate a clear, concise, and informative response to the user's question based on this data.
36
-
37
- Response Guidelines:
38
- - Use only the information provided in the data to answer the question.
39
- - Ensure the answer is accurate and directly related to the question.
40
- - If the data is insufficient to answer the question, politey apologise and tell the user that there is insufficient data available to answer their question.
41
- - Provide the response in a conversational yet professional tone.
42
-
43
- Context:
44
- {context}
45
- """
46
- qa_prompt = ChatPromptTemplate.from_messages(
47
- [
48
- ("system", qa_system_prompt),
49
- ("human", "{input}")
50
- ]
51
- )
52
 
53
- question_answer_chain = qa_prompt | llm | StrOutputParser()
 
54
 
 
 
55
 
56
  class StoppingCriteriaSub(StoppingCriteria):
57
 
@@ -63,7 +64,7 @@ class StoppingCriteriaSub(StoppingCriteria):
63
  for stop in self.stops:
64
  if torch.all(input_ids[:, -len(stop):] == stop).item():
65
  return True
66
-
67
  return False
68
 
69
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
@@ -99,7 +100,6 @@ def get_blip_config(model="base"):
99
 
100
  return config
101
 
102
-
103
  print("Creating model")
104
  config = get_blip_config("large")
105
 
@@ -121,16 +121,15 @@ print("="*50)
121
  transform = transform_test(384)
122
 
123
  print("Loading Data")
124
- df = pd.read_json("datasets/sidechef/my_recipes.json")
125
 
126
  print("Loading Target Embedding")
127
  tar_img_feats = []
128
  for _id in df["id_"].tolist():
129
- tar_img_feats.append(torch.load("datasets/sidechef/blip-embs-large/{:07d}.pth".format(_id)).unsqueeze(0))
130
 
131
  tar_img_feats = torch.cat(tar_img_feats, dim=0)
132
 
133
-
134
  class Chat:
135
 
136
  def __init__(self, model, transform, dataframe, tar_img_feats, device='cuda:0', stopping_criteria=None):
@@ -174,28 +173,358 @@ chat = Chat(model,transform,df,tar_img_feats, device)
174
  print("Chat Initialized !")
175
 
176
 
177
- custom_css = """
178
- .primary{
179
- background-color: #4CAF50; /* Green */
180
- }
181
- """
182
-
183
- @spaces.GPU
184
- def respond_to_user(image, message):
185
- # Process the image and message here
186
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
187
- chat = Chat(model,transform,df,tar_img_feats, device)
188
- chat.encode_image(image)
189
- data = chat.ask()
190
- formated_input = {
191
- 'input': message,
192
- 'context': data
193
- }
194
- try:
195
- response = question_answer_chain.invoke(formated_input)
196
- except Exception as e:
197
- response = {'content':"An error occurred while processing your request."}
198
- return response, data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199
 
200
  iface = gr.Interface(
201
  fn=respond_to_user,
 
20
  from langchain_core.output_parsers import StrOutputParser
21
  from langchain_core.prompts import ChatPromptTemplate
22
  from langchain_groq import ChatGroq
23
+ from langchain_community.chat_message_histories import ChatMessageHistory
24
+ from langchain_core.runnables import RunnableWithMessageHistory
25
+ from langchain_core.output_parsers import StrOutputParser
26
+
27
+ from dotenv import load_dotenv
28
+
29
+ from openai import OpenAI
30
 
31
 
32
  # GROQ_API_KEY = os.getenv("GROQ_API_KEY")
33
+ load_dotenv(".env")
34
+ USER_AGENT = os.getenv("USER_AGENT")
35
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY")
36
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
37
+
38
+ # Set environment variables
39
+ os.environ['USER_AGENT'] = USER_AGENT
40
  os.environ["GROQ_API_KEY"] = GROQ_API_KEY
41
+ os.environ['OPENAI_API_KEY'] = OPENAI_API_KEY
42
+ os.environ["TOKENIZERS_PARALLELISM"] = 'true'
43
+
44
 
45
  # Initialize LLM
46
  llm = ChatGroq(model="llama-3.1-8b-instant", temperature=0, max_tokens=1024, max_retries=2)
47
 
48
+ # Initialize Router
49
+ router = ChatGroq(model="llama-3.2-3b-preview", temperature=0, max_tokens=1024, max_retries=2, model_kwargs={"response_format": {"type": "json_object"}})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
51
+ # Initialize Router
52
+ answer_formatter = ChatGroq(model="llama-3.1-8b-instant", temperature=0, max_tokens=1024, max_retries=2)
53
 
54
+ # Initialized recommendation LLM
55
+ client = OpenAI()
56
 
57
  class StoppingCriteriaSub(StoppingCriteria):
58
 
 
64
  for stop in self.stops:
65
  if torch.all(input_ids[:, -len(stop):] == stop).item():
66
  return True
67
+
68
  return False
69
 
70
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
 
100
 
101
  return config
102
 
 
103
  print("Creating model")
104
  config = get_blip_config("large")
105
 
 
121
  transform = transform_test(384)
122
 
123
  print("Loading Data")
124
+ df = pd.read_json("my_recipes.json")
125
 
126
  print("Loading Target Embedding")
127
  tar_img_feats = []
128
  for _id in df["id_"].tolist():
129
+ tar_img_feats.append(torch.load("./datasets/sidechef/blip-embs-large/{:07d}.pth".format(_id)).unsqueeze(0))
130
 
131
  tar_img_feats = torch.cat(tar_img_feats, dim=0)
132
 
 
133
  class Chat:
134
 
135
  def __init__(self, model, transform, dataframe, tar_img_feats, device='cuda:0', stopping_criteria=None):
 
173
  print("Chat Initialized !")
174
 
175
 
176
+ def answer_generator(formated_input, session_id):
177
+ # QA system prompt and chain
178
+ qa_system_prompt = """
179
+ You are an AI assistant developed by Nutrigenics AI, specializing in intelligent recipe information retrieval and recipe suggestions. Your purpose is to help users by recommending recipes, providing detailed nutritional values, listing ingredients, offering step-by-step cooking instructions, and filtering recipes based on provide context ans user query.
180
+ Operational Guidelines:
181
+ 1. Input Structure:
182
+ - Context: You may receive contextual information related to recipes, such as specific data sets, user preferences, dietary restrictions, or previously selected dishes.
183
+ - User Query: Users will pose questions or requests related to recipes, nutritional information, ingredient substitutions, cooking instructions, and more.
184
+ 2. Response Strategy:
185
+ - Utilize Provided Context: If the context contains relevant information that addresses the user's query, base your response on this provided data to ensure accuracy and relevance.
186
+ - Respond to User Query Directly: If the context does not contain the necessary information to answer the user's query, kindly state that you do not have require information.
187
+ Core Functionalities:
188
+ - Nutritional Information: Accurately provide nutritional values for each recipe, including calories, macronutrients (proteins, fats, carbohydrates), and essential vitamins and minerals, using contextual data when available.
189
+ - Ingredient Details: List all ingredients required for recipes, including substitute options for dietary restrictions or ingredient availability, utilizing context when relevant.
190
+ - Step-by-Step Cooking Instructions: Deliver clear, easy-to-follow instructions for preparing and cooking meals, informed by any provided contextual data.
191
+ - Recipe Recommendations: Suggest dishes based on user preferences, dietary restrictions, available ingredients, and contextual data if provided.
192
+ Additional Instructions:
193
+ - Precision and Personalization: Always aim to provide precise, personalized, and relevant information to users based on both the provided context and their specific queries.
194
+ - Clarity and Coherence: Ensure that all responses are clear, well-structured, and easy to understand, facilitating a seamless user experience.
195
+ - Substitute Suggestions: When suggesting ingredient substitutes, consider user preferences and dietary restrictions outlined in the context or user query.
196
+ - Dynamic Adaptation: Adapt your responses dynamically based on whether the context is relevant to the user's current request, ensuring optimal use of available information.
197
+ Don't mention about context in the response, format the answer in a natural and friendly way.
198
+ Context:
199
+ {context}
200
+ """
201
+ qa_prompt = ChatPromptTemplate.from_messages(
202
+ [
203
+ ("system", qa_system_prompt),
204
+ ("human", "{input}")
205
+ ]
206
+ )
207
+
208
+ # Create the base chain
209
+ base_chain = qa_prompt | llm | StrOutputParser()
210
+
211
+ # Wrap the chain with message history
212
+ question_answer_chain = RunnableWithMessageHistory(
213
+ base_chain,
214
+ lambda session_id: ChatMessageHistory(), # This creates a new history for each session
215
+ input_messages_key="input",
216
+ history_messages_key="chat_history"
217
+ )
218
+
219
+ response = question_answer_chain.invoke(formated_input, config={"configurable": {"session_id": session_id}})
220
+
221
+ return response
222
+
223
+
224
+
225
+ ### Router
226
+ import json
227
+ from langchain_core.messages import HumanMessage, SystemMessage
228
+
229
+ def router_node(query):
230
+ # Prompt
231
+ router_instructions = """You are an expert at determining the appropriate task for a user’s question based on chat history and the current query context. You have two available tasks:
232
+
233
+ 1. Retrieval: Fetch information based on user's chat history and current query.
234
+ 2. Recommendation/Suggestion: Recommend recipes to users based on the query.
235
+
236
+ Return a JSON response with a single key named “task” indicating either “retrieval” or “recommendation” based on your decision.
237
+ """
238
+ response = router.invoke(
239
+ [SystemMessage(content=router_instructions)]
240
+ + [
241
+ HumanMessage(
242
+ content=query
243
+ )
244
+ ]
245
+ )
246
+ res = json.loads(response.content)
247
+ return res['task']
248
+
249
+ def recommendation_node(query):
250
+ prompt = """
251
+ You are a helpful assistant that writes Python code to filter recipes from a JSON filr based o the user query. \n
252
+ JSON file path = 'recipes.json' \n
253
+ The JSON file is a list of recipes with the following structure: \n
254
+ {
255
+ "recipe_name": string,
256
+ "recipe_time": integer,
257
+ "recipe_yields": string,
258
+ "recipe_ingredients": list of ingredients,
259
+ "recipe_instructions": list of instruections,
260
+ "recipe_image": string,
261
+ "blogger": string,
262
+ "recipe_nutrients": JSON object with key value pairs such as "protein: 10g",
263
+ "tags": list of tags related to recipe
264
+ } \n
265
+
266
+ Here is the example of an recipe json object from the JSON data: \n
267
+ {
268
+ "recipe_name": "Asian Potato Salad with Seven Minute Egg",
269
+ "recipe_time": 0,
270
+ "recipe_yields": "4 servings",
271
+ "recipe_ingredients": [
272
+ "2 1/2 cup Multi-Colored Fingerling Potato",
273
+ "3/4 cup Celery",
274
+ "1/4 cup Red Onion",
275
+ "2 tablespoon Fresh Parsley",
276
+ "1/3 cup Mayonnaise",
277
+ "1 tablespoon Chili Garlic Sauce",
278
+ "1 teaspoon Hoisin Sauce",
279
+ "1 splash Soy Sauce",
280
+ "to taste Salt",
281
+ "to taste Ground Black Pepper",
282
+ "4 Egg"
283
+ ],
284
+ "recipe_instructions": "Fill a large stock pot with water.\nAdd the Multi-Colored Fingerling Potato (2 1/2 cup) and bring water to a boil. Boil the potatoes for 20 minutes or until fork tender.\nDrain the potatoes and let them cool completely.\nMeanwhile, mix together in a small bowl Mayonnaise (1/3 cup), Chili Garlic Sauce (1 tablespoon), Hoisin Sauce (1 teaspoon), and Soy Sauce (1 splash).\nTo make the Egg (4), fill a stock pot with water and bring to a boil Gently add the eggs to the water and set a timer for seven minutes.\nThen move the eggs to an ice bath to cool completely. Once cooled, crack the egg slightly and remove the shell. Slice in half when ready to serve.\nNext, halve the cooled potatoes and place into a large serving bowl. Add the Ground Black Pepper (to taste), Celery (3/4 cup), Red Onion (1/4 cup), and mayo mixture. Toss to combine adding Salt (to taste) and Fresh Parsley (2 tablespoon).\nTop with seven minute eggs and serve. Enjoy!",
285
+ "recipe_image": "https://www.sidechef.com/recipe/eeeeeceb-493e-493d-8273-66c800821b13.jpg?d=1408x1120",
286
+ "blogger": "sidechef.com",
287
+ "recipe_nutrients": {
288
+ "calories": "80 calories",
289
+ "proteinContent": "2.1 g",
290
+ "fatContent": "6.2 g",
291
+ "carbohydrateContent": "3.9 g",
292
+ "fiberContent": "0.5 g",
293
+ "sugarContent": "0.4 g",
294
+ "sodiumContent": "108.0 mg",
295
+ "saturatedFatContent": "1.2 g",
296
+ "transFatContent": "0.0 g",
297
+ "cholesterolContent": "47.4 mg",
298
+ "unsaturatedFatContent": "3.8 g"
299
+ },
300
+ "tags": [
301
+ "Salad",
302
+ "Lunch",
303
+ "Brunch",
304
+ "Appetizers",
305
+ "Side Dish",
306
+ "Budget-Friendly",
307
+ "Vegetarian",
308
+ "Pescatarian",
309
+ "Eggs",
310
+ "Potatoes",
311
+ "Dairy-Free",
312
+ "Shellfish-Free"
313
+ ]
314
+ } \n
315
+
316
+ Based on the user query, provide a Python function to filter the JSON data. The output of the function should be a list of json objects. \n
317
+
318
+ Recipe filtering instructions:
319
+ - If a user asked for the highest nutrient recipe such as "high protein or high calories" then filtered recipes should be the top highest recipes from all the recipes with high nutrient.
320
+ - sort or rearrange recipes based which recipes are more appropriate for the user.
321
+
322
+ Your output instructions:
323
+ - The function name should be filter_recipes. The input to the function should be file name.
324
+ - The length of output recipes should not be more than 6.
325
+ - Only give me output function. Do not call the function.
326
+ - Give the python function as a key named "code" in a json format.
327
+ - Do not include any other text with the output, only give python code.
328
+ - If you do not follow the above given instructions, the chat may be terminated.
329
+ """
330
+ max_tries = 3
331
+ while True:
332
+ try:
333
+ # llm = ChatGroq(model="llama-3.1-8b-instant", temperature=0, max_tokens=1024, max_retries=2, model_kwargs={"response_format": {"type": "json_object"}})
334
+ response = client.chat.completions.create(
335
+ model="gpt-4o-mini",
336
+ messages=[
337
+ {"role": "system", "content": prompt},
338
+ {
339
+ "role": "user",
340
+ "content": query
341
+ }
342
+ ]
343
+ )
344
+
345
+ content = response.choices[0].message.content
346
+
347
+ res = json.loads(content)
348
+ script = res['code']
349
+ exec(script, globals())
350
+ filtered_recipes = filter_recipes('recipes.json')
351
+ if len(filtered_recipes) > 0:
352
+ return filtered_recipes
353
+ except Exception as e:
354
+ print(e)
355
+ if max_tries <= 0:
356
+ return []
357
+ else:
358
+ max_tries -= 1
359
+ return filtered_recipes
360
+
361
+
362
+ def answer_formatter_node(question, context):
363
+ prompt = f""" You are an highly clever question-answering assistant trained to provide clear and concise answers based on the user query and provided context.
364
+ Your task is to generated answers for the user query based on the context provided.
365
+ Instructions for your response:
366
+ 1. Directly answer the user query using only the information provided in the context.
367
+ 2. Ensure your response is clear and concise.
368
+ 3. Mention only details related to the recipe, including the recipe name, instructions, nutrients, yield, ingredients, and image.
369
+ 4. Do not include any information that is not related to the recipe context.
370
+
371
+ Please format an answer based on the following user question and context provided:
372
+
373
+ User Question:
374
+ {question}
375
+
376
+ Context:
377
+ {context}
378
+ """
379
+ response = answer_formatter.invoke(
380
+ [SystemMessage(content=prompt)]
381
+ )
382
+ res = response.content
383
+ return res
384
+
385
+ CURR_CONTEXT = ''
386
+
387
+ # @spaces.GPU
388
+ def get_answer(image=[], message='', sessionID='abc123'):
389
+ global CURR_CONTEXT
390
+ if len(image) > 0:
391
+ try:
392
+ # Process the image and message here
393
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
394
+ chat = Chat(model,transform,df,tar_img_feats, device)
395
+ chat.encode_image(image)
396
+ data = chat.ask()
397
+ CURR_CONTEXT = data
398
+ formated_input = {
399
+ 'input': message,
400
+ 'context': data
401
+ }
402
+ response = answer_generator(formated_input, session_id=sessionID)
403
+ except Exception as e:
404
+ print(e)
405
+ response = {'content':"An error occurred while processing your request."}
406
+ elif len(image) == 0 and message is not None:
407
+ print("I am here")
408
+ task = router_node(message)
409
+ if task == 'retrieval':
410
+ recipes = recommendation_node(message)
411
+ if not recipes:
412
+ response = {'content':"An error occurred while processing your request."}
413
+ response = answer_formatter_node(message, recipes)
414
+ else:
415
+ formated_input = {
416
+ 'input': message,
417
+ 'context': CURR_CONTEXT
418
+ }
419
+ response = answer_generator(formated_input, session_id=sessionID)
420
+
421
+ return response
422
+
423
+ import json
424
+ import base64
425
+ from PIL import Image
426
+ from io import BytesIO
427
+ import torchvision.transforms as transforms
428
+
429
+ # Dictionary to store incomplete image data by session
430
+ session_store = {}
431
+
432
+ def handle_message(data):
433
+ global session_store
434
+ global CURR_CONTEXT
435
+ context = "No data available"
436
+ session_id = request.sid
437
+ if session_id not in session_store:
438
+ session_store[session_id] = {'image_data': b"", 'message': None, 'image_received': False}
439
+
440
+ if 'message' in data:
441
+ session_store[session_id]['message'] = data['message']
442
+
443
+ # Handle image chunk data
444
+ if 'image' in data:
445
+ try:
446
+ # Append the incoming image chunk
447
+ session_store[session_id]['image_data'] += data['image']
448
+
449
+ except Exception as e:
450
+ print(f"Error processing image chunk: {str(e)}")
451
+ return
452
+
453
+ if session_store[session_id]['image_data'] or session_store[session_id]['message']:
454
+ try:
455
+ image_bytes = session_store[session_id]['image_data']
456
+ # print("checkpoint 2")
457
+ if isinstance(image_bytes, str):
458
+ image_bytes = base64.b64decode(image_bytes)
459
+ image = Image.open(BytesIO(image_bytes))
460
+ image_array = np.array(image)
461
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
462
+ chat = Chat(model, transform, df, tar_img_feats, device)
463
+ chat.encode_image(image_array)
464
+ context = chat.ask()
465
+ CURR_CONTEXT = context
466
+ message = data['message']
467
+ formated_input = {
468
+ 'input': message,
469
+ 'context': json.dumps(context)
470
+ }
471
+ # Invoke question_answer_chain and stream the response
472
+ response = answer_generator(formated_input, session_id=session_id)
473
+
474
+ except Exception as e:
475
+ print(f"Error processing image or message: {str(e)}")
476
+ return
477
+ finally:
478
+ # Clear session data after processing
479
+ session_store.pop(session_id, None)
480
+ else:
481
+ message = data['message']
482
+ task = router_node(message)
483
+ print(task)
484
+ if task == 'retrieval':
485
+ formated_input = {
486
+ 'input': message,
487
+ 'context': json.dumps(CURR_CONTEXT)
488
+ }
489
+ response = answer_generator(formated_input, session_id=session_id)
490
+ else:
491
+ response = recommendation_node(message)
492
+ # response = answer_formatter_node(message, recipes)
493
+ if response is None:
494
+ response = {'content':"An error occurred while processing your request."}
495
+
496
+ session_store.pop(session_id, None)
497
+
498
+
499
+
500
+ import requests
501
+ from PIL import Image
502
+ import numpy as np
503
+ from io import BytesIO
504
+
505
+ def download_image_to_numpy(url):
506
+ # Send a GET request to the URL to download the image
507
+ response = requests.get(url)
508
+
509
+ # Check if the request was successful
510
+ if response.status_code == 200:
511
+ # Open the image using PIL and convert it to RGB format
512
+ image = Image.open(BytesIO(response.content)).convert('RGB')
513
+
514
+ # Convert the image to a NumPy array
515
+ image_array = np.array(image)
516
+
517
+ return image_array
518
+ else:
519
+ raise Exception(f"Failed to download image. Status code: {response.status_code}")
520
+
521
+ def handle_message(data):
522
+ img_url = data['img_url']
523
+ message = data['message']
524
+ image_array = download_image_to_numpy(img_url)
525
+ response = get_answer(image=image_array, message=message)
526
+ return response
527
+
528
 
529
  iface = gr.Interface(
530
  fn=respond_to_user,
requirements.txt CHANGED
@@ -1,5 +1,5 @@
1
- pytorch_lightning
2
  hydra-core
 
3
  lightning
4
  einops
5
  pandas
@@ -12,3 +12,4 @@ gradio
12
  langchain
13
  langchain-community
14
  langchain-groq
 
 
 
1
  hydra-core
2
+ pytorch_lightning
3
  lightning
4
  einops
5
  pandas
 
12
  langchain
13
  langchain-community
14
  langchain-groq
15
+ openai