Turn PDF Slides into Narrated Audio with Gemini and TTS

Build a CocoIndex v1 pipeline that turns PDF slides into vision-generated speaker notes, local Pocket TTS narration, and searchable LanceDB records.

TutorialUpdated 11 min read
Turn slide decks into narrated audio. quarterly_review.pdf fans out into 3 slides; each slide becomes one SlideRecord row in LanceDB holding its id quarterly_review.pdf#2, speaker notes written by a vision model, a voice MP3 from Pocket TTS, and an embedding. Editing slide 2 re-runs 1 vision call and 23.4 s of TTS.
Enlarge cover

Turn PDF Slides into Narrated Audio with Gemini and TTS

Zoom in to see details.

Turn slide decks into narrated audio. quarterly_review.pdf fans out into 3 slides; each slide becomes one SlideRecord row in LanceDB holding its id quarterly_review.pdf#2, speaker notes written by a vision model, a voice MP3 from Pocket TTS, and an embedding. Editing slide 2 re-runs 1 vision call and 23.4 s of TTS.

Slide decks hold a lot of company knowledge: quarterly updates, technical specs, sales reports, training material. They live in PDF files that change often, and they are hard to search or consume outside a presentation.

This tutorial builds a pipeline that turns a folder of decks into a narrated, searchable knowledge base:

  • Listen to a deck slide by slide instead of reading it, which also helps people with visual impairments.
  • Speaker notes for every slide, written by a VLM (vision language model) that reads the rendered slide.
  • Semantic search over the notes, so a query finds slides by meaning rather than by the words in a title or file name.

Producing those outputs once is half the job. When a deck changes, its notes, audio and embeddings have to change with it, and only for the slides that changed. CocoIndex keeps derived data in sync with its sources and recomputes only what a change affects. LanceDB is an open-source, embedded retrieval library that stores the notes, MP3 bytes, embeddings and metadata in one table, with vector, full-text and secondary indexes next to the data.

The code follows the slides_to_speech example on the CocoIndex v1 API.

What we are building: one slide, three derived modalities

A PDF deck doesn’t become one large database record. The pipeline fans it out page by page, then turns each slide into three related outputs: speaker notes, MP3 narration, and a text embedding for semantic search.

CocoIndex maintains the transformation; LanceDB keeps every modality together.

The speaker notes sit at the center of the pipeline, but they first need to be generated by a vision model that reasons over the slide content. Once they exist, audio generation and embedding can start together. The completed outputs are then declared together as one SlideRecord, identified by its filename and page number.

Each tool has one focused job:

ComponentRole in the pipeline
CocoIndexDiscovers PDFs, runs the transformations, and reconciles the declared slide rows with the source files.
PyMuPDFRenders every PDF page as a PNG for the vision model.
DSPy + GeminiDSPy calls the VLM through a typed signature. The VLM (Gemini, gemini/gemini-2.5-flash unless LLM_MODEL says otherwise) reads each rendered slide PNG and writes the speaker notes.
Pocket TTSSynthesizes those notes as MP3 audio locally on the CPU.
Sentence TransformersEmbeds the speaker notes locally with sentence-transformers/all-MiniLM-L6-v2 (384-dimensional vectors).
LanceDBStores text, binary audio, metadata, and vectors together, then searches the notes by meaning.

Everything except the VLM runs locally and needs no GPU: PyMuPDF renders the pages as images, Pocket TTS synthesizes audio from the speaker notes, sentence-transformers generates text embeddings, and LanceDB runs as an embedded library.

Start backwards from the target

CocoIndex pipelines are easiest to reason about backwards from the target, i.e., where the data sits in its final form: target_state = transformation(source_state), where transformation can be any function, or a set of functions. For this pipeline, the target state is one LanceDB row for each slide.

python
# Declare the LanceDB table shape via a strictly typed schema
# Pydantic or PyArrow schemas work well, but dataclasses are simpler for this example
@dataclass
class SlideRecord:
    id: str
    filename: str
    page: int
    speaker_notes: str
    voice: bytes
    embedding: Annotated[NDArray, EMBEDDER]

# Mount a LanceDB table as the target
table = await lancedb.mount_table_target(
    LANCE_DB,
    table_name="slides_to_speech",
    table_schema=await lancedb.TableSchema.from_class(
        SlideRecord,
        primary_key=["id"],
    ),
)

