OmPrakashSingh1704 commited on
Commit
ffb922b
·
verified ·
1 Parent(s): 49c5906

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +299 -296
app.py CHANGED
@@ -13,39 +13,42 @@ import plotly.express as px
13
 
14
  st.set_page_config(layout="wide")
15
 
16
- # Load environment token
17
- login(token=os.getenv("TOKEN"))
 
18
 
19
- # Load data from pickled files
20
- with open('cv.pkl', 'rb') as file:
21
- cv = pickle.load(file)
22
 
23
- with open('vectors.pkl', 'rb') as file:
24
- vectors = pickle.load(file)
 
 
25
 
26
- with open('items_dict.pkl', 'rb') as file:
27
- items_dict = pd.DataFrame.from_dict(pickle.load(file))
 
28
 
29
 
30
- mode = st.toggle(label="MARTMAN")
31
 
32
  if 'ind' not in st.session_state:
33
  st.session_state.ind = []
34
 
 
 
 
35
  def preprocess_text(text):
36
  # Remove non-alphabet characters and extra spaces
37
  text = re.sub(r'[^a-zA-Z\s]', '', text)
38
  text = re.sub(r'\s+', ' ', text).strip()
39
  return text.lower()
40
-
41
  def get_recommendations(user_description, count_vectorizer, count_matrix):
42
  user_description = preprocess_text(user_description)
43
  user_vector = count_vectorizer.transform([user_description])
44
  cosine_similarities = cosine_similarity(user_vector, count_matrix).flatten()
45
  similar_indices = cosine_similarities.argsort()[::-1]
46
  return similar_indices
47
-
48
-
49
  def show_recipe(recipe):
50
  with st.spinner("HANG TIGHT, RECIPE INCOMING..."):
51
  name_and_dis = f'# {recipe["name"]}\n\n'
@@ -61,8 +64,7 @@ def show_recipe(recipe):
61
  cont = st.container(border=True, height=500)
62
  cont.write(ingredients)
63
  for j, i in enumerate(recipe["ingredients"]):
64
- x=i['name'].split()
65
- ind = get_recommendations(" ".join(x[2:])if len(x)>2 else " ".join(x) , cv, vectors)
66
  st.session_state.ind.append(ind[:5].tolist())
