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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import requests
|
| 2 |
+
import json
|
| 3 |
+
import gradio as gr
|
| 4 |
+
from typing import Dict, Any, List, Generator, Optional
|
| 5 |
+
import os
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
import re
|
| 8 |
+
import pandas as pd
|
| 9 |
+
import time
|
| 10 |
+
from datetime import datetime
|
| 11 |
+
import threading
|
| 12 |
+
from queue import Queue
|
| 13 |
+
import io
|
| 14 |
+
from requests.adapters import HTTPAdapter
|
| 15 |
+
from urllib3.util.retry import Retry
|
| 16 |
+
from enum import Enum
|
| 17 |
+
|
| 18 |
+
class APIProvider(Enum):
|
| 19 |
+
"""پرووایدرهای API پشتیبانی شده"""
|
| 20 |
+
CEREBRAS = "cerebras"
|
| 21 |
+
GROQ = "groq"
|
| 22 |
+
OPENAI = "openai"
|
| 23 |
+
|
| 24 |
+
@dataclass
|
| 25 |
+
class APIConfig:
|
| 26 |
+
"""تنظیمات API"""
|
| 27 |
+
provider: APIProvider
|
| 28 |
+
api_key: str
|
| 29 |
+
base_url: str
|
| 30 |
+
model: str
|
| 31 |
+
max_tokens: int = 2000
|
| 32 |
+
temperature: float = 0.1
|
| 33 |
+
|
| 34 |
+
# تنظیمات پیشفرض برای هر پرووایدر
|
| 35 |
+
API_CONFIGS = {
|
| 36 |
+
APIProvider.CEREBRAS: {
|
| 37 |
+
"base_url": "https://api.cerebras.ai/v1",
|
| 38 |
+
"models": ["qwen-3-32b", "llama-4-scout-17b-16e-instruct", "llama3.1-8b"],
|
| 39 |
+
"default_model": "qwen-3-32b"
|
| 40 |
+
},
|
| 41 |
+
APIProvider.GROQ: {
|
| 42 |
+
"base_url": "https://api.groq.com/openai/v1",
|
| 43 |
+
"models": ["llama-3.3-70b-versatile", "llama-3.1-8b-instant", "mixtral-8x7b-32768"],
|
| 44 |
+
"default_model": "llama-3.3-70b-versatile"
|
| 45 |
+
},
|
| 46 |
+
APIProvider.OPENAI: {
|
| 47 |
+
"base_url": "https://api.openai.com/v1",
|
| 48 |
+
"models": ["gpt-4o-mini", "gpt-4o", "gpt-3.5-turbo"],
|
| 49 |
+
"default_model": "gpt-4o-mini"
|
| 50 |
+
}
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
@dataclass
|
| 54 |
+
class RateLimitConfig:
|
| 55 |
+
"""تنظیمات محدودیت نرخ درخواست"""
|
| 56 |
+
requests_per_minute: int = 30
|
| 57 |
+
min_delay_between_requests: float = 2.0
|
| 58 |
+
max_retries: int = 5
|
| 59 |
+
initial_backoff: float = 5.0
|
| 60 |
+
max_backoff: float = 60.0
|
| 61 |
+
backoff_multiplier: float = 2.0
|
| 62 |
+
recovery_window: float = 60.0
|
| 63 |
+
|
| 64 |
+
class RateLimiter:
|
| 65 |
+
"""مدیریت محدودیت نرخ درخواست"""
|
| 66 |
+
|
| 67 |
+
def __init__(self, config: RateLimitConfig):
|
| 68 |
+
self.config = config
|
| 69 |
+
self.request_times: List[float] = []
|
| 70 |
+
self.lock = threading.Lock()
|
| 71 |
+
self.consecutive_failures = 0
|
| 72 |
+
self.last_failure_time = 0
|
| 73 |
+
self.last_success_time = time.time()
|
| 74 |
+
self.total_429_errors = 0
|
| 75 |
+
|
| 76 |
+
def wait_if_needed(self) -> float:
|
| 77 |
+
"""انتظار تا زمان مجاز ارسال درخواست بعدی"""
|
| 78 |
+
with self.lock:
|
| 79 |
+
now = time.time()
|
| 80 |
+
|
| 81 |
+
# پاک کردن درخواستهای قدیمی
|
| 82 |
+
self.request_times = [t for t in self.request_times if now - t < 60]
|
| 83 |
+
|
| 84 |
+
# بازیابی از خطاهای قبلی
|
| 85 |
+
if self.consecutive_failures > 0 and (now - self.last_failure_time) > self.config.recovery_window:
|
| 86 |
+
self.consecutive_failures = max(0, self.consecutive_failures - 1)
|
| 87 |
+
|
| 88 |
+
wait_time = 0.0
|
| 89 |
+
|
| 90 |
+
# محدودیت درخواست در دقیقه
|
| 91 |
+
if len(self.request_times) >= self.config.requests_per_minute:
|
| 92 |
+
oldest_request = min(self.request_times)
|
| 93 |
+
wait_time = max(wait_time, 60 - (now - oldest_request) + 1)
|
| 94 |
+
|
| 95 |
+
# حداقل تأخیر
|
| 96 |
+
if self.request_times:
|
| 97 |
+
time_since_last = now - max(self.request_times)
|
| 98 |
+
if time_since_last < self.config.min_delay_between_requests:
|
| 99 |
+
wait_time = max(wait_time, self.config.min_delay_between_requests - time_since_last)
|
| 100 |
+
|
| 101 |
+
# backoff برای خطاها
|
| 102 |
+
if self.consecutive_failures > 0:
|
| 103 |
+
failure_wait = min(
|
| 104 |
+
self.config.initial_backoff * (self.config.backoff_multiplier ** min(self.consecutive_failures, 4)),
|
| 105 |
+
self.config.max_backoff
|
| 106 |
+
)
|
| 107 |
+
wait_time = max(wait_time, failure_wait)
|
| 108 |
+
|
| 109 |
+
if wait_time > 0:
|
| 110 |
+
time.sleep(wait_time)
|
| 111 |
+
|
| 112 |
+
self.request_times.append(time.time())
|
| 113 |
+
return wait_time
|
| 114 |
+
|
| 115 |
+
def report_success(self):
|
| 116 |
+
with self.lock:
|
| 117 |
+
self.last_success_time = time.time()
|
| 118 |
+
self.consecutive_failures = 0
|
| 119 |
+
|
| 120 |
+
def report_failure(self, is_rate_limit: bool = False):
|
| 121 |
+
with self.lock:
|
| 122 |
+
self.last_failure_time = time.time()
|
| 123 |
+
if is_rate_limit:
|
| 124 |
+
self.consecutive_failures += 1
|
| 125 |
+
self.total_429_errors += 1
|
| 126 |
+
else:
|
| 127 |
+
self.consecutive_failures = min(self.consecutive_failures + 0.5, 3)
|
| 128 |
+
|
| 129 |
+
def get_estimated_wait_time(self) -> float:
|
| 130 |
+
with self.lock:
|
| 131 |
+
now = time.time()
|
| 132 |
+
self.request_times = [t for t in self.request_times if now - t < 60]
|
| 133 |
+
if len(self.request_times) >= self.config.requests_per_minute:
|
| 134 |
+
return max(0, 60 - (now - min(self.request_times)) + 1)
|
| 135 |
+
return self.config.min_delay_between_requests
|
| 136 |
+
|
| 137 |
+
def get_status(self) -> Dict[str, Any]:
|
| 138 |
+
with self.lock:
|
| 139 |
+
return {
|
| 140 |
+
"consecutive_failures": self.consecutive_failures,
|
| 141 |
+
"total_429_errors": self.total_429_errors,
|
| 142 |
+
"requests_in_last_minute": len(self.request_times)
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
class MultiProviderAnonymizer:
|
| 147 |
+
"""سیستم ناشناسسازی با پشتیبانی از چند API"""
|
| 148 |
+
|
| 149 |
+
def __init__(
|
| 150 |
+
self,
|
| 151 |
+
provider: APIProvider,
|
| 152 |
+
api_key: str,
|
| 153 |
+
model: str = None,
|
| 154 |
+
rate_limit_config: RateLimitConfig = None
|
| 155 |
+
):
|
| 156 |
+
self.provider = provider
|
| 157 |
+
self.api_key = api_key
|
| 158 |
+
|
| 159 |
+
provider_config = API_CONFIGS[provider]
|
| 160 |
+
self.base_url = provider_config["base_url"]
|
| 161 |
+
self.model = model or provider_config["default_model"]
|
| 162 |
+
|
| 163 |
+
self.rate_limit_config = rate_limit_config or RateLimitConfig()
|
| 164 |
+
self.rate_limiter = RateLimiter(self.rate_limit_config)
|
| 165 |
+
self.system_prompt = self._create_system_prompt()
|
| 166 |
+
self.session = self._create_session()
|
| 167 |
+
|
| 168 |
+
def _create_session(self) -> requests.Session:
|
| 169 |
+
"""ایجاد session با تنظیمات بهینه"""
|
| 170 |
+
session = requests.Session()
|
| 171 |
+
retry_strategy = Retry(
|
| 172 |
+
total=3,
|
| 173 |
+
backoff_factor=1,
|
| 174 |
+
status_forcelist=[500, 502, 503, 504],
|
| 175 |
+
allowed_methods=["POST"]
|
| 176 |
+
)
|
| 177 |
+
adapter = HTTPAdapter(max_retries=retry_strategy, pool_connections=10, pool_maxsize=10)
|
| 178 |
+
session.mount("https://", adapter)
|
| 179 |
+
session.mount("http://", adapter)
|
| 180 |
+
return session
|
| 181 |
+
|
| 182 |
+
def _create_system_prompt(self) -> str:
|
| 183 |
+
"""دستورالعمل سیستمی"""
|
| 184 |
+
return """شما یک «ناشناسساز متون مالی/خبری فارسی» هستید. وظیفهتان جایگزینی اسامی خاص و مقادیر عددی با شناسههای بیمعناست.
|
| 185 |
+
|
| 186 |
+
## **قوانین اندیسگذاری**
|
| 187 |
+
- شرکتها: company-01, company-02, ... (پیوسته)
|
| 188 |
+
- اشخاص: person-01, person-02, ... (پیوسته)
|
| 189 |
+
- اعداد: amount-01, amount-02, ... (پیوسته)
|
| 190 |
+
- درصدها: percent-01, percent-02, ... (پیوسته)
|
| 191 |
+
|
| 192 |
+
## **ثبات شناسهها:**
|
| 193 |
+
- اگر "همراه اول" اولبار company-01 شد، در تمام متن همان باشد
|
| 194 |
+
|
| 195 |
+
## **تشخیص صحیح:**
|
| 196 |
+
- **شرکت/سازمان:** همراه اول، بانک ملی، ایرانخودرو، سایپا، بانک مرکزی
|
| 197 |
+
- **گروهها:** "گروه همراه اول" → company-XX (نه group-XX)
|
| 198 |
+
- **کلمات عمومی:** "سه شرکت"، "چند بانک" → حفظ شوند
|
| 199 |
+
- **شخص:** مهدی اخوان بهابادی، محمدرضا فرزین
|
| 200 |
+
- **عدد:** 37، 70، 677 (هر عددی)
|
| 201 |
+
- **درصد:** 37 درصدی، 15%
|
| 202 |
+
|
| 203 |
+
## **مثال:**
|
| 204 |
+
**ورودی:** مهدی اخوان، مدیرعامل همراه اول، اعلام کرد درآمد با رشد 37 درصدی به 70 میلیارد رسید.
|
| 205 |
+
**خروجی:** person-01، مدیرعامل company-01، اعلام کرد درآمد با رشد percent-01 به amount-01 رسید.
|
| 206 |
+
|
| 207 |
+
## **حفظ شود:**
|
| 208 |
+
- تاریخها: 1404/04/23
|
| 209 |
+
- دورههای زمانی: ۹ ماهه، ۵ ماهه سال
|
| 210 |
+
- واحدها: میلیارد تومان، همت
|
| 211 |
+
- مکانها: تهران، اصفهان
|
| 212 |
+
|
| 213 |
+
**فقط متن ناشناسشده را برگردان - بدون توضیح اضافی.**
|
| 214 |
+
"""
|
| 215 |
+
|
| 216 |
+
def _make_api_request(self, text: str) -> Dict[str, Any]:
|
| 217 |
+
"""ارسال درخواست به API"""
|
| 218 |
+
headers = {
|
| 219 |
+
"Authorization": f"Bearer {self.api_key}",
|
| 220 |
+
"Content-Type": "application/json"
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
payload = {
|
| 224 |
+
"messages": [
|
| 225 |
+
{"role": "system", "content": self.system_prompt},
|
| 226 |
+
{"role": "user", "content": text}
|
| 227 |
+
],
|
| 228 |
+
"model": self.model,
|
| 229 |
+
"temperature": 0.1,
|
| 230 |
+
"max_tokens": 2000
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
# اضافه کردن پارامترهای خاص هر پرووایدر
|
| 234 |
+
if self.provider == APIProvider.GROQ:
|
| 235 |
+
# Groq نیاز به این پارامتر نداره
|
| 236 |
+
pass
|
| 237 |
+
|
| 238 |
+
last_error = None
|
| 239 |
+
|
| 240 |
+
for attempt in range(self.rate_limit_config.max_retries):
|
| 241 |
+
self.rate_limiter.wait_if_needed()
|
| 242 |
+
|
| 243 |
+
try:
|
| 244 |
+
response = self.session.post(
|
| 245 |
+
f"{self.base_url}/chat/completions",
|
| 246 |
+
headers=headers,
|
| 247 |
+
json=payload,
|
| 248 |
+
timeout=90
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
if response.status_code == 429:
|
| 252 |
+
self.rate_limiter.report_failure(is_rate_limit=True)
|
| 253 |
+
retry_after = response.headers.get('Retry-After')
|
| 254 |
+
wait_seconds = int(retry_after) if retry_after else min(
|
| 255 |
+
self.rate_limit_config.initial_backoff * (self.rate_limit_config.backoff_multiplier ** attempt),
|
| 256 |
+
60.0
|
| 257 |
+
)
|
| 258 |
+
last_error = f"Rate limit (429). تلاش {attempt + 1}/{self.rate_limit_config.max_retries}"
|
| 259 |
+
print(f"🚫 {last_error} - انتظار {wait_seconds}s")
|
| 260 |
+
time.sleep(wait_seconds)
|
| 261 |
+
continue
|
| 262 |
+
|
| 263 |
+
if response.status_code == 401:
|
| 264 |
+
raise Exception(f"❌ کلید API نامعتبر است برای {self.provider.value}")
|
| 265 |
+
|
| 266 |
+
if response.status_code == 503:
|
| 267 |
+
self.rate_limiter.report_failure(is_rate_limit=False)
|
| 268 |
+
last_error = f"سرویس در دسترس نیست (503)"
|
| 269 |
+
time.sleep(10)
|
| 270 |
+
continue
|
| 271 |
+
|
| 272 |
+
response.raise_for_status()
|
| 273 |
+
self.rate_limiter.report_success()
|
| 274 |
+
return response.json()
|
| 275 |
+
|
| 276 |
+
except requests.exceptions.Timeout:
|
| 277 |
+
self.rate_limiter.report_failure(is_rate_limit=False)
|
| 278 |
+
last_error = f"Timeout"
|
| 279 |
+
time.sleep(5)
|
| 280 |
+
|
| 281 |
+
except requests.exceptions.ConnectionError as e:
|
| 282 |
+
self.rate_limiter.report_failure(is_rate_limit=False)
|
| 283 |
+
last_error = f"خطای اتصال: {str(e)[:50]}"
|
| 284 |
+
time.sleep(10)
|
| 285 |
+
|
| 286 |
+
except requests.exceptions.RequestException as e:
|
| 287 |
+
self.rate_limiter.report_failure(is_rate_limit=False)
|
| 288 |
+
last_error = f"خطای شبکه: {str(e)[:50]}"
|
| 289 |
+
time.sleep(5)
|
| 290 |
+
|
| 291 |
+
raise Exception(f"ناموفق پس از {self.rate_limit_config.max_retries} تلاش: {last_error}")
|
| 292 |
+
|
| 293 |
+
def anonymize_text(self, text: str) -> Dict[str, Any]:
|
| 294 |
+
"""ناشناسسازی متن"""
|
| 295 |
+
if not text or not text.strip():
|
| 296 |
+
return {"success": False, "error": "متن ورودی خالی است", "anonymized_text": ""}
|
| 297 |
+
|
| 298 |
+
try:
|
| 299 |
+
response = self._make_api_request(text)
|
| 300 |
+
|
| 301 |
+
if "choices" not in response or not response["choices"]:
|
| 302 |
+
return {"success": False, "error": "پاسخ نامعتبر", "anonymized_text": ""}
|
| 303 |
+
|
| 304 |
+
content = response["choices"][0]["message"]["content"]
|
| 305 |
+
|
| 306 |
+
# پاک کردن markdown
|
| 307 |
+
if "```" in content:
|
| 308 |
+
lines = content.split('\n')
|
| 309 |
+
clean_lines = []
|
| 310 |
+
skip = False
|
| 311 |
+
for line in lines:
|
| 312 |
+
if line.strip().startswith('```'):
|
| 313 |
+
skip = not skip
|
| 314 |
+
continue
|
| 315 |
+
if not skip:
|
| 316 |
+
clean_lines.append(line)
|
| 317 |
+
content = '\n'.join(clean_lines)
|
| 318 |
+
|
| 319 |
+
content = content.strip()
|
| 320 |
+
|
| 321 |
+
# پاک کردن تگهای thinking (برای مدلهای Qwen و مشابه)
|
| 322 |
+
content = re.sub(r'<think>.*?</think>', '', content, flags=re.DOTALL)
|
| 323 |
+
content = re.sub(r'<thinking>.*?</thinking>', '', content, flags=re.DOTALL)
|
| 324 |
+
content = content.strip()
|
| 325 |
+
|
| 326 |
+
# تحلیل نتایج
|
| 327 |
+
companies = re.findall(r'company-(\d+)', content)
|
| 328 |
+
persons = re.findall(r'person-(\d+)', content)
|
| 329 |
+
amounts = re.findall(r'amount-(\d+)', content)
|
| 330 |
+
percents = re.findall(r'percent-(\d+)', content)
|
| 331 |
+
|
| 332 |
+
return {
|
| 333 |
+
"success": True,
|
| 334 |
+
"anonymized_text": content,
|
| 335 |
+
"statistics": {
|
| 336 |
+
"company": len(set(companies)),
|
| 337 |
+
"person": len(set(persons)),
|
| 338 |
+
"amount": len(set(amounts)),
|
| 339 |
+
"percent": len(set(percents))
|
| 340 |
+
},
|
| 341 |
+
"usage": response.get("usage", {})
|
| 342 |
+
}
|
| 343 |
+
|
| 344 |
+
except Exception as e:
|
| 345 |
+
return {"success": False, "error": f"خطا: {str(e)}", "anonymized_text": ""}
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
class BatchProcessor:
|
| 349 |
+
"""پردازشگر دستهای"""
|
| 350 |
+
|
| 351 |
+
def __init__(
|
| 352 |
+
self,
|
| 353 |
+
provider: APIProvider,
|
| 354 |
+
api_key: str,
|
| 355 |
+
model: str = None,
|
| 356 |
+
rate_limit_config: RateLimitConfig = None
|
| 357 |
+
):
|
| 358 |
+
self.provider = provider
|
| 359 |
+
self.api_key = api_key
|
| 360 |
+
self.model = model
|
| 361 |
+
self.rate_limit_config = rate_limit_config or RateLimitConfig()
|
| 362 |
+
self.anonymizer = None
|
| 363 |
+
self.is_cancelled = False
|
| 364 |
+
self.current_progress = 0
|
| 365 |
+
self.total_rows = 0
|
| 366 |
+
self.processed_rows = 0
|
| 367 |
+
self.failed_rows = 0
|
| 368 |
+
self.start_time = None
|
| 369 |
+
self.consecutive_api_failures = 0
|
| 370 |
+
self.max_consecutive_failures = 10
|
| 371 |
+
|
| 372 |
+
def cancel(self):
|
| 373 |
+
self.is_cancelled = True
|
| 374 |
+
|
| 375 |
+
def reset(self):
|
| 376 |
+
self.is_cancelled = False
|
| 377 |
+
self.current_progress = 0
|
| 378 |
+
self.total_rows = 0
|
| 379 |
+
self.processed_rows = 0
|
| 380 |
+
self.failed_rows = 0
|
| 381 |
+
self.start_time = None
|
| 382 |
+
self.consecutive_api_failures = 0
|
| 383 |
+
|
| 384 |
+
def process_csv(
|
| 385 |
+
self,
|
| 386 |
+
file_path: str,
|
| 387 |
+
text_column: str,
|
| 388 |
+
output_column: str = "anonymized_text"
|
| 389 |
+
) -> Generator[Dict[str, Any], None, None]:
|
| 390 |
+
"""پردازش فایل CSV"""
|
| 391 |
+
|
| 392 |
+
self.reset()
|
| 393 |
+
self.start_time = time.time()
|
| 394 |
+
|
| 395 |
+
# خواندن فایل
|
| 396 |
+
try:
|
| 397 |
+
df = pd.read_csv(file_path, encoding='utf-8')
|
| 398 |
+
except UnicodeDecodeError:
|
| 399 |
+
try:
|
| 400 |
+
df = pd.read_csv(file_path, encoding='utf-8-sig')
|
| 401 |
+
except:
|
| 402 |
+
df = pd.read_csv(file_path, encoding='cp1256')
|
| 403 |
+
|
| 404 |
+
if text_column not in df.columns:
|
| 405 |
+
yield {"type": "error", "message": f"ستون '{text_column}' یافت نشد"}
|
| 406 |
+
return
|
| 407 |
+
|
| 408 |
+
self.total_rows = len(df)
|
| 409 |
+
|
| 410 |
+
# ایجاد anonymizer
|
| 411 |
+
self.anonymizer = MultiProviderAnonymizer(
|
| 412 |
+
provider=self.provider,
|
| 413 |
+
api_key=self.api_key,
|
| 414 |
+
model=self.model,
|
| 415 |
+
rate_limit_config=self.rate_limit_config
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
df[output_column] = ""
|
| 419 |
+
df["anonymization_status"] = ""
|
| 420 |
+
df["entities_found"] = ""
|
| 421 |
+
|
| 422 |
+
yield {
|
| 423 |
+
"type": "info",
|
| 424 |
+
"message": f"🚀 شروع پردازش {self.total_rows} ردیف با {self.provider.value}..."
|
| 425 |
+
}
|
| 426 |
+
|
| 427 |
+
for idx, row in df.iterrows():
|
| 428 |
+
if self.is_cancelled:
|
| 429 |
+
yield {
|
| 430 |
+
"type": "cancelled",
|
| 431 |
+
"message": "لغو شد",
|
| 432 |
+
"processed": self.processed_rows,
|
| 433 |
+
"failed": self.failed_rows
|
| 434 |
+
}
|
| 435 |
+
break
|
| 436 |
+
|
| 437 |
+
if self.consecutive_api_failures >= self.max_consecutive_failures:
|
| 438 |
+
partial_path = file_path.replace('.csv', f'_partial_{idx}.csv')
|
| 439 |
+
df.to_csv(partial_path, index=False, encoding='utf-8-sig')
|
| 440 |
+
yield {
|
| 441 |
+
"type": "error",
|
| 442 |
+
"message": f"❌ توقف - خطاهای متوالی زیاد. ذخیره شد: {partial_path}"
|
| 443 |
+
}
|
| 444 |
+
return
|
| 445 |
+
|
| 446 |
+
text = str(row[text_column]) if pd.notna(row[text_column]) else ""
|
| 447 |
+
|
| 448 |
+
if not text.strip():
|
| 449 |
+
df.at[idx, output_column] = ""
|
| 450 |
+
df.at[idx, "anonymization_status"] = "خالی"
|
| 451 |
+
self.processed_rows += 1
|
| 452 |
+
continue
|
| 453 |
+
|
| 454 |
+
result = self.anonymizer.anonymize_text(text)
|
| 455 |
+
|
| 456 |
+
if result["success"]:
|
| 457 |
+
df.at[idx, output_column] = result["anonymized_text"]
|
| 458 |
+
df.at[idx, "anonymization_status"] = "موفق"
|
| 459 |
+
stats = result.get("statistics", {})
|
| 460 |
+
df.at[idx, "entities_found"] = f"C:{stats.get('company',0)}|P:{stats.get('person',0)}|A:{stats.get('amount',0)}|%:{stats.get('percent',0)}"
|
| 461 |
+
self.processed_rows += 1
|
| 462 |
+
self.consecutive_api_failures = 0
|
| 463 |
+
else:
|
| 464 |
+
df.at[idx, output_column] = f"خطا: {result.get('error', '')}"
|
| 465 |
+
df.at[idx, "anonymization_status"] = "ناموفق"
|
| 466 |
+
self.failed_rows += 1
|
| 467 |
+
if "rate limit" in result.get('error', '').lower() or "429" in result.get('error', ''):
|
| 468 |
+
self.consecutive_api_failures += 1
|
| 469 |
+
|
| 470 |
+
# پیشرفت
|
| 471 |
+
self.current_progress = (idx + 1) / self.total_rows * 100
|
| 472 |
+
elapsed = time.time() - self.start_time
|
| 473 |
+
|
| 474 |
+
yield {
|
| 475 |
+
"type": "progress",
|
| 476 |
+
"current": idx + 1,
|
| 477 |
+
"total": self.total_rows,
|
| 478 |
+
"progress": self.current_progress,
|
| 479 |
+
"processed": self.processed_rows,
|
| 480 |
+
"failed": self.failed_rows,
|
| 481 |
+
"elapsed": elapsed,
|
| 482 |
+
"estimated_remaining": (elapsed / (idx + 1)) * (self.total_rows - idx - 1),
|
| 483 |
+
"next_wait": self.anonymizer.rate_limiter.get_estimated_wait_time(),
|
| 484 |
+
"last_result": result,
|
| 485 |
+
"rate_status": self.anonymizer.rate_limiter.get_status()
|
| 486 |
+
}
|
| 487 |
+
|
| 488 |
+
# Checkpoint هر 100 ردیف
|
| 489 |
+
if (idx + 1) % 100 == 0:
|
| 490 |
+
checkpoint_path = file_path.replace('.csv', f'_checkpoint_{idx+1}.csv')
|
| 491 |
+
df.to_csv(checkpoint_path, index=False, encoding='utf-8-sig')
|
| 492 |
+
yield {"type": "info", "message": f"💾 Checkpoint: {checkpoint_path}"}
|
| 493 |
+
|
| 494 |
+
# ذخیره نهایی
|
| 495 |
+
if not self.is_cancelled:
|
| 496 |
+
output_path = file_path.replace('.csv', '_anonymized.csv')
|
| 497 |
+
if output_path == file_path:
|
| 498 |
+
output_path = file_path + '_anonymized.csv'
|
| 499 |
+
|
| 500 |
+
df.to_csv(output_path, index=False, encoding='utf-8-sig')
|
| 501 |
+
|
| 502 |
+
yield {
|
| 503 |
+
"type": "complete",
|
| 504 |
+
"message": "✅ تکمیل شد!",
|
| 505 |
+
"output_path": output_path,
|
| 506 |
+
"total": self.total_rows,
|
| 507 |
+
"processed": self.processed_rows,
|
| 508 |
+
"failed": self.failed_rows,
|
| 509 |
+
"total_time": time.time() - self.start_time
|
| 510 |
+
}
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
def create_interface():
|
| 514 |
+
"""ایجاد رابط کاربری"""
|
| 515 |
+
|
| 516 |
+
custom_css = """
|
| 517 |
+
.rtl-text { direction: rtl; text-align: right; font-family: 'Vazirmatn', 'Tahoma', sans-serif; }
|
| 518 |
+
"""
|
| 519 |
+
|
| 520 |
+
with gr.Blocks(css=custom_css, title="ناشناسساز چند-API", theme=gr.themes.Soft()) as interface:
|
| 521 |
+
gr.Markdown("""
|
| 522 |
+
# 🔒 سیستم ناشناسسازی متون فارسی
|
| 523 |
+
### پشتیبانی از Cerebras، Groq و OpenAI
|
| 524 |
+
""", elem_classes=["rtl-text"])
|
| 525 |
+
|
| 526 |
+
batch_processor = {"instance": None}
|
| 527 |
+
|
| 528 |
+
with gr.Tabs():
|
| 529 |
+
# تب پردازش تکی
|
| 530 |
+
with gr.Tab("پردازش تکی"):
|
| 531 |
+
with gr.Row():
|
| 532 |
+
with gr.Column():
|
| 533 |
+
single_provider = gr.Dropdown(
|
| 534 |
+
label="🌐 پرووایدر API",
|
| 535 |
+
choices=["cerebras", "groq", "openai"],
|
| 536 |
+
value="groq",
|
| 537 |
+
elem_classes=["rtl-text"]
|
| 538 |
+
)
|
| 539 |
+
single_api_key = gr.Textbox(
|
| 540 |
+
label="🔑 کلید API",
|
| 541 |
+
placeholder="کلید API خود را وارد کنید",
|
| 542 |
+
type="password"
|
| 543 |
+
)
|
| 544 |
+
single_model = gr.Dropdown(
|
| 545 |
+
label="🤖 مدل",
|
| 546 |
+
choices=["llama-3.3-70b-versatile", "llama-3.1-8b-instant"],
|
| 547 |
+
value="llama-3.3-70b-versatile"
|
| 548 |
+
)
|
| 549 |
+
single_input = gr.Textbox(
|
| 550 |
+
label="متن ورودی",
|
| 551 |
+
lines=5,
|
| 552 |
+
elem_classes=["rtl-text"]
|
| 553 |
+
)
|
| 554 |
+
single_btn = gr.Button("🔄 ناشناسسازی", variant="primary")
|
| 555 |
+
|
| 556 |
+
with gr.Column():
|
| 557 |
+
single_output = gr.Textbox(label="متن ناشناسشده", lines=5, elem_classes=["rtl-text"])
|
| 558 |
+
single_stats = gr.Textbox(label="آمار", lines=2)
|
| 559 |
+
|
| 560 |
+
# تب پردازش دستهای
|
| 561 |
+
with gr.Tab("پردازش دستهای"):
|
| 562 |
+
with gr.Row():
|
| 563 |
+
with gr.Column():
|
| 564 |
+
batch_provider = gr.Dropdown(
|
| 565 |
+
label="🌐 پرووایدر API",
|
| 566 |
+
choices=["cerebras", "groq", "openai"],
|
| 567 |
+
value="groq"
|
| 568 |
+
)
|
| 569 |
+
batch_api_key = gr.Textbox(
|
| 570 |
+
label="🔑 کلید API",
|
| 571 |
+
type="password"
|
| 572 |
+
)
|
| 573 |
+
batch_model = gr.Dropdown(
|
| 574 |
+
label="🤖 مدل",
|
| 575 |
+
choices=["llama-3.3-70b-versatile", "qwen-3-32b", "gpt-4o-mini"],
|
| 576 |
+
value="llama-3.3-70b-versatile"
|
| 577 |
+
)
|
| 578 |
+
csv_file = gr.File(label="📁 فایل CSV", file_types=[".csv"])
|
| 579 |
+
text_column = gr.Dropdown(label="ستون متن", choices=[], allow_custom_value=True)
|
| 580 |
+
output_column = gr.Textbox(label="نام ستون خروجی", value="anonymized_text")
|
| 581 |
+
|
| 582 |
+
with gr.Column():
|
| 583 |
+
delay_slider = gr.Slider(1, 30, 3, step=0.5, label="تأخیر (ثانیه)")
|
| 584 |
+
rpm_slider = gr.Slider(5, 30, 20, step=1, label="حداکثر درخواست/دقیقه")
|
| 585 |
+
retries_slider = gr.Slider(1, 10, 5, step=1, label="تلاش مجدد")
|
| 586 |
+
|
| 587 |
+
with gr.Row():
|
| 588 |
+
start_btn = gr.Button("🚀 شروع", variant="primary", size="lg")
|
| 589 |
+
cancel_btn = gr.Button("⏹️ لغو", variant="stop", size="lg")
|
| 590 |
+
|
| 591 |
+
progress_bar = gr.Slider(0, 100, 0, label="پیشرفت", interactive=False)
|
| 592 |
+
progress_text = gr.Markdown("در انتظار...")
|
| 593 |
+
time_stats = gr.Markdown("")
|
| 594 |
+
process_log = gr.Textbox(lines=10, label="لاگ")
|
| 595 |
+
preview_table = gr.Dataframe(headers=["متن", "ناشناسشده", "وضعیت"])
|
| 596 |
+
output_file = gr.File(label="دانلود", visible=False)
|
| 597 |
+
|
| 598 |
+
# توابع
|
| 599 |
+
def update_models(provider):
|
| 600 |
+
if provider == "cerebras":
|
| 601 |
+
return gr.update(choices=["qwen-3-32b", "llama-4-scout-17b-16e-instruct"], value="qwen-3-32b")
|
| 602 |
+
elif provider == "groq":
|
| 603 |
+
return gr.update(choices=["llama-3.3-70b-versatile", "llama-3.1-8b-instant", "mixtral-8x7b-32768"], value="llama-3.3-70b-versatile")
|
| 604 |
+
else:
|
| 605 |
+
return gr.update(choices=["gpt-4o-mini", "gpt-4o"], value="gpt-4o-mini")
|
| 606 |
+
|
| 607 |
+
def update_columns(file):
|
| 608 |
+
if file is None:
|
| 609 |
+
return gr.update(choices=[], value=None)
|
| 610 |
+
try:
|
| 611 |
+
df = pd.read_csv(file.name, nrows=0, encoding='utf-8')
|
| 612 |
+
except:
|
| 613 |
+
try:
|
| 614 |
+
df = pd.read_csv(file.name, nrows=0, encoding='utf-8-sig')
|
| 615 |
+
except:
|
| 616 |
+
df = pd.read_csv(file.name, nrows=0, encoding='cp1256')
|
| 617 |
+
columns = list(df.columns)
|
| 618 |
+
return gr.update(choices=columns, value=columns[0] if columns else None)
|
| 619 |
+
|
| 620 |
+
def process_single(provider, api_key, model, text):
|
| 621 |
+
if not text.strip():
|
| 622 |
+
return "", "❌ متن خالی"
|
| 623 |
+
if not api_key:
|
| 624 |
+
return "", "❌ کلید API وارد نشده"
|
| 625 |
+
|
| 626 |
+
try:
|
| 627 |
+
prov = APIProvider(provider)
|
| 628 |
+
anonymizer = MultiProviderAnonymizer(provider=prov, api_key=api_key, model=model)
|
| 629 |
+
result = anonymizer.anonymize_text(text)
|
| 630 |
+
|
| 631 |
+
if result["success"]:
|
| 632 |
+
stats = result.get("statistics", {})
|
| 633 |
+
return result["anonymized_text"], f"✅ C:{stats.get('company',0)} | P:{stats.get('person',0)} | A:{stats.get('amount',0)} | %:{stats.get('percent',0)}"
|
| 634 |
+
else:
|
| 635 |
+
return "", f"❌ {result.get('error', '')}"
|
| 636 |
+
except Exception as e:
|
| 637 |
+
return "", f"❌ {str(e)}"
|
| 638 |
+
|
| 639 |
+
def start_batch(file, text_col, output_col, delay, rpm, retries, provider, api_key, model):
|
| 640 |
+
if file is None:
|
| 641 |
+
yield (0, "❌ فایل انتخاب نشده", "", "", None, gr.update(visible=False))
|
| 642 |
+
return
|
| 643 |
+
if not api_key:
|
| 644 |
+
yield (0, "❌ کلید API وارد نشده", "", "", None, gr.update(visible=False))
|
| 645 |
+
return
|
| 646 |
+
|
| 647 |
+
prov = APIProvider(provider)
|
| 648 |
+
rate_config = RateLimitConfig(
|
| 649 |
+
requests_per_minute=int(rpm),
|
| 650 |
+
min_delay_between_requests=float(delay),
|
| 651 |
+
max_retries=int(retries)
|
| 652 |
+
)
|
| 653 |
+
|
| 654 |
+
processor = BatchProcessor(provider=prov, api_key=api_key, model=model, rate_limit_config=rate_config)
|
| 655 |
+
batch_processor["instance"] = processor
|
| 656 |
+
|
| 657 |
+
log_lines = []
|
| 658 |
+
preview_data = []
|
| 659 |
+
|
| 660 |
+
for update in processor.process_csv(file.name, text_col, output_col):
|
| 661 |
+
update_type = update.get("type")
|
| 662 |
+
|
| 663 |
+
if update_type == "error":
|
| 664 |
+
log_lines.append(f"❌ {update['message']}")
|
| 665 |
+
yield (0, f"❌ {update['message']}", "", "\n".join(log_lines), None, gr.update(visible=False))
|
| 666 |
+
return
|
| 667 |
+
|
| 668 |
+
elif update_type == "info":
|
| 669 |
+
log_lines.append(f"ℹ️ {update['message']}")
|
| 670 |
+
|
| 671 |
+
elif update_type == "progress":
|
| 672 |
+
progress = update["progress"]
|
| 673 |
+
current = update["current"]
|
| 674 |
+
total = update["total"]
|
| 675 |
+
elapsed = update["elapsed"]
|
| 676 |
+
remaining = update["estimated_remaining"]
|
| 677 |
+
|
| 678 |
+
progress_md = f"**{current}/{total}** ({progress:.1f}%) | ✅ {update['processed']} | ❌ {update['failed']}"
|
| 679 |
+
time_md = f"⏱️ {elapsed/60:.1f}m | باقیمانده: {remaining/60:.1f}m"
|
| 680 |
+
|
| 681 |
+
if current % 10 == 0:
|
| 682 |
+
log_lines.append(f"📊 {current}/{total}")
|
| 683 |
+
|
| 684 |
+
last_result = update.get("last_result", {})
|
| 685 |
+
if last_result.get("success"):
|
| 686 |
+
preview_data.append(["...", last_result.get("anonymized_text", "")[:80] + "...", "✅"])
|
| 687 |
+
if len(preview_data) > 5:
|
| 688 |
+
preview_data = preview_data[-5:]
|
| 689 |
+
|
| 690 |
+
yield (progress, progress_md, time_md, "\n".join(log_lines[-15:]), preview_data if preview_data else None, gr.update(visible=False))
|
| 691 |
+
|
| 692 |
+
elif update_type == "cancelled":
|
| 693 |
+
log_lines.append("⏹️ لغو شد")
|
| 694 |
+
yield (0, "⏹️ لغو شد", "", "\n".join(log_lines), preview_data if preview_data else None, gr.update(visible=False))
|
| 695 |
+
return
|
| 696 |
+
|
| 697 |
+
elif update_type == "complete":
|
| 698 |
+
log_lines.append(f"✅ {update['message']}")
|
| 699 |
+
progress_md = f"✅ تکمیل! {update['processed']}/{update['total']} موفق | {update['total_time']/60:.1f} دقیقه"
|
| 700 |
+
yield (100, progress_md, "", "\n".join(log_lines), preview_data if preview_data else None, gr.update(value=update['output_path'], visible=True))
|
| 701 |
+
|
| 702 |
+
def cancel():
|
| 703 |
+
if batch_processor["instance"]:
|
| 704 |
+
batch_processor["instance"].cancel()
|
| 705 |
+
return "⏹️ لغو شد..."
|
| 706 |
+
|
| 707 |
+
# اتصالات
|
| 708 |
+
single_provider.change(update_models, [single_provider], [single_model])
|
| 709 |
+
batch_provider.change(update_models, [batch_provider], [batch_model])
|
| 710 |
+
csv_file.change(update_columns, [csv_file], [text_column])
|
| 711 |
+
|
| 712 |
+
single_btn.click(process_single, [single_provider, single_api_key, single_model, single_input], [single_output, single_stats])
|
| 713 |
+
|
| 714 |
+
start_btn.click(
|
| 715 |
+
start_batch,
|
| 716 |
+
[csv_file, text_column, output_column, delay_slider, rpm_slider, retries_slider, batch_provider, batch_api_key, batch_model],
|
| 717 |
+
[progress_bar, progress_text, time_stats, process_log, preview_table, output_file]
|
| 718 |
+
)
|
| 719 |
+
|
| 720 |
+
cancel_btn.click(cancel, outputs=[process_log])
|
| 721 |
+
|
| 722 |
+
return interface
|
| 723 |
+
|
| 724 |
+
|
| 725 |
+
if __name__ == "__main__":
|
| 726 |
+
interface = create_interface()
|
| 727 |
+
interface.launch(server_name="0.0.0.0", server_port=7860, share=True, show_error=True)
|