leilaghomashchi commited on
Commit
ddd1a1c
·
verified ·
1 Parent(s): d838525

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -10
app.py CHANGED
@@ -15,19 +15,46 @@ class AnonymizationEvaluator:
15
  self.results_df = None
16
 
17
  def extract_entities_from_text(self, text: str) -> Dict[str, Set[str]]:
18
- """استخراج موجودیت‌ها از متن"""
19
  if pd.isna(text) or not isinstance(text, str):
20
  return {'companies': set(), 'persons': set(), 'amounts': set(), 'percents': set(), 'groups': set()}
21
-
22
- entities = {
23
- 'companies': set(re.findall(r'company-(\d+)', text)),
24
- 'persons': set(re.findall(r'person-(\d+)', text)),
25
- 'amounts': set(re.findall(r'amount-(\d+)', text)),
26
- 'percents': set(re.findall(r'percent-(\d+)', text)),
27
- 'groups': set(re.findall(r'group-(\d+)', text))
 
 
 
 
28
  }
 
 
 
 
 
 
 
 
 
29
  return entities
30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  def calculate_precision_recall_f1(self, reference_entities: Dict[str, Set[str]],
32
  predicted_entities: Dict[str, Set[str]]) -> Tuple[float, float, float]:
33
  """محاسبه Precision, Recall و F1-Score"""
@@ -101,7 +128,7 @@ class AnonymizationEvaluator:
101
  return 0.0, 0.0, 0.0
102
 
103
  def evaluate_dataset(self, file_path: str) -> Tuple[bool, str, pd.DataFrame]:
104
- """ارزیابی کل دیتاست"""
105
  try:
106
  # بارگذاری فایل
107
  df = pd.read_csv(file_path)
@@ -113,11 +140,27 @@ class AnonymizationEvaluator:
113
  if missing_columns:
114
  return False, f"ستون‌های مفقود: {', '.join(missing_columns)}", pd.DataFrame()
115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  # محاسبه متریک‌ها برای هر سطر
117
  precisions = []
118
  recalls = []
119
  f1_scores = []
120
 
 
 
121
  for index, row in df.iterrows():
