Cookbook

Extract · PDFs and scans

Extract from a PDF or a scan

The API takes text. Reports, invoices and letters arrive as PDFs, and some of those are scans: pictures of pages with no text in them. There is no upload for files on the server yet, so the file is turned into text on your own machine first, and then the extraction recipe runs on that text exactly as it does on any other.

The tool we recommend for that step is Docling. An MIT licence and fully local execution make it the easy default. Table structure survives its conversion, and scanned pages go through an optional OCR step.

The move
PDF or scan in, text out, on your machine. Then the same extraction as for text.
The model’s role
Unchanged: it reads text and returns the record. Docling does the reading of the file.
Why it fits
The conversion keeps tables as tables, so a value that stands in a cell arrives next to its label. And the file never leaves your machine: only the text you choose to send goes to the API.
How it goes
File in → Docling: Markdown text, with OCR switched on for a scan → the field list and that text → one record → check it.
Payoff
Measured: three real accident reports, each as the PDF its agency publishes and as a scan of it: 70 of 72 fields right, and the same answers from the scan as from the PDF every time. The report on this page: 12 of 12 from the PDF, 12 of 12 from the scan. A two-page file took 5 to 13 seconds to convert on four CPU threads.

The data#

The report that opens the accident-report cookbook, a Cessna that lost engine power over Georgia in May 2026, this time as the PDF the US National Transportation Safety Board publishes (public domain; files/NTSB-ERA26LA216.pdf). The PDF holds the narrative our test set has, and four tables that the narrative does not: the aircraft, the weather, the wreckage, the investigation.

The scan is made from it: every page drawn at 200 dots per inch in grey and saved as pictures in a new PDF (files/NTSB-ERA26LA216-scan.pdf). That file has no text layer, which is what a scanner gives you.

The answers come from two places. For the seven fields of the accident-report cookbook, from the test set. For five facts that stand only in the tables, from the PDF’s own text layer, read with a second tool (pdftotext) that owes nothing to Docling or to the model.

Set up#

Terminal
pip install openai docling

Docling needs Python 3.10 or later. It downloads its models the first time it runs (layout, tables and OCR, under 1 GB) and keeps them. On a Linux machine without a GPU, install the CPU build of PyTorch first: the whole environment was 1.5 GB that way, and the default build adds several gigabytes of GPU libraries.

Terminal
pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu
pip install openai docling
Python
import json
import time
from pathlib import Path

from docling.datamodel.base_models import InputFormat
from docling.datamodel.pipeline_options import OcrMode, PdfPipelineOptions
from docling.document_converter import DocumentConverter, PdfFormatOption
from openai import OpenAI

client = OpenAI(base_url="https://api.contrastivelabs.dev/v1", api_key="none")
HERE = Path(__file__).parent

The recipe#

The extract function of the API page, unchanged. It does not know that the text came from a PDF.

Python
def extract(kind, document, fields, max_tokens=800):
    """{field: value or None}. fields: [{"name", "type", "description"}], plus "schema" for lists and objects."""
    lines = "\n".join(f"- {f['name']} ({f['type']}): {f['description']}" for f in fields)
    system = (f"You extract structured data from {kind}s. For each document the user sends, give these fields.\n\n"
              f"Fields:\n{lines}\n\n"
              "Answer with one JSON object with exactly these keys. Use null for a field the text does not give.")
    properties = {f["name"]: f.get("schema") or {"type": [f["type"], "null"]} for f in fields}
    schema = {"type": "object", "properties": properties, "required": [f["name"] for f in fields],
              "additionalProperties": False}
    reply = client.chat.completions.create(
        model="nenya",
        messages=[{"role": "system", "content": system}, {"role": "user", "content": document}],
        temperature=0,                      # one right answer: do not sample
        max_tokens=max_tokens,
        response_format={"type": "json_schema", "json_schema": {"name": "record", "schema": schema}},
    )
    choice = reply.choices[0]
    if choice.finish_reason != "stop":      # "length": the JSON was cut off and will not parse
        raise RuntimeError(f"the reply was cut off ({choice.finish_reason}): raise max_tokens")
    return json.loads(choice.message.content)

Convert the PDF#