Each LanceDB row holds the slide’s metadata, generated notes, MP3 narration bytes, and vector embedding side by side. SlideRecord is the typed contract that keeps those values together.

Each slide needs a stable primary key so CocoIndex can match it to the same LanceDB row across runs, updating or removing the correct record as the source changes. This example derives that key from the filename and page number: page 3 of quarterly_review.pdf becomes quarterly_review.pdf#3.

Functions vs. processing components

Incremental processing is only useful when its boundaries match the unit of change. We want our pipeline to run every time a change is detected in the source files, without recomputing what didn’t change.

In CocoIndex, functions define the work, while processing components group that work into independently synchronized units. Where we draw those component boundaries determines how much of the pipeline runs each time a change is detected, and which target states CocoIndex reconciles afterward.

  • Functions are callable Python functions decorated with @coco.fn. Setting memo=True lets CocoIndex reuse results for unchanged inputs and code. Several functions can run inside the same processing component.
  • Processing components are created by grouping functions and mounting them to the target. They manage the necessary function calls and the target states they declare. Processing components help decide the granularity at which CocoIndex reruns work and synchronizes the result.

In this example, we define the processing component at the per-slide level, through the process_file function. It takes a PDF file, renders each slide as an image, and mounts one process_slide component for each slide.

python
@coco.fn(memo=True)
async def process_file(
    file: FileLike,
    table: lancedb.TableTarget[SlideRecord],
) -> None:
    slides = await pdf_to_slides(await file.read())
    await coco.mount_each(
        process_slide,
        ((slide.page_number, slide) for slide in slides),
        str(file.file_path.path),
        table,
    )

process_file is memoized too, so CocoIndex can skip reading and rendering an unchanged PDF. If the file does change, process_slide provides the finer-grained memoization boundary: slide images with unchanged inputs reuse their prior results, while changed slides go through note generation, TTS, embedding, and the declaration of SlideRecord in the LanceDB target based on its stable key.

Changing a slide in a PDF still reruns page rendering for that entire file. PyMuPDF rendering is cheap and no VLM call happens at this step. CocoIndex then compares each slide’s PNG bytes with the previous run and processes only the slides whose images changed, which is why the component is mounted per slide.

Pick a change below to see which calls run again for each slide of the sample deck:

What runs again when the deck changes

quarterly_review.pdf · 3 slides
Change one thing, then run cocoindex update:
pdf_to_slides(quarterly_review.pdf)re-runone call per file, renders every page
Per-slide calls on the next run
process_slidepage PNGnotes · VLMTTSembedLanceDB row
Slide 1Q3 Product Roadmapslide_1.mp3 · 0:25reusedsame bytesskippedskippedskippedkept
Slide 2Engineering Prioritiesslide_2.mp3 · 0:23regeneratedchangedre-runre-runre-runupserted
Slide 3Go-To-Marketslide_3.mp3 · 0:23reusedsame bytesskippedskippedskippedkept
VLM calls
1 of 3
TTS audio generated
23.4 s of 72.2 s
Rows upserted
1 of 3

The PDF bytes changed, so pdf_to_slides renders all 3 pages again (one cheap call, no model). Pages 1 and 3 render to the same PNG bytes, so their process_slide components are skipped.

If a PDF is deleted from the source folder, CocoIndex unmounts its per-file component and recursively cleans up the target states it owns. In this pipeline, that means deleting the PDF’s slide rows from LanceDB.

The next sections go through each stage of the pipeline.

Fan a PDF out into slides

The function pdf_to_slides turns the PDF bytes into typed SlidePage values, each carrying the page number and the rendered PNG that the vision model will inspect.

python
@dataclass
class SlidePage:
    page_number: int
    image: bytes

@coco.fn.as_async(runner=coco.GPU, memo=True)
def pdf_to_slides(content: bytes) -> list[SlidePage]:
    import pymupdf

    slides: list[SlidePage] = []
    doc = pymupdf.open(stream=content, filetype="pdf")
    for i, page in enumerate(doc):
        pix = page.get_pixmap(matrix=pymupdf.Matrix(2, 2))
        slides.append(
            SlidePage(page_number=i + 1, image=pix.tobytes("png"))
        )
    doc.close()
    return slides

