Tutorial

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

OCR scanned contracts in Python: extract parties, dates, fees and notice periods, flag missing clauses, highlight terms and build a renewal deadline register.

A scanned music production services agreement next to the fields extracted from it: parties, effective date, term, notice period, fee, governing law and missing clauses

This tutorial uses the OCR Wizard API. See the docs, live demo, and pricing.

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 with the OCR Wizard API 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.

What the API Returns on a Scanned Contract

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

python
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]))
text
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").

Each page comes back with fullText, the detected language and annotations, the list of words with their positions. Line breaks follow the printed lines, so a word like then-current can be split over two lines. The first step of the extraction is to join everything into one clean string.

Extract the Key Terms of a Contract

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:

python
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))

Run it on the scanned services agreement with python contract_ocr.py contracts/services_agreement.pdf:

json
{
  "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"
  ]
}

Every value matches the printed contract. Here is how each field is found:

  • 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"). The text between the name and the role (here "a New York limited liability company") is skipped.
  • 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 reliable one to read.
  • Amounts: every dollar figure, with the four words before it as context, so $4,500.00 comes with a monthly retainer of.
  • Missing clauses: a checklist of standard clauses. This agreement has no indemnification and no limitation of liability wording, which is exactly what a reviewer wants to know before signing a renewal.

Your own contracts will use their own phrasing. Add the variants your templates use to the patterns, for example hold harmless next to indemnif, and test them on a few signed documents before running the whole archive.

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 directly on the scan. Save this as highlight_terms.py and run it on a page image:

python
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}")
text
date    March 3, 2025
period  (12) months
period  (60) days
money   $4,500.00
money   $95.00
period  (30) days
Page one of the scanned services agreement with the effective date highlighted in yellow, the two fees in green and the 12 month term and notice periods in blue

The API returns punctuation as separate words (March, 3, ,, 2025), which makes multi-word terms easy to match token by token. The same boxes can feed a review screen where clicking a field in your app scrolls to it on the page.

Build a Contract Register with Renewal Deadlines

A missed renewal notice is a classic contract mistake: 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 as contract_register.py next to contract_ocr.py, and put the PDFs in a contracts folder:

python
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 '-'}")
text
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
Contract register with three cards: the services agreement must be stopped by January 2, 2027, the lease renewal option ends March 3, 2027, and the NDA has no renewal clause, each with its missing clauses

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. To stop the next renewal, notice must be sent 60 days before, by January 2, 2027. The lease does not renew on its own, but the tenant must use the renewal option by March 3, 2027.

The script writes two files: contract_register.csv, which opens in any spreadsheet, and deadlines.ics, which imports into Google Calendar or Outlook so the deadlines show up next to the rest of the team's schedule.

Test on a Real Archive: A 1960 Permit File

Real archives are messier than templates. To check the pipeline on one, 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 of the same permit.

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. The extraction needs two changes. A permit is not phrased like a modern agreement, so it gets its own field patterns. And since one PDF holds several documents, the pages are first grouped from the opening sentence of each permit to its signature block, which leaves the memo out. Save this aspermit_file.py next to contract_ocr.py:

python
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))
json
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"
}
Six scanned pages of a 1960 Bureau of Mines permit file grouped into a signed permit, a cover memo that is skipped and an unsigned draft, with the signature block and the extracted fields

The signed version and the draft come out separately, and the status field tells them apart. This is the pattern to reuse 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 extracted field so a reviewer can check any value on the original in one click.
  • 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 as JSON. When you add a new pattern, rerun the extraction on the saved text without calling the API again.
  • Batch the archive in the background. Process old contracts in a nightly job and new ones at upload, so the register is always current.
  • Use a language model for free-form clauses. Regular expressions are perfect for dates, amounts and notice periods. For questions like "who owns the recordings?", pass the OCR text to a model, as in our ID card to JSON tutorial.
  • Other documents, same pipeline. Receipts, invoices and forms work the same way, see the document OCR API guide and PDF OCR in 5 lines of Python.

Next Step

Get a key on the OCR Wizard API page, save contract_ocr.py, and run it on one of your own scanned contracts to see the fields it extracts. For firms with large archives, custom plans are available.

Sources

Frequently Asked Questions

Can OCR read scanned contracts accurately?
Yes. On the three scanned contracts used in this tutorial, the OCR Wizard API returned every clause, date, dollar amount and notice period exactly as printed, including a word split across two lines. A two-page PDF took about 1.7 seconds. On a real typewritten permit file from 1960, it also read the stamped dates and a name written in pen.
How do I extract the parties and dates from a contract in Python?
Send the scanned PDF to the /ocr-pdf endpoint, join the text of all pages, then read the fields with regular expressions: company names ending in LLC, Inc. or Corp. in the opening paragraph, the role in parentheses after each name, and dates written like March 3, 2025. The contract_ocr.py script in this article does it in about 100 lines.
Can I OCR contracts longer than 10 pages?
Yes. The /ocr-pdf endpoint processes up to 10 pages per request with first_page and last_page. Loop over windows of 10 pages and stop when a window returns fewer than 10 pages, as the ocr_pdf function in this article does.
Does automated contract extraction replace legal review?
No. It removes the typing and gives a reviewer a structured summary, highlighted terms and a list of deadlines. The missing clause check is a keyword check that tells a lawyer where to look first. The legal reading stays with a person.

Ready to Try OCR Wizard?

Check out the full API documentation, live demos, and code samples on the OCR Wizard spotlight page.

Related Articles

Continue learning with these related guides and tutorials.