DEV Community

Cover image for OCR Scanned Contracts in Python: Extract Parties, Dates and Clauses
AI Engine
AI Engine

Posted on Originally published at ai-engine.net

OCR Scanned Contracts in Python: Extract Parties, Dates and Clauses

Law firms, contract managers and legal tech tools all start from the same pile: signed contracts that only exist as scans. Before anyone can search them, track renewal dates or check which clauses are missing, the text has to come out of the image. This tutorial shows how to OCR scanned contracts in Python and turn them into structured data: parties, dates, fees, notice periods and a clause checklist.

We tested every script on three scanned contracts: a two-page music production services agreement, a commercial lease and a mutual NDA. They are sample contracts written for this tutorial and printed as scans, so no real client document was used. Company and person names are fictional. We then ran the pipeline on a real archive: a typewritten 1960 permit file from the U.S. Bureau of Mines, in the public domain.

Want to try it on your own contracts? Get a key for the OCR Wizard API.


What the API returns on a scanned contract

You need Python 3 with requests and a RapidAPI key in RAPIDAPI_KEY. Send the PDF to the /ocr-pdf endpoint in a field named pdf_file, with the page range to read:

import os

import requests

with open("contracts/services_agreement.pdf", "rb") as f:
    response = requests.post(
        "https://ocr-wizard.p.rapidapi.com/ocr-pdf",
        headers={
            "x-rapidapi-host": "ocr-wizard.p.rapidapi.com",
            "x-rapidapi-key": os.environ["RAPIDAPI_KEY"],
        },
        files={"pdf_file": f},
        data={"first_page": 1, "last_page": 10},
        timeout=120,
    )
pages = response.json()["body"]["pages"]
print(len(pages), "pages")
print(pages[0]["detectedLanguage"], len(pages[0]["annotations"]), "words")
print("\n".join(pages[0]["fullText"].splitlines()[:6]))
Enter fullscreen mode Exit fullscreen mode
2 pages
en 239 words
MUSIC PRODUCTION SERVICES AGREEMENT
This Music Production Services Agreement (the "Agreement") is entered
into as of March 3, 2025 (the "Effective Date") by and between
Northfield Records LLC, a New York limited liability company
("Client"), and Bluegate Audio Inc., a Delaware corporation
("Producer").
Enter fullscreen mode Exit fullscreen mode

Each page comes back with fullText, the detected language and annotations, the words with their positions. Line breaks follow the printed lines, so the first step of the extraction is to join everything into one clean string.


Extract the key terms

Save this as contract_ocr.py. It reads the whole PDF, 10 pages per request (the maximum range per call), and returns the fields a reviewer looks for first:

import json
import os
import re
import sys

import requests

API_URL = "https://ocr-wizard.p.rapidapi.com/ocr-pdf"
HEADERS = {
    "x-rapidapi-host": "ocr-wizard.p.rapidapi.com",
    "x-rapidapi-key": os.environ["RAPIDAPI_KEY"],
}

MONTHS = ("January|February|March|April|May|June|July|August|"
          "September|October|November|December")
DATE = rf"(?:{MONTHS}) \d{{1,2}}, \d{{4}}"
ENTITY = r"((?:[A-Z][A-Za-z&'-]* )+(?:LLC|Inc\.|Corp\.|Ltd\.|LLP))"
CLAUSES = {
    "termination": r"\bterminat",
    "confidentiality": r"\bconfidential",
    "governing_law": r"governed by the laws",
    "indemnification": r"\bindemnif",
    "limitation_of_liability": r"limitation of liability|\bliable for\b",
}


def ocr_pdf(path, max_pages=100):
    """OCR a scanned PDF, 10 pages per request, and return all pages."""
    pages = []
    for start in range(1, max_pages + 1, 10):
        with open(path, "rb") as f:
            r = requests.post(API_URL, headers=HEADERS, files={"pdf_file": f},
                              data={"first_page": start, "last_page": start + 9},
                              timeout=120)
        r.raise_for_status()
        data = r.json()
        if data.get("statusCode") != 200:
            raise RuntimeError(data["body"])
        pages += data["body"]["pages"]
        if len(data["body"]["pages"]) < 10:  # past the last page
            break
    return pages


