Spaces:
Sleeping
Sleeping
Update ner_logic.py
Browse files- ner_logic.py +93 -22
ner_logic.py
CHANGED
|
@@ -6,46 +6,117 @@ import spaces
|
|
| 6 |
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
| 7 |
from labels_config import CUSTOM_LABELS
|
| 8 |
|
| 9 |
-
#
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
model_id = "Qwen/Qwen2.5-1.5B-Instruct"
|
| 12 |
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
def get_wiki_summary(term):
|
|
|
|
| 16 |
try:
|
| 17 |
wikipedia.set_lang("tr")
|
| 18 |
search_results = wikipedia.search(term)
|
| 19 |
if not search_results: return None
|
|
|
|
| 20 |
return wikipedia.summary(search_results[0], sentences=2, auto_suggest=False)
|
| 21 |
-
except:
|
|
|
|
| 22 |
|
| 23 |
@spaces.GPU
|
| 24 |
def refine_labels_batch(misc_items, full_sentence):
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
-
|
| 29 |
-
targets = "".join([f"- VARLIK: {item['word']} | WIKI: {item['wiki']}\n" for item in misc_items])
|
| 30 |
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
|
|
|
| 34 |
|
| 35 |
-
|
| 36 |
-
|
|
|
|
|
|
|
| 37 |
|
| 38 |
-
|
|
|
|
|
|
|
| 39 |
{label_rules}
|
| 40 |
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
-
|
| 44 |
-
|
|
|
|
|
|
|
| 45 |
|
| 46 |
try:
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
| 7 |
from labels_config import CUSTOM_LABELS
|
| 8 |
|
| 9 |
+
# --- 1. MODEL YÜKLEME ---
|
| 10 |
+
# NER Modeli: Varlıkları tespit eder
|
| 11 |
+
ner_pipe = pipeline(
|
| 12 |
+
"ner",
|
| 13 |
+
model="xlm-roberta-large-finetuned-conll03-english",
|
| 14 |
+
aggregation_strategy="simple",
|
| 15 |
+
device=-1
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
# LLM Modeli: Karar destek ve CoT analizi yapar
|
| 19 |
model_id = "Qwen/Qwen2.5-1.5B-Instruct"
|
| 20 |
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 21 |
+
|
| 22 |
+
try:
|
| 23 |
+
llm_model = AutoModelForCausalLM.from_pretrained(
|
| 24 |
+
model_id,
|
| 25 |
+
torch_dtype=torch.bfloat16,
|
| 26 |
+
device_map="auto",
|
| 27 |
+
trust_remote_code=True
|
| 28 |
+
)
|
| 29 |
+
IS_LLM_ENABLED = True
|
| 30 |
+
except Exception as e:
|
| 31 |
+
print(f"LLM Yükleme Hatası: {e}")
|
| 32 |
+
IS_LLM_ENABLED = False
|
| 33 |
+
|
| 34 |
+
# --- 2. YARDIMCI FONKSİYONLAR ---
|
| 35 |
|
| 36 |
def get_wiki_summary(term):
|
| 37 |
+
"""Wikipedia'dan terim hakkında özet bilgi çeker."""
|
| 38 |
try:
|
| 39 |
wikipedia.set_lang("tr")
|
| 40 |
search_results = wikipedia.search(term)
|
| 41 |
if not search_results: return None
|
| 42 |
+
# İlk sonucun özetini al
|
| 43 |
return wikipedia.summary(search_results[0], sentences=2, auto_suggest=False)
|
| 44 |
+
except:
|
| 45 |
+
return None
|
| 46 |
|
| 47 |
@spaces.GPU
|
| 48 |
def refine_labels_batch(misc_items, full_sentence):
|
| 49 |
+
"""
|
| 50 |
+
Birden fazla MISC varlığını tek bir GPU çağrısında analiz eder.
|
| 51 |
+
Her varlık için ayrı ayrı Reasoning (Akıl Yürütme) üretir.
|
| 52 |
+
"""
|
| 53 |
+
if not IS_LLM_ENABLED or not misc_items:
|
| 54 |
+
return []
|
| 55 |
|
| 56 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
|
|
| 57 |
|
| 58 |
+
# Etiket tanımlarını LLM'e aktarılacak metne dönüştür
|
| 59 |
+
label_rules = ""
|
| 60 |
+
for k, v in CUSTOM_LABELS.items():
|
| 61 |
+
label_rules += f"### {k}\nTANIM: {v['tanim']}\nANAHTARLAR: {', '.join(v['anahtar_kelimeler'])}\n\n"
|
| 62 |
|
| 63 |
+
# Analiz edilecek varlıkları listele
|
| 64 |
+
targets_text = ""
|
| 65 |
+
for i, item in enumerate(misc_items):
|
| 66 |
+
targets_text += f"VARLIK {i+1}: {item['word']}\nWIKIPEDIA BİLGİSİ: {item['wiki']}\n---\n"
|
| 67 |
|
| 68 |
+
prompt = f"""Sen bir semantik analiz uzmanısın. Aşağıdaki varlıkları orijinal cümledeki bağlamına ve Wikipedia bilgilerine dayanarak sınıflandır.
|
| 69 |
+
|
| 70 |
+
ETİKET TANIMLARI:
|
| 71 |
{label_rules}
|
| 72 |
|
| 73 |
+
ORİJİNAL CÜMLE: "{full_sentence}"
|
| 74 |
+
|
| 75 |
+
GÖREV:
|
| 76 |
+
Aşağıdaki her varlık için 4 adımlı (Sentaktik, Bilgi Entegrasyonu, Çelişki Denetimi, Karar) bir Reasoning süreci oluştur ve en uygun etiketi ata.
|
| 77 |
+
Çıktıyı SADECE aşağıdaki JSON formatında ver, başka metin yazma:
|
| 78 |
+
|
| 79 |
+
[
|
| 80 |
+
{{
|
| 81 |
+
"varlik": "Varlık Adı",
|
| 82 |
+
"reasoning": "1. Sentaktik İnceleme... 2. Bilgi Entegrasyonu... 3. Çelişki Denetimi... 4. Karar...",
|
| 83 |
+
"karar": "ETIKET_ADI"
|
| 84 |
+
}}
|
| 85 |
+
]
|
| 86 |
+
|
| 87 |
+
ANALİZ EDİLECEK VARLIKLAR:
|
| 88 |
+
{targets_text}"""
|
| 89 |
|
| 90 |
+
# Chat Template Uygula
|
| 91 |
+
messages = [{"role": "user", "content": prompt}]
|
| 92 |
+
input_text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 93 |
+
model_inputs = tokenizer([input_text], return_tensors="pt").to(device)
|
| 94 |
|
| 95 |
try:
|
| 96 |
+
# Üretim ayarları
|
| 97 |
+
generated_ids = llm_model.generate(
|
| 98 |
+
model_inputs.input_ids,
|
| 99 |
+
max_new_tokens=1500,
|
| 100 |
+
do_sample=False,
|
| 101 |
+
temperature=0.1
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
# Yanıtı çözümle
|
| 105 |
+
response_ids = [output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)]
|
| 106 |
+
full_output = tokenizer.batch_decode(response_ids, skip_special_tokens=True)[0].strip()
|
| 107 |
+
|
| 108 |
+
# JSON Bloğunu Ayıkla
|
| 109 |
+
json_match = re.search(r'\[\s*\{.*\}\s*\]', full_output, re.DOTALL)
|
| 110 |
+
if json_match:
|
| 111 |
+
parsed_data = json.loads(json_match.group(0))
|
| 112 |
+
# Güvenlik Kontrolü: 'karar' alanının etiket listesinde olduğunu doğrula
|
| 113 |
+
valid_labels = list(CUSTOM_LABELS.keys())
|
| 114 |
+
for entry in parsed_data:
|
| 115 |
+
if entry['karar'] not in valid_labels:
|
| 116 |
+
entry['karar'] = "MISC"
|
| 117 |
+
return parsed_data
|
| 118 |
+
|
| 119 |
+
return []
|
| 120 |
+
except Exception as e:
|
| 121 |
+
print(f"LLM İşleme Hatası: {e}")
|
| 122 |
+
return []
|