PyMuPDF renders each page at 2× scale, so the vision model sees a legible PNG rather than extracted PDF text. The image is an intermediate input: Gemini uses it to generate notes, but the pipeline discards it afterward. If you want to keep the rendered image for reuse, you can add an image field and store its bytes in the same LanceDB table.

Why runner=coco.GPU on CPU code

The coco.GPU runner doesn’t require a GPU. Every function on it shares one queue, and a sync function runs on a dedicated thread, one call at a time. That suits blocking libraries that are not safe to call from several threads at once, such as PyMuPDF and Pocket TTS: @coco.fn.as_async turns the blocking call into an awaitable that doesn’t block the event loop, and the runner keeps two calls from overlapping.

Turn a slide image into narration

Extracting speaker notes from the slide images gives the Pocket TTS model the text it needs to narrate the slide. Text embeddings are also generated from the speaker notes, so semantic search can find slides by meaning rather than by keywords in their titles or filenames.

python
class SlideNotes(dspy.Signature):
    """Write natural spoken narration for a slide, as a presenter would say it aloud."""

    slide: dspy.Image = dspy.InputField(desc="the rendered slide image")
    speaker_notes: str = dspy.OutputField(
        desc="a few sentences of spoken narration — no markdown or bullet symbols"
    )

_speaker_notes = dspy.Predict(SlideNotes)

@functools.cache
def _get_lm(model: str) -> dspy.LM:
    return dspy.LM(model, max_tokens=8192)

@coco.fn(memo=True)
async def extract_speaker_notes(image: bytes) -> str:
    data_url = "data:image/png;base64," + base64.b64encode(image).decode()
    with dspy.context(lm=_get_lm(coco.use_context(LLM_MODEL))):
        result = await _speaker_notes.acall(slide=dspy.Image(url=data_url))
    return result.speaker_notes

SlideNotes is a DSPy signature, a typed contract that tells the VLM what we need. When a slide image comes in, speaker notes come out. The CocoIndex function extract_speaker_notes does the actual work of turning the PNG bytes into a text output.

This extraction function is memoized because speaker-note generation is the most expensive step: it calls a VLM to reason over the image. Its memoization key includes the rendered image and the change-detected LLM_MODEL context, so an unchanged slide reuses its notes while the image bytes and the model stay the same. If either changes, CocoIndex reruns the work for that slide.

text_to_speech synthesizes the notes with Pocket TTS and packs the audio as MP3. The model and each voice’s conditioning state load once and stay cached:

python
@functools.cache
def get_tts_model() -> TTSModel:
    return TTSModel.load_model()

@functools.cache
def get_voice_state(voice: str) -> dict:
    return get_tts_model().get_state_for_audio_prompt(voice)

@coco.fn.as_async(runner=coco.GPU, memo=True)
def text_to_speech(text: str, voice: str) -> bytes:
    model = get_tts_model()
    # Pocket TTS is not thread-safe; the coco.GPU runner serializes calls.
    audio = model.generate_audio(get_voice_state(voice), text)
    samples = np.clip(audio.to("cpu").numpy().reshape(-1), -1.0, 1.0)
    pcm16 = (samples * 32767.0).astype("<i2").tobytes()
    segment = AudioSegment(
        data=pcm16, sample_width=2, frame_rate=model.sample_rate, channels=1
    )
    out = io.BytesIO()
    segment.export(out, format="mp3", bitrate="64k")
    return out.getvalue()

The memo key is the text and the voice name, so the same notes in the same voice are not synthesized again while the function’s code stays the same.

Turn speaker notes into audio and embeddings

process_slide reads top to bottom. The speaker notes must exist first, so it awaits extract_speaker_notes. Audio synthesis and embedding don’t depend on each other, so asyncio.gather submits both at once; both heavy calls go through the coco.GPU runner, which executes them one after the other. CocoIndex commits the row to the LanceDB table only after both are ready.

python
@coco.fn(memo=True)
async def process_slide(
    slide: SlidePage,
    filename: str,
    table: lancedb.TableTarget[SlideRecord],
) -> None:
    notes = await extract_speaker_notes(slide.image)
    voice, embedding = await asyncio.gather(
        text_to_speech(notes, coco.use_context(TTS_VOICE)),
        coco.use_context(EMBEDDER).embed(notes),
    )
    table.declare_row(
        row=SlideRecord(
            id=f"{filename}#{slide.page_number}",
            filename=filename,
            page=slide.page_number,
            speaker_notes=notes,
            voice=voice,
            embedding=embedding,
        )
    )

