-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRecipe_Generation.py
1466 lines (1197 loc) · 61.3 KB
/
Recipe_Generation.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
# Author: Ashwin Raj <[email protected]>
# License: GNU Affero General Public License v3.0
# Discussions-to: github.com/thisisashwinraj/RecipeML-Recipe-Recommendation
# Copyright (C) 2023 Ashwin Raj
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
This module contains the top-level environment for RecipeML streamlit application.
It contains method for initializing the recipe generation model, managing session,
and displaying the frontend. This module uses RESTful APIs for Gen AI inferencing.
The front-end of the web application is developed using streamlit and css and the
backend uses Python3. The supporting modules and the related resources are stored
in the repective directories of the repository. API keys are maintained as secret.
Module Functions:
[1] apply_style_to_sidebar_button
[2] set_generate_recommendations_cache_to_true
[3] set_generate_recommendations_cache_to_false
APIs Used:
[1] PaLM API (Google)
[2] DALL.E2 API (OpenAI)
.. versionadded:: 1.0.0
.. versionupdated:: 1.3.0
Learn about RecipeML :ref:`RecipeML v1: User Interface and Functionality Overview`
"""
import re
import uuid
import random
import requests
import time
from PIL import Image
import base64
import joblib
import pandas as pd
from gtts import gTTS
from deep_translator import GoogleTranslator
import streamlit as st
import streamlit_antd_components as sac
import firebase_admin
from firebase_admin import auth, credentials
from cognitive_flux.recipe_generation import ProceduralTextGeneration
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
from deep_canvas.image_generation import GenerativeImageSynthesis
# Set the page title and favicon to be displayed on the streamlit web application
st.set_page_config(
page_title="RecipeML: Recipe Generation",
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 "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"
if st.session_state.themes["refreshed"] == False:
st.session_state.themes["refreshed"] = True
st.rerun()
if __name__ == "__main__":
# [Recipe Generation](Page 1/2) - The frontend of the streamlit web application
# Function to display RecipeML's home screen, with various interactive elements.
# The homepage incorporates a dropdown widget on the sidebar that sets paradigm
# for recipe generation. Users query is read and then subsequently utilized for
# executing multiple task including recipe generation & recipe image generation
# This web application utilizes the OpenAI API & RunwayMLs Stable Diffusion for
# image generation. The model binaries are maintained as GitHubs release assets.
# .. versionadded:: 1.1.0
# APIs: OpenAI API (Image: DALL.E2) & Google Pathways Language Model (PaLM API)
# Dependencies: NLTK, Torch, Diffusers, SkLearn, Pandas, Joblib, Streamlit, PIL
# NOTE: The API keys used in this module are maintained using streamlit secrets.
# When testing locally replace the API keys from ~./streamlit/secrets.toml file.
with st.sidebar:
selected_menu_item = sac.menu(
[
sac.MenuItem(
"Recipe Generation",
icon="stars",
),
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 == "Recipe Generation":
try:
firebase_credentials = FirebaseCredentials()
firebase_credentials.fetch_firebase_service_credentials(
"configurations/recipeml_firebase_secrets.json"
)
firebase_credentials = credentials.Certificate(
"configurations/recipeml_firebase_secrets.json"
)
firebase_admin.initialize_app(firebase_credentials)
except Exception as err:
pass
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()
# Fetch the 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()
cola, colb = st.sidebar.columns([2.5, 1])
with cola:
# Display selectbox for users to select RecipeML's recipe generation paradigm
recipe_generation_type = st.selectbox(
"Select Generation Technique",
("Generate by Name", "Generate by Ingredients"),
)
with colb:
selected_language = st.selectbox(
" ",
["en", "hi", "ml", "ta", "fr", "ru", "de", "ja", "ko"],
help="Select language",
)
# Check if the recipe generation's selectbox is set to Generate by Ingredient
if recipe_generation_type == "Generate by Ingredients":
# Load the ingredients list from the resource registry into the selectbox
with open(
resource_registry.ingredients_list_path, "rb"
) as recipe_nlg_ingredients:
ingredients_list = joblib.load(recipe_nlg_ingredients)
# Display sidebar with selectbox for a user to select the ingredients
input_selected_ingredients = st.sidebar.selectbox(
"Select a start ingredient",
ingredients_list,
index=None,
placeholder="Pick from over 10,000+ ingredients",
)
if input_selected_ingredients:
# Display the preloader, as the web app 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,
)
try:
with gif_image:
st.toast("Cooking up some tasty ideas") # Show notifications
# Attempt to generate a recipe using ProceduralTextGeneration
procedural_text_generation = ProceduralTextGeneration(
stochasticity=0.3,
max_token_length=1500,
palm_api_key=auth_token.palm_api_key,
)
# Fetch various recipe details using ProceduralTextGeneration
(
recipe_title,
recipe_ingredients,
recipe_instructions,
preperation_time_in_mins,
serving_size,
recipe_description,
calories_in_recipe,
) = procedural_text_generation.generate_recipe(
input_selected_ingredients, generate_recipe_by_name=False
)
flag_display_result = True
except Exception as error:
# Handle exception, display warning and wait for clearing warning
try:
gif_image.empty()
st.sidebar.exception(error)
except Exception as error:
st.sidebar.exception(error)
try:
if st.session_state.themes["current_theme"] == "dark":
exception_preloader = "assets/loading/exception_img.gif"
else:
exception_preloader = (
"assets/loading/exception_img_light.gif"
)
with open(exception_preloader, "rb") as f:
image_data = f.read()
encoded_image = base64.b64encode(image_data).decode()
# Display exception preloader if the app encounters any error
display_exception_preloader = st.markdown(
f'<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,
)
time.sleep(15) # Hold execution before clearing the warnings
display_exception_preloader.empty()
except:
flag_exception_raised = st.warning(
"Whoops! Looks like your recipe ran into a snag. Try again [Error Code: 201]"
)
st.sidebar.exception(error)
time.sleep(10) # Hold execution before clearing the warnings
flag_exception_raised.empty()
flag_display_result = False
else:
flag_display_result = False
# Check if the recipe generations selectbox is set to Generate by Recipe Name
elif recipe_generation_type == "Generate by Name":
# Display sidebar with text input for the user to enter a recipe name
input_recipe_name = st.sidebar.text_input(
"Enter Recipe Name:",
placeholder="Be playful, descriptive, or even a little poetic",
)
# Check if some recipe name is provided by the user, initialized on enter
if input_recipe_name:
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,
)
try:
# Display the preloader, as the app performs time intensive tasks
with gif_image:
st.toast("Cooking up some tasty ideas")
# Attempt to generate a recipe using ProceduralTextGeneration
procedural_text_generation = ProceduralTextGeneration(
stochasticity=0.7,
max_token_length=1500,
palm_api_key=auth_token.palm_api_key,
)
(
recipe_title,
recipe_ingredients,
recipe_instructions,
preperation_time_in_mins,
serving_size,
recipe_description,
calories_in_recipe,
) = procedural_text_generation.generate_recipe(
input_recipe_name, generate_recipe_by_name=True
)
flag_display_result = True
except Exception as err:
# Handle exception, display warning and wait for clearing warning
try:
gif_image.empty()
except:
pass
try:
if st.session_state.themes["current_theme"] == "dark":
exception_preloader = "assets/loading/exception_img.gif"
else:
exception_preloader = (
"assets/loading/exception_img_light.gif"
)
with open(exception_preloader, "rb") as f:
image_data = f.read()
encoded_image = base64.b64encode(image_data).decode()
# Display exception preloader if the app encounters any error
display_exception_preloader = st.markdown(
f'<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,
)
time.sleep(15) # Hold execution before clearing the warnings
display_exception_preloader.empty()
except:
flag_exception_raised = st.warning(
"Whoops! Looks like your recipe ran into a snag. Try again [Error Code: 202]"
)
# st.sidebar.exception(error)
time.sleep(10) # Hold execution before clearing the warnings
flag_exception_raised.empty()
flag_display_result = False
else:
flag_display_result = False
else:
# Handle unknown exception, display warning and wait for clearing warning
try:
if st.session_state.themes["current_theme"] == "dark":
exception_preloader = "assets/loading/exception_img.gif"
else:
exception_preloader = "assets/loading/exception_img_light.gif"
with open(exception_preloader, "rb") as f:
image_data = f.read()
encoded_image = base64.b64encode(image_data).decode()
# Display exception preloader if the streamlt app encounter any error
display_exception_preloader = st.markdown(
f'<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,
)
time.sleep(15) # Hold execution for 15s before clearing the warnings
display_exception_preloader.empty()
except:
flag_exception_raised = st.warning(
"Whoops! Looks like your recipe ran into a snag. Try again [Error Code: 203]"
)
# st.sidebar.exception(error)
time.sleep(10) # Hold execution for 10s before clearing the warnings
flag_exception_raised.empty()
flag_display_result = False
if flag_display_result: # Check if any result has been generated, to display
# Remove extra paddings from the top and bottom margin of block container
st.markdown(
"""
<style>
.block-container {
padding-top: 0rem;
padding-bottom: -0.5rem;
}
</style>
""",
unsafe_allow_html=True,
)
with gif_image:
# Display the preloader, as the web app performs time intensive tasks
st.toast("Warming up the digital oven")
# Initialize the GenerativeImageSynthesis mode,l for image generation
genisys_std_model = GenerativeImageSynthesis(
image_quality="standard", enable_gpu_acceleration=False
)
# Generate the primary and secondary images based on the recipe title
generated_primary_image_path = genisys_std_model.generate_image(
recipe_title, 424, 322
)
st.toast("Applying some final touches")
generated_secondary_image_path = genisys_std_model.generate_image(
recipe_title, 284, 322
)
recipe_id = str(uuid.uuid4())[:8]
try:
azure_storage_account = AzureStorageAccount(
"generated-recipe-images"
)
blob_url_primary_image = (
azure_storage_account.store_image_in_blob_container(
generated_primary_image_path, recipe_id + "_primary.png"
)
)
blob_url_secondary_image = (
azure_storage_account.store_image_in_blob_container(
generated_secondary_image_path, recipe_id + "_secondary.png"
)
)
except Exception as error:
blob_url_primary_image = "unavailable"
blob_url_secondary_image = "unavailable"
try:
audio_prompt = f"Hello and welcome to RecipeML! You are listening to the recipe for preparing {recipe_title}. This recipe takes approximately {preperation_time_in_mins} minutes to cook and can be served to {serving_size} people. Before jumping right in, please be advised that recipes generated by RecipeML are intended for creative exploration only. The results may not always be safe, accurate, or edible. You may use it to spark inspiration, but always consult trusted sources for reliable cooking information. For preparing this recipe, you will need {recipe_ingredients}. Now, here's how we'll make magic happen, {recipe_instructions}. Congratulations, chef! Your feast is ready. Grab your utensils, gather your guests, and savor every bite of this delectable dish. Bon appétit!"
try:
if selected_language != "en":
audio_prompt = GoogleTranslator(
source="auto", target=selected_language
).translate(audio_prompt)
except Exception as error:
pass
tts = gTTS(text=audio_prompt, lang="en", tld="co.in")
recipe_audio_name = (
recipe_title.replace("/", "").replace(" ", "_").lower()
+ "_audio.wav"
)
audio_path = f"exports/generated_aud/{recipe_audio_name}"
tts.save(audio_path)
except Exception as error:
pass
gif_image.empty() # Show notification message, & clear the preloader
try:
if selected_language != "en":
recipe_title = GoogleTranslator(
source="auto", target=selected_language
).translate(recipe_title)
except Exception as error:
pass
# Display title on the web app's frontend and show the interactive button
st.markdown(f"<H2>{recipe_title}</H2>", unsafe_allow_html=True)
seprating_spaces = "      "
serving_size_content = f"Serving for {serving_size}"
calories_in_recipe_content = f"{calories_in_recipe} Calories"
preparation_time_content = (
f"Requires {preperation_time_in_mins} minutes to prepare"
)
try:
if selected_language != "en":
serving_size_content = GoogleTranslator(
source="auto", target=selected_language
).translate(serving_size_content)
calories_in_recipe_content = GoogleTranslator(
source="auto", target=selected_language
).translate(calories_in_recipe_content)
preparation_time_content = GoogleTranslator(
source="auto", target=selected_language
).translate(preparation_time_content)
except Exception as error:
st.write(error)
st.markdown(
"<h5>🍜 "
+ serving_size_content
+ seprating_spaces
+ "🔥 "
+ calories_in_recipe_content
+ seprating_spaces
+ "🕓 "
+ preparation_time_content
+ "</h5><br>",
unsafe_allow_html=True,
)
primary_image, secondary_image = st.columns([1.48, 1])
# Display the primary and the secondary recipe image on the apps frontend
with primary_image:
if generated_primary_image_path:
recipe_image_424x322 = Image.open(
generated_primary_image_path
).resize((424, 322))
else:
# Use the placeholder image if the primary image is not generated
placeholder_image_path = (
resource_registry.placeholder_image_dir_path
+ "placeholder_1.png"
)
recipe_image_424x322 = Image.open(placeholder_image_path).resize(
(424, 322)
)
st.image(recipe_image_424x322) # Display the primary image, to users
with secondary_image:
if generated_secondary_image_path:
recipe_image_424x322 = Image.open(
generated_secondary_image_path
).resize((284, 322))
else:
# Use a placeholder image if the secondary image is not generated
placeholder_image_path = (
resource_registry.placeholder_image_dir_path
+ "placeholder_2.png"
)
recipe_image_424x322 = Image.open(placeholder_image_path).resize(
(284, 322)
)
st.image(recipe_image_424x322)
# Display the description of the generated recipe & the recipe ingredient
try:
if selected_language != "en":
recipe_description = GoogleTranslator(
source="auto", target=selected_language
).translate(recipe_description)
except Exception as error:
pass
st.markdown(
f"<p align='justify'>{recipe_description}</p>", unsafe_allow_html=True
)
ingredients_title = "Ingredients"
try:
if selected_language != "en":
ingredients_title = GoogleTranslator(
source="auto", target=selected_language
).translate(ingredients_title)
except Exception as error:
pass
st.markdown("<H3>" + ingredients_title + "</H3>", unsafe_allow_html=True)
recipe_ingredients = ", ".join(recipe_ingredients) # Display ingredients
try:
if selected_language != "en":
recipe_ingredients = GoogleTranslator(
source="auto", target=selected_language
).translate(recipe_ingredients)
except Exception as error:
pass
st.markdown(
f"<p align='justify'>{recipe_ingredients}</p>", unsafe_allow_html=True
)
# Display a cautionary message to the user, about using generated recipes
usage_caution_message = """
**Enjoy the wordplay, but cook with caution!**
Recipes generated by RecipeML are intended for creative exploration only! The results may'nt always be safe, accurate, or edible! You may use it to spark inspiration but always consult trusted sources for reliable cooking information. For more information on safe cooking practices, kindly visit USDAs [FSIS](https://www.fsis.usda.gov/wps/portal/fsis/topics/food-safety-education)
"""
st.info(usage_caution_message)
# Display the recipe direction heading and the cleaned recipe instruction
directions_heading = "Recipe Directions"
try:
if selected_language != "en":
directions_heading = GoogleTranslator(
source="auto", target=selected_language
).translate(directions_heading)
except Exception as error:
pass
st.markdown("<H3>" + directions_heading + "</H3>", unsafe_allow_html=True)
try:
if selected_language != "en":
recipe_instructions = GoogleTranslator(
source="auto", target=selected_language
).translate(recipe_instructions)
except Exception as error:
pass
st.markdown(
f"<p align='justify'>{recipe_instructions}</p>", unsafe_allow_html=True
)
st.markdown("<BR><BR>", unsafe_allow_html=True)
st.sidebar.markdown("<BR><BR><BR><BR><BR><BR>", unsafe_allow_html=True)
st.sidebar.audio(audio_path, format="audio/wav")
try:
mongo = MongoDB()
if st.session_state.authenticated_user_username is not None:
username = st.session_state.authenticated_user_username
else:
username = "guest_user"
if recipe_generation_type == "Generate by Ingredients":
input_query = input_selected_ingredients
else:
input_query = input_recipe_name
mongo.store_generated_recipes(
username,
recipe_generation_type,
input_query,
selected_language,
recipe_id,
recipe_title,
recipe_ingredients,
recipe_instructions,
serving_size,
preperation_time_in_mins,
calories_in_recipe,
blob_url_primary_image,
blob_url_secondary_image,
)
except Exception as error:
st.exception(error)
else:
try:
# Load & display animated GIF for visual appeal, when not inferencing
if st.session_state.themes["current_theme"] == "dark":
loading_gif = "intro_dotwave_img.gif"
else: loading_gif = "intro_dotwave_img_light.gif"
dotwave_image_path = (
resource_registry.loading_assets_dir + "dotwave_intro_img.gif"
)
with open(dotwave_image_path, "rb") as f:
image_data = f.read()
encoded_image = base64.b64encode(image_data).decode()
# Display base64 encoded image with rounded edge without expander
gif_image = st.markdown(
f'<br><br><div class="rounded-image"><img src="data:image/png;base64,{encoded_image}"></div>',
unsafe_allow_html=True,
)
except Exception as error:
pass
# Display a welcoming message to user with a randomly chosen recipe emoji
cuisines_emojis = [
"🍜",
"🍩",
"🍚",
"🍝",
"🍦",
"🍣",
]
cola, colb = st.columns([11.5, 1])
with cola:
if st.session_state.user_display_name is not None:
user_first_name = st.session_state.user_display_name.split()[0]
try:
st.markdown(
f"<H1>Welcome {user_first_name} {random.choice(cuisines_emojis)}</H1>",
unsafe_allow_html=True,
)
except:
st.markdown(
f"<H1>Hello there {random.choice(cuisines_emojis)}</H1>",
unsafe_allow_html=True,
)
else:
st.markdown(
f"<H1>Hello there {random.choice(cuisines_emojis)}</H1>",
unsafe_allow_html=True,
)
with colb:
st.markdown("<br>", unsafe_allow_html=True)
btn_face = (
st.session_state.themes["light"]["button_face"]
if st.session_state.themes["current_theme"] == "light"
else st.session_state.themes["dark"]["button_face"]
)
st.button(
btn_face,
use_container_width=True,
type="secondary",
on_click=change_streamlit_theme,
)
# Provide a brief description of RecipeMLs recipe generation capabilities
subheading_font_color = {"dark": "#C2C2C2", "light": "#424242"}
font_color = subheading_font_color[st.session_state.themes["current_theme"]]
st.markdown(
f"<H4 style='color: {font_color}'>Start by describing what you are craving, or what you have on hand!</H4>",
unsafe_allow_html=True,
)
st.markdown(
"<P align='justify'>Dreaming of a dish but dont have recipe? Or maybe you've got an ingredient begging to be transformed? Simply describe what you want and RecipeML will generate a mouthwatering recipe that is uniquely yours</P>",
unsafe_allow_html=True,
)
# Display usage instructions in an informative box for easy understanding
usage_instruction = """
**Here's how you can get started:**
**1. Whisper your wish**: Enter the recipes name or a starting ingredient to get started with your journey
**2. Discover inspirations**: Explore new recipes, from tried-and-true classics to some unexpected twists
**3. Save your favourite recipes**: Download the PDF documents, or send'em to your registered email id
"""
st.info(usage_instruction) # Display the usage information, to the users
if selected_menu_item == "Discover RecipeML":
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
def _valid_name(fullname):
# Validate the basic structure, and logical name based character restrictions
if not re.match(r"^[A-Z][a-z]+( [A-Z][a-z]+)*$", fullname):
return False
return (
True # Name is considered to be valid, only if all conditions are met
)
def _valid_username(username):
# Check for the minimum and maximum length of the password (i.e 4 characters)
if len(username) < 4:
return False, "MINIMUM_LENGTH_UID"
if len(username) > 25:
return False, "MAXIMUM_LENGTH_UID"
# Check for only the allowed characters: letters, numbers, underscores & dots
allowed_chars = set(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_."
)
if not all(char in allowed_chars for char in username):
return False, "INVALID_CHARACTERS"
# Check if username start with letter. Symbols & digits must not be the first
if not username[0].isalpha():
return False, "START_WITH_LETTERS"
return (
True,
"USERNAME_VALID",
) # Username is valid, if all conditions are met
def _valid_email_address(email):
# Define the regular expression for validating the e-mail address of the user
email_regex = r"^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
# Returns a boolean value indicating whether the mail address is valid or not
return re.match(email_regex, email) is not None
def signup_form():
if st.session_state.user_authentication_status is None:
with st.form("register_new_user_form"):
st.markdown(
'<H3 id="anchor-create-user">Register Now to Create an Account</H3>',
unsafe_allow_html=True,
)
subheading_font_color = {"dark": "#E2E2E2", "light": "#111111"}
font_color = subheading_font_color[
st.session_state.themes["current_theme"]
]
st.markdown(
f"<p align='justify' style='color: {font_color};'>Level up your recipe game! Get personalized recipe recommendations, create custom meal plans and more. Signup for your free RecipeML account today! Already have a account? LogIn now to get started</p>",
unsafe_allow_html=True,
)
signup_form_section_1, signup_form_section_2 = st.columns(2)
with signup_form_section_1:
name = st.text_input(
"Enter your Full Name:",
)
email = st.text_input(
"Enter your E-Mail Id:",
)
with signup_form_section_2:
username = st.text_input(
"Enter your Username:",
placeholder="Allowed characters: A-Z, 0-9, . & _",
)
phone_number = st.text_input(
"Enter Phone Number:",
placeholder="Include your Country Code (eg: +91)",
)
password = st.text_input(
"Enter your Password:",
type="password",
)
accept_terms_and_conditions = st.checkbox(
"By creating an account, you confirm your acceptance to our Terms of Use and the Privacy Policy"
)
button_section_1, button_section_2, button_section_3 = st.columns(3)
with button_section_1:
submitted = st.form_submit_button(
"Register Now", use_container_width=True
)
if submitted:
try:
if not name:
st.toast("Please enter your full name")
elif not _valid_name(name):
st.toast("Not quite! Double-check your full name.")
elif not _valid_username(username)[0]:
validation_error_message = _valid_username(username)[1]
if validation_error_message is "MINIMUM_LENGTH_UID":
st.toast("Username too short! Needs 4+ letters.")
elif validation_error_message is "MAXIMUM_LENGTH_UID":
st.toast("Username too long! Max 25 letters.")
elif validation_error_message is "INVALID_CHARACTERS":
st.toast("Username contains invalid charecters!")
time.sleep(1.5)
st.toast(
"Try again with valid chars (a-z, 0-9, ._)"
)
elif validation_error_message is "START_WITH_LETTERS":
st.toast("Start your username with a letter.")
else:
st.toast("Invalid Username! Try again.")
elif not _valid_email_address(email):
st.toast("Invalid email format. Please try again.")
elif len(password) < 8:
st.toast("Password too short! Needs 8+ characters.")
elif not accept_terms_and_conditions:
st.toast("Please accept our terms of use")
else:
firebase_admin.auth.create_user(
uid=username.lower(),
display_name=name,
email=email,
phone_number=phone_number,
password=password,
)
st.toast("Welcome to RecipeML!")
alert_successful_account_creation = st.success(
"Your Account has been created successfully"
)
time.sleep(2)
st.toast("Please login to access your account.")
time.sleep(3)
alert_successful_account_creation.empty()
except Exception as error:
if "Invalid phone number" in str(error):
st.toast("Invalid phone number format.")
time.sleep(1.5)
st.toast("Please check country code and + prefix.")
elif "PHONE_NUMBER_EXISTS" in str(error):