import gradio as gr import json from pydantic import BaseModel from pydantic import BaseModel from openai import OpenAI from typing import List import os API_KEY = os.getenv('api_key') client = OpenAI( api_key=API_KEY ) # Define the Pydantic models class Ingredient(BaseModel): """An ingredient for a recipe""" quantity: str unit: str name: str class Steps(BaseModel): """Steps to make a recipe""" stepNumber: int instruction: str class ProduceRecipe(BaseModel): """Makes a recipe for a meal""" mealName: str ingredients: list[Ingredient] steps : list[Steps] def generate_recipe(meal_name: str, calories: int, meal_time: str) -> ProduceRecipe: # This is where you'll implement your recipe generation logic # For now, we'll return a dummy recipe meal_template = f''' "role": "user", "content": "Create a recipe for a {meal_time} of {meal_name} with the following ingredients that is roughly {calories} calories." ''' completion = client.beta.chat.completions.parse( model="gpt-4o-2024-08-06", messages=[ {"role": "system", "content": "You are an expert chef and nutritionalist. You will be given a meal request and should convert it into a structured Recipe at the correct calories."}, {"role": "user", "content": meal_template} ], response_format=ProduceRecipe, ) recipe = completion.choices[0].message.parsed return recipe def format_recipe(recipe: ProduceRecipe) -> str: formatted = f"

{recipe.mealName}

\n\n" formatted += "

Ingredients:

\n\n\n" formatted += "

Instructions:

\n
    \n" for step in recipe.steps: formatted += f"
  1. {step.instruction}
  2. \n" formatted += "
" return formatted def recipe_interface(meal_name: str, calories: int, meal_time: str) -> str: recipe = generate_recipe(meal_name, calories, meal_time) return format_recipe(recipe) demo = gr.Interface( fn=recipe_interface, inputs=[ gr.Textbox(label="Meal Name"), gr.Number(label="Calories"), gr.Dropdown(["breakfast", "lunch", "dinner"], label="Meal Time") ], outputs=gr.HTML(label="Recipe"), title="Meal Recipe Generator", description="Generate a recipe based on meal name, calories, and meal time." ) demo.launch()