Spaces:
Runtime error
Runtime error
File size: 2,445 Bytes
19f1bca fb0d710 19f1bca fb0d710 5552af2 fb0d710 19f1bca fb0d710 061d23b fb0d710 87da903 fb0d710 1d11853 fb0d710 aa9f188 fb0d710 6f65233 fb0d710 178723a fb0d710 |
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 |
import gradio as gr
import openai
import requests
from PIL import Image
from io import BytesIO
import textwrap
def create_dalle_prompts(story_title, paragraph):
return f"Illustration of '{story_title}' - {textwrap.shorten(paragraph, width=50)}"
def generate_image(api_key, prompt):
openai.api_key = api_key
response = openai.Image.create(
prompt=prompt,
n=1,
size="1024x1024"
)
image_url = response['data'][0]['url']
response = requests.get(image_url)
image = Image.open(BytesIO(response.content))
return image
def generate_story_and_images(name, story_title, story_type, api_key):
openai.api_key = api_key
if story_type == "for children":
prompt_content = f"In a mystical kingdom, a brave adventurer named {name} discovers a magical object. Narrate their whimsical and heartwarming tale based on the title: '{story_title}'."
else:
prompt_content = f"In an odd city, {name} stumbles upon a series of bizarre events linked to the title '{story_title}'. Describe their hilariously absurd adventure."
messages = [
{"role": "system", "content": "You are a magical storyteller."},
{"role": "user", "content": prompt_content}
]
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages
)
story = response.choices[0].message['content']
# Split story into four paragraphs
paragraphs = story.split('\n')[:4]
# Create DALLE prompts for each paragraph
dalle_prompts = [create_dalle_prompts(story_title, para) for para in paragraphs]
images = [generate_image(api_key, prompt) for prompt in dalle_prompts]
return story, dalle_prompts, *images
iface = gr.Interface(
fn=generate_story_and_images,
inputs=[
gr.components.Textbox(label="Enter name (Example: Ella)"),
gr.components.Textbox(label="Enter story title (Example: The Enchanted Locket)"),
gr.components.Radio(["for children", "absurd"], label="Story Type"),
gr.components.Textbox(label="OpenAI API Key", type="password")
],
outputs=[
"text",
"text",
gr.components.Image(label="Image 1", type="pil"),
gr.components.Image(label="Image 2", type="pil"),
gr.components.Image(label="Image 3", type="pil"),
gr.components.Image(label="Image 4", type="pil")
],
live=True
)
iface.launch()
|