Spaces:
Running
Running
Delete app.py
Browse files
app.py
DELETED
|
@@ -1,1132 +0,0 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
-
import re
|
| 3 |
-
import os
|
| 4 |
-
import requests
|
| 5 |
-
import json
|
| 6 |
-
import logging
|
| 7 |
-
from typing import Dict, List, Tuple, Optional
|
| 8 |
-
from llm_sender_unified import create_llm_sender
|
| 9 |
-
|
| 10 |
-
# ✅ مدلهای موجود - بهروزرسانی نوامبر 2024
|
| 11 |
-
AVAILABLE_MODELS = {
|
| 12 |
-
"chatgpt": [
|
| 13 |
-
# GPT-5 Series (جدیدترین)
|
| 14 |
-
"gpt-5.1", # بهترین برای کدنویسی و وظایف agentic
|
| 15 |
-
"gpt-5", # مدل reasoning قبلی
|
| 16 |
-
# GPT-4 Series
|
| 17 |
-
"gpt-4.1", # هوشمندترین non-reasoning
|
| 18 |
-
"gpt-4o", # قدرتمند
|
| 19 |
-
"gpt-4o-mini", # سریع و ارزان
|
| 20 |
-
"gpt-4-turbo", # سریعتر از GPT-4
|
| 21 |
-
],
|
| 22 |
-
"grok": [
|
| 23 |
-
# Grok-4 Series (جدیدترین)
|
| 24 |
-
"grok-4-fast-reasoning", # سریع با reasoning
|
| 25 |
-
"grok-4-fast-non-reasoning", # سریع بدون reasoning
|
| 26 |
-
"grok-4-0709", # نسخه پایدار
|
| 27 |
-
# Grok-3 Series
|
| 28 |
-
"grok-3", # قدرتمند
|
| 29 |
-
"grok-3-mini", # سبک
|
| 30 |
-
# Grok-2 Series
|
| 31 |
-
"grok-2-vision-1212", # با قابلیت بینایی
|
| 32 |
-
"grok-2-1212", # نسخه پایدار
|
| 33 |
-
"grok-2" # نسخه قدیمی
|
| 34 |
-
]
|
| 35 |
-
}
|
| 36 |
-
|
| 37 |
-
logging.basicConfig(level=logging.INFO)
|
| 38 |
-
logger = logging.getLogger(__name__)
|
| 39 |
-
|
| 40 |
-
class AnonymizerAdvanced:
|
| 41 |
-
"""ناشناسساز پیشرفته با روشهای متعدد"""
|
| 42 |
-
|
| 43 |
-
def __init__(
|
| 44 |
-
self,
|
| 45 |
-
cerebras_key: str = None,
|
| 46 |
-
llm_provider: str = "chatgpt",
|
| 47 |
-
llm_model: str = None,
|
| 48 |
-
entities_to_anonymize: List[str] = None
|
| 49 |
-
):
|
| 50 |
-
self.cerebras_key = cerebras_key or os.getenv("CEREBRAS_API_KEY")
|
| 51 |
-
self.llm_provider = llm_provider
|
| 52 |
-
self.llm_model = llm_model
|
| 53 |
-
self.entities_to_anonymize = entities_to_anonymize or ["person", "company", "amount", "percent"]
|
| 54 |
-
self.mapping_table = {}
|
| 55 |
-
self.reverse_mapping = {}
|
| 56 |
-
|
| 57 |
-
# ایجاد LLM sender
|
| 58 |
-
self._create_llm_sender()
|
| 59 |
-
|
| 60 |
-
logger.info(f"✅ Anonymizer Advanced مقداردهی شد با {llm_provider}")
|
| 61 |
-
|
| 62 |
-
def _create_llm_sender(self):
|
| 63 |
-
"""ایجاد LLM sender مناسب"""
|
| 64 |
-
try:
|
| 65 |
-
# ✅ همیشه از Hugging Face Secrets استفاده کن
|
| 66 |
-
if self.llm_provider == "chatgpt":
|
| 67 |
-
api_key = os.getenv("OPENAI_API_KEY")
|
| 68 |
-
logger.info("🔑 استفاده از OPENAI_API_KEY از Secrets")
|
| 69 |
-
elif self.llm_provider == "grok":
|
| 70 |
-
api_key = os.getenv("XAI_API_KEY")
|
| 71 |
-
logger.info("🔑 استفاده از XAI_API_KEY از Secrets")
|
| 72 |
-
else:
|
| 73 |
-
api_key = None
|
| 74 |
-
logger.warning("⚠️ Provider ناشناخته")
|
| 75 |
-
|
| 76 |
-
# ایجاد sender
|
| 77 |
-
self.llm_sender = create_llm_sender(
|
| 78 |
-
provider=self.llm_provider,
|
| 79 |
-
api_key=api_key,
|
| 80 |
-
model=self.llm_model
|
| 81 |
-
)
|
| 82 |
-
|
| 83 |
-
logger.info(f"✅ LLM Sender ایجاد شد: {self.llm_provider} - {self.llm_sender.model}")
|
| 84 |
-
|
| 85 |
-
except Exception as e:
|
| 86 |
-
logger.error(f"❌ خطا در ایجاد LLM Sender: {e}")
|
| 87 |
-
# fallback to ChatGPT
|
| 88 |
-
self.llm_sender = create_llm_sender("chatgpt")
|
| 89 |
-
|
| 90 |
-
def set_llm_provider(self, provider: str, model: str = None, entities: List[str] = None):
|
| 91 |
-
"""تغییر provider و مدل LLM و موجودیتهای ناشناسسازی"""
|
| 92 |
-
self.llm_provider = provider
|
| 93 |
-
self.llm_model = model
|
| 94 |
-
if entities is not None:
|
| 95 |
-
self.entities_to_anonymize = entities
|
| 96 |
-
self._create_llm_sender()
|
| 97 |
-
logger.info(f"✅ LLM تغییر یافت به: {provider} - {model}")
|
| 98 |
-
logger.info(f"✅ موجودیتهای ناشناسسازی: {self.entities_to_anonymize}")
|
| 99 |
-
|
| 100 |
-
def anonymize_with_cerebras(self, text: str) -> Tuple[str, Dict]:
|
| 101 |
-
"""ناشناسسازی با Cerebras - بر اساس موجودیتهای انتخابی"""
|
| 102 |
-
logger.info("🧠 روش Cerebras...")
|
| 103 |
-
|
| 104 |
-
if not self.cerebras_key:
|
| 105 |
-
logger.error("❌ Cerebras API Key موجود نیست")
|
| 106 |
-
raise ValueError("Cerebras API Key مورد نیاز است")
|
| 107 |
-
|
| 108 |
-
# ✅ ساخت دستورات بر اساس موجودیتهای انتخابی
|
| 109 |
-
instructions = []
|
| 110 |
-
instruction_number = 1
|
| 111 |
-
|
| 112 |
-
if "person" in self.entities_to_anonymize:
|
| 113 |
-
instructions.append(f"{instruction_number}. اسامی اشخاص → person-01, person-02, ...")
|
| 114 |
-
instruction_number += 1
|
| 115 |
-
|
| 116 |
-
if "company" in self.entities_to_anonymize:
|
| 117 |
-
instructions.append(f"{instruction_number}. نام شرکتها/سازمانها → company-01, company-02, ...")
|
| 118 |
-
instruction_number += 1
|
| 119 |
-
|
| 120 |
-
if "amount" in self.entities_to_anonymize:
|
| 121 |
-
instructions.append(f"{instruction_number}. مقادیر پولی → amount-01, amount-02, ...")
|
| 122 |
-
instruction_number += 1
|
| 123 |
-
|
| 124 |
-
if "percent" in self.entities_to_anonymize:
|
| 125 |
-
instructions.append(f"{instruction_number}. درصدها → percent-01, percent-02, ...")
|
| 126 |
-
instruction_number += 1
|
| 127 |
-
|
| 128 |
-
# اگه هیچی انتخاب نشده، متن رو همونطور برگردون
|
| 129 |
-
if not instructions:
|
| 130 |
-
logger.warning("⚠️ هیچ موجودیتی برای ناشناسسازی انتخاب نشده!")
|
| 131 |
-
return text, {}
|
| 132 |
-
|
| 133 |
-
instructions_text = "\n".join(instructions)
|
| 134 |
-
instructions_text += f"\n{instruction_number}. فقط این توکنها استفاده کنید"
|
| 135 |
-
instructions_text += f"\n{instruction_number + 1}. شمارههای نسخه را درست حفظ کنید"
|
| 136 |
-
instructions_text += f"\n{instruction_number + 2}. اگر موجودیت تکرار شود از شماره قدیمی استفاده کنید"
|
| 137 |
-
|
| 138 |
-
try:
|
| 139 |
-
# مرحله 1: ناشناسسازی متن
|
| 140 |
-
prompt1 = f"""متن زیر را ناشناس کنید. قوانین:
|
| 141 |
-
{instructions_text}
|
| 142 |
-
|
| 143 |
-
متن:
|
| 144 |
-
{text}
|
| 145 |
-
|
| 146 |
-
خروجی: فقط متن ناشناس شده"""
|
| 147 |
-
|
| 148 |
-
response1 = requests.post(
|
| 149 |
-
"https://api.cerebras.ai/v1/chat/completions",
|
| 150 |
-
headers={
|
| 151 |
-
"Authorization": f"Bearer {self.cerebras_key}",
|
| 152 |
-
"Content-Type": "application/json"
|
| 153 |
-
},
|
| 154 |
-
json={
|
| 155 |
-
"model": "llama-3.3-70b",
|
| 156 |
-
"messages": [{"role": "user", "content": prompt1}],
|
| 157 |
-
"max_tokens": 4096,
|
| 158 |
-
"temperature": 0.1
|
| 159 |
-
},
|
| 160 |
-
timeout=60
|
| 161 |
-
)
|
| 162 |
-
|
| 163 |
-
if response1.status_code != 200:
|
| 164 |
-
logger.error(f"❌ Cerebras Error: {response1.status_code}")
|
| 165 |
-
raise Exception(f"Cerebras API Error: {response1.status_code}")
|
| 166 |
-
|
| 167 |
-
anonymized_text = response1.json()['choices'][0]['message']['content'].strip()
|
| 168 |
-
logger.info("✅ Cerebras: ناشناسسازی موفق")
|
| 169 |
-
|
| 170 |
-
# مرحله 2: استخراج mapping - فقط برای موجودیتهای انتخابی
|
| 171 |
-
mapping_instructions = []
|
| 172 |
-
json_example = "{\n"
|
| 173 |
-
|
| 174 |
-
if "person" in self.entities_to_anonymize:
|
| 175 |
-
mapping_instructions.append('- برای person-XX: نام کامل شخص (مثلاً "علی احمدی")')
|
| 176 |
-
json_example += ' "person-01": "متن اصلی کامل",\n'
|
| 177 |
-
|
| 178 |
-
if "company" in self.entities_to_anonymize:
|
| 179 |
-
mapping_instructions.append('- برای company-XX: نام کامل شرکت/سازمان (مثلاً "شرکت پتروشیمی")')
|
| 180 |
-
json_example += ' "company-01": "متن اصلی کامل",\n'
|
| 181 |
-
|
| 182 |
-
if "amount" in self.entities_to_anonymize:
|
| 183 |
-
mapping_instructions.append('- برای amount-XX: عدد + واحد (مثلاً "80 هزار تومان" یا "50 میلیارد ریال")')
|
| 184 |
-
json_example += ' "amount-01": "متن اصلی کامل با واحد",\n'
|
| 185 |
-
|
| 186 |
-
if "percent" in self.entities_to_anonymize:
|
| 187 |
-
mapping_instructions.append('- برای percent-XX: عدد + کلمه "درصد" (مثلاً "40 درصد" نه فقط "40")')
|
| 188 |
-
json_example += ' "percent-01": "عدد + درصد",\n'
|
| 189 |
-
|
| 190 |
-
json_example += " ...\n}"
|
| 191 |
-
mapping_instructions_text = "\n".join(mapping_instructions)
|
| 192 |
-
|
| 193 |
-
prompt2 = f"""متن اصلی:
|
| 194 |
-
{text}
|
| 195 |
-
|
| 196 |
-
متن ناشناس شده:
|
| 197 |
-
{anonymized_text}
|
| 198 |
-
|
| 199 |
-
لطفاً یک جدول mapping برای همه توکنهای ناشناس ایجاد کن.
|
| 200 |
-
برای هر توکن، متن اصلی کامل آن را مشخص کن.
|
| 201 |
-
|
| 202 |
-
**مهم:**
|
| 203 |
-
{mapping_instructions_text}
|
| 204 |
-
|
| 205 |
-
خروجی را به این فرمت JSON بده (فقط JSON، بدون توضیح اضافی):
|
| 206 |
-
{json_example}"""
|
| 207 |
-
|
| 208 |
-
response2 = requests.post(
|
| 209 |
-
"https://api.cerebras.ai/v1/chat/completions",
|
| 210 |
-
headers={
|
| 211 |
-
"Authorization": f"Bearer {self.cerebras_key}",
|
| 212 |
-
"Content-Type": "application/json"
|
| 213 |
-
},
|
| 214 |
-
json={
|
| 215 |
-
"model": "llama-3.3-70b",
|
| 216 |
-
"messages": [{"role": "user", "content": prompt2}],
|
| 217 |
-
"max_tokens": 2048,
|
| 218 |
-
"temperature": 0.1
|
| 219 |
-
},
|
| 220 |
-
timeout=60
|
| 221 |
-
)
|
| 222 |
-
|
| 223 |
-
if response2.status_code == 200:
|
| 224 |
-
mapping_text = response2.json()['choices'][0]['message']['content'].strip()
|
| 225 |
-
mapping_text = mapping_text.replace('```json', '').replace('```', '').strip()
|
| 226 |
-
|
| 227 |
-
try:
|
| 228 |
-
self.mapping_table = json.loads(mapping_text)
|
| 229 |
-
self._fix_percent_mapping()
|
| 230 |
-
self.reverse_mapping = {v: k for k, v in self.mapping_table.items()}
|
| 231 |
-
logger.info(f"✅ Mapping استخراج شد: {len(self.mapping_table)} موجودیت")
|
| 232 |
-
except json.JSONDecodeError:
|
| 233 |
-
logger.warning("⚠️ خطا در parse کردن JSON mapping - استفاده از روش fallback")
|
| 234 |
-
self._extract_mapping_from_text(text, anonymized_text)
|
| 235 |
-
else:
|
| 236 |
-
logger.warning("⚠️ خطا در دریافت mapping - استفاده از روش fallback")
|
| 237 |
-
self._extract_mapping_from_text(text, anonymized_text)
|
| 238 |
-
|
| 239 |
-
return anonymized_text, self.mapping_table
|
| 240 |
-
|
| 241 |
-
except Exception as e:
|
| 242 |
-
logger.error(f"❌ Cerebras Exception: {e}")
|
| 243 |
-
raise
|
| 244 |
-
|
| 245 |
-
def _fix_percent_mapping(self):
|
| 246 |
-
"""اصلاح mapping برای درصدها"""
|
| 247 |
-
for token, value in self.mapping_table.items():
|
| 248 |
-
value_str = str(value).strip()
|
| 249 |
-
|
| 250 |
-
if token.startswith('percent-'):
|
| 251 |
-
if not re.search(r'(درصد|%|درصدی)', value_str):
|
| 252 |
-
self.mapping_table[token] = f"{value_str} درصد"
|
| 253 |
-
logger.info(f"✅ اصلاح {token}: '{value_str}' → '{value_str} درصد'")
|
| 254 |
-
|
| 255 |
-
elif token.startswith('amount-'):
|
| 256 |
-
if not re.search(r'(میلیارد|میلیون|هزار|تومان|ریال|دلار|یورو|تن)', value_str):
|
| 257 |
-
logger.warning(f"⚠️ {token}: فقط عدد '{value_str}' - واحد مشخص نیست")
|
| 258 |
-
|
| 259 |
-
def _extract_mapping_from_text(self, original: str, anonymized: str):
|
| 260 |
-
"""استخراج mapping از متنهای اصلی و ناشناس شده - فقط برای موجودیتهای انتخابی"""
|
| 261 |
-
|
| 262 |
-
# ✅ استخراج فقط توکنهای انتخابی
|
| 263 |
-
all_tokens = []
|
| 264 |
-
for entity_type in self.entities_to_anonymize:
|
| 265 |
-
tokens = re.findall(f'{entity_type}-\\d+', anonymized)
|
| 266 |
-
all_tokens.extend([(t, entity_type) for t in tokens])
|
| 267 |
-
|
| 268 |
-
all_tokens = sorted(set(all_tokens), key=lambda x: (x[1], int(x[0].split('-')[1])))
|
| 269 |
-
|
| 270 |
-
# ✅ الگوهای موجودیت - فقط برای انتخابیها
|
| 271 |
-
patterns = {}
|
| 272 |
-
if "person" in self.entities_to_anonymize:
|
| 273 |
-
patterns['person'] = r'\b[ء-ي]+\s+[ء-ي]+(?:\s+[ء-ي]+)*\b'
|
| 274 |
-
if "company" in self.entities_to_anonymize:
|
| 275 |
-
patterns['company'] = r'(?:شرکت|بانک|سازمان|گروه|هلدینگ)\s+[ء-ي]+(?:\s+[ء-ي]+)*'
|
| 276 |
-
if "amount" in self.entities_to_anonymize:
|
| 277 |
-
patterns['amount'] = r'\d+(?:\.\d+)?\s*(?:میلیارد|میلیون|هزار|تومان|ریال|دلار|یورو|تن)'
|
| 278 |
-
if "percent" in self.entities_to_anonymize:
|
| 279 |
-
patterns['percent'] = r'\d+(?:\.\d+)?\s*(?:درصد|%|درصدی)'
|
| 280 |
-
|
| 281 |
-
original_entities = {}
|
| 282 |
-
for entity_type, pattern in patterns.items():
|
| 283 |
-
matches = list(re.finditer(pattern, original))
|
| 284 |
-
original_entities[entity_type] = [m.group().strip() for m in matches]
|
| 285 |
-
|
| 286 |
-
for token, entity_type in all_tokens:
|
| 287 |
-
if entity_type in original_entities and original_entities[entity_type]:
|
| 288 |
-
token_num = int(token.split('-')[1]) - 1
|
| 289 |
-
|
| 290 |
-
if token_num < len(original_entities[entity_type]):
|
| 291 |
-
original_text = original_entities[entity_type][token_num]
|
| 292 |
-
self.mapping_table[token] = original_text
|
| 293 |
-
self.reverse_mapping[original_text] = token
|
| 294 |
-
else:
|
| 295 |
-
original_text = original_entities[entity_type][-1]
|
| 296 |
-
if token not in self.mapping_table:
|
| 297 |
-
self.mapping_table[token] = original_text
|
| 298 |
-
self.reverse_mapping[original_text] = token
|
| 299 |
-
|
| 300 |
-
def analyze_with_llm(self, anonymized_text: str, analysis_prompt: str = None) -> str:
|
| 301 |
-
"""استفاده از LLM یکپارچه"""
|
| 302 |
-
logger.info(f"🤖 {self.llm_provider.upper()} اجرای پرامپت...")
|
| 303 |
-
|
| 304 |
-
if not analysis_prompt or not analysis_prompt.strip():
|
| 305 |
-
logger.info("⚠️ پرامپت خالی - بدون تحلیل")
|
| 306 |
-
return "⚠️ هیچ دستور تحلیل داده نشده است"
|
| 307 |
-
|
| 308 |
-
# ✅ بررسی اینکه آیا مدل GPT-4 است
|
| 309 |
-
is_gpt4 = self.llm_model and any(x in self.llm_model.lower() for x in ['gpt-4', 'gpt4'])
|
| 310 |
-
|
| 311 |
-
if is_gpt4:
|
| 312 |
-
# ✅ پرامپت ویژه GPT-4 با مثالهای واقعی
|
| 313 |
-
logger.info("🎯 استفاده از پرامپت ویژه GPT-4")
|
| 314 |
-
return self._analyze_with_gpt4_prompt(anonymized_text, analysis_prompt)
|
| 315 |
-
else:
|
| 316 |
-
# پرامپت عادی برای GPT-5 و Grok
|
| 317 |
-
return self._analyze_with_standard_prompt(anonymized_text, analysis_prompt)
|
| 318 |
-
|
| 319 |
-
def _analyze_with_gpt4_prompt(self, anonymized_text: str, analysis_prompt: str) -> str:
|
| 320 |
-
"""پرامپت ویژه GPT-4 با few-shot examples"""
|
| 321 |
-
|
| 322 |
-
# ✅ مثالهای واقعی Few-Shot
|
| 323 |
-
few_shot_examples = """
|
| 324 |
-
EXAMPLE 1 - CORRECT:
|
| 325 |
-
Input: "company-01 فروش amount-01 داشت"
|
| 326 |
-
Your output should be EXACTLY: "company-01 فروش amount-01 داشت"
|
| 327 |
-
NOT: "company-01 فروش مبلغ amount-01 داشت"
|
| 328 |
-
|
| 329 |
-
EXAMPLE 2 - CORRECT:
|
| 330 |
-
Input: "amount-02 به amount-03 رسید"
|
| 331 |
-
Your output should be EXACTLY: "amount-02 به amount-03 رسید"
|
| 332 |
-
NOT: "مبلغ amount-02 به amount-03 رسید"
|
| 333 |
-
|
| 334 |
-
EXAMPLE 3 - CORRECT:
|
| 335 |
-
Input: "company-01 سود percent-01 داشت"
|
| 336 |
-
Your output should be EXACTLY: "company-01 سود percent-01 داشت"
|
| 337 |
-
NOT: "شرکت company-01 سود درصد percent-01 داشت"
|
| 338 |
-
"""
|
| 339 |
-
|
| 340 |
-
# لیست توکنهای انتخابی
|
| 341 |
-
tokens_list = []
|
| 342 |
-
if "person" in self.entities_to_anonymize:
|
| 343 |
-
tokens_list.append("person-XX")
|
| 344 |
-
if "company" in self.entities_to_anonymize:
|
| 345 |
-
tokens_list.append("company-XX")
|
| 346 |
-
if "amount" in self.entities_to_anonymize:
|
| 347 |
-
tokens_list.append("amount-XX")
|
| 348 |
-
if "percent" in self.entities_to_anonymize:
|
| 349 |
-
tokens_list.append("percent-XX")
|
| 350 |
-
|
| 351 |
-
tokens_str = ", ".join(tokens_list)
|
| 352 |
-
|
| 353 |
-
# ✅ پرامپت انگلیسی برای GPT-4 (بهتر کار میکند)
|
| 354 |
-
combined_text = f"""You are processing anonymized Persian/Farsi text containing placeholder tokens.
|
| 355 |
-
|
| 356 |
-
ANONYMIZED TEXT:
|
| 357 |
-
{anonymized_text}
|
| 358 |
-
|
| 359 |
-
USER REQUEST:
|
| 360 |
-
{analysis_prompt}
|
| 361 |
-
|
| 362 |
-
CRITICAL RULES:
|
| 363 |
-
1. Use ONLY these exact tokens: {tokens_str}
|
| 364 |
-
2. NEVER add words before/after tokens
|
| 365 |
-
3. Keep the EXACT format: amount-01 (not "مبلغ amount-01" or "amount- 01")
|
| 366 |
-
4. Do NOT create new tokens
|
| 367 |
-
5. Preserve the exact structure
|
| 368 |
-
|
| 369 |
-
{few_shot_examples}
|
| 370 |
-
|
| 371 |
-
FORBIDDEN PATTERNS - NEVER USE:
|
| 372 |
-
❌ "مبلغ amount-01" → ✅ Use: "amount-01"
|
| 373 |
-
❌ "شرکت company-01" → ✅ Use: "company-01"
|
| 374 |
-
❌ "فروش به amount-02" → ✅ Use: "فروش amount-02"
|
| 375 |
-
❌ "درصد percent-01" → ✅ Use: "percent-01"
|
| 376 |
-
❌ "amount- 01" (space) → ✅ Use: "amount-01"
|
| 377 |
-
|
| 378 |
-
Now process the text following these rules EXACTLY."""
|
| 379 |
-
|
| 380 |
-
try:
|
| 381 |
-
# ✅ temperature خیلی پایین برای GPT-4
|
| 382 |
-
logger.info(f"🌡️ Temperature: 0.05 (GPT-4 ویژه)")
|
| 383 |
-
|
| 384 |
-
response = self.llm_sender.send(
|
| 385 |
-
combined_text,
|
| 386 |
-
lang='en', # انگلیسی برای GPT-4
|
| 387 |
-
temperature=0.05, # خیلی خیلی پایین
|
| 388 |
-
max_tokens=2000
|
| 389 |
-
)
|
| 390 |
-
|
| 391 |
-
# ✅ دیباگ: نمایش خروجی خام LLM
|
| 392 |
-
logger.info("=" * 60)
|
| 393 |
-
logger.info("🔍 DEBUG - خروجی خام GPT-4:")
|
| 394 |
-
logger.info(response[:500] + "..." if len(response) > 500 else response)
|
| 395 |
-
logger.info("=" * 60)
|
| 396 |
-
|
| 397 |
-
# ✅ پاکسازی قویتر
|
| 398 |
-
cleaned_response = self._clean_llm_response(response)
|
| 399 |
-
|
| 400 |
-
# ✅ دیباگ: نمایش خروجی بعد از clean
|
| 401 |
-
logger.info("=" * 60)
|
| 402 |
-
logger.info("🧹 DEBUG - خروجی بعد از clean:")
|
| 403 |
-
logger.info(cleaned_response[:500] + "..." if len(cleaned_response) > 500 else cleaned_response)
|
| 404 |
-
logger.info("=" * 60)
|
| 405 |
-
|
| 406 |
-
logger.info(f"✅ GPT-4: {len(cleaned_response)} کاراکتر")
|
| 407 |
-
return cleaned_response
|
| 408 |
-
|
| 409 |
-
except Exception as e:
|
| 410 |
-
logger.error(f"❌ GPT-4 Exception: {e}")
|
| 411 |
-
return f"❌ خطا در ارتباط با GPT-4: {str(e)}"
|
| 412 |
-
|
| 413 |
-
def _analyze_with_standard_prompt(self, anonymized_text: str, analysis_prompt: str) -> str:
|
| 414 |
-
"""پرامپت استاندارد برای GPT-5 و Grok"""
|
| 415 |
-
|
| 416 |
-
tokens_instruction = []
|
| 417 |
-
examples = []
|
| 418 |
-
|
| 419 |
-
if "person" in self.entities_to_anonymize:
|
| 420 |
-
tokens_instruction.append("person-XX")
|
| 421 |
-
examples.append("✅ صحیح: person-01 در جلسه حضور داشت\n❌ غلط: آقای person-01")
|
| 422 |
-
|
| 423 |
-
if "company" in self.entities_to_anonymize:
|
| 424 |
-
tokens_instruction.append("company-XX")
|
| 425 |
-
examples.append("✅ صحیح: company-01 فعالیت کرد\n❌ غلط: شرکت company-01")
|
| 426 |
-
|
| 427 |
-
if "amount" in self.entities_to_anonymize:
|
| 428 |
-
tokens_instruction.append("amount-XX")
|
| 429 |
-
examples.append("✅ صحیح: فروش amount-01 بود\n❌ غلط: فروش مبلغ amount-01")
|
| 430 |
-
|
| 431 |
-
if "percent" in self.entities_to_anonymize:
|
| 432 |
-
tokens_instruction.append("percent-XX")
|
| 433 |
-
examples.append("✅ صحیح: رشد percent-01 داشت\n❌ غلط: رشد درصد percent-01")
|
| 434 |
-
|
| 435 |
-
tokens_str = ", ".join(tokens_instruction)
|
| 436 |
-
examples_str = "\n".join(examples)
|
| 437 |
-
|
| 438 |
-
combined_text = f"""متن ناشناسسازی شده:
|
| 439 |
-
{anonymized_text}
|
| 440 |
-
|
| 441 |
-
دستورات:
|
| 442 |
-
{analysis_prompt}
|
| 443 |
-
|
| 444 |
-
⚠️ قوانین مهم:
|
| 445 |
-
1. فقط از کدهای ناشناس موجود استفاده کن: {tokens_str}
|
| 446 |
-
2. هیچ کلمهای قبل یا بعد از این کدها اضافه نکن
|
| 447 |
-
3. کد جدید ایجاد نکن
|
| 448 |
-
4. ساختار دقیق متن را حفظ کن
|
| 449 |
-
|
| 450 |
-
مثالهای صحیح و غلط:
|
| 451 |
-
{examples_str}"""
|
| 452 |
-
|
| 453 |
-
try:
|
| 454 |
-
temp_to_use = 0.2
|
| 455 |
-
logger.info(f"🌡️ Temperature: {temp_to_use}")
|
| 456 |
-
|
| 457 |
-
response = self.llm_sender.send(
|
| 458 |
-
combined_text,
|
| 459 |
-
lang='fa',
|
| 460 |
-
temperature=temp_to_use,
|
| 461 |
-
max_tokens=2000
|
| 462 |
-
)
|
| 463 |
-
|
| 464 |
-
response = self._clean_llm_response(response)
|
| 465 |
-
|
| 466 |
-
logger.info(f"✅ {self.llm_provider.upper()}: {len(response)} کاراکتر")
|
| 467 |
-
return response
|
| 468 |
-
|
| 469 |
-
except Exception as e:
|
| 470 |
-
logger.error(f"❌ {self.llm_provider.upper()} Exception: {e}")
|
| 471 |
-
return f"❌ خطا در ارتباط با {self.llm_provider.upper()}: {str(e)}"
|
| 472 |
-
|
| 473 |
-
def _clean_llm_response(self, text: str) -> str:
|
| 474 |
-
"""پاکسازی کلمات اضافی که LLM ممکن است قبل از موجودیتها اضافه کرده باشد"""
|
| 475 |
-
logger.info("🧹 پاکسازی کلمات اضافی...")
|
| 476 |
-
|
| 477 |
-
cleaned = text
|
| 478 |
-
changes_made = 0
|
| 479 |
-
|
| 480 |
-
# الگوهای کلمات اضافی برای هر نوع موجودیت
|
| 481 |
-
patterns = []
|
| 482 |
-
|
| 483 |
-
if "person" in self.entities_to_anonymize:
|
| 484 |
-
patterns.extend([
|
| 485 |
-
(r'(?:آقای|خانم|شخص|فرد)\s+(person-\d+)', r'\1'),
|
| 486 |
-
(r'(person-\d+)\s+(?:نامدار|محترم|عزیز)', r'\1'),
|
| 487 |
-
])
|
| 488 |
-
|
| 489 |
-
if "company" in self.entities_to_anonymize:
|
| 490 |
-
patterns.extend([
|
| 491 |
-
(r'(?:شرکت|سازمان|گروه|هلدینگ|بانک|موسسه)\s+(company-\d+)', r'\1'),
|
| 492 |
-
(r'(company-\d+)\s+(?:محترم)', r'\1'),
|
| 493 |
-
])
|
| 494 |
-
|
| 495 |
-
if "amount" in self.entities_to_anonymize:
|
| 496 |
-
patterns.extend([
|
| 497 |
-
# ✅ الگوهای کامل برای amount - تمام حالات ممکن
|
| 498 |
-
# حالت 1: کلمات قبل از amount
|
| 499 |
-
(r'(?:مبلغ|رقم|عدد|قیمت|ارزش|مقدار)\s+(amount-\d+)', r'\1'),
|
| 500 |
-
(r'(?:فروش|درآمد|سود|زیان|هزینه|خرج)\s+(amount-\d+)', r'\1'),
|
| 501 |
-
(r'(?:دارایی|بدهی|سرمایه|پول|وام)\s+(amount-\d+)', r'\1'),
|
| 502 |
-
|
| 503 |
-
# حالت 2: حروف اضافه قبل از amount
|
| 504 |
-
(r'\bبه\s+(amount-\d+)', r'\1'),
|
| 505 |
-
(r'\bبا\s+(amount-\d+)', r'\1'),
|
| 506 |
-
(r'\bاز\s+(amount-\d+)', r'\1'),
|
| 507 |
-
(r'\bتا\s+(amount-\d+)', r'\1'),
|
| 508 |
-
(r'\bدر\s+(amount-\d+)', r'\1'),
|
| 509 |
-
(r'\bبرای\s+(amount-\d+)', r'\1'),
|
| 510 |
-
|
| 511 |
-
# حالت 3: واحدها بعد از amount (اگر نباید باشند)
|
| 512 |
-
(r'(amount-\d+)\s+(?:ریال|تومان|دلار|یورو)', r'\1'),
|
| 513 |
-
(r'(amount-\d+)\s+(?:میلیون|میلیارد|هزار|تریلیون)', r'\1'),
|
| 514 |
-
|
| 515 |
-
# حالت 4: ترکیبات
|
| 516 |
-
(r'(?:به\s+مبلغ)\s+(amount-\d+)', r'\1'),
|
| 517 |
-
(r'(?:با\s+ارزش)\s+(amount-\d+)', r'\1'),
|
| 518 |
-
(r'(?:در\s+حد)\s+(amount-\d+)', r'\1'),
|
| 519 |
-
|
| 520 |
-
# حالت 5: فعل + amount (بدون حرف اضافه)
|
| 521 |
-
(r'(?:رسید|رسیده|می\u200cرسد)\s+(amount-\d+)', r'\1'),
|
| 522 |
-
(r'(?:شد|شده|می\u200cشود)\s+(amount-\d+)', r'\1'),
|
| 523 |
-
(r'(?:بود|بوده|است)\s+(amount-\d+)', r'\1'),
|
| 524 |
-
])
|
| 525 |
-
|
| 526 |
-
if "percent" in self.entities_to_anonymize:
|
| 527 |
-
patterns.extend([
|
| 528 |
-
(r'(?:درصد|%)\s+(percent-\d+)', r'\1'),
|
| 529 |
-
(r'(percent-\d+)\s+(?:درصد|درصدی|%)', r'\1'),
|
| 530 |
-
])
|
| 531 |
-
|
| 532 |
-
# اعمال الگوها
|
| 533 |
-
for pattern, replacement in patterns:
|
| 534 |
-
new_text = re.sub(pattern, replacement, cleaned)
|
| 535 |
-
if new_text != cleaned:
|
| 536 |
-
count = len(re.findall(pattern, cleaned))
|
| 537 |
-
changes_made += count
|
| 538 |
-
cleaned = new_text
|
| 539 |
-
logger.info(f" ✅ حذف '{pattern}': {count} مورد")
|
| 540 |
-
|
| 541 |
-
if changes_made > 0:
|
| 542 |
-
logger.info(f"✅ {changes_made} کلمه اضافی حذف شد")
|
| 543 |
-
else:
|
| 544 |
-
logger.info("✅ کلمه اضا��ی یافت نشد")
|
| 545 |
-
|
| 546 |
-
return cleaned
|
| 547 |
-
|
| 548 |
-
def restore_text(self, anonymized_text: str) -> str:
|
| 549 |
-
"""بازگردانی متن با ترتیب بهینه برای amount"""
|
| 550 |
-
logger.info("🔄 بازگردانی متن...")
|
| 551 |
-
|
| 552 |
-
if not self.mapping_table:
|
| 553 |
-
logger.warning("⚠️ جدول نگاشت خالی است")
|
| 554 |
-
return anonymized_text
|
| 555 |
-
|
| 556 |
-
logger.info(f"📋 تعداد موجودیتها در mapping: {len(self.mapping_table)}")
|
| 557 |
-
|
| 558 |
-
# ✅ STEP 1: normalize (hyphen یونیکد و جداسازی کلمات چسبیده)
|
| 559 |
-
restored = self._normalize_tokens(anonymized_text)
|
| 560 |
-
|
| 561 |
-
# ✅ STEP 2: restore قوی مخصوص amount با regex (قبل از clean!)
|
| 562 |
-
# این کلیدی است - باید قبل از clean انجام شود
|
| 563 |
-
logger.info("🔥 بازگردانی amount با regex...")
|
| 564 |
-
amount_restored_count = 0
|
| 565 |
-
for placeholder, original in self.mapping_table.items():
|
| 566 |
-
if placeholder.startswith("amount-"):
|
| 567 |
-
# استخراج شماره
|
| 568 |
-
num = placeholder.split("-")[1]
|
| 569 |
-
# الگوی regex: amount [فاصله اختیاری] - [فاصله اختیاری] شماره
|
| 570 |
-
pattern = rf'amount\s*-\s*{num}'
|
| 571 |
-
matches = re.findall(pattern, restored)
|
| 572 |
-
if matches:
|
| 573 |
-
restored = re.sub(pattern, original, restored)
|
| 574 |
-
amount_restored_count += 1
|
| 575 |
-
logger.info(f"✅ regex: {placeholder} → {original[:30]}...")
|
| 576 |
-
|
| 577 |
-
if amount_restored_count > 0:
|
| 578 |
-
logger.info(f"✅ {amount_restored_count} amount با regex بازگردانی شد")
|
| 579 |
-
|
| 580 |
-
# ✅ STEP 3: clean (حذف کلمات اضافی)
|
| 581 |
-
# حالا که amount ها restore شدن، میتونیم clean کنیم
|
| 582 |
-
restored = self._clean_for_restore(restored)
|
| 583 |
-
|
| 584 |
-
# ✅ STEP 4: replace ساده برای بقیه (person, company, percent)
|
| 585 |
-
replacements_count = 0
|
| 586 |
-
for placeholder, original in sorted(self.mapping_table.items(), key=lambda x: len(x[0]), reverse=True):
|
| 587 |
-
# amount ها رو قبلاً restore کردیم
|
| 588 |
-
if placeholder.startswith("amount-"):
|
| 589 |
-
continue
|
| 590 |
-
|
| 591 |
-
if placeholder in restored:
|
| 592 |
-
restored = restored.replace(placeholder, original)
|
| 593 |
-
replacements_count += 1
|
| 594 |
-
logger.info(f"✅ {placeholder} → {original[:30]}...")
|
| 595 |
-
else:
|
| 596 |
-
logger.warning(f"⚠️ {placeholder} در متن یافت نشد!")
|
| 597 |
-
|
| 598 |
-
total_restored = amount_restored_count + replacements_count
|
| 599 |
-
logger.info(f"✅ بازگردانی کامل - {total_restored}/{len(self.mapping_table)} جایگزین شد")
|
| 600 |
-
|
| 601 |
-
# ✅ STEP 5: fallback regex برای توکنهای باقیمانده
|
| 602 |
-
if total_restored < len(self.mapping_table):
|
| 603 |
-
logger.info("🔍 تلاش برای یافتن توکنهای گمشده با regex...")
|
| 604 |
-
restored = self._restore_with_regex(restored)
|
| 605 |
-
|
| 606 |
-
# هشدار در صورت شکست کامل
|
| 607 |
-
if total_restored == 0 and len(self.mapping_table) > 0:
|
| 608 |
-
logger.error("❌ هیچ توکنی جایگزین نشد! متن ورودی احتمالاً متفاوت است.")
|
| 609 |
-
|
| 610 |
-
return restored
|
| 611 |
-
|
| 612 |
-
def _clean_for_restore(self, text: str) -> str:
|
| 613 |
-
"""پاکسازی خاص برای بازگردانی (شبیه _clean_llm_response اما سبکتر)"""
|
| 614 |
-
logger.info("🧹 پاکسازی قبل از بازگردانی...")
|
| 615 |
-
|
| 616 |
-
cleaned = text
|
| 617 |
-
changes_made = 0
|
| 618 |
-
|
| 619 |
-
patterns = []
|
| 620 |
-
|
| 621 |
-
if "amount" in self.entities_to_anonymize:
|
| 622 |
-
patterns.extend([
|
| 623 |
-
(r'(?:مبلغ|رقم|عدد|قیمت|ارزش|فروش|درآمد|هزینه|سود|زیان)\s+(amount-\d+)', r'\1'),
|
| 624 |
-
(r'\bبه\s+(amount-\d+)', r'\1'),
|
| 625 |
-
(r'\bبا\s+(amount-\d+)', r'\1'),
|
| 626 |
-
(r'\bاز\s+(amount-\d+)', r'\1'),
|
| 627 |
-
(r'\bتا\s+(amount-\d+)', r'\1'),
|
| 628 |
-
])
|
| 629 |
-
|
| 630 |
-
for pattern, replacement in patterns:
|
| 631 |
-
new_text = re.sub(pattern, replacement, cleaned)
|
| 632 |
-
if new_text != cleaned:
|
| 633 |
-
changes_made += re.subn(pattern, replacement, cleaned)[1]
|
| 634 |
-
cleaned = new_text
|
| 635 |
-
|
| 636 |
-
if changes_made > 0:
|
| 637 |
-
logger.info(f"✅ {changes_made} کلمه اضافی حذف شد")
|
| 638 |
-
|
| 639 |
-
return cleaned
|
| 640 |
-
|
| 641 |
-
def _restore_with_regex(self, text: str) -> str:
|
| 642 |
-
"""بازگردانی با استفاده از regex برای پیدا کردن توکنهای دارای کلمات اضافی"""
|
| 643 |
-
restored = text
|
| 644 |
-
|
| 645 |
-
for placeholder, original in self.mapping_table.items():
|
| 646 |
-
# اگر قبلاً جایگزین شده، رد شو
|
| 647 |
-
if placeholder not in text:
|
| 648 |
-
# الگوی regex: کلمه اضافی (اختیاری) + توکن
|
| 649 |
-
# مثلاً: "فروش amount-01" یا "مبلغ amount-05"
|
| 650 |
-
entity_type = placeholder.split('-')[0]
|
| 651 |
-
entity_num = placeholder.split('-')[1]
|
| 652 |
-
|
| 653 |
-
# الگوهای مختلف
|
| 654 |
-
patterns = [
|
| 655 |
-
# کلمه فارسی + فاصله + توکن
|
| 656 |
-
rf'[ء-ي]+\s+({entity_type}-{entity_num})\b',
|
| 657 |
-
# توکن + فاصله + کلمه فارسی
|
| 658 |
-
rf'\b({entity_type}-{entity_num})\s+[ء-ي]+',
|
| 659 |
-
# فاصله اضافی داخل توکن
|
| 660 |
-
rf'\b{entity_type}\s+-\s+{entity_num}\b',
|
| 661 |
-
]
|
| 662 |
-
|
| 663 |
-
for pattern in patterns:
|
| 664 |
-
matches = list(re.finditer(pattern, restored))
|
| 665 |
-
if matches:
|
| 666 |
-
logger.info(f"✅ پیدا شد با regex: {pattern}")
|
| 667 |
-
for match in matches:
|
| 668 |
-
# جایگزینی کل عبارت با فقط original
|
| 669 |
-
full_match = match.group(0)
|
| 670 |
-
# اگر توکن داخل match هست، فقط اون رو جایگزین کن
|
| 671 |
-
if placeholder in full_match:
|
| 672 |
-
restored = restored.replace(full_match, full_match.replace(placeholder, original))
|
| 673 |
-
else:
|
| 674 |
-
# اگر فرمت توکن متفاوت بود
|
| 675 |
-
restored = restored.replace(full_match, original)
|
| 676 |
-
logger.info(f"✅ regex: {placeholder} → {original[:30]}...")
|
| 677 |
-
break
|
| 678 |
-
|
| 679 |
-
return restored
|
| 680 |
-
|
| 681 |
-
def _normalize_tokens(self, text: str) -> str:
|
| 682 |
-
"""نرمالسازی توکنها - حذف فاصلههای اضافی و hyphen یونیکد"""
|
| 683 |
-
logger.info("🧹 نرمالسازی توکنها...")
|
| 684 |
-
|
| 685 |
-
normalized = text
|
| 686 |
-
changes = 0
|
| 687 |
-
|
| 688 |
-
# ✅ 1. نرمالسازی hyphen های یونیکد برای همه موجودیتها
|
| 689 |
-
# این hyphen ها: ‐ ‑ ‒ – — − و hyphen معمولی -
|
| 690 |
-
unicode_hyphens = r'[\u2010\u2011\u2012\u2013\u2014\u2212\-]'
|
| 691 |
-
|
| 692 |
-
for entity_type in self.entities_to_anonymize:
|
| 693 |
-
# تبدیل همه hyphen ها به - معمولی
|
| 694 |
-
pattern = rf'{entity_type}{unicode_hyphens}(\d+)'
|
| 695 |
-
replacement = rf'{entity_type}-\1'
|
| 696 |
-
count = len(re.findall(pattern, normalized))
|
| 697 |
-
if count > 0:
|
| 698 |
-
normalized = re.sub(pattern, replacement, normalized)
|
| 699 |
-
changes += count
|
| 700 |
-
logger.info(f" ✅ {entity_type}: {count} hyphen یونیکد نرمال شد")
|
| 701 |
-
|
| 702 |
-
# ✅ 2. حذف فاضلههای اضافی داخل توکن
|
| 703 |
-
for entity_type in self.entities_to_anonymize:
|
| 704 |
-
pattern = rf'{entity_type}\s+-\s+(\d+)'
|
| 705 |
-
replacement = rf'{entity_type}-\1'
|
| 706 |
-
count = len(re.findall(pattern, normalized))
|
| 707 |
-
if count > 0:
|
| 708 |
-
normalized = re.sub(pattern, replacement, normalized)
|
| 709 |
-
changes += count
|
| 710 |
-
logger.info(f" ✅ {entity_type}: {count} فاصله اضافی حذف شد")
|
| 711 |
-
|
| 712 |
-
# ✅ 3. جدا کردن توکنها از کلمات فارسی چسبیده (ویژه amount)
|
| 713 |
-
# مثال: amount-01در → amount-01 در
|
| 714 |
-
if "amount" in self.entities_to_anonymize:
|
| 715 |
-
pattern = r'(amount-\d+)([ء-ي])'
|
| 716 |
-
replacement = r'\1 \2'
|
| 717 |
-
before = normalized
|
| 718 |
-
normalized = re.sub(pattern, replacement, normalized)
|
| 719 |
-
if normalized != before:
|
| 720 |
-
count = len(re.findall(pattern, before))
|
| 721 |
-
changes += count
|
| 722 |
-
logger.info(f" ✅ amount: {count} کلمه چسبیده جدا شد")
|
| 723 |
-
|
| 724 |
-
# ✅ 4. جدا کردن توکنها از نشانهگذاری (ویژه amount)
|
| 725 |
-
# مثال: amount-01، → amount-01 ،
|
| 726 |
-
if "amount" in self.entities_to_anonymize:
|
| 727 |
-
pattern = r'(amount-\d+)([،؛:.!?])'
|
| 728 |
-
replacement = r'\1 \2'
|
| 729 |
-
before = normalized
|
| 730 |
-
normalized = re.sub(pattern, replacement, normalized)
|
| 731 |
-
if normalized != before:
|
| 732 |
-
count = len(re.findall(pattern, before))
|
| 733 |
-
changes += count
|
| 734 |
-
logger.info(f" ✅ amount: {count} نشانهگذاری جدا شد")
|
| 735 |
-
|
| 736 |
-
if changes > 0:
|
| 737 |
-
logger.info(f"✅ مجموع {changes} تغییر نرمالسازی")
|
| 738 |
-
|
| 739 |
-
return normalized
|
| 740 |
-
|
| 741 |
-
def get_mapping_table_md(self) -> str:
|
| 742 |
-
"""تبدیل جدول نگاشت به Markdown"""
|
| 743 |
-
if not self.mapping_table:
|
| 744 |
-
return "### 📋 ج��ول نگاشت\n\nهیچ موجودیتی شناسایی نشد"
|
| 745 |
-
|
| 746 |
-
table = "### 📋 جدول نگاشت\n\n"
|
| 747 |
-
table += "| شناسه | متن اصلی |\n"
|
| 748 |
-
table += "|-------|----------|\n"
|
| 749 |
-
|
| 750 |
-
for token, original in sorted(self.mapping_table.items()):
|
| 751 |
-
table += f"| **{token}** | {original} |\n"
|
| 752 |
-
|
| 753 |
-
return table
|
| 754 |
-
|
| 755 |
-
# متغیر سراسری
|
| 756 |
-
anonymizer = None
|
| 757 |
-
|
| 758 |
-
def process(
|
| 759 |
-
input_text: str,
|
| 760 |
-
analysis_prompt: str,
|
| 761 |
-
llm_provider: str,
|
| 762 |
-
llm_model: str,
|
| 763 |
-
anonymize_all: bool,
|
| 764 |
-
anonymize_person: bool,
|
| 765 |
-
anonymize_company: bool,
|
| 766 |
-
anonymize_amount: bool,
|
| 767 |
-
anonymize_percent: bool
|
| 768 |
-
):
|
| 769 |
-
"""پردازش متن - 4 مرحله"""
|
| 770 |
-
global anonymizer
|
| 771 |
-
|
| 772 |
-
if not input_text.strip():
|
| 773 |
-
return "", "", "", ""
|
| 774 |
-
|
| 775 |
-
# ✅ ساخت لیست موجودیتهای انتخابی
|
| 776 |
-
if anonymize_all:
|
| 777 |
-
entities = ["person", "company", "amount", "percent"]
|
| 778 |
-
else:
|
| 779 |
-
entities = []
|
| 780 |
-
if anonymize_person:
|
| 781 |
-
entities.append("person")
|
| 782 |
-
if anonymize_company:
|
| 783 |
-
entities.append("company")
|
| 784 |
-
if anonymize_amount:
|
| 785 |
-
entities.append("amount")
|
| 786 |
-
if anonymize_percent:
|
| 787 |
-
entities.append("percent")
|
| 788 |
-
|
| 789 |
-
# اگه هیچی انتخاب نشده
|
| 790 |
-
if not entities:
|
| 791 |
-
return "", "❌ لطفاً حداقل یک موجودیت برای ناشناسسازی انتخاب کنید", "", ""
|
| 792 |
-
|
| 793 |
-
cerebras_key = os.getenv("CEREBRAS_API_KEY")
|
| 794 |
-
|
| 795 |
-
# ایجاد یا آپدیت anonymizer
|
| 796 |
-
if not anonymizer:
|
| 797 |
-
anonymizer = AnonymizerAdvanced(
|
| 798 |
-
cerebras_key,
|
| 799 |
-
llm_provider=llm_provider,
|
| 800 |
-
llm_model=llm_model,
|
| 801 |
-
entities_to_anonymize=entities
|
| 802 |
-
)
|
| 803 |
-
else:
|
| 804 |
-
anonymizer.set_llm_provider(llm_provider, llm_model, entities)
|
| 805 |
-
anonymizer.mapping_table = {}
|
| 806 |
-
anonymizer.reverse_mapping = {}
|
| 807 |
-
|
| 808 |
-
try:
|
| 809 |
-
logger.info("=" * 70)
|
| 810 |
-
logger.info(f"🚀 شروع پردازش - LLM: {llm_provider} ({llm_model})")
|
| 811 |
-
logger.info(f"🎯 موجودیتهای انتخابی: {', '.join(entities)}")
|
| 812 |
-
logger.info("=" * 70)
|
| 813 |
-
|
| 814 |
-
# مرحله 1: ناشناسسازی
|
| 815 |
-
logger.info("🔐 مرحله 1: ناشناسسازی...")
|
| 816 |
-
anonymized_text, _ = anonymizer.anonymize_with_cerebras(input_text)
|
| 817 |
-
logger.info(f"✅ ناشناسسازی: {len(anonymized_text)} کاراکتر")
|
| 818 |
-
|
| 819 |
-
# ✅ دیباگ: بررسی توکنهای موجود در متن ناشناس
|
| 820 |
-
logger.info("=" * 70)
|
| 821 |
-
logger.info("🔍 DEBUG - توکنهای موجود در متن ناشناس:")
|
| 822 |
-
for entity_type in entities:
|
| 823 |
-
tokens_found = re.findall(f'{entity_type}-\\d+', anonymized_text)
|
| 824 |
-
unique_tokens = sorted(set(tokens_found))
|
| 825 |
-
logger.info(f" {entity_type}: {unique_tokens}")
|
| 826 |
-
logger.info("=" * 70)
|
| 827 |
-
|
| 828 |
-
# مرحله 2: LLM (فقط اگر analysis_prompt داده شده باشد)
|
| 829 |
-
has_analysis = analysis_prompt and analysis_prompt.strip()
|
| 830 |
-
|
| 831 |
-
if has_analysis:
|
| 832 |
-
logger.info(f"🤖 مرحله 2: {llm_provider.upper()}...")
|
| 833 |
-
llm_response = anonymizer.analyze_with_llm(anonymized_text, analysis_prompt)
|
| 834 |
-
logger.info(f"✅ {llm_provider.upper()}: {len(llm_response)} کاراکتر")
|
| 835 |
-
else:
|
| 836 |
-
logger.info("⚠️ مرحله 2: بدون تحلیل LLM (پرامپت خالی)")
|
| 837 |
-
llm_response = "⚠️ هیچ دستور تحلیل داده نشده است"
|
| 838 |
-
|
| 839 |
-
# مرحله 3: بازگردانی
|
| 840 |
-
logger.info("🔄 مرحله 3: بازگردانی...")
|
| 841 |
-
|
| 842 |
-
# ✅ اصلاح: اگر تحلیل انجام نشده، متن ناشناس اصلی رو restore کن
|
| 843 |
-
if has_analysis:
|
| 844 |
-
# اگر LLM تحلیل کرده، خروجی LLM رو restore کن
|
| 845 |
-
restored_text = anonymizer.restore_text(llm_response)
|
| 846 |
-
else:
|
| 847 |
-
# اگر تحلیل نشده، متن ناشناس اصلی رو restore کن
|
| 848 |
-
restored_text = anonymizer.restore_text(anonymized_text)
|
| 849 |
-
|
| 850 |
-
logger.info("✅ بازگردانی کامل")
|
| 851 |
-
|
| 852 |
-
# مرحله 4: جدول نگاشت
|
| 853 |
-
logger.info("📋 مرحله 4: جدول نگاشت...")
|
| 854 |
-
mapping_str = anonymizer.get_mapping_table_md()
|
| 855 |
-
logger.info(f"✅ {len(anonymizer.mapping_table)} موجودیت")
|
| 856 |
-
|
| 857 |
-
logger.info("=" * 70)
|
| 858 |
-
logger.info("✅ تمام مراحل کامل!")
|
| 859 |
-
logger.info("=" * 70)
|
| 860 |
-
|
| 861 |
-
return restored_text, llm_response, anonymized_text, mapping_str
|
| 862 |
-
|
| 863 |
-
except Exception as e:
|
| 864 |
-
logger.error(f"❌ خطا: {str(e)}", exc_info=True)
|
| 865 |
-
return "", f"❌ خطا: {str(e)}", "", ""
|
| 866 |
-
|
| 867 |
-
def clear_all():
|
| 868 |
-
"""پاک کردن همه"""
|
| 869 |
-
return "", "", "", "", "", "", True, False, False, False, False
|
| 870 |
-
|
| 871 |
-
# Gradio Interface
|
| 872 |
-
css_rtl = """
|
| 873 |
-
.input-box {
|
| 874 |
-
direction: rtl;
|
| 875 |
-
text-align: right;
|
| 876 |
-
}
|
| 877 |
-
.textbox textarea {
|
| 878 |
-
direction: rtl;
|
| 879 |
-
text-align: right;
|
| 880 |
-
font-family: 'Tahoma', serif;
|
| 881 |
-
}
|
| 882 |
-
.thick-divider {
|
| 883 |
-
border-top: 2px solid #333;
|
| 884 |
-
margin: 10px 0;
|
| 885 |
-
}
|
| 886 |
-
.compact-group {
|
| 887 |
-
margin: 0;
|
| 888 |
-
padding: 0;
|
| 889 |
-
}
|
| 890 |
-
.compact-checkbox label {
|
| 891 |
-
padding: 5px 10px !important;
|
| 892 |
-
margin: 3px 0 !important;
|
| 893 |
-
font-size: 0.95em !important;
|
| 894 |
-
}
|
| 895 |
-
"""
|
| 896 |
-
|
| 897 |
-
with gr.Blocks(title="سیستم ناشناسسازی متون", theme=gr.themes.Soft(), css=css_rtl) as app:
|
| 898 |
-
|
| 899 |
-
gr.Markdown("# 🔐 پلتفرم امن چت با مدلهای متنوع و ناشناسسازی دادهها", elem_classes="input-box")
|
| 900 |
-
|
| 901 |
-
# ردیف اول: تنظیمات مدل و انتخاب موجودیتها
|
| 902 |
-
with gr.Row():
|
| 903 |
-
# سمت راست: تنظیمات مدل
|
| 904 |
-
with gr.Column(scale=1):
|
| 905 |
-
with gr.Group():
|
| 906 |
-
gr.Markdown("### ⚙️ تنظیمات مدل", elem_classes="input-box")
|
| 907 |
-
|
| 908 |
-
llm_provider = gr.Dropdown(
|
| 909 |
-
choices=["chatgpt", "grok"],
|
| 910 |
-
value="chatgpt",
|
| 911 |
-
label="🤖 انتخاب مدل زبانی",
|
| 912 |
-
interactive=True
|
| 913 |
-
)
|
| 914 |
-
|
| 915 |
-
llm_model = gr.Dropdown(
|
| 916 |
-
choices=AVAILABLE_MODELS["chatgpt"],
|
| 917 |
-
value="gpt-4o-mini",
|
| 918 |
-
label="📦 انتخاب نسخه مدل",
|
| 919 |
-
interactive=True
|
| 920 |
-
)
|
| 921 |
-
|
| 922 |
-
# سمت چپ: انتخاب موجودیتها
|
| 923 |
-
with gr.Column(scale=1):
|
| 924 |
-
with gr.Group():
|
| 925 |
-
gr.Markdown("### 🎯 انتخاب موجودیتها", elem_classes="input-box")
|
| 926 |
-
|
| 927 |
-
anonymize_all = gr.Checkbox(
|
| 928 |
-
label="✅ همه موجودیتها",
|
| 929 |
-
value=True,
|
| 930 |
-
elem_classes="input-box compact-checkbox"
|
| 931 |
-
)
|
| 932 |
-
|
| 933 |
-
anonymize_person = gr.Checkbox(
|
| 934 |
-
label="👤 اسامی اشخاص",
|
| 935 |
-
value=False,
|
| 936 |
-
elem_classes="input-box compact-checkbox"
|
| 937 |
-
)
|
| 938 |
-
|
| 939 |
-
anonymize_company = gr.Checkbox(
|
| 940 |
-
label="🏢 نام شرکتها",
|
| 941 |
-
value=False,
|
| 942 |
-
elem_classes="input-box compact-checkbox"
|
| 943 |
-
)
|
| 944 |
-
|
| 945 |
-
anonymize_amount = gr.Checkbox(
|
| 946 |
-
label="💰 ارقام مالی",
|
| 947 |
-
value=False,
|
| 948 |
-
elem_classes="input-box compact-checkbox"
|
| 949 |
-
)
|
| 950 |
-
|
| 951 |
-
anonymize_percent = gr.Checkbox(
|
| 952 |
-
label="📊 درصدها",
|
| 953 |
-
value=False,
|
| 954 |
-
elem_classes="input-box compact-checkbox"
|
| 955 |
-
)
|
| 956 |
-
|
| 957 |
-
# خط جداکننده پررنگ
|
| 958 |
-
gr.Markdown("---", elem_classes="thick-divider")
|
| 959 |
-
|
| 960 |
-
# ردیف دوم: دستورات پردازش و متن ورودی
|
| 961 |
-
with gr.Row():
|
| 962 |
-
# سمت راست: دستورات پردازش
|
| 963 |
-
with gr.Column(scale=1):
|
| 964 |
-
gr.Markdown("### 📋 دستورات پردازش", elem_classes="input-box")
|
| 965 |
-
|
| 966 |
-
analysis_prompt = gr.Textbox(
|
| 967 |
-
lines=22,
|
| 968 |
-
placeholder="مثال: این متن را خلاصه کن\nیا: نکات کلیدی را استخراج کن",
|
| 969 |
-
label="📋 دستورات LLM (اختیاری)",
|
| 970 |
-
elem_classes="textbox"
|
| 971 |
-
)
|
| 972 |
-
|
| 973 |
-
# سمت چپ: متن ورودی
|
| 974 |
-
with gr.Column(scale=1):
|
| 975 |
-
gr.Markdown("### 📝 متن ورودی", elem_classes="input-box")
|
| 976 |
-
|
| 977 |
-
input_text = gr.Textbox(
|
| 978 |
-
lines=22,
|
| 979 |
-
placeholder="متن مالی/خبری را وارد کنید...",
|
| 980 |
-
label="",
|
| 981 |
-
elem_classes="textbox"
|
| 982 |
-
)
|
| 983 |
-
|
| 984 |
-
# دکمههای پردازش و پاک کردن
|
| 985 |
-
with gr.Row():
|
| 986 |
-
process_btn = gr.Button(
|
| 987 |
-
"▶️ پردازش",
|
| 988 |
-
variant="primary",
|
| 989 |
-
size="lg",
|
| 990 |
-
scale=2
|
| 991 |
-
)
|
| 992 |
-
|
| 993 |
-
clear_btn = gr.Button(
|
| 994 |
-
"🗑️ پاک کردن",
|
| 995 |
-
variant="stop",
|
| 996 |
-
size="lg",
|
| 997 |
-
scale=1
|
| 998 |
-
)
|
| 999 |
-
|
| 1000 |
-
# نتایج
|
| 1001 |
-
gr.Markdown("## 📊 نتایج پردازش", elem_classes="input-box")
|
| 1002 |
-
|
| 1003 |
-
with gr.Row():
|
| 1004 |
-
with gr.Column(scale=1):
|
| 1005 |
-
restored_text = gr.Textbox(
|
| 1006 |
-
lines=12,
|
| 1007 |
-
label="✅ متن بازگردانی شده",
|
| 1008 |
-
interactive=False,
|
| 1009 |
-
elem_classes="textbox"
|
| 1010 |
-
)
|
| 1011 |
-
|
| 1012 |
-
with gr.Column(scale=1):
|
| 1013 |
-
llm_analysis = gr.Textbox(
|
| 1014 |
-
lines=12,
|
| 1015 |
-
label="🤖 تحلیل LLM",
|
| 1016 |
-
interactive=False,
|
| 1017 |
-
elem_classes="textbox"
|
| 1018 |
-
)
|
| 1019 |
-
|
| 1020 |
-
with gr.Column(scale=1):
|
| 1021 |
-
anonymized_text = gr.Textbox(
|
| 1022 |
-
lines=12,
|
| 1023 |
-
label="🔒 متن ناشناسشده",
|
| 1024 |
-
interactive=False,
|
| 1025 |
-
elem_classes="textbox"
|
| 1026 |
-
)
|
| 1027 |
-
|
| 1028 |
-
mapping_table = gr.Markdown(
|
| 1029 |
-
value="### 📋 جدول نگاشت\n\nهنوز پردازشی انجام نشده",
|
| 1030 |
-
label="📋 جدول نگاشت",
|
| 1031 |
-
elem_classes="input-box"
|
| 1032 |
-
)
|
| 1033 |
-
|
| 1034 |
-
|
| 1035 |
-
# Event Handler برای تغییر provider
|
| 1036 |
-
def handle_provider_change(provider):
|
| 1037 |
-
models = AVAILABLE_MODELS.get(provider, [])
|
| 1038 |
-
default_model = models[0] if models else None
|
| 1039 |
-
return gr.update(choices=models, value=default_model)
|
| 1040 |
-
|
| 1041 |
-
llm_provider.change(
|
| 1042 |
-
fn=handle_provider_change,
|
| 1043 |
-
inputs=[llm_provider],
|
| 1044 |
-
outputs=[llm_model]
|
| 1045 |
-
)
|
| 1046 |
-
|
| 1047 |
-
def handle_select_all(select_all):
|
| 1048 |
-
if select_all:
|
| 1049 |
-
return (
|
| 1050 |
-
gr.update(value=False, interactive=False),
|
| 1051 |
-
gr.update(value=False, interactive=False),
|
| 1052 |
-
gr.update(value=False, interactive=False),
|
| 1053 |
-
gr.update(value=False, interactive=False)
|
| 1054 |
-
)
|
| 1055 |
-
else:
|
| 1056 |
-
return (
|
| 1057 |
-
gr.update(value=False, interactive=True),
|
| 1058 |
-
gr.update(value=False, interactive=True),
|
| 1059 |
-
gr.update(value=False, interactive=True),
|
| 1060 |
-
gr.update(value=False, interactive=True)
|
| 1061 |
-
)
|
| 1062 |
-
|
| 1063 |
-
anonymize_all.change(
|
| 1064 |
-
fn=handle_select_all,
|
| 1065 |
-
inputs=[anonymize_all],
|
| 1066 |
-
outputs=[anonymize_person, anonymize_company, anonymize_amount, anonymize_percent]
|
| 1067 |
-
)
|
| 1068 |
-
|
| 1069 |
-
# پردازش
|
| 1070 |
-
process_btn.click(
|
| 1071 |
-
fn=process,
|
| 1072 |
-
inputs=[
|
| 1073 |
-
input_text,
|
| 1074 |
-
analysis_prompt,
|
| 1075 |
-
llm_provider,
|
| 1076 |
-
llm_model,
|
| 1077 |
-
anonymize_all,
|
| 1078 |
-
anonymize_person,
|
| 1079 |
-
anonymize_company,
|
| 1080 |
-
anonymize_amount,
|
| 1081 |
-
anonymize_percent
|
| 1082 |
-
],
|
| 1083 |
-
outputs=[restored_text, llm_analysis, anonymized_text, mapping_table]
|
| 1084 |
-
)
|
| 1085 |
-
|
| 1086 |
-
# پاک کردن
|
| 1087 |
-
clear_btn.click(
|
| 1088 |
-
fn=clear_all,
|
| 1089 |
-
outputs=[
|
| 1090 |
-
input_text,
|
| 1091 |
-
analysis_prompt,
|
| 1092 |
-
restored_text,
|
| 1093 |
-
llm_analysis,
|
| 1094 |
-
anonymized_text,
|
| 1095 |
-
mapping_table,
|
| 1096 |
-
anonymize_all,
|
| 1097 |
-
anonymize_person,
|
| 1098 |
-
anonymize_company,
|
| 1099 |
-
anonymize_amount,
|
| 1100 |
-
anonymize_percent
|
| 1101 |
-
]
|
| 1102 |
-
)
|
| 1103 |
-
|
| 1104 |
-
if __name__ == "__main__":
|
| 1105 |
-
print("=" * 70)
|
| 1106 |
-
print("🚀 سیستم ناشناسسازی متون در حال راهاندازی...")
|
| 1107 |
-
print("=" * 70)
|
| 1108 |
-
print("\n📋 نحوه استفاده:\n")
|
| 1109 |
-
print("1. API Keyها را در Hugging Face Secrets تنظیم کنید:")
|
| 1110 |
-
print(" - CEREBRAS_API_KEY (ضروری برای ناشناسسازی)")
|
| 1111 |
-
print(" - OPENAI_API_KEY (برای ChatGPT)")
|
| 1112 |
-
print(" - XAI_API_KEY (برای Grok)")
|
| 1113 |
-
print("2. http://localhost:7860 را باز کنید")
|
| 1114 |
-
print("3. مدل زبانی (ChatGPT/Grok) و نسخه مدل را انتخاب کنید")
|
| 1115 |
-
print("4. موجودیتهای مورد نظر برای ناشناسسازی را انتخاب کنید")
|
| 1116 |
-
print("5. متن و دستورات پردازش را وارد کنید")
|
| 1117 |
-
print("6. 'پردازش' را کلیک کنید\n")
|
| 1118 |
-
print("🔐 تمام API Keyها از Hugging Face Secrets خوانده میشوند")
|
| 1119 |
-
print("📦 مدلهای پشتیبانی شده:")
|
| 1120 |
-
print(" • ChatGPT GPT-5: gpt-5.1, gpt-5")
|
| 1121 |
-
print(" • ChatGPT GPT-4: gpt-4.1, gpt-4o, gpt-4o-mini, gpt-4-turbo")
|
| 1122 |
-
print(" • Grok-4: grok-4-fast-reasoning, grok-4-fast-non-reasoning, grok-4-0709")
|
| 1123 |
-
print(" • Grok-3: grok-3, grok-3-mini")
|
| 1124 |
-
print(" • Grok-2: grok-2-vision-1212, grok-2-1212, grok-2")
|
| 1125 |
-
print("=" * 70 + "\n")
|
| 1126 |
-
|
| 1127 |
-
app.launch(
|
| 1128 |
-
server_name="0.0.0.0",
|
| 1129 |
-
server_port=7860,
|
| 1130 |
-
share=False,
|
| 1131 |
-
show_error=True
|
| 1132 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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