File size: 19,484 Bytes
101017e
 
 
 
 
 
ee89318
101017e
cca57f2
6795bf0
2590d8a
101017e
5cb7f33
 
 
 
cca57f2
 
ba52fb4
101017e
98f6a5e
8576e15
101017e
7856036
 
 
 
 
 
 
 
 
c4a397e
101017e
 
26b4729
9753cc8
 
 
 
 
 
 
101017e
26b4729
c910c88
c4a397e
 
c910c88
c4a397e
c910c88
 
101017e
c910c88
 
 
 
 
 
 
c4a397e
 
 
c910c88
 
 
ee89318
101017e
c4a397e
 
 
101017e
c4a397e
 
f45a4ae
c4a397e
 
101017e
c4a397e
 
101017e
c4a397e
 
101017e
c4a397e
 
101017e
c4a397e
 
101017e
c4a397e
 
101017e
 
c4a397e
 
 
 
 
101017e
c4a397e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26b4729
c4a397e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f45a4ae
101017e
c4a397e
 
 
 
 
 
 
 
 
 
 
 
 
101017e
 
c4a397e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26b4729
101017e
c4a397e
 
 
 
 
 
 
 
 
2590d8a
c4a397e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101017e
c4a397e
 
 
 
 
101017e
c4a397e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de30414
 
c4a397e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee89318
c4a397e
 
 
 
 
5cb7f33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
import os
import re
import ast
import json
import pickle
import secrets
import random
import datetime
import pandas as pd
from huggingface_hub import login, InferenceClient
from sklearn.metrics.pairwise import cosine_similarity
import streamlit as st
import wordcloud
import matplotlib.pyplot as plt
from pygwalker.api.streamlit import StreamlitRenderer
import plotly.express as px

st.set_page_config(layout="wide")

# Load environment token
login(token=os.getenv("TOKEN"))

# Load data from pickled files
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))


mode = st.toggle(label="MART")


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 show_recipe(recipe):
    with st.spinner("HANG TIGHT, RECIPE INCOMING..."):
        name_and_dis = f'# {recipe["name"]}\n\n'
        name_and_dis += f'{recipe["description"]}\n\n'
        ingredients = '## Ingredients:\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)
            cont.write(ingredients)
            for j, i in enumerate(recipe["ingredients"]):
                cont.selectbox(i['name'],
                               options=items_dict.iloc[get_recommendations(i['name'], cv, vectors)][
                                   "PRODUCT_NAME"].values,
                               key=f"selectbox_{j}_{i['name']}{random.random() * 100}")
        with col02:
            cont = st.container(border=True, height=500)
            cont.write(instructions)


# Initialize the inference client for the Mixtral model

