apak commited on
Commit
d2ee440
·
verified ·
1 Parent(s): e4ab695

Update ner_logic.py

Browse files
Files changed (1) hide show
  1. 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
- # Modeller
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
  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: return None
 
22
 
23
  @spaces.GPU
24
  def refine_labels_batch(misc_items, full_sentence):
25
- if not misc_items: return []
26
- device = "cuda" if torch.cuda.is_available() else "cpu"
 
 
 
 
27
 
28
- label_rules = "".join([f"### {k}: {v['tanim']}\n" for k, v in CUSTOM_LABELS.items()])
29
- targets = "".join([f"- VARLIK: {item['word']} | WIKI: {item['wiki']}\n" for item in misc_items])
30
 
31
- prompt = f"""CÜMLE: "{full_sentence}"
32
- Aşağıdaki varlıkları analiz et. Her biri için SADECE şu JSON formatında yanıt ver:
33
- [{{ "varlik": "...", "analiz": "4 adımlı kısa CoT", "karar": "ETIKET" }}]
 
34
 
35
- VARLIKLAR:
36
- {targets}
 
 
37
 
38
- ETİKETLER:
 
 
39
  {label_rules}
40
 
41
- NOT: 'karar' alanına asla True/False yazma, sadece yukarıdaki etiket isimlerinden birini yaz."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
- inputs = tokenizer.apply_chat_template([{"role": "user", "content": prompt}], tokenize=False, add_generation_prompt=True)
44
- model_inputs = tokenizer([inputs], return_tensors="pt").to(device)
 
 
45
 
46
  try:
47
- generated_ids = llm_model.generate(model_inputs.input_ids, max_new_tokens=1000, do_sample=False)
48
- output = tokenizer.batch_decode(generated_ids[:, model_inputs.input_ids.shape[1]:], skip_special_tokens=True)[0]
49
- json_match = re.search(r'\[\s*\{.*\}\s*\]', output, re.DOTALL)
50
- return json.loads(json_match.group(0)) if json_match else []
51
- except: return []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 []