67
  cont.selectbox(i['name'],
68
  options=items_dict.iloc[ind][
@@ -71,295 +73,291 @@ def show_recipe(recipe):
71
  with col02:
72
  cont = st.container(border=True, height=500)
73
  cont.write(instructions)
 
 
 
74
 
 
 
75
 
76
- # Initialize the inference client for the Mixtral model
77
- if not mode:
78
- cook, saved = st.tabs(['COOK', 'SAVED'])
79
- with cook:
80
- client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
81
-
82
- if 'recipe' not in st.session_state:
83
- st.session_state.recipe = None
84
-
85
- if 'recipe_saved' not in st.session_state:
86
- st.session_state.recipe_saved = None
87
-
88
- if 'user_direction' not in st.session_state:
89
- st.session_state.user_direction = None
90
-
91
- if 'serving_size' not in st.session_state:
92
- st.session_state.serving_size = 2
93
-
94
- if 'selected_difficulty' not in st.session_state:
95
- st.session_state.selected_difficulty = "Quick & Easy"
96
-
97
- if 'exclusions' not in st.session_state:
98
- st.session_state.exclusions = None
99
-
100
-
101
- def create_detailed_prompt(user_direction, exclusions, serving_size, difficulty):
102
- if difficulty == "Quick & Easy":
103
- prompt = (
104
- f"Provide a 'Quick and Easy' recipe for {user_direction} that excludes {exclusions} and has a serving size of {serving_size}. "
105
- f"It should require as few ingredients as possible and should be ready in as little time as possible. "
106
- f"The steps should be simple, and the ingredients should be commonly found in a household pantry. "
107
- f"Provide a detailed ingredient list and step-by-step guide that explains the instructions to prepare in detail."
108
- )
109
- elif difficulty == "Intermediate":
110
- prompt = (
111
- f"Provide a classic recipe for {user_direction} that excludes {exclusions} and has a serving size of {serving_size}. "
112
- f"The recipe should offer a bit of a cooking challenge but should not require professional skills. "
113
- f"The recipe should feature traditional ingredients and techniques that are authentic to its cuisine. "
114
- f"Provide a detailed ingredient list and step-by-step guide that explains the instructions to prepare in detail."
115
- )
116
- elif difficulty == "Professional":
117
- prompt = (
118
- f"Provide an advanced recipe for {user_direction} that excludes {exclusions} and has a serving size of {serving_size}. "
119
- f"The recipe should push the boundaries of culinary arts, integrating unique ingredients, advanced cooking techniques, and innovative presentations. "
120
- f"The recipe should be able to be served at a high-end restaurant or would impress at a gourmet food competition. "
121
- f"Provide a detailed ingredient list and step-by-step guide that explains the instructions to prepare in detail."
122
- )
123
- return prompt
124
-
125
- def generate_recipe(user_inputs):
126
- with st.spinner('Building the perfect recipe...'):
127
- prompt = create_detailed_prompt(user_inputs['user_direction'], user_inputs['exclusions'],
128
- user_inputs['serving_size'], user_inputs['difficulty'])
129
-
130
- functions = [
131
- {
132
- "name": "provide_recipe",
133
- "description": "Provides a detailed recipe strictly adhering to the user input/specifications, especially ingredient exclusions and the recipe difficulty",
134
- "parameters": {
135
- "type": "object",
136
- "properties": {
137
- "name": {
138
- "type": "string",
139
- "description": "A creative name for the recipe"
140
- },
141
- "description": {
142
- "type": "string",
143
- "description": "a brief one-sentence description of the provided recipe"
144
- },
145
- "ingredients": {
146
- "type": "array",
147
- "items": {
148
- "type": "object",
149
- "properties": {
150
- "name": {
151
- "type": "string",
152
- "description": "Quantity and name of the ingredient"
153
- }
154
  }
155
  }
156
- },
157
- "instructions": {
158
- "type": "array",
159
- "items": {
160
- "type": "object",
161
- "properties": {
162
- "step_number": {
163
- "type": "number",
164
- "description": "The sequence number of this step"
165
- },
166
- "instruction": {
167
- "type": "string",
168
- "description": "Detailed description of what to do in this step"
169
- }
170
  }
171
  }
172
  }
173
- },
174
- "required": [
175
- "name",
176
- "description",
177
- "ingredients",
178
- "instructions"
179
- ],
180
  },
181
- }
182
- ]
183
-
184
- generate_kwargs = dict(
185
- temperature=0.9,
186
- max_new_tokens=10000,
187
- top_p=0.9,
188
- repetition_penalty=1.0,
189
- do_sample=True,
190
- )
191
-
192
- prompt += f"\nPlease format the output in JSON. The JSON should include fields for 'name', 'description', 'ingredients', and 'instructions', with each field structured as described below.\n\n{json.dumps(functions)}"
193
-
194
- response = client.text_generation(prompt, **generate_kwargs)
195
- st.session_state.recipe = response
196
- st.session_state.recipe_saved = False
197
-
198
- def clear_inputs():
199
- st.session_state.user_direction = None
200
- st.session_state.exclusions = None
201
- st.session_state.serving_size = 2
202
- st.session_state.selected_difficulty = "Quick & Easy"
203
- st.session_state.recipe = None
204
-
205
- st.title("Let's get cooking")
206
- col1, col2 = st.columns(2)
207
- with col1:
208
- st.session_state.user_direction = st.text_area(
209
- "What do you want to cook? Describe anything - a dish, cuisine, event, or vibe.",
210
- value=st.session_state.user_direction,
211
- placeholder="quick snack, asian style bowl with either noodles or rice, something italian",
212
- )
213
- with col2:
214
- st.session_state.serving_size = st.number_input(
215
- "How many servings would you like to cook?",
216
- min_value=1,
217
- max_value=100,
218
- value=st.session_state.serving_size,
219
- step=1
220
  )
221
 
222
- difficulty_dictionary = {
223
- "Quick & Easy": {
224
- "description": "Easy recipes with straightforward instructions. Ideal for beginners or those seeking quick and simple cooking.",
225
- },
226
- "Intermediate": {
227
- "description": "Recipes with some intricate steps that invite a little challenge. Perfect for regular cooks wanting to expand their repertoire with new ingredients and techniques.",
228
- },
229
- "Professional": {
230
- "description": "Complex recipes that demand a high level of skill and precision. Suited for seasoned cooks aspiring to professional-level sophistication and creativity.",
231
- }
232
- }
233
-
234
- st.session_state.selected_difficulty = st.radio(
235
- "Choose a difficulty level for your recipe.",
236
- [
237
- list(difficulty_dictionary.keys())[0],
238
- list(difficulty_dictionary.keys())[1],
239
- list(difficulty_dictionary.keys())[2]
240
- ],
241
- captions=[
242
- difficulty_dictionary["Quick & Easy"]["description"],
243
- difficulty_dictionary["Intermediate"]["description"],
244
- difficulty_dictionary["Professional"]["description"]
245
- ],
246
- index=list(difficulty_dictionary).index(st.session_state.selected_difficulty)
247
  )
248
-
249
- st.session_state.exclusions = st.text_area(
250
- "Any ingredients you want to exclude?",
251
- value=st.session_state.exclusions,
252
- placeholder="gluten, dairy, nuts, cilantro",
 
 
253
  )
254
 
255
- fancy_exclusions = ""
256
-
257
- if st.session_state.selected_difficulty == "Professional":
258
- exclude_fancy = st.checkbox(
259
- "Exclude cliche professional ingredients? (gold leaf, truffle, edible flowers, microgreens)",
260
- value=True)
261
- if exclude_fancy:
262
- fancy_exclusions = "gold leaf, truffle, edible flowers, microgreens, gold dust"
263
-
264
- user_inputs = {
265
- "user_direction": st.session_state.user_direction,
266
- "exclusions": f"{st.session_state.exclusions}, {fancy_exclusions}".strip(", "),
267
- "serving_size": st.session_state.serving_size,
268
- "difficulty": st.session_state.selected_difficulty
269
  }
270
-
271
- button_cols_submit = st.columns([1, 1, 4])
272
- with button_cols_submit[0]:
273
- st.button(label='Submit', on_click=generate_recipe, kwargs=dict(user_inputs=user_inputs),
274
- type="primary",
275
- use_container_width=True)
276
- with button_cols_submit[1]:
277
- st.button(label='Reset', on_click=clear_inputs, type="secondary", use_container_width=True)
278
- with button_cols_submit[2]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
279
  st.empty()
280
-
281
- def create_safe_filename(recipe_name):
282
- # format and generate random URL-safe text string
283
- safe_name = recipe_name.lower()
284
- safe_name = safe_name.replace(" ", "_")
285
- safe_name = re.sub(r"[^a-zA-Z0-9_]", "", safe_name)
286
- safe_name = (safe_name[:50]) if len(safe_name) > 50 else safe_name
287
- unique_token = secrets.token_hex(8)
288
- safe_filename = f"{unique_token}_{safe_name}"
289
- return safe_filename
290
-
291
- def save_recipe():
292
- with st.spinner('WAIT SAVING YOUR DISH...'):
293
- filename = create_safe_filename(recipe["name"])
294
- os.makedirs('data', exist_ok=True)
295
- with open(f'./data/{filename}.pkl', 'wb') as f:
296
- pickle.dump(recipe, f)
297
- st.session_state.recipe_saved = True
298
-
299
- if st.session_state.recipe is not None:
300
- st.divider()
301
- print(st.session_state.recipe)
302
- recipe = json.loads(st.session_state.recipe)
303
- show_recipe(recipe)
304
- recipe['timestamp'] = str(datetime.datetime.now())
305
- if st.session_state.recipe_saved == True:
306
- disable_button = True
307
- else:
308
- disable_button = False
309
- button_cols_save = st.columns([1, 1, 4])
310
- with button_cols_save[0]:
311
- st.button("Save Recipe", on_click=save_recipe, disabled=disable_button, type="primary")
312
- with button_cols_save[1]:
313
- st.empty()
314
- with button_cols_save[2]:
315
- st.empty()
316
- if st.session_state.recipe_saved == True:
317
- st.success("Recipe Saved!")
318
- with saved:
319
- st.title("Saved Recipes")
320
- with st.spinner('LOADING YOUR RECIPE...'):
321
- def load_saved_recipes_from_pickle(directory_path):
322
- os.makedirs('data', exist_ok=True)
323
- recipes = []
324
- # Iterate through all files in the directory
325
- for filename in os.listdir(directory_path):
326
- if filename.endswith('.pkl'):
327
- file_path = os.path.join(directory_path, filename)
328
- with open(file_path, 'rb') as file:
329
- recipe = pickle.load(file)
330
- recipes.append(recipe)
331
- return recipes
332
-
333
- # get all saved files
334
- directory_path = 'data'
335
- recipes = load_saved_recipes_from_pickle(directory_path)
336
- print(recipes)
337
-
338
- cols = st.columns([4, 1])
339
- with cols[1]:
340
- user_sort = st.selectbox("Sort", ('Recent', 'Oldest', 'A-Z', 'Z-A', 'Random'))
341
- if user_sort == 'Recent':
342
- recipes.sort(key=lambda x: x['timestamp'], reverse=True)
343
- elif user_sort == 'Oldest':
344
- recipes.sort(key=lambda x: x['timestamp'])
345
- elif user_sort == 'A-Z':
346
- recipes.sort(key=lambda x: x['name'])
347
- elif user_sort == 'Z-A':
348
- recipes.sort(key=lambda x: x['name'], reverse=True)
349
- elif user_sort == 'Random':
350
- recipes.sort(key=lambda x: x['file'])
351
- with cols[0]:
352
- user_search = st.selectbox("Search Recipes", [""] + [recipe['name'] for recipe in recipes])
353
- st.write("") # just some space
354
-
355
- if user_search != "":
356
- st.divider()
357
- filtered_recipes = [recipe for recipe in recipes if recipe['name'] == user_search]
358
- if filtered_recipes:
359
- show_recipe(filtered_recipes[0])
360
- else:
361
- st.write("No recipe found.")
362
- else:
363
  st.markdown("# :eyes: PEOPLE SEARCHING FOR...")
364
  print(st.session_state.ind)
365
  flattened_indices = list(set(index for sublist in st.session_state.ind for index in sublist))
@@ -395,7 +393,7 @@ else:
395
  st.plotly_chart(fig1, use_container_width=True)
396
 
397
  with st.container(border=True, height=620):
398
- st.markdown('## :deciduous_tree: Hierarchical view of Sales using TreeMap')
399
  fig4 = px.treemap(df, path=['CATEGORY', 'AVAILABILITY','PRODUCT'],color='AVAILABILITY')
400
  fig4.update_layout(height=550)
401
  st.plotly_chart(fig4, use_container_width=True,scrolling=False)
@@ -407,13 +405,18 @@ else:
407
  color='BRAND',
408
  # title='Gross Sales of Every Segment Country-wise',
409
  barmode='relative',
410
- title="Segment Vs. Gross Sales"
411
  )
412
  st.plotly_chart(fig, use_container_width=True)
413
-
414
- @st.cache_resource
415
- def pygwalerapp(df):
416
- return StreamlitRenderer(df)
417
  # st.markdown("## :desktop_computer: DO YOUR OWN RESEARCH...")
418
  with st.expander("## :desktop_computer: LOOKING FOR SOMETHING ELSE..."):
419
- pygwalerapp(df).explorer()
 
 
 
 
 
 
 
 
 
 
13
 
14
  st.set_page_config(layout="wide")
15
 
16
+ @st.cache_resource(experimental_allow_widgets=True)
17
+ def login_huggingface(token):
18
+ login(token=token)
19
 
20
+ login_huggingface(token=os.getenv("TOKEN"))
 
 
21
 
22
+ @st.cache_data
23
+ def load_pickle(file_path):
24
+ with open(file_path, 'rb') as file:
25
+ return pickle.load(file)
26
 
27
+ cv = load_pickle('cv.pkl')
28
+ vectors = load_pickle('vectors.pkl')
29
+ items_dict = pd.DataFrame.from_dict(load_pickle('items_dict.pkl'))
30
 
31
 
32
+ mode = st.toggle(label="MART")
33
 
34
  if 'ind' not in st.session_state:
35
  st.session_state.ind = []
36
 
37
+ @st.cache_resource(experimental_allow_widgets=True,show_spinner=False)
38
+ def pygwalerapp(df):
39
+ return StreamlitRenderer(df)
40
  def preprocess_text(text):
41
  # Remove non-alphabet characters and extra spaces
42
  text = re.sub(r'[^a-zA-Z\s]', '', text)
43
  text = re.sub(r'\s+', ' ', text).strip()
44
  return text.lower()
 
45
  def get_recommendations(user_description, count_vectorizer, count_matrix):
46
  user_description = preprocess_text(user_description)
47
  user_vector = count_vectorizer.transform([user_description])
48
  cosine_similarities = cosine_similarity(user_vector, count_matrix).flatten()
49
  similar_indices = cosine_similarities.argsort()[::-1]
50
  return similar_indices
51
+ @st.cache_resource(experimental_allow_widgets=True,show_spinner=False)
 
52
  def show_recipe(recipe):
53
  with st.spinner("HANG TIGHT, RECIPE INCOMING..."):
54
  name_and_dis = f'# {recipe["name"]}\n\n'
 
64
  cont = st.container(border=True, height=500)
65
  cont.write(ingredients)
66
  for j, i in enumerate(recipe["ingredients"]):
67
+ ind = get_recommendations(i['name'], cv, vectors)
 
68
  st.session_state.ind.append(ind[:5].tolist())
69
  cont.selectbox(i['name'],
70
  options=items_dict.iloc[ind][
 
73
  with col02:
74
  cont = st.container(border=True, height=500)
75
  cont.write(instructions)
76
+ @st.cache_resource(experimental_allow_widgets=True,show_spinner=False)
77
+ def cooking():
78
+ client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
79
 
80
+ if 'recipe' not in st.session_state:
81
+ st.session_state.recipe = None
82
 
83
+ if 'recipe_saved' not in st.session_state:
84
+ st.session_state.recipe_saved = None
85
+
86
+ if 'user_direction' not in st.session_state:
87
+ st.session_state.user_direction = None
88
+
89
+ if 'serving_size' not in st.session_state:
90
+ st.session_state.serving_size = 2
91
+
92
+ if 'selected_difficulty' not in st.session_state:
93
+ st.session_state.selected_difficulty = "Quick & Easy"
94
+
95
+ if 'exclusions' not in st.session_state:
96
+ st.session_state.exclusions = None
97
+
98
+ def create_detailed_prompt(user_direction, exclusions, serving_size, difficulty):
99
+ if difficulty == "Quick & Easy":
100
+ prompt = (
101
+ f"Provide a 'Quick and Easy' recipe for {user_direction} that excludes {exclusions} and has a serving size of {serving_size}. "
102
+ f"It should require as few ingredients as possible and should be ready in as little time as possible. "
103
+ f"The steps should be simple, and the ingredients should be commonly found in a household pantry. "
104
+ f"Provide a detailed ingredient list and step-by-step guide that explains the instructions to prepare in detail."
105
+ )
106
+ elif difficulty == "Intermediate":
107
+ prompt = (
108
+ f"Provide a classic recipe for {user_direction} that excludes {exclusions} and has a serving size of {serving_size}. "
109
+ f"The recipe should offer a bit of a cooking challenge but should not require professional skills. "
110
+ f"The recipe should feature traditional ingredients and techniques that are authentic to its cuisine. "
111
+ f"Provide a detailed ingredient list and step-by-step guide that explains the instructions to prepare in detail."
112
+ )
113
+ elif difficulty == "Professional":
114
+ prompt = (
115
+ f"Provide an advanced recipe for {user_direction} that excludes {exclusions} and has a serving size of {serving_size}. "
116
+ f"The recipe should push the boundaries of culinary arts, integrating unique ingredients, advanced cooking techniques, and innovative presentations. "
117
+ f"The recipe should be able to be served at a high-end restaurant or would impress at a gourmet food competition. "
118
+ f"Provide a detailed ingredient list and step-by-step guide that explains the instructions to prepare in detail."
119
+ )
120
+ return prompt
121
+
122
+ def generate_recipe(user_inputs):
123
+ with st.spinner('Building the perfect recipe...'):
124
+ prompt = create_detailed_prompt(user_inputs['user_direction'], user_inputs['exclusions'],
125
+ user_inputs['serving_size'], user_inputs['difficulty'])
126
+
127
+ functions = [
128
+ {
129
+ "name": "provide_recipe",
130
+ "description": "Provides a detailed recipe strictly adhering to the user input/specifications, especially ingredient exclusions and the recipe difficulty",
131
+ "parameters": {
132
+ "type": "object",
133
+ "properties": {
134
+ "name": {
135
+ "type": "string",
136
+ "description": "A creative name for the recipe"
137
+ },
138
+ "description": {
139
+ "type": "string",
140
+ "description": "a brief one-sentence description of the provided recipe"
141
+ },
142
+ "ingredients": {
143
+ "type": "array",
144
+ "items": {
145
+ "type": "object",
146
+ "properties": {
147
+ "name": {
148
+ "type": "string",
149
+ "description": "Quantity and name of the ingredient"
 
 
 
 
 
 
 
 
 
 
 
150
  }
151
  }
152
+ }
153
+ },
154
+ "instructions": {
155
+ "type": "array",
156
+ "items": {
157
+ "type": "object",
158
+ "properties": {
159
+ "step_number": {
160
+ "type": "number",
161
+ "description": "The sequence number of this step"
162
+ },
163
+ "instruction": {
164
+ "type": "string",
165
+ "description": "Detailed description of what to do in this step"
166
  }
167
  }
168
  }
169
+ }
 
 
 
 
 
 
170
  },
171
+ "required": [
172
+ "name",
173
+ "description",
174
+ "ingredients",
175
+ "instructions"
176
+ ],
177
+ },
178
+ }
179
+ ]
180
+
181
+ generate_kwargs = dict(
182
+ temperature=0.9,
183
+ max_new_tokens=10000,
184
+ top_p=0.9,
185
+ repetition_penalty=1.0,
186
+ do_sample=True,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
  )
188
 
189
+ prompt += f"\nPlease format the output in JSON. The JSON should include fields for 'name', 'description', 'ingredients', and 'instructions', with each field structured as described below.\n\n{json.dumps(functions)}"
190
+
191
+ response = client.text_generation(prompt, **generate_kwargs)
192
+ st.session_state.recipe = response
193
+ st.session_state.recipe_saved = False
194
+
195
+ def clear_inputs():
196
+ st.session_state.user_direction = None
197
+ st.session_state.exclusions = None
198
+ st.session_state.serving_size = 2
199
+ st.session_state.selected_difficulty = "Quick & Easy"
200
+ st.session_state.recipe = None
201
+
202
+ st.title("Let's get cooking")
203
+ col1, col2 = st.columns(2)
204
+ with col1:
205
+ st.session_state.user_direction = st.text_area(
206
+ "What do you want to cook? Describe anything - a dish, cuisine, event, or vibe.",
207
+ value=st.session_state.user_direction,
208
+ placeholder="quick snack, asian style bowl with either noodles or rice, something italian",
 
 
 
 
 
209
  )
210
+ with col2:
211
+ st.session_state.serving_size = st.number_input(
212
+ "How many servings would you like to cook?",
213
+ min_value=1,
214
+ max_value=100,
215
+ value=st.session_state.serving_size,
216
+ step=1
217
  )
218
 
219
+ difficulty_dictionary = {
220
+ "Quick & Easy": {
221
+ "description": "Easy recipes with straightforward instructions. Ideal for beginners or those seeking quick and simple cooking.",
222
+ },
223
+ "Intermediate": {
224
+ "description": "Recipes with some intricate steps that invite a little challenge. Perfect for regular cooks wanting to expand their repertoire with new ingredients and techniques.",
225
+ },
226
+ "Professional": {
227
+ "description": "Complex recipes that demand a high level of skill and precision. Suited for seasoned cooks aspiring to professional-level sophistication and creativity.",
 
 
 
 
 
228
  }
229
+ }
230
+
231
+ st.session_state.selected_difficulty = st.radio(
232
+ "Choose a difficulty level for your recipe.",
233
+ [
234
+ list(difficulty_dictionary.keys())[0],
235
+ list(difficulty_dictionary.keys())[1],
236
+ list(difficulty_dictionary.keys())[2]
237
+ ],
238
+ captions=[
239
+ difficulty_dictionary["Quick & Easy"]["description"],
240
+ difficulty_dictionary["Intermediate"]["description"],
241
+ difficulty_dictionary["Professional"]["description"]
242
+ ],
243
+ index=list(difficulty_dictionary).index(st.session_state.selected_difficulty)
244
+ )
245
+
246
+ st.session_state.exclusions = st.text_area(
247
+ "Any ingredients you want to exclude?",
248
+ value=st.session_state.exclusions,
249
+ placeholder="gluten, dairy, nuts, cilantro",
250
+ )
251
+
252
+ fancy_exclusions = ""
253
+
254
+ if st.session_state.selected_difficulty == "Professional":
255
+ exclude_fancy = st.checkbox(
256
+ "Exclude cliche professional ingredients? (gold leaf, truffle, edible flowers, microgreens)",
257
+ value=True)
258
+ if exclude_fancy:
259
+ fancy_exclusions = "gold leaf, truffle, edible flowers, microgreens, gold dust"
260
+
261
+ user_inputs = {
262
+ "user_direction": st.session_state.user_direction,
263
+ "exclusions": f"{st.session_state.exclusions}, {fancy_exclusions}".strip(", "),
264
+ "serving_size": st.session_state.serving_size,
265
+ "difficulty": st.session_state.selected_difficulty
266
+ }
267
+
268
+ button_cols_submit = st.columns([1, 1, 4])
269
+ with button_cols_submit[0]:
270
+ st.button(label='Submit', on_click=generate_recipe, kwargs=dict(user_inputs=user_inputs),
271
+ type="primary",
272
+ use_container_width=True)
273
+ with button_cols_submit[1]:
274
+ st.button(label='Reset', on_click=clear_inputs, type="secondary", use_container_width=True)
275
+ with button_cols_submit[2]:
276
+ st.empty()
277
+
278
+ def create_safe_filename(recipe_name):
279
+ # format and generate random URL-safe text string
280
+ safe_name = recipe_name.lower()
281
+ safe_name = safe_name.replace(" ", "_")
282
+ safe_name = re.sub(r"[^a-zA-Z0-9_]", "", safe_name)
283
+ safe_name = (safe_name[:50]) if len(safe_name) > 50 else safe_name
284
+ unique_token = secrets.token_hex(8)
285
+ safe_filename = f"{unique_token}_{safe_name}"
286
+ return safe_filename
287
+
288
+ def save_recipe():
289
+ with st.spinner('WAIT SAVING YOUR DISH...'):
290
+ filename = create_safe_filename(recipe["name"])
291
+ os.makedirs('data', exist_ok=True)
292
+ with open(f'./data/{filename}.pkl', 'wb') as f:
293
+ pickle.dump(recipe, f)
294
+ st.session_state.recipe_saved = True
295
+
296
+ if st.session_state.recipe is not None:
297
+ st.divider()
298
+ print(st.session_state.recipe)
299
+ recipe = json.loads(st.session_state.recipe)
300
+ show_recipe(recipe)
301
+ recipe['timestamp'] = str(datetime.datetime.now())
302
+ if st.session_state.recipe_saved == True:
303
+ disable_button = True
304
+ else:
305
+ disable_button = False
306
+ button_cols_save = st.columns([1, 1, 4])
307
+ with button_cols_save[0]:
308
+ st.button("Save Recipe", on_click=save_recipe, disabled=disable_button, type="primary")
309
+ with button_cols_save[1]:
310
  st.empty()
311
+ with button_cols_save[2]:
312
+ st.empty()
313
+ if st.session_state.recipe_saved == True:
314
+ st.success("Recipe Saved!")
315
+ @st.cache_resource(experimental_allow_widgets=True,show_spinner=False)
316
+ def rsaved():
317
+ st.title("Saved Recipes")
318
+ def load_saved_recipes_from_pickle(directory_path):
319
+ os.makedirs('data', exist_ok=True)
320
+ recipes = []
321
+ # Iterate through all files in the directory
322
+ for filename in os.listdir(directory_path):
323
+ if filename.endswith('.pkl'):
324
+ file_path = os.path.join(directory_path, filename)
325
+ with open(file_path, 'rb') as file:
326
+ recipe = pickle.load(file)
327
+ recipes.append(recipe)
328
+ return recipes
329
+
330
+ # get all saved files
331
+ directory_path = 'data'
332
+ recipes = load_saved_recipes_from_pickle(directory_path)
333
+ print(recipes)
334
+
335
+ cols = st.columns([4, 1])
336
+ with cols[1]:
337
+ user_sort = st.selectbox("Sort", ('Recent', 'Oldest', 'A-Z', 'Z-A', 'Random'))
338
+ if user_sort == 'Recent':
339
+ recipes.sort(key=lambda x: x['timestamp'], reverse=True)
340
+ elif user_sort == 'Oldest':
341
+ recipes.sort(key=lambda x: x['timestamp'])
342
+ elif user_sort == 'A-Z':
343
+ recipes.sort(key=lambda x: x['name'])
344
+ elif user_sort == 'Z-A':
345
+ recipes.sort(key=lambda x: x['name'], reverse=True)
346
+ elif user_sort == 'Random':
347
+ recipes.sort(key=lambda x: x['file'])
348
+ with cols[0]:
349
+ user_search = st.selectbox("Search Recipes", [""] + [recipe['name'] for recipe in recipes])
350
+ st.write("") # just some space
351
+
352
+ if user_search != "":
353
+ st.divider()
354
+ filtered_recipes = [recipe for recipe in recipes if recipe['name'] == user_search]
355
+ if filtered_recipes:
356
+ show_recipe(filtered_recipes[0])
357
+ else:
358
+ st.write("No recipe found.")
359
+ @st.cache_resource(experimental_allow_widgets=True,show_spinner=False)
360
+ def mart():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361
  st.markdown("# :eyes: PEOPLE SEARCHING FOR...")
362
  print(st.session_state.ind)
363
  flattened_indices = list(set(index for sublist in st.session_state.ind for index in sublist))
 
393
  st.plotly_chart(fig1, use_container_width=True)
394
 
395
  with st.container(border=True, height=620):
396
+ st.markdown('## :deciduous_tree: Hierarchical view of demand using TreeMap')
397
  fig4 = px.treemap(df, path=['CATEGORY', 'AVAILABILITY','PRODUCT'],color='AVAILABILITY')
398
  fig4.update_layout(height=550)
399
  st.plotly_chart(fig4, use_container_width=True,scrolling=False)
 
405
  color='BRAND',
406
  # title='Gross Sales of Every Segment Country-wise',
407
  barmode='relative',
408
+ title="CATEGORY Vs. BREADCRUMBS"
409
  )
410
  st.plotly_chart(fig, use_container_width=True)
 
 
 
 
411
  # st.markdown("## :desktop_computer: DO YOUR OWN RESEARCH...")
412
  with st.expander("## :desktop_computer: LOOKING FOR SOMETHING ELSE..."):
413
+ pygwalerapp(df).explorer()
414
+ # Initialize the inference client for the Mixtral model
415
+ if not mode:
416
+ cook, saved = st.tabs(['COOK', 'SAVED'])
417
+ with cook:
418
+ cooking()
419
+ with saved:
420
+ rsaved()
421
+ else:
422
+ mart()