File size: 10,851 Bytes
dfbf6c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
"""
🔄 نرمال‌سازی موجودیت‌ها
Entity Normalization for better matching
"""

import re
import logging

logger = logging.getLogger(__name__)


class EntityNormalizer:
    """
    کلاس برای نرمال‌سازی موجودیت‌های مختلف
    
    این کلاس موجودیت‌ها را به فرمت استاندارد تبدیل می‌کند تا:
    - تطابق دقیق بهتر انجام شود
    - fuzzy matching موثرتر باشد
    - از تکرار جلوگیری شود
    """
    
    def __init__(self):
        """مقداردهی اولیه normalizer"""
        logger.info("✅ EntityNormalizer initialized")
        
        # نقشه تبدیل اعداد فارسی به انگلیسی
        self.persian_to_english = str.maketrans('۰۱۲۳۴۵۶۷۸۹', '0123456789')
    
    def normalize(self, text: str, entity_type: str) -> str:
        """
        نرمال‌سازی بر اساس نوع موجودیت
        
        Args:
            text: متن اصلی موجودیت
            entity_type: نوع موجودیت (person/company/amount/percent)
            
        Returns:
            متن نرمال‌شده
            
        Examples:
            >>> normalizer = EntityNormalizer()
            >>> normalizer.normalize("آقای علی احمدی", "person")
            'علی احمدی'
            >>> normalizer.normalize("۵۰ میلیارد ریال", "amount")
            '50 میلیارد ریال'
        """
        if not text:
            return ""
        
        # انتخاب متد مناسب بر اساس نوع
        if entity_type == "person":
            return self.normalize_person(text)
        elif entity_type == "company":
            return self.normalize_company(text)
        elif entity_type == "amount":
            return self.normalize_amount(text)
        elif entity_type == "percent":
            return self.normalize_percent(text)
        else:
            logger.warning(f"⚠️ Unknown entity type: {entity_type}, using basic normalization")
            return self._basic_normalize(text)
    
    def _basic_normalize(self, text: str) -> str:
        """نرمال‌سازی پایه برای هر متنی"""
        text = text.strip().lower()
        text = re.sub(r'\s+', ' ', text)
        return text
    
    def normalize_person(self, text: str) -> str:
        """
        نرمال‌سازی اسامی اشخاص
        
        - حذف فضاهای اضافی
        - lowercase
        - حذف عناوین (آقای، خانم، دکتر، ...)
        
        Args:
            text: نام شخص
            
        Returns:
            نام نرمال‌شده
            
        Examples:
            >>> normalizer.normalize_person("آقای  علی  احمدی")
            'علی احمدی'
            >>> normalizer.normalize_person("دکتر مریم کریمی")
            'مریم کریمی'
        """
        text = text.strip().lower()
        
        # حذف فضاهای اضافی
        text = re.sub(r'\s+', ' ', text)
        
        # حذف عناوین رایج
        titles = [
            'آقای', 'خانم', 'خانوم',
            'دکتر', 'دکتور', 'dr.',
            'مهندس', 'استاد', 'اقای',
            'جناب', 'سرکار',
        ]
        
        for title in titles:
            # حذف عنوان از ابتدای متن
            pattern = rf'^{title}\s+'
            text = re.sub(pattern, '', text, flags=re.IGNORECASE)
        
        return text.strip()
    
    def normalize_company(self, text: str) -> str:
        """
        نرمال‌سازی نام شرکت‌ها
        
        - حذف فضاهای اضافی
        - lowercase
        - استانداردسازی اختصارات (ش. → شرکت)
        - حذف کلمات اضافی پایانی
        
        Args:
            text: نام شرکت
            
        Returns:
            نام نرمال‌شده
            
        Examples:
            >>> normalizer.normalize_company("ش. پارس")
            'شرکت پارس'
            >>> normalizer.normalize_company("شرکت ملی نفت ایران")
            'شرکت ملی نفت'
        """
        text = text.strip().lower()
        
        # حذف فضاهای اضافی
        text = re.sub(r'\s+', ' ', text)
        
        # استانداردسازی اختصارات
        replacements = {
            'ش.': 'شرکت',
            'ش ': 'شرکت ',
            'شرکت‌': 'شرکت',
            'بانک‌': 'بانک',
            'سازمان‌': 'سازمان',
            'موسسه‌': 'موسسه',
            'گروه‌': 'گروه',
        }
        
        for old, new in replacements.items():
            text = text.replace(old, new)
        
        # حذف کلمات اضافی پایانی که معمولاً اختیاری هستند
        # مثلاً "شرکت ملی نفت ایران" → "شرکت ملی نفت"
        optional_suffixes = [
            r'\s+ایران$',
            r'\s+تهران$',
            r'\s+خصوصی$',
            r'\s+عام$',
            r'\s+سهامی$',
            r'\s+سهامی\s+عام$',
            r'\s+سهامی\s+خاص$',
        ]
        
        for pattern in optional_suffixes:
            text = re.sub(pattern, '', text)
        
        return text.strip()
    
    def normalize_amount(self, text: str) -> str:
        """
        نرمال‌سازی مبالغ مالی
        
        - تبدیل اعداد فارسی به انگلیسی
        - حذف فضاهای اضافی
        - lowercase
        - استانداردسازی واحدها
        
        Args:
            text: مبلغ مالی
            
        Returns:
            مبلغ نرمال‌شده
            
        Examples:
            >>> normalizer.normalize_amount("۵۰ میلیارد ریال")
            '50 میلیارد ریال'
            >>> normalizer.normalize_amount("30 میلیارد تومن")
            '30 میلیارد تومان'
        """
        # تبدیل اعداد فارسی به انگلیسی
        text = text.translate(self.persian_to_english)
        
        text = text.strip().lower()
        
        # حذف فضاهای اضافی
        text = re.sub(r'\s+', ' ', text)
        
        # استانداردسازی واحدهای پولی
        unit_map = {
            'تومن': 'تومان',
            'ریآل': 'ریال',
            'ريال': 'ریال',
            'دالر': 'دلار',
            'يورو': 'یورو',
        }
        
        for old, new in unit_map.items():
            text = text.replace(old, new)
        
        # استانداردسازی واحدهای مقیاس
        scale_map = {
            'ميليارد': 'میلیارد',
            'ميليون': 'میلیون',
            'هزار': 'هزار',
            'تریلیون': 'تریلیون',
        }
        
        for old, new in scale_map.items():
            text = text.replace(old, new)
        
        # حذف صفات اضافی (مثلاً "ریالی" → "ریال")
        text = text.replace('ریالی', 'ریال')
        text = text.replace('تومانی', 'تومان')
        text = text.replace('دلاری', 'دلار')
        
        return text.strip()
    
    def normalize_percent(self, text: str) -> str:
        """
        نرمال‌سازی درصدها
        
        - تبدیل اعداد فارسی به انگلیسی
        - یکسان‌سازی علامت درصد (%, ٪ → درصد)
        - فرمت استاندارد: "عدد درصد"
        
        Args:
            text: درصد
            
        Returns:
            درصد نرمال‌شده
            
        Examples:
            >>> normalizer.normalize_percent("۱۵٪")
            '15 درصد'
            >>> normalizer.normalize_percent("20%")
            '20 درصد'
            >>> normalizer.normalize_percent("25 درصدی")
            '25 درصد'
        """
        # تبدیل اعداد فارسی به انگلیسی
        text = text.translate(self.persian_to_english)
        
        text = text.strip()
        
        # حذف فضاهای اضافی
        text = re.sub(r'\s+', ' ', text)
        
        # یکسان‌سازی علامت‌های درصد
        text = text.replace('٪', '%')
        
        # تبدیل به فرمت استاندارد: "عدد درصد"
        # مثال: "15%" → "15 درصد"
        text = re.sub(r'(\d+(?:\.\d+)?)\s*[%٪]', r'\1 درصد', text)
        
        # حذف "درصدی" و تبدیل به "درصد"
        text = re.sub(r'(\d+(?:\.\d+)?)\s*درصدی', r'\1 درصد', text)
        
        return text.strip()