def flatten(pages):
    """Join pages into one clean string: no page footers, no line breaks."""
    text = "\n".join(p["fullText"] for p in pages)
    text = re.sub(r"Page \d+ of \d+", " ", text)
    text = re.sub(r"-\n", "-", text)          # "then-\ncurrent" -> "then-current"
    return re.sub(r"\s+", " ", text)


def first(pattern, text, group=1):
    m = re.search(pattern, text)
    return m.group(group) if m else None


def extract(pages):
    raw = "\n".join(p["fullText"] for p in pages)
    text = flatten(pages)
    preamble = text[:600]

    parties = []
    for m in re.finditer(ENTITY + r"(?:(?:,[^()]*?)? \(\"(\w+)\"\))?", preamble):
        name, role = m.group(1).strip(), m.group(2)
        if name not in [p["name"] for p in parties]:
            parties.append({"name": name, "role": role})

    effective = first(rf"(?:as of|made on|dated) ({DATE})", text)
    term = re.search(r"(?:for a period of|continues for|in effect for) "
                     r"[\w-]+ \((\d+)\) (months|years)", text)
    amounts = [{"amount": m.group(2), "context": m.group(1).strip()}
               for m in re.finditer(r"((?:\S+ ){1,4})(\$[\d,]+(?:\.\d{2})?)", text)]

    return {
        "title": pages[0]["fullText"].splitlines()[0].strip(),
        "parties": parties,
        "effective_date": effective,
        "start_date": first(rf"(?:commences on|begins on) ({DATE})", text) or effective,
        "term": f"{term.group(1)} {term.group(2)}" if term else None,
        "auto_renewal": bool(re.search(r"automatically renew", text)),
        "renewal_notice_days": first(r"\((\d+)\) days before the end", text),
        "termination_notice_days": first(r"terminate[^.]*?\((\d+)\) days (?:written )?notice", text),
        "amounts": amounts,
        "governing_law": first(r"laws of the State of ([A-Z][a-z]+(?: [A-Z][a-z]+)?)", text),
        "signatures": [{"name": n, "title": t, "date": d} for n, t, d in
                       re.findall(rf"Name: (.+)\n\s*Title: (.+)\n\s*Date: ({DATE})", raw)],
        "missing_clauses": [c for c, rx in CLAUSES.items()
                            if not re.search(rx, text, re.IGNORECASE)],
    }


if __name__ == "__main__":
    pages = ocr_pdf(sys.argv[1])
    print(json.dumps(extract(pages), indent=2))
Enter fullscreen mode Exit fullscreen mode

Output on the scanned services agreement:

{
  "title": "MUSIC PRODUCTION SERVICES AGREEMENT",
  "parties": [
    {
      "name": "Northfield Records LLC",
      "role": "Client"
    },
    {
      "name": "Bluegate Audio Inc.",
      "role": "Producer"
    }
  ],
  "effective_date": "March 3, 2025",
  "start_date": "March 3, 2025",
  "term": "12 months",
  "auto_renewal": true,
  "renewal_notice_days": "60",
  "termination_notice_days": "60",
  "amounts": [
    {
      "amount": "$4,500.00",
      "context": "a monthly retainer of"
    },
    {
      "amount": "$95.00",
      "context": "retainer is billed at"
    }
  ],
  "governing_law": "New York",
  "signatures": [
    {
      "name": "Dana Whitfield",
      "title": "Managing Director",
      "date": "March 3, 2025"
    },
    {
      "name": "Luis Ortega",
      "title": "President",
      "date": "March 4, 2025"
    }
  ],
  "missing_clauses": [
    "indemnification",
    "limitation_of_liability"
  ]
}
Enter fullscreen mode Exit fullscreen mode

