BlogBooks & scholarship9 min read

Check the tashkeel in a converted, vowelled Arabic text

To check diacritics in a converted, fully vowelled Arabic text, run a script that flags marks with no letter, two vowels on one letter, sukun with a vowel, tanween inside a word and bare words in vowelled paragraphs. Normalize the shadda order before comparing files, then proofread every flag against the printed page.

Hadith collections, poetry, grammar primers, mutun for memorization and many school texts are printed with full tashkeel: a fatha, damma, kasra, sukun, shadda or tanween on almost every letter. When such a page is converted to Word, the letters can be right while the marks are not. A kasra drops off, a fatha lands on the next letter, a speck of dirt on the scan becomes a sukun, or a mark is left floating after a space. In a vowelled text those errors change how a word is read, and they are tiny on screen.

This guide is for editors, muhaqqiqs, publishers and teachers who need a converted vowelled text to be right before it goes to print, into a course or to a translator. It gives an automatic first pass that points you to the likely errors, explains one storage detail that trips up comparisons, and ends with the proofreading a person still has to do.

What goes wrong with diacritics in a converted text

Each diacritic is stored as its own Unicode character after the letter it belongs to. The Unicode Arabic chart lists them from U+064B to U+0652 (fathatan, dammatan, kasratan, fatha, damma, kasra, shadda, sukun), plus U+0670 for the superscript or "dagger" alef. Because they are separate characters, a converted file can hold combinations that no correct text has:

What you seeWhat is storedLikely cause
A mark sitting alone, often on a dotted circleA mark after a space, punctuation or a Latin letterThe mark was read as a separate shape
Two vowels on one letterFatha and kasra (for example) after the same letterA mark from the line above or below, or noise
Sukun on a vowelled letterSukun plus fatha, damma, kasra or shaddaA dot or speck read as sukun
Tanween in the middle of a wordTanween followed by more lettersA mark moved to the wrong letter, or two words joined
A few bare words in a vowelled paragraphLetters with no marks at allMarks dropped, often on small or faint type

Not every odd-looking sequence is an error. A fathatan written before a final alef (كتابًا) or alef maqsura (هدًى) is normal, and Quranic text uses extra marks this guide does not cover. That is why the script below flags things for a person to look at rather than fixing them.

The shadda order: same word, two strings

A letter with a shadda and a vowel can be stored in two orders: shadda then fatha, or fatha then shadda. They display the same, and Unicode treats them as canonically equivalent. Unicode Standard Annex #53 explains why: the Arabic vowels have lower combining classes (fatha 30, damma 31, kasra 32) than shadda (33), so normalization moves the vowel before the shadda. Annex #53 then recommends that renderers move the shadda back next to the letter for display, and states that this reordering "is not intended for modifying original text".

So neither order is wrong. But a file that mixes both orders contains two different strings for the same word, and any tool that compares characters one by one (a Python script, a command-line search, a diff between two editions) will treat them as different. The fix is to normalize both texts to the same form before comparing them. Unicode Standard Annex #15 defines the forms; in Python, unicodedata.normalize("NFC", text) puts the vowel before the shadda. We checked this in Python 3.11: lam + shadda + fatha and lam + fatha + shadda are unequal as stored and equal after NFC.

Do this on a copy you use for checking, not by rewriting the delivered file, unless the client or publisher has asked for a normalized text.

Step 1: save a working copy

  1. Save the converted book as .docx (File, Save As, Word Document).
  2. If the notes matter, check them separately: the script below reads the main text, not footnotes or text boxes. Our guide to rebuilding footnotes in a converted Arabic book covers getting notes into proper Word footnotes first.
  3. Keep the scan or PDF open beside it. Every flag has to be checked against the printed page.

Step 2: run the diacritics check

This script uses only the Python standard library. It reads a .docx (or a UTF-8 .txt file) and prints one line per suspected problem, with the paragraph number and the word.

"""Flag likely diacritic (tashkeel) errors in a converted, vowelled Arabic text.

Usage: python3 check_tashkeel.py book.docx   (or a UTF-8 .txt file)
Reads the main text of a .docx (not footnotes or text boxes).
"""
import re
import sys
import unicodedata
import zipfile
import xml.etree.ElementTree as ET

W = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
TANWEEN = {"ً", "ٌ", "ٍ"}           # fathatan, dammatan, kasratan
VOWELS = {"َ", "ُ", "ِ"} | TANWEEN   # fatha, damma, kasra + tanween
SHADDA, SUKUN = "ّ", "ْ"
MARKS = VOWELS | {SHADDA, SUKUN, "ٰ"}          # + superscript (dagger) alef
NAMES = {"ً": "fathatan", "ٌ": "dammatan", "ٍ": "kasratan",
         "َ": "fatha", "ُ": "damma", "ِ": "kasra",
         SHADDA: "shadda", SUKUN: "sukun", "ٰ": "dagger alef"}


