Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -14,13 +14,6 @@ from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
|
| 14 |
import urllib3
|
| 15 |
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
| 16 |
|
| 17 |
-
# Wikipedia için özel session
|
| 18 |
-
session = requests.Session()
|
| 19 |
-
session.verify = False # SSL doğrulamasını kapat
|
| 20 |
-
session.headers.update({
|
| 21 |
-
'User-Agent': 'Mozilla/5.0 (compatible; RAG-NER-System/1.0; +https://huggingface.co/spaces)'
|
| 22 |
-
})
|
| 23 |
-
|
| 24 |
# --- 1. MODELLERİN HAZIRLANMASI ---
|
| 25 |
ner_pipe = pipeline("ner", model="xlm-roberta-large-finetuned-conll03-english", aggregation_strategy="simple", device=-1)
|
| 26 |
model_id = "Qwen/Qwen2.5-1.5B-Instruct"
|
|
@@ -33,10 +26,10 @@ except Exception as e:
|
|
| 33 |
IS_LLM_ENABLED = False
|
| 34 |
print(f"⚠️ LLM yüklenemedi: {e}")
|
| 35 |
|
| 36 |
-
# --- 2. WIKIPEDIA FONKSİYONLARI (
|
| 37 |
|
| 38 |
def test_wikipedia_connection():
|
| 39 |
-
"""Wikipedia bağlantısını ve fonksiyonelliğini test et"""
|
| 40 |
logs = []
|
| 41 |
|
| 42 |
# 1. Modül kontrolü
|
|
@@ -49,70 +42,107 @@ def test_wikipedia_connection():
|
|
| 49 |
|
| 50 |
# 2. İnternet bağlantısı kontrolü
|
| 51 |
try:
|
| 52 |
-
response = requests.get("https://
|
| 53 |
logs.append(f"✅ İnternet bağlantısı var: {response.status_code}")
|
| 54 |
except Exception as e:
|
| 55 |
logs.append(f"❌ İnternet bağlantısı yok: {e}")
|
| 56 |
return "\n".join(logs)
|
| 57 |
|
| 58 |
-
# 3. Türkçe Wikipedia'ya erişim
|
| 59 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
wikipedia.set_lang("tr")
|
| 61 |
test_term = "Türkiye"
|
|
|
|
|
|
|
| 62 |
search_results = wikipedia.search(test_term)
|
| 63 |
-
logs.append(f"
|
| 64 |
|
| 65 |
if search_results:
|
|
|
|
| 66 |
try:
|
| 67 |
summary = wikipedia.summary(search_results[0], sentences=2, auto_suggest=False)
|
| 68 |
logs.append(f"✅ Özet alındı: {summary[:100]}...")
|
| 69 |
except Exception as e:
|
| 70 |
-
logs.append(f"❌ Özet alınamadı: {e}")
|
|
|
|
|
|
|
|
|
|
| 71 |
except Exception as e:
|
| 72 |
-
logs.append(f"❌ Türkçe Wikipedia hatası: {e}")
|
| 73 |
|
| 74 |
-
# 4.
|
| 75 |
try:
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
try:
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
except Exception as e:
|
| 88 |
-
logs.append(f"❌
|
| 89 |
|
| 90 |
return "\n".join(logs)
|
| 91 |
|
| 92 |
def get_wiki_summary(term):
|
| 93 |
-
"""Varlık için Wikipedia özeti getirir -
|
| 94 |
import wikipedia
|
| 95 |
import traceback
|
| 96 |
|
| 97 |
print(f"\n{'='*50}")
|
| 98 |
-
print(f"🔍 Wikipedia sorgusu başladı: '{term}'")
|
| 99 |
|
| 100 |
try:
|
| 101 |
-
#
|
| 102 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
-
#
|
| 105 |
wikipedia.wikipedia._session = session
|
| 106 |
|
| 107 |
-
#
|
| 108 |
-
print(f"🌐 Türkçe Wikipedia aranıyor...")
|
| 109 |
wikipedia.set_lang("tr")
|
|
|
|
| 110 |
|
| 111 |
-
#
|
| 112 |
try:
|
|
|
|
| 113 |
page = wikipedia.page(term, auto_suggest=False)
|
| 114 |
if page:
|
| 115 |
summary = page.summary
|
|
|
|
| 116 |
sentences = summary.split('.')[:3]
|
| 117 |
result = '.'.join(sentences) + '.'
|
| 118 |
if len(result) > 20:
|
|
@@ -121,56 +151,25 @@ def get_wiki_summary(term):
|
|
| 121 |
except wikipedia.exceptions.DisambiguationError as e:
|
| 122 |
print(f"⚠️ Anlam karmaşası: {e.options[:3]}")
|
| 123 |
# İlk seçeneği dene
|
| 124 |
-
|
| 125 |
-
page = wikipedia.page(e.options[0], auto_suggest=False)
|
| 126 |
-
summary = page.summary
|
| 127 |
-
sentences = summary.split('.')[:3]
|
| 128 |
-
result = '.'.join(sentences) + '.'
|
| 129 |
-
if len(result) > 20:
|
| 130 |
-
print(f"✅ Anlam karmaşası çözüldü: {result[:100]}...")
|
| 131 |
-
return result
|
| 132 |
-
except:
|
| 133 |
-
pass
|
| 134 |
-
except wikipedia.exceptions.PageError:
|
| 135 |
-
print(f"⚠️ Sayfa bulunamadı, arama yapılıyor...")
|
| 136 |
-
|
| 137 |
-
# Arama yap
|
| 138 |
-
search_results = wikipedia.search(term, results=5)
|
| 139 |
-
print(f"📊 Türkçe arama sonuçları: {len(search_results)} adet")
|
| 140 |
-
if search_results:
|
| 141 |
-
print(f"📄 İlk sonuç: '{search_results[0]}'")
|
| 142 |
-
for title in search_results:
|
| 143 |
try:
|
| 144 |
-
page = wikipedia.page(
|
| 145 |
summary = page.summary
|
| 146 |
sentences = summary.split('.')[:3]
|
| 147 |
result = '.'.join(sentences) + '.'
|
| 148 |
if len(result) > 20:
|
| 149 |
-
print(f"✅
|
| 150 |
return result
|
| 151 |
except:
|
| 152 |
continue
|
|
|
|
|
|
|
| 153 |
|
| 154 |
-
#
|
| 155 |
-
print(f"
|
| 156 |
-
wikipedia.set_lang("en")
|
| 157 |
-
|
| 158 |
-
# Önce doğrudan sayfayı kontrol et
|
| 159 |
-
try:
|
| 160 |
-
page = wikipedia.page(term, auto_suggest=False)
|
| 161 |
-
if page:
|
| 162 |
-
summary = page.summary
|
| 163 |
-
sentences = summary.split('.')[:3]
|
| 164 |
-
result = '.'.join(sentences) + '.'
|
| 165 |
-
if len(result) > 20:
|
| 166 |
-
print(f"✅ İngilizce doğrudan sayfa bulundu: {result[:100]}...")
|
| 167 |
-
return result
|
| 168 |
-
except:
|
| 169 |
-
pass
|
| 170 |
-
|
| 171 |
-
# Arama yap
|
| 172 |
search_results = wikipedia.search(term, results=5)
|
| 173 |
-
print(f"📊
|
|
|
|
| 174 |
if search_results:
|
| 175 |
print(f"📄 İlk sonuç: '{search_results[0]}'")
|
| 176 |
for title in search_results:
|
|
@@ -180,12 +179,69 @@ def get_wiki_summary(term):
|
|
| 180 |
sentences = summary.split('.')[:3]
|
| 181 |
result = '.'.join(sentences) + '.'
|
| 182 |
if len(result) > 20:
|
| 183 |
-
print(f"✅
|
| 184 |
return result
|
| 185 |
-
except:
|
|
|
|
| 186 |
continue
|
| 187 |
|
| 188 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 189 |
return None
|
| 190 |
|
| 191 |
except Exception as e:
|
|
@@ -200,8 +256,9 @@ def get_wiki_summary(term):
|
|
| 200 |
|
| 201 |
def get_random_examples():
|
| 202 |
"""Wikipedia'dan rastgele cümleler çekerek örnek listesi oluşturur."""
|
| 203 |
-
wikipedia.set_lang("tr")
|
| 204 |
try:
|
|
|
|
|
|
|
| 205 |
random_titles = wikipedia.random(pages=3)
|
| 206 |
return [[wikipedia.summary(t, sentences=1, auto_suggest=False)] for t in random_titles]
|
| 207 |
except:
|
|
@@ -335,36 +392,21 @@ def process_ner(text):
|
|
| 335 |
current_logs.append(f"🔍 <b>Analiz Başladı:</b> '{word}'")
|
| 336 |
yield "<br>".join(current_logs), [[r["Varlık"], r["İlk Etiket"], r["Nihai Etiket"], r["Kaynak"]] for r in final_results]
|
| 337 |
|
| 338 |
-
#
|
| 339 |
start_time = time.time()
|
| 340 |
-
current_logs.append(f"⏱️ <b>Wikipedia sorgusu
|
| 341 |
yield "<br>".join(current_logs), [[r["Varlık"], r["İlk Etiket"], r["Nihai Etiket"], r["Kaynak"]] for r in final_results]
|
| 342 |
|
| 343 |
-
# Wikipedia'dan bilgi al
|
| 344 |
wiki_text = None
|
| 345 |
try:
|
| 346 |
wiki_text = get_wiki_summary(word)
|
| 347 |
elapsed = time.time() - start_time
|
| 348 |
|
| 349 |
if wiki_text:
|
| 350 |
-
current_logs.append(f"✅ <b>Wikipedia başarılı</b> ({elapsed:.2f}s)
|
| 351 |
-
# Wikipedia özetini detaylı göster
|
| 352 |
current_logs.append(f"<div style='margin-left:20px; border-left:2px solid #007bff; padding-left:10px; color:#555;'>🌐 <b>Wiki:</b> {wiki_text}</div>")
|
| 353 |
else:
|
| 354 |
-
current_logs.append(f"❌ <b>Wikipedia boş döndü</b> ({elapsed:.2f}s) - '{word}' için bilgi yok")
|
| 355 |
-
|
| 356 |
-
# Neden boş olduğunu anlamak için ek test
|
| 357 |
-
try:
|
| 358 |
-
import wikipedia
|
| 359 |
-
wikipedia.set_lang("tr")
|
| 360 |
-
test_search = wikipedia.search(word)
|
| 361 |
-
if test_search:
|
| 362 |
-
current_logs.append(f"🔍 <b>Test arama:</b> '{word}' -> {len(test_search)} sonuç: {', '.join(test_search[:3])}")
|
| 363 |
-
else:
|
| 364 |
-
current_logs.append(f"🔍 <b>Test arama:</b> '{word}' -> Hiç sonuç yok")
|
| 365 |
-
except Exception as e:
|
| 366 |
-
current_logs.append(f"⚠️ <b>Test hatası:</b> {str(e)[:100]}")
|
| 367 |
-
|
| 368 |
except Exception as e:
|
| 369 |
elapsed = time.time() - start_time
|
| 370 |
current_logs.append(f"❌ <b>Wikipedia hatası</b> ({elapsed:.2f}s): {str(e)[:100]}")
|
|
@@ -395,40 +437,43 @@ def process_ner(text):
|
|
| 395 |
# --- 5. DEBUG FONKSİYONLARI ---
|
| 396 |
|
| 397 |
def debug_wikipedia():
|
| 398 |
-
"""Wikipedia debug bilgilerini göster"""
|
| 399 |
result = test_wikipedia_connection()
|
| 400 |
return f"<pre style='background:#f4f4f4;padding:10px;border-radius:5px;font-family:monospace;font-size:12px;'>{result}</pre>"
|
| 401 |
|
| 402 |
def test_single_term(term):
|
| 403 |
-
"""Tek bir terim için Wikipedia testi"""
|
| 404 |
if not term:
|
| 405 |
return "Lütfen bir terim girin."
|
| 406 |
|
| 407 |
-
logs = [f"🔍 '{term}' için Wikipedia testi başlatılıyor..."]
|
| 408 |
|
| 409 |
try:
|
| 410 |
result = get_wiki_summary(term)
|
| 411 |
if result:
|
| 412 |
logs.append(f"✅ Sonuç: {result}")
|
| 413 |
else:
|
| 414 |
-
logs.append(f"❌
|
| 415 |
|
| 416 |
# Detaylı test
|
| 417 |
import wikipedia
|
| 418 |
logs.append(f"\n📊 Detaylı test:")
|
| 419 |
try:
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
|
|
|
|
|
|
| 425 |
|
| 426 |
-
|
| 427 |
-
wikipedia.set_lang("en")
|
| 428 |
search_results = wikipedia.search(term)
|
| 429 |
-
logs.append(f"
|
|
|
|
|
|
|
| 430 |
except Exception as e:
|
| 431 |
-
logs.append(f"
|
| 432 |
|
| 433 |
except Exception as e:
|
| 434 |
logs.append(f"❌ Hata: {str(e)}")
|
|
@@ -439,7 +484,7 @@ def test_single_term(term):
|
|
| 439 |
# --- 6. GRADIO ARAYÜZÜ ---
|
| 440 |
|
| 441 |
with gr.Blocks(title="RAG-NER Uzman Karar Destek Sistemi") as demo:
|
| 442 |
-
gr.Markdown("# 🚀 RAG-NER Uzman Karar Destek Sistemi")
|
| 443 |
|
| 444 |
with gr.Tab("Metin Analizi"):
|
| 445 |
input_text = gr.Textbox(
|
|
@@ -477,20 +522,20 @@ with gr.Blocks(title="RAG-NER Uzman Karar Destek Sistemi") as demo:
|
|
| 477 |
|
| 478 |
# --- 7. DEBUG TABI ---
|
| 479 |
with gr.Tab("Debug"):
|
| 480 |
-
gr.Markdown("## 🐛 Wikipedia Debug Paneli")
|
| 481 |
-
gr.Markdown("Bu panel Wikipedia bağlantı sorunlarını tespit etmek için kullanılır.")
|
| 482 |
|
| 483 |
with gr.Row():
|
| 484 |
-
debug_btn = gr.Button("Wikipedia Bağlantısını Test Et", variant="secondary")
|
| 485 |
debug_output = gr.HTML(label="Debug Sonuçları")
|
| 486 |
|
| 487 |
debug_btn.click(debug_wikipedia, outputs=debug_output)
|
| 488 |
|
| 489 |
-
gr.Markdown("### 🔍 Tek Terim Testi")
|
| 490 |
with gr.Row():
|
| 491 |
single_term_input = gr.Textbox(
|
| 492 |
label="Test Edilecek Terim",
|
| 493 |
-
placeholder="Örn: Türkiye,
|
| 494 |
scale=3
|
| 495 |
)
|
| 496 |
single_term_btn = gr.Button("Test Et", variant="secondary", scale=1)
|
|
@@ -511,7 +556,7 @@ if __name__ == "__main__":
|
|
| 511 |
print("🚀 SİSTEM BAŞLATILIYOR...")
|
| 512 |
print("="*50)
|
| 513 |
|
| 514 |
-
print("\n📡 Wikipedia bağlantısı test ediliyor...")
|
| 515 |
test_result = test_wikipedia_connection()
|
| 516 |
print(test_result)
|
| 517 |
|
|
|
|
| 14 |
import urllib3
|
| 15 |
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
| 16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
# --- 1. MODELLERİN HAZIRLANMASI ---
|
| 18 |
ner_pipe = pipeline("ner", model="xlm-roberta-large-finetuned-conll03-english", aggregation_strategy="simple", device=-1)
|
| 19 |
model_id = "Qwen/Qwen2.5-1.5B-Instruct"
|
|
|
|
| 26 |
IS_LLM_ENABLED = False
|
| 27 |
print(f"⚠️ LLM yüklenemedi: {e}")
|
| 28 |
|
| 29 |
+
# --- 2. WIKIPEDIA FONKSİYONLARI (SADECE TÜRKÇE) ---
|
| 30 |
|
| 31 |
def test_wikipedia_connection():
|
| 32 |
+
"""Wikipedia bağlantısını ve fonksiyonelliğini test et - Sadece Türkçe"""
|
| 33 |
logs = []
|
| 34 |
|
| 35 |
# 1. Modül kontrolü
|
|
|
|
| 42 |
|
| 43 |
# 2. İnternet bağlantısı kontrolü
|
| 44 |
try:
|
| 45 |
+
response = requests.get("https://tr.wikipedia.org", timeout=5, verify=False)
|
| 46 |
logs.append(f"✅ İnternet bağlantısı var: {response.status_code}")
|
| 47 |
except Exception as e:
|
| 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 (SADECE TÜRKÇE)
|
| 52 |
try:
|
| 53 |
+
# Özel session ile dene
|
| 54 |
+
session = requests.Session()
|
| 55 |
+
session.verify = False
|
| 56 |
+
session.headers.update({
|
| 57 |
+
'User-Agent': 'Mozilla/5.0 (compatible; RAG-NER-System/1.0; +https://huggingface.co/spaces)'
|
| 58 |
+
})
|
| 59 |
+
wikipedia.wikipedia._session = session
|
| 60 |
+
|
| 61 |
wikipedia.set_lang("tr")
|
| 62 |
test_term = "Türkiye"
|
| 63 |
+
|
| 64 |
+
logs.append(f"🔍 '{test_term}' aranıyor (Türkçe Wikipedia)...")
|
| 65 |
search_results = wikipedia.search(test_term)
|
| 66 |
+
logs.append(f"📊 Arama sonucu: {len(search_results)} sonuç")
|
| 67 |
|
| 68 |
if search_results:
|
| 69 |
+
logs.append(f"📄 İlk sonuç: '{search_results[0]}'")
|
| 70 |
try:
|
| 71 |
summary = wikipedia.summary(search_results[0], sentences=2, auto_suggest=False)
|
| 72 |
logs.append(f"✅ Özet alındı: {summary[:100]}...")
|
| 73 |
except Exception as e:
|
| 74 |
+
logs.append(f"❌ Özet alınamadı: {str(e)}")
|
| 75 |
+
else:
|
| 76 |
+
logs.append(f"❌ Arama sonucu boş!")
|
| 77 |
+
|
| 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):
|
| 117 |
+
"""Varlık için Türkçe Wikipedia özeti getirir - Sadece Türkçe"""
|
| 118 |
import wikipedia
|
| 119 |
import traceback
|
| 120 |
|
| 121 |
print(f"\n{'='*50}")
|
| 122 |
+
print(f"🔍 Türkçe Wikipedia sorgusu başladı: '{term}'")
|
| 123 |
|
| 124 |
try:
|
| 125 |
+
# Özel session oluştur
|
| 126 |
+
session = requests.Session()
|
| 127 |
+
session.verify = False
|
| 128 |
+
session.headers.update({
|
| 129 |
+
'User-Agent': 'Mozilla/5.0 (compatible; RAG-NER-System/1.0; +https://huggingface.co/spaces)'
|
| 130 |
+
})
|
| 131 |
|
| 132 |
+
# Wikipedia modülünün session'ını değiştir
|
| 133 |
wikipedia.wikipedia._session = session
|
| 134 |
|
| 135 |
+
# Sadece Türkçe Wikipedia
|
|
|
|
| 136 |
wikipedia.set_lang("tr")
|
| 137 |
+
print(f"🌐 Dil: Türkçe")
|
| 138 |
|
| 139 |
+
# 1. YÖNTEM: Doğrudan sayfa kontrolü (en hızlı)
|
| 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:
|
|
|
|
| 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)
|
| 157 |
summary = page.summary
|
| 158 |
sentences = summary.split('.')[:3]
|
| 159 |
result = '.'.join(sentences) + '.'
|
| 160 |
if len(result) > 20:
|
| 161 |
+
print(f"✅ Anlam karmaşası çözüldü: '{option}' -> {result[:100]}...")
|
| 162 |
return result
|
| 163 |
except:
|
| 164 |
continue
|
| 165 |
+
except wikipedia.exceptions.PageError:
|
| 166 |
+
print(f"⚠️ Sayfa bulunamadı, arama yapılıyor...")
|
| 167 |
|
| 168 |
+
# 2. YÖNTEM: Arama yap
|
| 169 |
+
print(f"🔎 Arama yapılıyor: '{term}'")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
search_results = wikipedia.search(term, results=5)
|
| 171 |
+
print(f"📊 Arama sonuçları: {len(search_results)} adet")
|
| 172 |
+
|
| 173 |
if search_results:
|
| 174 |
print(f"📄 İlk sonuç: '{search_results[0]}'")
|
| 175 |
for title in search_results:
|
|
|
|
| 179 |
sentences = summary.split('.')[:3]
|
| 180 |
result = '.'.join(sentences) + '.'
|
| 181 |
if len(result) > 20:
|
| 182 |
+
print(f"✅ Arama sonucu özet alındı: '{title}' -> {result[:100]}...")
|
| 183 |
return result
|
| 184 |
+
except Exception as e:
|
| 185 |
+
print(f"⚠️ '{title}' alınamadı: {str(e)[:50]}")
|
| 186 |
continue
|
| 187 |
|
| 188 |
+
# 3. YÖNTEM: Doğrudan API ile dene (JSON hatasını çözmek için)
|
| 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",
|
| 197 |
+
"list": "search",
|
| 198 |
+
"srsearch": term,
|
| 199 |
+
"srlimit": 3,
|
| 200 |
+
"srprop": "snippet"
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
search_response = requests.get(url, params=search_params, timeout=10, verify=False,
|
| 204 |
+
headers={'User-Agent': 'RAG-NER-System/1.0'})
|
| 205 |
+
|
| 206 |
+
if search_response.status_code == 200:
|
| 207 |
+
try:
|
| 208 |
+
search_data = search_response.json()
|
| 209 |
+
if search_data.get('query', {}).get('search'):
|
| 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",
|
| 217 |
+
"prop": "extracts",
|
| 218 |
+
"exintro": True,
|
| 219 |
+
"explaintext": True,
|
| 220 |
+
"titles": page_title,
|
| 221 |
+
"exsentences": 3
|
| 222 |
+
}
|
| 223 |
+
|
| 224 |
+
summary_response = requests.get(url, params=summary_params, timeout=10, verify=False,
|
| 225 |
+
headers={'User-Agent': 'RAG-NER-System/1.0'})
|
| 226 |
+
|
| 227 |
+
if summary_response.status_code == 200:
|
| 228 |
+
try:
|
| 229 |
+
summary_data = summary_response.json()
|
| 230 |
+
pages = summary_data.get('query', {}).get('pages', {})
|
| 231 |
+
for page_id, page_info in pages.items():
|
| 232 |
+
if page_id != "-1":
|
| 233 |
+
extract = page_info.get('extract', '')
|
| 234 |
+
if extract and len(extract) > 20:
|
| 235 |
+
print(f"✅ API ile özet alındı: {extract[:100]}...")
|
| 236 |
+
return extract
|
| 237 |
+
except json.JSONDecodeError:
|
| 238 |
+
print(f"❌ API JSON hatası")
|
| 239 |
+
except json.JSONDecodeError:
|
| 240 |
+
print(f"❌ API arama JSON hatası")
|
| 241 |
+
except Exception as e:
|
| 242 |
+
print(f"⚠️ API denemesi başarısız: {str(e)[:50]}")
|
| 243 |
+
|
| 244 |
+
print(f"❌ '{term}' için Türkçe Wikipedia'da sonuç bulunamadı")
|
| 245 |
return None
|
| 246 |
|
| 247 |
except Exception as e:
|
|
|
|
| 256 |
|
| 257 |
def get_random_examples():
|
| 258 |
"""Wikipedia'dan rastgele cümleler çekerek örnek listesi oluşturur."""
|
|
|
|
| 259 |
try:
|
| 260 |
+
import wikipedia
|
| 261 |
+
wikipedia.set_lang("tr")
|
| 262 |
random_titles = wikipedia.random(pages=3)
|
| 263 |
return [[wikipedia.summary(t, sentences=1, auto_suggest=False)] for t in random_titles]
|
| 264 |
except:
|
|
|
|
| 392 |
current_logs.append(f"🔍 <b>Analiz Başladı:</b> '{word}'")
|
| 393 |
yield "<br>".join(current_logs), [[r["Varlık"], r["İlk Etiket"], r["Nihai Etiket"], r["Kaynak"]] for r in final_results]
|
| 394 |
|
| 395 |
+
# Wikipedia çağrısı
|
| 396 |
start_time = time.time()
|
| 397 |
+
current_logs.append(f"⏱️ <b>Türkçe Wikipedia sorgusu:</b> '{word}'")
|
| 398 |
yield "<br>".join(current_logs), [[r["Varlık"], r["İlk Etiket"], r["Nihai Etiket"], r["Kaynak"]] for r in final_results]
|
| 399 |
|
|
|
|
| 400 |
wiki_text = None
|
| 401 |
try:
|
| 402 |
wiki_text = get_wiki_summary(word)
|
| 403 |
elapsed = time.time() - start_time
|
| 404 |
|
| 405 |
if wiki_text:
|
| 406 |
+
current_logs.append(f"✅ <b>Wikipedia başarılı</b> ({elapsed:.2f}s)")
|
|
|
|
| 407 |
current_logs.append(f"<div style='margin-left:20px; border-left:2px solid #007bff; padding-left:10px; color:#555;'>🌐 <b>Wiki:</b> {wiki_text}</div>")
|
| 408 |
else:
|
| 409 |
+
current_logs.append(f"❌ <b>Wikipedia boş döndü</b> ({elapsed:.2f}s) - '{word}' için Türkçe Wikipedia'da bilgi yok")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 410 |
except Exception as e:
|
| 411 |
elapsed = time.time() - start_time
|
| 412 |
current_logs.append(f"❌ <b>Wikipedia hatası</b> ({elapsed:.2f}s): {str(e)[:100]}")
|
|
|
|
| 437 |
# --- 5. DEBUG FONKSİYONLARI ---
|
| 438 |
|
| 439 |
def debug_wikipedia():
|
| 440 |
+
"""Wikipedia debug bilgilerini göster - Sadece Türkçe"""
|
| 441 |
result = test_wikipedia_connection()
|
| 442 |
return f"<pre style='background:#f4f4f4;padding:10px;border-radius:5px;font-family:monospace;font-size:12px;'>{result}</pre>"
|
| 443 |
|
| 444 |
def test_single_term(term):
|
| 445 |
+
"""Tek bir terim için Türkçe Wikipedia testi"""
|
| 446 |
if not term:
|
| 447 |
return "Lütfen bir terim girin."
|
| 448 |
|
| 449 |
+
logs = [f"🔍 '{term}' için Türkçe Wikipedia testi başlatılıyor..."]
|
| 450 |
|
| 451 |
try:
|
| 452 |
result = get_wiki_summary(term)
|
| 453 |
if result:
|
| 454 |
logs.append(f"✅ Sonuç: {result}")
|
| 455 |
else:
|
| 456 |
+
logs.append(f"❌ Türkçe Wikipedia'da sonuç bulunamadı")
|
| 457 |
|
| 458 |
# Detaylı test
|
| 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({
|
| 466 |
+
'User-Agent': 'Mozilla/5.0 (compatible; RAG-NER-System/1.0)'
|
| 467 |
+
})
|
| 468 |
+
wikipedia.wikipedia._session = session
|
| 469 |
|
| 470 |
+
wikipedia.set_lang("tr")
|
|
|
|
| 471 |
search_results = wikipedia.search(term)
|
| 472 |
+
logs.append(f"Türkçe arama: {len(search_results)} sonuç")
|
| 473 |
+
if search_results:
|
| 474 |
+
logs.append(f"İlk sonuçlar: {', '.join(search_results[:3])}")
|
| 475 |
except Exception as e:
|
| 476 |
+
logs.append(f"Türkçe arama hatası: {str(e)}")
|
| 477 |
|
| 478 |
except Exception as e:
|
| 479 |
logs.append(f"❌ Hata: {str(e)}")
|
|
|
|
| 484 |
# --- 6. GRADIO ARAYÜZÜ ---
|
| 485 |
|
| 486 |
with gr.Blocks(title="RAG-NER Uzman Karar Destek Sistemi") as demo:
|
| 487 |
+
gr.Markdown("# 🚀 RAG-NER Uzman Karar Destek Sistemi (Türkçe Wikipedia)")
|
| 488 |
|
| 489 |
with gr.Tab("Metin Analizi"):
|
| 490 |
input_text = gr.Textbox(
|
|
|
|
| 522 |
|
| 523 |
# --- 7. DEBUG TABI ---
|
| 524 |
with gr.Tab("Debug"):
|
| 525 |
+
gr.Markdown("## 🐛 Türkçe Wikipedia Debug Paneli")
|
| 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 (Türkçe Wikipedia)")
|
| 535 |
with gr.Row():
|
| 536 |
single_term_input = gr.Textbox(
|
| 537 |
label="Test Edilecek Terim",
|
| 538 |
+
placeholder="Örn: Türkiye, İstanbul, Kış Uykusu",
|
| 539 |
scale=3
|
| 540 |
)
|
| 541 |
single_term_btn = gr.Button("Test Et", variant="secondary", scale=1)
|
|
|
|
| 556 |
print("🚀 SİSTEM BAŞLATILIYOR...")
|
| 557 |
print("="*50)
|
| 558 |
|
| 559 |
+
print("\n📡 Türkçe Wikipedia bağlantısı test ediliyor...")
|
| 560 |
test_result = test_wikipedia_connection()
|
| 561 |
print(test_result)
|
| 562 |
|