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)