Files
init_dataParser/app/monir/monir_text_normalizer.py
2025-12-09 19:55:37 +03:30

596 lines
17 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import re
from typing import Dict, Optional
from typing import List, Tuple
from typing import ClassVar
from typing import ClassVar, Optional, Set, FrozenSet
class TextNormalizer:
HAMZE_PATTERN: List[Tuple[re.Pattern[str], str]] = [
(re.compile(r"ئ|ﺌ|ﺋ"), "ی"),
(re.compile(r"ؤ|ﺅ"), "و"),
(re.compile(r"ﺔ|ۀ|ﺓ|ة"), "ه"),
(re.compile(r"إ|أ"), "ا"),
]
CHAR_PATTERN_MONIR: List[Tuple[re.Pattern[str], str]] = [
(re.compile(r"\u200e|\u200f"), " "), # LTR, RTL
(re.compile(r"\u00AD|\u00AC"), "\u200c"), # نیم اسپیس خاص
(re.compile(r"(\u002C)+"), "\u200c"), # نیم اسپیس تکراری
(re.compile(r"ﺁ|آ"), "آ"),
(re.compile(r"ﺎ|ٱ|ﺍ"), "ا"),
(re.compile(r"ٲ|أ|ﺄ|ﺃ"), "أ"),
(re.compile(r"ﺈ|ٳ|ﺇ"), "إ"),
(re.compile(r"ﺐ|ﺏ|ﺑ|ٮ|ﺒ"), "ب"),
(re.compile(r"ﭖ|ﭗ|ﭙ|ﭘ|ݒ|ݐ"), "پ"),
(re.compile(r"ﭡ|ٺ|ٹ|ﭞ|ٿ|ټ|ﺕ|ﺗ|ﺖ|ݓ|ﺘ"), "ت"),
(re.compile(r"ﺙ|ﺛ|ﺚ|ݑ|ݖ|ﺜ"), "ث"),
(re.compile(r"ﺝ|ڃ|ﺠ|ﺟ|ڄ"), "ج"),
(re.compile(r"ڃ|ﭽ|ݘ|ﭻ|ﭼ"), "چ"),
(re.compile(r"ﺢ|ﺤ|څ|ځ|ﺣ"), "ح"),
(re.compile(r"ﺥ|ﺦ|ﺨ|ﺧ"), "خ"),
(re.compile(r"ڏ|ډ|ﺪ|ڌ|ﺩ"), "د"),
(re.compile(r"ﺫ|ﺬ|ذ"), "ذ"),
(re.compile(r"ڙ|ڗ|ڒ|ڑ|ڕ|ﺭ|ړ|ڔ|ݫ|ݬ|ﺮ"), "ر"),
(re.compile(r"ﺰ|ﺯ"), "ز"),
(re.compile(r"ﮋ|ﮊ|ࢲ"), "ژ"),
(re.compile(r"ݭ|ݜ|ﺱ|ﺲ|ښ|ﺴ|ﺳ"), "س"),
(re.compile(r"ﺵ|ﺶ|ﺸ|ﺷ"), "ش"),
(re.compile(r"ﺺ|ﺼ|ﺻ|ﺹ"), "ص"),
(re.compile(r"ﺽ|ﺾ|ﺿ|ﻀ"), "ض"),
(re.compile(r"ﻁ|ﻂ|ﻃ|ڟ|ﻄ"), "ط"),
(re.compile(r"ﻆ|ﻇ|ﻈ"), "ظ"),
(re.compile(r"ڠ|ﻉ|ﻊ|ﻋ|ﻌ"), "ع"),
(re.compile(r"ﻎ|ۼ|ﻍ|ﻐ|ﻏ"), "غ"),
(re.compile(r"ﻒ|ڤ|ﻑ|ﻔ|ڡ|ݠ|ݡ|ﻓ"), "ف"),
(re.compile(r"ﻕ|ﻖ|ﻗ|ڨ|ﻘ|ٯ"), "ق"),
(re.compile(r"ڭ|ﻚ|ﮎ|ﻜ|ﮏ|ګ|ﻛ|ﮑ|ﮐ|ڪ|ݢ|ݣ|ݤ|ك|ࢴ"), "ک"),
(re.compile(r"ﮚ|ﮒ|ﮓ|ﮕ|ڳ|ﮔ"), "گ"),
(re.compile(r"ﻝ|ﻞ|ﻠ|ڵ|ﻟ"), "ل"),
(re.compile(r"ﻵ|ﻶ|ﻷ|ﻸ|ﻹ|ﻺ|ﻻ|ﻼ"), "لا"),
(re.compile(r"ﻡ|ﻤ|ﻢ|ݥ|ݦ|ﻣ"), "م"),
(re.compile(r"ڼ|ﻦ|ﻥ|ﻨ|ݔ|ݧ|ݨ|ݩ|ݪ|ﻧ"), "ن"),
(re.compile(r"ވ|ﯙ|ۈ|ۋ|ﺆ|ۊ|ۇ|ۏ|ۅ|ۉ|ﻭ|ﻮ|ٶ|ۆ|ؤ"), "و"),
(re.compile(r"ﻬ|ھ|ﻩ|ﻫ|ﻪ|ە|ۂ|ۃ|٥|ﮪ|ﮬ|ﮭ|ہ"), "ه"),
(re.compile(r"ﭛ|ﻯ|ۍ|ﻰ|ﻱ|ﻲ|ں|ﻳ|ﻴ|ﯼ|ې|ﯽ|ﯾ|ﯿ|ێ|ے|ى|ي"), "ی"),
(re.compile(r"¬"), "‌"),
(re.compile(r"•|·|●|·|・|∙|。|ⴰ"), "."),
(re.compile(r",|٬|٫|‚|،"), "،"),
(re.compile(r"ʕ"), "؟"),
(re.compile(r"”|“|¨|″"), '"'),
(re.compile(r"۰|٠"), "0"),
(re.compile(r"۱|١"), "1"),
(re.compile(r"۲|٢"), "2"),
(re.compile(r"۳|٣|³"), "3"),
(re.compile(r"۴|٤"), "4"),
(re.compile(r"۵"), "5"),
(re.compile(r"۶|٦"), "6"),
(re.compile(r"۷|٧"), "7"),
(re.compile(r"۸|٨"), "8"),
(re.compile(r"۹|٩"), "9"),
(re.compile(r"²"), "2"),
(re.compile(r"٪"), '%'),
(re.compile(r"ˆ"), '^'),
(re.compile(r"˜"), '~'),
(re.compile(r"٭"), '*'),
(re.compile(r"ᆖ"), '='),
(re.compile(r"‑|–|—|−"), '-'),
(re.compile(r"‹"), '<'),
(re.compile(r"›"), '>'),
# اعراب و تنوین + Maddah
# ً (Fathatan) → U+064B
# ٌ (Dammatan) → U+064C
# ٍ (Kasratan) → U+064D
# َ (Fatha) → U+064E
# ُ (Damma) → U+064F
# ِ (Kasra) → U+0650
# ّ (Shadda) → U+0651
# ْ (Sukun) → U+0652
# ٰ (Maddah above) → U+0670
# (re.compile(r"|ِ|ُ|َ|ٍ|ٌ|ً|"), ""),
# (
# re.compile(r"ـ"),
# "",
# ), # حذف حروف کشیده # این باعث خطای حذف اضافی شد و با خط بعدی جایگزین شد
]
EMPTY_LINE_PATTERN: List[Tuple[re.Pattern[str], str]] = [
(re.compile(r"\\n"), "\n"),
(re.compile(r"\\r"), "\n"),
(re.compile(r"(\r\n)+"), "\n"),
(re.compile(r"\r+"), "\n"),
(re.compile(r"\f"), "\n"),
]
FINALL_LINE_PATTERN: List[Tuple[re.Pattern[str], str]] = [
# حذف خطوطی که با ":" شروع می‌شوند (حتی با فاصله پیش از آن)
(re.compile(r"^[ \t]*:[^\n]*\n?", re.MULTILINE), ""),
# جایگزینی فواصل اضافی و خطوط خالی (همان قبلی)
(re.compile(r" +"), " "),
(re.compile(r"\n{2,}"), "\n\n"), # حداکثر یک خط خالی بین پاراگراف‌ها
]
# ✅ لیست پیش‌فرض کاراکترهای نامعتبر — immutable و global
DEFAULT_INVALID_CHARS: ClassVar[FrozenSet[str]] = frozenset(
{
"\u001f",
"\u001e",
"\u000b",
"\u0002",
"\u0007",
"„","΄",
"",
"°",
"´",
"Ã",
"É",
"Í",
"Ï",
"×",
"Û",
"à",
"á",
"ã",
"ä",
"ç",
"è",
"é",
"ê",
"í",
"ï",
"ñ",
"ó",
"õ",
"ö",
"ø",
"ú",
"ü",
"þ",
"ÿ",
"ā",
"Ă",
"Ĉ",
"Ĥ",
"Ŋ",
"ˇ",
"ࠤ",
"࠮",
"ࡸ",
"ࢆ",
"Ḩ",
"ḭ",
"Ḿ",
"Ṏ",
"Ἂ",
"Ῥ",
"\u0001",
"\u0000",
"¢",
"£",
"¤",
"μ",
"π",
"Щ",
"؀",
"ऀ",
"ऌ",
"ऎ",
"ऐ",
"द",
"ऴ",
"ू",
"ॄ",
"ॆ",
"ग़",
"ड़",
"চ",
"জ",
"৤",
"০",
"৪",
"৮",
"ਢ",
"ਤ",
"ੋ",
"੒",
"ੜ",
"ઈ",
"଀",
"଎",
"஘",
"௚",
"ా",
"౔",
"ೂ",
"ඊ",
"ฃ",
"ด",
"ฮ",
"โ",
"ไ",
"๒",
"ༀ",
"ᆘ",
"ᆦ",
"ᐨ",
"ᑪ",
"ᒂ",
"ᒶ",
"ᔟ",
"ᔢ",
"ᔧ",
"ᔪ",
"ᘀ",
"ᘂ",
"ᨾ",
"ᰀ",
"᱊",
" ",
"‌",
"‍",
"‘",
"’",
"…",
"‪",
"‬",
"⁋",
"",
"™",
"↓",
"≥",
"⍤",
"␂",
"␃",
"⒢",
"◮",
"⚚",
"⚜",
"⛾",
"⡯",
"⤦",
"⤨",
"ⱆ",
"ⱶ",
"ま",
"㈬",
"㈮",
"㈺",
"㈼",
"㛸",
"㝶",
"㩴",
"㪐",
"㵹",
"㸐",
"㸒",
"䂨",
"䌀",
"䐀",
"䑶",
"䑸",
"䗜",
"䠨",
"䡟",
"䢪",
"䩞",
"䩡",
"䭨",
"䭪",
"䳸",
"䴮",
"䴰",
"伀",
"偦",
"偨",
"儀",
"凄",
"刐",
"刚",
"唃",
"唎",
"唢",
"唤",
"喈",
"喡",
"娀",
"宜",
"屨",
"恨",
"惄",
"愀",
"愔",
"掋",
"摧",
"撆",
"桨",
"汊",
"汌",
"淄",
"皆",
"稀",
"笺",
"筠",
"筨",
"箜",
"篃",
"絘",
"脈",
"茊",
"茌",
"菈",
"蕞",
"蚞",
"譨",
"軺",
"輒",
"輔",
"辜",
"酠",
"鉦",
"鉼",
"鉾",
"銨",
"镖",
"闎",
"餸",
"馼",
"髄",
"魰",
"鶊",
"ꅨ",
"ꉣ",
"ꍀ",
"ꡨ",
"꡻",
"ꢆ",
"ꢘ",
"꣜",
"넣",
"뫜",
"뺨",
"뻪",
"쌀",
"쫮",
"쵕",
"케",
"퓪",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"�",
}
)
# ✅ جدول پیش‌فرض (یکبار محاسبه می‌شود)
_DEFAULT_TRANSLATION_TABLE: ClassVar[dict] = str.maketrans(
"", "", "".join(DEFAULT_INVALID_CHARS)
)
def __init__(
self, options=None, pattern_normalize=None, pattern_hamze_normalize=None
):
"""for Use and Dev
(re.compile(r""), ""),
"""
self.options = (
options
if options
else {
"charArNormal": True,
"errorLine": True,
"alphabetsNormal": False,
"removeInvalidChar": False,
"emptylinesNormal": False,
"hamzehNormal": False,
"spaceCorrection": False,
"trimLine": False,
}
)
self.valid_charset = self.__extract_valid_chars()
if pattern_normalize:
self.pattern_normalize = pattern_normalize
else:
self.pattern_normalize = TextNormalizer.CHAR_PATTERN_MONIR
if pattern_hamze_normalize:
self.pattern_hamze_normalize = pattern_hamze_normalize
else:
self.pattern_hamze_normalize = TextNormalizer.HAMZE_PATTERN
self.pattern_emptylinesnormal = TextNormalizer.EMPTY_LINE_PATTERN
def __extract_valid_chars(self):
valid = set()
for regex, replacement in TextNormalizer.CHAR_PATTERN_MONIR:
# چون replacement ممکن است بیش از یک کاراکتر باشد
for ch in replacement:
valid.add(ch)
return valid
def normalize_text_monir(self, text: str) -> str:
if text == "":
return ""
text = text.strip()
# یکسان سازی اختلاف حروف کیبوردهای مختلف - کدهای مختلف ولی نمایش یکسان
if self.options.get("alphabetsNormal", False):
text = self.alphabets_normalize(text)
# حذف کاراکتر های نامعتبر
if self.options.get("removeInvalidChar", False):
text = self.remove_invalid_chars(text)
# نرمال کردن حروف اختلافی عربی و فارسی
# if self.options.get("charArNormal", True):
# text = self.yeke_normal(text)
# پرش از اختلافات همزه‌ا
if self.options.get("hamzehNormal", False):
text = self.hamze_normalize(text)
# حذف خطوط و فاصله‌های خالی
if self.options.get("emptylinesNormal", False):
text = self.emptylines_normalize(text)
# اصلاح فاصله‌ها در ترکیب کلمات
# if self.options.get("spaceCorrection", False):
# text = self.space_correction(text)
# حذف خطوط اضافی اول و انتهای متن
# if self.options.get("trimLine", False):
# text = text.strip()
return text
def html():
pass
@staticmethod
def remove_invalid_chars(
text: str,
extra_invalid_chars: Optional[Set[str]] = None,
exclude_default: bool = False,
) -> str:
"""
حذف کاراکترهای نامعتبر از متن.
Args:
text: متن ورودی.
extra_invalid_chars: مجموعه‌ای از کاراکترهای اضافی برای حذف.
exclude_default: اگر True باشد، فقط کاراکترهای custom حذف می‌شوند (پیش‌فرض نادیده گرفته می‌شود).
Returns:
متن پاک‌سازی‌شده.
"""
if not text:
return text
# ۱. تعیین مجموعه نهایی کاراکترهای نامعتبر
if exclude_default:
invalid_chars = extra_invalid_chars or set()
else:
invalid_chars = set(TextNormalizer.DEFAULT_INVALID_CHARS)
if extra_invalid_chars:
invalid_chars.update(extra_invalid_chars)
# ۲. اگر مجموعه خالی است → هیچ کاری نکن
if not invalid_chars:
return text
# ۳. ساخت جدول ترجمه (بهینه: فقط وقتی لازم است)
# 🔹 برای بهینه‌سازی بیشتر، می‌توانید cache اضافه کنید (در صورت نیاز)
table = str.maketrans("", "", "".join(invalid_chars))
return text.translate(table)
@staticmethod
def alphabets_normalize(
text: str, quote_map: Optional[List[Tuple[re.Pattern[str], str]]] = None
) -> str:
if text == "":
return ""
mapping = quote_map if quote_map else TextNormalizer.CHAR_PATTERN_MONIR
for pattern, repl in mapping:
text = pattern.sub(repl, text)
return text
@staticmethod
def hamze_normalize(
text: str, quote_map: Optional[List[Tuple[re.Pattern[str], str]]] = None
) -> str:
if text == "":
return ""
mapping = quote_map if quote_map else TextNormalizer.HAMZE_PATTERN
for pattern, repl in mapping:
text = pattern.sub(repl, text)
return text
@staticmethod
def emptylines_normalize(
text: str, quote_map: Optional[List[Tuple[re.Pattern[str], str]]] = None
) -> str:
if text == "":
return ""
mapping = quote_map if quote_map else TextNormalizer.EMPTY_LINE_PATTERN
for pattern, repl in mapping:
text = pattern.sub(repl, text)
for pattern, repl in TextNormalizer.FINALL_LINE_PATTERN:
text = pattern.sub(repl, text)
return text
# TEST M
# ـکشیدگی هایی که به جای _ به کار رفته اند
def keshide_corrected(self, text):
(r"(\d)ـ(\d)", r"\1_\2"), # فاصله بین دو عدد
(r"(\d)ـ", r"\1_"), # عدد و خط تیره
(r"ـ(\d)", r"_\1"), # خط تیره و عدد
(r"\sـ\s", r" _ "), # فاصله‌های خالی بین خط تیره
(
r"(?<![ویهبتثجحخدذرزسشصضطظعغفقكلمنپچژکگ])ـ(?![ویهبتثجحخدذرزسشصضطظعغفقكلمنپچژکگ])",
r"_",
),
(r"\sـ\s", r" _ "),
pass