Ir para o conteúdo

tempest_fastapi_sdk.text

Busca aproximada de texto sem modelo: normalização, distância de edição e lookup fuzzy.

« IA e visão computacional


text

Text matching without a model: normalization, edit distance, fuzzy lookup.

For "what did the user mean?" over a known list of names — cities, products, categories — lexical matching answers faster and more predictably than an embedding model: no weights, no GPU, a typo costs one edit. Semantic search over free-form passages lives in :mod:tempest_fastapi_sdk.genai (Embedder, Retriever, HybridRetriever).

  • :func:normalize_text / :func:strip_accents / :func:tokenize — one canonical form (no accents, case folded, punctuation as spaces), tokens with their offsets in the original string.
  • :func:levenshtein / :func:similarity / :func:trigrams — edit distance with adjacent swaps, the 0..1 ratio, the trigram set.
  • :class:FuzzyIndex — names to values, exact and typo-tolerant search through a trigram index.

No dependency beyond the standard library.

FuzzyIndex

FuzzyIndex(entries: Iterable[tuple[str, T]] = ())

Names mapped to values, searchable exactly and with typos.

Keys are normalized with :func:~tempest_fastapi_sdk.text.normalize_text on the way in and on every query, so "São Paulo", "sao paulo" and "SAO PAULO" are one key. One key may hold several values (two towns with the same name); every value comes back.

Example::

index = FuzzyIndex([("São Paulo", 1), ("Santos", 2)])
index.search("sao paolo")[0].value  # 1

Build the index.

Parameters:

Name Type Description Default
entries Iterable[tuple[str, T]]

(name, value) pairs.

()

add

add(name: str, value: T) -> None

Store value under name.

Parameters:

Name Type Description Default
name str

The name, normalized here. A name that normalizes to an empty string is ignored.

required
value T

The value to return for it.

required

exact

exact(query: str) -> list[T]

Return the values whose name normalizes to the query's.

Parameters:

Name Type Description Default
query str

The name to look up.

required

Returns:

Type Description
list[T]

list[T]: The values, in insertion order; empty when none.

search

search(
    query: str, *, limit: int | None = 5, cutoff: float = 0.8
) -> list[FuzzyMatch[T]]

Return the entries whose name is at least cutoff similar.

Parameters:

Name Type Description Default
query str

What the user typed.

required
limit int | None

Most matches to return; None for all.

5
cutoff float

Lowest similarity accepted, in (0, 1]. 0.8 accepts one edit in five letters.

0.8

Returns:

Type Description
list[FuzzyMatch[T]]

list[FuzzyMatch[T]]: Best first; ties by key. One match per

list[FuzzyMatch[T]]

value, so a key holding two values yields two matches with the

list[FuzzyMatch[T]]

same score.

Raises:

Type Description
ValueError

When cutoff is outside (0, 1].

FuzzyMatch dataclass

FuzzyMatch(key: str, value: T, score: float)

One entry that matched a query.

Attributes:

Name Type Description
key str

The normalized name that matched.

value T

The value stored under it.

score float

1.0 for an exact match, lower for each edit (:func:~tempest_fastapi_sdk.text.similarity).

Token dataclass

Token(text: str, start: int, end: int, original: str)

One normalized word and where it sits in the original text.

Attributes:

Name Type Description
text str

The normalized word (:func:normalize_text of it).

start int

Offset of its first character in the original string.

end int

Offset just past its last character.

original str

The word as written, original[start:end].

max_edits

max_edits(length: int, cutoff: float) -> int

Return the most edits a query of length may have at cutoff.

similarity = 1 - d / L with L the longer length, and L is at most length + d, so d <= (1 - cutoff) * length / cutoff.

Parameters:

Name Type Description Default
length int

The normalized query length.

required
cutoff float

The lowest similarity accepted, in (0, 1].

required

Returns:

Name Type Description
int int

The bound on the edit distance.

normalize_text

normalize_text(text: str) -> str

Return the canonical form used for matching.

Accents stripped (:func:strip_accents), case folded, every run of characters that is not a letter or digit replaced by one space, and the ends trimmed: " São José-dos Campos/SP " -> "sao jose dos campos sp".

Parameters:

Name Type Description Default
text str

Any string.

required

Returns:

Name Type Description
str str

The normalized string; empty when text has no letter or

str

digit.

strip_accents

strip_accents(text: str) -> str

Remove combining marks: "São Tomé" -> "Sao Tome".

Decomposes to NFKD and drops every combining character, so a letter keeps its base and loses its accent; "ç" becomes "c".

Parameters:

Name Type Description Default
text str

Any string.

required

Returns:

Name Type Description
str str

The string without combining marks.

tokenize

tokenize(text: str) -> list[Token]

Split text into normalized words with their original offsets.

Parameters:

Name Type Description Default
text str

Any string.

required

Returns:

Type Description
list[Token]

list[Token]: One token per run of letters or digits, in order. A

list[Token]

word whose normalized form is empty (a lone combining mark) is

list[Token]

skipped.

levenshtein

levenshtein(left: str, right: str, *, limit: int | None = None) -> int

Return the edit distance between two strings.

Insert, delete and substitute cost one each, and so does swapping two adjacent characters ("paolo" -> "paulo" is one substitution, "soa" -> "sao" one swap): the optimal-string-alignment distance, which matches the way people mistype.

Parameters:

Name Type Description Default
left str

One string.

required
right str

The other.

required
limit int | None

Stop early and return limit + 1 once every path is already longer than limit. With a limit only the cells within limit of the diagonal are computed (no path that leaves that band can come back under the limit), so the cost is O(len * limit) instead of O(len * len). None computes the exact distance.

None

Returns:

Name Type Description
int int

The number of edits; limit + 1 when limit is given and

int

exceeded.

trigrams

trigrams(text: str) -> frozenset[str]

Return the set of three-character slices of text (padded).

The string is padded with one space on each side, so the first and last letters take part ("rio" -> {" ri", "rio", "io "}) and even a one- or two-letter string has a trigram.

Parameters:

Name Type Description Default
text str

A normalized string.

required

Returns:

Type Description
frozenset[str]

frozenset[str]: Its trigrams.