prithivida commited on
Commit
9cbc26e
β€’
1 Parent(s): 92130e3

Update with InferenceServer call

Browse files
Files changed (1) hide show
  1. app.py +137 -8
app.py CHANGED
@@ -1,21 +1,150 @@
 
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")
8
- st.markdown("Built for fun with πŸ’™ by a quintessential foodie - Prithivi Da, The maker of [Gramformer](https://github.com/PrithivirajDamodaran/Gramformer), [Styleformer](https://github.com/PrithivirajDamodaran/Styleformer) and [Parrot paraphraser](https://github.com/PrithivirajDamodaran/Parrot_Paraphraser) | [@prithivida](https://twitter.com/prithivida) |[[GitHub]](https://github.com/PrithivirajDamodaran)", unsafe_allow_html=True)
9
  st.markdown("""<i> (Read Me: The idea: Food Image => Recipe. So it works on single foods and platters <p style='color:red; display:inline'> but May Not perform well on custom combinations or hyper-local foods.</p>) </i>""", unsafe_allow_html=True)
10
 
11
 
12
- def load_image(image_file):
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.info("Regret the inconvenience, Please come back later")
20
 
21
 
 
1
+
2
  import streamlit as st
3
+ import streamlit.components.v1 as components
4
  from PIL import Image
5
+ import os
6
+ import glob
7
+ import random
8
+ from random import shuffle
9
+ import requests
10
+ import time
11
+ from multiprocessing import Process
12
+ import json
13
+
14
+
15
+ def load_image(image_file):
16
+ img = Image.open(image_file)
17
+ return img
18
+
19
+ def start_server():
20
+ os.system("uvicorn InferenceServer:app --port 8080 --host 0.0.0.0 --workers 1")
21
+
22
+ def load_models():
23
+ if not is_port_in_use(8080):
24
+ with st.spinner(text="Loading models, please wait..."):
25
+ proc = Process(target=start_server, args=(), daemon=True)
26
+ proc.start()
27
+ while not is_port_in_use(8080):
28
+ time.sleep(1)
29
+ st.success("Model server started.")
30
+ else:
31
+ st.success("Model server already running...")
32
+ st.session_state['models_loaded'] = True
33
+
34
+
35
+ def is_port_in_use(port):
36
+ import socket
37
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
38
+ return s.connect_ex(('0.0.0.0', port)) == 0
39
+
40
+
41
+ def run_search(food_image):
42
+
43
+ get_request = "http://0.0.0.0:8080/food?food_input="+food_image
44
+ food_response = requests.get(get_request)
45
+ food_response_obj = json.loads(food_response.text)
46
+ results = food_response_obj["top3"]
47
 
