How to classify documents automatically
Updated · Tested with Python 3.13, pypdf 7.2.0
In short
Classify business documents by the labels they carry: an invoice says "Invoice number" and "Total due". Count how many of each kind's labels a file contains, pick the best, and return "none" when no kind scores high enough. That needs no training. Use a trained model or a language model for free text with no fixed labels.
Documents rarely arrive sorted. An inbox or an upload folder holds invoices, statements, forms and letters together, and before you can extract anything you have to know what each file is. Classification is that first step: given a document, name its kind.
There are three ways to do it. They trade setup effort against how much variety they can handle.
| Method | Setup | Handles | Can explain itself |
|---|---|---|---|
| Labels on the page | A list of phrases per kind | Documents with stable wording: forms, invoices, statements | Yes |
| A trained model | Dozens to hundreds of labelled examples per kind | Free text with no fixed phrases: letters, emails | Poorly |
| A language model | A prompt listing the kinds | Almost anything | Somewhat |
Method 1: labels on the page
Business documents announce themselves. An invoice says "Invoice number" and "Total due". A registry extract says "Company number" and "Share capital". If you know the labels each kind carries, you can count how many of them a file contains.
from pypdf import PdfReader
kinds = {
"invoice": ["Invoice number", "Invoice date", "Total due", "Bill to"],
"company extract": ["Company name", "Company number", "Registered", "Share capital"],
"operations report": ["Quarterly operations report", "third quarter", "Next quarter"],
}
def classify(path, threshold=0.6):
text = PdfReader(path).pages[0].extract_text()
scores = {kind: sum(label in text for label in labels) / len(labels) for kind, labels in kinds.items()}
best = max(scores, key=scores.get)
return (best if scores[best] >= threshold else None), scores
for path in ["invoice.pdf", "company-extract.pdf", "report-two-columns.pdf", "form-fillable.pdf"]:
print(path, classify(path))invoice.pdf ('invoice', {'invoice': 1.0, 'company extract': 0.0, 'operations report': 0.0})
company-extract.pdf ('company extract', {'invoice': 0.0, 'company extract': 1.0, 'operations report': 0.0})
report-two-columns.pdf ('operations report', {'invoice': 0.0, 'company extract': 0.0, 'operations report': 1.0})
form-fillable.pdf (None, {'invoice': 0.0, 'company extract': 0.25, 'operations report': 0.0})Three files are named correctly with full scores. The fourth, a registration form, matches one label of four ("Company number") and is correctly left unnamed. That None is the most important part of the code.
Always allow "none of these". A classifier forced to pick will put every unknown document into its nearest kind, and the extraction that follows will produce nonsense. A threshold turns "I don't know" into an answer.
Twenty lines, no training, and you can see exactly why each file was named as it was. The limits:
- Scans. A scanned page has no text, so every score is zero. Run OCR first.
- Kinds that share labels. Two suppliers' invoices carry the same words. Tell them apart with a phrase only one has, such as the supplier's name.
- Free text. A complaint letter and a thank-you letter share no fixed labels.
Method 2: a trained model
When there are no stable phrases, train a text classifier: collect labelled examples of each kind, dozens at least and preferably hundreds, and fit a model. Classic ones, such as logistic regression over word counts, are fast, cheap to run and good enough for many jobs.
The cost is the labelled examples, and the upkeep: each new kind needs its own, and the model has to be retrained and re-checked when your documents drift.
Method 3: a language model
Give a language model the text of the document and the list of kinds, and ask for one of them. It needs no examples and handles kinds described in a sentence. It is the practical choice when kinds are many, fuzzy, or change often.
Its costs are the usual ones: you pay for every document, it takes seconds, the same file may not always get the same answer, and it will pick something unless you tell it firmly that "none" is allowed.
Measure it before you trust it
Take a few hundred real documents whose kind you know, run them through, and count. Two numbers matter per kind: of the files named "invoice", how many were invoices; and of the real invoices, how many were found. Also look at which kinds get confused with which. One pair usually accounts for most of the errors, and one extra distinguishing phrase usually fixes it.
Classify, then extract
Classification is rarely the goal. The usual pipeline is: name the kind, then run the extraction for that kind, then check the values. A wrong name at the first step wastes the rest, which is why a careful "none" is worth more than a few points of accuracy.
Classification in 100sands
100sands classifies by method 1, against the document types you have set up: it compares a file with phrases typical of each type, and you can add phrases of your own. Send a file to /v1/classify, or drop it in the app, and it reports which of your live document types the file is, with a score from 0 to 1. There is nothing to train. With extract=true it returns the matched type's fields as well:
curl "https://api.100sands.com/v1/classify?extract=true" \
-H "Authorization: Bearer $SANDS_API_KEY" \
-F [email protected]The response has this shape:
{
"result": "matched",
"documentType": { "id": 42, "name": "Company registry extract" },
"score": 0.94,
"candidates": [
{ "id": 42, "name": "Company registry extract", "score": 0.94 },
{ "id": 57, "name": "Supplier invoice", "score": 0.18 }
],
"pages": 3,
"extraction": {
"id": "ext_...",
"documentType": { "id": 42, "name": "Company registry extract" },
"version": 2,
"fileName": "incoming.pdf",
"pages": 3,
"createdAt": "2026-12-04T09:30:00Z",
"fields": { "companyName": "Harbor Lane Logistics Ltd", "companyNumber": "51-482913-6" }
}
}It answers matched, ambiguous when two types fit about equally, or none, so it never forces a choice. It reads PDFs and HTML files that contain text. A scan is refused with status 422 and the code NO_TEXT_IN_FILE, and a refused file does not count toward your plan. The API docs have the details.