122
  precision, recall, f1 = self.evaluate_single_row(
123
  row['Reference_text'],
@@ -127,6 +170,12 @@ class AnonymizationEvaluator:
127
  precisions.append(round(precision, 4))
128
  recalls.append(round(recall, 4))
129
  f1_scores.append(round(f1, 4))
 
 
 
 
 
 
130
 
131
  # اضافه کردن ستون‌های جدید
132
  df['Precision'] = precisions
@@ -136,7 +185,12 @@ class AnonymizationEvaluator:
136
  # ذخیره نتایج
137
  self.results_df = df
138
 
139
- return True, "ارزیابی با موفقیت انجام شد", df
 
 
 
 
 
140
 
141
  except Exception as e:
142
  return False, f"خطا در پردازش فایل: {str(e)}", pd.DataFrame()
 
15
  self.results_df = None
16
 
17
  def extract_entities_from_text(self, text: str) -> Dict[str, Set[str]]:
18
+ """استخراج موجودیت‌ها از متن با debugging"""
19
  if pd.isna(text) or not isinstance(text, str):
20
  return {'companies': set(), 'persons': set(), 'amounts': set(), 'percents': set(), 'groups': set()}
21
+
22
+ # تمیز کردن متن
23
+ text = str(text).strip()
24
+
25
+ # الگوهای مختلف برای موجودیت‌ها
26
+ patterns = {
27
+ 'companies': [r'company-(\d+)', r'Company-(\d+)', r'COMPANY-(\d+)'],
28
+ 'persons': [r'person-(\d+)', r'Person-(\d+)', r'PERSON-(\d+)'],
29
+ 'amounts': [r'amount-(\d+)', r'Amount-(\d+)', r'AMOUNT-(\d+)'],
30
+ 'percents': [r'percent-(\d+)', r'Percent-(\d+)', r'PERCENT-(\d+)'],
31
+ 'groups': [r'group-(\d+)', r'Group-(\d+)', r'GROUP-(\d+)']
32
  }
33
+
34
+ entities = {}
35
+ for entity_type, pattern_list in patterns.items():
36
+ found = set()
37
+ for pattern in pattern_list:
38
+ matches = re.findall(pattern, text)
39
+ found.update(matches)
40
+ entities[entity_type] = found
41
+
42
  return entities
43
 
44
+ def debug_text_analysis(self, reference_text: str, predicted_text: str, row_num: int = 0) -> str:
45
+ """تابع debugging برای تحلیل متن‌ها"""
46
+ debug_info = f"\n--- Debug Row {row_num + 1} ---\n"
47
+ debug_info += f"Reference: '{reference_text[:100]}...'\n"
48
+ debug_info += f"Predicted: '{predicted_text[:100]}...'\n"
49
+
50
+ ref_entities = self.extract_entities_from_text(reference_text)
51
+ pred_entities = self.extract_entities_from_text(predicted_text)
52
+
53
+ debug_info += f"Reference entities: {dict(ref_entities)}\n"
54
+ debug_info += f"Predicted entities: {dict(pred_entities)}\n"
55
+
56
+ return debug_info
57
+
58
  def calculate_precision_recall_f1(self, reference_entities: Dict[str, Set[str]],
59
  predicted_entities: Dict[str, Set[str]]) -> Tuple[float, float, float]:
60
  """محاسبه Precision, Recall و F1-Score"""
 
128
  return 0.0, 0.0, 0.0
129
 
130
  def evaluate_dataset(self, file_path: str) -> Tuple[bool, str, pd.DataFrame]:
131
+ """ارزیابی کل دیتاست با debugging"""
132
  try:
133
  # بارگذاری فایل
134
  df = pd.read_csv(file_path)
 
140
  if missing_columns:
141
  return False, f"ستون‌های مفقود: {', '.join(missing_columns)}", pd.DataFrame()
142
 
143
+ # تشخیص مشکل - بررسی نمونه‌ای از داده‌ها
144
+ debug_info = "\n=== Debug Information ===\n"
145
+ debug_info += f"تعداد سطرها: {len(df)}\n"
146
+ debug_info += f"ستون‌ها: {list(df.columns)}\n\n"
147
+
148
+ # بررسی چند سطر اول
149
+ for i in range(min(3, len(df))):
150
+ ref_text = str(df.iloc[i]['Reference_text'])
151
+ anon_text = str(df.iloc[i]['anonymized_text'])
152
+
153
+ debug_info += self.debug_text_analysis(ref_text, anon_text, i)
154
+
155
+ print(debug_info) # نمایش در console
156
+
157
  # محاسبه متریک‌ها برای هر سطر
158
  precisions = []
159
  recalls = []
160
  f1_scores = []
161
 
162
+ total_entities_found = 0 # شمارنده کل موجودیت‌های یافت شده
163
+
164
  for index, row in df.iterrows():
165
  precision, recall, f1 = self.evaluate_single_row(
166
  row['Reference_text'],
 
170
  precisions.append(round(precision, 4))
171
  recalls.append(round(recall, 4))
172
  f1_scores.append(round(f1, 4))
173
+
174
+ # شمارش موجودیت‌ها برای debugging
175
+ ref_entities = self.extract_entities_from_text(str(row['Reference_text']))
176
+ pred_entities = self.extract_entities_from_text(str(row['anonymized_text']))
177
+ total_entities_found += sum(len(entities) for entities in ref_entities.values())
178
+ total_entities_found += sum(len(entities) for entities in pred_entities.values())
179
 
180
  # اضافه کردن ستون‌های جدید
181
  df['Precision'] = precisions
 
185
  # ذخیره نتایج
186
  self.results_df = df
187
 
188
+ # پیام وضعیت شامل اطلاعات debugging
189
+ status_message = f"ارزیابی انجام شد. کل موجودیت‌های یافت شده: {total_entities_found}"
190
+ if total_entities_found == 0:
191
+ status_message += "\n⚠️ هیچ موجودیتی تشخیص داده نشد! لطفاً فرمت داده‌ها را بررسی کنید."
192
+
193
+ return True, status_message, df
194
 
195
  except Exception as e:
196
  return False, f"خطا در پردازش فایل: {str(e)}", pd.DataFrame()