Build an AI Lease Abstraction Pipeline with OCR and an LLM
Commercial lease agreements contain critical information, but extracting it manually can take hours, especially when you're working with hundreds of PDFs, scanned agreements, amendments, and lease exhibits. An AI lease
Commercial lease agreements contain critical information, but extracting it manually can take hours, especially when you're working with hundreds of PDFs, scanned agreements, amendments, and lease exhibits.
An AI lease abstraction pipeline can help automate much of this work by combining Optical Character Recognition (OCR) with a Large Language Model (LLM). OCR converts scanned lease documents into readable text, while an LLM identifies relevant clauses and organizes the extracted information into structured records. In this tutorial, we'll build a basic Python pipeline that reads a scanned lease PDF, extracts its text, identifies important lease terms, and produces a JSON output for further review.
What Does an AI Lease Abstraction Pipeline Do?
An AI lease abstraction pipeline combines document processing, OCR, and language models to convert unstructured lease agreements into structured information.
The pipeline generally follows this sequence:
- Upload or receive a lease agreement in PDF format.
- Convert scanned pages into images.
- Extract text using OCR.
- Pass the extracted content to an LLM.
- Identify important lease terms.
- Validate the extracted fields.
- Export the results into JSON or another structured format.
For this tutorial, we'll use Python, Tesseract OCR, and a locally running LLM through Ollama. This keeps the example accessible without requiring a paid model API.
Step 1: Identify the Lease Information to Extract
Before writing code, define what information the application should identify.
A commercial lease abstraction workflow may need to capture:
- Property and tenant names.
- Landlord information.
- Lease commencement and expiration dates.
- Rentable square footage.
- Base rent.
- Renewal and extension options.
- Expense structures, including NNN and CAM provisions.
- Security deposits.
- Important lease conditions.
Not every lease uses the same terminology or structure. Some agreements contain the relevant information in the main document, while others reference separate exhibits or amendments.
For this example, we'll focus on a basic set of fields that can be extended based on your requirements.
Step 2: Set Up the Python Environment
We'll need a few Python libraries to process PDFs, perform OCR, communicate with the LLM, and validate the extracted information.
Install the dependencies:
pip install pytesseract pdf2image pillow requests pydantic
You'll also need to install:
- Tesseract OCR: The OCR engine that recognizes text from document images.
-
Poppler: Required by
pdf2imageto convert PDF pages into images. - Ollama: Used to run a compatible LLM locally.
After installing Ollama, download a model:
ollama pull llama3.1
Start the Ollama service before running the Python application.
For installation and configuration details, refer to the Tesseract documentation [VERIFY LINK].
Step 3: Extract Text from Lease PDFs Using OCR
Commercial lease documents aren't always searchable PDFs. Some are scanned images, which means ordinary PDF text extraction won't work.
OCR helps convert the scanned pages into machine-readable text.
Create a Python file named lease_ocr.py:
import pytesseract
from pdf2image import convert_from_path
def extract_lease_text(pdf_path):
pages = convert_from_path(
pdf_path,
dpi=250
)
extracted_pages = []
for page_number, image in enumerate(pages, start=1):
text = pytesseract.image_to_string(
image,
lang="eng"
)
extracted_pages.append(
f"[PAGE {page_number}]\n{text}"
)
return "\n\n".join(extracted_pages)
if __name__ == "__main__":
text = extract_lease_text("sample_lease.pdf")
with open("lease_text.txt", "w", encoding="utf-8") as file:
file.write(text)
print("OCR extraction completed.")
The script converts each PDF page into an image and runs OCR to identify its text.
Page markers are included intentionally. They help preserve the original document structure and make it easier to trace extracted information back to its source.
One practical consideration: OCR accuracy depends on document quality. Low-resolution scans, handwritten notes, unusual fonts, and complex tables may require additional image preprocessing or a document-focused OCR service.
Step 4: Define a Structured Lease Data Schema
Sending extracted text directly to an LLM and accepting whatever it returns isn't a reliable abstraction process.
You need to define the expected output.
For this tutorial, we'll use Pydantic to validate the structure of the LLM response.
from pydantic import BaseModel
from typing import Optional
class ExtractedField(BaseModel):
value: Optional[str] = None
evidence: Optional[str] = None
page: Optional[int] = None
class LeaseAbstraction(BaseModel):
fields: dict[str, ExtractedField]
review_notes: list[str] = []
Each extracted field contains three components:
-
value: The identified lease information. -
evidence: A supporting text excerpt from the document. -
page: The page where the information appears.
This structure is useful because it allows reviewers to examine the extracted value alongside its supporting evidence.
For example, a commencement date shouldn't be accepted simply because the LLM generated a date. The system should retain the relevant lease language for verification.
Step 5: Use an LLM to Identify Lease Terms
Now we'll connect the OCR output to a language model.
The LLM will receive the extracted lease text and return the requested information in JSON format.
Create a second file called lease_extract.py:
import json
import requests
from lease_ocr import extract_lease_text
from pydantic import ValidationError
from lease_schema import LeaseAbstraction
OLLAMA_URL = "http://localhost:11434/api/chat"
MODEL = "llama3.1"
def extract_lease_data(lease_text):
prompt = f"""
You are a commercial lease document analyst.
Extract the following information:
property_name
tenant_name
landlord_name
commencement_date
expiration_date
rentable_area_sf
base_rent
renewal_options
expense_structure
security_deposit
Return valid JSON with this structure:
{{
"fields": {{
"field_name": {{
"value": "extracted value or null",
"evidence": "supporting text or null",
"page": 1
}}
}},
"review_notes": []
}}
Rules:
- Use only information found in the document.
- Never invent missing lease terms.
- Return null when a value cannot be established.
- Include supporting text for extracted values.
- Preserve relevant units and currency.
- Identify unclear or conflicting information
in review_notes.
- Do not provide legal interpretations.
LEASE DOCUMENT:
{lease_text}
"""
response = requests.post(
OLLAMA_URL,
json={
"model": MODEL,
"messages": [
{
"role": "user",
"content": prompt
}
],
"format": "json",
"stream": False
},
timeout=300
)
response.raise_for_status()
result = response.json()
return json.loads(
result["message"]["content"]
)
if __name__ == "__main__":
lease_text = extract_lease_text("sample_lease.pdf")
try:
extracted_data = extract_lease_data(lease_text)
validated_data = LeaseAbstraction.model_validate(
extracted_data
)
with open(
"lease_abstraction.json",
"w",
encoding="utf-8"
) as file:
file.write(
validated_data.model_dump_json(indent=2)
)
print("Lease abstraction completed.")
except (ValidationError, ValueError) as error:
print("Extraction requires review:", error)
Save the schema from Step 4 in a separate file named lease_schema.py.
The application now performs three main tasks: OCR extraction, LLM-based field identification, and structured output validation.
The model is instructed to return null when information is missing rather than filling gaps with assumptions.
Step 6: Review and Validate the Extracted Results
An LLM-generated response shouldn't automatically become an approved lease record.
Commercial lease agreements can contain complex conditions, and a small extraction error can affect downstream reporting or financial workflows.
For example, a document might contain:
- Original lease expiration date.
- An amendment extending the lease.
- A separate renewal option.
- Different rent commencement and lease commencement dates.
A basic extraction system may confuse these values unless the prompt and validation rules account for their context.
A useful review process should check:
- Whether extracted dates match the supporting lease language.
- Whether rent values include the correct currency and payment period.
- Whether square footage is identified correctly.
- Whether NNN and CAM obligations are interpreted from the correct clauses.
- Whether amendments override or modify original lease terms.
- Whether supporting evidence and page references are available.
For production applications, add field-level confidence checks, document version tracking, exception handling, and human approval before extracted information enters an authoritative lease record.
What Could Go Wrong?
Even a well-designed OCR and LLM pipeline has limitations.
Poor OCR output: Blurry scans and complex layouts can produce incorrect text. Improve image quality or use a document OCR service that preserves layout and table relationships.
Incorrect clause interpretation: An LLM may confuse an option date with an actual expiration date. Include contextual instructions and require evidence for important fields.
Missing information: Some details may exist only in amendments or exhibits. Process related documents together and retain their individual source references.
Inconsistent output: LLM responses may omit fields or return unexpected values. Validate the output against a defined schema and send invalid records for review.
Large documents: Sending an entire lease package in one request may exceed the model's context capacity. Use page-aware processing or clause-based document chunking, while preserving relevant context across sections.
The biggest limitation is that automated extraction isn't the same as legal or financial validation. Human review remains necessary for material lease obligations and critical data.
Conclusion
Building an AI lease abstraction pipeline with OCR and an LLM involves more than extracting text from a PDF. You need structured data definitions, contextual clause identification, evidence tracking, and validation to make the results useful for commercial real estate operations.
The Python example provides a starting point that can be extended with better document classification, amendment comparison, confidence scoring, and integration with property management workflows.
For CRE technology teams, the real objective is to turn lease information into structured, reviewable data that supports day-to-day property operations.
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes โ full credit and traffic to the original publisher.