DEV Community

Cover image for arabic-normalize: configurable Arabic text normalization for search, in Rust and Python
Abdeldjalil Chougui
Abdeldjalil Chougui

Posted on Originally published at abdeldjalilchougui.biz

arabic-normalize: configurable Arabic text normalization for search, in Rust and Python

Type احمد in a search box and the record saved as أحمد does not show up. Search for مدرسة and miss مدرسه. Paste a word from a PDF and it fails to match the same word typed on a keyboard, because the pasted one carries an invisible direction mark. Arabic text that looks identical to a reader is often different to a computer.

There are several sources of this. Diacritics (harakat) are optional, so مَدْرَسَة and مدرسة are the same word in two byte sequences. The alef has four common forms, أ إ آ ا, and people do not type them consistently. The tatweel ـ stretches a word for decoration. Digits come in Western, Arabic-Indic and Persian shapes. And copied text brings zero-width and bidi control characters that nobody sees.

The fix is normalization: bring both the stored text and the query to one canonical form before comparing. arabic-normalize is a Rust library, with Python bindings, that does this. It is configurable, because not every project wants the same level of folding.

What it does

Removes what does not matter for matching. Diacritics (harakat, tanwin, shadda, sukun, dagger alef, Quranic marks) and the tatweel are dropped.

Unifies alef forms. أ إ آ ٱ all become ا.

Optional letter folding. You can also turn on ى → ي, ة → ه, ؤ → و and ئ → ي. These are off by default for a good reason, explained below.

Persian and Urdu letters. An optional mapping turns ک into ك, ی ے into ي, and ۀ ہ ھ into ه. This matters because some keyboards and fonts produce the Persian kaf and yeh, which look like the Arabic ones.

Digits. Arabic-Indic ٠-٩ and Persian ۰-۹ can be converted to Western 0-9, or the other way.

Invisible characters. Zero-width and bidi control characters (ZWNJ, ZWJ, LRM, RLM, ALM, BOM) are stripped.

Light stemming for search. A Light10 stemmer strips common prefixes and suffixes, so والمكتبات becomes مكتب.

A fast path that allocates nothing. Text that needs no change comes back as Cow::Borrowed, with no allocation. Pure-ASCII input is detected with one SIMD-friendly check.

Conservative defaults

The default configuration only does the safe things: diacritics, tatweel, alef forms and invisible marks. Letters that can change meaning, ة/ه, ى/ي and the hamza seats, are only changed when you ask for it, or when you use the search() preset, which turns everything on.

That split is the main design decision. Folding ة into ه is fine for a search index, where both sides get the same treatment. It is wrong if you plan to show the normalized text to a user or store it as the cleaned version.

How to use it

Add the library to a Rust project from GitHub:

cargo add --git https://github.com/AbdeldjalilChougui/arabic-normalize
Enter fullscreen mode Exit fullscreen mode

Then build a normalizer with the options you want:

use arabic_normalize::{Normalizer, Digits};

let n = Normalizer::builder()      // starts from the conservative defaults
    .alef_maqsura(true)
    .ta_marbuta(true)
    .digits(Digits::Western)
    .build();
assert_eq!(n.normalize("مَدْرَسَةُ عَلَى الطَّرِيقِ ١٢"), "مدرسه علي الطريق 12");

let search = Normalizer::search();  // everything on
assert_eq!(search.search_terms("وَالمَكْتَبَاتُ الجامِعِيَّة"), ["مكتب", "جامع"]);
Enter fullscreen mode Exit fullscreen mode

For Python, clone the repository and build the bindings from source with maturin:

git clone https://github.com/AbdeldjalilChougui/arabic-normalize
cd arabic-normalize/python
uv tool install maturin
maturin build --release -o dist
uv venv && uv pip install dist/*.whl
.venv/bin/python tests/test_smoke.py
Enter fullscreen mode Exit fullscreen mode
import arabic_normalize as an

an.normalize("بِسْمِ اللَّهِ")              # 'بسم الله'
an.normalize_for_search("مدرسة على")   # 'مدرسه علي'
an.to_western_digits("٢٠٢٤")           # '2024'
an.light_stem("والكتاب")               # 'كتاب'
n = an.Normalizer(ta_marbuta=True, digits="western")
n.normalize_many(["…", "…"])           # releases the GIL while working
Enter fullscreen mode Exit fullscreen mode

normalize_many takes a list and releases the GIL while it works, which is the call to use when you normalize a whole column of data.

The usual pattern for search is simple: normalize every value once when you index it, normalize the query with the same configuration when the user types, and compare the two normalized forms. Keep the original text for display.

How it works

The configuration is compiled into a 256-entry action table for the Arabic block (U+0600 to U+06FF). Each entry says: keep this character, drop it, or replace it with another code point. The hot loop is one table read per character. Characters outside the block only need a few range checks: extended Arabic marks, bidi controls, and ASCII digits when the target is Arabic-Indic.

normalize scans until the first character that changes. If there is none, it returns the input borrowed. Otherwise it copies the clean prefix once and maps the rest. Every mapping is one character to at most one character, so the output is never longer than the input.

That last property is useful in practice: you can normalize into a buffer of the input's size and know it will fit.

Things to know

  • Light10 is a light stemmer. It strips affixes and does not find roots. It sometimes merges unrelated words or misses related ones. Broken plurals such as كتب and كتاب are not merged.
  • Presentation forms are not folded. Arabic presentation forms (the U+FB50 to U+FEFF ligatures) are left as they are. Run NFKC first if your text contains them.
  • No real tokenizer. There is nothing beyond splitting on non-word characters, and there is no stopword list.

What is tested. cargo test runs unit tests, doc tests and property tests written with proptest. The properties are checked on random strings that mix letters, variants, marks, digits, invisible characters and arbitrary Unicode, under random configurations:

  • normalization is idempotent, and the second pass is always zero-copy
  • the result is Borrowed exactly when the text is unchanged
  • the output never grows
  • nothing the search preset removes survives it
  • normalize_into matches normalize
  • the digit round trip is lossless
  • stems are non-empty substrings

cargo bench runs criterion benchmarks on vocalized, already-clean and ASCII text. The README gives no numbers, and neither will I: run them on your own machine and your own text. The Python bindings have a smoke test.

Why I built it

Every project that stores Arabic names, addresses or product labels meets this problem the first time someone searches and gets nothing back. The common answer is a short chain of regular expressions copied from one project to the next. It works, but it tends to differ a little each time, it forgets the invisible characters or the Persian yeh, and it rebuilds every string even when most of the input, such as Latin text and numbers, needs no change at all.

I wanted the rules in one library with a clear line between safe normalization and aggressive search folding, so the choice is explicit in the code. And since normalization runs on every indexed value and every query, I wanted the unchanged case to cost close to nothing, which is what the borrowed return path is for. The property tests are there because "idempotent" and "never grows" are easy to claim and easy to break.

Get the code

The source, tests and benchmarks are on GitHub: https://github.com/AbdeldjalilChougui/arabic-normalize. It is MIT licensed. Issues and pull requests are welcome, especially examples of text that normalizes in a way you did not expect.


Originally published at abdeldjalilchougui.biz.

Top comments (0)