apak commited on
Commit
e5df85c
·
verified ·
1 Parent(s): 64de3d2

Update ner_logic.py

Browse files
Files changed (1) hide show
  1. ner_logic.py +31 -102
ner_logic.py CHANGED
@@ -1,122 +1,51 @@
1
  import torch
2
- import wikipedia
3
  import re
4
  import json
5
  import spaces
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 []
 
1
  import torch
 
2
  import re
3
  import json
4
  import spaces
5
  from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
6
  from labels_config import CUSTOM_LABELS
7
+ from prompts import SYSTEM_COT_PROMPT # Harici prompt modulu
8
 
9
+ # Modellerin yuklenmesi (XLMR ve Qwen)
10
+ ner_pipe = pipeline("ner", model="xlm-roberta-large-finetuned-conll03-english", aggregation_strategy="simple", device=-1)
 
 
 
 
 
 
 
 
11
  model_id = "Qwen/Qwen2.5-1.5B-Instruct"
12
  tokenizer = AutoTokenizer.from_pretrained(model_id)
13
+ llm_model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.bfloat16, device_map="auto", trust_remote_code=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
  @spaces.GPU
16
  def refine_labels_batch(misc_items, full_sentence):
17
+ if not misc_items: return []
 
 
 
 
 
 
18
  device = "cuda" if torch.cuda.is_available() else "cpu"
19
+
20
+ # Etiket kurallari metni oluşturma
21
+ label_rules = "".join([f"### {k}: {v['tanim']}\n" for k, v in CUSTOM_LABELS.items()])
22
+
23
+ # Varlik ve Wiki metni oluşturma
24
+ targets_text = "".join([f"- VARLIK: {item['word']} | WIKI: {item['wiki']}\n" for item in misc_items])
25
+
26
+ # Harici promptu doldurma
27
+ final_prompt = SYSTEM_COT_PROMPT.format(
28
+ label_rules=label_rules,
29
+ full_sentence=full_sentence,
30
+ targets=targets_text
31
+ )
32
 
33
+ messages = [{"role": "user", "content": final_prompt}]
34
+ text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
35
+ model_inputs = tokenizer([text], return_tensors="pt").to(device)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
  try:
38
+ generated_ids = llm_model.generate(model_inputs.input_ids, max_new_tokens=1500, do_sample=False)
39
+ output = tokenizer.batch_decode(generated_ids[:, model_inputs.input_ids.shape[1]:], skip_special_tokens=True)[0]
 
 
 
 
 
40
 
41
+ json_match = re.search(r'\[\s*\{.*\}\s*\]', output, re.DOTALL)
 
 
 
 
 
42
  if json_match:
43
+ results = json.loads(json_match.group(0))
44
+ # Karar alaninda True/False temizligi
45
+ for r in results:
46
+ if not isinstance(r.get("karar"), str) or r["karar"] in ["True", "False"]:
47
+ r["karar"] = "MISC"
48
+ return results
 
 
49
  return []
50
+ except:
 
51
  return []