From a scanned PDF to contract data: where the pipeline really breaks
An eighty-page supply contract arrives as a scan. Your goal is to know who the parties are, how long it lasts, how much it costs and which clauses need a lawyer's eye. It can be done, but not with a single model: you need a chain of steps, and the point few people make up front is that an error at the first link is not recovered by any later link. If the OCR reads "3O giomi" instead of "30 giorni" (30 days), neither a duration extractor nor a classification model will find the lost number again.
This article opens the LegalTech series and builds the chain from the beginning: deciding whether you need OCR, extracting entities with rules you can read and test, splitting the text into clauses, measuring how much the OCR gets wrong and understanding where a language model comes in. Two parts of the code were actually run, in Python with the standard library only; the others depend on packages that are not available here and are declared as schemas to adapt, before each block.
An analogy to fix the idea: the pipeline is an assembly line for documents. If the first worker straightens the sheet badly, the second cannot read well even if they are excellent. That is why quality is measured on the final result and, in parallel, on the first station, which is the cheapest to fix.
The six stages and where the errors come from
From file to structured data the document goes through six steps. Each has a typical error, and knowing it in advance tells you where to put the checks.
- Acquisition: the file comes in as a scan, a native PDF, a Word file or an email attachment; the typical error is treating everything as an image.
- Triage and OCR: you decide whether the pixels need reading; the typical error is running OCR on a PDF that already has its text.
- Structuring: the text becomes sections and clauses; the typical error is a cut in the wrong place.
- Entity extraction: parties, dates, amounts, legal references; the typical error is an internal cross-reference mistaken for a statute.
- Classification: which type the clause belongs to; the typical error is high confidence on a clause outside the training domain.
- Output: a JSON for the contract management system; the typical error is losing the position in the text, and with it the ability to show the user where the data point comes from.
The order here is not decorative: swapping two items changes the result, because each stage works on the output of the previous one. That is why it pays to surface errors as early as possible and to keep, for each data point, its position in the text: a lawyer accepts an extraction only if they can see the line it comes from.
Triage: do you really need OCR?
A PDF can contain a text layer (generated by Word or by a management system) or only page images. In the first
case reading the pixels is slow and introduces errors the file did not have; in the second there is no
alternative. The decision is made by counting the characters the PDF library manages to extract. The listing uses
PyMuPDF,
where pagina.get_text() returns the text of the native layer and an empty or nearly empty string on
scans.
import fitz # PyMuPDF
def ha_testo_nativo(percorso_pdf: str, soglia_caratteri_per_pagina: int = 100) -> bool:
"""True if the PDF has a text layer: in that case OCR is not needed."""
with fitz.open(percorso_pdf) as documento:
if len(documento) == 0:
return False
caratteri = sum(len(pagina.get_text()) for pagina in documento)
return caratteri / len(documento) > soglia_caratteri_per_pagina
# Not run: PyMuPDF is not installed on this machine. Schema to adapt.
The function divides the total characters by the number of pages and compares them with a threshold. The value 100 is a project choice, not a standard: a scanned page with a few recognisable stamps can exceed it, and a native contract with many blank pages can stay below it. That is why the threshold must be tuned on a sample of your own files, and a file with native text on only some pages deserves a page-by-page check instead of the average. The output of the check is not a fact about the document: it is a hypothesis that holds until a sample disproves it.
Which OCR engine to choose, and by what criterion
For scans the free starting point is Tesseract: Apache 2.0 licence, an engine based on LSTM networks since version 4.0, language models for over a hundred languages, version 5 stable since 30 November 2021. It runs wherever you want, including on your own server. Managed services exist, for example Amazon Textract, which besides text extract forms and tables with dedicated APIs. I do not publish accuracy or price comparisons: they depend on the quality of your scans and on the price lists of the moment, and only a test on your own files makes them comparable.
The criteria that really matter are three. The first is where the data travels: a contract contains names, amounts and commercial terms, so sending it to an external service is a data-processing decision, to be assessed with the controller and regulated by contract (it is discussed in the article on GDPR). The second is structure: if your contracts are full of tables and forms, an engine that returns them already separated saves you work that with Tesseract you have to write yourself. The third is the cost of an error: if a human always reviews, a free engine with good preprocessing may be enough.
Whichever engine you choose, rasterise the pages at a suitable resolution before reading them. The Tesseract
documentation uses automatic page segmentation (--psm 3) as the default: changing it, for example
for tables or single columns, is a choice to verify with a test, not a rule.
Extracting dates, amounts and references with readable rules
For patterns that have a fixed form (a date written out in full, an amount in euros, "D.Lgs. 36/2023", that is, Italian Legislative Decree 36/2023) deterministic rules beat the model on two fronts: they are explainable and they can be tested with an example. The listing collects the regular expressions by category and discards overlaps, so that "Art. 1341 c.c." (article 1341 of the Italian Civil Code) is not read twice. Each entity carries its label, its text and the start and end positions, so the original can be highlighted. The sample contract is in Italian on purpose: the patterns (month names, "euro", "D.Lgs.") are Italian, and they are part of the experiment.
import re
from dataclasses import dataclass
MESI = "gennaio|febbraio|marzo|aprile|maggio|giugno|luglio|agosto|settembre|ottobre|novembre|dicembre"
PATTERN = {
"LAW_REF": [
r"D\.\s?Lgs\.\s?\d+/\d{4}",
r"[Ll]egge\s+(?:n\.\s*)?\d+/\d{4}",
r"[Aa]rt(?:icolo|\.)\s*\d+(?:\s+c\.c\.|\s+c\.p\.c\.)?",
],
"AMOUNT": [
r"(?:EUR|euro|€)\s*\d{1,3}(?:\.\d{3})*(?:,\d{2})?",
r"\d{1,3}(?:\.\d{3})*,\d{2}\s*(?:EUR|euro|€)",
],
"DATE": [
rf"\d{{1,2}}\s+(?:{MESI})\s+\d{{4}}",
r"\d{2}[/.]\d{2}[/.]\d{4}",
],
"DURATION": [r"\d+\s+(?:mesi|anni|giorni)"],
}
@dataclass(frozen=True)
class Entita:
etichetta: str
testo: str
inizio: int
fine: int
def estrai(testo: str) -> list[Entita]:
trovate: list[Entita] = []
for etichetta, pattern in PATTERN.items():
for p in pattern:
for m in re.finditer(p, testo):
if not any(e.inizio < m.end() and m.start() < e.fine for e in trovate):
trovate.append(Entita(etichetta, m.group(), m.start(), m.end()))
return sorted(trovate, key=lambda e: e.inizio)
if __name__ == "__main__":
# Sample data: an Italian contract (the patterns above are Italian)
campione = ("Il corrispettivo annuo è pari a EUR 150.000,00 ai sensi dell'Art. 1341 c.c. "
"La durata è di 36 mesi a decorrere dal 1 marzo 2026; si applica il D.Lgs. 36/2023. "
"Penale: 2.500,00 euro, come da Art. 5 del presente contratto. Firma del 15/03/2026.")
for e in estrai(campione):
print(f"{e.etichetta:<9} {e.testo!r} [{e.inizio}:{e.fine}]")
# Output (run):
# AMOUNT 'EUR 150.000,00' [32:46]
# LAW_REF 'Art. 1341 c.c.' [61:75]
# DURATION '36 mesi' [91:98]
# DATE '1 marzo 2026' [115:127]
# LAW_REF 'D.Lgs. 36/2023' [143:157]
# AMOUNT '2.500,00 euro' [167:180]
# LAW_REF 'Art. 5' [190:196]
# DATE '15/03/2026' [231:241]
In the output the entities are all right, except for a choice the rules cannot make: Art. 5 is a
reference to another article of the same contract, not to a statute, but it has the same form as
Art. 1341 c.c. and gets the same label. The "c.c." suffix tells the cases apart, but it is not
always present. The solution is not a cleverer regex: it is to use structuring (stage 3) to know that "Art. 5"
appears among the clauses of the document and to treat it as an internal reference. Other limits to know about:
amounts in English format ($2,500.00) are not covered, and a date such as "1° marzo" loses the year.
A caution about statutes: the code recognises the form "D.Lgs. 36/2023", it does not know whether it exists or whether it is still in force. A system that shows a legal reference to a user must verify it against a primary source (for Italy, Normattiva, the official database of Italian legislation) and tell the user that the extraction is an aid, not legal advice.
Splitting the text into clauses and measuring the OCR
Language models work on small units of text: one clause at a time, not a whole contract. The segmenter cuts
before every line that starts like a clause ("Art. 2", "3.", "3.1 Title"). The re.M flag makes
^ match at the start of every line, and the length filter removes fragments too short to be
clauses. The second piece of the listing is the cer function: it computes the Character Error
Rate, that is, the Levenshtein distance between the reference text and the OCR text divided by the length
of the reference.
import re
INIZIO_CLAUSOLA = re.compile(r"^(?:Art(?:icolo|\.)\s*\d+|\d+(?:\.\d+)*[.)]?\s+[A-ZÈ])", re.M)
def segmenta(testo: str, minimo: int = 40) -> list[str]:
"""Cuts the text before every line that starts like a clause."""
posizioni = [m.start() for m in INIZIO_CLAUSOLA.finditer(testo)]
if not posizioni:
return [testo.strip()]
pezzi = [testo[a:b].strip() for a, b in zip(posizioni, posizioni[1:] + [len(testo)])]
premessa = testo[: posizioni[0]].strip()
if premessa:
pezzi.insert(0, premessa)
return [p for p in pezzi if len(p) >= minimo]
def cer(riferimento: str, ocr: str) -> float:
"""Character Error Rate: Levenshtein distance / length of the reference."""
prec = list(range(len(ocr) + 1))
for i, a in enumerate(riferimento, 1):
corr = [i]
for j, b in enumerate(ocr, 1):
corr.append(min(prec[j] + 1, corr[j - 1] + 1, prec[j - 1] + (a != b)))
prec = corr
return prec[-1] / len(riferimento)
if __name__ == "__main__":
# Sample data: an Italian contract (the clause pattern is the same in any language)
contratto = """Contratto di fornitura tra Acme S.p.A. e Beta S.r.l.
Art. 1 Oggetto. Il Fornitore consegna al Cliente i prodotti elencati nell'Allegato A.
Art. 2 Durata. Il contratto dura 36 mesi dalla firma ed è rinnovabile.
3. Riservatezza. Le parti non divulgano le informazioni riservate per 5 anni.
3.1 Eccezioni. Non è vietata la comunicazione imposta da un'autorità."""
for i, c in enumerate(segmenta(contratto), 1):
print(i, c[:48])
esatto = "Il Fornitore consegna entro 30 giorni."
ocr = "Il Fornitore consegna entro 3O giomi."
print(f"CER = {cer(esatto, ocr):.3f}")
# Output (run):
# 1 Contratto di fornitura tra Acme S.p.A. e Beta S.
# 2 Art. 1 Oggetto. Il Fornitore consegna al Cliente
# 3 Art. 2 Durata. Il contratto dura 36 mesi dalla f
# 4 3. Riservatezza. Le parti non divulgano le infor
# 5 3.1 Eccezioni. Non è vietata la comunicazione im
# CER = 0.079
The sample contract (in Italian: a supply contract between Acme and Beta, with clauses on subject matter, duration, confidentiality and exceptions) produces five pieces: the preamble and the four clauses, with "3.1" recognised as a clause of its own thanks to the optional final dot in the expression. The number that matters is the last one: "30 giorni" read as "3O giomi" has three errors over 38 characters, that is 0.079. Almost 8% seems small, but the wrong character is exactly the number the duration extractor is looking for. That is why the CER is measured on a sample of pages transcribed by hand from your documents, and thresholds taken from a generic table are not accepted: the right threshold is the one below which downstream extraction stops working.
The segmenter has limits too: a line that starts with a number followed by a capital letter, such as "36 Mesi…" in a list, is mistaken for a clause. On real contracts you test on a sample and compare with the cut made by a human.
Where the model comes in: classifying clauses
Rules are not enough when the meaning depends on context: "The parties may not assign the contract" is a ban on assignment, but no regular expression understands it in all the forms in which it is written. This is where a trained model is used. The work of Chalkidis and colleagues released LEGAL-BERT, a family of BERT models for legal texts in English, pretrained on 12 GB of legal text (legislation, court decisions, contracts). The same research shows that adapting BERT to a domain is not always done the way it is taken for granted: you need to compare the strategies on your own task.
For training and evaluation there is a public benchmark, CUAD: 510 contracts, 13,101 clauses annotated by experts, 41 categories. Pay attention to how it is built: it is not a "text → label" dataset, but a task of extracting spans of text, in question-and-answer style (the model indicates the start and end of the relevant part for a category). Turning it into classification requires preparation work that is up to you, and it is English and American: for Italian contracts you need Italian examples annotated by Italian lawyers.
import torch
from transformers import AutoModelForSequenceClassification, AutoTokenizer
NOME_MODELLO = "nlpaueb/legal-bert-base-uncased" # English model: for Italian you need another one
ETICHETTE = ["termination", "indemnification", "confidentiality", "governing_law", "other"]
tokenizer = AutoTokenizer.from_pretrained(NOME_MODELLO)
modello = AutoModelForSequenceClassification.from_pretrained(
NOME_MODELLO, num_labels=len(ETICHETTE)
) # the classification head starts with random weights: train it on YOUR examples
def classifica(clausola: str) -> tuple[str, float]:
ingresso = tokenizer(clausola, truncation=True, max_length=512, return_tensors="pt")
with torch.no_grad():
probabilita = modello(**ingresso).logits.softmax(dim=-1)[0]
indice = int(probabilita.argmax())
return ETICHETTE[indice], float(probabilita[indice])
# Not run: torch and transformers are not installed on this machine. Schema to adapt.
In the schema the point not to miss is the comment on the classification head: when you load the model with a
num_labels different from the original, the weights of the last layer start random, and a
classification before training is noise with an air of confidence. truncation=True with
max_length=512 silently cuts clauses longer than 512 tokens: the reason why segmentation comes
before classification, and why very long clauses must be split instead of truncated. The probability returned
by softmax is not a probability of being correct: on text unlike what was seen in training it can
be very high and wrong.
What to measure, and when to stop
Measure each stage with its own metric: CER for the OCR, precision and recall for the entities, F1 for the classes, and in the end an outcome measure, that is the percentage of extractions the reviewer accepts without correcting. The "acceptable" and "excellent" thresholds that circulate in presentations are not standards: the useful threshold is the one below which the reviewer spends more time correcting than reading from scratch.
- Start from a single type of contract (an NDA, a supply contract) and a single task (the expiry date).
- Keep, for each data point, its position in the text and the page.
- Always put a human in to confirm, and record their corrections.
- Measure again when the models or the type of documents change.
The four items have a common root: the system is an aid to review, not a substitute. Narrowing the use case makes the error measurable; keeping the positions makes the data point verifiable; human confirmation turns every correction into new examples for the model. Integration with company systems is covered in the article on data integration patterns.
What you can do now
You can decide whether a PDF needs OCR and where to tune the threshold, extract dates, amounts and references with rules you can test and whose failure points you know, split a contract into clauses, and compute the CER on a sample. You also know where the model steps in and why its "confidence" is not proof. In the next article the same material becomes an archive problem: the architecture of an e-discovery platform, where the same documents have to be indexed and searched thousands at a time; for searching case law there is instead the search engine with embeddings.
Frequently asked questions
When is OCR not needed on a contract?
When the PDF already has a text layer, as happens with files exported from Word or from a management system. You check by counting the characters extracted per page with a PDF library: if there are many, you read the native text, which is faster and free of OCR errors.
Rules or a language model for extracting entities?
Rules for what has a fixed form, such as dates, amounts and references to statutes: they are explainable and can be tested with examples. The model is needed when the meaning depends on context, for example to recognise a ban on assignment written in a thousand ways. The two approaches can be combined.
Does a model trained on CUAD work on Italian contracts?
There is no reason to expect it to: CUAD contains commercial contracts in English and the LEGAL-BERT models are trained on English text. For Italian you need models suited to the language and examples annotated by Italian lawyers, verified on a sample.
Sources
- CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review - 510 contracts, 13,101 annotated clauses, 41 categories and the formulation as extraction of text spans, text of the paper read on 2026-11-12
- LEGAL-BERT: The Muppets straight out of Law School - the 12 GB of English legal corpus and the three strategies for adapting BERT, text of the paper read on 2026-11-12
- Tesseract User Manual - Apache 2.0 licence, LSTM engine since 4.0, version 5.0.0 of 30 November 2021, consulted on 2026-11-12
- Tesseract: Command Line Usage -
--psm 3as the default segmentation and--oem 1for the LSTM engine alone, consulted on 2026-11-12 - PyMuPDF: Text recipes -
Page.get_text()on the native text layer, consulted on 2026-11-12 - Amazon Textract: What is Amazon Textract - extraction of text, forms and tables with dedicated APIs, consulted on 2026-11-12
- Normattiva: D.Lgs. 31 marzo 2023, n. 36 (Italian Legislative Decree of 31 March 2023, no. 36) - existence of the act used as an example of a legal reference, consulted on 2026-11-12; its being in force was not verified
The two listings marked "Output (run)" were run with Python 3 and the standard library only, and the outputs shown are the real ones; the other two, which require PyMuPDF, torch and transformers, were not run. The CER figures come from the listing itself (3 errors over 38 characters). No step of this pipeline constitutes legal advice: the extractions must be reviewed by a professional.
Commenti
Caricamento commenti...
Sign in to comment