Fuzzy number matching for grounded citations

Install grounding skill

By View as Markdown

Graphic explains how numbers can match words in a lookup for a document. In this case 14 = fourteen

Why correct citations look wrong

A model reads a contract that says refunds are issued within “fourteen days”. It answers your question and quotes the source as “Refunds are issued within 14 days”. The answer is right. But when you try to find that quote in the PDF to prove it, an exact text search comes back empty.

That gap matters and in a citation-checking pipeline, an empty search means the claim gets flagged as unsupported, sent to a human for review, or worse, counted as a hallucination. Contracts, policies and regulatory filings spell numbers out all the time, so this isn’t an edge case.

The PyMuPDF grounding skill now has an answer: fuzzy=True. It treats numbers written as digits and as words as the same thing, while every other word in the quote still has to match exactly. This post walks through the cookbook notebook that shows it in action, tested with PyMuPDF 2.1.

Setting up

You only need PyMuPDF and the grounding helpers, which live in scripts/grounding.py in the cookbook repository. The notebook uses a local copy if you’re inside a clone, and downloads it otherwise:

import os, sys, urllib.request

LOCAL = "../skills/grounding-skill/scripts/grounding.py"
URL = "https://raw.githubusercontent.com/pymupdf/cookbook/main/skills/grounding-skill/scripts/grounding.py"

if os.path.exists(LOCAL):
    sys.path.insert(0, os.path.dirname(LOCAL))
else:
    urllib.request.urlretrieve(URL, "grounding.py")

import grounding
from grounding import locate, snippet, to_json

Create the Sample Document

For a test document, the notebook generates a one-page services agreement for a fictional company, Northwind, where every number is spelled out: a term of twenty-four months, a fee of two hundred and fifty thousand dollars, ninety-nine per cent availability, refunds within fourteen days. You can swap in any PDF of your own, as long as it has a text layer.

import pymupdf

text = """Northwind Services Agreement

1. Term. This agreement runs for twenty-four months from the effective date and renews for further periods of twelve months unless either party gives ninety days' written notice.

2. Fees. The annual fee is two hundred and fifty thousand dollars, rising by three per cent each year.

3. Refunds. Refunds are issued within fourteen days of a valid request.

4. Service levels. The provider will respond to critical incidents within four hours and maintain availability of ninety-nine per cent.

5. Support. Support is provided in three eight-hour shifts, five days a week.

6. Records. Records are retained for seven years after termination."""

doc = pymupdf.open()
page = doc.new_page()
page.insert_textbox(pymupdf.Rect(72, 72, 523, 770), text, fontsize=11, fontname="helv")
doc.save("northwind_agreement.pdf")

One flag turns a miss into a match

Start with the quote a model might produce when asked how long refunds take. By default, locate() compares text literally, so the digits don’t match the words on the page, open the sample document, ent and try this search quote:

path = "northwind_agreement.pdf"
doc = pymupdf.open(path)
page = doc[0]

quote = "Refunds are issued within 14 days"
locate(page, quote)

Nothing is found.

However, add fuzzy=True and the same call succeeds:

quads = locate(page, quote, fuzzy=True)
print(len(quads), "quads")
# 6 quads

print(to_json([{"claim": None, "cited_text": quote,
                "doc": 0, "page": 0, "quads": quads}])[0])
# {'claim': None, 'cited_text': 'Refunds are issued within 14 days',
#  'found': True, 'page_number': 1, 'rect': [131.3, 202.0, 327.0, 217.1]}

The returned quads cover the words as they’re actually printed, “fourteen” included, so anything you draw from them points at the real text.

Importantly, the flag doesn’t change the normal path. locate() still runs the exact Page.search_for() first. Quotes that match word for word behave exactly as before; the number rules only kick in as a fallback when the exact search finds nothing.

What counts as the same number

Under the hood, both the quote and the page text are normalised before they’re compared: every run of number words collapses into a single number. The notebook tests seven digit-based quotes against the Northwind agreement. The default search finds none of them; fuzzy matching finds all seven.

quotes = [
    "runs for 24 months from the effective date",
    "periods of 12 months unless either party gives 90 days' written notice",
    "The annual fee is 250,000 dollars, rising by 3% each year",
    "The annual fee is 250 thousand dollars",
    "maintain availability of 99 percent",
    "Support is provided in 3 8-hour shifts, 5 days a week",
    "Records are retained for 7 years after termination",
]

for q in quotes:
    print(q, bool(locate(page, q)), bool(locate(page, q, fuzzy=True)))
# every line: False True

Here’s what these quotes match:

On the pageMatches in the quote
fourteen, seven14, 7
twenty-four, ninety-nine (even when split across a line end)24, 99
two hundred and fifty thousand250,000, 250000 or 250 thousand
three per cent, ninety-nine percent3%, 99%, 3 percent
eight-hour8-hour
Note

Matching runs both ways, too. If the model spells a number out and the page uses digits, the quote is still found.

Fuzzy about format, strict about value

A looser search is only useful for verification if it still catches wrong answers. Fuzzy matching changes how a number may be written, never which number it is:

wrong = [
    "Refunds are issued within 30 days",        # page says fourteen
    "maintain availability of 99.9%",           # page says ninety-nine per cent
    "Support is provided in 38-hour shifts",    # page says three eight-hour shifts
    "renews for further periods of 24 months",  # page says twelve
]
for q in wrong:
    print(q, bool(locate(page, q, fuzzy=True)))
# every line: False

The shifts example is the subtle one. “Three eight-hour shifts” is the numbers 3 and 8 side by side, and the normaliser doesn’t glue them into 38. Punctuation also ends a number, so “five, six” stays two numbers. That’s what makes fuzzy=True safe to switch on in a checker: a model that quietly changed 14 to 30 still gets caught.

With Claude citations

ground_citations() takes the same flag:

results = grounding.ground_citations(response, [doc], fuzzy=True)

Claude’s cited_text is copied straight from the document, so it usually matches without help. Fuzzy matching earns its keep where the model writes the quote itself: prompt-based citations from any model, agent outputs, and values extracted into structured fields.

From the command line

The helper script has a --fuzzy flag too. It prints the page number and rectangle as JSON, and exits with status 1 when the quote isn’t found, which makes it easy to drop into a CI check or shell pipeline:

python grounding.py northwind_agreement.pdf --quote "within 14 days" --fuzzy

Result:

{
  "claim": null,
  "cited_text": "within 14 days",
  "found": true,
  "page_number": 1,
  "rect": [229.1, 202.0, 327.0, 217.1]
}

Limits worth knowing

  • Only numbers are normalised. A paraphrased quote still won’t be found, by design. The skill’s rule is never to loosen matching just to force a result.
  • Some forms aren’t covered yet: ordinals (“first” vs “1st”), decimals in words (“four point one”), fractions (“half”), and currency words (“dollars” vs “$”).
  • “One” is always read as a number, on both sides, so “the one that” still matches itself. It only matters if a quote writes “1” where the page means the pronoun.
  • Numbers compare by value, not format, so “250,000” and “250000” are the same.

Try it

If you verify model citations against PDFs, fuzzy=True removes a whole class of false alarms without letting wrong numbers through. To get started:


Discuss This Article with the Community

Have a question, a different approach, or something you built after reading this? Share it on the forum or join the Discord, we'd love to hear from you.

PyMuPDF Logo

© 2026 Artifex Software Inc. All rights reserved.