BhavaishKumar112 commited on
Commit
a581271
·
verified ·
1 Parent(s): c8d823f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -107
app.py CHANGED
@@ -1,124 +1,98 @@
1
  import json
2
  import gradio as gr
 
3
  from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
 
4
  from format.format_output import format_output
 
5
  from device.get_device_id import get_device_id
6
 
 
7
  tokenizer = AutoTokenizer.from_pretrained("Ashikan/dut-recipe-generator")
8
  model = AutoModelForCausalLM.from_pretrained("Ashikan/dut-recipe-generator")
9
  pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, device=get_device_id())
10
 
 
11
  def perform_model_inference(ingredients_list=None, recipe_name=None):
12
- try:
13
- if ingredients_list:
14
- for ingredient_index in range(len(ingredients_list)):
15
- ingredients_list[ingredient_index] = ingredients_list[ingredient_index].strip()
16
-
17
- # Create a simple prompt for generating a recipe from ingredients
18
- input_text = "Generate a recipe with these ingredients: " + ", ".join(ingredients_list)
19
- elif recipe_name:
20
- # Simple prompt for generating ingredients and method from recipe name
21
- input_text = "Generate ingredients and cooking method for the recipe: " + recipe_name
22
- else:
23
- return "Invalid input"
24
-
25
- # Limit the length of the input text to avoid long processing times
26
- input_text = input_text[:512] # Truncate if it's too long
27
-
28
- # Generate output with a higher temperature for quicker responses
29
- output = pipe(input_text, max_length=512, temperature=0.7, do_sample=True, truncation=True)[0]["generated_text"]
30
-
31
- return format_output(output)
32
 
33
- except Exception as e:
34
- return f"Error occurred: {str(e)}"
35
-
36
- def chat_function(history, user_input, mode):
37
- # If mode is "ingredients", process as ingredient list
38
- if mode == "ingredients":
39
- ingredients_list = user_input.lower().split(',')
40
-
41
- # Validate the ingredients
42
- if len(ingredients_list) < 2:
43
- error_text = "Please provide at least 2 ingredients, separated by commas."
44
- history.append((user_input, error_text))
45
- return history, ""
46
-
47
- # Generate the recipe
48
- history.append((user_input, "Generating recipe..."))
49
- recipe = perform_model_inference(ingredients_list=ingredients_list)
50
- history[-1] = (user_input, recipe) # Replace the "Generating recipe..." message with the result
51
- return history, ""
52
-
53
- # If mode is "recipe", process as recipe name
54
- elif mode == "recipe":
55
- recipe_name = user_input.strip()
56
-
57
- # Validate the recipe name
58
- if not recipe_name:
59
- error_text = "Please provide a valid recipe name."
60
- history.append((user_input, error_text))
61
- return history, ""
62
-
63
- # Generate ingredients and method
64
- history.append((user_input, "Generating ingredients and method..."))
65
- recipe_details = perform_model_inference(recipe_name=recipe_name)
66
- history[-1] = (user_input, recipe_details) # Replace the "Generating ingredients..." message with the result
67
- return history, ""
68
-
69
- # Define the Gradio interface
70
- with gr.Blocks(css="""
71
- #chatbot-container {
72
- background-color: #f7f7f8;
73
- border-radius: 10px;
74
- padding: 10px;
75
- max-width: 800px;
76
- margin: auto;
77
- box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
78
- }
79
- .chat-message {
80
- border-radius: 8px;
81
- padding: 10px;
82
- margin-bottom: 10px;
83
- font-family: Arial, sans-serif;
84
- }
85
- .user-message {
86
- background-color: #e6f7ff;
87
- text-align: left;
88
- }
89
- .bot-message {
90
- background-color: #f0f0f0;
91
- text-align: left;
92
- }
93
- #chatbot-container .user-message {
94
- color: #0073e6;
95
- }
96
- #chatbot-container .bot-message {
97
- color: #333;
98
- }
99
- .gr-button {
100
- background-color: #0073e6 !important;
101
- color: white !important;
102
- border: none !important;
103
- border-radius: 5px !important;
104
- }
105
- """) as recipegen:
106
- gr.Markdown("# Recipe Generator")
107
- gr.Markdown("An AI model attempting to produce healthier, diabetic-friendly recipes. Start by entering ingredients or a recipe name.")
108
-
109
- chatbot = gr.Chatbot(elem_id="chatbot-container")
110
- user_input = gr.Textbox(placeholder="Enter ingredients or recipe name", label="Your Input")
111
 
112
- # Dropdown for selecting input mode (ingredients or recipe name)
113
- mode_selector = gr.Dropdown(
114
- choices=["ingredients", "recipe"],
115
- label="Select Input Mode",
116
- value="ingredients"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  )
118
 
119
- submit_button = gr.Button("Generate")
120
-
121
- # Link the chatbot and input to the chat function
122
- submit_button.click(chat_function, inputs=[chatbot, user_input, mode_selector], outputs=[chatbot, user_input])
 
