OmPrakashSingh1704 commited on
Commit
2590d8a
1 Parent(s): 3307cd1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +105 -44
app.py CHANGED
@@ -1,30 +1,36 @@
1
  import streamlit as st
 
 
2
  import os
3
  import pandas as pd
4
  from huggingface_hub import login, InferenceClient
5
  import pickle
6
- import json
7
 
8
  st.set_page_config(layout="wide")
9
 
10
- # Authenticate with Hugging Face
11
  login(token=os.getenv("TOKEN"))
12
 
13
- # Load similarity data
14
- with open('l.pkl', 'rb') as file:
15
- similarity = pickle.load(file)
 
 
16
 
17
- # Load items dictionary
18
- with open('items_dict.pkl', 'rb') as file:
19
- items_dict = pickle.load(file)
 
 
20
 
21
- # Load dataset
22
- data = pd.read_csv('marketing_sample_for_walmart_com-product_details__20200101_20200331__30k_data.csv')
 
 
23
 
24
  # Initialize the inference client for the Mixtral model
25
  client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
26
 
27
- # Initialize session state variables
28
  if 'recipe' not in st.session_state:
29
  st.session_state.recipe = None
30
 
@@ -32,7 +38,7 @@ if 'recipe_saved' not in st.session_state:
32
  st.session_state.recipe_saved = None
33
 
34
  if 'user_direction' not in st.session_state:
35
- st.session_state.user_direction = ""
36
 
37
  if 'serving_size' not in st.session_state:
38
  st.session_state.serving_size = 2
@@ -41,7 +47,7 @@ if 'selected_difficulty' not in st.session_state:
41
  st.session_state.selected_difficulty = "Quick & Easy"
42
 
43
  if 'exclusions' not in st.session_state:
44
- st.session_state.exclusions = ""
45
 
46
 
47
  def create_detailed_prompt(user_direction, exclusions, serving_size, difficulty):
@@ -74,6 +80,60 @@ def generate_recipe(user_inputs):
74
  prompt = create_detailed_prompt(user_inputs['user_direction'], user_inputs['exclusions'],
75
  user_inputs['serving_size'], user_inputs['difficulty'])
76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  generate_kwargs = dict(
78
  temperature=0.9,
79
  max_new_tokens=10000,
@@ -82,17 +142,16 @@ def generate_recipe(user_inputs):
82
  do_sample=True,
83
  )
84
 
 
 
85
  response = client.text_generation(prompt, **generate_kwargs)
86
- try:
87
- st.session_state.recipe = json.loads(response)
88
- except json.JSONDecodeError:
89
- st.session_state.recipe = None
90
  st.session_state.recipe_saved = False
91
 
92
 
93
  def clear_inputs():
94
- st.session_state.user_direction = ""
95
- st.session_state.exclusions = ""
96
  st.session_state.serving_size = 2
97
  st.session_state.selected_difficulty = "Quick & Easy"
98
 
@@ -101,7 +160,7 @@ st.title("Let's get cooking")
101
  st.session_state.user_direction = st.text_area(
102
  "What do you want to cook? Describe anything - a dish, cuisine, event, or vibe.",
103
  value=st.session_state.user_direction,
104
- placeholder="quick snack, Asian style bowl with either noodles or rice, something Italian",
105
  )
106
 
