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])) 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 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)) 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" ] } 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}") date March 3, 2025 period (12) months period (60) days money $4,500.00 money $95.00 period (30) days 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(...