The target state is declared as a SlideRecord dataclass (per the LanceDB schema) keyed by its unique ID that combines the filename and page number. This is how CocoIndex reconciles the target state with the source files, updating or removing rows as needed.

The expensive nested operations are memoized as well. If only the voice changes, CocoIndex reuses the notes and embedding and regenerates the audio. If the embedding model changes, it reuses the notes and audio and computes a new vector. This gives reuse at the file, slide, and individual transformation levels.

Define the app

Apps are the top-level runnable unit in CocoIndex. They name your pipeline and bind a main function with its parameters. When you call app.update(), CocoIndex runs that main function as the root processing component that can mount processing components (like our process_file and its child component process_slide) that do work and declare target states.

app_main mounts the SlideRecord table we defined earlier, uses localfs.walk_dir in live mode to discover PDFs, then calls the outer mount_each. The app is configured with a name, the main function, and the source directory to watch for changes.

python
@coco.fn
async def app_main(sourcedir: pathlib.Path) -> None:
    table = await lancedb.mount_table_target(
        LANCE_DB,
        table_name="slides_to_speech",
        table_schema=await lancedb.TableSchema.from_class(
            SlideRecord,
            primary_key=["id"],
        ),
    )
    files = localfs.walk_dir(
        sourcedir,
        recursive=True,
        path_matcher=PatternFilePathMatcher(
            included_patterns=["**/*.pdf"]
        ),
        live=True,
    )
    await coco.mount_each(process_file, files.items(), table)

app = coco.App(
    coco.AppConfig(name="SlidesToSpeech"),
    app_main,
    sourcedir=pathlib.Path("./slides"),
)

The example’s coco_lifespan provides the context values the functions read: the LanceDB connection, the embedder, LLM_MODEL and TTS_VOICE, the last two from environment variables.

Prerequisites

  • Python 3.11+
  • A Gemini API key for the default vision model
  • ffmpeg for MP3 export

Pocket TTS is open source and runs locally on the CPU. Its weights download on the first run, so it needs neither a TTS API key nor a GPU.

Quick start

From the example directory, copy the environment file and set GEMINI_API_KEY. The file also sets LLM_MODEL (gemini/gemini-3.5-flash) and POCKET_TTS_VOICE (anna); without them, the code falls back to gemini/gemini-2.5-flash and the alba voice. Then install and run:

sh
cp .env.example .env
uv sync
cocoindex update main

# Keep watching slides/ for changes instead:
cocoindex update -L main

Search the deck

sh
python main.py "reducing latency and reliability"

The query helper embeds the question with the same sentence-transformer, then asks LanceDB for its nearest neighbors. The results already arrive ranked, so we can print the matching slide and its notes directly:

python
for row in table.search(vec).limit(5).to_list():
    print(f"{row['filename']} slide {row['page']}")

The slide deck we use here is an example “quarterly-review” deck, so the query about “reducing latency and reliability” brings the slide about “Engineering Priorities” to the top because its notes discuss “reducing p95 latency and multi-region resilience”.

The returned row can also fetch the voice bytes, so a downstream application can serve them as audio/mpeg, or write them to an MP3 file for playback.

Here is the narration the pipeline generated for the sample deck, one MP3 per slide. The recordings and transcripts describe the illustrative quarterly-review deck:

  1. Slide 1: Q3 Product RoadmapMP3 · 0:25
    Show transcript

    Now, let's take a look at our Q3 product roadmap. For this upcoming quarter, we have three key priorities. First, we are focused on shipping the new search index to improve overall performance. Next, we will be launching live mode into general availability. And finally, we plan to successfully onboard three design partners to help us refine and validate our product updates.

  2. Slide 2: Engineering PrioritiesMP3 · 0:23
    Show transcript

    Next, let's look at our top engineering priorities. First, we are targeting performance by aiming to cut our P95 latency by 40%. Second, we will be implementing incremental graph rebuilds to make our processes much more efficient. Finally, to ensure high availability and resilience, we are working on a robust multi-region failover solution.

  3. Slide 3: Go-To-MarketMP3 · 0:23
    Show transcript

    For our go-to-market strategy, we will begin with a developer-focused launch on Hacker News to build early traction and community engagement. From there, we plan to roll out a partner webinar series to expand our reach and establish credibility. Finally, we will introduce flexible pricing tiers designed specifically for teams, helping us transition from individual users to organisational accounts.

