joethi commited on
Commit
e8ed882
·
1 Parent(s): b9172e4

creating app.py for the AIrecipeWizard project.

Browse files
Files changed (1) hide show
  1. app.py +99 -0
app.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from huggingface_hub import InferenceClient
2
+ from PIL import Image
3
+ import gradio as gr
4
+ import os
5
+ import json
6
+ # Function to generate recipe from ingredients
7
+ def generate_recipe(ingredients: str, model_name_recipe: str, token: str) -> str:
8
+ """
9
+ Generates a recipe based on input ingredients using an LLM.
10
+ Args:
11
+ ingredients (str): Ingredients input by the user.
12
+ model_name_recipe (str): Hugging Face model for text generation.
13
+ token (str): API token for Hugging Face authentication.
14
+ Returns:
15
+ str: Generated recipe text.
16
+ """
17
+ prompt = f"Generate a recipe using the following ingredients: {ingredients}. Write the recipe in detail along with a suitable title."
18
+ client = InferenceClient(model_name_recipe, token=token)
19
+ try:
20
+ response = client.post(
21
+ json={
22
+ "inputs": prompt,
23
+ "parameters": {"max_new_tokens": 500},
24
+ "task": "text-generation",
25
+ }
26
+ )
27
+ return json.loads(response.decode())[0]["generated_text"]
28
+ except Exception as e:
29
+ return f"Error generating recipe: {e}"
30
+ # Function to generate image of the recipe
31
+ def generate_image(recipe_title: str, model_name_image: str, token: str) -> Image.Image:
32
+ """
33
+ Generates an image based on the recipe title using a text-to-image model.
34
+ Args:
35
+ recipe_title (str): Title of the recipe to use as the prompt.
36
+ model_name_image (str): Hugging Face model for image generation.
37
+ token (str): API token for Hugging Face authentication.
38
+ Returns:
39
+ PIL.Image.Image: Generated image.
40
+ """
41
+ client = InferenceClient(model_name_image, token=token)
42
+ try:
43
+ prompt = f"A photo the dish: {recipe_title}, showing delicious presentation."
44
+ return client.text_to_image(prompt)
45
+ except Exception as e:
46
+ print(f"Error generating image: {e}")
47
+ return None
48
+ # Gradio function that combines both recipe generation and image generation
49
+ def generate_recipe_and_image(message: str, history):
50
+ token = os.getenv("API_Token_HF_AIrecipe") # Ensure your Hugging Face token is set in environment variables
51
+ model_name_recipe = "microsoft/Phi-3-mini-4k-instruct" # Replace with the LLM model of your choice
52
+ model_name_image = "prompthero/openjourney" # Replace with the image generation model of your choice
53
+
54
+ # Generate recipe
55
+ recipe_text = generate_recipe(message, model_name_recipe, token)
56
+ prompt_to_remove = f"Generate a recipe using the following ingredients: {message}. Write the recipe in detail along with a suitable title."
57
+ if prompt_to_remove in recipe_text:
58
+ recipe_text = recipe_text.replace(prompt_to_remove, "").strip()
59
+ # print("recipe_text:",recipe_text)
60
+ # Extract recipe title from generated recipe text
61
+ lines = recipe_text.split("\n")
62
+ for line in lines:
63
+ if line.lower().startswith("title:"): # Case-insensitive match
64
+ recipe_title = line.replace("Title:", "").strip() # Extract and clean title
65
+ break
66
+ print("recipe_title",recipe_title)
67
+ # Generate image for the recipe
68
+ recipe_image = generate_image(recipe_title, model_name_image, token)
69
+ image_path = "./recipe_image.png"
70
+ recipe_image.save(image_path, format="PNG")
71
+
72
+ # Combine text and image
73
+ return recipe_text, gr.Image(value=image_path)
74
+
75
+
76
+ if __name__ == "__main__":
77
+ # Gradio UI
78
+ with gr.Blocks(theme=gr.themes.Monochrome()) as demo:
79
+ gr_image = gr.Image(render=False)
80
+ with gr.Row():
81
+ with gr.Column(scale=4):
82
+ gr.Markdown("<center><h1>AI Recipe Chatbot</h1></center>")
83
+ chatbot = gr.ChatInterface(
84
+ generate_recipe_and_image,
85
+ examples=["chicken, rice, tomatoes, onions, spices", "oats, milk, fruits", "Noodles, Tofu, Soy sauce"],
86
+ type="messages",
87
+ additional_outputs=[gr_image]
88
+ )
89
+ with gr.Column(scale=1):
90
+ gr.Markdown("<center><h1>Recipe Image</h1></center>")
91
+ # recipe_image = gr.Image(label="Generated Recipe Image")
92
+ gr_image.render()
93
+ demo.launch()
94
+
95
+
96
+
97
+
98
+
99
+