File size: 1,895 Bytes
f4931e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
"""Conservative Arabic/English normalization for ASR metrics.

Training text remains human-readable Arabic. Normalization is applied only for
comparison, so the model is not taught to emit stripped-down orthography.
"""

from __future__ import annotations

import re
import unicodedata

ARABIC_DIACRITICS_RE = re.compile(
    "[\u0610-\u061a\u064b-\u065f\u0670\u06d6-\u06ed]"
)
WHITESPACE_RE = re.compile(r"\s+")

CHAR_TRANSLATION = str.maketrans(
    {
        "أ": "ا",
        "إ": "ا",
        "آ": "ا",
        "ٱ": "ا",
        "ى": "ي",
        "ـ": "",
        "٠": "0",
        "١": "1",
        "٢": "2",
        "٣": "3",
        "٤": "4",
        "٥": "5",
        "٦": "6",
        "٧": "7",
        "٨": "8",
        "٩": "9",
        "۰": "0",
        "۱": "1",
        "۲": "2",
        "۳": "3",
        "۴": "4",
        "۵": "5",
        "۶": "6",
        "۷": "7",
        "۸": "8",
        "۹": "9",
    }
)


def contains_arabic(text: str) -> bool:
    return any("ARABIC" in unicodedata.name(char, "") for char in text)


def _replace_punctuation_and_symbols(text: str) -> str:
    chars: list[str] = []
    for char in text:
        category = unicodedata.category(char)
        if category.startswith(("P", "S")):
            chars.append(" ")
        else:
            chars.append(char)
    return "".join(chars)


def normalize_for_metrics(text: str, language: str | None = None) -> str:
    """Normalize orthographic variants without collapsing distinct Arabic letters."""

    del language  # Reserved for future dialect-specific policies.
    normalized = unicodedata.normalize("NFKC", text).casefold()
    normalized = ARABIC_DIACRITICS_RE.sub("", normalized)
    normalized = normalized.translate(CHAR_TRANSLATION)
    normalized = _replace_punctuation_and_symbols(normalized)
    return WHITESPACE_RE.sub(" ", normalized).strip()