if not mode:
    cook, saved = st.tabs(['COOK', 'SAVED'])
    with cook:
        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 preprocess_text(text):
            # Remove non-alphabet characters and extra spaces
            text = re.sub(r'[^a-zA-Z\s]', '', text)
            text = re.sub(r'\s+', ' ', text).strip()
            return text.lower()


        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.session_state.recipe = None


        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()


        def create_safe_filename(recipe_name):
            # format and generate random URL-safe text string
            safe_name = recipe_name.lower()
            safe_name = safe_name.replace(" ", "_")
            safe_name = re.sub(r"[^a-zA-Z0-9_]", "", safe_name)
            safe_name = (safe_name[:50]) if len(safe_name) > 50 else safe_name
            unique_token = secrets.token_hex(8)
            safe_filename = f"{unique_token}_{safe_name}"
            return safe_filename


        def save_recipe():
            with st.spinner('WAIT SAVING YOUR DISH...'):
                filename = create_safe_filename(recipe["name"])
                os.makedirs('data', exist_ok=True)
                with open(f'./data/{filename}.pkl', 'wb') as f:
                    pickle.dump(recipe, f)
                st.session_state.recipe_saved = True


        if st.session_state.recipe is not None:
            st.divider()
            print(st.session_state.recipe)
            recipe = json.loads(st.session_state.recipe)
            if not st.session_state.recipe_saved:
                show_recipe(recipe)
            recipe['timestamp'] = str(datetime.datetime.now())
            if st.session_state.recipe_saved == True:
                disable_button = True
            else:
                disable_button = False
            button_cols_save = st.columns([1, 1, 4])
            with button_cols_save[0]:
                st.button("Save Recipe", on_click=save_recipe, disabled=disable_button, type="primary")
            with button_cols_save[1]:
                st.empty()
            with button_cols_save[2]:
                st.empty()
            if st.session_state.recipe_saved == True:
                st.success("Recipe Saved!")
    with saved:
        st.title("Saved Recipes")
        with st.spinner('LOADING YOUR RECIPE...'):
            def load_saved_recipes_from_pickle(directory_path):
                os.makedirs('data', exist_ok=True)
                recipes = []
                # Iterate through all files in the directory
                for filename in os.listdir(directory_path):
                    if filename.endswith('.pkl'):
                        file_path = os.path.join(directory_path, filename)
                        with open(file_path, 'rb') as file:
                            recipe = pickle.load(file)
                            recipes.append(recipe)
                return recipes


            # get all saved files
            directory_path = 'data'
            recipes = load_saved_recipes_from_pickle(directory_path)
            print(recipes)

            cols = st.columns([4, 1])
            with cols[1]:
                user_sort = st.selectbox("Sort", ('Recent', 'Oldest', 'A-Z', 'Z-A', 'Random'))
                if user_sort == 'Recent':
                    recipes.sort(key=lambda x: x['timestamp'], reverse=True)
                elif user_sort == 'Oldest':
                    recipes.sort(key=lambda x: x['timestamp'])
                elif user_sort == 'A-Z':
                    recipes.sort(key=lambda x: x['name'])
                elif user_sort == 'Z-A':
                    recipes.sort(key=lambda x: x['name'], reverse=True)
                elif user_sort == 'Random':
                    recipes.sort(key=lambda x: x['file'])
            with cols[0]:
                user_search = st.selectbox("Search Recipes", [""] + [recipe['name'] for recipe in recipes])
            st.write("")  # just some space

            if user_search != "":
                st.divider()
                filtered_recipes = [recipe for recipe in recipes if recipe['name'] == user_search]
                if filtered_recipes:
                    show_recipe(filtered_recipes[0])
                else:
                    st.write("No recipe found.")
else:
    st.markdown("# :eyes: PEOPLE SEARCHING FOR...")
    print(st.session_state.ind)
    flattened_indices = list(set(index for sublist in st.session_state.ind for index in sublist))
    df = items_dict.iloc[flattened_indices]
    if st.session_state.ind != []:
        with st.spinner("LET'S SEE, WHAT PEOPLE WANT..."):
            cont1 = st.container(border=True, height=500)
            with cont1:
                wc = wordcloud.WordCloud(width=1000, height=320, background_color='white').generate(
                    ' '.join(df['CATEGORY']))

                # Display word cloud
                fig, ax = plt.subplots()
                ax.imshow(wc, interpolation='bilinear')
                ax.axis('off')

                st.pyplot(fig, use_container_width=True)

            with st.container(border=True, height=500):
                col1, col2 = st.columns(2)
                with col1:
                    st.markdown('## DEMAND AS PER CATEGORY')
                    with plt.style.context('Solarize_Light2'):
                        fig0 = px.pie(df, names='CATEGORY', hole=0.5)
                        fig0.update_traces(text=df['CATEGORY'], textposition='outside')
                        st.plotly_chart(fig0, use_container_width=True)

                with col2:
                    st.markdown('## DEMAND AS PER AVAILABILITY')
                    with plt.style.context('Solarize_Light2'):
                        fig1 = px.pie(df, names='AVAILABILITY', hole=0.5)
                        fig1.update_traces(text=df['AVAILABILITY'], textposition='outside')
                        st.plotly_chart(fig1, use_container_width=True)

            with st.container(border=True, height=620):
                st.markdown('## :deciduous_tree: Hierarchical view of Sales using TreeMap')
                fig4 = px.treemap(df, path=['CATEGORY', 'AVAILABILITY','PRODUCT'],color='AVAILABILITY')
                fig4.update_layout(height=550)
                st.plotly_chart(fig4, use_container_width=True,scrolling=False)

            with st.container(border=True, height=500):
                fig = px.bar(df,
                             y='CATEGORY',
                             x='BREADCRUMBS',
                             color='BRAND',
                             # title='Gross Sales of Every Segment Country-wise',
                             barmode='relative',
                             title="Segment Vs. Gross Sales"
                             )
                st.plotly_chart(fig, use_container_width=True)

            @st.cache_resource
            def pygwalerapp(df):
                return StreamlitRenderer(df)
            # st.markdown("## :desktop_computer: DO YOUR OWN RESEARCH...")
            with st.expander("## :desktop_computer: LOOKING FOR SOMETHING ELSE..."):
                pygwalerapp(df).explorer()