One function. For a PDF that has a text layer, OCR is switched off: there is nothing to recognise, and with OCR on Docling also reads the pictures in the page (here it read the words of the agency’s seal in the header, and a stray character with them). For a scan, OCR is switched on for the whole page.

Python
def pdf_to_text(path, scanned=False):
    """The text of a PDF as Markdown, tables included. It runs on this machine: nothing is sent anywhere.
    scanned=True reads every page with OCR, for a file that is only pictures of pages."""
    options = PdfPipelineOptions(do_ocr=scanned)            # a PDF that has a text layer needs no OCR
    if scanned:
        options.ocr_options.mode = OcrMode.FULL_PAGE        # read the whole page, not only the pictures in it
    converter = DocumentConverter(format_options={InputFormat.PDF: PdfFormatOption(pipeline_options=options)})
    return converter.convert(path).document.export_to_markdown()

A PDF with a text layer#

Python
start = time.perf_counter()
text = pdf_to_text(HERE / "files" / "NTSB-ERA26LA216.pdf")
print(f"[converted in {time.perf_counter() - start:.0f} s: {len(text):,} characters]")
print()
print(text)
Output
[converted in 10 s: 3,620 characters]

<!-- image -->

## Aviation Investigation Preliminary Report

Location:

Date &amp; Time:

Doerun, GA

Accident Number:

ERA26LA216

May 23, 2026, 15:00 Local Registration:

N8288G

Aircraft:

Cessna A188B

Injuries:

1 None

Flight Conducted Under: Part 137: Agricultural

On May 23, 2026, about 1500 eastern daylight time, a Cessna A188B, N8288G, was substantially damaged when it was involved in an accident near Doerun, Georgia. The pilot was not injured. The airplane was operated as a Title 14 Code of Federal Regulations Part 137 agricultural flight.

According to the pilot, during his fourth flight of the day the airplane sustained a total loss of engine power while en route to apply fertilizer to a corn field. The pilot initiated a forced landing to a field, during which the airplane struck trees before it came to rest upright, resulting in substantial damage to the fuselage and wings.

The wreckage was retained for further examination.

## Aircraft and Owner/Operator Information

| Aircraft Make:            | Cessna   | Registration:                  | N8288G                      |
|---------------------------|----------|--------------------------------|-----------------------------|
| Model/Series:             | A188B    | Aircraft Category:             | Airplane                    |
| Amateur Built:            |          |                                |                             |
| Operator:                 | On file  | Operating Certificate(s) Held: | Agricultural aircraft (137) |
| Operator Designator Code: |          |                                |                             |

## Meteorological Information and Flight Plan

| Conditions at Accident Site:     | VMC                     | Condition of Light:          | Day                       |
|----------------------------------|-------------------------|------------------------------|---------------------------|
| Observation Facility, Elevation: | ABY,191 ft msl          | Observation Time:            | 15:00 Local               |
| Distance from Accident Site:     | 19 Nautical Miles       | Temperature/Dew Point:       | 31°C /21°C                |
| Lowest Cloud Condition:          | Scattered / 4000 ft AGL | Wind Speed/Gusts, Direction: | 10 knots / 18 knots, 220° |
| Lowest Ceiling:                  |                         | Visibility:                  | 10 miles                  |
| Altimeter Setting:               | 30.03 inches Hg         | Type of Flight Plan Filed:   | NONE                      |
| Departure Point:                 | Doerun, GA              | Destination:                 | Doerun, GA                |

## Wreckage and Impact Information

| Crew Injuries:      | 1 None   | Aircraft Damage:     | Substantial               |
|---------------------|----------|----------------------|---------------------------|
| Passenger Injuries: | N/A      | Aircraft Fire:       | None                      |
| Ground Injuries:    | N/A      | Aircraft Explosion:  | None                      |
| Total Injuries:     | 1 None   | Latitude, Longitude: | 31.348442,-83.89832 (est) |

## Administrative Information

| Investigator In Charge (IIC):     | Wait, Dennis                                           |
|-----------------------------------|--------------------------------------------------------|
| Additional Participating Persons: | Brian Williamson; FAA/FSDO; Atlanta, GA                |
| Investigation Class:              | Class 3                                                |
| Note:                             | The NTSB did not travel to the scene of this accident. |