Every value matches the printed contract:

  • Parties and roles: names ending in LLC, Inc., Corp., Ltd. or LLP in the opening paragraph, followed by the defined role in parentheses, like ("Client").
  • Dates: the effective date follows "as of", "made on" or "dated"; the start date follows "commences on" or "begins on", which matters for leases signed weeks before they start.
  • Term and notice periods: contracts write numbers twice, as in sixty (60) days, so the number in parentheses is the one to read.
  • Amounts: every dollar figure with the four words before it as context.
  • Missing clauses: this agreement has no indemnification and no limitation of liability wording, exactly what a reviewer wants to know before a renewal.

Add the phrasing your own templates use to the patterns, for example hold harmless next to indemnif.


Highlight dates, amounts and notice periods on the scan

Reviewers trust what they can see on the original page. The /ocr endpoint returns every word with its boundingPoly, so you can draw the extracted terms on the scan:

import os
import re
import sys

import requests
from PIL import Image, ImageDraw

HEADERS = {
    "x-rapidapi-host": "ocr-wizard.p.rapidapi.com",
    "x-rapidapi-key": os.environ["RAPIDAPI_KEY"],
}
MONTHS = {"January", "February", "March", "April", "May", "June", "July",
          "August", "September", "October", "November", "December"}
UNITS = (["days"], ["months"], ["years"])
COLORS = {"date": (255, 196, 0), "money": (0, 200, 120), "period": (80, 150, 255)}


def ocr_image(path):
    with open(path, "rb") as f:
        r = requests.post("https://ocr-wizard.p.rapidapi.com/ocr", headers=HEADERS,
                          files={"image": f}, timeout=60)
    r.raise_for_status()
    return r.json()["body"]["annotations"]


def box(word):
    xs = [p["x"] for p in word["boundingPoly"]]
    ys = [p["y"] for p in word["boundingPoly"]]
    return min(xs), min(ys), max(xs), max(ys)


def find_terms(words):
    """Return (kind, [words]) for dates, dollar amounts and periods like (60) days."""
    texts = [w["text"] for w in words]
    terms, i = [], 0
    while i < len(words):
        t = texts[i]
        nxt = texts[i + 1:i + 4]
        if t in MONTHS and len(nxt) == 3 and nxt[0].isdigit() and re.fullmatch(r"\d{4}", nxt[2]):
            terms.append(("date", words[i:i + 4]))
            i += 4
        elif t == "$" and i + 1 < len(words):
            terms.append(("money", words[i:i + 2]))
            i += 2
        elif t == "(" and texts[i + 2:i + 3] == [")"] and texts[i + 3:i + 4] in UNITS:
            terms.append(("period", words[i:i + 4]))
            i += 4
        else:
            i += 1
    return terms


def highlight(path, out_path):
    words = ocr_image(path)
    terms = find_terms(words)
    img = Image.open(path).convert("RGBA")
    layer = Image.new("RGBA", img.size, (0, 0, 0, 0))
    draw = ImageDraw.Draw(layer)
    for kind, group in terms:
        boxes = [box(w) for w in group]
        x0, y0 = min(b[0] for b in boxes), min(b[1] for b in boxes)
        x1, y1 = max(b[2] for b in boxes), max(b[3] for b in boxes)
        draw.rectangle((x0 - 4, y0 - 4, x1 + 4, y1 + 4), fill=COLORS[kind] + (90,))
    Image.alpha_composite(img, layer).convert("RGB").save(out_path, quality=90)
    return [(kind, re.sub(r"(?<=[($]) | (?=[,)])", "", " ".join(w["text"] for w in group)))
            for kind, group in terms]


if __name__ == "__main__":
    for kind, text in highlight(sys.argv[1], "highlighted.jpg"):
        print(f"{kind:<7} {text}")
Enter fullscreen mode Exit fullscreen mode
date    March 3, 2025
period  (12) months
period  (60) days
money   $4,500.00
money   $95.00
period  (30) days
Enter fullscreen mode Exit fullscreen mode

Page one of the scanned agreement with the date, fees and notice periods highlighted


Build a contract register with renewal deadlines

An auto-renewing agreement that nobody cancelled in time runs for another full term. With the extracted fields, a few lines of date math give each contract its current end date and the last day to act. Save this next to contract_ocr.py and put the PDFs in a contracts folder:

