Ritesh-hf commited on
Commit
5a5ba32
·
1 Parent(s): 28ff4fe
Files changed (2) hide show
  1. .gitignore +4 -1
  2. demo.py +455 -61
.gitignore CHANGED
@@ -11,4 +11,7 @@ bert-base-uncased/
11
  delete*
12
  __pycache__/
13
  env/
14
- .env
 
 
 
 
11
  delete*
12
  __pycache__/
13
  env/
14
+ .env
15
+ demo.ipynb
16
+ demo.py
17
+ test-1.py
demo.py CHANGED
@@ -15,22 +15,24 @@ from src.data.transforms import transform_test
15
 
16
  from transformers import StoppingCriteria, StoppingCriteriaList, TextIteratorStreamer
17
  import gradio as gr
18
- import spaces
19
 
 
 
 
20
  from langchain_core.output_parsers import StrOutputParser
21
  from langchain_core.prompts import ChatPromptTemplate
22
  from langchain_groq import ChatGroq
23
 
24
  from dotenv import load_dotenv
25
- import asyncio
26
  from flask import Flask, request, render_template
27
  from flask_cors import CORS
28
- from flask_socketio import SocketIO, emit, join_room, leave_room
29
 
30
 
31
  # GROQ_API_KEY = os.getenv("GROQ_API_KEY")
32
  GROQ_API_KEY = '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'
33
- load_dotenv(".env")
34
  USER_AGENT = os.getenv("USER_AGENT")
35
  GROQ_API_KEY = os.getenv("GROQ_API_KEY")
36
  SECRET_KEY = os.getenv("SECRET_KEY")
@@ -44,38 +46,77 @@ os.environ["TOKENIZERS_PARALLELISM"] = 'true'
44
  # Initialize Flask app and SocketIO with CORS
45
  app = Flask(__name__)
46
  CORS(app)
47
- socketio = SocketIO(app, cors_allowed_origins="*")
48
  app.config['SESSION_COOKIE_SECURE'] = True # Use HTTPS
49
  app.config['SESSION_COOKIE_HTTPONLY'] = True
50
  app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
 
51
  app.config['SECRET_KEY'] = SECRET_KEY
52
 
53
- # Initialize LLM
54
- llm = ChatGroq(model="llama-3.1-8b-instant", temperature=0, max_tokens=1024, max_retries=2)
 
 
55
 
56
- # QA system prompt and chain
57
- qa_system_prompt = """
58
- Prompt:
59
- 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.
60
 
61
- Response Guidelines:
62
- - Use only the information provided in the data to answer the question.
63
- - Ensure the answer is accurate and directly related to the question.
64
- - 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.
65
- - Provide the response in a conversational yet professional tone.
66
 
67
- Context:
68
- {context}
69
- """
70
- qa_prompt = ChatPromptTemplate.from_messages(
71
- [
72
- ("system", qa_system_prompt),
73
- ("human", "{input}")
74
- ]
75
- )
 
76
 
77
- question_answer_chain = qa_prompt | llm | StrOutputParser()
 
 
 
78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
 
80
  class StoppingCriteriaSub(StoppingCriteria):
81
 
@@ -123,7 +164,6 @@ def get_blip_config(model="base"):
123
 
124
  return config
125
 
126
-
127
  print("Creating model")
128
  config = get_blip_config("large")
129
 
@@ -145,16 +185,15 @@ print("="*50)
145
  transform = transform_test(384)
146
 
147
  print("Loading Data")
148
- df = pd.read_json("datasets/sidechef/my_recipes.json")
149
 
150
  print("Loading Target Embedding")
151
  tar_img_feats = []
152
  for _id in df["id_"].tolist():
153
- tar_img_feats.append(torch.load("datasets/sidechef/blip-embs-large/{:07d}.pth".format(_id)).unsqueeze(0))
154
 
155
  tar_img_feats = torch.cat(tar_img_feats, dim=0)
156
 
157
-
158
  class Chat:
159
 
160
  def __init__(self, model, transform, dataframe, tar_img_feats, device='cuda:0', stopping_criteria=None):
@@ -186,7 +225,7 @@ class Chat:
186
 
187
  def get_target(self, img_feats, tar_img_feats) :
188
  score = (img_feats @ tar_img_feats.t()).squeeze(0).cpu().detach().numpy()
189
- index = np.argsort(score)[::-1][0] + 1
190
  self.target_recipe = df.iloc[index]
