|
| 1 | +"""Text normalisation policies. |
| 2 | +
|
| 3 | +Every transform here changes the ground-truth label, not just the pixels, so each one is |
| 4 | +opt-in and recorded on the sample. A dataset that silently strips diacritics teaches a |
| 5 | +model to drop them; that has to be a deliberate choice. |
| 6 | +""" |
| 7 | + |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import re |
| 11 | +import unicodedata |
| 12 | +from dataclasses import dataclass |
| 13 | +from enum import Enum |
| 14 | + |
| 15 | +__all__ = [ |
| 16 | + "NormalizationPolicy", |
| 17 | + "NumeralSystem", |
| 18 | + "normalize_text", |
| 19 | + "strip_diacritics", |
| 20 | + "strip_tatweel", |
| 21 | + "to_numeral_system", |
| 22 | +] |
| 23 | + |
| 24 | +TATWEEL = "ـ" |
| 25 | + |
| 26 | +# Tashkeel, Quranic annotation marks and the superscript alef. |
| 27 | +_DIACRITICS = re.compile( |
| 28 | + "[" |
| 29 | + "ؐ-ؚ" |
| 30 | + "ً-ٟ" |
| 31 | + "ٰ" |
| 32 | + "ۖ-ۜ" |
| 33 | + "۟-ۨ" |
| 34 | + "۪-ۭ" |
| 35 | + "࣓-ࣿ" |
| 36 | + "]" |
| 37 | +) |
| 38 | + |
| 39 | +_ALEF_VARIANTS = str.maketrans({"أ": "ا", "إ": "ا", "آ": "ا", "ٱ": "ا"}) |
| 40 | +_YA_VARIANTS = str.maketrans({"ى": "ي"}) |
| 41 | +_TA_MARBUTA = str.maketrans({"ة": "ه"}) |
| 42 | + |
| 43 | +_WESTERN_DIGITS = "0123456789" |
| 44 | +_ARABIC_INDIC_DIGITS = "٠١٢٣٤٥٦٧٨٩" |
| 45 | +_EASTERN_DIGITS = "۰۱۲۳۴۵۶۷۸۹" |
| 46 | + |
| 47 | +_HORIZONTAL_WS = re.compile(r"[^\S\n]+") |
| 48 | +_ALL_WS = re.compile(r"\s+") |
| 49 | + |
| 50 | + |
| 51 | +class NumeralSystem(str, Enum): |
| 52 | + """Which digit shapes appear in the rendered text and in the label.""" |
| 53 | + |
| 54 | + KEEP = "keep" |
| 55 | + WESTERN = "western" |
| 56 | + ARABIC_INDIC = "arabic_indic" |
| 57 | + EASTERN_ARABIC_INDIC = "eastern_arabic_indic" |
| 58 | + |
| 59 | + |
| 60 | +_DIGIT_TABLES: dict[NumeralSystem, str] = { |
| 61 | + NumeralSystem.WESTERN: _WESTERN_DIGITS, |
| 62 | + NumeralSystem.ARABIC_INDIC: _ARABIC_INDIC_DIGITS, |
| 63 | + NumeralSystem.EASTERN_ARABIC_INDIC: _EASTERN_DIGITS, |
| 64 | +} |
| 65 | + |
| 66 | +_ALL_DIGITS = _WESTERN_DIGITS + _ARABIC_INDIC_DIGITS + _EASTERN_DIGITS |
| 67 | + |
| 68 | + |
| 69 | +def strip_diacritics(text: str) -> str: |
| 70 | + """Remove Arabic tashkeel and Quranic annotation marks, leaving the skeleton.""" |
| 71 | + return _DIACRITICS.sub("", text) |
| 72 | + |
| 73 | + |
| 74 | +def strip_tatweel(text: str) -> str: |
| 75 | + """Remove kashida (tatweel) elongation characters.""" |
| 76 | + return text.replace(TATWEEL, "") |
| 77 | + |
| 78 | + |
| 79 | +def to_numeral_system(text: str, system: NumeralSystem) -> str: |
| 80 | + """Rewrite every digit in `text` using `system`'s digit shapes.""" |
| 81 | + if system is NumeralSystem.KEEP: |
| 82 | + return text |
| 83 | + target = _DIGIT_TABLES[system] |
| 84 | + table = {ord(digit): target[index % 10] for index, digit in enumerate(_ALL_DIGITS)} |
| 85 | + return text.translate(table) |
| 86 | + |
| 87 | + |
| 88 | +@dataclass(frozen=True, slots=True) |
| 89 | +class NormalizationPolicy: |
| 90 | + """Declarative description of how raw source text becomes a label. |
| 91 | +
|
| 92 | + Defaults are deliberately conservative: only runs of whitespace are collapsed, which |
| 93 | + no OCR label format preserves anyway. |
| 94 | + """ |
| 95 | + |
| 96 | + collapse_whitespace: bool = True |
| 97 | + preserve_line_breaks: bool = False |
| 98 | + strip_diacritics: bool = False |
| 99 | + strip_tatweel: bool = False |
| 100 | + unify_alef: bool = False |
| 101 | + unify_ya: bool = False |
| 102 | + unify_ta_marbuta: bool = False |
| 103 | + numerals: NumeralSystem = NumeralSystem.KEEP |
| 104 | + unicode_form: str | None = "NFC" |
| 105 | + |
| 106 | + def apply(self, text: str) -> str: |
| 107 | + return normalize_text(text, self) |
| 108 | + |
| 109 | + |
| 110 | +def normalize_text(text: str, policy: NormalizationPolicy | None = None) -> str: |
| 111 | + """Apply `policy` to `text`. |
| 112 | +
|
| 113 | + The order is fixed and the result is idempotent: composing characters are folded |
| 114 | + first so that later character-level rules see a canonical form. |
| 115 | + """ |
| 116 | + policy = policy or NormalizationPolicy() |
| 117 | + |
| 118 | + if policy.unicode_form: |
| 119 | + text = unicodedata.normalize(policy.unicode_form, text) |
| 120 | + if policy.strip_diacritics: |
| 121 | + text = strip_diacritics(text) |
| 122 | + if policy.strip_tatweel: |
| 123 | + text = strip_tatweel(text) |
| 124 | + if policy.unify_alef: |
| 125 | + text = text.translate(_ALEF_VARIANTS) |
| 126 | + if policy.unify_ya: |
| 127 | + text = text.translate(_YA_VARIANTS) |
| 128 | + if policy.unify_ta_marbuta: |
| 129 | + text = text.translate(_TA_MARBUTA) |
| 130 | + text = to_numeral_system(text, policy.numerals) |
| 131 | + |
| 132 | + if policy.collapse_whitespace: |
| 133 | + if policy.preserve_line_breaks: |
| 134 | + text = _HORIZONTAL_WS.sub(" ", text) |
| 135 | + # Keep one break between non-empty lines and no leading/trailing padding, |
| 136 | + # so a paragraph's line structure survives without ragged indentation. |
| 137 | + text = "\n".join(line.strip() for line in text.split("\n") if line.strip()) |
| 138 | + else: |
| 139 | + text = _ALL_WS.sub(" ", text) |
| 140 | + text = text.strip() |
| 141 | + return text |
0 commit comments