OmPrakashSingh1704 commited on
Commit
e81c2f0
1 Parent(s): bf24bdd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -33
app.py CHANGED
@@ -34,6 +34,25 @@ mode = st.toggle(label="MART")
34
  if 'ind' not in st.session_state:
35
  st.session_state.ind = []
36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  @st.cache_resource(show_spinner=False)
38
  def pygwalerapp(df):
39
  return StreamlitRenderer(df)
@@ -48,9 +67,9 @@ def get_recommendations(user_description, count_vectorizer, count_matrix):
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(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'
55
  name_and_dis += f'{recipe["description"]}\n\n'
56
  ingredients = '## Ingredients:\n'
@@ -59,21 +78,22 @@ def show_recipe(recipe):
59
  instructions += f"{instruction['step_number']}. {instruction['instruction']}\n"
60
 
61
  st.write(name_and_dis)
62
- col01, col02 = st.columns(2)
63
  with col01:
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][
71
- "PRODUCT_NAME"].values,
72
- key=f"selectbox_{j}_{i['name']}{random.random() * 100}")
 
73
  with col02:
74
- cont = st.container(border=True, height=500)
75
- cont.write(instructions)
76
- @st.cache_resource(show_spinner=False)
77
  def cooking():
78
  client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
79
 
@@ -120,7 +140,7 @@ def cooking():
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
 
@@ -200,15 +220,15 @@ def cooking():
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,
@@ -267,11 +287,11 @@ def cooking():
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
 
@@ -305,14 +325,14 @@ def cooking():
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(show_spinner=False)
316
  def rsaved():
317
  st.title("Saved Recipes")
318
  def load_saved_recipes_from_pickle(directory_path):
@@ -346,7 +366,7 @@ def rsaved():
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 != "":
@@ -356,15 +376,15 @@ def rsaved():
356
  show_recipe(filtered_recipes[0])
357
  else:
358
  st.write("No recipe found.")
359
- @st.cache_resource(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))
364
  df = items_dict.iloc[flattened_indices]
365
  if st.session_state.ind != []:
366
- with st.spinner("LET'S SEE, WHAT PEOPLE WANT..."):
367
- cont1 = st.container(border=True, height=500)
368
  with cont1:
369
  wc = wordcloud.WordCloud(width=1000, height=320, background_color='white').generate(
370
  ' '.join(df['CATEGORY']))
@@ -376,8 +396,8 @@ def mart():
376
 
377
  st.pyplot(fig, use_container_width=True)
378
 
379
- with st.container(border=True, height=500):
380
- col1, col2 = st.columns(2)
381
  with col1:
382
  st.markdown('## DEMAND AS PER CATEGORY')
383
  with plt.style.context('Solarize_Light2'):
@@ -392,13 +412,13 @@ def mart():
392
  fig1.update_traces(text=df['AVAILABILITY'], textposition='outside')
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)
400
 
