top of page
Search

StoryWeaver – Create Magical Children's Books with AI

  • Writer: Mohammed  Juyel Haque
    Mohammed Juyel Haque
  • Apr 8
  • 3 min read

StoryWeaver is an AI-powered application that lets you generate short, whimsical children's stories with customized illustrations and downloadable PDFs—all with just a few inputs like your child’s name, favorite animal, and theme!



Features

  • AI-generated stories using OpenAI GPT-3.5 or GPT-4

  • AI-generated illustrations

  • Downloadable PDF book

  • Simple and beautiful Streamlit UI


Tools Used and What They Do

Tool

Purpose

FastAPI

Backend API to handle story and image generation

Streamlit

Frontend interface for user interaction

OpenAI API

For GPT story generation and DALL·E illustrations

FPDF

Converts story and image into a downloadable PDF

uuid

For unique PDF filenames

dotenv

Loads the OpenAI API key securely

requests

For HTTP communication between frontend and backend

 Setup Guide

  1. Clone the repo:

  1. Add your OpenAI API key to .env:

OPENAI_API_KEY=your_openai_key_here
  1. Install the dependencies:

pip install -r requirements.txt
  1. Make sure the required font file exists:

    Place DejaVuSans.ttf in a folder named fonts/.

fastapi
uvicorn
openai
python-dotenv
fpdf
streamlit
requests

Running the App

Step 1: Start FastAPI backend

uvicorn main:app --reload

Step 2: Run the Streamlit frontend

streamlit run app.py

  Backend Code (fastapi_backend.py)


from fastapi import FastAPI
from pydantic import BaseModel
from fastapi.responses import FileResponse
import uuid
import os
from fpdf import FPDF
from openai import OpenAI
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

# Initialize OpenAI client
api_key = os.getenv("OPENAI_API_KEY")
client = OpenAI(api_key=api_key)

# Initialize FastAPI app
app = FastAPI()

# Pydantic model for request payload
class StoryRequest(BaseModel):
    child_name: str
    favorite_animal: str
    theme: str
    quality: str = "standard"  # standard = gpt-3.5, high = gpt-4

@app.post("/generate-story/")
def generate_story(req: StoryRequest):
    # Prompt to generate story
    prompt = (
        f"Write a magical, illustrated children's story about a child named {req.child_name} "
        f"who has a best friend that is a {req.favorite_animal}. Theme: {req.theme}. "
        "The story should be under 500 words, whimsical, and suitable for ages 3–8."
    )

    # Choose GPT model
    model_name = "gpt-4" if req.quality == "high" else "gpt-3.5-turbo"

    # Generate story with OpenAI
    response = client.chat.completions.create(
        model=model_name,
        messages=[{"role": "user", "content": prompt}]
    )
    story = response.choices[0].message.content.strip()

    # Generate image from OpenAI
    image_prompt = f"A cute, storybook-style illustration of a {req.favorite_animal} in a magical setting"
    image_response = client.images.generate(prompt=image_prompt, n=1, size="512x512")
    image_url = image_response.data[0].url

    # Create output directory for PDFs
    os.makedirs("pdfs", exist_ok=True)
    filename = f"{uuid.uuid4()}.pdf"
    pdf_path = os.path.join("pdfs", filename)

    # Load local font
    font_path = os.path.join("fonts", "DejaVuSans.ttf")
    if not os.path.exists(font_path):
        raise FileNotFoundError("Font file not found! Please place DejaVuSans.ttf inside the 'fonts/' folder.")

    # Create PDF
    pdf = FPDF()
    pdf.add_page()
    pdf.add_font("DejaVu", "", font_path, uni=True)
    pdf.set_font("DejaVu", size=12)
    pdf.multi_cell(0, 10, f"StoryWeaver - A Story for {req.child_name}")
    pdf.ln()
    for line in story.split("\n"):
        pdf.multi_cell(0, 10, line)
    pdf.output(pdf_path)

    # Return response
    return {
        "story": story,
        "image_url": image_url,
        "pdf_url": f"/download-pdf/{filename}"
    }

@app.get("/download-pdf/{filename}")
def download_pdf(filename: str):
    file_path = os.path.join("pdfs", filename)
    if os.path.exists(file_path):
        return FileResponse(file_path, media_type='application/pdf', filename=filename)
    return {"error": "File not found"}

Frontend Code (streamlit_frontend.py)


import streamlit as st
import requests

API_URL = "http://localhost:8000"

st.set_page_config(page_title="StoryWeaver", layout="centered")
st.title("📚 StoryWeaver – AI Children's Book Generator")

with st.form("story_form"):
    name = st.text_input("👶 Child's Name", placeholder="e.g. Aria")
    animal = st.text_input("🦄 Favorite Animal", placeholder="e.g. Dragon")
    theme = st.text_input("🌈 Theme", placeholder="e.g. Friendship in the forest")
    submit = st.form_submit_button("✨ Create Story")

if submit:
    with st.spinner("Weaving your magical story... 🧵"):
        response = requests.post(f"{API_URL}/generate-story/", json={
            "child_name": name,
            "favorite_animal": animal,
            "theme": theme
        })
        if response.status_code == 200:
            result = response.json()
            st.success("Story created! 📖")

            st.subheader("📖 Story")
            st.write(result["story"])

            st.subheader("🎨 Illustration")
            st.image(result["image_url"], use_column_width=True)

            st.subheader("📄 Download Your Book")
            pdf_link = f"{API_URL}{result['pdf_url']}"
            st.markdown(f"[📥 Download PDF]({pdf_link})", unsafe_allow_html=True)
        else:
            st.error("Something went wrong. Try again!")

Frontend UI Screenshot



Conclusion

StoryWeaver brings a touch of AI magic to bedtime stories. Whether you're a parent, educator, or just someone with a big imagination—this tool lets you create personalized, illustrated stories in seconds!


To use the code : Click Me (It will Take you to my github repo)

To watch the demo: Click Me (It will Take you to my youtube channel)

 
 
 

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating*

© 2024 Mohammed Juyel Haque. All rights reserved.

bottom of page