def paragraphs(path):
    if path.endswith(".docx"):
        with zipfile.ZipFile(path) as z:
            root = ET.fromstring(z.read("word/document.xml"))
        for p in root.iter(W + "p"):
            yield "".join(t.text or "" for t in p.iter(W + "t"))
    else:
        yield from open(path, encoding="utf-8").read().splitlines()


def is_letter(ch):
    return unicodedata.name(ch, "").startswith("ARABIC LETTER")


def clusters(word):
    """Split a word into (base letter, [marks]) pairs; base None = orphan."""
    out = []
    for ch in word:
        if ch in MARKS:
            if out and out[-1][0] is not None:
                out[-1][1].append(ch)
            else:
                out.append((None, [ch]))
        elif ch != "ـ":                        # skip tatweel
            out.append((ch, []))
    return out


def check(word):
    problems, cl = [], clusters(word)
    for i, (base, marks) in enumerate(cl):
        names = "+".join(NAMES[m] for m in marks)
        vowels = [m for m in marks if m in VOWELS]
        if base is None or not is_letter(base):
            problems.append(f"mark with no letter ({names})")
            continue
        if len(vowels) > 1 or len(set(marks)) < len(marks):
            problems.append(f"two vowels or a doubled mark on {base} ({names})")
        if SUKUN in marks and (vowels or SHADDA in marks):
            problems.append(f"sukun with another mark on {base} ({names})")
        if set(vowels) & TANWEEN:
            rest = "".join(b for b, _ in cl[i + 1:] if b)
            if rest and not ("ً" in vowels and rest in ("ا", "ى")):
                problems.append(f"tanween inside the word on {base}")
    return problems


def order(word):
    """Count shadda stored before / after a vowel on the same letter."""
    first = len(re.findall("ّ[ً-ِ]", word))
    after = len(re.findall("[ً-ِ]ّ", word))
    return first, after


total_first = total_after = 0
for n, para in enumerate(paragraphs(sys.argv[1]), 1):
    words = re.findall(r"\S+", para)
    arabic = [w for w in words if any(is_letter(c) for c in w)]
    for w in words:
        for p in check(w.strip("«»()[]{}،؛؟.,:!\"'")):
            print(f"para {n}: {w}: {p}")
        f, a = order(w)
        total_first += f
        total_after += a
    long_words = [w for w in arabic if sum(map(is_letter, w)) >= 3]
    bare = [w for w in long_words if not any(c in MARKS for c in w)]
    if len(long_words) >= 5 and 0 < len(bare) <= len(long_words) * 0.2:
        print(f"para {n}: vowelled paragraph, bare words: {' '.join(bare)}")

print(f"shadda stored before its vowel: {total_first}; after it: {total_after}")
if total_first and total_after:
    print("  mixed storage order: normalize (NFC) before comparing or searching with scripts")

Run it with python3 check_tashkeel.py book.docx. It reports five kinds of flag:

  • mark with no letter: a diacritic after a space, punctuation, a digit or a Latin letter;
  • two vowels or a doubled mark: more than one of fatha, damma, kasra or tanween on one letter, or the same mark twice;
  • sukun with another mark: sukun together with a vowel or a shadda;
  • tanween inside the word: tanween followed by more letters, except fathatan before a final alef or alef maqsura;
  • bare words in a vowelled paragraph: in a paragraph where most words of three or more letters carry marks, the few that carry none.

It also counts how many shadda-plus-vowel pairs are stored in each order and tells you if they are mixed.

