Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,4 @@
|
|
| 1 |
import torch
|
| 2 |
-
import wikipedia
|
| 3 |
import spaces
|
| 4 |
import os
|
| 5 |
import re
|
|
@@ -10,7 +9,7 @@ import json
|
|
| 10 |
import traceback
|
| 11 |
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
| 12 |
|
| 13 |
-
# --- SSL ve Network Ayarları
|
| 14 |
import urllib3
|
| 15 |
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
| 16 |
|
|
@@ -19,7 +18,7 @@ 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 |
-
# LLM modelini
|
| 23 |
llm_model = None
|
| 24 |
IS_LLM_ENABLED = False
|
| 25 |
|
|
@@ -35,195 +34,217 @@ try:
|
|
| 35 |
llm_model = llm_model.to("cpu")
|
| 36 |
llm_model.eval()
|
| 37 |
IS_LLM_ENABLED = True
|
| 38 |
-
print(f"✅ LLM modeli yüklendi!
|
| 39 |
except Exception as e:
|
| 40 |
IS_LLM_ENABLED = False
|
| 41 |
print(f"⚠️ LLM yüklenemedi: {e}")
|
| 42 |
|
| 43 |
-
# --- 2. WIKIPEDIA
|
| 44 |
|
| 45 |
-
def
|
| 46 |
-
"""Wikipedia
|
| 47 |
-
logs = []
|
| 48 |
-
|
| 49 |
-
try:
|
| 50 |
-
import wikipedia
|
| 51 |
-
logs.append(f"✅ Wikipedia modülü yüklü: {wikipedia.__version__}")
|
| 52 |
-
except ImportError as e:
|
| 53 |
-
logs.append(f"❌ Wikipedia modülü yüklü değil: {e}")
|
| 54 |
-
return "\n".join(logs)
|
| 55 |
-
|
| 56 |
-
try:
|
| 57 |
-
response = requests.get("https://tr.wikipedia.org", timeout=5, verify=False)
|
| 58 |
-
logs.append(f"✅ İnternet bağlantısı var: {response.status_code}")
|
| 59 |
-
except Exception as e:
|
| 60 |
-
logs.append(f"❌ İnternet bağlantısı yok: {e}")
|
| 61 |
-
return "\n".join(logs)
|
| 62 |
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
session.verify = False
|
| 66 |
-
session.headers.update({
|
| 67 |
-
'User-Agent': 'Mozilla/5.0 (compatible; RAG-NER-System/1.0)'
|
| 68 |
-
})
|
| 69 |
-
wikipedia.wikipedia._session = session
|
| 70 |
-
|
| 71 |
-
wikipedia.set_lang("tr")
|
| 72 |
-
test_terms = ["Türkiye", "İstanbul", "Mustafa Kemal Atatürk"]
|
| 73 |
-
|
| 74 |
-
for term in test_terms:
|
| 75 |
-
try:
|
| 76 |
-
search_results = wikipedia.search(term)
|
| 77 |
-
if search_results:
|
| 78 |
-
summary = wikipedia.summary(search_results[0], sentences=1, auto_suggest=False)
|
| 79 |
-
logs.append(f"✅ '{term}' -> '{search_results[0]}' (başarılı)")
|
| 80 |
-
else:
|
| 81 |
-
logs.append(f"❌ '{term}' -> sonuç yok")
|
| 82 |
-
time.sleep(0.3)
|
| 83 |
-
except Exception as e:
|
| 84 |
-
logs.append(f"❌ '{term}' -> hata: {str(e)[:50]}")
|
| 85 |
-
|
| 86 |
-
except Exception as e:
|
| 87 |
-
logs.append(f"❌ Wikipedia hatası: {str(e)}")
|
| 88 |
|
| 89 |
-
return "\n".join(logs)
|
| 90 |
-
|
| 91 |
-
def improve_search_term(term):
|
| 92 |
-
"""Arama terimini iyileştir - Daha fazla eşleşme için"""
|
| 93 |
# Özel terim dönüşümleri
|
| 94 |
special_cases = {
|
| 95 |
"Türk": "Türkler",
|
| 96 |
-
"
|
| 97 |
"Altın Aslan": "Altın Aslan Ödülü",
|
| 98 |
"Venedik Film Festivali": "Venedik Film Festivali",
|
| 99 |
"Kış Uykusu": "Kış Uykusu (film)",
|
| 100 |
"Inception": "Inception (film)",
|
| 101 |
"Oscar": "Akademi Ödülü",
|
| 102 |
"Nobel": "Nobel Ödülü",
|
| 103 |
-
"Altın Palmiye": "Altın Palmiye",
|
| 104 |
-
"Cannes": "Cannes Film Festivali",
|
| 105 |
-
"Berlin": "Berlin Film Festivali",
|
| 106 |
}
|
| 107 |
|
| 108 |
-
#
|
|
|
|
| 109 |
for key, value in special_cases.items():
|
| 110 |
if term.lower() == key.lower():
|
| 111 |
-
|
|
|
|
| 112 |
|
| 113 |
-
#
|
| 114 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
|
| 116 |
-
|
| 117 |
-
improved.append(term.title())
|
| 118 |
|
| 119 |
-
#
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
|
| 126 |
-
|
| 127 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
-
|
|
|
|
|
|
|
| 130 |
|
| 131 |
-
def
|
| 132 |
-
"""
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
print(f"\n{'='*50}")
|
| 136 |
-
print(f"🔍 Türkçe Wikipedia sorgusu: '{term}'")
|
| 137 |
|
| 138 |
try:
|
| 139 |
-
#
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
print(f"📝 Aranacak terimler: {search_terms}")
|
| 151 |
|
| 152 |
-
|
| 153 |
-
print(f"🔎 '{search_term}' aranıyor...")
|
| 154 |
-
|
| 155 |
try:
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
if
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
if search_results:
|
| 173 |
-
print(f"📊 '{search_term}' -> {len(search_results)} sonuç: {search_results[:3]}")
|
| 174 |
-
|
| 175 |
-
for title in search_results:
|
| 176 |
-
try:
|
| 177 |
-
page = wikipedia.page(title, auto_suggest=False)
|
| 178 |
-
summary = page.summary
|
| 179 |
-
sentences = summary.split('.')[:3]
|
| 180 |
-
result = '.'.join(sentences) + '.'
|
| 181 |
-
if len(result) > 20:
|
| 182 |
-
print(f"✅ '{search_term}' -> '{title}' bulundu")
|
| 183 |
-
print(f" {result[:100]}...")
|
| 184 |
-
return result
|
| 185 |
-
except:
|
| 186 |
-
continue
|
| 187 |
-
|
| 188 |
-
except Exception as e:
|
| 189 |
-
print(f"⚠️ '{search_term}' hatası: {str(e)[:50]}")
|
| 190 |
-
continue
|
| 191 |
|
| 192 |
-
time.sleep(0.3) # Rate limiting
|
| 193 |
-
|
| 194 |
-
# Hiçbir sonuç yoksa
|
| 195 |
-
print(f"❌ '{term}' için Türkçe Wikipedia'da sonuç bulunamadı")
|
| 196 |
-
return None
|
| 197 |
-
|
| 198 |
except Exception as e:
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
print(f"{'='*50}\n")
|
| 203 |
|
| 204 |
-
# --- 3. LLM ANALİZ FONKSİYONU
|
| 205 |
|
| 206 |
@spaces.GPU
|
| 207 |
def refine_label_with_llm(entity_text, full_sentence, wiki_context, custom_label_definitions):
|
| 208 |
-
"""LLM ile etiket analizi yapar
|
| 209 |
global llm_model, IS_LLM_ENABLED
|
| 210 |
|
| 211 |
if not IS_LLM_ENABLED or llm_model is None:
|
| 212 |
return "MISC", "LLM Aktif Değil"
|
| 213 |
|
| 214 |
try:
|
| 215 |
-
print(f"\n
|
| 216 |
-
print(f"🧠 LLM analizi: '{entity_text}'")
|
| 217 |
-
|
| 218 |
-
# Model CPU'da çalışıyor, emin olalım
|
| 219 |
-
try:
|
| 220 |
-
current_device = next(llm_model.parameters()).device
|
| 221 |
-
if str(current_device) != "cpu":
|
| 222 |
-
llm_model.to("cpu")
|
| 223 |
-
if torch.cuda.is_available():
|
| 224 |
-
torch.cuda.empty_cache()
|
| 225 |
-
except:
|
| 226 |
-
pass
|
| 227 |
|
| 228 |
# Etiket Tanımları
|
| 229 |
label_rules = ""
|
|
@@ -283,12 +304,8 @@ Cevap: [SADECE_ETIKET_ADI]"""
|
|
| 283 |
messages = [{"role": "user", "content": prompt}]
|
| 284 |
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 285 |
model_inputs = tokenizer([text], return_tensors="pt")
|
| 286 |
-
|
| 287 |
-
# CPU'ya taşı
|
| 288 |
model_inputs = {k: v.to("cpu") for k, v in model_inputs.items()}
|
| 289 |
|
| 290 |
-
print(f"🔄 LLM generate başlatılıyor...")
|
| 291 |
-
|
| 292 |
with torch.no_grad():
|
| 293 |
generated_ids = llm_model.generate(
|
| 294 |
model_inputs.input_ids,
|
|
@@ -301,8 +318,6 @@ Cevap: [SADECE_ETIKET_ADI]"""
|
|
| 301 |
response_ids = [output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)]
|
| 302 |
full_output = tokenizer.batch_decode(response_ids, skip_special_tokens=True)[0].strip()
|
| 303 |
|
| 304 |
-
print(f"✅ LLM çıktısı alındı")
|
| 305 |
-
|
| 306 |
# Etiket Ayıklama
|
| 307 |
clean_output = full_output.replace("*", "")
|
| 308 |
final_label = "MISC"
|
|
@@ -314,26 +329,11 @@ Cevap: [SADECE_ETIKET_ADI]"""
|
|
| 314 |
if extracted in valid_keys:
|
| 315 |
final_label = extracted
|
| 316 |
print(f"🏷️ Etiket: {final_label}")
|
| 317 |
-
else:
|
| 318 |
-
print(f"⚠️ Geçersiz etiket: {extracted}")
|
| 319 |
-
else:
|
| 320 |
-
print(f"⚠️ Etiket bulunamadı, MISC atanıyor")
|
| 321 |
|
| 322 |
return final_label, clean_output
|
| 323 |
|
| 324 |
-
except RuntimeError as e:
|
| 325 |
-
print(f"❌ RuntimeError: {str(e)}")
|
| 326 |
-
try:
|
| 327 |
-
llm_model.to("cpu")
|
| 328 |
-
if torch.cuda.is_available():
|
| 329 |
-
torch.cuda.empty_cache()
|
| 330 |
-
except:
|
| 331 |
-
pass
|
| 332 |
-
return "MISC", f"RuntimeError: {str(e)[:100]}"
|
| 333 |
-
|
| 334 |
except Exception as e:
|
| 335 |
-
print(f"❌ LLM hatası: {
|
| 336 |
-
print(traceback.format_exc())
|
| 337 |
return "MISC", f"Hata: {str(e)[:100]}"
|
| 338 |
|
| 339 |
# --- 4. ANA İŞLEM HATTI ---
|
|
@@ -451,40 +451,8 @@ def test_single_term(term):
|
|
| 451 |
logs.append(f"✅ SONUÇ: {result}")
|
| 452 |
else:
|
| 453 |
logs.append(f"❌ Sonuç bulunamadı")
|
| 454 |
-
|
| 455 |
-
import wikipedia
|
| 456 |
-
logs.append(f"\n📊 Detaylı arama:")
|
| 457 |
-
try:
|
| 458 |
-
session = requests.Session()
|
| 459 |
-
session.verify = False
|
| 460 |
-
session.headers.update({
|
| 461 |
-
'User-Agent': 'Mozilla/5.0 (compatible; RAG-NER-System/1.0)'
|
| 462 |
-
})
|
| 463 |
-
wikipedia.wikipedia._session = session
|
| 464 |
-
wikipedia.set_lang("tr")
|
| 465 |
-
|
| 466 |
-
test_terms = improve_search_term(term)
|
| 467 |
-
for t in test_terms:
|
| 468 |
-
try:
|
| 469 |
-
search_results = wikipedia.search(t)
|
| 470 |
-
if search_results:
|
| 471 |
-
logs.append(f" '{t}' -> {len(search_results)} sonuç: {search_results[:3]}")
|
| 472 |
-
try:
|
| 473 |
-
summary = wikipedia.summary(search_results[0], sentences=1)
|
| 474 |
-
logs.append(f" Özet: {summary[:100]}...")
|
| 475 |
-
except:
|
| 476 |
-
pass
|
| 477 |
-
else:
|
| 478 |
-
logs.append(f" '{t}' -> sonuç yok")
|
| 479 |
-
except Exception as e:
|
| 480 |
-
logs.append(f" '{t}' -> hata: {str(e)[:50]}")
|
| 481 |
-
time.sleep(0.2)
|
| 482 |
-
except Exception as e:
|
| 483 |
-
logs.append(f"Test hatası: {str(e)}")
|
| 484 |
-
|
| 485 |
except Exception as e:
|
| 486 |
logs.append(f"❌ Hata: {str(e)}")
|
| 487 |
-
logs.append(traceback.format_exc())
|
| 488 |
|
| 489 |
return "\n".join(logs)
|
| 490 |
|
|
@@ -501,7 +469,6 @@ def check_llm_status():
|
|
| 501 |
dtype = next(llm_model.parameters()).dtype
|
| 502 |
logs.append(f"Device: {device}")
|
| 503 |
logs.append(f"Dtype: {dtype}")
|
| 504 |
-
logs.append(f"CUDA Kullanılabilir: {torch.cuda.is_available()}")
|
| 505 |
except Exception as e:
|
| 506 |
logs.append(f"Device kontrol hatası: {str(e)}")
|
| 507 |
else:
|
|
@@ -557,7 +524,7 @@ with gr.Blocks(title="RAG-NER Uzman Karar Destek Sistemi") as demo:
|
|
| 557 |
debug_output = gr.HTML(label="Debug Sonuçları")
|
| 558 |
debug_btn.click(debug_wikipedia, outputs=debug_output)
|
| 559 |
|
| 560 |
-
gr.Markdown("### 🔍 Tek Terim Testi
|
| 561 |
with gr.Row():
|
| 562 |
single_term_input = gr.Textbox(
|
| 563 |
label="Test Edilecek Terim",
|
|
|
|
| 1 |
import torch
|
|
|
|
| 2 |
import spaces
|
| 3 |
import os
|
| 4 |
import re
|
|
|
|
| 9 |
import traceback
|
| 10 |
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
| 11 |
|
| 12 |
+
# --- SSL ve Network Ayarları ---
|
| 13 |
import urllib3
|
| 14 |
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
| 15 |
|
|
|
|
| 18 |
model_id = "Qwen/Qwen2.5-1.5B-Instruct"
|
| 19 |
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 20 |
|
| 21 |
+
# LLM modelini yükle
|
| 22 |
llm_model = None
|
| 23 |
IS_LLM_ENABLED = False
|
| 24 |
|
|
|
|
| 34 |
llm_model = llm_model.to("cpu")
|
| 35 |
llm_model.eval()
|
| 36 |
IS_LLM_ENABLED = True
|
| 37 |
+
print(f"✅ LLM modeli yüklendi!")
|
| 38 |
except Exception as e:
|
| 39 |
IS_LLM_ENABLED = False
|
| 40 |
print(f"⚠️ LLM yüklenemedi: {e}")
|
| 41 |
|
| 42 |
+
# --- 2. WIKIPEDIA API (DOĞRUDAN API KULLANIMI) ---
|
| 43 |
|
| 44 |
+
def get_wiki_summary(term):
|
| 45 |
+
"""Türkçe Wikipedia'dan doğrudan API ile özet getirir"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
+
print(f"\n{'='*50}")
|
| 48 |
+
print(f"🔍 Türkçe Wikipedia sorgusu: '{term}'")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
# Özel terim dönüşümleri
|
| 51 |
special_cases = {
|
| 52 |
"Türk": "Türkler",
|
| 53 |
+
"türk": "Türkler",
|
| 54 |
"Altın Aslan": "Altın Aslan Ödülü",
|
| 55 |
"Venedik Film Festivali": "Venedik Film Festivali",
|
| 56 |
"Kış Uykusu": "Kış Uykusu (film)",
|
| 57 |
"Inception": "Inception (film)",
|
| 58 |
"Oscar": "Akademi Ödülü",
|
| 59 |
"Nobel": "Nobel Ödülü",
|
|
|
|
|
|
|
|
|
|
| 60 |
}
|
| 61 |
|
| 62 |
+
# Arama terimlerini hazırla
|
| 63 |
+
search_terms = [term]
|
| 64 |
for key, value in special_cases.items():
|
| 65 |
if term.lower() == key.lower():
|
| 66 |
+
search_terms = [value, term]
|
| 67 |
+
break
|
| 68 |
|
| 69 |
+
# Eğer özel durum yoksa, çoğul ve tekil dene
|
| 70 |
+
if len(search_terms) == 1:
|
| 71 |
+
if term.endswith("lar") or term.endswith("ler"):
|
| 72 |
+
search_terms.append(term[:-3])
|
| 73 |
+
else:
|
| 74 |
+
search_terms.append(term + "lar")
|
| 75 |
+
search_terms.append(term + "ler")
|
| 76 |
|
| 77 |
+
print(f"📝 Aranacak terimler: {search_terms}")
|
|
|
|
| 78 |
|
| 79 |
+
# Headers
|
| 80 |
+
headers = {
|
| 81 |
+
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
|
| 82 |
+
'Accept': 'application/json',
|
| 83 |
+
'Accept-Language': 'tr,en;q=0.9'
|
| 84 |
+
}
|
| 85 |
|
| 86 |
+
for search_term in search_terms:
|
| 87 |
+
print(f"🔎 '{search_term}' aranıyor...")
|
| 88 |
+
|
| 89 |
+
try:
|
| 90 |
+
# 1. Önce sayfayı doğrudan kontrol et
|
| 91 |
+
url = "https://tr.wikipedia.org/w/api.php"
|
| 92 |
+
params = {
|
| 93 |
+
"action": "query",
|
| 94 |
+
"format": "json",
|
| 95 |
+
"titles": search_term,
|
| 96 |
+
"prop": "extracts",
|
| 97 |
+
"exintro": True,
|
| 98 |
+
"explaintext": True,
|
| 99 |
+
"exsentences": 3,
|
| 100 |
+
"origin": "*"
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
response = requests.get(url, params=params, headers=headers, timeout=10, verify=False)
|
| 104 |
+
|
| 105 |
+
if response.status_code == 200:
|
| 106 |
+
try:
|
| 107 |
+
data = response.json()
|
| 108 |
+
pages = data.get('query', {}).get('pages', {})
|
| 109 |
+
|
| 110 |
+
for page_id, page_info in pages.items():
|
| 111 |
+
if page_id != "-1":
|
| 112 |
+
extract = page_info.get('extract', '')
|
| 113 |
+
if extract and len(extract) > 20:
|
| 114 |
+
print(f"✅ Doğrudan sayfa bulundu: '{search_term}'")
|
| 115 |
+
print(f" {extract[:100]}...")
|
| 116 |
+
return extract
|
| 117 |
+
except json.JSONDecodeError:
|
| 118 |
+
print(f"⚠️ JSON hatası, devam ediliyor...")
|
| 119 |
+
|
| 120 |
+
# 2. Doğrudan bulunamazsa arama yap
|
| 121 |
+
search_params = {
|
| 122 |
+
"action": "query",
|
| 123 |
+
"format": "json",
|
| 124 |
+
"list": "search",
|
| 125 |
+
"srsearch": search_term,
|
| 126 |
+
"srlimit": 3,
|
| 127 |
+
"srprop": "snippet",
|
| 128 |
+
"origin": "*"
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
search_response = requests.get(url, params=search_params, headers=headers, timeout=10, verify=False)
|
| 132 |
+
|
| 133 |
+
if search_response.status_code == 200:
|
| 134 |
+
try:
|
| 135 |
+
search_data = search_response.json()
|
| 136 |
+
search_results = search_data.get('query', {}).get('search', [])
|
| 137 |
+
|
| 138 |
+
if search_results:
|
| 139 |
+
print(f"📊 '{search_term}' -> {len(search_results)} sonuç")
|
| 140 |
+
|
| 141 |
+
for result in search_results:
|
| 142 |
+
title = result.get('title', '')
|
| 143 |
+
if title:
|
| 144 |
+
print(f"📄 '{title}' deneniyor...")
|
| 145 |
+
|
| 146 |
+
# Sayfa özetini al
|
| 147 |
+
summary_params = {
|
| 148 |
+
"action": "query",
|
| 149 |
+
"format": "json",
|
| 150 |
+
"titles": title,
|
| 151 |
+
"prop": "extracts",
|
| 152 |
+
"exintro": True,
|
| 153 |
+
"explaintext": True,
|
| 154 |
+
"exsentences": 3,
|
| 155 |
+
"origin": "*"
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
summary_response = requests.get(url, params=summary_params, headers=headers, timeout=10, verify=False)
|
| 159 |
+
|
| 160 |
+
if summary_response.status_code == 200:
|
| 161 |
+
try:
|
| 162 |
+
summary_data = summary_response.json()
|
| 163 |
+
pages = summary_data.get('query', {}).get('pages', {})
|
| 164 |
+
|
| 165 |
+
for page_id, page_info in pages.items():
|
| 166 |
+
if page_id != "-1":
|
| 167 |
+
extract = page_info.get('extract', '')
|
| 168 |
+
if extract and len(extract) > 20:
|
| 169 |
+
print(f"✅ '{search_term}' -> '{title}' bulundu")
|
| 170 |
+
print(f" {extract[:100]}...")
|
| 171 |
+
return extract
|
| 172 |
+
except json.JSONDecodeError:
|
| 173 |
+
print(f"⚠️ JSON hatası")
|
| 174 |
+
|
| 175 |
+
except json.JSONDecodeError:
|
| 176 |
+
print(f"⚠️ Arama JSON hatası")
|
| 177 |
+
|
| 178 |
+
except requests.exceptions.RequestException as e:
|
| 179 |
+
print(f"⚠️ Request hatası: {str(e)[:50]}")
|
| 180 |
+
continue
|
| 181 |
+
except Exception as e:
|
| 182 |
+
print(f"⚠️ Hata: {str(e)[:50]}")
|
| 183 |
+
continue
|
| 184 |
+
|
| 185 |
+
time.sleep(0.3)
|
| 186 |
|
| 187 |
+
print(f"❌ '{term}' için Türkçe Wikipedia'da sonuç bulunamadı")
|
| 188 |
+
print(f"{'='*50}\n")
|
| 189 |
+
return None
|
| 190 |
|
| 191 |
+
def test_wikipedia_connection():
|
| 192 |
+
"""Wikipedia API bağlantısını test et"""
|
| 193 |
+
logs = []
|
|
|
|
|
|
|
|
|
|
| 194 |
|
| 195 |
try:
|
| 196 |
+
# API testi
|
| 197 |
+
url = "https://tr.wikipedia.org/w/api.php"
|
| 198 |
+
params = {
|
| 199 |
+
"action": "query",
|
| 200 |
+
"format": "json",
|
| 201 |
+
"titles": "Türkiye",
|
| 202 |
+
"prop": "extracts",
|
| 203 |
+
"exintro": True,
|
| 204 |
+
"explaintext": True,
|
| 205 |
+
"origin": "*"
|
| 206 |
+
}
|
| 207 |
+
headers = {'User-Agent': 'Mozilla/5.0 (compatible; Test/1.0)'}
|
| 208 |
|
| 209 |
+
response = requests.get(url, params=params, headers=headers, timeout=10, verify=False)
|
| 210 |
+
logs.append(f"📡 API Status: {response.status_code}")
|
|
|
|
| 211 |
|
| 212 |
+
if response.status_code == 200:
|
|
|
|
|
|
|
| 213 |
try:
|
| 214 |
+
data = response.json()
|
| 215 |
+
pages = data.get('query', {}).get('pages', {})
|
| 216 |
+
for page_id, page_info in pages.items():
|
| 217 |
+
if page_id != "-1":
|
| 218 |
+
extract = page_info.get('extract', '')
|
| 219 |
+
if extract:
|
| 220 |
+
logs.append(f"✅ Türkçe Wikipedia API çalışıyor!")
|
| 221 |
+
logs.append(f"📄 Örnek: {extract[:100]}...")
|
| 222 |
+
break
|
| 223 |
+
else:
|
| 224 |
+
logs.append(f"⚠️ Sayfa bulunamadı")
|
| 225 |
+
except json.JSONDecodeError:
|
| 226 |
+
logs.append(f"❌ JSON parse hatası")
|
| 227 |
+
logs.append(f"Response: {response.text[:200]}")
|
| 228 |
+
else:
|
| 229 |
+
logs.append(f"❌ API hatası: {response.status_code}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 230 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 231 |
except Exception as e:
|
| 232 |
+
logs.append(f"❌ Bağlantı hatası: {str(e)}")
|
| 233 |
+
|
| 234 |
+
return "\n".join(logs)
|
|
|
|
| 235 |
|
| 236 |
+
# --- 3. LLM ANALİZ FONKSİYONU ---
|
| 237 |
|
| 238 |
@spaces.GPU
|
| 239 |
def refine_label_with_llm(entity_text, full_sentence, wiki_context, custom_label_definitions):
|
| 240 |
+
"""LLM ile etiket analizi yapar"""
|
| 241 |
global llm_model, IS_LLM_ENABLED
|
| 242 |
|
| 243 |
if not IS_LLM_ENABLED or llm_model is None:
|
| 244 |
return "MISC", "LLM Aktif Değil"
|
| 245 |
|
| 246 |
try:
|
| 247 |
+
print(f"\n🧠 LLM analizi: '{entity_text}'")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 248 |
|
| 249 |
# Etiket Tanımları
|
| 250 |
label_rules = ""
|
|
|
|
| 304 |
messages = [{"role": "user", "content": prompt}]
|
| 305 |
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 306 |
model_inputs = tokenizer([text], return_tensors="pt")
|
|
|
|
|
|
|
| 307 |
model_inputs = {k: v.to("cpu") for k, v in model_inputs.items()}
|
| 308 |
|
|
|
|
|
|
|
| 309 |
with torch.no_grad():
|
| 310 |
generated_ids = llm_model.generate(
|
| 311 |
model_inputs.input_ids,
|
|
|
|
| 318 |
response_ids = [output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)]
|
| 319 |
full_output = tokenizer.batch_decode(response_ids, skip_special_tokens=True)[0].strip()
|
| 320 |
|
|
|
|
|
|
|
| 321 |
# Etiket Ayıklama
|
| 322 |
clean_output = full_output.replace("*", "")
|
| 323 |
final_label = "MISC"
|
|
|
|
| 329 |
if extracted in valid_keys:
|
| 330 |
final_label = extracted
|
| 331 |
print(f"🏷️ Etiket: {final_label}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 332 |
|
| 333 |
return final_label, clean_output
|
| 334 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 335 |
except Exception as e:
|
| 336 |
+
print(f"❌ LLM hatası: {str(e)}")
|
|
|
|
| 337 |
return "MISC", f"Hata: {str(e)[:100]}"
|
| 338 |
|
| 339 |
# --- 4. ANA İŞLEM HATTI ---
|
|
|
|
| 451 |
logs.append(f"✅ SONUÇ: {result}")
|
| 452 |
else:
|
| 453 |
logs.append(f"❌ Sonuç bulunamadı")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 454 |
except Exception as e:
|
| 455 |
logs.append(f"❌ Hata: {str(e)}")
|
|
|
|
| 456 |
|
| 457 |
return "\n".join(logs)
|
| 458 |
|
|
|
|
| 469 |
dtype = next(llm_model.parameters()).dtype
|
| 470 |
logs.append(f"Device: {device}")
|
| 471 |
logs.append(f"Dtype: {dtype}")
|
|
|
|
| 472 |
except Exception as e:
|
| 473 |
logs.append(f"Device kontrol hatası: {str(e)}")
|
| 474 |
else:
|
|
|
|
| 524 |
debug_output = gr.HTML(label="Debug Sonuçları")
|
| 525 |
debug_btn.click(debug_wikipedia, outputs=debug_output)
|
| 526 |
|
| 527 |
+
gr.Markdown("### 🔍 Tek Terim Testi")
|
| 528 |
with gr.Row():
|
| 529 |
single_term_input = gr.Textbox(
|
| 530 |
label="Test Edilecek Terim",
|