Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,172 +6,150 @@ import re
|
|
| 6 |
import gradio as gr
|
| 7 |
from transformers import pipeline
|
| 8 |
|
| 9 |
-
# --- 1. MODELLERİN
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
# NER Modeli (Her zaman CPU)
|
| 13 |
ner_pipe = pipeline(
|
| 14 |
"ner",
|
| 15 |
model="xlm-roberta-large-finetuned-conll03-english",
|
| 16 |
aggregation_strategy="simple",
|
| 17 |
-
device="cpu"
|
| 18 |
)
|
| 19 |
-
_initial_logs.append("✅ Standart NER Modeli Hazır (CPU).")
|
| 20 |
|
| 21 |
-
# LLM Modeli
|
| 22 |
model_id = "Qwen/Qwen2.5-1.5B-Instruct"
|
| 23 |
-
IS_LLM_ENABLED = False
|
| 24 |
try:
|
| 25 |
gen_pipe = pipeline(
|
| 26 |
"text-generation",
|
| 27 |
model=model_id,
|
| 28 |
model_kwargs={"dtype": torch.bfloat16},
|
| 29 |
-
device_map="cpu",
|
| 30 |
trust_remote_code=True
|
| 31 |
)
|
| 32 |
IS_LLM_ENABLED = True
|
| 33 |
-
_initial_logs.append("✅ LLM (Qwen) CPU belleğine yüklendi.")
|
| 34 |
except Exception as e:
|
| 35 |
-
|
|
|
|
| 36 |
|
| 37 |
# --- 2. YARDIMCI FONKSİYONLAR ---
|
| 38 |
|
| 39 |
def get_wiki_summary(term):
|
| 40 |
-
"""Wikipedia'dan
|
| 41 |
try:
|
| 42 |
wikipedia.set_lang("tr")
|
| 43 |
-
#
|
| 44 |
search_results = wikipedia.search(term)
|
| 45 |
if not search_results:
|
| 46 |
return None
|
|
|
|
| 47 |
return wikipedia.summary(search_results[0], sentences=2, auto_suggest=False)
|
| 48 |
-
except:
|
|
|
|
| 49 |
return None
|
| 50 |
|
| 51 |
@spaces.GPU
|
| 52 |
def refine_label_with_llm(entity_text, wiki_context, custom_label_definitions):
|
| 53 |
-
"""
|
| 54 |
if not IS_LLM_ENABLED or gen_pipe is None:
|
| 55 |
-
return "MISC", "LLM
|
| 56 |
|
|
|
|
| 57 |
if next(gen_pipe.model.parameters()).device.type != "cuda":
|
| 58 |
gen_pipe.model.to("cuda")
|
| 59 |
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
# Sizin paylaştığınız ve çalışan Few-Shot yapısı
|
| 63 |
-
prompt = f"""Sen uzman bir veri sınıflandırma sistemisin.
|
| 64 |
-
Görevin, aşağıdaki BAĞLAM'ı okumak ve ETİKET TANIMLARI'ndan hangisinin varlığa en uygun olduğunu belirlemektir.
|
| 65 |
|
| 66 |
-
|
| 67 |
-
VARLIK: Türk
|
| 68 |
-
BAĞLAM: Türkler, Türkiye Cumhuriyeti'nde yaşayan büyük bir etnik gruptur.
|
| 69 |
-
SONUÇ: NORP
|
| 70 |
|
| 71 |
-
ÖRNEK 2 (SOFTWARE İÇİN):
|
| 72 |
-
VARLIK: Photoshop
|
| 73 |
-
BAĞLAM: Adobe tarafından geliştirilen fotoğraf düzenleme programı.
|
| 74 |
-
SONUÇ: SOFTWARE
|
| 75 |
-
|
| 76 |
-
---
|
| 77 |
ETİKET TANIMLARI:
|
| 78 |
-
{
|
| 79 |
-
|
|
|
|
| 80 |
VARLIK: {entity_text}
|
| 81 |
-
BAĞLAM
|
| 82 |
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
|
| 87 |
-
Gerekçe:
|
|
|
|
| 88 |
|
| 89 |
messages = [{"role": "user", "content": prompt}]
|
| 90 |
|
| 91 |
try:
|
| 92 |
-
outputs = gen_pipe(messages, max_new_tokens=
|
| 93 |
full_output = outputs[0]["generated_text"][-1]["content"].strip()
|
| 94 |
|
| 95 |
-
#
|
| 96 |
-
|
| 97 |
-
|
| 98 |
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
final_label = raw_label
|
| 107 |
-
elif 'Gerekçe:' in line:
|
| 108 |
-
reasoning = line.replace('Gerekçe:', '').strip()
|
| 109 |
-
|
| 110 |
-
return final_label, reasoning
|
| 111 |
-
except:
|
| 112 |
-
return "MISC", "LLM işleme hatası."
|
| 113 |
-
|
| 114 |
-
# --- 3. ANA İŞLEM HATTI ---
|
| 115 |
|
| 116 |
-
|
| 117 |
-
log_messages = list(_initial_logs)
|
| 118 |
-
yield log_messages, None
|
| 119 |
|
| 120 |
-
|
|
|
|
|
|
|
| 121 |
final_results = []
|
| 122 |
-
|
| 123 |
-
for
|
| 124 |
word = entity['word']
|
| 125 |
label = entity['entity_group']
|
| 126 |
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
if label == "MISC":
|
| 132 |
standardized_word = word.strip().title()
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
res_obj.update({"final_label": new_label, "source": "RAG+LLM", "reasoning": reason})
|
| 143 |
-
log_messages.append(f"🔄 Etiket Güncellendi: {new_label}")
|
| 144 |
-
else:
|
| 145 |
-
log_messages.append(f"❌ '{word}' için Wiki kaydı yok.")
|
| 146 |
|
| 147 |
final_results.append(res_obj)
|
| 148 |
-
|
|
|
|
| 149 |
|
| 150 |
-
# --- 4.
|
| 151 |
|
| 152 |
-
|
| 153 |
-
"
|
| 154 |
-
"
|
| 155 |
-
"
|
| 156 |
-
"
|
|
|
|
|
|
|
| 157 |
}
|
| 158 |
|
| 159 |
-
def
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
if table:
|
| 165 |
-
for r in table:
|
| 166 |
-
table_data.append([r['entity'], r['initial_label'], r['final_label'], r['source']])
|
| 167 |
-
|
| 168 |
-
yield log_html, table_data
|
| 169 |
|
| 170 |
iface = gr.Interface(
|
| 171 |
-
fn=
|
| 172 |
-
inputs=gr.Textbox(label="Metin Girin"),
|
| 173 |
-
outputs=
|
| 174 |
-
title="NER RAG v2"
|
| 175 |
)
|
| 176 |
|
| 177 |
if __name__ == "__main__":
|
|
|
|
| 6 |
import gradio as gr
|
| 7 |
from transformers import pipeline
|
| 8 |
|
| 9 |
+
# --- 1. MODELLERİN YÜKLENMESİ ---
|
| 10 |
+
# NER Modeli CPU'da çalışır
|
|
|
|
|
|
|
| 11 |
ner_pipe = pipeline(
|
| 12 |
"ner",
|
| 13 |
model="xlm-roberta-large-finetuned-conll03-english",
|
| 14 |
aggregation_strategy="simple",
|
| 15 |
+
device="cpu"
|
| 16 |
)
|
|
|
|
| 17 |
|
| 18 |
+
# LLM Modeli CPU'da başlar, @spaces.GPU ile GPU'ya geçer
|
| 19 |
model_id = "Qwen/Qwen2.5-1.5B-Instruct"
|
|
|
|
| 20 |
try:
|
| 21 |
gen_pipe = pipeline(
|
| 22 |
"text-generation",
|
| 23 |
model=model_id,
|
| 24 |
model_kwargs={"dtype": torch.bfloat16},
|
| 25 |
+
device_map="cpu",
|
| 26 |
trust_remote_code=True
|
| 27 |
)
|
| 28 |
IS_LLM_ENABLED = True
|
|
|
|
| 29 |
except Exception as e:
|
| 30 |
+
print(f"LLM Yükleme Hatası: {e}")
|
| 31 |
+
IS_LLM_ENABLED = False
|
| 32 |
|
| 33 |
# --- 2. YARDIMCI FONKSİYONLAR ---
|
| 34 |
|
| 35 |
def get_wiki_summary(term):
|
| 36 |
+
"""Wikipedia'dan hata almadan özet çeker."""
|
| 37 |
try:
|
| 38 |
wikipedia.set_lang("tr")
|
| 39 |
+
# Belirsizlik (Disambiguation) hatalarını önlemek için arama sonucunun ilkini alıyoruz
|
| 40 |
search_results = wikipedia.search(term)
|
| 41 |
if not search_results:
|
| 42 |
return None
|
| 43 |
+
# summary fonksiyonunda auto_suggest=False kullanarak tam eşleşme arıyoruz
|
| 44 |
return wikipedia.summary(search_results[0], sentences=2, auto_suggest=False)
|
| 45 |
+
except Exception as e:
|
| 46 |
+
print(f"Wiki Hatası ({term}): {e}")
|
| 47 |
return None
|
| 48 |
|
| 49 |
@spaces.GPU
|
| 50 |
def refine_label_with_llm(entity_text, wiki_context, custom_label_definitions):
|
| 51 |
+
"""ZeroGPU üzerinde çalışan akıllı etiketleme."""
|
| 52 |
if not IS_LLM_ENABLED or gen_pipe is None:
|
| 53 |
+
return "MISC", "LLM Yüklenemedi."
|
| 54 |
|
| 55 |
+
# GPU'ya taşıma kontrolü
|
| 56 |
if next(gen_pipe.model.parameters()).device.type != "cuda":
|
| 57 |
gen_pipe.model.to("cuda")
|
| 58 |
|
| 59 |
+
label_defs = "\n".join([f"- {k}: {v}" for k, v in custom_label_definitions.items()])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
+
prompt = f"""Görevin, Wikipedia bağlamını kullanarak varlığı en uygun etikete yerleştirmektir.
|
|
|
|
|
|
|
|
|
|
| 62 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
ETİKET TANIMLARI:
|
| 64 |
+
{label_defs}
|
| 65 |
+
|
| 66 |
+
GÖREV:
|
| 67 |
VARLIK: {entity_text}
|
| 68 |
+
BAĞLAM: {wiki_context}
|
| 69 |
|
| 70 |
+
Kurallar:
|
| 71 |
+
1. Sadece tanımlardaki etiketlerden birini seç.
|
| 72 |
+
2. Kararını Gerekçe ve Cevap formatında yaz.
|
| 73 |
|
| 74 |
+
Gerekçe: [Analiz]
|
| 75 |
+
Cevap: [ETİKET]"""
|
| 76 |
|
| 77 |
messages = [{"role": "user", "content": prompt}]
|
| 78 |
|
| 79 |
try:
|
| 80 |
+
outputs = gen_pipe(messages, max_new_tokens=100, do_sample=False, temperature=0.1)
|
| 81 |
full_output = outputs[0]["generated_text"][-1]["content"].strip()
|
| 82 |
|
| 83 |
+
# Cevap kısmını yakala (Büyük/Küçük harf duyarsız)
|
| 84 |
+
match = re.search(r"Cevap:\s*([A-Z_]+)", full_output, re.IGNORECASE)
|
| 85 |
+
final_label = match.group(1).upper() if match else "MISC"
|
| 86 |
|
| 87 |
+
# Seçilen etiket listede var mı kontrolü
|
| 88 |
+
if final_label not in custom_label_definitions:
|
| 89 |
+
final_label = "MISC"
|
| 90 |
+
|
| 91 |
+
return final_label, full_output
|
| 92 |
+
except Exception as e:
|
| 93 |
+
return "MISC", f"Hata: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
+
# --- 3. ANA İŞLEM HATTI (PIPELINE) ---
|
|
|
|
|
|
|
| 96 |
|
| 97 |
+
def advanced_ner_pipeline(text, target_labels):
|
| 98 |
+
"""Hem Gradio hem terminal için uyumlu ana fonksiyon."""
|
| 99 |
+
initial_results = ner_pipe(text)
|
| 100 |
final_results = []
|
| 101 |
+
|
| 102 |
+
for entity in initial_results:
|
| 103 |
word = entity['word']
|
| 104 |
label = entity['entity_group']
|
| 105 |
|
| 106 |
+
res_obj = {
|
| 107 |
+
"entity": word,
|
| 108 |
+
"initial_label": label,
|
| 109 |
+
"final_label": label,
|
| 110 |
+
"source": "Model",
|
| 111 |
+
"reasoning": ""
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
# Sadece MISC ise ve Wiki/LLM süreci başlatılacaksa
|
| 115 |
if label == "MISC":
|
| 116 |
standardized_word = word.strip().title()
|
| 117 |
+
wiki_context = get_wiki_summary(standardized_word)
|
| 118 |
+
|
| 119 |
+
if wiki_context:
|
| 120 |
+
new_label, reasoning = refine_label_with_llm(standardized_word, wiki_context, target_labels)
|
| 121 |
+
res_obj.update({
|
| 122 |
+
"final_label": new_label,
|
| 123 |
+
"source": "RAG+LLM",
|
| 124 |
+
"reasoning": reasoning
|
| 125 |
+
})
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
final_results.append(res_obj)
|
| 128 |
+
|
| 129 |
+
return final_results
|
| 130 |
|
| 131 |
+
# --- 4. GRADIO ARAYÜZÜ ---
|
| 132 |
|
| 133 |
+
custom_label_definitions = {
|
| 134 |
+
"SOFTWARE": "Bilgisayar programları, işletim sistemleri.",
|
| 135 |
+
"AWARD": "Ödüller, madalyalar.",
|
| 136 |
+
"BOOK": "Kitaplar ve yazılı eserler.",
|
| 137 |
+
"MOVIE": "Sinema filmleri.",
|
| 138 |
+
"PRODUCT": "Ticari ürünler ve cihazlar.",
|
| 139 |
+
"NORP": "Milliyetler, dini veya politik gruplar."
|
| 140 |
}
|
| 141 |
|
| 142 |
+
def process_and_display(text):
|
| 143 |
+
results = advanced_ner_pipeline(text, custom_label_definitions)
|
| 144 |
+
# Gradio Dataframe için veriyi listeye çevir
|
| 145 |
+
table_data = [[r['entity'], r['initial_label'], r['final_label'], r['source']] for r in results]
|
| 146 |
+
return table_data
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
|
| 148 |
iface = gr.Interface(
|
| 149 |
+
fn=process_and_display,
|
| 150 |
+
inputs=gr.Textbox(label="Metin Girin", lines=5),
|
| 151 |
+
outputs=gr.Dataframe(headers=["Varlık", "İlk Etiket", "Nihai Etiket", "Kaynak"]),
|
| 152 |
+
title="NER RAG Final v2"
|
| 153 |
)
|
| 154 |
|
| 155 |
if __name__ == "__main__":
|