191
 
192
  def ask(self):
@@ -198,36 +237,391 @@ chat = Chat(model,transform,df,tar_img_feats, device)
198
  print("Chat Initialized !")
199
 
200
 
201
- custom_css = """
202
- .primary{
203
- background-color: #4CAF50; /* Green */
204
- }
205
- """
206
-
207
- @spaces.GPU
208
- def respond_to_user(image, message):
209
- # Process the image and message here
210
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
211
- chat = Chat(model,transform,df,tar_img_feats, device)
212
- chat.encode_image(image)
213
- data = chat.ask()
214
- formated_input = {
215
- 'input': message,
216
- 'context': data
217
- }
218
- try:
219
- response = question_answer_chain.invoke(formated_input)
220
- except Exception as e:
221
- response = {'content':"An error occurred while processing your request."}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
222
  return response
223
 
224
- iface = gr.Interface(
225
- fn=respond_to_user,
226
- inputs=[gr.Image(), gr.Textbox(label="Ask Query")],
227
- outputs=gr.Textbox(label="Nutrition-GPT"),
228
- title="Nutrition-GPT Demo",
229
- description="Upload an food image and ask queries!",
230
- css=".component-12 {background-color: red}",
231
- )
232
 
233
- iface.launch()
 
 
 
 
 
 
 
 
 
 
15
 
16
  from transformers import StoppingCriteria, StoppingCriteriaList, TextIteratorStreamer
17
  import gradio as gr
18
+ # import spaces
19
 
20
+ from langchain.chains import ConversationChain
21
+ from langchain_community.chat_message_histories import ChatMessageHistory
22
+ from langchain_core.runnables import RunnableWithMessageHistory
23
  from langchain_core.output_parsers import StrOutputParser
24
  from langchain_core.prompts import ChatPromptTemplate
25
  from langchain_groq import ChatGroq
26
 
27
  from dotenv import load_dotenv
 
28
  from flask import Flask, request, render_template
29
  from flask_cors import CORS
30
+ from flask_socketio import SocketIO, emit
31
 
32
 
33
  # GROQ_API_KEY = os.getenv("GROQ_API_KEY")
34
  GROQ_API_KEY = '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'
35
+ # load_dotenv(".env")
36
  USER_AGENT = os.getenv("USER_AGENT")
37
  GROQ_API_KEY = os.getenv("GROQ_API_KEY")
38
  SECRET_KEY = os.getenv("SECRET_KEY")
 
46
  # Initialize Flask app and SocketIO with CORS
47
  app = Flask(__name__)
48
  CORS(app)
49
+ app.config['MAX_CONTENT_LENGTH'] = 1e7
50
  app.config['SESSION_COOKIE_SECURE'] = True # Use HTTPS
51
  app.config['SESSION_COOKIE_HTTPONLY'] = True
52
  app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
53
+ socketio = SocketIO(app, cors_allowed_origins="*", logger=True, max_http_buffer_size=1e7)
54
  app.config['SECRET_KEY'] = SECRET_KEY
55
 
56
+ import pandas as pd
57
+ from PIL import Image
58
+ import numpy as np
59
+ import os
60
 
61
+ import torch
62
+ import torch.nn.functional as F
 
 
63
 
64
+ # from src.data.embs import ImageDataset
65
+ from src.model.blip_embs import blip_embs
66
+ from src.data.transforms import transform_test
 
 
67
 
68
+ from transformers import StoppingCriteria, StoppingCriteriaList, TextIteratorStreamer
69
+ import gradio as gr
70
+ # import spaces
71
+
72
+ from langchain.chains import ConversationChain
73
+ from langchain_community.chat_message_histories import ChatMessageHistory
74
+ from langchain_core.runnables import RunnableWithMessageHistory
75
+ from langchain_core.output_parsers import StrOutputParser
76
+ from langchain_core.prompts import ChatPromptTemplate
77
+ from langchain_groq import ChatGroq
78
 
79
+ from dotenv import load_dotenv
80
+ from flask import Flask, request, render_template
81
+ from flask_cors import CORS
82
+ from flask_socketio import SocketIO, emit
83
 
