Ritesh-hf commited on
Commit
f3b7ab2
·
verified ·
1 Parent(s): 99490d9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +398 -38
app.py CHANGED
@@ -1,10 +1,7 @@
1
  import pandas as pd
2
- import json
3
  from PIL import Image
4
  import numpy as np
5
-
6
  import os
7
- from pathlib import Path
8
 
9
  import torch
10
  import torch.nn.functional as F
@@ -17,41 +14,42 @@ from transformers import StoppingCriteria, StoppingCriteriaList, TextIteratorStr
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
 
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
 
@@ -99,7 +97,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 +118,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,11 +170,375 @@ 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):
@@ -192,15 +552,15 @@ def respond_to_user(image, 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,
202
  inputs=[gr.Image(), gr.Textbox(label="Ask Query")],
203
- outputs=[gr.Textbox(label="Nutrition-GPT"), gr.JSON(label="context")],
204
  title="Nutrition-GPT Demo",
205
  description="Upload an food image and ask queries!",
206
  css=".component-12 {background-color: red}",
 
1
  import pandas as pd
 
2
  from PIL import Image
3
  import numpy as np
 
4
  import os
 
5
 
6
  import torch
7
  import torch.nn.functional as F
 
14
  import gradio as gr
15
  import spaces
16
 
17
+ from langchain.chains import ConversationChain
18
+ from langchain_community.chat_message_histories import ChatMessageHistory
19
+ from langchain_core.runnables import RunnableWithMessageHistory
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
+
26
+ import json
27
+ from openai import OpenAI
28
 
29
  # GROQ_API_KEY = os.getenv("GROQ_API_KEY")
30
+ load_dotenv(".env")
31
+ USER_AGENT = os.getenv("USER_AGENT")
32
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY")
33
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
34
+ SECRET_KEY = os.getenv("SECRET_KEY")
35
+
36
+ # Set environment variables
37
+ os.environ['USER_AGENT'] = USER_AGENT
38
  os.environ["GROQ_API_KEY"] = GROQ_API_KEY
39
+ os.environ['OPENAI_API_KEY'] = OPENAI_API_KEY
40
+ os.environ["TOKENIZERS_PARALLELISM"] = 'true'
41
 
42
  # Initialize LLM
43
  llm = ChatGroq(model="llama-3.1-8b-instant", temperature=0, max_tokens=1024, max_retries=2)
44
 
45
+ # Initialize Router
46
+ router = ChatGroq(model="llama-3.2-3b-preview", temperature=0, max_tokens=1024, max_retries=2, model_kwargs={"response_format": {"type": "json_object"}})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
+ # Initialize Router
49
+ answer_formatter = ChatGroq(model="llama-3.1-8b-instant", temperature=0, max_tokens=1024, max_retries=2)
50
 
51
+ # Initialized recommendation LLM
52
+ client = OpenAI()
53
 
54
  class StoppingCriteriaSub(StoppingCriteria):
55
 
 
97
 
98
  return config
99
 
 
100
  print("Creating model")
101
  config = get_blip_config("large")
102
 
 
118
  transform = transform_test(384)
119
 
120
  print("Loading Data")
121
+ df = pd.read_json("my_recipes.json")
122
 
123
  print("Loading Target Embedding")
124
  tar_img_feats = []
125
  for _id in df["id_"].tolist():
126
+ tar_img_feats.append(torch.load("./datasets/sidechef/blip-embs-large/{:07d}.pth".format(_id)).unsqueeze(0))
127
 
128
  tar_img_feats = torch.cat(tar_img_feats, dim=0)
129
 
 
130
  class Chat:
131
 
132
  def __init__(self, model, transform, dataframe, tar_img_feats, device='cuda:0', stopping_criteria=None):
 
170
  print("Chat Initialized !")
171
 
172
 
173
+
174
+ import secrets
175
+ import string
176
+
177
+ def generate_session_key():
178
+ characters = string.ascii_letters + string.digits
179
+ session_key = ''.join(secrets.choice(characters) for _ in range(8))
180
+ return session_key
181
+
182
+
183
+ def answer_generator(formated_input, session_id):
184
+ # QA system prompt and chain
185
+ qa_system_prompt = """
186
+ 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.
187
+ Operational Guidelines:
188
+ 1. Input Structure:
189
+ - Context: You may receive contextual information related to recipes, such as specific data sets, user preferences, dietary restrictions, or previously selected dishes.
190
+ - User Query: Users will pose questions or requests related to recipes, nutritional information, ingredient substitutions, cooking instructions, and more.
191
+ 2. Response Strategy:
192
+ - 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.
193
+ - 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.
194
+ Core Functionalities:
195
+ - 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.
196
+ - Ingredient Details: List all ingredients required for recipes, including substitute options for dietary restrictions or ingredient availability, utilizing context when relevant.
197
+ - Step-by-Step Cooking Instructions: Deliver clear, easy-to-follow instructions for preparing and cooking meals, informed by any provided contextual data.
198
+ - Recipe Recommendations: Suggest dishes based on user preferences, dietary restrictions, available ingredients, and contextual data if provided.
199
+ Additional Instructions:
200
+ - Precision and Personalization: Always aim to provide precise, personalized, and relevant information to users based on both the provided context and their specific queries.
201
+ - Clarity and Coherence: Ensure that all responses are clear, well-structured, and easy to understand, facilitating a seamless user experience.
202
+ - Substitute Suggestions: When suggesting ingredient substitutes, consider user preferences and dietary restrictions outlined in the context or user query.
203
+ - 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.
204
+ Don't mention about context in the response, format the answer in a natural and friendly way.
205
+ Context:
206
+ {context}
207
+ """
208
+ qa_prompt = ChatPromptTemplate.from_messages(
209
+ [
210
+ ("system", qa_system_prompt),
211
+ ("human", "{input}")
212
+ ]
213
+ )
214
+
215
+ # Create the base chain
216
+ base_chain = qa_prompt | llm | StrOutputParser()
217
+
218
+ # Wrap the chain with message history
219
+ question_answer_chain = RunnableWithMessageHistory(
220
+ base_chain,
221
+ lambda session_id: ChatMessageHistory(), # This creates a new history for each session
222
+ input_messages_key="input",
223
+ history_messages_key="chat_history"
224
+ )
225
+
226
+ response = question_answer_chain.invoke(formated_input, config={"configurable": {"session_id": session_id}})
227
+
228
+ return response
229
+
230
+
231
+
232
+ ### Router
233
+ import json
234
+ from langchain_core.messages import HumanMessage, SystemMessage
235
+
236
+ def router_node(query):
237
+ # Prompt
238
+ 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:
239
+
240
+ 1. Retrieval: Fetch information based on user's chat history and current query.
241
+ 2. Recommendation/Suggestion: Recommend recipes to users based on the query.
242
+
243
+ Return a JSON response with a single key named “task” indicating either “retrieval” or “recommendation” based on your decision.
244
+ """
245
+ response = router.invoke(
246
+ [SystemMessage(content=router_instructions)]
247
+ + [
248
+ HumanMessage(
249
+ content=query
250
+ )
251
+ ]
252
+ )
253
+ res = json.loads(response.content)
254
+ return res['task']
255
+
256
+ def recommendation_node(query):
257
+ prompt = """
258
+ You are a helpful assistant that writes Python code to filter recipes from a JSON filr based o the user query. \n
259
+ JSON file path = 'recipes.json' \n
260
+ The JSON file is a list of recipes with the following structure: \n
261
+ {
262
+ "recipe_name": string,
263
+ "recipe_time": integer,
264
+ "recipe_yields": string,
265
+ "recipe_ingredients": list of ingredients,
266
+ "recipe_instructions": list of instruections,
267
+ "recipe_image": string,
268
+ "blogger": string,
269
+ "recipe_nutrients": JSON object with key value pairs such as "protein: 10g",
270
+ "tags": list of tags related to recipe
271
+ } \n
272
+
273
+ Here is the example of an recipe json object from the JSON data: \n
274
+ {
275
+ "recipe_name": "Asian Potato Salad with Seven Minute Egg",
276
+ "recipe_time": 0,
277
+ "recipe_yields": "4 servings",
278
+ "recipe_ingredients": [
279
+ "2 1/2 cup Multi-Colored Fingerling Potato",
280
+ "3/4 cup Celery",
281
+ "1/4 cup Red Onion",
282
+ "2 tablespoon Fresh Parsley",
283
+ "1/3 cup Mayonnaise",
284
+ "1 tablespoon Chili Garlic Sauce",
285
+ "1 teaspoon Hoisin Sauce",
286
+ "1 splash Soy Sauce",
287
+ "to taste Salt",
288
+ "to taste Ground Black Pepper",
289
+ "4 Egg"
290
+ ],
291
+ "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!",
292
+ "recipe_image": "https://www.sidechef.com/recipe/eeeeeceb-493e-493d-8273-66c800821b13.jpg?d=1408x1120",
293
+ "blogger": "sidechef.com",
294
+ "recipe_nutrients": {
295
+ "calories": "80 calories",
296
+ "proteinContent": "2.1 g",
297
+ "fatContent": "6.2 g",
298
+ "carbohydrateContent": "3.9 g",
299
+ "fiberContent": "0.5 g",
300
+ "sugarContent": "0.4 g",
301
+ "sodiumContent": "108.0 mg",
302
+ "saturatedFatContent": "1.2 g",
303
+ "transFatContent": "0.0 g",
304
+ "cholesterolContent": "47.4 mg",
305
+ "unsaturatedFatContent": "3.8 g"
306
+ },
307
+ "tags": [
308
+ "Salad",
309
+ "Lunch",
310
+ "Brunch",
311
+ "Appetizers",
312
+ "Side Dish",
313
+ "Budget-Friendly",
314
+ "Vegetarian",
315
+ "Pescatarian",
316
+ "Eggs",
317
+ "Potatoes",
318
+ "Dairy-Free",
319
+ "Shellfish-Free"
320
+ ]
321
+ } \n
322
+
323
+ 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
324
+
325
+ Recipe filtering instructions:
326
+ - 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.
327
+ - sort or rearrange recipes based which recipes are more appropriate for the user.
328
+
329
+ Your output instructions:
330
+ - The function name should be filter_recipes. The input to the function should be file name.
331
+ - The length of output recipes should not be more than 6.
332
+ - Only give me output function. Do not call the function.
333
+ - Give the python function as a key named "code" in a json format.
334
+ - Do not include any other text with the output, only give python code.
335
+ - If you do not follow the above given instructions, the chat may be terminated.
336
+ """
337
+ max_tries = 3
338
+ while True:
339
+ try:
340
+ # llm = ChatGroq(model="llama-3.1-8b-instant", temperature=0, max_tokens=1024, max_retries=2, model_kwargs={"response_format": {"type": "json_object"}})
341
+ response = client.chat.completions.create(
342
+ model="gpt-4o-mini",
343
+ messages=[
344
+ {"role": "system", "content": prompt},
345
+ {
346
+ "role": "user",
347
+ "content": query
348
+ }
349
+ ]
350
+ )
351
+
352
+ content = response.choices[0].message.content
353
+
354
+ res = json.loads(content)
355
+ script = res['code']
356
+ exec(script, globals())
357
+ filtered_recipes = filter_recipes('recipes.json')
358
+ if len(filtered_recipes) > 0:
359
+ return filtered_recipes
360
+ except Exception as e:
361
+ print(e)
362
+ if max_tries <= 0:
363
+ return []
364
+ else:
365
+ max_tries -= 1
366
+ return filtered_recipes
367
+
368
+
369
+ def answer_formatter_node(question, context):
370
+ 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.
371
+ Your task is to generated answers for the user query based on the context provided.
372
+ Instructions for your response:
373
+ 1. Directly answer the user query using only the information provided in the context.
374
+ 2. Ensure your response is clear and concise.
375
+ 3. Mention only details related to the recipe, including the recipe name, instructions, nutrients, yield, ingredients, and image.
376
+ 4. Do not include any information that is not related to the recipe context.
377
+
378
+ Please format an answer based on the following user question and context provided:
379
+
380
+ User Question:
381
+ {question}
382
+
383
+ Context:
384
+ {context}
385
+ """
386
+ response = answer_formatter.invoke(
387
+ [SystemMessage(content=prompt)]
388
+ )
389
+ res = response.content
390
+ return res
391
+
392
+ CURR_CONTEXT = ''
393
+ CURR_SESSION_KEY = generate_session_key()
394
+
395
+ @spaces.GPU
396
+ def get_answer(image=[], message='', sessionID='abc123'):
397
+ global CURR_CONTEXT
398
+ global CURR_SESSION_KEY
399
+ sessionID = CURR_SESSION_KEY
400
+ if image is not None:
401
+ try:
402
+ # Process the image and message here
403
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
404
+ chat = Chat(model,transform,df,tar_img_feats, device)
405
+ chat.encode_image(image)
406
+ data = chat.ask()
407
+ CURR_CONTEXT = data
408
+ formated_input = {
409
+ 'input': message,
410
+ 'context': data
411
+ }
412
+ response = answer_generator(formated_input, session_id=sessionID)
413
+ except Exception as e:
414
+ print(e)
415
+ response = {'content':"An error occurred while processing your request."}
416
+ elif (image is None) and (message is not None):
417
+ task = router_node(message)
418
+ print(task)
419
+ if task == 'recommendation':
420
+ response = recommendation_node(message)
421
+ if not response:
422
+ response = {'content':"An error occurred while processing your request."}
423
+ # response = answer_formatter_node(message, recipes)
424
+ else:
425
+ formated_input = {
426
+ 'input': message,
427
+ 'context': CURR_CONTEXT
428
+ }
429
+ response = answer_generator(formated_input, session_id=sessionID)
430
+ return response
431
+
432
+ import json
433
+ import base64
434
+ from PIL import Image
435
+ from io import BytesIO
436
+ import torchvision.transforms as transforms
437
+
438
+ # Dictionary to store incomplete image data by session
439
+ session_store = {}
440
+
441
+ def handle_message(data):
442
+ global session_store
443
+ global CURR_CONTEXT
444
+ global CURR_SESSION_KEY
445
+ session_id = CURR_SESSION_KEY
446
+ context = "No data available"
447
+ if session_id not in session_store:
448
+ session_store[session_id] = {'image_data': b"", 'message': None, 'image_received': False}
449
+
450
+ if 'message' in data:
451
+ session_store[session_id]['message'] = data['message']
452
+
453
+ # Handle image chunk data
454
+ if 'image' in data:
455
+ try:
456
+ # Append the incoming image chunk
457
+ session_store[session_id]['image_data'] += data['image']
458
+
459
+ except Exception as e:
460
+ print(f"Error processing image chunk: {str(e)}")
461
+ return "An error occurred while receiving the image chunk."
462
+
463
+ if session_store[session_id]['image_data'] or session_store[session_id]['message']:
464
+ try:
465
+ image_bytes = session_store[session_id]['image_data']
466
+ # print("checkpoint 2")
467
+ if isinstance(image_bytes, str):
468
+ image_bytes = base64.b64decode(image_bytes)
469
+ image = Image.open(BytesIO(image_bytes))
470
+ image_array = np.array(image)
471
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
472
+ chat = Chat(model, transform, df, tar_img_feats, device)
473
+ chat.encode_image(image_array)
474
+ context = chat.ask()
475
+ CURR_CONTEXT = context
476
+ message = data['message']
477
+ formated_input = {
478
+ 'input': message,
479
+ 'context': json.dumps(context)
480
+ }
481
+ # Invoke question_answer_chain and stream the response
482
+ response = answer_generator(formated_input, session_id=session_id)
483
+ return response
484
+
485
+ except Exception as e:
486
+ print(f"Error processing image or message: {str(e)}")
487
+ return "An error occurred while processing your request."
488
+ finally:
489
+ # Clear session data after processing
490
+ session_store.pop(session_id, None)
491
+ else:
492
+ message = data['message']
493
+ task = router_node(message)
494
+ print(task)
495
+ if task == 'retrieval':
496
+ formated_input = {
497
+ 'input': message,
498
+ 'context': json.dumps(CURR_CONTEXT)
499
+ }
500
+ response = answer_generator(formated_input, session_id=session_id)
501
+ session_store.pop(session_id, None)
502
+ return response
503
+ else:
504
+ response = recommendation_node(message)
505
+ # response = answer_formatter_node(message, recipes)
506
+ if response is None:
507
+ response = {'content':"An error occurred while processing your request."}
508
+ session_store.pop(session_id, None)
509
+ return response
510
+
511
+ import requests
512
+ from PIL import Image
513
+ import numpy as np
514
+ from io import BytesIO
515
+
516
+ def download_image_to_numpy(url):
517
+ # Send a GET request to the URL to download the image
518
+ response = requests.get(url)
519
+
520
+ # Check if the request was successful
521
+ if response.status_code == 200:
522
+ # Open the image using PIL and convert it to RGB format
523
+ image = Image.open(BytesIO(response.content)).convert('RGB')
524
+
525
+ # Convert the image to a NumPy array
526
+ image_array = np.array(image)
527
+
528
+ return image_array
529
+ else:
530
+ raise Exception(f"Failed to download image. Status code: {response.status_code}")
531
+
532
+ def handle_message(data):
533
+ global CURR_SESSION_KEY
534
+ session_id = CURR_SESSION_KEY
535
+ img_url = data['img_url']
536
+ message = data['message']
537
+ image_array = download_image_to_numpy(img_url)
538
+ response = get_answer(image=image_array, message=message, sessionID=session_id)
539
+ return response
540
+
541
+
542
 
543
  @spaces.GPU
544
  def respond_to_user(image, message):
 
552
  'context': data
553
  }
554
  try:
555
+ response = answer_generator(formated_input, session_id="123cnedc")
556
  except Exception as e:
557
  response = {'content':"An error occurred while processing your request."}
558
+ return response
559
 
560
  iface = gr.Interface(
561
+ fn=get_answer,
562
  inputs=[gr.Image(), gr.Textbox(label="Ask Query")],
563
+ outputs=[gr.Textbox(label="Nutrition-GPT")],
564
  title="Nutrition-GPT Demo",
565
  description="Upload an food image and ask queries!",
566
  css=".component-12 {background-color: red}",