Spaces:
Sleeping
Sleeping
Create ner_logic.py
Browse files- ner_logic.py +46 -0
ner_logic.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Modellerin Yüklenmesi
|
| 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}\n- TANIM: {v['tanim']}\n" for k, v in CUSTOM_LABELS.items()])
|
| 29 |
+
targets_text = "".join([f"\nVARLIK {i+1}: {item['word']}\nWIKI: {item['wiki']}\n" for i, item in enumerate(misc_items)])
|
| 30 |
+
|
| 31 |
+
prompt = f"""Sen semantik analiz uzmanısın. 4 adımlı CoT protokolüyle analiz yap.
|
| 32 |
+
CÜMLE: "{full_sentence}"
|
| 33 |
+
VARLIKLAR: {targets_text}
|
| 34 |
+
ETİKETLER: {label_rules}
|
| 35 |
+
ÇIKTI: Sadece JSON listesi döndür. Her nesne 'varlik', 'analiz', 'karar' içermeli."""
|
| 36 |
+
|
| 37 |
+
messages = [{"role": "user", "content": prompt}]
|
| 38 |
+
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 39 |
+
model_inputs = tokenizer([text], return_tensors="pt").to(device)
|
| 40 |
+
|
| 41 |
+
try:
|
| 42 |
+
generated_ids = llm_model.generate(model_inputs.input_ids, max_new_tokens=1500, do_sample=False)
|
| 43 |
+
full_output = tokenizer.batch_decode(generated_ids[:, model_inputs.input_ids.shape[1]:], skip_special_tokens=True)[0].strip()
|
| 44 |
+
json_match = re.search(r'\[\s*\{.*\}\s*\]', full_output, re.DOTALL)
|
| 45 |
+
return json.loads(json_match.group(0)) if json_match else []
|
| 46 |
+
except: return []
|