123
 
124
  recipegen.launch(share=True)
 
1
  import json
2
  import gradio as gr
3
+ import spaces
4
  from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
5
+
6
  from format.format_output import format_output
7
+ from validate.validate_ingredients import validate_ingredients
8
  from device.get_device_id import get_device_id
9
 
10
+ # Load the model and tokenizer
11
  tokenizer = AutoTokenizer.from_pretrained("Ashikan/dut-recipe-generator")
12
  model = AutoModelForCausalLM.from_pretrained("Ashikan/dut-recipe-generator")
13
  pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, device=get_device_id())
14
 
15
+ @spaces.GPU
16
  def perform_model_inference(ingredients_list=None, recipe_name=None):
17
+ # If ingredients are provided
18
+ if ingredients_list:
19
+ for ingredient_index in range(len(ingredients_list)):
20
+ ingredients_list[ingredient_index] = ingredients_list[ingredient_index].strip()
21
+ input_text = '{"prompt": ' + json.dumps(ingredients_list)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
+ # If recipe name is provided
24
+ elif recipe_name:
25
+ input_text = "Generate ingredients and cooking method for the recipe: " + recipe_name
26
+ else:
27
+ return "Invalid input"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
+ # Generate output from the model
30
+ output = pipe(input_text, max_length=1024, temperature=0.1, do_sample=True, truncation=True)[0]["generated_text"]
31
+ return format_output(output)
32
+
33
+ def generate_recipe(ingredients=None, recipe_name=None):
34
+ # If ingredients are provided
35
+ if ingredients:
36
+ ingredients_list = ingredients.lower().split(',')
37
+ is_ingredients_valid = validate_ingredients(ingredients_list)
38
+
39
+ if is_ingredients_valid:
40
+ generated_text = perform_model_inference(ingredients_list=ingredients_list)
41
+ return {
42
+ generated_recipe: gr.Markdown(value=generated_text, label="Generated Recipe",
43
+ elem_id="recipe-container", visible=True)
44
+ }
45
+ else:
46
+ error_text = "## Invalid ingredients. Please include at least 2 ingredients in a comma-separated list. e.g. brown rice, onions, garlic"
47
+ return {
48
+ generated_recipe: gr.Markdown(value=error_text, elem_id="recipe-container", visible=True)
49
+ }
50
+
51
+ # If recipe name is provided
52
+ if recipe_name:
53
+ generated_text = perform_model_inference(recipe_name=recipe_name)
54
+ return {
55
+ generated_recipe: gr.Markdown(value=generated_text, label="Generated Recipe",
56
+ elem_id="recipe-container", visible=True)
57
+ }
58
+
59
+ return {
60
+ generated_recipe: gr.Markdown(value="## Please enter either ingredients or a recipe name.",
61
+ elem_id="recipe-container", visible=True)
62
+ }
63
+
64
+ # Gradio Interface
65
+ with gr.Blocks(css="./css/styles.css") as recipegen:
66
+ gr.Image("./assets/dut.png", interactive=False, show_share_button=False, show_download_button=False,
67
+ show_fullscreen_button=False, show_label=False, elem_id="dut-logo", height=256)
68
+ gr.Markdown("# Recipe Generator", elem_id="header")
69
+ gr.Markdown("### An AI Model Attempting To Produce Healthier, Diabetic-Friendly Recipes",
70
+ elem_id="header-sub-heading")
71
+ gr.Markdown("Start by entering a comma-separated list of ingredients or a recipe name below.", elem_id="header-instructions")
72
+
73
+ with gr.Column() as column:
74
+ user_ingredients = gr.Textbox(label="Ingredients", placeholder="e.g. chicken, onion, garlic", autofocus=True, max_lines=1, elem_id="ingredients-input")
75
+ user_recipe_name = gr.Textbox(label="Recipe Name", placeholder="e.g. Chicken Biryani", max_lines=1, elem_id="recipe-name-input")
76
+ generate_button = gr.Button(value="Generate")
77
+
78
+ with gr.Column():
79
+ generated_recipe = gr.Markdown(visible=True)
80
+
81
+ examples = gr.Examples(
82
+ elem_id="examples",
83
+ examples=[
84
+ "sweet potato, mushrooms, cheese, garlic",
85
+ "chicken breast, chili, onion, tomato, parmesan cheese",
86
+ "strawberries, vanilla, honey, rolled oats, almonds, butter",
87
+ "hake, spring onion, lemon"
88
+ ],
89
+ inputs=[user_ingredients]
90
  )
91
 
92
+ generate_button.click(
93
+ fn=generate_recipe,
94
+ inputs=[user_ingredients, user_recipe_name],
95
+ outputs=[generated_recipe]
96
+ )
97
 
98
  recipegen.launch(share=True)