48
+ st.markdown("<br/>", unsafe_allow_html=True)
49
+ with col2:
50
+ st.markdown("<b>Top 3 predictions &nbsp </b>", unsafe_allow_html=True)
51
+ 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>'
52
+ result_rows = ""
53
+ for i, result in enumerate(results):
54
+ results_dynamic_tag= '{} <br/> <div class="w3-light-grey"> <div class="{}" style="height:4px;width:{}%"></div> </div><br>'
55
+ if i == 0:
56
+ results_dynamic_tag = results_dynamic_tag.format("<b>" + str(i+1) + "." + result[0].title() + "</b>", 'w3-blue', result[1] * 100)
57
+ else:
58
+ results_dynamic_tag = results_dynamic_tag.format(str(i+1) + "." + result[0].title(), "w3-orange" ,result[1] * 100)
59
+ result_rows += results_dynamic_tag
60
+ results_static_tag = results_static_tag.format(result_rows)
61
+ st.markdown(results_static_tag, unsafe_allow_html=True)
62
+
63
+ recipe_response_obj = food_response_obj["recipe"]
64
+ recipe_name = recipe_response_obj['recipe_name']
65
+ highlighted_ingredients =recipe_response_obj['highlighted_ingredients']
66
+ recipe = recipe_response_obj['recipe']
67
+ source = recipe_response_obj['source']
68
+ nutritional_facts = recipe_response_obj['nutritional_facts']
69
+
70
+ title_tag = '<h4> Recipe for top result: &nbsp' + recipe_name + '</h4>'
71
+ st.markdown(title_tag, unsafe_allow_html=True)
72
+
73
+ ing_hdr_tag = '<h5> Ingredients </h5>'
74
+ ing_style= "{border: 3x outset white; background-color: #ccf5ff; color: black; text-align: left; font-size: 14px; padding: 5px;}"
75
+ ing_tag = '<html><head><style>.ingdiv{}</style></head><body><div class="ingdiv">{}</div></body></html>'
76
+ ing_tag = ing_tag.format(ing_style, highlighted_ingredients.strip())
77
+ st.markdown(ing_hdr_tag, unsafe_allow_html=True)
78
+ st.markdown(ing_tag + "<br/>", unsafe_allow_html=True)
79
+
80
+
81
+ rec_hdr_tag = '<h5> Recipe </h5>'
82
+ rec_style= "{border: 3x outset white; background-color: #ffeee6; color: black; text-align: left; font-size: 14px; padding: 5px;}"
83
+ rec_tag = '<html><head><style>.recdiv{}</style></head><body><div class="recdiv">{}</div></body></html>'
84
+ rec_tag = rec_tag.format(rec_style, recipe.strip())
85
+ st.markdown(rec_hdr_tag, unsafe_allow_html=True)
86
+ st.markdown(rec_tag + "<br/>", unsafe_allow_html=True)
87
+
88
+ nut_hdr_tag = '<h5> Nutritional facts </h5>'
89
+ nut_style= "{border: 3x outset white; background-color: #e6e6ff; color: black; text-align: left; font-size: 14px; padding: 5px;}"
90
+ nut_tag = '<html><head><style>.nutdiv{}</style></head><body><div class="nutdiv">{}</div></body></html>'
91
+ nut_tag = nut_tag.format(nut_style, nutritional_facts.strip())
92
+ st.markdown(nut_hdr_tag, unsafe_allow_html=True)
93
+ st.markdown(nut_tag + "<br/>", unsafe_allow_html=True)
94
+
95
+ src_hdr_tag = '<h5> Recipe source </h5>'
96
+ src_tag = '<a href={} target="_blank">{}</a>'
97
+ src_tag = src_tag.format(source, source)
98
+ st.markdown(src_hdr_tag, unsafe_allow_html=True)
99
+ st.markdown(src_tag + "<br/>", unsafe_allow_html=True)
100
+
101
+ return 1
102
+
103
+
104
+ if 'models_loaded' not in st.session_state:
105
+ st.session_state['models_loaded'] = False
106
 
107
  st.title('WTF - What The Food 🀬')
108
  st.subheader("Image to Recipe - 1.5M foods supported")
109
+ st.markdown("Built for fun with πŸ’™ by a quintessential foodie - Prithivi Da, The maker of [Gramformer](https://github.com/PrithivirajDamodaran/Gramformer), [Styleformer](https://github.com/PrithivirajDamodaran/Styleformer) and [Parrot paraphraser](https://github.com/PrithivirajDamodaran/Parrot_Paraphraser) | ✍️ [@prithivida](https://twitter.com/prithivida) |[[GitHub]](https://github.com/PrithivirajDamodaran)", unsafe_allow_html=True)
110
  st.markdown("""<i> (Read Me: The idea: Food Image => Recipe. So it works on single foods and platters <p style='color:red; display:inline'> but May Not perform well on custom combinations or hyper-local foods.</p>) </i>""", unsafe_allow_html=True)
111
 
112
 
113
+
114
+ if __name__ == '__main__':
115
+ if not st.session_state['models_loaded']:
116
+ load_models()
117
+
118
+ random_button = st.button('⚑ Try a Random Food')
119
+ st.write("(or)")
120
+ st.info('Upload a HD, landscape image')
121
+ image_file = st.file_uploader("", type=["jpg","jpeg"])
122
+ col1, col2 = st.columns(2)
123
+
124
+ if random_button:
125
+
126
+ with st.spinner(text="Detecting food..."):
127
+ samples = glob.glob('./samples' + "/*")
128
+ shuffle(samples)
129
+ random_sample = random.choice(samples)
130
+ pil_image = load_image(random_sample)
131
+ with col1:
132
+ st.image(pil_image, use_column_width='auto')
133
+ return_code = run_search(random_sample)
134
+ else:
135
+ if image_file is not None:
136
+ pil_image = load_image(image_file)
137
+ with open(image_file.name, 'wb') as f:
138
+ pil_image.save(f)
139
+
140
+ with col1:
141
+ st.image(pil_image, use_column_width='auto')
142
+
143
+ with st.spinner(text="Detecting food..."):
144
+ return_code = run_search(image_file.name)
145
+ os.system('rm -r "' + image_file.name + '"')
146
+
147
 
148
 
 
 
 
149
 
150