401
- with st.container(border=True, height=500):
402
  fig = px.bar(df,
403
  y='CATEGORY',
404
  x='BREADCRUMBS',
@@ -409,11 +429,14 @@ def mart():
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:
 
34
  if 'ind' not in st.session_state:
35
  st.session_state.ind = []
36
 
37
+
38
+ def spinner(txt):return st.spinner(txt)
39
+
40
+ def columns(n):
41
+ return st.columns(n)
42
+
43
+ def text_area(txt,value,placeholder):
44
+ return st.text_area(txt,value=value,placeholder=placeholder)
45
+
46
+ def number_input(txt,min_value,max_value,value,step):return st.number_input(txt,min_value=min_value,max_value=max_value,value=value,step=step)
47
+
48
+ def button(txt,on_click,type,disabled=False,use_container_width=False,kwargs=None):
49
+ return st.button(label=txt,on_click=on_click,disabled=disabled,type=type,use_container_width=use_container_width,kwargs=kwargs)
50
+
51
+ def container(border,height):
52
+ return st.container(border=border,height=height)
53
+
54
+ def selectbox(txt,options,key=None):return st.selectbox(txt,options=options,key=key)
55
+ def expander(txt):return st.expander(txt)
56
  @st.cache_resource(show_spinner=False)
57
  def pygwalerapp(df):
58
  return StreamlitRenderer(df)
 
67
  cosine_similarities = cosine_similarity(user_vector, count_matrix).flatten()
68
  similar_indices = cosine_similarities.argsort()[::-1]
69
  return similar_indices
70
+ @st.experimental_fragment
71
  def show_recipe(recipe):
72
+ with spinner("HANG TIGHT, RECIPE INCOMING..."):
73
  name_and_dis = f'# {recipe["name"]}\n\n'
74
  name_and_dis += f'{recipe["description"]}\n\n'
75
  ingredients = '## Ingredients:\n'
 
78
  instructions += f"{instruction['step_number']}. {instruction['instruction']}\n"
79
 
80
  st.write(name_and_dis)
81
+ col01, col02 = columns(2)
82
  with col01:
83
+ cont = container(border=True, height=500)
84
+ with cont:
85
+ st.write(ingredients)
86
+ for j, i in enumerate(recipe["ingredients"]):
87
+ ind = get_recommendations(i['name'], cv, vectors)
88
+ st.session_state.ind.append(ind[:5].tolist())
89
+ selectbox(i['name'],
90
+ options=items_dict.iloc[ind][
91
+ "PRODUCT_NAME"].values,
92
+ key=f"selectbox_{j}_{i['name']}{random.random() * 100}")
93
  with col02:
94
+ cont = container(border=True, height=500)
95
+ with cont:st.write(instructions)
96
+ @st.experimental_fragment
97
  def cooking():
98
  client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
99
 
 
140
  return prompt
141
 
142
  def generate_recipe(user_inputs):
143
+ with spinner('Building the perfect recipe...'):
144
  prompt = create_detailed_prompt(user_inputs['user_direction'], user_inputs['exclusions'],
145
  user_inputs['serving_size'], user_inputs['difficulty'])
146
 
 
220
  st.session_state.recipe = None
221
 
222
  st.title("Let's get cooking")
223
+ col1, col2 = columns(2)
224
  with col1:
225
+ st.session_state.user_direction = text_area(
226
  "What do you want to cook? Describe anything - a dish, cuisine, event, or vibe.",
227
  value=st.session_state.user_direction,
228
  placeholder="quick snack, asian style bowl with either noodles or rice, something italian",
229
  )
230
  with col2:
231
+ st.session_state.serving_size = number_input(
232
  "How many servings would you like to cook?",
233
  min_value=1,
234
  max_value=100,
 
287
 
288
  button_cols_submit = st.columns([1, 1, 4])
289
  with button_cols_submit[0]:
290
+ button(txt='Submit', on_click=generate_recipe, kwargs=dict(user_inputs=user_inputs),
291
  type="primary",
292
  use_container_width=True)
293
  with button_cols_submit[1]:
294
+ button(txt='Reset', on_click=clear_inputs, type="secondary", use_container_width=True)
295
  with button_cols_submit[2]:
296
  st.empty()
297
 
 
325
  disable_button = False
326
  button_cols_save = st.columns([1, 1, 4])
327
  with button_cols_save[0]:
328
+ button("Save Recipe", on_click=save_recipe, disabled=disable_button, type="primary")
329
  with button_cols_save[1]:
330
  st.empty()
331
  with button_cols_save[2]:
332
  st.empty()
333
  if st.session_state.recipe_saved == True:
334
  st.success("Recipe Saved!")
335
+ @st.experimental_fragment
336
  def rsaved():
337
  st.title("Saved Recipes")
338
  def load_saved_recipes_from_pickle(directory_path):
 
366
  elif user_sort == 'Random':
367
  recipes.sort(key=lambda x: x['file'])
368
  with cols[0]:
369
+ user_search = selectbox("Search Recipes", [""] + [recipe['name'] for recipe in recipes])
370
  st.write("") # just some space
371
 
372
  if user_search != "":
 
376
  show_recipe(filtered_recipes[0])
377
  else:
378
  st.write("No recipe found.")
379
+ @st.experimental_fragment
380
  def mart():
381
  st.markdown("# :eyes: PEOPLE SEARCHING FOR...")
382
  print(st.session_state.ind)
383
  flattened_indices = list(set(index for sublist in st.session_state.ind for index in sublist))
384
  df = items_dict.iloc[flattened_indices]
385
  if st.session_state.ind != []:
386
+ with spinner("LET'S SEE, WHAT PEOPLE WANT..."):
387
+ cont1 = container(border=True, height=500)
388
  with cont1:
389
  wc = wordcloud.WordCloud(width=1000, height=320, background_color='white').generate(
390
  ' '.join(df['CATEGORY']))
 
396
 
397
  st.pyplot(fig, use_container_width=True)
398
 
399
+ with container(border=True, height=500):
400
+ col1, col2 = columns(2)
401
  with col1:
402
  st.markdown('## DEMAND AS PER CATEGORY')
403
  with plt.style.context('Solarize_Light2'):
 
412
  fig1.update_traces(text=df['AVAILABILITY'], textposition='outside')
413
  st.plotly_chart(fig1, use_container_width=True)
414
 
415
+ with container(border=True, height=620):
416
  st.markdown('## :deciduous_tree: Hierarchical view of demand using TreeMap')
417
  fig4 = px.treemap(df, path=['CATEGORY', 'AVAILABILITY','PRODUCT'],color='AVAILABILITY')
418
  fig4.update_layout(height=550)
419
  st.plotly_chart(fig4, use_container_width=True,scrolling=False)
420
 
421
+ with container(border=True, height=500):
422
  fig = px.bar(df,
423
  y='CATEGORY',
424
  x='BREADCRUMBS',
 
429
  )
430
  st.plotly_chart(fig, use_container_width=True)
431
  # st.markdown("## :desktop_computer: DO YOUR OWN RESEARCH...")
432
+ with expander("## :desktop_computer: LOOKING FOR SOMETHING ELSE..."):
433
  pygwalerapp(df).explorer()
434
  # Initialize the inference client for the Mixtral model
435
+ @st.experimental_fragment
436
+ def tabs():
437
+ return st.tabs(['COOK','SAVED'])
438
  if not mode:
439
+ cook, saved = tabs()
440
  with cook:
441
  cooking()
442
  with saved: