Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,15 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import random
|
2 |
-
import
|
3 |
-
import re, ast, secrets, os, json
|
4 |
import pandas as pd
|
5 |
from huggingface_hub import login, InferenceClient
|
6 |
-
import pickle,datetime
|
7 |
from sklearn.metrics.pairwise import cosine_similarity
|
|
|
8 |
|
9 |
st.set_page_config(layout="wide")
|
10 |
|
|
|
11 |
login(token=os.getenv("TOKEN"))
|
12 |
|
|
|
13 |
with open('cv.pkl', 'rb') as file:
|
14 |
cv = pickle.load(file)
|
15 |
|
@@ -19,7 +26,13 @@ with open('vectors.pkl', 'rb') as file:
|
|
19 |
with open('items_dict.pkl', 'rb') as file:
|
20 |
items_dict = pd.DataFrame.from_dict(pickle.load(file))
|
21 |
|
22 |
-
mode=st.toggle(label="MART")
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
|
24 |
def get_recommendations(user_description, count_vectorizer, count_matrix):
|
25 |
user_description = preprocess_text(user_description)
|
@@ -28,15 +41,91 @@ def get_recommendations(user_description, count_vectorizer, count_matrix):
|
|
28 |
similar_indices = cosine_similarities.argsort()[::-1]
|
29 |
return similar_indices
|
30 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
31 |
def show_recipe(recipe):
|
32 |
with st.spinner("HANG TIGHT, RECIPE INCOMING..."):
|
33 |
-
name_and_dis = f'# {recipe["name"]}\n\n'
|
34 |
-
name_and_dis += f'{recipe["description"]}\n\n'
|
35 |
ingredients = '## Ingredients:\n'
|
36 |
-
instructions = '
|
37 |
for instruction in recipe["instructions"]:
|
38 |
instructions += f"{instruction['step_number']}. {instruction['instruction']}\n"
|
39 |
-
|
40 |
st.write(name_and_dis)
|
41 |
col01, col02 = st.columns(2)
|
42 |
with col01:
|
@@ -50,155 +139,74 @@ def show_recipe(recipe):
|
|
50 |
cont = st.container(border=True, height=500)
|
51 |
cont.write(instructions)
|
52 |
|
53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
54 |
|
|
|
55 |
if not mode:
|
56 |
if 'current_tab' not in st.session_state:
|
57 |
st.session_state.current_tab = 'COOK'
|
58 |
-
|
59 |
-
cook,saved=st.tabs(['COOK','SAVED'])
|
60 |
|
61 |
if cook:
|
62 |
st.session_state.current_tab = 'COOK'
|
63 |
if saved:
|
64 |
st.session_state.current_tab = 'SAVED'
|
|
|
65 |
if st.session_state.current_tab == 'COOK':
|
66 |
with cook:
|
67 |
client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
|
68 |
-
|
69 |
if 'recipe' not in st.session_state:
|
70 |
st.session_state.recipe = None
|
71 |
-
|
72 |
if 'recipe_saved' not in st.session_state:
|
73 |
st.session_state.recipe_saved = None
|
74 |
-
|
75 |
if 'user_direction' not in st.session_state:
|
76 |
st.session_state.user_direction = None
|
77 |
-
|
78 |
if 'serving_size' not in st.session_state:
|
79 |
st.session_state.serving_size = 2
|
80 |
-
|
81 |
if 'selected_difficulty' not in st.session_state:
|
82 |
st.session_state.selected_difficulty = "Quick & Easy"
|
83 |
-
|
84 |
if 'exclusions' not in st.session_state:
|
85 |
st.session_state.exclusions = None
|
86 |
-
|
87 |
-
def preprocess_text(text):
|
88 |
-
# Remove non-alphabet characters and extra spaces
|
89 |
-
text = re.sub(r'[^a-zA-Z\s]', '', text)
|
90 |
-
text = re.sub(r'\s+', ' ', text).strip()
|
91 |
-
return text.lower()
|
92 |
-
|
93 |
-
def create_detailed_prompt(user_direction, exclusions, serving_size, difficulty):
|
94 |
-
if difficulty == "Quick & Easy":
|
95 |
-
prompt = (
|
96 |
-
f"Provide a 'Quick and Easy' recipe for {user_direction} that excludes {exclusions} and has a serving size of {serving_size}. "
|
97 |
-
f"It should require as few ingredients as possible and should be ready in as little time as possible. "
|
98 |
-
f"The steps should be simple, and the ingredients should be commonly found in a household pantry. "
|
99 |
-
f"Provide a detailed ingredient list and step-by-step guide that explains the instructions to prepare in detail."
|
100 |
-
)
|
101 |
-
elif difficulty == "Intermediate":
|
102 |
-
prompt = (
|
103 |
-
f"Provide a classic recipe for {user_direction} that excludes {exclusions} and has a serving size of {serving_size}. "
|
104 |
-
f"The recipe should offer a bit of a cooking challenge but should not require professional skills. "
|
105 |
-
f"The recipe should feature traditional ingredients and techniques that are authentic to its cuisine. "
|
106 |
-
f"Provide a detailed ingredient list and step-by-step guide that explains the instructions to prepare in detail."
|
107 |
-
)
|
108 |
-
elif difficulty == "Professional":
|
109 |
-
prompt = (
|
110 |
-
f"Provide an advanced recipe for {user_direction} that excludes {exclusions} and has a serving size of {serving_size}. "
|
111 |
-
f"The recipe should push the boundaries of culinary arts, integrating unique ingredients, advanced cooking techniques, and innovative presentations. "
|
112 |
-
f"The recipe should be able to be served at a high-end restaurant or would impress at a gourmet food competition. "
|
113 |
-
f"Provide a detailed ingredient list and step-by-step guide that explains the instructions to prepare in detail."
|
114 |
-
)
|
115 |
-
return prompt
|
116 |
-
|
117 |
-
|
118 |
-
def generate_recipe(user_inputs):
|
119 |
-
with st.spinner('Building the perfect recipe...'):
|
120 |
-
prompt = create_detailed_prompt(user_inputs['user_direction'], user_inputs['exclusions'],
|
121 |
-
user_inputs['serving_size'], user_inputs['difficulty'])
|
122 |
-
|
123 |
-
functions = [
|
124 |
-
{
|
125 |
-
"name": "provide_recipe",
|
126 |
-
"description": "Provides a detailed recipe strictly adhering to the user input/specifications, especially ingredient exclusions and the recipe difficulty",
|
127 |
-
"parameters": {
|
128 |
-
"type": "object",
|
129 |
-
"properties": {
|
130 |
-
"name": {
|
131 |
-
"type": "string",
|
132 |
-
"description": "A creative name for the recipe"
|
133 |
-
},
|
134 |
-
"description": {
|
135 |
-
"type": "string",
|
136 |
-
"description": "a brief one-sentence description of the provided recipe"
|
137 |
-
},
|
138 |
-
"ingredients": {
|
139 |
-
"type": "array",
|
140 |
-
"items": {
|
141 |
-
"type": "object",
|
142 |
-
"properties": {
|
143 |
-
"name": {
|
144 |
-
"type": "string",
|
145 |
-
"description": "Quantity and name of the ingredient"
|
146 |
-
}
|
147 |
-
}
|
148 |
-
}
|
149 |
-
},
|
150 |
-
"instructions": {
|
151 |
-
"type": "array",
|
152 |
-
"items": {
|
153 |
-
"type": "object",
|
154 |
-
"properties": {
|
155 |
-
"step_number": {
|
156 |
-
"type": "number",
|
157 |
-
"description": "The sequence number of this step"
|
158 |
-
},
|
159 |
-
"instruction": {
|
160 |
-
"type": "string",
|
161 |
-
"description": "Detailed description of what to do in this step"
|
162 |
-
}
|
163 |
-
}
|
164 |
-
}
|
165 |
-
}
|
166 |
-
},
|
167 |
-
"required": [
|
168 |
-
"name",
|
169 |
-
"description",
|
170 |
-
"ingredients",
|
171 |
-
"instructions"
|
172 |
-
],
|
173 |
-
},
|
174 |
-
}
|
175 |
-
]
|
176 |
-
|
177 |
-
generate_kwargs = dict(
|
178 |
-
temperature=0.9,
|
179 |
-
max_new_tokens=10000,
|
180 |
-
top_p=0.9,
|
181 |
-
repetition_penalty=1.0,
|
182 |
-
do_sample=True,
|
183 |
-
)
|
184 |
-
|
185 |
-
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)}"
|
186 |
-
|
187 |
-
response = client.text_generation(prompt, **generate_kwargs)
|
188 |
-
st.session_state.recipe = response
|
189 |
-
st.session_state.recipe_saved = False
|
190 |
-
|
191 |
-
|
192 |
-
def clear_inputs():
|
193 |
-
st.session_state.user_direction = None
|
194 |
-
st.session_state.exclusions = None
|
195 |
-
st.session_state.serving_size = 2
|
196 |
-
st.session_state.selected_difficulty = "Quick & Easy"
|
197 |
-
st.session_state.recipe=None
|
198 |
-
|
199 |
-
|
200 |
st.title("Let's get cooking")
|
201 |
-
col1,col2=st.columns(2)
|
202 |
with col1:
|
203 |
st.session_state.user_direction = st.text_area(
|
204 |
"What do you want to cook? Describe anything - a dish, cuisine, event, or vibe.",
|
@@ -213,7 +221,7 @@ if not mode:
|
|
213 |
value=st.session_state.serving_size,
|
214 |
step=1
|
215 |
)
|
216 |
-
|
217 |
difficulty_dictionary = {
|
218 |
"Quick & Easy": {
|
219 |
"description": "Easy recipes with straightforward instructions. Ideal for beginners or those seeking quick and simple cooking.",
|
@@ -225,44 +233,35 @@ if not mode:
|
|
225 |
"description": "Complex recipes that demand a high level of skill and precision. Suited for seasoned cooks aspiring to professional-level sophistication and creativity.",
|
226 |
}
|
227 |
}
|
228 |
-
|
229 |
st.session_state.selected_difficulty = st.radio(
|
230 |
"Choose a difficulty level for your recipe.",
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
list(difficulty_dictionary.keys())[2]
|
235 |
-
],
|
236 |
-
captions=[
|
237 |
-
difficulty_dictionary["Quick & Easy"]["description"],
|
238 |
-
difficulty_dictionary["Intermediate"]["description"],
|
239 |
-
difficulty_dictionary["Professional"]["description"]
|
240 |
-
],
|
241 |
-
index=list(difficulty_dictionary).index(st.session_state.selected_difficulty)
|
242 |
)
|
243 |
-
|
244 |
st.session_state.exclusions = st.text_area(
|
245 |
"Any ingredients you want to exclude?",
|
246 |
value=st.session_state.exclusions,
|
247 |
placeholder="gluten, dairy, nuts, cilantro",
|
248 |
)
|
249 |
-
|
250 |
fancy_exclusions = ""
|
251 |
-
|
252 |
if st.session_state.selected_difficulty == "Professional":
|
253 |
exclude_fancy = st.checkbox(
|
254 |
"Exclude cliche professional ingredients? (gold leaf, truffle, edible flowers, microgreens)",
|
255 |
value=True)
|
256 |
if exclude_fancy:
|
257 |
fancy_exclusions = "gold leaf, truffle, edible flowers, microgreens, gold dust"
|
258 |
-
|
259 |
user_inputs = {
|
260 |
"user_direction": st.session_state.user_direction,
|
261 |
"exclusions": f"{st.session_state.exclusions}, {fancy_exclusions}".strip(", "),
|
262 |
"serving_size": st.session_state.serving_size,
|
263 |
"difficulty": st.session_state.selected_difficulty
|
264 |
}
|
265 |
-
|
266 |
button_cols_submit = st.columns([1, 1, 4])
|
267 |
with button_cols_submit[0]:
|
268 |
st.button(label='Submit', on_click=generate_recipe, kwargs=dict(user_inputs=user_inputs), type="primary",
|
@@ -271,36 +270,15 @@ if not mode:
|
|
271 |
st.button(label='Reset', on_click=clear_inputs, type="secondary", use_container_width=True)
|
272 |
with button_cols_submit[2]:
|
273 |
st.empty()
|
274 |
-
|
275 |
-
def create_safe_filename(recipe_name):
|
276 |
-
# format and generate random URL-safe text string
|
277 |
-
safe_name = recipe_name.lower()
|
278 |
-
safe_name = safe_name.replace(" ", "_")
|
279 |
-
safe_name = re.sub(r"[^a-zA-Z0-9_]", "", safe_name)
|
280 |
-
safe_name = (safe_name[:50]) if len(safe_name) > 50 else safe_name
|
281 |
-
unique_token = secrets.token_hex(8)
|
282 |
-
safe_filename = f"{unique_token}_{safe_name}"
|
283 |
-
return safe_filename
|
284 |
-
|
285 |
-
def save_recipe():
|
286 |
-
with st.spinner('WAIT SAVING YOUR DISH...'):
|
287 |
-
filename = create_safe_filename(recipe["name"])
|
288 |
-
os.makedirs('data', exist_ok=True)
|
289 |
-
with open(f'./data/{filename}.pkl', 'wb') as f:
|
290 |
-
pickle.dump(recipe, f)
|
291 |
-
st.session_state.recipe_saved = True
|
292 |
-
|
293 |
if st.session_state.recipe is not None:
|
294 |
st.divider()
|
295 |
-
print(st.session_state.recipe)
|
296 |
recipe = json.loads(st.session_state.recipe)
|
297 |
if not st.session_state.recipe_saved:
|
298 |
show_recipe(recipe)
|
299 |
recipe['timestamp'] = str(datetime.datetime.now())
|
300 |
-
|
301 |
-
|
302 |
-
else:
|
303 |
-
disable_button = False
|
304 |
button_cols_save = st.columns([1, 1, 4])
|
305 |
with button_cols_save[0]:
|
306 |
st.button("Save Recipe", on_click=save_recipe, disabled=disable_button, type="primary")
|
@@ -308,30 +286,17 @@ if not mode:
|
|
308 |
st.empty()
|
309 |
with button_cols_save[2]:
|
310 |
st.empty()
|
311 |
-
|
|
|
312 |
st.success("Recipe Saved!")
|
313 |
-
|
|
|
314 |
with saved:
|
315 |
st.title("Saved Recipes")
|
316 |
with st.spinner('LOADING YOUR RECIPE...'):
|
317 |
-
def load_saved_recipes_from_pickle(directory_path):
|
318 |
-
os.makedirs('data', exist_ok=True)
|
319 |
-
recipes = []
|
320 |
-
# Iterate through all files in the directory
|
321 |
-
for filename in os.listdir(directory_path):
|
322 |
-
if filename.endswith('.pkl'):
|
323 |
-
file_path = os.path.join(directory_path, filename)
|
324 |
-
with open(file_path, 'rb') as file:
|
325 |
-
recipe = pickle.load(file)
|
326 |
-
recipes.append(recipe)
|
327 |
-
return recipes
|
328 |
-
|
329 |
-
|
330 |
-
# get all saved files
|
331 |
directory_path = 'data'
|
332 |
recipes = load_saved_recipes_from_pickle(directory_path)
|
333 |
-
|
334 |
-
|
335 |
cols = st.columns([4, 1])
|
336 |
with cols[1]:
|
337 |
user_sort = st.selectbox("Sort", ('Recent', 'Oldest', 'A-Z', 'Z-A', 'Random'))
|
@@ -344,15 +309,15 @@ if not mode:
|
|
344 |
elif user_sort == 'Z-A':
|
345 |
recipes.sort(key=lambda x: x['name'], reverse=True)
|
346 |
elif user_sort == 'Random':
|
347 |
-
|
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.")
|
|
|
1 |
+
import os
|
2 |
+
import re
|
3 |
+
import ast
|
4 |
+
import json
|
5 |
+
import pickle
|
6 |
+
import secrets
|
7 |
import random
|
8 |
+
import datetime
|
|
|
9 |
import pandas as pd
|
10 |
from huggingface_hub import login, InferenceClient
|
|
|
11 |
from sklearn.metrics.pairwise import cosine_similarity
|
12 |
+
import streamlit as st
|
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 |
|
|
|
26 |
with open('items_dict.pkl', 'rb') as file:
|
27 |
items_dict = pd.DataFrame.from_dict(pickle.load(file))
|
28 |
|
29 |
+
mode = st.toggle(label="MART")
|
30 |
+
|
31 |
+
# Utility functions
|
32 |
+
def preprocess_text(text):
|
33 |
+
text = re.sub(r'[^a-zA-Z\s]', '', text)
|
34 |
+
text = re.sub(r'\s+', ' ', text).strip()
|
35 |
+
return text.lower()
|
36 |
|
37 |
def get_recommendations(user_description, count_vectorizer, count_matrix):
|
38 |
user_description = preprocess_text(user_description)
|
|
|
41 |
similar_indices = cosine_similarities.argsort()[::-1]
|
42 |
return similar_indices
|
43 |
|
44 |
+
def create_detailed_prompt(user_direction, exclusions, serving_size, difficulty):
|
45 |
+
prompt_template = {
|
46 |
+
"Quick & Easy": (
|
47 |
+
"Provide a 'Quick and Easy' recipe for {user_direction} that excludes {exclusions} and has a serving size of {serving_size}. "
|
48 |
+
"It should require as few ingredients as possible and should be ready in as little time as possible. "
|
49 |
+
"The steps should be simple, and the ingredients should be commonly found in a household pantry. "
|
50 |
+
"Provide a detailed ingredient list and step-by-step guide that explains the instructions to prepare in detail."
|
51 |
+
),
|
52 |
+
"Intermediate": (
|
53 |
+
"Provide a classic recipe for {user_direction} that excludes {exclusions} and has a serving size of {serving_size}. "
|
54 |
+
"The recipe should offer a bit of a cooking challenge but should not require professional skills. "
|
55 |
+
"The recipe should feature traditional ingredients and techniques that are authentic to its cuisine. "
|
56 |
+
"Provide a detailed ingredient list and step-by-step guide that explains the instructions to prepare in detail."
|
57 |
+
),
|
58 |
+
"Professional": (
|
59 |
+
"Provide an advanced recipe for {user_direction} that excludes {exclusions} and has a serving size of {serving_size}. "
|
60 |
+
"The recipe should push the boundaries of culinary arts, integrating unique ingredients, advanced cooking techniques, and innovative presentations. "
|
61 |
+
"The recipe should be able to be served at a high-end restaurant or would impress at a gourmet food competition. "
|
62 |
+
"Provide a detailed ingredient list and step-by-step guide that explains the instructions to prepare in detail."
|
63 |
+
)
|
64 |
+
}
|
65 |
+
return prompt_template[difficulty].format(
|
66 |
+
user_direction=user_direction,
|
67 |
+
exclusions=exclusions,
|
68 |
+
serving_size=serving_size
|
69 |
+
)
|
70 |
+
|
71 |
+
def generate_recipe(user_inputs):
|
72 |
+
with st.spinner('Building the perfect recipe...'):
|
73 |
+
prompt = create_detailed_prompt(user_inputs['user_direction'], user_inputs['exclusions'],
|
74 |
+
user_inputs['serving_size'], user_inputs['difficulty'])
|
75 |
+
functions = [
|
76 |
+
{
|
77 |
+
"name": "provide_recipe",
|
78 |
+
"description": "Provides a detailed recipe strictly adhering to the user input/specifications, especially ingredient exclusions and the recipe difficulty",
|
79 |
+
"parameters": {
|
80 |
+
"type": "object",
|
81 |
+
"properties": {
|
82 |
+
"name": {"type": "string", "description": "A creative name for the recipe"},
|
83 |
+
"description": {"type": "string", "description": "a brief one-sentence description of the provided recipe"},
|
84 |
+
"ingredients": {
|
85 |
+
"type": "array",
|
86 |
+
"items": {
|
87 |
+
"type": "object",
|
88 |
+
"properties": {"name": {"type": "string", "description": "Quantity and name of the ingredient"}}
|
89 |
+
}
|
90 |
+
},
|
91 |
+
"instructions": {
|
92 |
+
"type": "array",
|
93 |
+
"items": {
|
94 |
+
"type": "object",
|
95 |
+
"properties": {
|
96 |
+
"step_number": {"type": "number", "description": "The sequence number of this step"},
|
97 |
+
"instruction": {"type": "string", "description": "Detailed description of what to do in this step"}
|
98 |
+
}
|
99 |
+
}
|
100 |
+
}
|
101 |
+
},
|
102 |
+
"required": ["name", "description", "ingredients", "instructions"]
|
103 |
+
}
|
104 |
+
}
|
105 |
+
]
|
106 |
+
|
107 |
+
generate_kwargs = dict(
|
108 |
+
temperature=0.9,
|
109 |
+
max_new_tokens=10000,
|
110 |
+
top_p=0.9,
|
111 |
+
repetition_penalty=1.0,
|
112 |
+
do_sample=True,
|
113 |
+
)
|
114 |
+
|
115 |
+
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)}"
|
116 |
+
|
117 |
+
response = client.text_generation(prompt, **generate_kwargs)
|
118 |
+
st.session_state.recipe = response
|
119 |
+
st.session_state.recipe_saved = False
|
120 |
+
|
121 |
def show_recipe(recipe):
|
122 |
with st.spinner("HANG TIGHT, RECIPE INCOMING..."):
|
123 |
+
name_and_dis = f'# {recipe["name"]}\n\n{recipe["description"]}\n\n'
|
|
|
124 |
ingredients = '## Ingredients:\n'
|
125 |
+
instructions = '## Instructions:\n'
|
126 |
for instruction in recipe["instructions"]:
|
127 |
instructions += f"{instruction['step_number']}. {instruction['instruction']}\n"
|
128 |
+
|
129 |
st.write(name_and_dis)
|
130 |
col01, col02 = st.columns(2)
|
131 |
with col01:
|
|
|
139 |
cont = st.container(border=True, height=500)
|
140 |
cont.write(instructions)
|
141 |
|
142 |
+
def clear_inputs():
|
143 |
+
st.session_state.user_direction = None
|
144 |
+
st.session_state.exclusions = None
|
145 |
+
st.session_state.serving_size = 2
|
146 |
+
st.session_state.selected_difficulty = "Quick & Easy"
|
147 |
+
st.session_state.recipe = None
|
148 |
+
|
149 |
+
def create_safe_filename(recipe_name):
|
150 |
+
safe_name = recipe_name.lower().replace(" ", "_")
|
151 |
+
safe_name = re.sub(r"[^a-zA-Z0-9_]", "", safe_name)
|
152 |
+
safe_name = safe_name[:50] if len(safe_name) > 50 else safe_name
|
153 |
+
unique_token = secrets.token_hex(8)
|
154 |
+
return f"{unique_token}_{safe_name}"
|
155 |
+
|
156 |
+
def save_recipe():
|
157 |
+
with st.spinner('WAIT SAVING YOUR DISH...'):
|
158 |
+
filename = create_safe_filename(recipe["name"])
|
159 |
+
os.makedirs('data', exist_ok=True)
|
160 |
+
with open(f'./data/{filename}.pkl', 'wb') as f:
|
161 |
+
pickle.dump(recipe, f)
|
162 |
+
st.session_state.recipe_saved = True
|
163 |
+
|
164 |
+
def load_saved_recipes_from_pickle(directory_path):
|
165 |
+
os.makedirs('data', exist_ok=True)
|
166 |
+
recipes = []
|
167 |
+
for filename in os.listdir(directory_path):
|
168 |
+
if filename.endswith('.pkl'):
|
169 |
+
with open(os.path.join(directory_path, filename), 'rb') as file:
|
170 |
+
recipe = pickle.load(file)
|
171 |
+
recipes.append(recipe)
|
172 |
+
return recipes
|
173 |
|
174 |
+
# Main UI logic
|
175 |
if not mode:
|
176 |
if 'current_tab' not in st.session_state:
|
177 |
st.session_state.current_tab = 'COOK'
|
178 |
+
|
179 |
+
cook, saved = st.tabs(['COOK', 'SAVED'])
|
180 |
|
181 |
if cook:
|
182 |
st.session_state.current_tab = 'COOK'
|
183 |
if saved:
|
184 |
st.session_state.current_tab = 'SAVED'
|
185 |
+
|
186 |
if st.session_state.current_tab == 'COOK':
|
187 |
with cook:
|
188 |
client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
|
189 |
+
|
190 |
if 'recipe' not in st.session_state:
|
191 |
st.session_state.recipe = None
|
192 |
+
|
193 |
if 'recipe_saved' not in st.session_state:
|
194 |
st.session_state.recipe_saved = None
|
195 |
+
|
196 |
if 'user_direction' not in st.session_state:
|
197 |
st.session_state.user_direction = None
|
198 |
+
|
199 |
if 'serving_size' not in st.session_state:
|
200 |
st.session_state.serving_size = 2
|
201 |
+
|
202 |
if 'selected_difficulty' not in st.session_state:
|
203 |
st.session_state.selected_difficulty = "Quick & Easy"
|
204 |
+
|
205 |
if 'exclusions' not in st.session_state:
|
206 |
st.session_state.exclusions = None
|
207 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
208 |
st.title("Let's get cooking")
|
209 |
+
col1, col2 = st.columns(2)
|
210 |
with col1:
|
211 |
st.session_state.user_direction = st.text_area(
|
212 |
"What do you want to cook? Describe anything - a dish, cuisine, event, or vibe.",
|
|
|
221 |
value=st.session_state.serving_size,
|
222 |
step=1
|
223 |
)
|
224 |
+
|
225 |
difficulty_dictionary = {
|
226 |
"Quick & Easy": {
|
227 |
"description": "Easy recipes with straightforward instructions. Ideal for beginners or those seeking quick and simple cooking.",
|
|
|
233 |
"description": "Complex recipes that demand a high level of skill and precision. Suited for seasoned cooks aspiring to professional-level sophistication and creativity.",
|
234 |
}
|
235 |
}
|
236 |
+
|
237 |
st.session_state.selected_difficulty = st.radio(
|
238 |
"Choose a difficulty level for your recipe.",
|
239 |
+
list(difficulty_dictionary.keys()),
|
240 |
+
index=list(difficulty_dictionary.keys()).index(st.session_state.selected_difficulty),
|
241 |
+
format_func=lambda x: f"{x}: {difficulty_dictionary[x]['description']}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
242 |
)
|
243 |
+
|
244 |
st.session_state.exclusions = st.text_area(
|
245 |
"Any ingredients you want to exclude?",
|
246 |
value=st.session_state.exclusions,
|
247 |
placeholder="gluten, dairy, nuts, cilantro",
|
248 |
)
|
249 |
+
|
250 |
fancy_exclusions = ""
|
|
|
251 |
if st.session_state.selected_difficulty == "Professional":
|
252 |
exclude_fancy = st.checkbox(
|
253 |
"Exclude cliche professional ingredients? (gold leaf, truffle, edible flowers, microgreens)",
|
254 |
value=True)
|
255 |
if exclude_fancy:
|
256 |
fancy_exclusions = "gold leaf, truffle, edible flowers, microgreens, gold dust"
|
257 |
+
|
258 |
user_inputs = {
|
259 |
"user_direction": st.session_state.user_direction,
|
260 |
"exclusions": f"{st.session_state.exclusions}, {fancy_exclusions}".strip(", "),
|
261 |
"serving_size": st.session_state.serving_size,
|
262 |
"difficulty": st.session_state.selected_difficulty
|
263 |
}
|
264 |
+
|
265 |
button_cols_submit = st.columns([1, 1, 4])
|
266 |
with button_cols_submit[0]:
|
267 |
st.button(label='Submit', on_click=generate_recipe, kwargs=dict(user_inputs=user_inputs), type="primary",
|
|
|
270 |
st.button(label='Reset', on_click=clear_inputs, type="secondary", use_container_width=True)
|
271 |
with button_cols_submit[2]:
|
272 |
st.empty()
|
273 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
274 |
if st.session_state.recipe is not None:
|
275 |
st.divider()
|
|
|
276 |
recipe = json.loads(st.session_state.recipe)
|
277 |
if not st.session_state.recipe_saved:
|
278 |
show_recipe(recipe)
|
279 |
recipe['timestamp'] = str(datetime.datetime.now())
|
280 |
+
disable_button = st.session_state.recipe_saved
|
281 |
+
|
|
|
|
|
282 |
button_cols_save = st.columns([1, 1, 4])
|
283 |
with button_cols_save[0]:
|
284 |
st.button("Save Recipe", on_click=save_recipe, disabled=disable_button, type="primary")
|
|
|
286 |
st.empty()
|
287 |
with button_cols_save[2]:
|
288 |
st.empty()
|
289 |
+
|
290 |
+
if st.session_state.recipe_saved:
|
291 |
st.success("Recipe Saved!")
|
292 |
+
|
293 |
+
elif st.session_state.current_tab == 'SAVED':
|
294 |
with saved:
|
295 |
st.title("Saved Recipes")
|
296 |
with st.spinner('LOADING YOUR RECIPE...'):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
297 |
directory_path = 'data'
|
298 |
recipes = load_saved_recipes_from_pickle(directory_path)
|
299 |
+
|
|
|
300 |
cols = st.columns([4, 1])
|
301 |
with cols[1]:
|
302 |
user_sort = st.selectbox("Sort", ('Recent', 'Oldest', 'A-Z', 'Z-A', 'Random'))
|
|
|
309 |
elif user_sort == 'Z-A':
|
310 |
recipes.sort(key=lambda x: x['name'], reverse=True)
|
311 |
elif user_sort == 'Random':
|
312 |
+
random.shuffle(recipes)
|
313 |
with cols[0]:
|
314 |
user_search = st.selectbox("Search Recipes", [""] + [recipe['name'] for recipe in recipes])
|
315 |
st.write("") # just some space
|
316 |
+
|
317 |
+
if user_search:
|
318 |
st.divider()
|
319 |
filtered_recipes = [recipe for recipe in recipes if recipe['name'] == user_search]
|
320 |
if filtered_recipes:
|
321 |
show_recipe(filtered_recipes[0])
|
322 |
else:
|
323 |
+
st.write("No recipe found.")
|