import calendar
import csv
from datetime import date, datetime, timedelta
from pathlib import Path

from contract_ocr import extract, ocr_pdf


def parse_date(text):
    return datetime.strptime(text, "%B %d, %Y").date() if text else None


def add_months(d, months):
    m = d.month - 1 + months
    year, month = d.year + m // 12, m % 12 + 1
    return date(year, month, min(d.day, calendar.monthrange(year, month)[1]))


def key_dates(c, today):
    """Return the current end date and the last day to send a notice."""
    start = parse_date(c["start_date"])
    if not start or not c["term"]:
        return None, None
    n, unit = c["term"].split()
    months = int(n) * (12 if unit == "years" else 1)
    end = add_months(start, months)
    while c["auto_renewal"] and end <= today:   # already renewed: move to the current term
        end = add_months(end, months)
    notice = c["renewal_notice_days"]
    act_by = end - timedelta(days=int(notice)) if notice else None
    return end, act_by


today = date.today()
rows = []
for pdf in sorted(Path("contracts").glob("*.pdf")):
    c = extract(ocr_pdf(pdf))
    end, act_by = key_dates(c, today)
    rows.append({
        "file": pdf.name,
        "title": c["title"].title(),
        "parties": " / ".join(p["name"] for p in c["parties"]),
        "start": c["start_date"],
        "end": end.isoformat() if end else "",
        "auto_renewal": c["auto_renewal"],
        "act_by": act_by.isoformat() if act_by else "",
        "governing_law": c["governing_law"],
        "missing_clauses": ", ".join(c["missing_clauses"]),
    })

rows.sort(key=lambda r: r["act_by"] or r["end"])
with open("contract_register.csv", "w", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=rows[0].keys())
    writer.writeheader()
    writer.writerows(rows)

events = []
for r in rows:
    if r["act_by"]:
        day = r["act_by"].replace("-", "")
        events.append("BEGIN:VEVENT\r\n"
                      f"UID:{r['file']}-{day}\r\n"
                      f"DTSTAMP:{today.strftime('%Y%m%d')}T000000Z\r\n"
                      f"DTSTART;VALUE=DATE:{day}\r\n"
                      f"SUMMARY:Notice deadline: {r['title']} ({r['parties']})\r\n"
                      "END:VEVENT\r\n")
Path("deadlines.ics").write_text(
    "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//contract-register//EN\r\n"
    + "".join(events) + "END:VCALENDAR\r\n")

for r in rows:
    print(f"{r['title']:<38} end {r['end']}  act by {r['act_by'] or '-':<10}  "
          f"missing: {r['missing_clauses'] or '-'}")
Enter fullscreen mode Exit fullscreen mode
Music Production Services Agreement    end 2027-03-03  act by 2027-01-02  missing: indemnification, limitation_of_liability
Commercial Lease Agreement             end 2027-06-01  act by 2027-03-03  missing: confidentiality, limitation_of_liability
Mutual Nondisclosure Agreement         end 2027-09-15  act by -           missing: indemnification
Enter fullscreen mode Exit fullscreen mode

Contract register with the notice deadline and missing clauses of each contract

The three PDFs were processed in 3.0 seconds. The services agreement started on March 3, 2025 and already renewed once, so the script moves it to the current term ending March 3, 2027; notice to stop the next renewal is due by January 2, 2027. The script also writes contract_register.csv for spreadsheets and deadlines.ics for Google Calendar or Outlook.


Test on a real archive: a 1960 permit file

Real archives are messier than templates. We used a public domain file from the U.S. Bureau of Mines: a 1960 permit letting the Indian Arts and Crafts Board use space in a laboratory building in Douglas, Alaska, for $75.00 a month. The six scanned pages contain three documents: the signed permit, a cover memo and an unsigned draft.

The OCR read the typewritten text, the stamped dates (APR 5 1960) and even the name written in pen at the top of page 1, in 6.2 seconds for the six pages. A permit gets its own field patterns, and the pages are first grouped from the opening sentence of each permit to its signature block, which leaves the memo out:

import json
import re
import sys

