# pip install gradio openai python-dotenv import gradio as gr import openai import os from dotenv import load_dotenv # Load environment variables load_dotenv() # Set OpenAI API key openai.api_key = os.getenv("OPENAI_API_KEY") HEADER_IMAGE_PATH = "header.jpg" def compose_prompt(ingredients, complexity): """Composes the prompt for the OpenAI API.""" complexity_level = { 1: "very simple and quick", 2: "simple", 3: "moderate", 4: "complex", 5: "very complex and gourmet" }.get(complexity, "simple") prompt = f"""Task: Generate a recipe using the following ingredients with a {complexity_level} complexity level. Ingredients: {ingredients} The recipe should include: - Recipe title - Estimated prep and cook time (in minutes, total time <= 60 for complexity <= 2, <= 120 for complexity 5, using metric units) - List of ingredients with approximate amounts (using metric units) - Step-by-step cooking instructions (using degrees °C) - Optional tips or substitutions - Note about what to buy if something is missing Format the output as Markdown. """ return prompt def generate_recipe(ingredients, complexity): """Generates a recipe using the OpenAI API.""" if not ingredients: return "Please provide some ingredients." prompt = compose_prompt(ingredients, complexity) try: response = openai.chat.completions.create( model="gpt-4-turbo", # or "gpt-4-turbo" messages=[ {"role": "system", "content": "You are a helpful recipe generator."}, {"role": "user", "content": prompt} ], temperature=0.7, max_tokens=500, ) return response.choices[0].message.content except Exception as e: return f"An error occurred: {e}" with gr.Blocks(title="Recipe Generator") as demo: headline_html = f"""
Header

Recipe Generator

""" gr.HTML(headline_html) gr.Markdown("# Recipe Generator") gr.Markdown("Enter your ingredients and desired complexity to get a recipe.") with gr.Row(): ingredients_input = gr.Textbox( label="Ingredients", placeholder="chicken, rice, tomatoes, garlic", lines=3, interactive=True ) complexity_slider = gr.Slider( label="Complexity level", minimum=1, maximum=5, step=1, value=2, interactive=True ) generate_button = gr.Button("Generate recipe") recipe_output = gr.Markdown() generate_button.click( fn=generate_recipe, inputs=[ingredients_input, complexity_slider], outputs=recipe_output ) gr.Examples( examples=[ ["pasta, spinach, cheese, garlic", 3], ["salmon, asparagus, lemon", 2], ["beef, potatoes, carrots, onions", 4] ], inputs=[ingredients_input, complexity_slider] ) if __name__ == "__main__": demo.launch()