Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,210 +1,201 @@
|
|
| 1 |
import torch
|
| 2 |
import wikipedia
|
| 3 |
-
|
| 4 |
-
import gradio as gr
|
| 5 |
import os
|
| 6 |
import re
|
| 7 |
-
import
|
|
|
|
| 8 |
|
| 9 |
-
# ---
|
| 10 |
_initial_logs = []
|
| 11 |
|
| 12 |
-
# ---
|
| 13 |
-
|
| 14 |
-
|
| 15 |
ner_pipe = pipeline(
|
| 16 |
"ner",
|
| 17 |
model="xlm-roberta-large-finetuned-conll03-english",
|
| 18 |
aggregation_strategy="simple",
|
| 19 |
device="cpu"
|
| 20 |
)
|
| 21 |
-
_initial_logs.append("✅ Standart NER Modeli Hazır
|
| 22 |
|
| 23 |
-
# ---
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
|
|
|
| 27 |
|
| 28 |
try:
|
| 29 |
-
# Modeli başlangıçta CPU'da (RAM) tutuyoruz.
|
| 30 |
gen_pipe = pipeline(
|
| 31 |
"text-generation",
|
| 32 |
model=model_id,
|
| 33 |
-
model_kwargs={"dtype": torch.bfloat16},
|
| 34 |
-
device_map="cpu",
|
| 35 |
trust_remote_code=True
|
| 36 |
)
|
| 37 |
IS_LLM_ENABLED = True
|
| 38 |
-
|
| 39 |
-
|
| 40 |
except Exception as e:
|
| 41 |
-
_initial_logs.append(f"❌ LLM yüklenirken
|
|
|
|
| 42 |
|
|
|
|
| 43 |
|
| 44 |
-
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
def refine_label_with_llm(entity_text, wiki_context, custom_label_definitions):
|
| 47 |
-
"""LLM kullanarak MISC etiketini rafine eder
|
| 48 |
-
|
| 49 |
if not IS_LLM_ENABLED or gen_pipe is None:
|
| 50 |
-
return "MISC", "LLM
|
| 51 |
|
| 52 |
-
# Modeli
|
| 53 |
if gen_pipe.device.type != "cuda":
|
| 54 |
gen_pipe.model.to("cuda")
|
| 55 |
|
|
|
|
| 56 |
refinable_labels = {k: v for k, v in custom_label_definitions.items() if k not in ["PER", "LOC", "ORG", "MISC"]}
|
| 57 |
label_definitions_str = "\n".join([f"- {k}: {v}" for k, v in refinable_labels.items()])
|
| 58 |
-
|
| 59 |
-
# ... (Buradaki prompt hazırlama kısımları aynı kalıyor, kısalık adına atladım) ...
|
| 60 |
-
few_shot_examples = "..." # Mevcut kodundaki örnekleri buraya ekle
|
| 61 |
|
| 62 |
-
prompt = f"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
messages = [{"role": "user", "content": prompt}]
|
| 64 |
|
| 65 |
try:
|
| 66 |
-
outputs = gen_pipe(
|
| 67 |
-
messages,
|
| 68 |
-
max_new_tokens=150,
|
| 69 |
-
do_sample=False,
|
| 70 |
-
temperature=0.1
|
| 71 |
-
)
|
| 72 |
full_output = outputs[0]["generated_text"][-1]["content"].strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
except Exception as e:
|
| 74 |
-
return "MISC", f"
|
| 75 |
|
| 76 |
-
|
| 77 |
-
final_label = "MISC"
|
| 78 |
-
cog_output = ""
|
| 79 |
-
valid_labels = list(custom_label_definitions.keys())
|
| 80 |
-
|
| 81 |
-
match_cevap = re.search(r'CEVAP:\s*([A-Z_]+)', full_output, re.IGNORECASE)
|
| 82 |
-
if match_cevap:
|
| 83 |
-
raw_label = match_cevap.group(1).strip().upper()
|
| 84 |
-
if raw_label in valid_labels:
|
| 85 |
-
final_label = raw_label
|
| 86 |
-
|
| 87 |
-
match_reasoning = re.search(r'AKIL YÜRÜTME:\s*(.*)', full_output, re.IGNORECASE | re.DOTALL)
|
| 88 |
-
if match_reasoning:
|
| 89 |
-
cog_output = match_reasoning.group(1).strip().replace('\n', ' ')
|
| 90 |
-
|
| 91 |
-
return final_label, cog_output
|
| 92 |
|
| 93 |
-
# --- NER Pipeline Fonksiyonu (RAG KISITLAMASI İLE) ---
|
| 94 |
def advanced_ner_pipeline(text, target_labels, progress=gr.Progress()):
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
try:
|
| 101 |
initial_results = ner_pipe(text)
|
| 102 |
except Exception as e:
|
| 103 |
-
log_messages.append(f"❌
|
| 104 |
yield log_messages, []
|
| 105 |
return
|
| 106 |
-
|
| 107 |
final_results = []
|
| 108 |
-
|
| 109 |
|
| 110 |
-
log_messages.append(f"🕵️♀️ Toplam {total_entities} varlık inceleniyor...")
|
| 111 |
-
yield log_messages, None
|
| 112 |
-
|
| 113 |
-
STANDARD_LABELS = ["PER", "LOC", "ORG"]
|
| 114 |
-
|
| 115 |
for i, entity in enumerate(initial_results):
|
| 116 |
word = entity['word']
|
| 117 |
label = entity['entity_group']
|
| 118 |
-
score = entity['score']
|
| 119 |
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
result_obj = {
|
| 124 |
"entity": word,
|
| 125 |
"initial_label": label,
|
| 126 |
-
"initial_score": score,
|
| 127 |
"final_label": label,
|
| 128 |
"source": "Model",
|
| 129 |
"reasoning": ""
|
| 130 |
}
|
| 131 |
-
|
| 132 |
-
#
|
| 133 |
if label == "MISC" and IS_LLM_ENABLED:
|
| 134 |
-
|
| 135 |
-
log_messages.append(f" ⚠️ MISC tespit edildi: '{word}'. Wiki'ye soruluyor...")
|
| 136 |
yield log_messages, None
|
| 137 |
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
log_messages.append(f" 📄 Wiki Bağlamı bulundu. LLM (GPU) devreye giriyor...")
|
| 142 |
-
yield log_messages, None
|
| 143 |
-
|
| 144 |
-
# Bu fonksiyon @spaces.GPU ile işaretlendiği için burada GPU tahsis edilir
|
| 145 |
-
new_label, reasoning = refine_label_with_llm(standardized_word, wiki_context, target_labels)
|
| 146 |
-
|
| 147 |
-
result_obj["final_label"] = new_label
|
| 148 |
-
result_obj["source"] = "RAG+LLM (CoT)"
|
| 149 |
-
result_obj["reasoning"] = reasoning
|
| 150 |
-
|
| 151 |
-
log_messages.append(f" 🔄 Güncellendi: {new_label}")
|
| 152 |
yield log_messages, None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
else:
|
| 154 |
-
log_messages.append("
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
log_messages.append("✅ İşlem tamamlandı!")
|
| 164 |
yield log_messages, final_results
|
| 165 |
|
| 166 |
-
# ---
|
|
|
|
| 167 |
custom_label_definitions = {
|
| 168 |
"PER": "Kişi adları.", "ORG": "Kurumlar.", "LOC": "Yerler.",
|
| 169 |
"DATE": "Tarihler.", "NORP": "Milliyetler/Gruplar.", "BOOK": "Kitaplar.",
|
| 170 |
"LANGUAGE": "Diller.", "TITLE": "Unvanlar.", "PRODUCT": "Ürünler.",
|
| 171 |
-
"SOFTWARE": "Yazılımlar.", "MISC": "Diğer."
|
| 172 |
}
|
| 173 |
|
| 174 |
-
# --- Gradio Arayüz Fonksiyonu ---
|
| 175 |
def process_ner_request(text, progress=gr.Progress()):
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
current_results_html = "<table><tr><th>Varlık</th><th>Etiket</th><th>Kaynak</th></tr>"
|
| 192 |
-
if final_results:
|
| 193 |
-
for item in final_results:
|
| 194 |
-
current_results_html += f"<tr><td>{item['entity']}</td><td>{item['final_label']}</td><td>{item['source']}</td></tr>"
|
| 195 |
-
current_results_html += "</table>"
|
| 196 |
|
| 197 |
-
yield
|
| 198 |
|
| 199 |
-
# --- Arayüzü Başlat ---
|
| 200 |
iface = gr.Interface(
|
| 201 |
fn=process_ner_request,
|
| 202 |
-
inputs=gr.Textbox(lines=
|
| 203 |
-
outputs=[gr.HTML(label="Sistem
|
| 204 |
-
title="Hibrit NER
|
|
|
|
| 205 |
)
|
| 206 |
|
| 207 |
if __name__ == "__main__":
|
| 208 |
port = int(os.environ.get('PORT', 7860))
|
| 209 |
-
print(f"🚀 Uygulama {port} portunda başlatılıyor...")
|
| 210 |
iface.launch(server_name="0.0.0.0", server_port=port)
|
|
|
|
| 1 |
import torch
|
| 2 |
import wikipedia
|
| 3 |
+
import spaces
|
|
|
|
| 4 |
import os
|
| 5 |
import re
|
| 6 |
+
import gradio as gr
|
| 7 |
+
from transformers import pipeline
|
| 8 |
|
| 9 |
+
# --- 1. SİSTEM HAZIRLIĞI VE LOGLAMA ---
|
| 10 |
_initial_logs = []
|
| 11 |
|
| 12 |
+
# --- 2. XLM-ROBERTA (NER) YÜKLEME ---
|
| 13 |
+
# Bu model her zaman CPU'da kalacak şekilde yapılandırıldı.
|
| 14 |
+
_initial_logs.append("1. Standart NER Modeli (XLM-Roberta) CPU üzerinde yükleniyor...")
|
| 15 |
ner_pipe = pipeline(
|
| 16 |
"ner",
|
| 17 |
model="xlm-roberta-large-finetuned-conll03-english",
|
| 18 |
aggregation_strategy="simple",
|
| 19 |
device="cpu"
|
| 20 |
)
|
| 21 |
+
_initial_logs.append("✅ Standart NER Modeli Hazır.")
|
| 22 |
|
| 23 |
+
# --- 3. QWEN 2.5 (LLM) YÜKLEME ---
|
| 24 |
+
# Başlangıçta sadece RAM'e yüklenir, GPU fonksiyonu çağrıldığında CUDA'ya taşınır.
|
| 25 |
+
_initial_logs.append("2. LLM (Qwen 2.5-1.5B) RAM'e yükleniyor...")
|
| 26 |
+
model_id = "Qwen/Qwen2.5-1.5B-Instruct"
|
| 27 |
+
IS_LLM_ENABLED = False
|
| 28 |
|
| 29 |
try:
|
|
|
|
| 30 |
gen_pipe = pipeline(
|
| 31 |
"text-generation",
|
| 32 |
model=model_id,
|
| 33 |
+
model_kwargs={"dtype": torch.bfloat16},
|
| 34 |
+
device_map="cpu",
|
| 35 |
trust_remote_code=True
|
| 36 |
)
|
| 37 |
IS_LLM_ENABLED = True
|
| 38 |
+
_initial_logs.append("✅ LLM (Karar Verici) Başarıyla RAM'e yüklendi.")
|
|
|
|
| 39 |
except Exception as e:
|
| 40 |
+
_initial_logs.append(f"❌ LLM yüklenirken hata oluştu: {e}")
|
| 41 |
+
gen_pipe = None
|
| 42 |
|
| 43 |
+
# --- 4. YARDIMCI FONKSİYONLAR (WIKIPEDIA & GPU) ---
|
| 44 |
|
| 45 |
+
def get_wiki_summary(term):
|
| 46 |
+
"""Wikipedia'dan terim hakkında özet bilgi çeker."""
|
| 47 |
+
try:
|
| 48 |
+
wikipedia.set_lang("tr")
|
| 49 |
+
search_results = wikipedia.search(term)
|
| 50 |
+
if not search_results:
|
| 51 |
+
return None
|
| 52 |
+
# En alakalı ilk sonucun özetini getir
|
| 53 |
+
return wikipedia.summary(search_results[0], sentences=2, auto_suggest=False)
|
| 54 |
+
except Exception:
|
| 55 |
+
return None
|
| 56 |
+
|
| 57 |
+
@spaces.GPU
|
| 58 |
def refine_label_with_llm(entity_text, wiki_context, custom_label_definitions):
|
| 59 |
+
"""ZeroGPU üzerinde LLM kullanarak MISC etiketini rafine eder."""
|
|
|
|
| 60 |
if not IS_LLM_ENABLED or gen_pipe is None:
|
| 61 |
+
return "MISC", "LLM aktif değil."
|
| 62 |
|
| 63 |
+
# Modeli anlık olarak GPU'ya taşı
|
| 64 |
if gen_pipe.device.type != "cuda":
|
| 65 |
gen_pipe.model.to("cuda")
|
| 66 |
|
| 67 |
+
# Etiket tanımlarını hazırlama
|
| 68 |
refinable_labels = {k: v for k, v in custom_label_definitions.items() if k not in ["PER", "LOC", "ORG", "MISC"]}
|
| 69 |
label_definitions_str = "\n".join([f"- {k}: {v}" for k, v in refinable_labels.items()])
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
+
prompt = f"""Sen uzman bir veri sınıflandırma sistemisin.
|
| 72 |
+
Aşağıdaki varlığı, Wikipedia bağlamını kullanarak en uygun etikete yerleştir.
|
| 73 |
+
|
| 74 |
+
ETİKET TANIMLARI:
|
| 75 |
+
{label_definitions_str}
|
| 76 |
+
|
| 77 |
+
GÖREV:
|
| 78 |
+
VARLIK: {entity_text}
|
| 79 |
+
WIKIPEDIA BAĞLAMI: {wiki_context}
|
| 80 |
+
|
| 81 |
+
ÇIKTI FORMATI (Sadece bunu kullan):
|
| 82 |
+
GÖZLEM: [Tespitlerin]
|
| 83 |
+
AKIL YÜRÜTME: [Neden bu etiketi seçtin?]
|
| 84 |
+
CEVAP: [Sadece Etiket Adı]"""
|
| 85 |
+
|
| 86 |
messages = [{"role": "user", "content": prompt}]
|
| 87 |
|
| 88 |
try:
|
| 89 |
+
outputs = gen_pipe(messages, max_new_tokens=150, do_sample=False, temperature=0.1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
full_output = outputs[0]["generated_text"][-1]["content"].strip()
|
| 91 |
+
|
| 92 |
+
# Regex ile CEVAP ve AKIL YÜRÜTME kısımlarını ayıkla
|
| 93 |
+
match_cevap = re.search(r'CEVAP:\s*([A-Z_]+)', full_output, re.IGNORECASE)
|
| 94 |
+
final_label = match_cevap.group(1).strip().upper() if match_cevap else "MISC"
|
| 95 |
+
|
| 96 |
+
match_reasoning = re.search(r'AKIL YÜRÜTME:\s*(.*)', full_output, re.IGNORECASE | re.DOTALL)
|
| 97 |
+
cog_output = match_reasoning.group(1).strip().replace('\n', ' ') if match_reasoning else ""
|
| 98 |
+
|
| 99 |
+
return final_label, cog_output
|
| 100 |
except Exception as e:
|
| 101 |
+
return "MISC", f"LLM İşleme Hatası: {str(e)}"
|
| 102 |
|
| 103 |
+
# --- 5. ANA İŞLEM HATTI (PIPELINE) ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
|
|
|
| 105 |
def advanced_ner_pipeline(text, target_labels, progress=gr.Progress()):
|
| 106 |
+
log_messages = list(_initial_logs)
|
| 107 |
+
log_messages.append(f"🚀 İşlem başladı: '{text[:30]}...'")
|
| 108 |
+
yield log_messages, None
|
| 109 |
+
|
|
|
|
| 110 |
try:
|
| 111 |
initial_results = ner_pipe(text)
|
| 112 |
except Exception as e:
|
| 113 |
+
log_messages.append(f"❌ NER Hatası: {e}")
|
| 114 |
yield log_messages, []
|
| 115 |
return
|
| 116 |
+
|
| 117 |
final_results = []
|
| 118 |
+
total = len(initial_results)
|
| 119 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
for i, entity in enumerate(initial_results):
|
| 121 |
word = entity['word']
|
| 122 |
label = entity['entity_group']
|
| 123 |
+
score = entity['score']
|
| 124 |
|
| 125 |
+
progress((i + 1) / total, desc=f"İnceleniyor: {word}")
|
| 126 |
+
|
| 127 |
+
res_obj = {
|
|
|
|
| 128 |
"entity": word,
|
| 129 |
"initial_label": label,
|
|
|
|
| 130 |
"final_label": label,
|
| 131 |
"source": "Model",
|
| 132 |
"reasoning": ""
|
| 133 |
}
|
| 134 |
+
|
| 135 |
+
# Eğer etiket MISC ise RAG sürecini başlat
|
| 136 |
if label == "MISC" and IS_LLM_ENABLED:
|
| 137 |
+
log_messages.append(f"🔍 MISC: '{word}' için Wikipedia taranıyor...")
|
|
|
|
| 138 |
yield log_messages, None
|
| 139 |
|
| 140 |
+
wiki_text = get_wiki_summary(word)
|
| 141 |
+
if wiki_text:
|
| 142 |
+
log_messages.append(f"🤖 LLM (GPU) '{word}' için karar veriyor...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
yield log_messages, None
|
| 144 |
+
|
| 145 |
+
new_label, reason = refine_label_with_llm(word, wiki_text, target_labels)
|
| 146 |
+
res_obj.update({
|
| 147 |
+
"final_label": new_label,
|
| 148 |
+
"source": "RAG+LLM",
|
| 149 |
+
"reasoning": reason
|
| 150 |
+
})
|
| 151 |
+
log_messages.append(f"✅ Sonuç: {new_label}")
|
| 152 |
else:
|
| 153 |
+
log_messages.append(f"⚠️ '{word}' için Wikipedia'da bilgi bulunamadı.")
|
| 154 |
+
else:
|
| 155 |
+
log_messages.append(f"➡️ '{word}' zaten {label} olarak belirlendi.")
|
| 156 |
+
|
| 157 |
+
final_results.append(res_obj)
|
| 158 |
+
yield log_messages, None
|
| 159 |
|
| 160 |
+
log_messages.append("✨ Tüm işlemler başarıyla tamamlandı.")
|
|
|
|
|
|
|
| 161 |
yield log_messages, final_results
|
| 162 |
|
| 163 |
+
# --- 6. GRADIO ARAYÜZÜ ---
|
| 164 |
+
|
| 165 |
custom_label_definitions = {
|
| 166 |
"PER": "Kişi adları.", "ORG": "Kurumlar.", "LOC": "Yerler.",
|
| 167 |
"DATE": "Tarihler.", "NORP": "Milliyetler/Gruplar.", "BOOK": "Kitaplar.",
|
| 168 |
"LANGUAGE": "Diller.", "TITLE": "Unvanlar.", "PRODUCT": "Ürünler.",
|
| 169 |
+
"SOFTWARE": "Yazılımlar.", "MISC": "Diğer her şey."
|
| 170 |
}
|
| 171 |
|
|
|
|
| 172 |
def process_ner_request(text, progress=gr.Progress()):
|
| 173 |
+
for logs, results in advanced_ner_pipeline(text, custom_label_definitions, progress):
|
| 174 |
+
# Logları HTML formatına getir
|
| 175 |
+
log_html = "<div style='height:200px; overflow-y:auto; background:#f0f0f0; padding:10px; font-family:monospace;'>"
|
| 176 |
+
for m in logs:
|
| 177 |
+
log_html += f"<p style='margin:0; border-bottom:1px solid #ddd;'>{m}</p>"
|
| 178 |
+
log_html += "</div>"
|
| 179 |
+
|
| 180 |
+
# Sonuçları Tablo formatına getir
|
| 181 |
+
table_html = "<table style='width:100%; border-collapse:collapse;'><thead><tr style='background:#3b82f6; color:white;'>"
|
| 182 |
+
table_html += "<th>Varlık</th><th>İlk Etiket</th><th>Nihai Etiket</th><th>Kaynak</th></tr></thead><tbody>"
|
| 183 |
+
|
| 184 |
+
if results:
|
| 185 |
+
for r in results:
|
| 186 |
+
table_html += f"<tr><td>{r['entity']}</td><td>{r['initial_label']}</td><td><b>{r['final_label']}</b></td><td>{r['source']}</td></tr>"
|
| 187 |
+
table_html += "</tbody></table>"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
|
| 189 |
+
yield log_html, table_html
|
| 190 |
|
|
|
|
| 191 |
iface = gr.Interface(
|
| 192 |
fn=process_ner_request,
|
| 193 |
+
inputs=gr.Textbox(lines=4, label="Analiz Edilecek Metin"),
|
| 194 |
+
outputs=[gr.HTML(label="Sistem Günlüğü"), gr.HTML(label="NER Sonuç Tablosu")],
|
| 195 |
+
title="Hibrit NER & RAG Karar Mekanizması",
|
| 196 |
+
description="XLM-Roberta (CPU) ile temel NER ve Qwen 2.5 (ZeroGPU) ile akıllı etiket rafine etme."
|
| 197 |
)
|
| 198 |
|
| 199 |
if __name__ == "__main__":
|
| 200 |
port = int(os.environ.get('PORT', 7860))
|
|
|
|
| 201 |
iface.launch(server_name="0.0.0.0", server_port=port)
|