
Summarize this article using AI
What NER means for customer documents
Textbook NER was built for newswire. The CoNLL-2003 shared task, for example, added a fourth miscellaneous category and released annotated English and German newswire, and many general models still carry that heritage of person, location and organisation labels. Customer documents are different in three ways.
- The interesting fields are not names. Invoice numbers, GSTIN-style tax IDs, purchase order numbers and policy numbers carry most of the business value.
- The label set is yours. Category inventories vary widely by domain: biomedical corpora distinguish genes, proteins and diseases, while legal and financial corpora define their own. You will design the schema with the customer, not download it.
- The text is damaged. OCR output has substituted characters, broken lines and table cells flattened into prose.
NER is only the first step. Turning "Kaveri Textiles Pvt Ltd" and "KAVERI TEXTILES" into one customer record is a separate problem, covered under master data management.
How NER works: spans, labels and BIO tags
Most statistical NER treats extraction as sequence labelling. Formats such as BIO tag each token as beginning an entity, inside one, or outside any, which turns span finding into per-token classification; variants such as BIOES add explicit end and single-token tags.
spaCy uses a close cousin called BILUO (begin, inside, last, unit, outside). Here is the real output for one of our test sentences, converted from character offsets:
text
Credit note CN-2024-0042 raised against INV-2024-0183 ...
('Credit','O') ('note','O') ('CN-2024','B-INVOICE_NO') ('-','I-INVOICE_NO') ('0042','L-INVOICE_NO')
('raised','O') ('against','O') ('INV-2024','B-INVOICE_NO') ('-','I-INVOICE_NO') ('0183','L-INVOICE_NO')
The tokenizer split CN-2024-0042 at the hyphens, which is why token-pattern rules for IDs get fiddly. Matching identifiers with regex on raw text, then snapping to token boundaries, is simpler.
Rules, trained models and LLMs: which one for which field
There is no single best method. Each fits a different kind of field.
Rules. spaCy's documentation says its entity ruler lets you add spans using token-based rules or exact phrase matches, and that it can be combined with the statistical entity recognizer to boost accuracy or used alone as a purely rule-based system. Rules are transparent, need no training data and are quick to fix when a template changes.
Trained models. The spaCy guide says that for complex tasks it is usually better to train a statistical entity recognition model, but because such models need training data, rule-based approaches are often more practical. It also suggests that detecting person or company names may benefit from a statistical model. That matches what we saw below.
LLMs. A language model prompted to return JSON can extract both formatted and free-form fields without training data, which makes it attractive for a first pass on unfamiliar documents. The trade-offs are cost per document, latency, nondeterminism and the need to verify every output against the source text. The reasoning in fine-tuning vs RAG carries over: start with the cheapest approach you can measure.
A tested example: rules vs a general model vs a hybrid
To avoid hand-waving, we ran a small experiment. The dataset is synthetic: twelve short snippets written to resemble Indian business documents, with 52 hand-labelled entities across ten types (invoice, claim, PO and policy numbers; GSTIN; email; amount; date; person; organisation). Two snippets contain deliberate OCR-style errors, such as the letter O in place of a zero. We scored entity-level exact match: a prediction counts only if both span boundaries and label match the gold annotation.
The rule component is a short regex pass converted to spaCy spans:
python
import re, spacy
from spacy.language import Language
RULES = [
("INVOICE_NO", r"\b(?:INV|CN|BL)-(?:\d{4}-)?\d{4,6}\b"),
("GSTIN", r"\b\d{2}[A-Z]{5}\d{4}[A-Z]\d[A-Z][A-Z0-9]\b"),
("EMAIL", r"\b[\w.+-]+@[\w-]+(?:\.[\w-]+)+\b"),
("AMOUNT", r"(?:Rs\.?|INR|₹|USD|\$)\s?\d[\d,]*(?:\.\d{1,2})?"),
]
@Language.component("regex_ner")
def regex_ner(doc):
spans = []
for label, pat in RULES:
for m in re.finditer(pat, doc.text):
sp = doc.char_span(m.start(), m.end(), label=label,
alignment_mode="expand")
if sp is not None:
spans.append(sp)
doc.ents = spacy.util.filter_spans(spans)
return doc
nlp = spacy.blank("en")
nlp.add_pipe("regex_ner")
We compared three setups: the regex rules alone, spaCy's small English model (en_core_web_sm, with its MONEY label mapped to our AMOUNT), and a hybrid that uses rules for every formatted field and keeps the model's PERSON and ORG predictions.
What the numbers show, and what they do not:
- Rules were perfect on the formats we wrote them for, and blind to names. They scored zero on PERSON and ORG.
- The general model missed every custom identifier. It found no invoice, GSTIN, PO, policy or email entities, and stretched spans, for example returning "Kaveri Textiles Pvt Ltd for Rs" as one organisation.
- OCR errors broke the rules. INV-2O24-0191 and 21 Feb 2O24 were missed because the patterns expect digits. The fix is normalisation before extraction, not a looser regex.
- The hybrid did not fix names. Person and organisation F1 stayed at 0.75 and 0.50.
Two caveats. We wrote the rules after seeing the examples, so rule scores are optimistic. And one "false positive" (Lotus Mills) may be an annotation gap. With 52 entities, one change moves a score by several points, so treat this as an illustration of failure patterns, not a benchmark.
Designing the extraction pipeline
A reliable pipeline is more than a model. A common pattern has these stages:
- Ingest and classify. Identify file type and document type. A claim form and a contract need different schemas.
- Text extraction and OCR. Born-digital PDFs give clean text; scans do not. Record OCR confidence where available.
- Normalise. Fix OCR confusions (O and 0) only inside numeric fields, and keep the original text.
- Extract. Run rules for formatted fields and a model or LLM for open-vocabulary fields.
- Validate. Check each field against its schema: date parses, amount is positive, tax ID matches its pattern, invoice total equals the sum of its line items.
- Resolve. Match names to master records.
- Review. Route low-confidence or failed-validation items to a person.
Stages one to three are data engineering, so the habits in AI data pipelines for messy enterprise data and data cleaning for AI projects apply. If the customer runs on Microsoft tooling, the orchestration side looks like customer data pipelines in Azure Data Factory.
Keep each value's character offsets and page reference so reviewers can see the evidence in one click.
How to evaluate NER honestly
Accuracy on a token level hides errors. Most tokens are outside any entity, so a model that tags nothing can still score high token accuracy. Use entity-level precision, recall and F1:
- Precision: of the entities you extracted, how many were right.
- Recall: of the entities that exist, how many you found.
- F1: their harmonic mean.
Exact boundary match is usually right for IDs and amounts, because "INV-2024" is not the invoice number. Report scores per entity type, not just overall: a healthy micro-F1 can hide a weak payment-amount field.
Build the gold set from real customer documents sampled across templates, vendors and scan quality. Have two people label a subset; disagreement shows the schema is ambiguous. Hold out templates you did not tune on, or you will measure memory instead of generalisation.
Agree acceptance thresholds and review ownership with the customer before launch, as described in AI governance.
Privacy, compliance and human review
Customer documents are full of personal and financial data, and extraction output is often more sensitive than the input because it is structured, searchable and easy to join.
- Minimise. Extract only the fields the use case needs.
- Control where text goes. Sending documents to an external LLM API is a data transfer; see HIPAA, GDPR and SOC 2 for the obligations.
- Redact or tokenise identifiers before they reach logs and prompts.
Regulated sectors raise the stakes: clinical forms carry patient identifiers (healthcare AI deployments), and KYC documents carry identity and account data (AI in banking).
Human review is part of the design. Set a confidence threshold, send low-confidence and failed-validation records to a reviewer, and feed corrections back into the gold set. The patterns in guardrails and human-in-the-loop design show how to build that queue so reviewers handle exceptions, not every document.
A hypothetical scenario
This is an illustrative scenario, not a real engagement. An FDE joins a distributor whose accounts payable team keys in supplier invoices by hand. A sample of 200 invoices across the twenty largest suppliers shows that invoice number, date, GSTIN and total are formatted consistently within each supplier but differently across suppliers.
The FDE starts with regex rules and normalisation for those four fields, adds an LLM call only for the supplier name and ship-to address, and validates that line items sum to the total. Anything that fails validation goes to the AP team's review queue. The team then measures entity-level F1 per field on unseen suppliers. The identifier fields hold up, the address field does not, so addresses stay human-verified. The result is a narrower promise the customer can trust.
Frequently Asked Questions
What is named entity recognition?
Named entity recognition is the task of locating spans of text that name real-world entities and assigning each span a category such as person, organisation, date or amount. In business use, the label set is extended with domain fields such as invoice numbers or policy IDs.
What is the difference between NER and information extraction?
NER finds and labels individual mentions. Information extraction is the wider task that also links entities together, for example which amount belongs to which invoice, and captures relations, events and times. NER is usually the first step.
Should I use rules, a trained model or an LLM for NER?
Use rules for fixed-format fields, a trained model or LLM for open-vocabulary fields such as names, and an LLM with a schema for free-form facts. Combine them, validate outputs, and choose by measuring on your own documents.
How do I evaluate an NER system?
Score at the entity level using precision, recall and F1 on exact span-and-label matches, reported per entity type. Build the gold set from real customer documents, label a subset twice to check agreement, and hold out unseen templates.
How does OCR quality affect NER?
Directly. Character errors such as the letter O in place of zero break pattern rules and confuse models. Improve scan quality, normalise known confusions in numeric fields, and route low-confidence pages to review.
Is it safe to send customer documents to an LLM API?
Only if the customer's contracts, regulations and security policies allow it. Check retention and training terms with the provider, minimise and redact what you send, and involve the customer's security team.
Become one of India’s first Forward-Deployed Engineers.
The world is hiring - and this Academy prepares you for it.