The four ruled tables came out as Markdown tables, every value in the cell next to its label. The block at the top of the page, which the PDF lays out in two columns without rules, came out as loose lines in an order of its own (“Location:”, “Date & Time:”, “Doerun, GA”). The narrative under it is intact.

The request#

The seven fields of the accident-report cookbook, and the text above as the document:

Python
DATA = json.loads((HERE / "data" / "extract-pdfs-and-scans.json").read_text())
KIND = DATA["kind"]                         # "aviation accident report"
FIELDS = DATA["fields"]                     # the seven fields of the accident-report cookbook, as they are there

record = extract(KIND, text, FIELDS)
print(json.dumps(record, indent=2))

The response#

Output
{
  "event_date": "2026-05-23",
  "city": "Doerun",
  "state": "GA",
  "registration": "N8288G",
  "aircraft_make": "Cessna",
  "aircraft_model": "A188B",
  "cfr_part": 137
}

Check it#

Python
def same(value, answer):
    """Is an extracted value the right one? Text is compared by its letters and digits (case, spaces and
    punctuation aside), numbers as numbers, and a field the document does not state has to be null."""
    if value is None or answer is None:
        return value is None and answer is None
    if isinstance(answer, (int, float)):
        return isinstance(value, (int, float)) and value == answer
    squeeze = lambda s: "".join(c for c in str(s).casefold() if c.isalnum())      # noqa: E731
    return squeeze(value) == squeeze(answer)


report = DATA["documents"][0]               # the test set's answer for this report
for name, value in record.items():
    verdict = "right" if same(value, report["answer"][name]) else f"the narrative has {report['answer'][name]!r}"
    print(f"{name:<15} {value!r:<14} {verdict}")
Output
event_date      '2026-05-23'   right
city            'Doerun'       right
state           'GA'           the narrative has 'Georgia'
registration    'N8288G'       right
aircraft_make   'Cessna'       right
aircraft_model  'A188B'        right
cfr_part        137            right

Six fields are the test set’s. The seventh is the state, and both answers are the report’s own words: the header of the PDF writes “Doerun, GA”, the narrative writes “Doerun, Georgia”, and the field asks for the state “as written in the report”. From the narrative alone the model returned “Georgia”. With the header in front of it, it took “GA”. If you need one of the two, say so in the description: “as a two-letter code”, or “spelled out”.

What only the tables say#

The tables hold facts that the narrative does not: the wind, the visibility, the class of damage. Ask for them the same way:

Python
TABLE_FIELDS = DATA["table_fields"]
for field in TABLE_FIELDS:
    print(f"- {field['name']} ({field['type']}): {field['description']}")

from_tables = extract(KIND, text, TABLE_FIELDS)
print()
for name, value in from_tables.items():
    verdict = "right" if same(value, report["table_answer"][name]) else f"WRONG, the PDF has {report['table_answer'][name]!r}"
    print(f"{name:<17} {value!r:<14} {verdict}")
Output
- accident_number (string): NTSB accident number of the case
- wind_speed_knots (integer): Wind speed in knots at the time of the accident
- wind_gusts_knots (integer): Wind gusts in knots, if the report gives any
- visibility_miles (integer): Visibility in miles
- aircraft_damage (string): Damage to the aircraft, as the report classes it

accident_number   'ERA26LA216'   right
wind_speed_knots  10             right
wind_gusts_knots  18             right
visibility_miles  10             right
aircraft_damage   'Substantial'  right

“10 knots / 18 knots, 220°” stands in one cell, and came back as two numbers in two fields.

A scan#

The same report with no text in the file. One argument changes:

Python
start = time.perf_counter()
scan_text = pdf_to_text(HERE / "files" / "NTSB-ERA26LA216-scan.pdf", scanned=True)
print(f"[converted in {time.perf_counter() - start:.0f} s: {len(scan_text):,} characters]")
print()
print(scan_text[scan_text.index("## Meteorological"):scan_text.index("## Wreckage")])

from_scan = extract(KIND, scan_text, FIELDS + TABLE_FIELDS)
from_pdf = {**record, **from_tables}
print("the same twelve values from the scan as from the PDF:", from_scan == from_pdf)
Output
[converted in 11 s: 3,620 characters]

