Spaces:
Sleeping
Sleeping
Delete qwen_anonymizer_fixed.py
Browse files- qwen_anonymizer_fixed.py +0 -341
qwen_anonymizer_fixed.py
DELETED
|
@@ -1,341 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
🤖 Qwen Anonymizer Module - نسخه Space (لود لوکال)
|
| 3 |
-
ماژول استفاده مستقیم از مدل فاینتیون شده Qwen2.5-1.5B
|
| 4 |
-
✅ بدون نیاز به Inference API - مدل مستقیماً از Space لود میشود
|
| 5 |
-
"""
|
| 6 |
-
|
| 7 |
-
import os
|
| 8 |
-
import logging
|
| 9 |
-
from typing import Optional, Dict, Tuple
|
| 10 |
-
import json
|
| 11 |
-
import re
|
| 12 |
-
import torch
|
| 13 |
-
|
| 14 |
-
logging.basicConfig(level=logging.INFO)
|
| 15 |
-
logger = logging.getLogger(__name__)
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
class QwenAnonymizer:
|
| 19 |
-
"""کلاس برای استفاده از مدل فاینتیون شده Qwen - لود لوکال"""
|
| 20 |
-
|
| 21 |
-
def __init__(
|
| 22 |
-
self,
|
| 23 |
-
model_path: str = "./qwen-anonymizer-v2", # ⭐ مسیر لوکال در Space
|
| 24 |
-
device: str = "auto"
|
| 25 |
-
):
|
| 26 |
-
"""
|
| 27 |
-
مقداردهی اولیه
|
| 28 |
-
|
| 29 |
-
Args:
|
| 30 |
-
model_path: مسیر مدل در Space
|
| 31 |
-
device: دستگاه (auto, cuda, cpu)
|
| 32 |
-
"""
|
| 33 |
-
self.model_path = model_path
|
| 34 |
-
self.device = device
|
| 35 |
-
|
| 36 |
-
self.model = None
|
| 37 |
-
self.tokenizer = None
|
| 38 |
-
self.base_model = None
|
| 39 |
-
self._model_loaded = False
|
| 40 |
-
|
| 41 |
-
# لود مدل
|
| 42 |
-
self._load_model()
|
| 43 |
-
|
| 44 |
-
logger.info(f"✅ QwenAnonymizer آماده است: {self.model_path}")
|
| 45 |
-
|
| 46 |
-
def _load_model(self):
|
| 47 |
-
"""لود کردن مدل LoRA + Base Model"""
|
| 48 |
-
try:
|
| 49 |
-
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 50 |
-
from peft import PeftModel
|
| 51 |
-
|
| 52 |
-
logger.info("📥 شروع لود مدل...")
|
| 53 |
-
logger.info(f" مسیر مدل: {self.model_path}")
|
| 54 |
-
|
| 55 |
-
# ✅ مرحله 1: لود Base Model
|
| 56 |
-
logger.info("📥 لود Base Model: Qwen/Qwen2.5-1.5B")
|
| 57 |
-
self.base_model = AutoModelForCausalLM.from_pretrained(
|
| 58 |
-
"Qwen/Qwen2.5-1.5B",
|
| 59 |
-
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
|
| 60 |
-
device_map=self.device,
|
| 61 |
-
trust_remote_code=True,
|
| 62 |
-
low_cpu_mem_usage=True # کاهش مصرف RAM
|
| 63 |
-
)
|
| 64 |
-
logger.info("✅ Base Model لود شد")
|
| 65 |
-
|
| 66 |
-
# ✅ مرحله 2: لود LoRA Adapter
|
| 67 |
-
logger.info(f"🔧 لود LoRA Adapter از: {self.model_path}")
|
| 68 |
-
self.model = PeftModel.from_pretrained(
|
| 69 |
-
self.base_model,
|
| 70 |
-
self.model_path,
|
| 71 |
-
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32
|
| 72 |
-
)
|
| 73 |
-
logger.info("✅ LoRA Adapter لود شد")
|
| 74 |
-
|
| 75 |
-
# ✅ مرحله 3: لود Tokenizer
|
| 76 |
-
logger.info("📝 لود Tokenizer...")
|
| 77 |
-
self.tokenizer = AutoTokenizer.from_pretrained(
|
| 78 |
-
"Qwen/Qwen2.5-1.5B",
|
| 79 |
-
trust_remote_code=True,
|
| 80 |
-
fix_mistral_regex=True # ⭐ رفع مشکل tokenizer
|
| 81 |
-
)
|
| 82 |
-
logger.info("✅ Tokenizer لود شد")
|
| 83 |
-
|
| 84 |
-
# تنظیم pad token
|
| 85 |
-
if self.tokenizer.pad_token is None:
|
| 86 |
-
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 87 |
-
|
| 88 |
-
# فعال کردن eval mode
|
| 89 |
-
self.model.eval()
|
| 90 |
-
|
| 91 |
-
self._model_loaded = True
|
| 92 |
-
|
| 93 |
-
# نمایش اطلاعات دستگاه
|
| 94 |
-
if torch.cuda.is_available():
|
| 95 |
-
logger.info(f"🚀 استفاده از GPU: {torch.cuda.get_device_name(0)}")
|
| 96 |
-
logger.info(f"💾 VRAM موجود: {torch.cuda.get_device_properties(0).total_memory / 1024**3:.1f} GB")
|
| 97 |
-
else:
|
| 98 |
-
logger.info("⚠️ استفاده از CPU (ممکنه کند باشه)")
|
| 99 |
-
|
| 100 |
-
logger.info("✅ مدل کاملاً آماده است!")
|
| 101 |
-
|
| 102 |
-
except Exception as e:
|
| 103 |
-
logger.error(f"❌ خطا در لود مدل: {e}")
|
| 104 |
-
logger.error("💡 مطمئن شوید:")
|
| 105 |
-
logger.error(f" 1. مدل در مسیر {self.model_path} وجود دارد")
|
| 106 |
-
logger.error(" 2. فایلهای adapter_config.json و adapter_model.safetensors موجود هستند")
|
| 107 |
-
logger.error(" 3. GPU در دسترس است (برای Space)")
|
| 108 |
-
self._model_loaded = False
|
| 109 |
-
raise
|
| 110 |
-
|
| 111 |
-
def anonymize(
|
| 112 |
-
self,
|
| 113 |
-
text: str,
|
| 114 |
-
entity_types: list = None,
|
| 115 |
-
entities_to_anonymize: list = None, # سازگاری با app.py
|
| 116 |
-
max_new_tokens: int = 200
|
| 117 |
-
) -> Tuple[str, Dict[str, str]]:
|
| 118 |
-
"""
|
| 119 |
-
ناشناسسازی متن
|
| 120 |
-
|
| 121 |
-
Args:
|
| 122 |
-
text: متن ورودی
|
| 123 |
-
entity_types: لیست انواع موجودیتها
|
| 124 |
-
entities_to_anonymize: لیست انواع موجودیتها (سازگاری)
|
| 125 |
-
max_new_tokens: حداکثر توکن خروجی
|
| 126 |
-
|
| 127 |
-
Returns:
|
| 128 |
-
(متن ناشناس شده, mapping dictionary)
|
| 129 |
-
"""
|
| 130 |
-
if not self._model_loaded:
|
| 131 |
-
logger.error("❌ مدل لود نشده است!")
|
| 132 |
-
return text, {}
|
| 133 |
-
|
| 134 |
-
if not text or not text.strip():
|
| 135 |
-
return "", {}
|
| 136 |
-
|
| 137 |
-
# سازگاری با app.py
|
| 138 |
-
if entities_to_anonymize is not None:
|
| 139 |
-
entity_types = entities_to_anonymize
|
| 140 |
-
|
| 141 |
-
# تنظیم entity types پیشفرض
|
| 142 |
-
if entity_types is None:
|
| 143 |
-
entity_types = ["person", "company", "amount", "percent"]
|
| 144 |
-
|
| 145 |
-
# ساخت prompt
|
| 146 |
-
prompt = self._create_prompt(text, entity_types)
|
| 147 |
-
|
| 148 |
-
# تولید خروجی
|
| 149 |
-
try:
|
| 150 |
-
generated = self._generate(prompt, max_new_tokens)
|
| 151 |
-
|
| 152 |
-
# پردازش خروجی
|
| 153 |
-
anonymized_text, mapping = self._parse_output(generated)
|
| 154 |
-
|
| 155 |
-
return anonymized_text, mapping
|
| 156 |
-
|
| 157 |
-
except Exception as e:
|
| 158 |
-
logger.error(f"❌ خطا در anonymization: {e}")
|
| 159 |
-
return text, {}
|
| 160 |
-
|
| 161 |
-
def _create_prompt(self, text: str, entity_types: list) -> str:
|
| 162 |
-
"""ساخت prompt برای مدل"""
|
| 163 |
-
# تبدیل entity types به فرمت مناسب
|
| 164 |
-
entity_mappings = {
|
| 165 |
-
"person": "اسامی اشخاص → person-01, person-02, ...",
|
| 166 |
-
"company": "نام شرکتها → company-01, company-02, ...",
|
| 167 |
-
"amount": "اعداد و مبالغ → amount-01, amount-02, ...",
|
| 168 |
-
"percent": "درصدها → percent-01, percent-02, ..."
|
| 169 |
-
}
|
| 170 |
-
|
| 171 |
-
instructions = [entity_mappings.get(et, et) for et in entity_types]
|
| 172 |
-
instructions_text = "\n".join([f"{i+1}. {inst}" for i, inst in enumerate(instructions)])
|
| 173 |
-
|
| 174 |
-
prompt = f"""<|im_start|>system
|
| 175 |
-
شما یک سیستم هوش مصنوعی برای ناشناسسازی متون فارسی هستید.
|
| 176 |
-
<|im_end|>
|
| 177 |
-
<|im_start|>user
|
| 178 |
-
متن زیر را ناشناس کنید:
|
| 179 |
-
{instructions_text}
|
| 180 |
-
|
| 181 |
-
متن:
|
| 182 |
-
{text}
|
| 183 |
-
|
| 184 |
-
خروجی: فقط متن ناشناس شده
|
| 185 |
-
<|im_end|>
|
| 186 |
-
<|im_start|>assistant
|
| 187 |
-
"""
|
| 188 |
-
return prompt
|
| 189 |
-
|
| 190 |
-
def _generate(self, prompt: str, max_tokens: int = 200) -> str:
|
| 191 |
-
"""تولید متن با مدل"""
|
| 192 |
-
try:
|
| 193 |
-
# Tokenize
|
| 194 |
-
inputs = self.tokenizer(prompt, return_tensors="pt").to(self.model.device)
|
| 195 |
-
|
| 196 |
-
# Generate با پارامترهای بهینه شده
|
| 197 |
-
logger.info("🔄 در حال تولید متن...")
|
| 198 |
-
with torch.no_grad():
|
| 199 |
-
outputs = self.model.generate(
|
| 200 |
-
**inputs,
|
| 201 |
-
max_new_tokens=max_tokens,
|
| 202 |
-
min_new_tokens=20, # ⭐ حداقل طول خروجی
|
| 203 |
-
do_sample=False, # greedy decoding
|
| 204 |
-
repetition_penalty=1.2, # کاهش penalty
|
| 205 |
-
pad_token_id=self.tokenizer.pad_token_id,
|
| 206 |
-
eos_token_id=self.tokenizer.eos_token_id,
|
| 207 |
-
num_beams=1, # greedy search
|
| 208 |
-
temperature=1.0, # ⭐ اضافه شد
|
| 209 |
-
top_p=None, # ⭐ غیرفعال کردن sampling
|
| 210 |
-
top_k=None # ⭐ غیرفعال کردن sampling
|
| 211 |
-
)
|
| 212 |
-
|
| 213 |
-
# Decode
|
| 214 |
-
result = self.tokenizer.decode(
|
| 215 |
-
outputs[0][inputs['input_ids'].shape[1]:],
|
| 216 |
-
skip_special_tokens=True
|
| 217 |
-
).strip()
|
| 218 |
-
|
| 219 |
-
logger.info(f"✅ تولید متن موفق - طول: {len(result)} کاراکتر")
|
| 220 |
-
logger.info(f"📝 خروجی خام: {result[:200]}...") # ⭐ نمایش خروجی
|
| 221 |
-
return result
|
| 222 |
-
|
| 223 |
-
except Exception as e:
|
| 224 |
-
logger.error(f"❌ خطا در تولید: {e}")
|
| 225 |
-
raise
|
| 226 |
-
|
| 227 |
-
def _parse_output(self, output: str) -> Tuple[str, Dict[str, str]]:
|
| 228 |
-
"""پردازش خروجی مدل"""
|
| 229 |
-
try:
|
| 230 |
-
logger.info(f"🔍 پردازش خروجی - طول: {len(output)} کاراکتر")
|
| 231 |
-
logger.info(f"📝 خروجی اولیه: {output[:300]}...")
|
| 232 |
-
|
| 233 |
-
# تمیز کردن خروجی از prompt های تکراری
|
| 234 |
-
if "متن زیر را ناشناس کنید" in output:
|
| 235 |
-
output = output.split("متن زیر را ناشناس کنید")[0].strip()
|
| 236 |
-
logger.info("🧹 پاک کردن prompt تکراری")
|
| 237 |
-
|
| 238 |
-
# حذف "خروجی:" و متن بعدش
|
| 239 |
-
if "خروجی:" in output:
|
| 240 |
-
# بعضی وقتا مدل مینویسه "خروجی: فقط متن ناشناس شده"
|
| 241 |
-
# و بعد متن اصلی رو میده
|
| 242 |
-
parts = output.split("خروجی:")
|
| 243 |
-
if len(parts) > 1:
|
| 244 |
-
# اگه بعد از "خروجی:" متن داریم، اونو بگیر
|
| 245 |
-
output = parts[1].strip()
|
| 246 |
-
# پاک کردن "فقط متن ناشناس شده" اگه ��ست
|
| 247 |
-
output = output.replace("فقط متن ناشناس شده", "").strip()
|
| 248 |
-
logger.info("🧹 پاک کردن 'خروجی:'")
|
| 249 |
-
|
| 250 |
-
# حذف newline های اضافی - ولی نه همه!
|
| 251 |
-
lines = output.split("\n")
|
| 252 |
-
if len(lines) > 3: # اگه خیلی زیاد newline داره
|
| 253 |
-
# فقط اولین چند خط رو نگه دار
|
| 254 |
-
output = "\n".join(lines[:3]).strip()
|
| 255 |
-
|
| 256 |
-
# حذف خطوط که شامل "(iParam" یا چیزهای غیرمرتبط هستن
|
| 257 |
-
lines = output.split("\n")
|
| 258 |
-
clean_lines = []
|
| 259 |
-
for line in lines:
|
| 260 |
-
line = line.strip()
|
| 261 |
-
# خطوط مفید رو نگه دار
|
| 262 |
-
if line and not any(x in line for x in ["(iParam", "متن زیر", "خروجی:", "###"]):
|
| 263 |
-
clean_lines.append(line)
|
| 264 |
-
|
| 265 |
-
if clean_lines:
|
| 266 |
-
anonymized_text = " ".join(clean_lines[:2]) # حداکثر 2 خط اول
|
| 267 |
-
else:
|
| 268 |
-
anonymized_text = output.strip()
|
| 269 |
-
|
| 270 |
-
logger.info(f"✅ متن تمیز شده: {anonymized_text[:200]}...")
|
| 271 |
-
|
| 272 |
-
# استخراج mapping از توکنها
|
| 273 |
-
mapping = {}
|
| 274 |
-
# پیدا کردن همه توکنها
|
| 275 |
-
tokens = re.findall(r'(person|company|amount|percent)-(\d+)', anonymized_text)
|
| 276 |
-
|
| 277 |
-
logger.info(f"🔍 توکنهای پیدا شده: {tokens}")
|
| 278 |
-
|
| 279 |
-
for entity_type, number in tokens:
|
| 280 |
-
token = f"{entity_type}-{number}"
|
| 281 |
-
if token not in mapping:
|
| 282 |
-
mapping[token] = f"[{token}]" # placeholder
|
| 283 |
-
|
| 284 |
-
logger.info(f"✅ پردازش موفق: {len(mapping)} توکن استخراج شد")
|
| 285 |
-
logger.info(f"📋 Mapping: {mapping}")
|
| 286 |
-
|
| 287 |
-
return anonymized_text, mapping
|
| 288 |
-
|
| 289 |
-
except Exception as e:
|
| 290 |
-
logger.error(f"❌ خطا در parse: {e}")
|
| 291 |
-
return output, {}
|
| 292 |
-
|
| 293 |
-
def deanonymize(self, anonymized_text: str, mapping: Dict[str, str]) -> str:
|
| 294 |
-
"""بازگردانی متن ناشناس شده"""
|
| 295 |
-
result = anonymized_text
|
| 296 |
-
|
| 297 |
-
# معکوس کردن mapping
|
| 298 |
-
reverse_mapping = {v: k for k, v in mapping.items()}
|
| 299 |
-
|
| 300 |
-
# جایگزینی توکنها با مقادیر اصلی
|
| 301 |
-
for token, original in reverse_mapping.items():
|
| 302 |
-
result = result.replace(token, original)
|
| 303 |
-
|
| 304 |
-
return result
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
def create_qwen_anonymizer(
|
| 308 |
-
model_path: str = "./qwen-anonymizer-v2",
|
| 309 |
-
device: str = "auto"
|
| 310 |
-
) -> QwenAnonymizer:
|
| 311 |
-
"""
|
| 312 |
-
ایجاد instance از QwenAnonymizer
|
| 313 |
-
|
| 314 |
-
Args:
|
| 315 |
-
model_path: مسیر مدل در Space
|
| 316 |
-
device: دستگاه (auto, cuda, cpu)
|
| 317 |
-
|
| 318 |
-
Returns:
|
| 319 |
-
QwenAnonymizer instance
|
| 320 |
-
"""
|
| 321 |
-
return QwenAnonymizer(model_path=model_path, device=device)
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
if __name__ == "__main__":
|
| 325 |
-
# تست
|
| 326 |
-
print("=" * 60)
|
| 327 |
-
print("🧪 تست QwenAnonymizer")
|
| 328 |
-
print("=" * 60)
|
| 329 |
-
|
| 330 |
-
try:
|
| 331 |
-
anonymizer = create_qwen_anonymizer()
|
| 332 |
-
|
| 333 |
-
test_text = "شرکت پتروشیمی با سرمایه 100 میلیارد ریال توسط علی احمدی تاسیس شد."
|
| 334 |
-
print(f"\n📝 متن ورودی:\n {test_text}")
|
| 335 |
-
|
| 336 |
-
result, mapping = anonymizer.anonymize(test_text)
|
| 337 |
-
print(f"\n🔒 متن ناشناس شده:\n {result}")
|
| 338 |
-
print(f"\n📋 Mapping:\n {json.dumps(mapping, ensure_ascii=False, indent=2)}")
|
| 339 |
-
|
| 340 |
-
except Exception as e:
|
| 341 |
-
print(f"\n❌ خطا: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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