File size: 4,788 Bytes
24708e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import openai
import os
from dotenv import load_dotenv
import logging

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Load environment variables
load_dotenv()

# Configure OpenAI
openai.api_key = os.getenv("OPENAI_API_KEY")
if not openai.api_key:
    raise ValueError("OPENAI_API_KEY environment variable is not set")

def generate_recipe(query, diet_preference=None, cuisine_type=None):
    """Generate a recipe with optional diet and cuisine preferences"""
    logger.info(f"Generating recipe for query: {query}, diet: {diet_preference}, cuisine: {cuisine_type}")
    
    if not query:
        raise ValueError("Recipe query is required")

    # Create a detailed prompt for the recipe
    prompt = f"""Create a detailed recipe for {query}"""
    if diet_preference:
        prompt += f" that is {diet_preference}"
    if cuisine_type:
        prompt += f" in {cuisine_type} style"
    
    prompt += """\n\nFormat the recipe in markdown with the following sections:
    1. Brief Description
    2. Ingredients (as a bulleted list)
    3. Instructions (as numbered steps)
    4. Tips (as a bulleted list)
    5. Nutritional Information (as a bulleted list)
    
    Use markdown formatting like:
    - Headers (###)
    - Bold text (**)
    - Lists (- and 1.)
    - Sections (>)
    """

    try:
        # Generate recipe text
        completion = openai.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": "You are a professional chef who provides detailed recipes with ingredients, instructions, nutritional information, and cooking tips. Format your responses in markdown."},
                {"role": "user", "content": prompt}
            ],
            temperature=0.7
        )
        recipe_text = completion.choices[0].message.content

        # Generate recipe image
        image_response = openai.images.generate(
            model="dall-e-3",
            prompt=f"Professional food photography of {query}, appetizing, high-quality, restaurant style",
            n=1,
            size="1024x1024"
        )
        image_url = image_response.data[0].url

        # Get learning resources (simplified version)
        learning_resources = [
            {
                "title": f"Master the Art of {query}",
                "url": f"https://cooking-school.example.com/learn/{query.lower().replace(' ', '-')}",
                "type": "video"
            },
            {
                "title": f"Tips and Tricks for Perfect {query}",
                "url": f"https://recipes.example.com/tips/{query.lower().replace(' ', '-')}",
                "type": "article"
            }
        ]

        return recipe_text, image_url, learning_resources

    except Exception as e:
        logger.error(f"Error generating recipe: {str(e)}")
        raise

def format_learning_resources(resources):
    """Format learning resources as a markdown list"""
    if not resources:
        return "No learning resources available."
    
    return "\n".join([f"- **{r['title']}** ({r['type']}): {r['url']}" for r in resources])

def recipe_generation_app():
    """Create Gradio interface for recipe generation"""
    # Inputs
    recipe_input = gr.Textbox(label="Recipe Query", placeholder="Enter a recipe name (e.g., chocolate chip cookies)")
    diet_input = gr.Dropdown(
        label="Diet Preference", 
        choices=["None", "Vegetarian", "Vegan", "Gluten-Free", "Keto"],
        value="None"
    )
    cuisine_input = gr.Dropdown(
        label="Cuisine Type", 
        choices=["None", "Italian", "Mexican", "Chinese", "Indian", "French"],
        value="None"
    )

    # Outputs
    recipe_output = gr.Markdown(label="Generated Recipe")
    image_output = gr.Image(label="Recipe Image")
    resources_output = gr.Markdown(label="Learning Resources")

    # Define the app interface
    demo = gr.Interface(
        fn=lambda query, diet, cuisine: (
            *generate_recipe(
                query, 
                diet if diet != "None" else None, 
                cuisine if cuisine != "None" else None
            )[:2],
            format_learning_resources(generate_recipe(
                query, 
                diet if diet != "None" else None, 
                cuisine if cuisine != "None" else None
            )[2])
        ),
        inputs=[recipe_input, diet_input, cuisine_input],
        outputs=[recipe_output, image_output, resources_output],
        title="🍳 AI Recipe Assistant",
        description="Generate delicious recipes with AI-powered suggestions!"
    )

    return demo

# Launch the Gradio app
if __name__ == "__main__":
    app = recipe_generation_app()
    app.launch(share=True)