## Meteorological Information and Flight Plan

| Conditions at Accident Site:     | VMC                     | Condition of Light:          | Day                       |
|----------------------------------|-------------------------|------------------------------|---------------------------|
| Observation Facility, Elevation: | ABY,191 ft msl          | Observation Time:            | 15:00 Local               |
| Distance from Accident Site:     | 19 Nautical Miles       | Temperature/Dew Point:       | 31℃/21℃                   |
| Lowest Cloud Condition:          | Scattered / 4000 ft AGL | Wind Speed/Gusts, Direction: | 10 knots / 18 knots, 220° |
| Lowest Ceiling:                  |                         | Visibility:                  | 10 miles                  |
| Altimeter Setting:               | 30.03 inches Hg         | Type of Flight Plan Filed:   | NONE                      |
| Departure Point:                 | Doerun, GA              | Destination:                 | Doerun, GA                |


the same twelve values from the scan as from the PDF: True

The weather table as the OCR read it. One difference from the PDF: “31°C /21°C” is “31℃/21℃”. All twelve values the model returned are the same as from the PDF.

What we tested#

Three reports of the test set, each as the agency’s PDF and as a scan made the same way, twelve fields each. Docling 2.156.0 and PyTorch 2.15 on Linux, on four CPU threads, with no GPU:

FileConverted inFields right
The report on this page, PDF10 s12 of 12
The same, scan12 s12 of 12
A helicopter accident in Idaho, PDF5 s11 of 12
The same, scan10 s11 of 12
An accident in Alaska, PDF5 s12 of 12
The same, scan13 s12 of 12

The first conversion in a process also loads the models, which is why the first row is slower than the third. The one miss is the same in the PDF and in the scan: the city came back as “Malad City, ID”, the whole cell of the header, where the answer is “Malad City”. The scan never cost a field.

What this does not tell you: these are clean two-page reports from one agency, and the scans are clean renderings at 200 dots per inch. A skewed photograph of a crumpled page, handwriting, or a table that runs over several pages will do worse. Try your own files. We ran this on Linux only. On a Mac, Docling picks its accelerator and its OCR engine by itself and may choose differently.

Make it yours#

  • Look at the text before you send it. print(text) once for each kind of document you have. If the value you want is not in the text, no prompt will find it.
  • Switch OCR off for PDFs that have text, and on for scans. To tell them apart, convert with OCR off first: the scan on this page came back as 14 characters, a placeholder for a picture.
  • Send the part that holds the facts. A long PDF becomes a long text, and extraction gets worse with length (about 85 F1 under 1,000 tokens, 69 between 2,000 and 4,000 in our tests). converter.convert(path, page_range=(1, 2)) converts the first two pages only.
  • Nothing leaves your machine in the conversion. Docling runs its models locally, and its remote services are off unless you switch them on. What goes to the API is the text you pass to extract.
  • Other tools work too. Anything that gives you text will do: pdftotext is faster for PDFs that have a text layer and do not have tables you care about. Docling is the default because it keeps tables and reads scans in one package under a permissive licence.

Run it#

Terminal
pip install openai docling
curl -O https://contrastivelabs.com/cookbook/extract-pdfs-and-scans.py
curl --create-dirs -o data/extract-pdfs-and-scans.json \
     https://contrastivelabs.com/cookbook/data/extract-pdfs-and-scans.json
curl --create-dirs -o files/NTSB-ERA26LA216.pdf \
     https://contrastivelabs.com/cookbook/files/NTSB-ERA26LA216.pdf
curl --create-dirs -o files/NTSB-ERA26LA216-scan.pdf \
     https://contrastivelabs.com/cookbook/files/NTSB-ERA26LA216-scan.pdf
python extract-pdfs-and-scans.py

The file is this page’s code in one piece: extract-pdfs-and-scans.py. The PDF and its scan are in files/, and the answers in data/extract-pdfs-and-scans.json.

Loading…

Need fine-tuning, on-prem deployment, your own evals or support?

Nenya 1 is free to call here and free to download. Book a call for a fine-tuned model or an on-prem deployment.