-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRecommendation.py
2266 lines (1934 loc) · 99.6 KB
/
Recommendation.py
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import re
import ast
import uuid
import json
import time
import base64
import random
import pickle
import joblib
import requests
import nltk
import numpy as np
import pandas as pd
from PIL import Image
from io import BytesIO
import streamlit as st
import streamlit_antd_components as sac
import firebase_admin
from firebase_admin import auth, credentials
from deep_canvas.image_generation import GenerativeImageSynthesis
from feature_scape.recommendation import FeatureSpaceMatching
from backend.send_mail import MailUtils
from backend.generate_pdf import PDFUtils
from configurations.api_authtoken import AuthTokens
from configurations.resource_path import ResourceRegistry
from configurations.firebase_credentials import FirebaseCredentials
from database.mongodb import MongoDB
from database.blob_storage import AzureStorageAccount
# Set the page title and favicon to be displayed on the streamlit web application
st.set_page_config(
page_title="RecipeML: Recipe Recommendation",
page_icon="assets/images/favicon/recipeml_favicon.png",
)
# Remove the extra paddings from the top and bottom margin of the block container
st.markdown(
"""
<style>
.block-container {
padding-top: 0.5rem;
padding-bottom: 0rem;
}
</style>
""",
unsafe_allow_html=True,
)
# Hide the streamlit menu & the default footer from the production app's frontend
st.markdown(
"""
<style>
#MainMenu {visibility: hidden;}
footer {visibility: hidden;}
</style>
""",
unsafe_allow_html=True,
)
# Remove the default styling from the hyperlinks displayed on the web application
st.markdown(
"""
<style>
.stMarkdown a {
text-decoration: none;
}
</style>
""",
unsafe_allow_html=True,
)
if "user_authentication_status" not in st.session_state:
st.session_state.user_authentication_status = None
if "cache_generate_recommendations" not in st.session_state:
st.session_state.cache_generate_recommendations = False
if "themes" not in st.session_state:
st.session_state.themes = {
"current_theme": "dark",
"refreshed": True,
"light": {
"theme.base": "dark",
"theme.backgroundColor": "#111111",
"theme.primaryColor": "#64ABD8",
"theme.secondaryBackgroundColor": "#181818",
"theme.textColor": "#FFFFFF",
"button_face": "🌜",
},
"dark": {
"theme.base": "light",
"theme.backgroundColor": "#fdfefe",
"theme.primaryColor": "#64ABD8",
"theme.secondaryBackgroundColor": "#dee4e7",
"theme.textColor": "#333333",
"button_face": "🌞",
},
}
def change_streamlit_theme():
previous_theme = st.session_state.themes["current_theme"]
tdict = (
st.session_state.themes["light"]
if st.session_state.themes["current_theme"] == "light"
else st.session_state.themes["dark"]
)
for vkey, vval in tdict.items():
if vkey.startswith("theme"):
st._config.set_option(vkey, vval)
st.session_state.themes["refreshed"] = False
if previous_theme == "dark":
st.session_state.themes["current_theme"] = "light"
elif previous_theme == "light":
st.session_state.themes["current_theme"] = "dark"
def set_generate_recommendations_cache_to_true():
st.session_state.cache_generate_recommendations = True
def set_generate_recommendations_cache_to_false():
st.session_state.cache_generate_recommendations = False
def apply_style_to_sidebar_button(css_file_name):
with open(css_file_name, encoding="utf-8") as file:
st.markdown(f"<style>{file.read()}</style>", unsafe_allow_html=True)
if st.session_state.themes["refreshed"] == False:
st.session_state.themes["refreshed"] = True
st.rerun()
try:
# Read the CSS code from the css file & allow html parsing to apply the style
apply_style_to_sidebar_button("assets/css/login_sidebar_button_style.css")
except:
pass # Use the default style if the file is'nt found or if exception happens
if __name__ == "__main__":
with st.sidebar:
selected_menu_item = sac.menu(
[
sac.MenuItem(
"Recommendations",
icon="boxes",
),
sac.MenuItem(
"Discover RecipeML",
icon="layers",
tag=[sac.Tag("New", color="blue")],
),
sac.MenuItem(" ", disabled=True),
sac.MenuItem(type="divider"),
],
open_all=True,
)
if selected_menu_item == "Recommendations":
if "user_authentication_status" not in st.session_state:
st.session_state.user_authentication_status = None
if "authenticated_user_email_id" not in st.session_state:
st.session_state.authenticated_user_email_id = None
if "authenticated_user_username" not in st.session_state:
st.session_state.authenticated_user_username = None
if "user_display_name" not in st.session_state:
st.session_state.user_display_name = None
auth_token = AuthTokens()
resource_registry = ResourceRegistry()
feature_space_matching = FeatureSpaceMatching()
genisys = GenerativeImageSynthesis(
image_quality="low", enable_gpu_acceleration=False
)
# Fetch preloader image from the assets directory, to be used in this app
if st.session_state.themes["current_theme"] == "dark":
loading_image_path = (
resource_registry.loading_assets_dir + "loading_img.gif"
)
else:
loading_image_path = (
resource_registry.loading_assets_dir + "loading_img_light.gif"
)
with open(loading_image_path, "rb") as f:
image_data = f.read()
encoded_image = base64.b64encode(image_data).decode()
# Load processed list of ingredients from the binary dump to a global var
try:
with open(
resource_registry.ingredients_list_path, "rb"
) as recipe_nlg_ingredients_list:
ingredients_list = joblib.load(recipe_nlg_ingredients_list)
except:
ingredients_list = [
"Bread",
"Mushroom",
"Butter",
"Onion",
"Cheese",
"Tomato",
"Orange",
]
try:
# Read CSS code from the file & allow html parsing to apply the style
apply_style_to_sidebar_button("assets/css/login_home_button_style.css")
except:
pass # Use default style if file is'nt found or if exception happens
# Create multiselect widget in the sidebar for selecting input ingredient
selected_ingredients = st.sidebar.multiselect(
"Select the ingredients",
ingredients_list,
on_change=set_generate_recommendations_cache_to_false,
)
input_ingredients = [ingredient.lower() for ingredient in selected_ingredients]
generate_recommendations_button = st.sidebar.button(
"Recommend Recipes",
on_click=set_generate_recommendations_cache_to_true,
use_container_width=True,
)
# Check if ingredients are selected, and recommendation button is clicked
if (
generate_recommendations_button
or st.session_state.cache_generate_recommendations
) and len(input_ingredients) > 0:
# Display preloader, as the application performs time-intensive tasks
gif_image = st.markdown(
f'<br><br><br><br><div class="rounded-image"><img src="data:image/png;base64,{encoded_image}"></div><br><br><br><br><br><br><br><br><br><br><br>',
unsafe_allow_html=True,
)
use_large_model = True
with gif_image:
# Initialize the instances for PDFUtility, and MailUtility module
pdf_utils = PDFUtils()
mail_utils = MailUtils()
if use_large_model is True:
try:
recipeml_flask_api_url = auth_token.recipeml_flask_api_url
response = requests.post(
recipeml_flask_api_url, json=input_ingredients
)
if response.status_code == 200:
# Extract and print the first recommended recipe's details from JSON response
recommended_recipes_indices = response.json()["recipe_id"]
else:
use_large_model = False
except:
use_large_model = False
if use_large_model is False:
@st.cache_data(show_spinner=False)
def _load_dataset_for_inferencing():
dataset_path_1 = "data/processed/recipe_nlg_batch_datasets/recipeml_processed_data_split_1.csv"
dataset_path_2 = "data/processed/recipe_nlg_batch_datasets/recipeml_processed_data_split_2.csv"
dataset_path_3 = "data/processed/recipe_nlg_batch_datasets/recipeml_processed_data_split_3.csv"
dataset_path_4 = "data/processed/recipe_nlg_batch_datasets/recipeml_processed_data_split_4.csv"
dataset_path_5 = "data/processed/recipe_nlg_batch_datasets/recipeml_processed_data_split_5.csv"
dataset1 = pd.read_csv(dataset_path_1)
dataset2 = pd.read_csv(dataset_path_2)
dataset3 = pd.read_csv(dataset_path_3)
dataset4 = pd.read_csv(dataset_path_4)
dataset5 = pd.read_csv(dataset_path_5)
recipeml_processed_data = [
dataset1,
dataset2,
dataset3,
dataset4,
dataset5,
]
# Load data into a variable for generating the embeddings
recipe_data = pd.concat(
recipeml_processed_data, ignore_index=True
)
recipe_data.dropna(inplace=True)
return recipe_data
recipe_data = _load_dataset_for_inferencing()
# Load TF/IDF vectorizer and the feature space matching model
(
tfidf_vectorizer,
model,
) = feature_space_matching.initialize_feature_space_matching_algorithm(
recipe_data
)
# Generate the recommendations - using feature space matching
recommended_recipes_indices = (
feature_space_matching.generate_recipe_recommendations(
input_ingredients, model, tfidf_vectorizer
)
)
st.markdown(
"""
<style>
.custom-hr {
margin-top: -10px;
}
</style>
""",
unsafe_allow_html=True,
)
azure_storage_account = AzureStorageAccount("generated-recipe-images")
recommended_recipes_names = []
recommended_recipes_images = []
gif_image.empty() # Stop displaying preloader image on the front end
recommendation_id = str(uuid.uuid4())[:8]
st.markdown(
"<H2>Here are some recipes you can try</H2>", unsafe_allow_html=True
)
st.markdown(
"<P align='justify'>These recommendations are generated using Recipe ML - one of our latest AI advancements. Our goal is to learn, improve, & innovate responsibly on AI together. Check out the data security policy for our users <a href='https://recipeml-recommendations.streamlit.app/Discover_RecipeML#no-hidden-ingredients-here-recipeml-v1-3-privacy-policy' style='color: #64ABD8;'>here</A></P>",
unsafe_allow_html=True,
)
# Create three columns to display recommendations on the web app's layout
container_1, container_2, container_3 = st.columns(3)
button_width = 225 # Set the width of each column buttons, to 256 pixels
st.markdown(
f"<style>.stButton button {{ width: {button_width}px; }}</style>",
unsafe_allow_html=True,
)
with container_1:
# Fetch details of the recommended recipe from the index location - 0
if use_large_model:
(
recipe_name,
recipe_type,
recipe_ingredients,
recipe_instructions,
recipe_preperation_time,
recipe_url,
) = feature_space_matching.lookup_recipe_details_by_index(
response.json(), 0, True
)
else:
(
recipe_name,
recipe_type,
recipe_ingredients,
recipe_instructions,
recipe_preperation_time,
recipe_url,
) = feature_space_matching.lookup_recipe_details_by_index(
recipe_data, recommended_recipes_indices[0]
)
# Attempt to generate image of the recipe, using Generative AI models
generated_image_path = genisys.generate_image(recipe_name, 225, 225)
if generated_image_path:
recipe_image = Image.open(generated_image_path)
else:
# Display a placeholder image if the image could not be generated
generated_image_path = (
resource_registry.placeholder_image_dir_path
+ "placeholder_1.png"
)
recipe_image = Image.open(generated_image_path).resize((225, 225))
st.image(recipe_image)
try:
recommended_recipes_images.append(
azure_storage_account.store_image_in_blob_container(
generated_image_path,
"".join(
[
char.lower()
if char.isalnum()
else "_"
if char == " "
else ""
for char in recipe_name
]
)
+ "_"
+ recommendation_id
+ ".png",
)
)
except:
recommended_recipes_images.append("unavailable")
recommended_recipes_names.append(recipe_name)
# Shorten recipe name to max 26 characters and add ellipsis if longer
if len(recipe_name) <= 26:
recipe_name = recipe_name
else:
recipe_name = recipe_name[:26] + "..."
# Display the name of the recommended recipe, as an HTML <H6> heading
st.markdown("<H6>" + recipe_name.title() + "</H6>", unsafe_allow_html=True)
# Display recipe details including the source, URL & preparation time
if type(recipe_preperation_time) == list:
preperation_time_in_minutes = recipe_preperation_time[0]
else:
preperation_time_in_minutes = recipe_preperation_time
if preperation_time_in_minutes < 100:
if recipe_type == "Gathered" or recipe_type == "Recipes1M":
# Determine the type, based on the source of recipe's details
if "Gathered":
recipe_type = recipe_type + " Recipe"
if "Recipes1M" in recipe_type:
recipe_type = "Recipes 1M Site"
st.markdown(
"<p style='font-size: 16px;'>Cuisine Source: <a href ='https://"
+ recipe_url
+ "' style='color: #64ABD8;'>"
+ recipe_type.title()
+ "</A><BR>Takes around "
+ str(recipe_preperation_time)
+ " mins to prepare<BR>",
unsafe_allow_html=True,
)
else:
# Display the recipe type, & the approximate preperation time
recipe_type = recipe_type + " Cuisine"
if len(recipe_type) > 19:
recipe_type = recipe_type[:15] + "..."
st.markdown(
"<p style='font-size: 16px;'>"
+ recipe_type.title()
+ f" • {str(recipe_preperation_time[1])} Calories<BR>Takes around "
+ str(recipe_preperation_time[0])
+ " mins to prepare<BR>",
unsafe_allow_html=True,
)
else:
if recipe_type == "Gathered" or recipe_type == "Recipes1M":
# Determine the type, based on the source of recipe's details
if "Gathered":
recipe_type = recipe_type + " Recipe"
if "Recipes1M" in recipe_type:
recipe_type = "Recipes 1M Site"
st.markdown(
"<p style='font-size: 16px;'>Cuisine Source: <a href ='https://"
+ recipe_url
+ "' style='color: #64ABD8;'>"
+ recipe_type.title()
+ "</A><BR>Takes over a "
+ str(recipe_preperation_time)
+ " mins to prepare<BR>",
unsafe_allow_html=True,
)
else:
# Display the recipe type, & the approximate preperation time
st.markdown(
"<p style='font-size: 16px;'>"
+ recipe_type.title()
+ "Cuisine<BR>Takes over a "
+ str(recipe_preperation_time)
+ " mins to prepare<BR>",
unsafe_allow_html=True,
)
if st.session_state.user_authentication_status is not True:
# Generate PDF file with necessary recipe details and usage terms
download_location_0 = pdf_utils.generate_recommendations_pdf(
recipe_name,
recipe_type,
recipe_url,
recipe_ingredients,
recipe_instructions,
)
# Display a download button only for the unauthenticated app user
st.download_button(
label="Download Recipe Details PDF",
data=open(download_location_0, "rb").read(),
key="download_button_0",
file_name=recipe_name.replace(" ", "_").lower() + ".pdf",
)
else:
# For authenticated user, send a mail with recipe details and PDF
if st.button(
"Send Recipe to Mail", key="button_0", use_container_width=True
):
try:
st.toast("Hold tight! Your recipe is taking flight.")
# Generate the PDF file with the necessary recipe details
download_location_0 = (
pdf_utils.generate_recommendations_pdf(
recipe_name,
recipe_type,
recipe_url,
recipe_ingredients,
recipe_instructions,
)
)
# Send the mail with attachment to the registered mail id
mail_utils.send_recipe_info_to_mail(
recipe_name,
recipe_ingredients,
recipe_instructions,
st.session_state.authenticated_user_email_id,
download_location_0,
)
# Display the information status upon successful delivery
st.toast("Bon appétit! We've delivered your recipe.")
except Exception as error:
# Display information status upon a unsuccessful delivery
st.toast("Whoops! Looks like your recipe ran into a snag.")
time.sleep(1)
st.toast("Please check your connectivity and try again.")
st.markdown("<BR>", unsafe_allow_html=True)
# Fetch details of the recommended recipe from the index location - 3
if use_large_model:
(
recipe_name,
recipe_type,
recipe_ingredients,
recipe_instructions,
recipe_preperation_time,
recipe_url,
) = feature_space_matching.lookup_recipe_details_by_index(
response.json(), 3, True
)
else:
(
recipe_name,
recipe_type,
recipe_ingredients,
recipe_instructions,
recipe_preperation_time,
recipe_url,
) = feature_space_matching.lookup_recipe_details_by_index(
recipe_data, recommended_recipes_indices[3]
)
# Attempt to generate image of the recipe, using Generative AI models
generated_image_path = genisys.generate_image(recipe_name, 225, 225)
if generated_image_path:
recipe_image = Image.open(generated_image_path)
else:
# Display a placeholder image if the image could not be generated
generated_image_path = (
resource_registry.placeholder_image_dir_path
+ "placeholder_4.png"
)
recipe_image = Image.open(generated_image_path).resize((225, 225))
st.image(recipe_image)
try:
recommended_recipes_images.append(
azure_storage_account.store_image_in_blob_container(
generated_image_path,
"".join(
[
char.lower()
if char.isalnum()
else "_"
if char == " "
else ""
for char in recipe_name
]
)
+ "_"
+ recommendation_id
+ ".png",
)
)
except:
recommended_recipes_images.append("unavailable")
recommended_recipes_names.append(recipe_name)
# Shorten recipe name to max 26 characters and add ellipsis if longer
if len(recipe_name) <= 26:
recipe_name = recipe_name
else:
recipe_name = recipe_name[:26] + "..."
# Display the name of the recommended recipe, as an HTML <H6> heading
st.markdown("<H6>" + recipe_name.title() + "</H6>", unsafe_allow_html=True)
# Display recipe details including the source, URL & preparation time
if type(recipe_preperation_time) == list:
preperation_time_in_minutes = recipe_preperation_time[0]
else:
preperation_time_in_minutes = recipe_preperation_time
if preperation_time_in_minutes < 100:
if recipe_type == "Gathered" or recipe_type == "Recipes1M":
# Determine the type, based on the source of recipe's details
if "Gathered":
recipe_type = recipe_type + " Recipe"
if "Recipes1M" in recipe_type:
recipe_type = "Recipes 1M Site"
st.markdown(
"<p style='font-size: 16px;'>Cuisine Source: <a href ='https://"
+ recipe_url
+ "' style='color: #64ABD8;'>"
+ recipe_type.title()
+ "</A><BR>Takes around "
+ str(recipe_preperation_time)
+ " mins to prepare<BR>",
unsafe_allow_html=True,
)
else:
# Display the recipe type, & the approximate preperation time
recipe_type = recipe_type + " Cuisine"
if len(recipe_type) > 19:
recipe_type = recipe_type[:15] + "..."
st.markdown(
"<p style='font-size: 16px;'>"
+ recipe_type.title()
+ f" • {str(recipe_preperation_time[1])} Calories<BR>Takes around "
+ str(recipe_preperation_time[0])
+ " mins to prepare<BR>",
unsafe_allow_html=True,
)
else:
if recipe_type == "Gathered" or recipe_type == "Recipes1M":
# Determine type, based on the source of the recipe's details
if "Gathered":
recipe_type = recipe_type + " Recipe"
if "Recipes1M" in recipe_type:
recipe_type = "Recipes 1M Site"
st.markdown(
"<p style='font-size: 16px;'>Cuisine Source: <a href ='https://"
+ recipe_url
+ "' style='color: #64ABD8;'>"
+ recipe_type.title()
+ "</A><BR>Takes over a "
+ str(recipe_preperation_time)
+ " mins to prepare<BR>",
unsafe_allow_html=True,
)
else:
# Display the recipe type, & the approximate preperation time
st.markdown(
"<p style='font-size: 16px;'>"
+ recipe_type.title()
+ "Cuisine<BR>Takes over a "
+ str(recipe_preperation_time)
+ " mins to prepare<BR>",
unsafe_allow_html=True,
)
if st.session_state.user_authentication_status is not True:
# Generate PDF file with necessary recipe details and usage terms
download_location_3 = pdf_utils.generate_recommendations_pdf(
recipe_name,
recipe_type,
recipe_url,
recipe_ingredients,
recipe_instructions,
)
# Display a download button only for the unauthenticated app user
st.download_button(
label="Download Recipe Details PDF",
data=open(download_location_3, "rb").read(),
key="download_location_3",
file_name=recipe_name.replace(" ", "_").lower() + ".pdf",
)
else:
# For authenticated user, send a mail with recipe details and PDF
if st.button(
"Send Recipe to Mail", key="button_3", use_container_width=True
):
try:
st.toast("Hold tight! Your recipe is taking flight.")
# Generate the PDF file with the necessary recipe details
download_location_3 = (
pdf_utils.generate_recommendations_pdf(
recipe_name,
recipe_type,
recipe_url,
recipe_ingredients,
recipe_instructions,
)
)
# Send the mail with attachment to the registered mail id
mail_utils.send_recipe_info_to_mail(
recipe_name,
recipe_ingredients,
recipe_instructions,
st.session_state.authenticated_user_email_id,
download_location_3,
)
# Display the information status upon successful delivery
st.toast("Bon appétit! We've delivered your recipe.")
except Exception as error:
# Display the information status upon successful delivery
st.toast("Whoops! Looks like your recipe ran into a snag.")
time.sleep(1)
st.toast("Please check your connectivity and try again.")
with container_2:
# Fetch details of the recommended recipe from the index location - 1
if use_large_model:
(
recipe_name,
recipe_type,
recipe_ingredients,
recipe_instructions,
recipe_preperation_time,
recipe_url,
) = feature_space_matching.lookup_recipe_details_by_index(
response.json(), 1, True
)
else:
(
recipe_name,
recipe_type,
recipe_ingredients,
recipe_instructions,
recipe_preperation_time,
recipe_url,
) = feature_space_matching.lookup_recipe_details_by_index(
recipe_data, recommended_recipes_indices[1]
)
# Attempt to generate image of the recipe, using Generative AI models
generated_image_path = genisys.generate_image(recipe_name, 225, 225)
if generated_image_path:
recipe_image = Image.open(generated_image_path)
else:
# Display a placeholder image if the image could not be generated
generated_image_path = (
resource_registry.placeholder_image_dir_path
+ "placeholder_2.png"
)
recipe_image = Image.open(generated_image_path).resize((225, 225))
st.image(recipe_image)
try:
recommended_recipes_images.append(
azure_storage_account.store_image_in_blob_container(
generated_image_path,
"".join(
[
char.lower()
if char.isalnum()
else "_"
if char == " "
else ""
for char in recipe_name
]
)
+ "_"
+ recommendation_id
+ ".png",
)
)
except:
recommended_recipes_images.append("unavailable")
recommended_recipes_names.append(recipe_name)
# Shorten recipe name to max 26 characters and add ellipsis if longer
if len(recipe_name) <= 26:
recipe_name = recipe_name
else:
recipe_name = recipe_name[:26] + "..."
# Display the name of the recommended recipe, as an HTML <H6> heading
st.markdown("<H6>" + recipe_name.title() + "</H6>", unsafe_allow_html=True)
# Display recipe details including the source, URL & preparation time
if type(recipe_preperation_time) == list:
preperation_time_in_minutes = recipe_preperation_time[0]
else:
preperation_time_in_minutes = recipe_preperation_time
if preperation_time_in_minutes < 100:
if recipe_type == "Gathered" or recipe_type == "Recipes1M":
# Determine the type, based on the source of recipe's details
if "Gathered":
recipe_type = recipe_type + " Recipe"
if "Recipes1M" in recipe_type:
recipe_type = "Recipes 1M Site"
st.markdown(
"<p style='font-size: 16px;'>Cuisine Source: <a href ='https://"
+ recipe_url
+ "' style='color: #64ABD8;'>"
+ recipe_type.title()
+ "</A><BR>Takes around "
+ str(recipe_preperation_time)
+ " mins to prepare<BR>",
unsafe_allow_html=True,
)
else:
# Display the recipe type, & the approximate preperation time
recipe_type = recipe_type + " Cuisine"
if len(recipe_type) > 19:
recipe_type = recipe_type[:15] + "..."
st.markdown(
"<p style='font-size: 16px;'>"
+ recipe_type.title()
+ f" • {str(recipe_preperation_time[1])} Calories<BR>Takes around "
+ str(recipe_preperation_time[0])
+ " mins to prepare<BR>",
unsafe_allow_html=True,
)
else:
if recipe_type == "Gathered" or recipe_type == "Recipes1M":
# Determine the type, based on the source of recipe's details
if "Gathered":
recipe_type = recipe_type + " Recipe"
if "Recipes1M" in recipe_type:
recipe_type = "Recipes 1M Site"
st.markdown(
"<p style='font-size: 16px;'>Cuisine Source: <a href ='https://"
+ recipe_url
+ "' style='color: #64ABD8;'>"
+ recipe_type.title()
+ "</A><BR>Takes over a "
+ str(recipe_preperation_time)
+ " mins to prepare<BR>",
unsafe_allow_html=True,
)
else:
# Display the recipe type, & the approximate preperation time
st.markdown(
"<p style='font-size: 16px;'>"
+ recipe_type.title()
+ "Cuisine<BR>Takes over a "
+ str(recipe_preperation_time)
+ " mins to prepare<BR>",
unsafe_allow_html=True,
)
if st.session_state.user_authentication_status is not True:
# Generate PDF file with necessary recipe details and usage terms
download_location_1 = pdf_utils.generate_recommendations_pdf(
recipe_name,
recipe_type,
recipe_url,
recipe_ingredients,
recipe_instructions,
)
# Display a download button only for the unauthenticated app user
st.download_button(
label="Download Recipe Details PDF",
data=open(download_location_1, "rb").read(),
key="download_location_1",
file_name=recipe_name.replace(" ", "_").lower() + ".pdf",
)
else:
# For authenticated user, send a mail with recipe details and PDF
if st.button(
"Send Recipe to Mail", key="button_1", use_container_width=True
):
try:
st.toast("Hold tight! Your recipe is taking flight.")
# Generate the PDF file with the necessary recipe details
download_location_1 = (
pdf_utils.generate_recommendations_pdf(
recipe_name,
recipe_type,
recipe_url,
recipe_ingredients,
recipe_instructions,
)
)
# Send the mail with attachment to the registered mail id
mail_utils.send_recipe_info_to_mail(
recipe_name,
recipe_ingredients,
recipe_instructions,
st.session_state.authenticated_user_email_id,
download_location_1,
)
# Display the information status upon successful delivery
st.toast("Bon appétit! We've delivered your recipe.")
except Exception as error:
# Display the information status upon successful delivery
st.toast("Whoops! Looks like your recipe ran into a snag.")
time.sleep(1)
st.toast("Please check your connectivity and try again.")
st.markdown("<BR>", unsafe_allow_html=True)
# Fetch details of the recommended recipe from the index location - 4
if use_large_model:
(
recipe_name,
recipe_type,
recipe_ingredients,
recipe_instructions,
recipe_preperation_time,
recipe_url,
) = feature_space_matching.lookup_recipe_details_by_index(
response.json(), 4, True
)
else:
(
recipe_name,
recipe_type,
recipe_ingredients,
recipe_instructions,
recipe_preperation_time,
recipe_url,
) = feature_space_matching.lookup_recipe_details_by_index(
recipe_data, recommended_recipes_indices[4]
)
# Attempt to generate image of the recipe, using Generative AI models
generated_image_path = genisys.generate_image(recipe_name, 225, 225)
if generated_image_path:
recipe_image = Image.open(generated_image_path)
else:
# Display a placeholder image if the image could not be generated
generated_image_path = (
resource_registry.placeholder_image_dir_path
+ "placeholder_5.png"
)
recipe_image = Image.open(generated_image_path).resize((225, 225))
st.image(recipe_image)
try:
recommended_recipes_images.append(
azure_storage_account.store_image_in_blob_container(
generated_image_path,