Spaces:
Sleeping
Sleeping
import streamlit as st | |
import re | |
import json | |
import os | |
import pandas as pd | |
from huggingface_hub import login, InferenceClient | |
import pickle | |
from sklearn.metrics.pairwise import cosine_similarity | |
st.set_page_config(layout="wide") | |
login(token=os.getenv("TOKEN")) | |
with open('cv.pkl', 'rb') as file: | |
cv = pickle.load(file) | |
with open('vectors.pkl', 'rb') as file: | |
vectors = pickle.load(file) | |
with open('items_dict.pkl', 'rb') as file: | |
items_dict = pd.DataFrame.from_dict(pickle.load(file)) | |
data = pd.read_csv('marketing_sample_for_walmart_com-product_details__20200101_20200331__30k_data.csv') | |
# Initialize the inference client for the Mixtral model | |
client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1") | |
if 'recipe' not in st.session_state: | |
st.session_state.recipe = None | |
if 'recipe_saved' not in st.session_state: | |
st.session_state.recipe_saved = None | |
if 'user_direction' not in st.session_state: | |
st.session_state.user_direction = None | |
if 'serving_size' not in st.session_state: | |
st.session_state.serving_size = 2 | |
if 'selected_difficulty' not in st.session_state: | |
st.session_state.selected_difficulty = "Quick & Easy" | |
if 'exclusions' not in st.session_state: | |
st.session_state.exclusions = None | |
def get_recommendations(user_description, count_vectorizer, count_matrix): | |
user_description = preprocess_text(user_description) | |
user_vector = count_vectorizer.transform([user_description]) | |
cosine_similarities = cosine_similarity(user_vector, count_matrix).flatten() | |
similar_indices = cosine_similarities.argsort()[::-1] | |
return similar_indices | |
def create_detailed_prompt(user_direction, exclusions, serving_size, difficulty): | |
if difficulty == "Quick & Easy": | |
prompt = ( | |
f"Provide a 'Quick and Easy' recipe for {user_direction} that excludes {exclusions} and has a serving size of {serving_size}. " | |
f"It should require as few ingredients as possible and should be ready in as little time as possible. " | |
f"The steps should be simple, and the ingredients should be commonly found in a household pantry. " | |
f"Provide a detailed ingredient list and step-by-step guide that explains the instructions to prepare in detail." | |
) | |
elif difficulty == "Intermediate": | |
prompt = ( | |
f"Provide a classic recipe for {user_direction} that excludes {exclusions} and has a serving size of {serving_size}. " | |
f"The recipe should offer a bit of a cooking challenge but should not require professional skills. " | |
f"The recipe should feature traditional ingredients and techniques that are authentic to its cuisine. " | |
f"Provide a detailed ingredient list and step-by-step guide that explains the instructions to prepare in detail." | |
) | |
elif difficulty == "Professional": | |
prompt = ( | |
f"Provide an advanced recipe for {user_direction} that excludes {exclusions} and has a serving size of {serving_size}. " | |
f"The recipe should push the boundaries of culinary arts, integrating unique ingredients, advanced cooking techniques, and innovative presentations. " | |
f"The recipe should be able to be served at a high-end restaurant or would impress at a gourmet food competition. " | |
f"Provide a detailed ingredient list and step-by-step guide that explains the instructions to prepare in detail." | |
) | |
return prompt | |
def generate_recipe(user_inputs): | |
with st.spinner('Building the perfect recipe...'): | |
prompt = create_detailed_prompt(user_inputs['user_direction'], user_inputs['exclusions'], | |
user_inputs['serving_size'], user_inputs['difficulty']) | |
functions = [ | |
{ | |
"name": "provide_recipe", | |
"description": "Provides a detailed recipe strictly adhering to the user input/specifications, especially ingredient exclusions and the recipe difficulty", | |
"parameters": { | |
"type": "object", | |
"properties": { | |
"name": { | |
"type": "string", | |
"description": "A creative name for the recipe" | |
}, | |
"description": { | |
"type": "string", | |
"description": "a brief one-sentence description of the provided recipe" | |
}, | |
"ingredients": { | |
"type": "array", | |
"items": { | |
"type": "object", | |
"properties": { | |
"name": { | |
"type": "string", | |
"description": "Quantity and name of the ingredient" | |
} | |
} | |
} | |
}, | |
"instructions": { | |
"type": "array", | |
"items": { | |
"type": "object", | |
"properties": { | |
"step_number": { | |
"type": "number", | |
"description": "The sequence number of this step" | |
}, | |
"instruction": { | |
"type": "string", | |
"description": "Detailed description of what to do in this step" | |
} | |
} | |
} | |
} | |
}, | |
"required": [ | |
"name", | |
"description", | |
"ingredients", | |
"instructions" | |
], | |
}, | |
} | |
] | |
generate_kwargs = dict( | |
temperature=0.9, | |
max_new_tokens=10000, | |
top_p=0.9, | |
repetition_penalty=1.0, | |
do_sample=True, | |
) | |
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)}" | |
response = client.text_generation(prompt, **generate_kwargs) | |
st.session_state.recipe = response | |
st.session_state.recipe_saved = False | |
def clear_inputs(): | |
st.session_state.user_direction = None | |
st.session_state.exclusions = None | |
st.session_state.serving_size = 2 | |
st.session_state.selected_difficulty = "Quick & Easy" | |
st.title("Let's get cooking") | |
col1,col2=st.columns(2) | |
with col1: | |
st.session_state.user_direction = st.text_area( | |
"What do you want to cook? Describe anything - a dish, cuisine, event, or vibe.", | |
value=st.session_state.user_direction, | |
placeholder="quick snack, asian style bowl with either noodles or rice, something italian", | |
) | |
with col2: | |
st.session_state.serving_size = st.number_input( | |
"How many servings would you like to cook?", | |
min_value=1, | |
max_value=100, | |
value=st.session_state.serving_size, | |
step=1 | |
) | |
difficulty_dictionary = { | |
"Quick & Easy": { | |
"description": "Easy recipes with straightforward instructions. Ideal for beginners or those seeking quick and simple cooking.", | |
}, | |
"Intermediate": { | |
"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.", | |
}, | |
"Professional": { | |
"description": "Complex recipes that demand a high level of skill and precision. Suited for seasoned cooks aspiring to professional-level sophistication and creativity.", | |
} | |
} | |
st.session_state.selected_difficulty = st.radio( | |
"Choose a difficulty level for your recipe.", | |
[ | |
list(difficulty_dictionary.keys())[0], | |
list(difficulty_dictionary.keys())[1], | |
list(difficulty_dictionary.keys())[2] | |
], | |
captions=[ | |
difficulty_dictionary["Quick & Easy"]["description"], | |
difficulty_dictionary["Intermediate"]["description"], | |
difficulty_dictionary["Professional"]["description"] | |
], | |
index=list(difficulty_dictionary).index(st.session_state.selected_difficulty) | |
) | |
st.session_state.exclusions = st.text_area( | |
"Any ingredients you want to exclude?", | |
value=st.session_state.exclusions, | |
placeholder="gluten, dairy, nuts, cilantro", | |
) | |
fancy_exclusions = "" | |
if st.session_state.selected_difficulty == "Professional": | |
exclude_fancy = st.checkbox( | |
"Exclude cliche professional ingredients? (gold leaf, truffle, edible flowers, microgreens)", | |
value=True) | |
if exclude_fancy: | |
fancy_exclusions = "gold leaf, truffle, edible flowers, microgreens, gold dust" | |
user_inputs = { | |
"user_direction": st.session_state.user_direction, | |
"exclusions": f"{st.session_state.exclusions}, {fancy_exclusions}".strip(", "), | |
"serving_size": st.session_state.serving_size, | |
"difficulty": st.session_state.selected_difficulty | |
} | |
button_cols_submit = st.columns([1, 1, 4]) | |
with button_cols_submit[0]: | |
st.button(label='Submit', on_click=generate_recipe, kwargs=dict(user_inputs=user_inputs), type="primary", | |
use_container_width=True) | |
with button_cols_submit[1]: | |
st.button(label='Reset', on_click=clear_inputs, type="secondary", use_container_width=True) | |
with button_cols_submit[2]: | |
st.empty() | |
if st.session_state.recipe is not None: | |
st.divider() | |
try: | |
print(st.session_state.recipe) | |
recipe = json.loads(st.session_state.recipe) | |
name_and_dis = f'# {recipe["name"]}\n\n' | |
name_and_dis += f'{recipe["description"]}\n\n' | |
ingredients = '## Ingredients:\n' | |
# for ingredient in recipe["ingredients"]: | |
# ingredients += f"- {ingredient['name']}\n" | |
instructions = '\n## Instructions:\n' | |
for instruction in recipe["instructions"]: | |
instructions += f"{instruction['step_number']}. {instruction['instruction']}\n" | |
st.write(name_and_dis) | |
col01, col02 = st.columns(2) | |
with col01: | |
cont = st.container(border=True, height=500) | |
for i in recipe["ingredients"]: | |
cont.selectbox(i['name'],options=items_dict.iloc[get_recommendations(i['name'],cv,vectors)]["Product Name"].values) | |
with col02: | |
cont = st.container(border=True, height=500) | |
cont.write(instructions) | |
except (json.JSONDecodeError, KeyError) as e: | |
st.error(f"Failed to parse recipe: {e}") | |