Spaces:
Sleeping
Sleeping
update all_cals
Browse files
app.py
CHANGED
@@ -1,161 +1,162 @@
|
|
1 |
-
from langchain.chat_models import ChatOpenAI
|
2 |
-
from langchain.schema import HumanMessage, SystemMessage
|
3 |
-
|
4 |
-
from langchain_community.tools import DuckDuckGoSearchRun
|
5 |
-
from ai71 import AI71
|
6 |
-
import gradio as gr
|
7 |
-
import openai
|
8 |
-
import os
|
9 |
-
import re
|
10 |
-
import matplotlib.pyplot as plt
|
11 |
-
|
12 |
-
from PIL import Image
|
13 |
-
import numpy as np
|
14 |
-
import pytesseract
|
15 |
-
# Make sure to import the necessary OpenAI API client and configure it.
|
16 |
-
all_cals = {}
|
17 |
-
def extract_calories_and_items(text):
|
18 |
-
# Use regular expression to find all numerical values associated with "calory" or "calories"
|
19 |
-
pattern = r'(\d+)\s*(?:calory|calories)'
|
20 |
-
matches = re.findall(pattern, text, re.IGNORECASE)
|
21 |
-
|
22 |
-
# Convert the matches to integers
|
23 |
-
calories = [int(match) for match in matches]
|
24 |
-
|
25 |
-
return calories
|
26 |
-
|
27 |
-
def plot_calories(calories):
|
28 |
-
labels = sorted(calories, key=calories.get)
|
29 |
-
vals = [calories[label] for label in labels]
|
30 |
-
plt.barh(labels, vals, color='skyblue')
|
31 |
-
plt.xlabel('Calories')
|
32 |
-
plt.title('Item and Count')
|
33 |
-
plt.tight_layout()
|
34 |
-
|
35 |
-
def parse_items(items_string):
|
36 |
-
# Remove square brackets and split by comma
|
37 |
-
items_list = items_string.strip('[]').split(',')
|
38 |
-
|
39 |
-
item_dict = {}
|
40 |
-
|
41 |
-
# Define the pattern to match the quantity and item
|
42 |
-
pattern = r'(\d+)\s*x\s*(\w+)'
|
43 |
-
|
44 |
-
for item in items_list:
|
45 |
-
match = re.match(pattern, item.strip())
|
46 |
-
if match:
|
47 |
-
quantity = int(match.group(1))
|
48 |
-
item_name = match.group(2)
|
49 |
-
if item_name in item_dict:
|
50 |
-
item_dict[item_name] += quantity
|
51 |
-
else:
|
52 |
-
item_dict[item_name] = quantity
|
53 |
-
|
54 |
-
return item_dict
|
55 |
-
|
56 |
-
# Set the API key for AI71
|
57 |
-
#AI71_API_KEY = "key"
|
58 |
-
AI71_API_KEY = os.getenv('KEY')
|
59 |
-
AI71_BASE_URL = "https://api.ai71.ai/v1/"
|
60 |
-
client = AI71(AI71_API_KEY)
|
61 |
-
|
62 |
-
search = DuckDuckGoSearchRun()
|
63 |
-
|
64 |
-
# usr_input = input(f"User:")
|
65 |
-
#
|
66 |
-
# print(items)
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
def chatGPT_food(userinput, temperature=0.1, max_tokens=300):
|
71 |
-
|
72 |
-
keyword = client.chat.completions.create(
|
73 |
-
model="tiiuae/falcon-180B-chat",
|
74 |
-
messages=[
|
75 |
-
{"role": "system", "content": '''you need to extract the food item from the user text without any comments
|
76 |
-
example:
|
77 |
-
user: I ate two apples
|
78 |
-
assistant: 2 x apple'''},
|
79 |
-
{"role": "user", "content": userinput}
|
80 |
-
],
|
81 |
-
# temperature=0.5,
|
82 |
-
)
|
83 |
-
|
84 |
-
items = parse_items(keyword.choices[0].message.content)
|
85 |
-
|
86 |
-
for item, count in items.items():
|
87 |
-
result = search.invoke(f'calories of {item}')
|
88 |
-
|
89 |
-
response = client.chat.completions.create(
|
90 |
-
model="tiiuae/falcon-180B-chat",
|
91 |
-
messages=[
|
92 |
-
{"role": "system", "content": '''based on the provided information extract the calories count per portion of the item provided, just the calories and portion in grams or ml without further comments
|
93 |
-
Example:
|
94 |
-
orange 47 calories per 100 gram
|
95 |
-
cola 38 calories per 100 gram
|
96 |
-
do not generate more or add any unneeded comments, just follow the examples strictly'''},
|
97 |
-
{"role": "user", "content": result}
|
98 |
-
],
|
99 |
-
temperature=0.2,
|
100 |
-
)
|
101 |
-
|
102 |
-
# print("search")
|
103 |
-
# print(result)
|
104 |
-
# print("ai")
|
105 |
-
# print (response.choices[0].message.content)
|
106 |
-
calories = extract_calories_and_items(response.choices[0].message.content)
|
107 |
-
# print("calories")
|
108 |
-
# print(calories)
|
109 |
-
try:
|
110 |
-
all_cals[f"{count}x{item}"] = count*calories[0]
|
111 |
-
except:
|
112 |
-
continue
|
113 |
-
return all_cals
|
114 |
-
|
115 |
-
def chatGPT_invoice(userinput, temperature=0.1, max_tokens=300):
|
116 |
-
response = client.chat.completions.create(
|
117 |
-
model="tiiuae/falcon-180B-chat",
|
118 |
-
messages=[
|
119 |
-
{"role": "system", "content": '''from the following invoice, find the name of the restaurant, then write a table for each food in the invoice and estimate its calories count only knowing that this food is from the same restaurant, with no further text or comments, or notes:
|
120 |
-
example:
|
121 |
-
"Restaurant: KFC
|
122 |
-
<insert the table of food and estimated calories>"
|
123 |
-
Do it for this text:'''},
|
124 |
-
{"role": "user", "content": userinput}
|
125 |
-
],
|
126 |
-
temperature=temperature,
|
127 |
-
max_tokens=max_tokens
|
128 |
-
)
|
129 |
-
return response.choices[0].message.content
|
130 |
-
|
131 |
-
def update_plot(userinput):
|
132 |
-
# all_cals = chatGPT_food(userinput)
|
133 |
-
fig, ax = plt.subplots()
|
134 |
-
plot_calories(all_cals)
|
135 |
-
return fig
|
136 |
-
|
137 |
-
def ocr(input_img):
|
138 |
-
img1 = np.array(input_img)
|
139 |
-
text = pytesseract.image_to_string(img1)
|
140 |
-
output = chatGPT_invoice(text)
|
141 |
-
return output
|
142 |
-
|
143 |
-
with gr.Blocks() as demo:
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
greet_btn.
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
plot_btn.
|
160 |
-
|
161 |
-
|
|
|
|
1 |
+
from langchain.chat_models import ChatOpenAI
|
2 |
+
from langchain.schema import HumanMessage, SystemMessage
|
3 |
+
|
4 |
+
from langchain_community.tools import DuckDuckGoSearchRun
|
5 |
+
from ai71 import AI71
|
6 |
+
import gradio as gr
|
7 |
+
import openai
|
8 |
+
import os
|
9 |
+
import re
|
10 |
+
import matplotlib.pyplot as plt
|
11 |
+
|
12 |
+
from PIL import Image
|
13 |
+
import numpy as np
|
14 |
+
import pytesseract
|
15 |
+
# Make sure to import the necessary OpenAI API client and configure it.
|
16 |
+
# all_cals = {}
|
17 |
+
def extract_calories_and_items(text):
|
18 |
+
# Use regular expression to find all numerical values associated with "calory" or "calories"
|
19 |
+
pattern = r'(\d+)\s*(?:calory|calories)'
|
20 |
+
matches = re.findall(pattern, text, re.IGNORECASE)
|
21 |
+
|
22 |
+
# Convert the matches to integers
|
23 |
+
calories = [int(match) for match in matches]
|
24 |
+
|
25 |
+
return calories
|
26 |
+
|
27 |
+
def plot_calories(calories):
|
28 |
+
labels = sorted(calories, key=calories.get)
|
29 |
+
vals = [calories[label] for label in labels]
|
30 |
+
plt.barh(labels, vals, color='skyblue')
|
31 |
+
plt.xlabel('Calories')
|
32 |
+
plt.title('Item and Count')
|
33 |
+
plt.tight_layout()
|
34 |
+
|
35 |
+
def parse_items(items_string):
|
36 |
+
# Remove square brackets and split by comma
|
37 |
+
items_list = items_string.strip('[]').split(',')
|
38 |
+
|
39 |
+
item_dict = {}
|
40 |
+
|
41 |
+
# Define the pattern to match the quantity and item
|
42 |
+
pattern = r'(\d+)\s*x\s*(\w+)'
|
43 |
+
|
44 |
+
for item in items_list:
|
45 |
+
match = re.match(pattern, item.strip())
|
46 |
+
if match:
|
47 |
+
quantity = int(match.group(1))
|
48 |
+
item_name = match.group(2)
|
49 |
+
if item_name in item_dict:
|
50 |
+
item_dict[item_name] += quantity
|
51 |
+
else:
|
52 |
+
item_dict[item_name] = quantity
|
53 |
+
|
54 |
+
return item_dict
|
55 |
+
|
56 |
+
# Set the API key for AI71
|
57 |
+
#AI71_API_KEY = "key"
|
58 |
+
AI71_API_KEY = os.getenv('KEY')
|
59 |
+
AI71_BASE_URL = "https://api.ai71.ai/v1/"
|
60 |
+
client = AI71(AI71_API_KEY)
|
61 |
+
|
62 |
+
search = DuckDuckGoSearchRun()
|
63 |
+
|
64 |
+
# usr_input = input(f"User:")
|
65 |
+
#
|
66 |
+
# print(items)
|
67 |
+
|
68 |
+
|
69 |
+
|
70 |
+
def chatGPT_food(userinput, temperature=0.1, max_tokens=300):
|
71 |
+
|
72 |
+
keyword = client.chat.completions.create(
|
73 |
+
model="tiiuae/falcon-180B-chat",
|
74 |
+
messages=[
|
75 |
+
{"role": "system", "content": '''you need to extract the food item from the user text without any comments
|
76 |
+
example:
|
77 |
+
user: I ate two apples
|
78 |
+
assistant: 2 x apple'''},
|
79 |
+
{"role": "user", "content": userinput}
|
80 |
+
],
|
81 |
+
# temperature=0.5,
|
82 |
+
)
|
83 |
+
|
84 |
+
items = parse_items(keyword.choices[0].message.content)
|
85 |
+
|
86 |
+
for item, count in items.items():
|
87 |
+
result = search.invoke(f'calories of {item}')
|
88 |
+
|
89 |
+
response = client.chat.completions.create(
|
90 |
+
model="tiiuae/falcon-180B-chat",
|
91 |
+
messages=[
|
92 |
+
{"role": "system", "content": '''based on the provided information extract the calories count per portion of the item provided, just the calories and portion in grams or ml without further comments
|
93 |
+
Example:
|
94 |
+
orange 47 calories per 100 gram
|
95 |
+
cola 38 calories per 100 gram
|
96 |
+
do not generate more or add any unneeded comments, just follow the examples strictly'''},
|
97 |
+
{"role": "user", "content": result}
|
98 |
+
],
|
99 |
+
temperature=0.2,
|
100 |
+
)
|
101 |
+
|
102 |
+
# print("search")
|
103 |
+
# print(result)
|
104 |
+
# print("ai")
|
105 |
+
# print (response.choices[0].message.content)
|
106 |
+
calories = extract_calories_and_items(response.choices[0].message.content)
|
107 |
+
# print("calories")
|
108 |
+
# print(calories)
|
109 |
+
try:
|
110 |
+
all_cals[f"{count}x{item}"] = count*calories[0]
|
111 |
+
except:
|
112 |
+
continue
|
113 |
+
return all_cals
|
114 |
+
|
115 |
+
def chatGPT_invoice(userinput, temperature=0.1, max_tokens=300):
|
116 |
+
response = client.chat.completions.create(
|
117 |
+
model="tiiuae/falcon-180B-chat",
|
118 |
+
messages=[
|
119 |
+
{"role": "system", "content": '''from the following invoice, find the name of the restaurant, then write a table for each food in the invoice and estimate its calories count only knowing that this food is from the same restaurant, with no further text or comments, or notes:
|
120 |
+
example:
|
121 |
+
"Restaurant: KFC
|
122 |
+
<insert the table of food and estimated calories>"
|
123 |
+
Do it for this text:'''},
|
124 |
+
{"role": "user", "content": userinput}
|
125 |
+
],
|
126 |
+
temperature=temperature,
|
127 |
+
max_tokens=max_tokens
|
128 |
+
)
|
129 |
+
return response.choices[0].message.content
|
130 |
+
|
131 |
+
def update_plot(userinput):
|
132 |
+
# all_cals = chatGPT_food(userinput)
|
133 |
+
fig, ax = plt.subplots()
|
134 |
+
plot_calories(all_cals)
|
135 |
+
return fig
|
136 |
+
|
137 |
+
def ocr(input_img):
|
138 |
+
img1 = np.array(input_img)
|
139 |
+
text = pytesseract.image_to_string(img1)
|
140 |
+
output = chatGPT_invoice(text)
|
141 |
+
return output
|
142 |
+
|
143 |
+
with gr.Blocks() as demo:
|
144 |
+
all_cals = {}
|
145 |
+
with gr.Tab("Food Calories"):
|
146 |
+
food = gr.Textbox(label="Food")
|
147 |
+
output = gr.Textbox(label="Calories")
|
148 |
+
greet_btn = gr.Button("Get Calories")
|
149 |
+
greet_btn.click(fn=chatGPT_food, inputs=food, outputs=output)
|
150 |
+
|
151 |
+
with gr.Tab("Invoice OCR"):
|
152 |
+
image_input = gr.Image(height=200, width=200)
|
153 |
+
output_text = gr.Textbox(label="Estimated Calories from Invoice")
|
154 |
+
demo_ocr = gr.Interface(fn=ocr, inputs=image_input, outputs=output_text)
|
155 |
+
|
156 |
+
with gr.Tab("Calories Plot"):
|
157 |
+
# food_plot = gr.Textbox(label="Enter Food for Plot")
|
158 |
+
plot_output = gr.Plot(label="Calories Plot")
|
159 |
+
plot_btn = gr.Button("Generate Plot")
|
160 |
+
plot_btn.click(fn=update_plot, inputs=plot_btn, outputs=plot_output)
|
161 |
+
|
162 |
+
demo.launch()
|