Illustrative example. While writing this guide we built a six-paragraph .docx in this session (with Python's zipfile module, not Word), using a well-known hadith, a short verse and some invented sentences. We planted five problems: two words left bare in a vowelled paragraph, fatha plus sukun on one letter, fatha plus kasra on another, a kasra left after a space, and a tanween in the middle of a word. Paragraph 1 stored every shadda before its vowel and paragraph 5 stored it after, and paragraph 6 was ordinary unvowelled prose. The script (Python 3.11) printed:

para 2: vowelled paragraph, bare words: الدين قال
para 3: العِلَْمِ: sukun with another mark on ل (fatha+sukun)
para 3: لَِطُلَّابِ: two vowels or a doubled mark on ل (fatha+kasra)
para 4: ِ: mark with no letter (kasra)
para 4: كُتُبٌهُ: tanween inside the word on ب
shadda stored before its vowel: 5; after it: 9
  mixed storage order: normalize (NFC) before comparing or searching with scripts

All five planted problems were reported. The unvowelled paragraph was not flagged, and صَبَاحًا and عَظِيمًا (fathatan before a final alef) were correctly left alone. This was a small file built for the guide, not a book, and not the output of any particular OCR tool.

Step 3: read what each flag means

FlagUsual causesWhat to do
Mark with no letterMark split off by a space; noise read as a markCompare with the page; delete it or move it to its letter
Two vowels on one letterA mark from a neighbouring line; noiseKeep the vowel the page shows, delete the other
Sukun with another markA dot or speck read as sukunUsually delete the sukun, but check the page
Tanween inside the wordMark on the wrong letter; two words run togetherMove the tanween or insert the missing space
Bare wordsMarks dropped on faint or small type; or the page itself leaves them bareVowel them as printed, or leave them if the page does

The last flag needs the most judgment. Many printed books leave common words such as قال or the divine name unvowelled on purpose, so a bare word is only an error if the page has marks on it. Decide the house rule once, and you can quickly pass over the flags it explains.

Step 4: fix marks in Word

The script names each mark it reports, so you know what is stored even when the screen shows only a smudge. To fix a flag, put the cursor after the letter, delete the wrong mark (then check that the letter itself is still there, since editors handle a letter and its marks differently), and type the right one. If your keyboard layout makes a mark awkward to type, Microsoft documents that typing a Unicode code and pressing Alt+X inserts the character: 064E is fatha, 064F damma, 0650 kasra, 0651 shadda, 0652 sukun. If the code comes straight after a letter, select just the code before pressing Alt+X.

Use Word's Find to see the same problem elsewhere in the book. With an Arabic editing language enabled, desktop Word's Find options can include Match diacritics (the MatchDiacritics setting in Word's object model, which Microsoft describes as matching "text with matching diacritics in a right-to-left language document"); labels vary by version. Turn it on when you search for a specific vowelled form, so كَتَبَ and كُتُبٌ are not treated as the same word. For more on why searches miss vowelled words, see why Find can't locate Arabic words.

Step 5: proofread what a script cannot see

The script checks that the marks are possible. It cannot check that they are right: a damma where the book has a fatha passes, because one vowel on one letter is valid. A person who reads vowelled Arabic still has to:

  1. Check every flag against the printed page.
  2. Read a deliberate sample in full against the scan: the densest page, a page of poetry, a page with many names, and any page in small type.
  3. Read case endings (i'rab) closely in that sample. These are the marks most often lost or changed, and the ones a reader of a vowelled text relies on.
  4. Check that the font you deliver in shows every mark clearly. Some fonts place marks badly on tall or descending letters, which can look like an error when the stored text is fine.

For Quranic quotations, compare against a verified text rather than reading by eye; our guide to checking Quran quotations in a converted book does the letters, and this check helps with the marks.

Checklist before you deliver a vowelled text

  • The diacritics check has been run on the main text
  • Every "mark with no letter" removed or moved to its letter
  • Every doubled vowel and sukun-with-vowel resolved against the page
  • Every tanween inside a word fixed (moved, or a space inserted)
  • Bare words checked against the page, with a written house rule for words left bare
  • Footnotes and text boxes checked separately
  • Shadda order normalized in any copy used for comparison or search scripts
  • A deliberate sample proofread in full, including case endings
  • Delivery font shows every mark clearly on screen and in print

Limitations

  • The script checks whether marks are possible, not whether they are correct. A wrong vowel in a valid position passes.
  • It covers the common diacritics (U+064B to U+0652) and the dagger alef. It does not check Quranic annotation marks, small high letters or other extended marks, and it may report sequences that are valid in Quranic orthography or in other languages written in Arabic script.
  • The bare-word flag depends on the book's style; on a partly vowelled text it can report words that are bare on the page.
  • It reads the main text of a .docx and plain text files. It ignores footnotes, text boxes, headers and tables in other parts of the file, and it does not read PDF.
  • We tested it on a small file built for this guide, not on a whole book, and not on output from any particular tool, including ScribeTools. Word itself was not tested here.
  • Converted output should always be reviewed before anyone relies on it. This check makes that review faster; it does not replace it.

If you are starting from a scanned vowelled book, see Arabic OCR for getting an editable text that keeps the marks, and does OCR preserve Arabic diacritics? for what to expect. Before handing the file on, run the wider QA checklist for an OCR'd Arabic Word file.

Sources

  1. Unicode Standard Annex #53: Unicode Arabic Mark Rendering
  2. Unicode Standard Annex #15: Unicode Normalization Forms
  3. Unicode Consortium: Arabic code chart (U+0600 to U+06FF)
  4. Microsoft Learn: Find.MatchDiacritics property (Word)
  5. Microsoft Support: Insert ASCII or Unicode character codes in Word
Check the tashkeel in a converted, vowelled Arabic text | ScribeTools