import openai import requests from io import BytesIO import gradio as gr openai.api_key = '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' def generate_image(prompt): # Use GPT-3 to generate a description of the image model_engine = "text-davinci-002" description = openai.Completion.create( engine=model_engine, prompt=f"Generate an image of {prompt}", max_tokens=256, n=1, stop=None, temperature=0.5 ).choices[0].text.strip() # Use DALL-E to generate an image based on the description response = requests.post( "https://api.openai.com/v1/images/generations", headers={ "Content-Type": "application/json", "Authorization": f"Bearer {openai.api_key}" }, json={ "model": "image-alpha-001", "prompt": description, "num_images": 1, "size": "1024x1024", "response_format": "url" } ) # Parse the image URL from the API response and return the image image_url = response.json()["data"][0]["url"] response = requests.get(image_url) image = BytesIO(response.content) return image iface = gr.Interface( fn=generate_image, inputs="text", outputs="image", title="Text to Image Generator", description="Enter a prompt to generate an image", examples=[ ["a red apple on a white background"], ["a yellow sun setting over a mountain range"], ["a futuristic cityscape at night"] ] ) iface.launch()