Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -19,9 +19,20 @@ ner_pipe = pipeline("ner", model="xlm-roberta-large-finetuned-conll03-english",
|
|
| 19 |
model_id = "Qwen/Qwen2.5-1.5B-Instruct"
|
| 20 |
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
try:
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
IS_LLM_ENABLED = True
|
|
|
|
| 25 |
except Exception as e:
|
| 26 |
IS_LLM_ENABLED = False
|
| 27 |
print(f"⚠️ LLM yüklenemedi: {e}")
|
|
@@ -48,9 +59,8 @@ def test_wikipedia_connection():
|
|
| 48 |
logs.append(f"❌ İnternet bağlantısı yok: {e}")
|
| 49 |
return "\n".join(logs)
|
| 50 |
|
| 51 |
-
# 3. Türkçe Wikipedia'ya erişim
|
| 52 |
try:
|
| 53 |
-
# Özel session ile dene
|
| 54 |
session = requests.Session()
|
| 55 |
session.verify = False
|
| 56 |
session.headers.update({
|
|
@@ -78,39 +88,6 @@ def test_wikipedia_connection():
|
|
| 78 |
except Exception as e:
|
| 79 |
logs.append(f"❌ Türkçe Wikipedia hatası: {str(e)}")
|
| 80 |
|
| 81 |
-
# 4. Doğrudan API testi (JSON hatasını tespit için)
|
| 82 |
-
try:
|
| 83 |
-
logs.append(f"\n📡 Doğrudan API testi:")
|
| 84 |
-
url = "https://tr.wikipedia.org/w/api.php"
|
| 85 |
-
params = {
|
| 86 |
-
"action": "query",
|
| 87 |
-
"format": "json",
|
| 88 |
-
"list": "search",
|
| 89 |
-
"srsearch": "Türkiye",
|
| 90 |
-
"srlimit": 1
|
| 91 |
-
}
|
| 92 |
-
|
| 93 |
-
response = requests.get(url, params=params, timeout=10, verify=False,
|
| 94 |
-
headers={'User-Agent': 'RAG-NER-System/1.0'})
|
| 95 |
-
|
| 96 |
-
logs.append(f"API Status: {response.status_code}")
|
| 97 |
-
|
| 98 |
-
if response.status_code == 200:
|
| 99 |
-
try:
|
| 100 |
-
data = response.json()
|
| 101 |
-
if data.get('query', {}).get('search'):
|
| 102 |
-
logs.append(f"✅ API çalışıyor: {len(data['query']['search'])} sonuç")
|
| 103 |
-
else:
|
| 104 |
-
logs.append(f"⚠️ API sonuç döndü ama boş")
|
| 105 |
-
except json.JSONDecodeError as e:
|
| 106 |
-
logs.append(f"❌ JSON parse hatası: {e}")
|
| 107 |
-
logs.append(f" İlk 100 karakter: {response.text[:100]}")
|
| 108 |
-
else:
|
| 109 |
-
logs.append(f"❌ API hatası: {response.status_code}")
|
| 110 |
-
|
| 111 |
-
except Exception as e:
|
| 112 |
-
logs.append(f"❌ API test hatası: {str(e)}")
|
| 113 |
-
|
| 114 |
return "\n".join(logs)
|
| 115 |
|
| 116 |
def get_wiki_summary(term):
|
|
@@ -136,13 +113,12 @@ def get_wiki_summary(term):
|
|
| 136 |
wikipedia.set_lang("tr")
|
| 137 |
print(f"🌐 Dil: Türkçe")
|
| 138 |
|
| 139 |
-
# 1. YÖNTEM: Doğrudan sayfa kontrolü
|
| 140 |
try:
|
| 141 |
print(f"📖 Doğrudan sayfa aranıyor: '{term}'")
|
| 142 |
page = wikipedia.page(term, auto_suggest=False)
|
| 143 |
if page:
|
| 144 |
summary = page.summary
|
| 145 |
-
# İlk 3 cümle
|
| 146 |
sentences = summary.split('.')[:3]
|
| 147 |
result = '.'.join(sentences) + '.'
|
| 148 |
if len(result) > 20:
|
|
@@ -150,7 +126,6 @@ def get_wiki_summary(term):
|
|
| 150 |
return result
|
| 151 |
except wikipedia.exceptions.DisambiguationError as e:
|
| 152 |
print(f"⚠️ Anlam karmaşası: {e.options[:3]}")
|
| 153 |
-
# İlk seçeneği dene
|
| 154 |
for option in e.options[:3]:
|
| 155 |
try:
|
| 156 |
page = wikipedia.page(option, auto_suggest=False)
|
|
@@ -185,12 +160,11 @@ def get_wiki_summary(term):
|
|
| 185 |
print(f"⚠️ '{title}' alınamadı: {str(e)[:50]}")
|
| 186 |
continue
|
| 187 |
|
| 188 |
-
# 3. YÖNTEM: Doğrudan API ile dene
|
| 189 |
print(f"📡 API ile deneniyor...")
|
| 190 |
try:
|
| 191 |
url = "https://tr.wikipedia.org/w/api.php"
|
| 192 |
|
| 193 |
-
# Önce ara
|
| 194 |
search_params = {
|
| 195 |
"action": "query",
|
| 196 |
"format": "json",
|
|
@@ -210,7 +184,6 @@ def get_wiki_summary(term):
|
|
| 210 |
page_title = search_data['query']['search'][0]['title']
|
| 211 |
print(f"📄 API ile bulundu: '{page_title}'")
|
| 212 |
|
| 213 |
-
# Özet al
|
| 214 |
summary_params = {
|
| 215 |
"action": "query",
|
| 216 |
"format": "json",
|
|
@@ -266,19 +239,30 @@ def get_random_examples():
|
|
| 266 |
|
| 267 |
@spaces.GPU
|
| 268 |
def refine_label_with_llm(entity_text, full_sentence, wiki_context, custom_label_definitions):
|
| 269 |
-
|
|
|
|
|
|
|
|
|
|
| 270 |
return "MISC", "LLM Aktif Değil"
|
| 271 |
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 282 |
Görevin, '[[{entity_text}]]' varlığını aşağıdaki 4 adımlı Sistematik CoT protokolüne göre sınıflandırmaktır.
|
| 283 |
|
| 284 |
ETİKET TANIMLARI:
|
|
@@ -326,15 +310,24 @@ GÜNCEL GÖREV:
|
|
| 326 |
Analiz: [4 Adımlı CoT Analizi]
|
| 327 |
Cevap: [SADECE_ETIKET_ADI]"""
|
| 328 |
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
|
| 333 |
-
|
| 334 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 335 |
response_ids = [output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)]
|
| 336 |
full_output = tokenizer.batch_decode(response_ids, skip_special_tokens=True)[0].strip()
|
| 337 |
|
|
|
|
|
|
|
| 338 |
# Markdown temizliği ve Etiket Ayıklama
|
| 339 |
clean_output = full_output.replace("*", "")
|
| 340 |
final_label = "MISC"
|
|
@@ -345,10 +338,28 @@ Cevap: [SADECE_ETIKET_ADI]"""
|
|
| 345 |
extracted = match.group(1).upper().strip()
|
| 346 |
if extracted in valid_keys:
|
| 347 |
final_label = extracted
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 348 |
|
| 349 |
return final_label, clean_output
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 350 |
except Exception as e:
|
| 351 |
-
|
|
|
|
|
|
|
| 352 |
|
| 353 |
# --- 4. ANA İŞLEM HATTI ---
|
| 354 |
|
|
@@ -414,18 +425,32 @@ def process_ner(text):
|
|
| 414 |
|
| 415 |
yield "<br>".join(current_logs), [[r["Varlık"], r["İlk Etiket"], r["Nihai Etiket"], r["Kaynak"]] for r in final_results]
|
| 416 |
|
| 417 |
-
# LLM ile analiz
|
| 418 |
-
if wiki_text:
|
| 419 |
try:
|
|
|
|
|
|
|
|
|
|
| 420 |
new_label, cot_text = refine_label_with_llm(word, text, wiki_text, custom_labels)
|
| 421 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 422 |
res = {"Varlık": word, "İlk Etiket": label, "Nihai Etiket": new_label, "Kaynak": "RAG+LLM"}
|
|
|
|
|
|
|
| 423 |
except Exception as e:
|
| 424 |
-
|
| 425 |
-
|
|
|
|
| 426 |
else:
|
| 427 |
-
|
| 428 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 429 |
|
| 430 |
final_results.append(res)
|
| 431 |
table_display = [[r["Varlık"], r["İlk Etiket"], f"<b>{r['Nihai Etiket']}</b>", r["Kaynak"]] for r in final_results]
|
|
@@ -459,7 +484,6 @@ def test_single_term(term):
|
|
| 459 |
import wikipedia
|
| 460 |
logs.append(f"\n📊 Detaylı test:")
|
| 461 |
try:
|
| 462 |
-
# Özel session ile dene
|
| 463 |
session = requests.Session()
|
| 464 |
session.verify = False
|
| 465 |
session.headers.update({
|
|
@@ -481,6 +505,29 @@ def test_single_term(term):
|
|
| 481 |
|
| 482 |
return "\n".join(logs)
|
| 483 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 484 |
# --- 6. GRADIO ARAYÜZÜ ---
|
| 485 |
|
| 486 |
with gr.Blocks(title="RAG-NER Uzman Karar Destek Sistemi") as demo:
|
|
@@ -522,16 +569,16 @@ with gr.Blocks(title="RAG-NER Uzman Karar Destek Sistemi") as demo:
|
|
| 522 |
|
| 523 |
# --- 7. DEBUG TABI ---
|
| 524 |
with gr.Tab("Debug"):
|
| 525 |
-
gr.Markdown("## 🐛
|
| 526 |
-
gr.Markdown("Bu panel Türkçe Wikipedia bağlantı sorunlarını tespit etmek için kullanılır.")
|
| 527 |
|
|
|
|
| 528 |
with gr.Row():
|
| 529 |
debug_btn = gr.Button("Türkçe Wikipedia Bağlantısını Test Et", variant="secondary")
|
| 530 |
debug_output = gr.HTML(label="Debug Sonuçları")
|
| 531 |
|
| 532 |
debug_btn.click(debug_wikipedia, outputs=debug_output)
|
| 533 |
|
| 534 |
-
gr.Markdown("### 🔍 Tek Terim Testi
|
| 535 |
with gr.Row():
|
| 536 |
single_term_input = gr.Textbox(
|
| 537 |
label="Test Edilecek Terim",
|
|
@@ -547,6 +594,17 @@ with gr.Blocks(title="RAG-NER Uzman Karar Destek Sistemi") as demo:
|
|
| 547 |
)
|
| 548 |
|
| 549 |
single_term_btn.click(test_single_term, inputs=single_term_input, outputs=single_term_output)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 550 |
|
| 551 |
# --- 8. BAŞLATMA ---
|
| 552 |
|
|
@@ -560,6 +618,9 @@ if __name__ == "__main__":
|
|
| 560 |
test_result = test_wikipedia_connection()
|
| 561 |
print(test_result)
|
| 562 |
|
|
|
|
|
|
|
|
|
|
| 563 |
print("\n" + "="*50)
|
| 564 |
print("✅ Sistem hazır, Gradio başlatılıyor...")
|
| 565 |
print("="*50 + "\n")
|
|
|
|
| 19 |
model_id = "Qwen/Qwen2.5-1.5B-Instruct"
|
| 20 |
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 21 |
|
| 22 |
+
# LLM modelini global olarak yükle
|
| 23 |
+
llm_model = None
|
| 24 |
+
IS_LLM_ENABLED = False
|
| 25 |
+
|
| 26 |
try:
|
| 27 |
+
print("📦 LLM modeli yükleniyor...")
|
| 28 |
+
llm_model = AutoModelForCausalLM.from_pretrained(
|
| 29 |
+
model_id,
|
| 30 |
+
torch_dtype=torch.bfloat16,
|
| 31 |
+
device_map="cpu", # CPU'da çalıştır (Space'lerde genelde CPU var)
|
| 32 |
+
trust_remote_code=True
|
| 33 |
+
)
|
| 34 |
IS_LLM_ENABLED = True
|
| 35 |
+
print("✅ LLM modeli yüklendi!")
|
| 36 |
except Exception as e:
|
| 37 |
IS_LLM_ENABLED = False
|
| 38 |
print(f"⚠️ LLM yüklenemedi: {e}")
|
|
|
|
| 59 |
logs.append(f"❌ İnternet bağlantısı yok: {e}")
|
| 60 |
return "\n".join(logs)
|
| 61 |
|
| 62 |
+
# 3. Türkçe Wikipedia'ya erişim
|
| 63 |
try:
|
|
|
|
| 64 |
session = requests.Session()
|
| 65 |
session.verify = False
|
| 66 |
session.headers.update({
|
|
|
|
| 88 |
except Exception as e:
|
| 89 |
logs.append(f"❌ Türkçe Wikipedia hatası: {str(e)}")
|
| 90 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
return "\n".join(logs)
|
| 92 |
|
| 93 |
def get_wiki_summary(term):
|
|
|
|
| 113 |
wikipedia.set_lang("tr")
|
| 114 |
print(f"🌐 Dil: Türkçe")
|
| 115 |
|
| 116 |
+
# 1. YÖNTEM: Doğrudan sayfa kontrolü
|
| 117 |
try:
|
| 118 |
print(f"📖 Doğrudan sayfa aranıyor: '{term}'")
|
| 119 |
page = wikipedia.page(term, auto_suggest=False)
|
| 120 |
if page:
|
| 121 |
summary = page.summary
|
|
|
|
| 122 |
sentences = summary.split('.')[:3]
|
| 123 |
result = '.'.join(sentences) + '.'
|
| 124 |
if len(result) > 20:
|
|
|
|
| 126 |
return result
|
| 127 |
except wikipedia.exceptions.DisambiguationError as e:
|
| 128 |
print(f"⚠️ Anlam karmaşası: {e.options[:3]}")
|
|
|
|
| 129 |
for option in e.options[:3]:
|
| 130 |
try:
|
| 131 |
page = wikipedia.page(option, auto_suggest=False)
|
|
|
|
| 160 |
print(f"⚠️ '{title}' alınamadı: {str(e)[:50]}")
|
| 161 |
continue
|
| 162 |
|
| 163 |
+
# 3. YÖNTEM: Doğrudan API ile dene
|
| 164 |
print(f"📡 API ile deneniyor...")
|
| 165 |
try:
|
| 166 |
url = "https://tr.wikipedia.org/w/api.php"
|
| 167 |
|
|
|
|
| 168 |
search_params = {
|
| 169 |
"action": "query",
|
| 170 |
"format": "json",
|
|
|
|
| 184 |
page_title = search_data['query']['search'][0]['title']
|
| 185 |
print(f"📄 API ile bulundu: '{page_title}'")
|
| 186 |
|
|
|
|
| 187 |
summary_params = {
|
| 188 |
"action": "query",
|
| 189 |
"format": "json",
|
|
|
|
| 239 |
|
| 240 |
@spaces.GPU
|
| 241 |
def refine_label_with_llm(entity_text, full_sentence, wiki_context, custom_label_definitions):
|
| 242 |
+
"""LLM ile etiket analizi yapar - RuntimeError çözümlü"""
|
| 243 |
+
global llm_model, IS_LLM_ENABLED
|
| 244 |
+
|
| 245 |
+
if not IS_LLM_ENABLED or llm_model is None:
|
| 246 |
return "MISC", "LLM Aktif Değil"
|
| 247 |
|
| 248 |
+
try:
|
| 249 |
+
# Device kontrolü - model zaten CPU'da
|
| 250 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 251 |
+
print(f"🖥️ LLM Device: {device}")
|
| 252 |
+
|
| 253 |
+
# Modeli device'a taşı (sadece gerekirse)
|
| 254 |
+
if device == "cuda" and next(llm_model.parameters()).device.type != "cuda":
|
| 255 |
+
llm_model.to(device)
|
| 256 |
+
elif device == "cpu" and next(llm_model.parameters()).device.type != "cpu":
|
| 257 |
+
llm_model.to(device)
|
| 258 |
+
|
| 259 |
+
# 1. Etiket Tanımları
|
| 260 |
+
label_rules = ""
|
| 261 |
+
for k, v in custom_label_definitions.items():
|
| 262 |
+
label_rules += f"### {k}\n- TANIM: {v['tanim']}\n- ANAHTARLAR: {', '.join(v['anahtar_kelimeler'])}\n\n"
|
| 263 |
+
|
| 264 |
+
# 2. Sistematik CoT ve Kuralların Tanımlanması
|
| 265 |
+
prompt = f"""Sen yüksek hassasiyetli bir semantik analiz uzmanısın.
|
| 266 |
Görevin, '[[{entity_text}]]' varlığını aşağıdaki 4 adımlı Sistematik CoT protokolüne göre sınıflandırmaktır.
|
| 267 |
|
| 268 |
ETİKET TANIMLARI:
|
|
|
|
| 310 |
Analiz: [4 Adımlı CoT Analizi]
|
| 311 |
Cevap: [SADECE_ETIKET_ADI]"""
|
| 312 |
|
| 313 |
+
messages = [{"role": "user", "content": prompt}]
|
| 314 |
+
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 315 |
+
model_inputs = tokenizer([text], return_tensors="pt").to(device)
|
| 316 |
|
| 317 |
+
print(f"🧠 LLM analizi başlatılıyor: '{entity_text}'")
|
| 318 |
+
|
| 319 |
+
generated_ids = llm_model.generate(
|
| 320 |
+
model_inputs.input_ids,
|
| 321 |
+
max_new_tokens=450,
|
| 322 |
+
do_sample=False,
|
| 323 |
+
temperature=0.1
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
response_ids = [output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)]
|
| 327 |
full_output = tokenizer.batch_decode(response_ids, skip_special_tokens=True)[0].strip()
|
| 328 |
|
| 329 |
+
print(f"✅ LLM çıktısı alındı: {full_output[:100]}...")
|
| 330 |
+
|
| 331 |
# Markdown temizliği ve Etiket Ayıklama
|
| 332 |
clean_output = full_output.replace("*", "")
|
| 333 |
final_label = "MISC"
|
|
|
|
| 338 |
extracted = match.group(1).upper().strip()
|
| 339 |
if extracted in valid_keys:
|
| 340 |
final_label = extracted
|
| 341 |
+
print(f"🏷️ Etiket bulundu: {final_label}")
|
| 342 |
+
else:
|
| 343 |
+
print(f"⚠️ Geçersiz etiket: {extracted}")
|
| 344 |
+
else:
|
| 345 |
+
print(f"⚠️ Etiket bulunamadı, MISC atanıyor")
|
| 346 |
|
| 347 |
return final_label, clean_output
|
| 348 |
+
|
| 349 |
+
except RuntimeError as e:
|
| 350 |
+
print(f"❌ RuntimeError: {str(e)}")
|
| 351 |
+
# Modeli yeniden CPU'ya taşı
|
| 352 |
+
try:
|
| 353 |
+
llm_model.to("cpu")
|
| 354 |
+
torch.cuda.empty_cache() if torch.cuda.is_available() else None
|
| 355 |
+
except:
|
| 356 |
+
pass
|
| 357 |
+
return "MISC", f"RuntimeError: {str(e)[:100]}"
|
| 358 |
+
|
| 359 |
except Exception as e:
|
| 360 |
+
print(f"❌ LLM hatası: {type(e).__name__} - {str(e)}")
|
| 361 |
+
print(traceback.format_exc())
|
| 362 |
+
return "MISC", f"Hata: {str(e)[:100]}"
|
| 363 |
|
| 364 |
# --- 4. ANA İŞLEM HATTI ---
|
| 365 |
|
|
|
|
| 425 |
|
| 426 |
yield "<br>".join(current_logs), [[r["Varlık"], r["İlk Etiket"], r["Nihai Etiket"], r["Kaynak"]] for r in final_results]
|
| 427 |
|
| 428 |
+
# LLM ile analiz (sadece wiki_text varsa)
|
| 429 |
+
if wiki_text and IS_LLM_ENABLED:
|
| 430 |
try:
|
| 431 |
+
current_logs.append(f"🧠 <b>LLM analizi başlatılıyor:</b> '{word}'")
|
| 432 |
+
yield "<br>".join(current_logs), [[r["Varlık"], r["İlk Etiket"], r["Nihai Etiket"], r["Kaynak"]] for r in final_results]
|
| 433 |
+
|
| 434 |
new_label, cot_text = refine_label_with_llm(word, text, wiki_text, custom_labels)
|
| 435 |
+
|
| 436 |
+
# CoT çıktısını kısalt
|
| 437 |
+
cot_preview = cot_text[:300] + "..." if len(cot_text) > 300 else cot_text
|
| 438 |
+
current_logs.append(f"🧠 <b>CoT Analizi:</b> {cot_preview}")
|
| 439 |
+
|
| 440 |
res = {"Varlık": word, "İlk Etiket": label, "Nihai Etiket": new_label, "Kaynak": "RAG+LLM"}
|
| 441 |
+
current_logs.append(f"🏷️ <b>Nihai Etiket:</b> {new_label}")
|
| 442 |
+
|
| 443 |
except Exception as e:
|
| 444 |
+
error_msg = str(e)[:100]
|
| 445 |
+
current_logs.append(f"❌ <b>LLM analiz hatası:</b> {error_msg}")
|
| 446 |
+
res = {"Varlık": word, "İlk Etiket": label, "Nihai Etiket": "MISC", "Kaynak": f"Hata: {error_msg}"}
|
| 447 |
else:
|
| 448 |
+
if not wiki_text:
|
| 449 |
+
res = {"Varlık": word, "İlk Etiket": label, "Nihai Etiket": "MISC", "Kaynak": "Model"}
|
| 450 |
+
current_logs.append(f"⚠️ '{word}' için Wikipedia bilgisi olmadığından MISC olarak etiketlendi.")
|
| 451 |
+
else:
|
| 452 |
+
res = {"Varlık": word, "İlk Etiket": label, "Nihai Etiket": "MISC", "Kaynak": "Model"}
|
| 453 |
+
current_logs.append(f"⚠️ LLM aktif olmadığından '{word}' MISC olarak etiketlendi.")
|
| 454 |
|
| 455 |
final_results.append(res)
|
| 456 |
table_display = [[r["Varlık"], r["İlk Etiket"], f"<b>{r['Nihai Etiket']}</b>", r["Kaynak"]] for r in final_results]
|
|
|
|
| 484 |
import wikipedia
|
| 485 |
logs.append(f"\n📊 Detaylı test:")
|
| 486 |
try:
|
|
|
|
| 487 |
session = requests.Session()
|
| 488 |
session.verify = False
|
| 489 |
session.headers.update({
|
|
|
|
| 505 |
|
| 506 |
return "\n".join(logs)
|
| 507 |
|
| 508 |
+
def check_llm_status():
|
| 509 |
+
"""LLM durumunu kontrol et"""
|
| 510 |
+
global IS_LLM_ENABLED, llm_model
|
| 511 |
+
|
| 512 |
+
logs = []
|
| 513 |
+
logs.append("=== LLM DURUM KONTROLÜ ===")
|
| 514 |
+
logs.append(f"LLM Aktif: {IS_LLM_ENABLED}")
|
| 515 |
+
logs.append(f"LLM Model: {model_id}")
|
| 516 |
+
|
| 517 |
+
if llm_model is not None:
|
| 518 |
+
try:
|
| 519 |
+
device = next(llm_model.parameters()).device
|
| 520 |
+
logs.append(f"Model Device: {device}")
|
| 521 |
+
logs.append(f"CUDA Kullanılabilir: {torch.cuda.is_available()}")
|
| 522 |
+
if torch.cuda.is_available():
|
| 523 |
+
logs.append(f"GPU: {torch.cuda.get_device_name(0)}")
|
| 524 |
+
except Exception as e:
|
| 525 |
+
logs.append(f"Device kontrol hatası: {str(e)}")
|
| 526 |
+
else:
|
| 527 |
+
logs.append("Model yüklenmemiş!")
|
| 528 |
+
|
| 529 |
+
return "\n".join(logs)
|
| 530 |
+
|
| 531 |
# --- 6. GRADIO ARAYÜZÜ ---
|
| 532 |
|
| 533 |
with gr.Blocks(title="RAG-NER Uzman Karar Destek Sistemi") as demo:
|
|
|
|
| 569 |
|
| 570 |
# --- 7. DEBUG TABI ---
|
| 571 |
with gr.Tab("Debug"):
|
| 572 |
+
gr.Markdown("## 🐛 Debug Paneli")
|
|
|
|
| 573 |
|
| 574 |
+
gr.Markdown("### 🌐 Türkçe Wikipedia Testi")
|
| 575 |
with gr.Row():
|
| 576 |
debug_btn = gr.Button("Türkçe Wikipedia Bağlantısını Test Et", variant="secondary")
|
| 577 |
debug_output = gr.HTML(label="Debug Sonuçları")
|
| 578 |
|
| 579 |
debug_btn.click(debug_wikipedia, outputs=debug_output)
|
| 580 |
|
| 581 |
+
gr.Markdown("### 🔍 Tek Terim Testi")
|
| 582 |
with gr.Row():
|
| 583 |
single_term_input = gr.Textbox(
|
| 584 |
label="Test Edilecek Terim",
|
|
|
|
| 594 |
)
|
| 595 |
|
| 596 |
single_term_btn.click(test_single_term, inputs=single_term_input, outputs=single_term_output)
|
| 597 |
+
|
| 598 |
+
gr.Markdown("### 🧠 LLM Durum Kontrolü")
|
| 599 |
+
with gr.Row():
|
| 600 |
+
llm_status_btn = gr.Button("LLM Durumunu Kontrol Et", variant="secondary")
|
| 601 |
+
llm_status_output = gr.Textbox(
|
| 602 |
+
label="LLM Durumu",
|
| 603 |
+
lines=10,
|
| 604 |
+
interactive=False
|
| 605 |
+
)
|
| 606 |
+
|
| 607 |
+
llm_status_btn.click(check_llm_status, outputs=llm_status_output)
|
| 608 |
|
| 609 |
# --- 8. BAŞLATMA ---
|
| 610 |
|
|
|
|
| 618 |
test_result = test_wikipedia_connection()
|
| 619 |
print(test_result)
|
| 620 |
|
| 621 |
+
print("\n🧠 LLM durumu kontrol ediliyor...")
|
| 622 |
+
print(check_llm_status())
|
| 623 |
+
|
| 624 |
print("\n" + "="*50)
|
| 625 |
print("✅ Sistem hazır, Gradio başlatılıyor...")
|
| 626 |
print("="*50 + "\n")
|