107
  st.session_state.serving_size = st.number_input(
@@ -126,14 +185,10 @@ difficulty_dictionary = {
126
 
127
  st.session_state.selected_difficulty = st.radio(
128
  "Choose a difficulty level for your recipe.",
129
- options=list(difficulty_dictionary.keys()),
130
  index=list(difficulty_dictionary).index(st.session_state.selected_difficulty)
131
  )
132
 
133
- for level, details in difficulty_dictionary.items():
134
- if level == st.session_state.selected_difficulty:
135
- st.caption(details["description"])
136
-
137
  st.session_state.exclusions = st.text_area(
138
  "Any ingredients you want to exclude?",
139
  value=st.session_state.exclusions,
@@ -141,6 +196,7 @@ st.session_state.exclusions = st.text_area(
141
  )
142
 
143
  fancy_exclusions = ""
 
144
  if st.session_state.selected_difficulty == "Professional":
145
  exclude_fancy = st.checkbox(
146
  "Exclude cliche professional ingredients? (gold leaf, truffle, edible flowers, microgreens)",
@@ -150,7 +206,7 @@ if st.session_state.selected_difficulty == "Professional":
150
 
151
  user_inputs = {
152
  "user_direction": st.session_state.user_direction,
153
- "exclusions": f"{st.session_state.exclusions}, {fancy_exclusions}",
154
  "serving_size": st.session_state.serving_size,
155
  "difficulty": st.session_state.selected_difficulty
156
  }
@@ -164,22 +220,27 @@ with button_cols_submit[1]:
164
  with button_cols_submit[2]:
165
  st.empty()
166
 
167
- if st.session_state.recipe:
168
  st.divider()
169
- print(st.session_state.recipe)
170
- recipe = st.session_state.recipe
171
- name_and_dis = f'# {recipe["name"]}\n\n'
172
- name_and_dis += f'{recipe["description"]}\n\n'
173
- ingredients = '## Ingredients:\n'
174
- for ingredient in recipe["ingredients"]:
175
- ingredients += f"- {ingredient['name']}\n"
176
- instructions = '\n## Instructions:\n'
177
- for instruction in recipe["instructions"]:
178
- instructions += f"{instruction['step_number']}. {instruction['instruction']}\n"
179
-
180
- st.write(name_and_dis)
181
- col01, col02 = st.columns(2)
182
- with col01:
183
- st.write(ingredients)
184
- with col02:
185
- st.write(instructions)
 
 
 
 
 
 
1
  import streamlit as st
2
+ import re
3
+ import json
4
  import os
5
  import pandas as pd
6
  from huggingface_hub import login, InferenceClient
7
  import pickle
8
+ from sklearn.metrics.pairwise import cosine_similarity
9
 
10
  st.set_page_config(layout="wide")
11
 
 
12
  login(token=os.getenv("TOKEN"))
13
 
14
+ try:
15
+ with open('l.pkl', 'rb') as file:
16
+ similarity = pickle.load(file)
17
+ except FileNotFoundError:
18
+ st.error("The similarity file was not found.")
19
 
20
+ try:
21
+ with open('items_dict.pkl', 'rb') as file:
22
+ items_dict = pickle.load(file)
23
+ except FileNotFoundError:
24
+ st.error("The items dictionary file was not found.")
25
 
26
+ try:
27
+ data = pd.read_csv('marketing_sample_for_walmart_com-product_details__20200101_20200331__30k_data.csv')
28
+ except FileNotFoundError:
29
+ st.error("The CSV file was not found.")
30
 
31
  # Initialize the inference client for the Mixtral model
32
  client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
33
 
 
34
  if 'recipe' not in st.session_state:
35
  st.session_state.recipe = None
36
 
 
38
  st.session_state.recipe_saved = None
39
 
40
  if 'user_direction' not in st.session_state:
41
+ st.session_state.user_direction = None
42
 
43
  if 'serving_size' not in st.session_state:
44
  st.session_state.serving_size = 2
 
47
  st.session_state.selected_difficulty = "Quick & Easy"
48
 
49
  if 'exclusions' not in st.session_state:
50
+ st.session_state.exclusions = None
51
 
52
 
53
  def create_detailed_prompt(user_direction, exclusions, serving_size, difficulty):
 
80
  prompt = create_detailed_prompt(user_inputs['user_direction'], user_inputs['exclusions'],
81
  user_inputs['serving_size'], user_inputs['difficulty'])
82
 
83
+ functions = [
84
+ {
85
+ "name": "provide_recipe",
86
+ "description": "Provides a detailed recipe strictly adhering to the user input/specifications, especially ingredient exclusions and the recipe difficulty",
87
+ "parameters": {
88
+ "type": "object",
89
+ "properties": {
90
+ "name": {
91
+ "type": "string",
92
+ "description": "A creative name for the recipe"
93
+ },
94
+ "description": {
95
+ "type": "string",
96
+ "description": "a brief one-sentence description of the provided recipe"
97
+ },
98
+ "ingredients": {
99
+ "type": "array",
100
+ "items": {
101
+ "type": "object",
102
+ "properties": {
103
+ "name": {
104
+ "type": "string",
105
+ "description": "Quantity and name of the ingredient"
106
+ }
107
+ }
108
+ }
109
+ },
110
+ "instructions": {
111
+ "type": "array",
112
+ "items": {
113
+ "type": "object",
114
+ "properties": {
115
+ "step_number": {
116
+ "type": "number",
117
+ "description": "The sequence number of this step"
118
+ },
119
+ "instruction": {
120
+ "type": "string",
121
+ "description": "Detailed description of what to do in this step"
122
+ }
123
+ }
124
+ }
125
+ }
126
+ },
127
+ "required": [
128
+ "name",
129
+ "description",
130
+ "ingredients",
131
+ "instructions"
132
+ ],
133
+ },
134
+ }
135
+ ]
136
+
137
  generate_kwargs = dict(
138
  temperature=0.9,
139
  max_new_tokens=10000,
 
142
  do_sample=True,
143
  )
144
 
145
+ 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)}"
146
+
147
  response = client.text_generation(prompt, **generate_kwargs)
148
+ st.session_state.recipe = response
 
 
 
149
  st.session_state.recipe_saved = False
150
 
151
 
152
  def clear_inputs():
153
+ st.session_state.user_direction = None
154
+ st.session_state.exclusions = None
155
  st.session_state.serving_size = 2
156
  st.session_state.selected_difficulty = "Quick & Easy"
157
 
 
160
  st.session_state.user_direction = st.text_area(
161
  "What do you want to cook? Describe anything - a dish, cuisine, event, or vibe.",
162
  value=st.session_state.user_direction,
163
+ placeholder="quick snack, asian style bowl with either noodles or rice, something italian",
164
  )
165
 
166
  st.session_state.serving_size = st.number_input(
 
185
 
186
  st.session_state.selected_difficulty = st.radio(
187
  "Choose a difficulty level for your recipe.",
188
+ list(difficulty_dictionary.keys()),
189
  index=list(difficulty_dictionary).index(st.session_state.selected_difficulty)
190
  )
191
 
 
 
 
 
192
  st.session_state.exclusions = st.text_area(
193
  "Any ingredients you want to exclude?",
194
  value=st.session_state.exclusions,
 
196
  )
197
 
198
  fancy_exclusions = ""
199
+
200
  if st.session_state.selected_difficulty == "Professional":
201
  exclude_fancy = st.checkbox(
202
  "Exclude cliche professional ingredients? (gold leaf, truffle, edible flowers, microgreens)",
 
206
 
207
  user_inputs = {
208
  "user_direction": st.session_state.user_direction,
209
+ "exclusions": f"{st.session_state.exclusions}, {fancy_exclusions}".strip(", "),
210
  "serving_size": st.session_state.serving_size,
211
  "difficulty": st.session_state.selected_difficulty
212
  }
 
220
  with button_cols_submit[2]:
221
  st.empty()
222
 
223
+ if st.session_state.recipe is not None:
224
  st.divider()
225
+ try:
226
+ print(st.session_state.recipe)
227
+ recipe = json.loads(st.session_state.recipe)
228
+ name_and_dis = f'# {recipe["name"]}\n\n'
229
+ name_and_dis += f'{recipe["description"]}\n\n'
230
+ ingredients = '## Ingredients:\n'
231
+ for ingredient in recipe["ingredients"]:
232
+ ingredients += f"- {ingredient['name']}\n"
233
+ instructions = '\n## Instructions:\n'
234
+ for instruction in recipe["instructions"]:
235
+ instructions += f"{instruction['step_number']}. {instruction['instruction']}\n"
236
+
237
+ st.write(name_and_dis)
238
+ col01, col02 = st.columns(2)
239
+ with col01:
240
+ cont = st.container()
241
+ cont.write(ingredients)
242
+ with col02:
243
+ cont = st.container()
244
+ cont.write(instructions)
245
+ except (json.JSONDecodeError, KeyError) as e:
246
+ st.error(f"Failed to parse recipe: {e}")