84
+ import json
85
+ from openai import OpenAI
86
+
87
+ # GROQ_API_KEY = os.getenv("GROQ_API_KEY")
88
+ load_dotenv(".env")
89
+ USER_AGENT = os.getenv("USER_AGENT")
90
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY")
91
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
92
+ SECRET_KEY = os.getenv("SECRET_KEY")
93
+
94
+ # Set environment variables
95
+ os.environ['USER_AGENT'] = USER_AGENT
96
+ os.environ["GROQ_API_KEY"] = GROQ_API_KEY
97
+ os.environ['OPENAI_API_KEY'] = OPENAI_API_KEY
98
+ os.environ["TOKENIZERS_PARALLELISM"] = 'true'
99
+
100
+ # Initialize Flask app and SocketIO with CORS
101
+ app = Flask(__name__)
102
+ CORS(app)
103
+ socketio = SocketIO(app, cors_allowed_origins="*", logger=True)
104
+ app.config['SESSION_COOKIE_SECURE'] = True # Use HTTPS
105
+ app.config['SESSION_COOKIE_HTTPONLY'] = True
106
+ app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
107
+ app.config['SECRET_KEY'] = SECRET_KEY
108
+
109
+ # Initialize LLM
110
+ llm = ChatGroq(model="llama-3.1-8b-instant", temperature=0, max_tokens=1024, max_retries=2)
111
+
112
+ # Initialize Router
113
+ router = ChatGroq(model="llama-3.2-3b-preview", temperature=0, max_tokens=1024, max_retries=2, model_kwargs={"response_format": {"type": "json_object"}})
114
+
115
+ # Initialize Router
116
+ answer_formatter = ChatGroq(model="llama-3.1-8b-instant", temperature=0, max_tokens=1024, max_retries=2)
117
+
118
+ # Initialized recommendation LLM
119
+ client = OpenAI()
120
 
121
  class StoppingCriteriaSub(StoppingCriteria):
122
 
 
164
 
165
  return config
166
 
 
167
  print("Creating model")
168
  config = get_blip_config("large")
169
 
 
185
  transform = transform_test(384)
186
 
187
  print("Loading Data")
188
+ df = pd.read_json("my_recipes.json")
189
 
190
  print("Loading Target Embedding")
191
  tar_img_feats = []
192
  for _id in df["id_"].tolist():
193
+ tar_img_feats.append(torch.load("./datasets/sidechef/blip-embs-large/{:07d}.pth".format(_id)).unsqueeze(0))
194
 
195
  tar_img_feats = torch.cat(tar_img_feats, dim=0)
196
 
 
197
  class Chat:
198
 
199
  def __init__(self, model, transform, dataframe, tar_img_feats, device='cuda:0', stopping_criteria=None):
 
225
 
226
  def get_target(self, img_feats, tar_img_feats) :
227
  score = (img_feats @ tar_img_feats.t()).squeeze(0).cpu().detach().numpy()
228
+ index = np.argsort(score)[::-1][0]
229
  self.target_recipe = df.iloc[index]
230
 
231
  def ask(self):
 
237
  print("Chat Initialized !")
238
 
239
 
