Spaces:
Sleeping
Sleeping
Update ner_logic.py
Browse files- ner_logic.py +19 -50
ner_logic.py
CHANGED
|
@@ -1,42 +1,22 @@
|
|
| 1 |
import torch
|
| 2 |
-
import wikipedia # Hata almamak için pip install wikipedia yapılmalı
|
| 3 |
-
import re
|
| 4 |
import json
|
| 5 |
-
import
|
| 6 |
-
from transformers import
|
| 7 |
from labels_config import CUSTOM_LABELS
|
| 8 |
from prompts import SYSTEM_COT_PROMPT
|
|
|
|
| 9 |
|
| 10 |
-
#
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 14 |
-
llm_model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.bfloat16, device_map="auto", trust_remote_code=True)
|
| 15 |
-
|
| 16 |
-
def get_wiki_summary(term):
|
| 17 |
-
"""Wikipedia'dan bilgi çeken kritik fonksiyon."""
|
| 18 |
-
try:
|
| 19 |
-
wikipedia.set_lang("tr")
|
| 20 |
-
search_results = wikipedia.search(term)
|
| 21 |
-
if not search_results:
|
| 22 |
-
return "Wikipedia'da bu terim için sonuç bulunamadı."
|
| 23 |
-
# İlk sonucun özetini al
|
| 24 |
-
summary = wikipedia.summary(search_results[0], sentences=2, auto_suggest=False)
|
| 25 |
-
return summary
|
| 26 |
-
except Exception as e:
|
| 27 |
-
return f"Wikipedia sorgu hatası: {str(e)}"
|
| 28 |
|
| 29 |
@spaces.GPU
|
| 30 |
def refine_labels_batch(misc_items, full_sentence):
|
| 31 |
-
if not misc_items:
|
| 32 |
-
return []
|
| 33 |
-
|
| 34 |
-
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 35 |
|
| 36 |
-
# Label kurallarını oluşturma
|
| 37 |
label_rules = ""
|
| 38 |
for k, v in CUSTOM_LABELS.items():
|
| 39 |
-
label_rules += f"### {k}\nTANIM: {v['tanim']}\nANAHTARLAR: {', '.join(v['anahtar_kelimeler'])}\
|
| 40 |
|
| 41 |
targets_text = "".join([f"- VARLIK: {item['word']} | WIKI: {item['wiki']}\n" for item in misc_items])
|
| 42 |
|
|
@@ -48,37 +28,26 @@ def refine_labels_batch(misc_items, full_sentence):
|
|
| 48 |
|
| 49 |
messages = [{"role": "user", "content": final_prompt}]
|
| 50 |
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 51 |
-
model_inputs = tokenizer([text], return_tensors="pt").to(device)
|
| 52 |
|
| 53 |
try:
|
| 54 |
-
|
| 55 |
-
generated_ids = llm_model.generate(
|
| 56 |
-
model_inputs.input_ids,
|
| 57 |
-
max_new_tokens=1500,
|
| 58 |
-
do_sample=False
|
| 59 |
-
)
|
| 60 |
output = tokenizer.batch_decode(generated_ids[:, model_inputs.input_ids.shape[1]:], skip_special_tokens=True)[0]
|
| 61 |
|
| 62 |
-
|
| 63 |
-
json_match = re.search(r'\[.*\]', output, re.DOTALL)
|
| 64 |
-
|
| 65 |
if json_match:
|
| 66 |
-
raw_json = json_match.group(0)
|
|
|
|
| 67 |
|
| 68 |
-
# Eksik parantez kontrolü ve tamamlama
|
| 69 |
-
if raw_json.count('{') > raw_json.count('}'):
|
| 70 |
-
raw_json += "}]"
|
| 71 |
-
|
| 72 |
-
# JSON Parse işlemi
|
| 73 |
results = json.loads(raw_json)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
return results
|
| 75 |
else:
|
| 76 |
-
print(f"
|
| 77 |
return []
|
| 78 |
-
|
| 79 |
-
except json.JSONDecodeError as e:
|
| 80 |
-
print(f"JSON Çözümleme Hatası: {str(e)}")
|
| 81 |
-
return []
|
| 82 |
except Exception as e:
|
| 83 |
-
print(f"
|
| 84 |
return []
|
|
|
|
| 1 |
import torch
|
|
|
|
|
|
|
| 2 |
import json
|
| 3 |
+
import re
|
| 4 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 5 |
from labels_config import CUSTOM_LABELS
|
| 6 |
from prompts import SYSTEM_COT_PROMPT
|
| 7 |
+
import spaces
|
| 8 |
|
| 9 |
+
# Global modeller (Örnek olarak Qwen kullanılmıştır)
|
| 10 |
+
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-1.5B-Instruct")
|
| 11 |
+
llm_model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-1.5B-Instruct", torch_dtype="auto", device_map="auto")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
@spaces.GPU
|
| 14 |
def refine_labels_batch(misc_items, full_sentence):
|
| 15 |
+
if not misc_items: return []
|
|
|
|
|
|
|
|
|
|
| 16 |
|
|
|
|
| 17 |
label_rules = ""
|
| 18 |
for k, v in CUSTOM_LABELS.items():
|
| 19 |
+
label_rules += f"### {k}\nTANIM: {v['tanim']}\nANAHTARLAR: {', '.join(v['anahtar_kelimeler'])}\n\n"
|
| 20 |
|
| 21 |
targets_text = "".join([f"- VARLIK: {item['word']} | WIKI: {item['wiki']}\n" for item in misc_items])
|
| 22 |
|
|
|
|
| 28 |
|
| 29 |
messages = [{"role": "user", "content": final_prompt}]
|
| 30 |
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 31 |
+
model_inputs = tokenizer([text], return_tensors="pt").to(llm_model.device)
|
| 32 |
|
| 33 |
try:
|
| 34 |
+
generated_ids = llm_model.generate(model_inputs.input_ids, max_new_tokens=1500, do_sample=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
output = tokenizer.batch_decode(generated_ids[:, model_inputs.input_ids.shape[1]:], skip_special_tokens=True)[0]
|
| 36 |
|
| 37 |
+
json_match = re.search(r'\[\s*\{.*\}\s*\]', output, re.DOTALL)
|
|
|
|
|
|
|
| 38 |
if json_match:
|
| 39 |
+
raw_json = json_match.group(0).strip()
|
| 40 |
+
if raw_json.count('{') > raw_json.count('}'): raw_json += "}]"
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
results = json.loads(raw_json)
|
| 43 |
+
# app.py uyumu için anahtar kontrolü
|
| 44 |
+
for r in results:
|
| 45 |
+
if 'karar' not in r: r['karar'] = "MISC"
|
| 46 |
+
if 'reasoning' not in r: r['reasoning'] = "Analiz adımları oluşturulamadı."
|
| 47 |
return results
|
| 48 |
else:
|
| 49 |
+
print(f"Format Hatası: {output}")
|
| 50 |
return []
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
except Exception as e:
|
| 52 |
+
print(f"Hata: {str(e)}")
|
| 53 |
return []
|