How CocoIndex tracks changes

In this demo, CocoIndex watches the ./slides directory for changed PDFs. It then identifies the changed slides, and only those slides regenerate notes, audio, and embeddings.

Source files changing is only one such scenario. The table below shows the other changes that CocoIndex tracks, and what they mean for this pipeline and others like it.

ChangeWhat it means in this pipeline
NothingMemoized calls reuse their prior results and retain their rows.
One slide changes inside a PDFThe PDF renders again, then only the slide with different PNG bytes reruns notes, TTS, embedding, and its row declaration.
A PDF is added or deletedCocoIndex creates or removes the file component and all of its owned slide rows.
LLM model, embedder, or voice changesThe change-detected context refreshes the functions that consume it; unrelated memoized calls can be reused.
Decorated function logic changesA changed @coco.fn fingerprint invalidates memoized calls that depend on that function, then CocoIndex reconciles the resulting rows.
SlideRecord fields or primary key changeThe target contract has changed. Treat compatibility, backfill, and identity changes as a deliberate migration decision.

Extend the pipeline to other formats

This pipeline derives narration, embeddings, and searchable rows from slide decks. Similar pipelines can process other document and media formats into one collection that agents can retrieve from:

  • One storage layer: text, audio, vectors, and metadata in the same table.
  • More structure: speaker notes, extracted fields, embeddings, tags, and other derived signals.
  • Kept in sync: incremental recomputation when source files change, with updated rows in LanceDB.
  • Applications on top: semantic search, narrated slide playback, assistants, and video-generation pipelines.

Run the complete slides-to-speech example with your own deck. The source repositories are CocoIndex and LanceDB.

Frequently asked questions

How do I turn slide decks into narrated audio automatically?

This pipeline watches a local slides/ folder for new and updated PDFs, renders each page to an image, writes structured speaker notes with a vision model, synthesizes narration, embeds the notes for search, and stores everything in LanceDB. The result is a continuously updated, searchable multimodal dataset of slide metadata, speaker notes, MP3 audio, and embeddings.

See What we are building: one slide, three derived modalities

How are speaker notes extracted from slide images?

Each PDF page is rendered to a PNG at 2× scale with PyMuPDF, then passed to a SlideNotes DSPy signature backed by the configured vision model. The signature defines a slide-image input and spoken-notes output; the code defaults to gemini/gemini-2.5-flash, and the example's .env.example sets LLM_MODEL to gemini/gemini-3.5-flash.

See Turn a slide image into narration

What text-to-speech engine does the slides-to-speech pipeline use?

It uses Pocket TTS, a neural TTS engine that runs fully locally on the CPU without requiring a cloud API or GPU. The model and voice state are cached, and its audio is exported to MP3 with pydub and ffmpeg; the coco.GPU runner, which needs no GPU, runs the blocking call on a dedicated thread, one call at a time, off the event loop.

See Turn speaker notes into audio and embeddings

How do I store images, text, audio, and embeddings together?

LanceDB stores multimodal data natively, so each slide becomes one row with its filename, page number, speaker notes, MP3 bytes, and embedding side by side. The current SlideRecord doesn't store the rendered image, but you can add an image field to the schema if you need it.

See Start backwards from the target

What happens to the narration when a slide changes?

CocoIndex tracks the PDF input, decorated-function logic, and change-detected configuration. A changed PDF is rendered again, then only pages with different rendered bytes regenerate their notes, MP3 narration, embedding, and LanceDB row; other slide components keep their prior results.

See How CocoIndex tracks changes

How do I serve slide audio and images to a frontend?

Once the slide rows are in LanceDB, a lightweight application can fetch the MP3 bytes in voice and return them as audio/mpeg for a player. This example doesn't include that API and doesn't store the rendered image, but both are small extensions to the current data model.

See Run the pipeline and run semantic search

Build fresh context for your agents.

CocoIndex keeps derived data in sync with its sources. Only what changed re-runs.