240
+ def answer_generator(formated_input, session_id):
241
+ # QA system prompt and chain
242
+ qa_system_prompt = """
243
+ 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.
244
+ Operational Guidelines:
245
+ 1. Input Structure:
246
+ - Context: You may receive contextual information related to recipes, such as specific data sets, user preferences, dietary restrictions, or previously selected dishes.
247
+ - User Query: Users will pose questions or requests related to recipes, nutritional information, ingredient substitutions, cooking instructions, and more.
248
+ 2. Response Strategy:
249
+ - 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.
250
+ - 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.
251
+ Core Functionalities:
252
+ - 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.
253
+ - Ingredient Details: List all ingredients required for recipes, including substitute options for dietary restrictions or ingredient availability, utilizing context when relevant.
254
+ - Step-by-Step Cooking Instructions: Deliver clear, easy-to-follow instructions for preparing and cooking meals, informed by any provided contextual data.
255
+ - Recipe Recommendations: Suggest dishes based on user preferences, dietary restrictions, available ingredients, and contextual data if provided.
256
+ Additional Instructions:
257
+ - Precision and Personalization: Always aim to provide precise, personalized, and relevant information to users based on both the provided context and their specific queries.
258
+ - Clarity and Coherence: Ensure that all responses are clear, well-structured, and easy to understand, facilitating a seamless user experience.
259
+ - Substitute Suggestions: When suggesting ingredient substitutes, consider user preferences and dietary restrictions outlined in the context or user query.
260
+ - 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.
261
+ Don't mention about context in the response, format the answer in a natural and friendly way.
262
+ Context:
263
+ {context}
264
+ """
265
+ qa_prompt = ChatPromptTemplate.from_messages(
266
+ [
267
+ ("system", qa_system_prompt),
268
+ ("human", "{input}")
269
+ ]
270
+ )
271
+
272
+ # Create the base chain
273
+ base_chain = qa_prompt | llm | StrOutputParser()
274
+
275
+ # Wrap the chain with message history
276
+ question_answer_chain = RunnableWithMessageHistory(
277
+ base_chain,
278
+ lambda session_id: ChatMessageHistory(), # This creates a new history for each session
279
+ input_messages_key="input",
280
+ history_messages_key="chat_history"
281
+ )
282
+
283
+ response = question_answer_chain.invoke(formated_input, config={"configurable": {"session_id": session_id}})
284
+
285
+ return response
286
+
287
+
288
+
289
+ ### Router
290
+ import json
291
+ from langchain_core.messages import HumanMessage, SystemMessage
292
+
293
+ def router_node(query):
294
+ # Prompt
295
+ 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:
296
+
297
+ 1. Retrieval: Fetch information based on user's chat history and current query.
298
+ 2. Recommendation/Suggestion: Recommend recipes to users based on the query.
299
+
300
+ Return a JSON response with a single key named “task” indicating either “retrieval” or “recommendation” based on your decision.
301
+ """
302
+ response = router.invoke(
303
+ [SystemMessage(content=router_instructions)]
304
+ + [
305
+ HumanMessage(
306
+ content=query
307
+ )
308
+ ]
309
+ )
310
+ res = json.loads(response.content)
311
+ return res['task']
312
+
313
+ def recommendation_node(query):
314
+ prompt = """
315
+ You are a helpful assistant that writes Python code to filter recipes from a JSON filr based o the user query. \n
316
+ JSON file path = 'recipes.json' \n
317
+ The JSON file is a list of recipes with the following structure: \n
318
+ {
319
+ "recipe_name": string,
320
+ "recipe_time": integer,
321
+ "recipe_yields": string,
322
+ "recipe_ingredients": list of ingredients,
323
+ "recipe_instructions": list of instruections,
324
+ "recipe_image": string,
325
+ "blogger": string,
326
+ "recipe_nutrients": JSON object with key value pairs such as "protein: 10g",
327
+ "tags": list of tags related to recipe
328
+ } \n
329
+
330
+ Here is the example of an recipe json object from the JSON data: \n
331
+ {
332
+ "recipe_name": "Asian Potato Salad with Seven Minute Egg",
333
+ "recipe_time": 0,
334
+ "recipe_yields": "4 servings",
335
+ "recipe_ingredients": [
336
+ "2 1/2 cup Multi-Colored Fingerling Potato",
337
+ "3/4 cup Celery",
338
+ "1/4 cup Red Onion",
339
+ "2 tablespoon Fresh Parsley",
340
+ "1/3 cup Mayonnaise",
341
+ "1 tablespoon Chili Garlic Sauce",
342
+ "1 teaspoon Hoisin Sauce",
343
+ "1 splash Soy Sauce",
344
+ "to taste Salt",
345
+ "to taste Ground Black Pepper",
346
+ "4 Egg"
347
+ ],
348
+ "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!",
349
+ "recipe_image": "https://www.sidechef.com/recipe/eeeeeceb-493e-493d-8273-66c800821b13.jpg?d=1408x1120",
350
+ "blogger": "sidechef.com",
351
+ "recipe_nutrients": {
352
+ "calories": "80 calories",
353
+ "proteinContent": "2.1 g",
354
+ "fatContent": "6.2 g",
355
+ "carbohydrateContent": "3.9 g",
356
+ "fiberContent": "0.5 g",
357
+ "sugarContent": "0.4 g",
358
+ "sodiumContent": "108.0 mg",
359
+ "saturatedFatContent": "1.2 g",
360
+ "transFatContent": "0.0 g",
361
+ "cholesterolContent": "47.4 mg",
362
+ "unsaturatedFatContent": "3.8 g"
363
+ },
364
+ "tags": [
365
+ "Salad",
366
+ "Lunch",
367
+ "Brunch",
368
+ "Appetizers",
369
+ "Side Dish",
370
+ "Budget-Friendly",
371
+ "Vegetarian",
372
+ "Pescatarian",
373
+ "Eggs",
374
+ "Potatoes",
375
+ "Dairy-Free",
376
+ "Shellfish-Free"
377
+ ]
378
+ } \n
379
+
380
+ 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
381
+
382
+ Recipe filtering instructions:
383
+ - 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.
384
+ - sort or rearrange recipes based which recipes are more appropriate for the user.
385
+
386
+ Your output instructions:
387
+ - The function name should be filter_recipes. The input to the function should be file name.
388
+ - The length of output recipes should not be more than 6.
389
+ - Only give me output function. Do not call the function.
390
+ - Give the python function as a key named "code" in a json format.
391
+ - Do not include any other text with the output, only give python code.
392
+ - If you do not follow the above given instructions, the chat may be terminated.
393
+ """
394
+ max_tries = 3
395
+ while True:
396
+ try:
397
+ # llm = ChatGroq(model="llama-3.1-8b-instant", temperature=0, max_tokens=1024, max_retries=2, model_kwargs={"response_format": {"type": "json_object"}})
398
+ response = client.chat.completions.create(
399
+ model="gpt-4o-mini",
400
+ messages=[
401
+ {"role": "system", "content": prompt},
402
+ {
403
+ "role": "user",
404
+ "content": query
405
+ }
406
+ ]
407
+ )
408
+
409
+ content = response.choices[0].message.content
410
+
411
+ res = json.loads(content)
412
+ script = res['code']
413
+ exec(script, globals())
414
+ filtered_recipes = filter_recipes('recipes.json')
415
+ if len(filtered_recipes) > 0:
416
+ return filtered_recipes
417
+ except Exception as e:
418
+ print(e)
419
+ if max_tries <= 0:
420
+ return []
421
+ else:
422
+ max_tries -= 1
423
+ return filtered_recipes
424
+
425
+
426
+ def answer_formatter_node(question, context):
427
+ 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.
428
+ Your task is to generated answers for the user query based on the context provided.
429
+ Instructions for your response:
430
+ 1. Directly answer the user query using only the information provided in the context.
431
+ 2. Ensure your response is clear and concise.
432
+ 3. Mention only details related to the recipe, including the recipe name, instructions, nutrients, yield, ingredients, and image.
433
+ 4. Do not include any information that is not related to the recipe context.
434
+
435
+ Please format an answer based on the following user question and context provided:
436
+
437
+ User Question:
438
+ {question}
439
+
440
+ Context:
441
+ {context}
442
+ """
443
+ response = answer_formatter.invoke(
444
+ [SystemMessage(content=prompt)]
445
+ )
446
+ res = response.content
447
+ return res
448
+
449
+ CURR_CONTEXT = ''
450
+
451
+ # @spaces.GPU
452
+ def get_answer(image=[], message='', sessionID='abc123'):
453
+ global CURR_CONTEXT
454
+ if len(image) > 0:
455
+ try:
456
+ # Process the image and message here
457
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
458
+ chat = Chat(model,transform,df,tar_img_feats, device)
459
+ chat.encode_image(image)
460
+ data = chat.ask()
461
+ CURR_CONTEXT = data
462
+ formated_input = {
463
+ 'input': message,
464
+ 'context': data
465
+ }
466
+ response = answer_generator(formated_input, session_id=sessionID)
467
+ except Exception as e:
468
+ print(e)
469
+ response = {'content':"An error occurred while processing your request."}
470
+ elif len(image) == 0 and message is not None:
471
+ print("I am here")
472
+ task = router_node(message)
473
+ if task == 'retrieval':
474
+ recipes = recommendation_node(message)
475
+ if not recipes:
476
+ response = {'content':"An error occurred while processing your request."}
477
+ response = answer_formatter_node(message, recipes)
478
+ else:
479
+ formated_input = {
480
+ 'input': message,
481
+ 'context': CURR_CONTEXT
482
+ }
483
+ response = answer_generator(formated_input, session_id=sessionID)
484
+
485
+ return response
486
+
487
+ # Function to handle WebSocket connection
488
+ @socketio.on('ping')
489
+ def handle_connect():
490
+ emit('Ping-return', {'message': 'Connected'}, room=request.sid)
491
+
492
+
493
+ # Function to handle WebSocket connection
494
+ @socketio.on('connect')
495
+ def handle_connect():
496
+ print(f"Client connected: {request.sid}")
497
+
498
+ # Function to handle WebSocket disconnection
499
+ @socketio.on('disconnect')
500
+ def handle_disconnect():
501
+ print(f"Client disconnected: {request.sid}")
502
+
503
+ import json
504
+ import base64
505
+ from PIL import Image
506
+ from io import BytesIO
507
+ import torchvision.transforms as transforms
508
+
509
+ # Dictionary to store incomplete image data by session
510
+ session_store = {}
511
+
512
+ @socketio.on('message')
513
+ def handle_message(data):
514
+ global session_store
515
+ global CURR_CONTEXT
516
+ context = "No data available"
517
+ session_id = request.sid
518
+ if session_id not in session_store:
519
+ session_store[session_id] = {'image_data': b"", 'message': None, 'image_received': False}
520
+
521
+ if 'message' in data:
522
+ session_store[session_id]['message'] = data['message']
523
+
524
+ # Handle image chunk data
525
+ if 'image' in data:
526
+ try:
527
+ # Append the incoming image chunk
528
+ session_store[session_id]['image_data'] += data['image']
529
+
530
+ except Exception as e:
531
+ print(f"Error processing image chunk: {str(e)}")
532
+ emit('response', "An error occurred while receiving the image chunk.", room=session_id)
533
+ return
534
+
535
+ if session_store[session_id]['image_data'] or session_store[session_id]['message']:
536
+ try:
537
+ image_bytes = session_store[session_id]['image_data']
538
+ # print("checkpoint 2")
539
+ if isinstance(image_bytes, str):
540
+ image_bytes = base64.b64decode(image_bytes)
541
+ image = Image.open(BytesIO(image_bytes))
542
+ image_array = np.array(image)
543
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
544
+ chat = Chat(model, transform, df, tar_img_feats, device)
545
+ chat.encode_image(image_array)
546
+ context = chat.ask()
547
+ CURR_CONTEXT = context
548
+ message = data['message']
549
+ formated_input = {
550
+ 'input': message,
551
+ 'context': json.dumps(context)
552
+ }
553
+ # Invoke question_answer_chain and stream the response
554
+ response = answer_generator(formated_input, session_id=session_id)
555
+ emit('response', response, room=session_id)
556
+
557
+ except Exception as e:
558
+ print(f"Error processing image or message: {str(e)}")
559
+ emit('response', "An error occurred while processing your request.", room=session_id)
560
+ return
561
+ finally:
562
+ # Clear session data after processing
563
+ session_store.pop(session_id, None)
564
+ else:
565
+ message = data['message']
566
+ task = router_node(message)
567
+ print(task)
568
+ if task == 'retrieval':
569
+ formated_input = {
570
+ 'input': message,
571
+ 'context': json.dumps(CURR_CONTEXT)
572
+ }
573
+ response = answer_generator(formated_input, session_id=session_id)
574
+ emit('response', response, room=session_id)
575
+ else:
576
+ response = recommendation_node(message)
577
+ # response = answer_formatter_node(message, recipes)
578
+ if response is None:
579
+ response = {'content':"An error occurred while processing your request."}
580
+
581
+ emit('json_response', response, room=session_id)
582
+ session_store.pop(session_id, None)
583
+
584
+
585
+
586
+ import requests
587
+ from PIL import Image
588
+ import numpy as np
589
+ from io import BytesIO
590
+
591
+ def download_image_to_numpy(url):
592
+ # Send a GET request to the URL to download the image
593
+ response = requests.get(url)
594
+
595
+ # Check if the request was successful
596
+ if response.status_code == 200:
597
+ # Open the image using PIL and convert it to RGB format
598
+ image = Image.open(BytesIO(response.content)).convert('RGB')
599
+
600
+ # Convert the image to a NumPy array
601
+ image_array = np.array(image)
602
+
603
+ return image_array
604
+ else:
605
+ raise Exception(f"Failed to download image. Status code: {response.status_code}")
606
+
607
+ @socketio.on('example')
608
+ def handle_message(data):
609
+ img_url = data['img_url']
610
+ message = data['message']
611
+ session_id = request.sid
612
+ image_array = download_image_to_numpy(img_url)
613
+ response = get_answer(image=image_array, message=message, sessionID=request.sid)
614
+ emit('response', response, room=session_id)
615
  return response
616
 
 
 
 
 
 
 
 
 
617
 
618
+
619
+
620
+ # Home route
621
+ @app.route("/")
622
+ def index_view():
623
+ return render_template('chat.html')
624
+
625
+ # Main function to run the app
626
+ if __name__ == '__main__':
627
+ socketio.run(app, debug=True)