# ✅ تست‌های سریع
if __name__ == "__main__":
    print("=" * 60)
    print("🧪 Testing Normalizer Module")
    print("=" * 60)
    
    normalizer = EntityNormalizer()
    
    # تست 1: Person normalization
    print("\n📊 Test 1: Person Normalization")
    person_tests = [
        "آقای علی احمدی",
        "دکتر  مریم  کریمی",
        "خانم سارا رضایی",
        "علی محمدی"
    ]
    
    for person in person_tests:
        normalized = normalizer.normalize_person(person)
        print(f"  '{person}' → '{normalized}'")
    
    # تست 2: Company normalization
    print("\n📊 Test 2: Company Normalization")
    company_tests = [
        "شرکت پارس",
        "ش. ملی نفت ایران",
        "شرکت صبا سهامی خاص",
        "بانک ملی ایران"
    ]
    
    for company in company_tests:
        normalized = normalizer.normalize_company(company)
        print(f"  '{company}' → '{normalized}'")
    
    # تست 3: Amount normalization
    print("\n📊 Test 3: Amount Normalization")
    amount_tests = [
        "۵۰ میلیارد ریال",
        "30 میلیارد تومن",
        "100 میلیارد ریالی",
        "5 ميليون دلار"
    ]
    
    for amount in amount_tests:
        normalized = normalizer.normalize_amount(amount)
        print(f"  '{amount}' → '{normalized}'")
    
    # تست 4: Percent normalization
    print("\n📊 Test 4: Percent Normalization")
    percent_tests = [
        "۱۵٪",
        "20%",
        "25 درصدی",
        "30 درصد"
    ]
    
    for percent in percent_tests:
        normalized = normalizer.normalize_percent(percent)
        print(f"  '{percent}' → '{normalized}'")
    
    print("\n" + "=" * 60)
    print("✅ All tests completed!")
    print("=" * 60)