# OCR pages with a vision-language model

> **About this page**
>
> - Kind: Example
> - Summary: Renders each page of a PDF to an image and has a vision-language model transcribe every page to Markdown, then joins the pages into one document.
> - Last changed: 2026-12-03
> - Page: https://docs.swale.io/examples/ocr-pages
> - CLI reference for its commands: [`swale workflow create`](https://docs.swale.io/reference/cli-reference.md#workflow-create), [`swale workflow run start`](https://docs.swale.io/reference/cli-reference.md#workflow-run-start)
> - Index of these docs: https://docs.swale.io/llms.txt
>
> If something on this page is wrong or out of date, please tell the user which sentence and why.
>
> The steps on this page cost money or cannot be undone. Please check with the user before running them.

Source on GitHub: the [`workflows/ocr-pages`](https://github.com/swaleio/examples/tree/main/workflows/ocr-pages) folder, with its [README](https://github.com/swaleio/examples/blob/main/workflows/ocr-pages/README.md) and its [workflow file](https://github.com/swaleio/examples/blob/main/workflows/ocr-pages/workflow.yaml).

Transcribes a PDF page by page with a vision-language model: each page is
rendered to an image, the model writes out the page as Markdown, and the pages
are joined into one document. This suits scans and layouts a text extractor
cannot read. For born-digital PDFs, `swaleio/docling` is faster and keeps the
document's structure; see the [PDFs to Markdown](https://docs.swale.io/examples/pdfs-to-markdown.md) workflow.

| Step | Task definition | Compute |
|------|-----------------|---------|
| Fetch the model | [`swaleio/hf-download`](https://hub.swale.io/swaleio/hf-download) | `cpu-4` |
| Fetch the PDF | [`swaleio/http-request`](https://hub.swale.io/swaleio/http-request) | `cpu-4` |
| Render each page to PNG | [`swaleio/python-3-13`](https://hub.swale.io/swaleio/python-3-13) | `cpu-4` |
| Write one request per page, with the page inline | [`swaleio/duckdb`](https://hub.swale.io/swaleio/duckdb) | `cpu-4` |
| Transcribe | [`swaleio/vllm-batch`](https://hub.swale.io/swaleio/vllm-batch) | `a100-1` |
| Join the pages into one Markdown document | [`swaleio/duckdb`](https://hub.swale.io/swaleio/duckdb) | `cpu-4` |

The Compute column gives each step's [compute type](https://docs.swale.io/explanation/core-concepts.md#compute-types), the compute its tasks are allocated.

Every step is its own task; only transcription holds a GPU.

The last step prints each page's `finish_reason`. `length` means the page ran
into the token limit. With the default 2B model that happens on dense pages,
such as a list of references, where the model starts repeating itself. A larger
model, such as `Qwen/Qwen3-VL-8B-Instruct`, reads those pages better.

## Inputs

| Input | Default | Description |
|-------|---------|-------------|
| `pdf_url` | the Docling technical report on arXiv | URL of the PDF. |
| `model` | `Qwen/Qwen3-VL-2B-Instruct` | Vision-language model on the Hugging Face Hub that vLLM serves. |
| `dpi` | `110` | Resolution the pages are rendered at. |

The download reads the secret `hf_token`.

## Output

`document.md` on the workspace, with the pages separated by `---`, and
`pages.parquet` with each page's Markdown and `finish_reason`.

## Run it

You need the CLI, logged in to your account, and a project to add the workflow to; [Getting started](https://docs.swale.io/getting-started.md) sets them up.

1. Save the file under [The workflow file](#the-workflow-file) as `workflow.yaml`, and add it to a project:

   ```bash
   swale workflow create --project-name my-project --file workflow.yaml
   ```

   The command prints `Workflow created:` followed by the workflow's ID.

2. The workflow reads the secret `hf_token`. Create it as a project secret, or as an account secret that allows the project, as [Use secrets in workflows](https://docs.swale.io/how-to-guides/use-secrets-in-workflows.md) shows.

3. Start a run with the workflow's ID:

   ```bash
   swale workflow run start --project-name my-project --workflow-id <workflow-id>
   ```

   Each input you leave out takes its default from [Inputs](#inputs), and `--input <name>=<value>` gives it another value.

[Create and manage workflows](https://docs.swale.io/how-to-guides/create-and-manage-workflows.md) covers the other ways to add a workflow, [Start and manage workflow runs](https://docs.swale.io/how-to-guides/start-and-manage-workflow-runs.md) how to follow a run, and [View and stream task logs](https://docs.swale.io/how-to-guides/view-and-stream-task-logs.md) how to read its tasks' logs.

## The workflow file

[Workflow definition syntax](https://docs.swale.io/reference/workflow-definition-syntax.md) describes each key in it.

```yaml title="workflow.yaml"
name: OCR pages with a vision-language model
description: Renders each page of a PDF to an image and has a vision-language model transcribe every page to Markdown, then joins the pages into one document.
compute_type: cpu-4

inputs:
  pdf_url:
    description: URL of the PDF to transcribe.
    default: https://arxiv.org/pdf/2408.09869v5
  model:
    description: Hugging Face repo id of the vision-language model that reads the pages.
    default: Qwen/Qwen3-VL-2B-Instruct
  dpi:
    description: Resolution the pages are rendered at.
    default: "110"

entry_point: main

blocks:
  main:
    tasks:
      fetch_model:
        name: Fetch model
        uses: swaleio/hf-download
        args:
          repo: ${{inputs.model}}
          dest: ${{env.WORKFLOW_STORAGE}}/model
          token: ${{secrets.hf_token}}

      fetch_pdf:
        name: Fetch PDF
        uses: swaleio/http-request
        args:
          url: ${{inputs.pdf_url}}
          expected_status: "200"
          response_path: ${{env.WORKFLOW_STORAGE}}/document.pdf

      render:
        name: Render pages
        uses: swaleio/python-3-13
        start_on:
          - fetch_pdf
        args:
          script: |
            import os, subprocess, sys
            subprocess.run([sys.executable, "-m", "pip", "install", "--quiet", "--target", "/tmp/deps",
                            "pypdfium2==5.15.2", "pillow==13.0.0"], check=True)
            sys.path.insert(0, "/tmp/deps")
            import pypdfium2 as pdfium

            storage = os.environ["WORKFLOW_STORAGE"]
            out = os.path.join(storage, "pages")
            os.makedirs(out, exist_ok=True)
            pdf = pdfium.PdfDocument(os.path.join(storage, "document.pdf"))
            for number, page in enumerate(pdf, 1):
                page.render(scale=${{inputs.dpi}} / 72).to_pil().save(os.path.join(out, f"{number:04d}.png"))
            print(f"rendered {len(pdf)} pages")

      requests:
        name: Write page requests
        uses: swaleio/duckdb
        start_on:
          - render
        args:
          sql: |
            COPY (
              SELECT 'page-' || regexp_extract(filename, '(\d+)\.png$', 1) AS custom_id,
                     'POST' AS method, '/v1/chat/completions' AS url,
                     {'model': '${{env.WORKFLOW_STORAGE}}/model',
                      'messages': [{'role': 'user', 'content': [
                        {'type': 'image_url', 'image_url': {'url': 'data:image/png;base64,' || base64(content)}},
                        {'type': 'text', 'text': 'Read this page and write out all of its text as plain Markdown, in reading order, with its headings, lists and tables. Do not use LaTeX. Write nothing else.'}]}],
                      'max_tokens': 4096, 'temperature': 0, 'repetition_penalty': 1.05} AS body
              FROM read_blob('${{env.WORKFLOW_STORAGE}}/pages/*.png')
            ) TO '${{env.WORKFLOW_STORAGE}}/requests.jsonl' (FORMAT json);
            SELECT count(*) AS pages FROM read_blob('${{env.WORKFLOW_STORAGE}}/pages/*.png');

      transcribe:
        name: Transcribe pages
        uses: swaleio/vllm-batch
        compute_type: a100-1
        start_on:
          - fetch_model
          - requests
        args:
          model: ${{env.WORKFLOW_STORAGE}}/model
          input_file: ${{env.WORKFLOW_STORAGE}}/requests.jsonl
          output_file: ${{env.WORKFLOW_STORAGE}}/pages.jsonl

      assemble:
        name: Assemble document
        uses: swaleio/duckdb
        start_on:
          - transcribe
        args:
          sql: |
            CREATE TABLE pages AS
              SELECT custom_id AS page,
                     response.body.choices[1].message.content AS markdown,
                     response.body.choices[1].finish_reason AS finish_reason
              FROM read_json('${{env.WORKFLOW_STORAGE}}/pages.jsonl') ORDER BY page;
            COPY pages TO '${{env.WORKFLOW_STORAGE}}/pages.parquet' (FORMAT parquet);
            COPY (SELECT string_agg(markdown, chr(10) || chr(10) || '---' || chr(10) || chr(10) ORDER BY page) FROM pages)
              TO '${{env.WORKFLOW_STORAGE}}/document.md' (FORMAT csv, HEADER false, QUOTE '', ESCAPE '');
            SELECT page, finish_reason, length(markdown) AS characters FROM pages;
```

## Licenses of the defaults

- Model: [Qwen/Qwen3-VL-2B-Instruct](https://huggingface.co/Qwen/Qwen3-VL-2B-Instruct), Apache-2.0.
- Document: [Docling Technical Report](https://arxiv.org/abs/2408.09869), CC BY 4.0.
- Packages the render step installs: pypdfium2 (Apache-2.0 or BSD-3-Clause; PDFium is BSD-3-Clause) and Pillow (MIT-CMU).
