Spaces:
Sleeping
Sleeping
prithivida
commited on
Commit
•
e551c21
1
Parent(s):
92160fe
maintenance
Browse files
app.py
CHANGED
@@ -1,127 +1,7 @@
|
|
1 |
import streamlit as st
|
2 |
-
import streamlit.components.v1 as components
|
3 |
-
import pickle
|
4 |
-
import sentence_transformers
|
5 |
-
from sentence_transformers import SentenceTransformer, util
|
6 |
from PIL import Image
|
7 |
-
import torch
|
8 |
-
import spacy
|
9 |
-
import os
|
10 |
-
import glob
|
11 |
-
import random
|
12 |
-
import pysos
|
13 |
-
from random import shuffle
|
14 |
|
15 |
-
torch.set_num_threads(4)
|
16 |
-
|
17 |
-
|
18 |
-
def get_spacy_dbpedia_highlights(ingredients):
|
19 |
-
import spacy
|
20 |
-
import spacy_dbpedia_spotlight
|
21 |
-
|
22 |
-
raw_ingredients = ingredients
|
23 |
-
import re
|
24 |
-
ingredients = re.sub("[0-9,()\/\-\.]", "", ingredients)
|
25 |
-
doc = nlp(ingredients)
|
26 |
-
|
27 |
-
for ent in doc.ents:
|
28 |
-
if ent.text.lower() not in stop_words and ent.text in raw_ingredients:
|
29 |
-
replace_str = '<mark style="color: green; background-color:yellow"> <a href="' + ent.kb_id_ + '" target="_blank"> ' + ent.text + '</a> </mark>'
|
30 |
-
raw_ingredients = raw_ingredients.replace(ent.text, replace_str)
|
31 |
-
return raw_ingredients
|
32 |
-
|
33 |
-
def detect_food(query, text_emb, labels, k=1):
|
34 |
-
query_emb = model.encode(Image.open(query), convert_to_tensor=True, show_progress_bar=False)
|
35 |
-
hits = util.semantic_search(query_emb, text_emb, top_k=k)[0]
|
36 |
-
results = []
|
37 |
-
for i, hit in enumerate(hits):
|
38 |
-
results.append((labels[hit['corpus_id']], hit['score']))
|
39 |
-
if i > 2:
|
40 |
-
break
|
41 |
-
return results
|
42 |
-
|
43 |
-
def run_search(food_image, col2):
|
44 |
-
|
45 |
-
with open("./Pretrained/labels.pkl", 'rb') as fIn:
|
46 |
-
labels = pickle.load(fIn)
|
47 |
-
|
48 |
-
emb_filename = './Pretrained/food_embeddings.pkl'
|
49 |
-
text_emb = torch.load(emb_filename, map_location=torch.device('cpu'))
|
50 |
-
|
51 |
-
results = detect_food(food_image, text_emb, labels, 3)
|
52 |
-
food_recognised, score = results[0]
|
53 |
-
|
54 |
-
del text_emb
|
55 |
-
del labels
|
56 |
-
|
57 |
-
import pysos
|
58 |
-
food2id = pysos.Dict("./Pretrained/food2id")
|
59 |
-
id2recipe = pysos.Dict("./Pretrained/id2recipe")
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
id = food2id[food_recognised]
|
64 |
-
|
65 |
-
recipe_name = food_recognised.title()
|
66 |
-
ingredients_list =id2recipe[id]['ingredients']
|
67 |
-
highlighted_ingredients= get_spacy_dbpedia_highlights(ingredients_list)
|
68 |
-
recipe= id2recipe[id]['instructions']
|
69 |
-
dataset = " " + id2recipe[id]['dataset']
|
70 |
-
if dataset.strip() == "Recipe1M":
|
71 |
-
nutritional_facts= "For nutritional facts, schedule and servings, visit the link in the footer"
|
72 |
-
else:
|
73 |
-
nutritional_facts = id2recipe[id]['nutrition_facts']
|
74 |
-
source= id2recipe[id]['recipesource']
|
75 |
-
|
76 |
-
|
77 |
-
del id2recipe
|
78 |
-
del food2id
|
79 |
-
|
80 |
-
st.markdown("<br/>", unsafe_allow_html=True)
|
81 |
-
with col2:
|
82 |
-
st.markdown("<b>Top 3 predictions   </b>", unsafe_allow_html=True)
|
83 |
-
results_static_tag = '<html><title>W3.CSS</title><meta name="viewport" content="width=device-width, initial-scale=1"><link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"><body><div class="w3-container">{}</div></body></html>'
|
84 |
-
result_rows = ""
|
85 |
-
for i, result in enumerate(results):
|
86 |
-
results_dynamic_tag= '{} <br/> <div class="w3-light-grey"> <div class="{}" style="height:4px;width:{}%"></div> </div><br>'
|
87 |
-
if i == 0:
|
88 |
-
results_dynamic_tag = results_dynamic_tag.format("<b>" + str(i+1) + "." + result[0].title() + "</b>", 'w3-blue', result[1] * 100)
|
89 |
-
else:
|
90 |
-
results_dynamic_tag = results_dynamic_tag.format(str(i+1) + "." + result[0].title(), "w3-orange" ,result[1] * 100)
|
91 |
-
result_rows += results_dynamic_tag
|
92 |
-
results_static_tag = results_static_tag.format(result_rows)
|
93 |
-
st.markdown(results_static_tag, unsafe_allow_html=True)
|
94 |
-
|
95 |
-
title_tag = '<h4> Recipe for top result:  ' + recipe_name + '</h4>'
|
96 |
-
st.markdown(title_tag, unsafe_allow_html=True)
|
97 |
-
|
98 |
-
ing_hdr_tag = '<h5> Ingredients </h5>'
|
99 |
-
ing_style= "{border: 3x outset white; background-color: #ccf5ff; color: black; text-align: left; font-size: 14px; padding: 5px;}"
|
100 |
-
ing_tag = '<html><head><style>.ingdiv{}</style></head><body><div class="ingdiv">{}</div></body></html>'
|
101 |
-
ing_tag = ing_tag.format(ing_style, highlighted_ingredients.strip())
|
102 |
-
st.markdown(ing_hdr_tag, unsafe_allow_html=True)
|
103 |
-
st.markdown(ing_tag + "<br/>", unsafe_allow_html=True)
|
104 |
-
|
105 |
-
|
106 |
-
rec_hdr_tag = '<h5> Recipe </h5>'
|
107 |
-
rec_style= "{border: 3x outset white; background-color: #ffeee6; color: black; text-align: left; font-size: 14px; padding: 5px;}"
|
108 |
-
rec_tag = '<html><head><style>.recdiv{}</style></head><body><div class="recdiv">{}</div></body></html>'
|
109 |
-
rec_tag = rec_tag.format(rec_style, recipe.strip())
|
110 |
-
st.markdown(rec_hdr_tag, unsafe_allow_html=True)
|
111 |
-
st.markdown(rec_tag + "<br/>", unsafe_allow_html=True)
|
112 |
-
|
113 |
-
|
114 |
-
src_hdr_tag = '<h5> Recipe source </h5>'
|
115 |
-
src_tag = '<a href={} target="_blank">{}</a>'
|
116 |
-
src_tag = src_tag.format(source, source)
|
117 |
-
st.markdown(src_hdr_tag, unsafe_allow_html=True)
|
118 |
-
st.markdown(src_tag + "<br/>", unsafe_allow_html=True)
|
119 |
-
|
120 |
-
return 1
|
121 |
-
|
122 |
-
|
123 |
-
if 'models_loaded' not in st.session_state:
|
124 |
-
st.session_state['models_loaded'] = False
|
125 |
|
126 |
st.title('WTF - What The Food 🤬')
|
127 |
st.subheader("Image to Recipe - 1.5M foods supported")
|
@@ -133,70 +13,9 @@ def load_image(image_file):
|
|
133 |
img = Image.open(image_file)
|
134 |
return img
|
135 |
|
136 |
-
def load_models():
|
137 |
-
with st.spinner(text="Loading models, please wait..."):
|
138 |
-
os.system("python -m spacy download en_core_web_sm")
|
139 |
-
nlp = spacy.load('en_core_web_sm')
|
140 |
-
nlp.add_pipe('dbpedia_spotlight')
|
141 |
-
model = SentenceTransformer('clip-ViT-B-32')
|
142 |
-
stop_words = set(['chopped', 'freshly ground', 'skinless', 'freshly squeezed', 'dash', 'powder', 'rice', 'ice', 'noodles', 'pepper', 'milk', 'ced', 'cheese', 'sugar', 'salt', 'pkt', 'minced', 'onion', 'onions', 'garlic', 'butter', 'slices', 'ounce', 'sauce', 'freshly', 'grated', 'teaspoon', 'cup', 'oz', '⁄', 'to', 'or', 'diced', 'into', 'pound', 'dried', 'water', 'about', 'whole', 'small', 'vegetable', 'inch', 'tbsp', 'cooked', 'large', 'sliced', 'dry', 'optional', 'package', 'ounces', 'unsalted', 'lbs', 'green', 'flour', 'for', 'wine', 'crushed', 'drained', 'lb', 'frozen', 'tsp', 'finely', 'medium', 'tablespoon', 'tablespoons', 'juice', 'shredded', 'can', 'minced', 'fresh', 'cut', 'pieces', 'in', 'thinly', 'of', 'extract', 'teaspoons', 'ground', 'and', 'cups', 'peeled', 'taste', 'ml', 'lengths'])
|
143 |
-
st.session_state['nlp'] = nlp
|
144 |
-
st.session_state['model'] = model
|
145 |
-
st.session_state['stop_words'] = stop_words
|
146 |
-
#st.session_state['id2recipe'] = pysos.Dict("./Pretrained/id2recipe")
|
147 |
-
# st.session_state['food2id'] = pysos.Dict("./Pretrained/food2id")
|
148 |
-
# with open("./Pretrained/labels.pkl", 'rb') as fIn:
|
149 |
-
# labels = pickle.load(fIn)
|
150 |
-
# st.session_state['labels'] = labels
|
151 |
-
#emb_filename = './Pretrained/food_embeddings.pkl'
|
152 |
-
#text_emb = torch.load(emb_filename, map_location=torch.device('cpu'))
|
153 |
-
#st.session_state['text_emb'] = text_emb
|
154 |
-
|
155 |
-
|
156 |
-
if not st.session_state['models_loaded']:
|
157 |
-
load_models()
|
158 |
-
st.session_state['models_loaded'] = True
|
159 |
-
|
160 |
-
random_button = st.button('⚡ Try a Random Food')
|
161 |
-
st.write("(or)")
|
162 |
-
st.info('Upload a HD, landscape image')
|
163 |
-
image_file = st.file_uploader("", type=["jpg","jpeg"])
|
164 |
-
|
165 |
-
nlp = st.session_state['nlp']
|
166 |
-
model = st.session_state['model']
|
167 |
-
stop_words = st.session_state['stop_words']
|
168 |
-
#id2recipe = st.session_state['id2recipe']
|
169 |
-
#text_emb = st.session_state['text_emb']
|
170 |
-
# food2id = st.session_state['food2id']
|
171 |
-
# labels = st.session_state['labels']
|
172 |
-
|
173 |
-
|
174 |
-
col1, col2 = st.columns(2)
|
175 |
-
|
176 |
-
if random_button:
|
177 |
-
|
178 |
-
with st.spinner(text="Detecting food..."):
|
179 |
-
samples = glob.glob('./samples' + "/*")
|
180 |
-
shuffle(samples)
|
181 |
-
random_sample = random.choice(samples)
|
182 |
-
pil_image = load_image(random_sample)
|
183 |
-
with col1:
|
184 |
-
st.image(pil_image, use_column_width='auto')
|
185 |
-
return_code = run_search(random_sample, col2)
|
186 |
-
else:
|
187 |
-
if image_file is not None:
|
188 |
-
pil_image = load_image(image_file)
|
189 |
-
with open(image_file.name, 'wb') as f:
|
190 |
-
pil_image.save(f)
|
191 |
-
|
192 |
-
with col1:
|
193 |
-
st.image(pil_image, use_column_width='auto')
|
194 |
-
|
195 |
-
with st.spinner(text="Detecting food..."):
|
196 |
-
return_code = run_search(image_file.name, col2)
|
197 |
-
os.system('rm -r "' + image_file.name + '"')
|
198 |
-
|
199 |
|
200 |
-
|
|
|
|
|
201 |
|
202 |
|
|
|
1 |
import streamlit as st
|
2 |
+
import streamlit.components.v1 as components
|
|
|
|
|
|
|
3 |
from PIL import Image
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
|
6 |
st.title('WTF - What The Food 🤬')
|
7 |
st.subheader("Image to Recipe - 1.5M foods supported")
|
|
|
13 |
img = Image.open(image_file)
|
14 |
return img
|
15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
|
17 |
+
pil_image = load_image("./samples/under_maint.png")
|
18 |
+
st.image(pil_image)
|
19 |
+
st.write("Please come back later")
|
20 |
|
21 |
|