from contract_ocr import DATE, first, flatten, ocr_pdf

STAMP = r"[A-Z]{3} \d{1,2} \d{4}"  # date stamps like APR 5 1960
PERMIT_FIELDS = {
    "grantee": r"The (.+?), Department of the Interior, is hereby granted a permit",
    "start_date": rf"beginning ({DATE})",
    "duration": r"(continuing indefinitely, but revocable at will)",
    "fee": r"(\$[\d,]+\.\d{2} per month)",
    "location": r"located (on .+?), at the",
}


def split_documents(pages, start_marker, end_pattern):
    """Group pages into documents: from the opening sentence to the signature block."""
    docs, current = [], None
    for number, page in enumerate(pages, 1):
        if start_marker in " ".join(page["fullText"].split()):  # ignore line breaks
            current = {"first_page": number, "pages": []}
        if current is not None:
            current["pages"].append(page)
            if re.search(end_pattern, page["fullText"]):
                docs.append(current)
                current = None
    return docs


pages = ocr_pdf(sys.argv[1])
docs = split_documents(pages, "hereby granted a permit",
                       r"\(Signed\)|\(Signature and Title\)")
print(f"{len(pages)} pages, {len(docs)} permits found")

for doc in docs:
    raw = "\n".join(p["fullText"] for p in doc["pages"])
    text = flatten(doc["pages"])
    fields = {name: first(rx, text) for name, rx in PERMIT_FIELDS.items()}
    fields["pages"] = f"{doc['first_page']}-{doc['first_page'] + len(doc['pages']) - 1}"
    fields["signed_by"] = [f"{name} ({title})" for name, title in
                           re.findall(r"\(Signed\) (.+)\n(.+)", raw)]
    fields["signed_on"] = sorted(set(re.findall(STAMP, raw)))
    fields["status"] = "signed" if fields["signed_by"] else "unsigned draft"
    print(json.dumps(fields, indent=2))
Enter fullscreen mode Exit fullscreen mode
6 pages, 2 permits found
{
  "grantee": "Indian Arts and Crafts Board",
  "start_date": "March 1, 1960",
  "duration": "continuing indefinitely, but revocable at will",
  "fee": "$75.00 per month",
  "location": "on Juneau Island adjacent to the town of Douglas, Alaska",
  "pages": "1-2",
  "signed_by": [
    "Marling J. Ankeny (Director, Bureau of Mines)",
    "J. Edw. Davis (Manager, Indian Arts and Crafts Board)"
  ],
  "signed_on": [
    "APR 5 1960"
  ],
  "status": "signed"
}
{
  "grantee": "Indian Arts and Crafts Board",
  "start_date": "March 1, 1960",
  "duration": "continuing indefinitely, but revocable at will",
  "fee": "$75.00 per month",
  "location": "on Juneau Island adjacent to the town of Douglas, Alaska",
  "pages": "5-6",
  "signed_by": [],
  "signed_on": [],
  "status": "unsigned draft"
}
Enter fullscreen mode Exit fullscreen mode

A 1960 permit file grouped into a signed permit, a skipped cover memo and an unsigned draft

The signed version and the draft come out separately. Reuse the pattern on any archive: one set of field patterns per document type, and a split rule based on how each document starts and ends.


Production tips

  • Keep the scan as the source of truth. Store the page number and word boxes with each field so a reviewer can check it on the original.
  • Review flags, do not auto-decide. Send contracts with missing clauses or no detected end date to a person. The script finds where to look; a lawyer reads the clause.
  • Run OCR once, extract many times. Save the raw API response and rerun new patterns on it without calling the API again.
  • Other documents, same pipeline. See the document OCR API guide for receipts and forms.

Full tutorial with images: OCR Scanned Contracts in Python on ai-engine.net.


Try it on your own contracts: grab a key from the OCR Wizard API page and run contract_ocr.py.

Source of the real file: Lease Agreement, Douglas, Alaska, 1960, U.S. Bureau of Mines (Wikimedia Commons via DPLA, public domain). The other three contracts are samples written for this tutorial.

Top comments (0)