| |
| """Atlas RAG retrieval sistemini uçtan uca değerlendiren komut satırı aracı. |
| |
| Script iki ayrı kontrol katmanı içerir: |
| |
| 1. Veri bütünlüğü: benchmarkın 20 pozitif ve 10 negatif sorudan oluştuğunu, |
| pozitif referansların gerçek chunk'lara bağlandığını ve negatif konuların ham |
| korpusta bulunmadığını doğrular. |
| 2. Retrieval başarısı: soruları dokümanlarla aynı modelle vektörleştirir, |
| ChromaDB'de cosine araması yapar ve 0.50 eşiğine göre cevapla/reddet kararı verir. |
| |
| Bu dosya cevap üreten bir LLM testi değildir. Ölçülen şey doğru bilgi parçasının |
| getirilmesi ve kaynakta cevap yokken sistemin sabit ret yanıtına geçebilmesidir. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import re |
| import shutil |
| import sys |
| import tempfile |
| from collections import Counter |
| from pathlib import Path |
| from typing import Any |
|
|
| import chromadb |
| import numpy as np |
| import pandas as pd |
| from sentence_transformers import SentenceTransformer |
|
|
|
|
| |
| |
| |
| PROJECT_ROOT = Path(__file__).resolve().parents[1] |
| BENCHMARK_PATH = PROJECT_ROOT / "test" / "benchmark.jsonl" |
| RAW_DATA_PATH = PROJECT_ROOT / "data" / "atlas.parquet" |
| CHUNKS_PATH = PROJECT_ROOT / "data" / "atlas_chunks.parquet" |
| CHROMA_PATH = PROJECT_ROOT / "data" / "chroma_db" |
| DEFAULT_RESULTS_PATH = PROJECT_ROOT / "test" / "results.jsonl" |
|
|
| |
| |
| MODEL_NAME = "magibu/embeddingmagibu-200m" |
| COLLECTION_NAME = "atlas_medical_articles" |
|
|
| |
| |
| NO_ANSWER_RESPONSE = "Bu sorunun cevabı dokümanlarımda yer almamaktadır" |
|
|
|
|
| def parse_args() -> argparse.Namespace: |
| """Komut satırı seçeneklerini tanımlar ve doğrulama öncesi ham değerleri döndürür.""" |
| parser = argparse.ArgumentParser( |
| description="Benchmark yapısını ve ChromaDB retrieval sonuçlarını test eder." |
| ) |
|
|
| |
| parser.add_argument( |
| "--threshold", |
| type=float, |
| default=0.50, |
| help="Cevap üretmek için gereken en düşük cosine benzerliği (varsayılan: 0.50).", |
| ) |
| parser.add_argument( |
| "--top-k", |
| type=int, |
| default=5, |
| help="Her soru için getirilecek en yakın chunk sayısı (varsayılan: 5).", |
| ) |
|
|
| |
| parser.add_argument( |
| "--batch-size", |
| type=int, |
| default=16, |
| help="Soru embedding'leri için batch boyutu (varsayılan: 16).", |
| ) |
| parser.add_argument( |
| "--device", |
| default="cpu", |
| help="SentenceTransformer çalışma aygıtı (varsayılan: cpu).", |
| ) |
|
|
| |
| |
| parser.add_argument( |
| "--output", |
| type=Path, |
| default=DEFAULT_RESULTS_PATH, |
| help="Detaylı test sonuçlarının yazılacağı JSONL dosyası.", |
| ) |
| parser.add_argument( |
| "--validate-only", |
| action="store_true", |
| help="Modeli yüklemeden yalnızca benchmark ve referans bütünlüğünü doğrula.", |
| ) |
| parser.add_argument( |
| "--no-fail", |
| action="store_true", |
| help="Başarısız retrieval kayıtları olsa da sıfır çıkış kodu döndür.", |
| ) |
| return parser.parse_args() |
|
|
|
|
| def normalize_text(value: str) -> str: |
| """Metni yalnızca güvenilir birebir kanıt kontrolü için normalize eder. |
| |
| Bir veya daha fazla boşluk/satır sonunu tek boşluğa indirir ve büyük-küçük |
| harf farkını kaldırır. Kelimeleri köklerine ayırmadığımız için bu kontrol |
| hâlâ gerçek bir alt metin eşleşmesidir; anlamsal benzerlik testi değildir. |
| """ |
| return re.sub(r"\s+", " ", value).strip().casefold() |
|
|
|
|
| def load_jsonl(path: Path) -> list[dict[str, Any]]: |
| """JSONL dosyasını yükler ve bozuk satırda dosya/satır bilgisiyle hata verir. |
| |
| JSONL biçiminde her dolu satır bağımsız bir JSON nesnesidir. Dosyanın tamamını |
| tek bir JSON listesi gibi okumamak, kayıtların satır bazında incelenmesini ve |
| ileride akış şeklinde işlenmesini kolaylaştırır. |
| """ |
| records: list[dict[str, Any]] = [] |
| with path.open(encoding="utf-8") as handle: |
| for line_number, line in enumerate(handle, start=1): |
| if not line.strip(): |
| continue |
| try: |
| records.append(json.loads(line)) |
| except json.JSONDecodeError as error: |
| raise ValueError(f"{path}:{line_number} geçerli JSON değil: {error}") from error |
| return records |
|
|
|
|
| def validate_benchmark(records: list[dict[str, Any]]) -> None: |
| """Benchmarkın sayısal dağılımını ve kaynak referanslarını doğrular. |
| |
| Pozitif soru için verilen chunk_id, URL, başlık ve kanıt metni üretilmiş chunk |
| dosyasıyla karşılaştırılır. Negatif soru içinse seçilen ayırt edici terimlerin |
| ham Atlas makalelerinde gerçekten bulunmadığı kontrol edilir. Bu ikinci kontrol, |
| yanlışlıkla cevabı bulunan bir soruyu negatif olarak etiketleme riskini azaltır. |
| """ |
|
|
| |
| |
| if len(records) != 30: |
| raise AssertionError(f"Benchmark tam 30 kayıt içermeli; bulunan: {len(records)}") |
|
|
| ids = [record.get("id") for record in records] |
| if len(set(ids)) != len(ids): |
| raise AssertionError("Benchmark id değerleri benzersiz olmalı.") |
|
|
| label_counts = Counter(record.get("label") for record in records) |
| if label_counts != {"positive": 20, "negative": 10}: |
| raise AssertionError(f"Beklenen etiket dağılımı 20/10; bulunan: {dict(label_counts)}") |
|
|
| |
| |
| chunks = pd.read_parquet(CHUNKS_PATH).set_index("chunk_id", drop=False) |
| raw_articles = pd.read_parquet(RAW_DATA_PATH) |
| normalized_corpus = normalize_text("\n".join(raw_articles["text"].fillna("").astype(str))) |
|
|
| for record in records: |
| test_id = record["id"] |
| if not record.get("question") or not record.get("expected_answer"): |
| raise AssertionError(f"{test_id}: question ve expected_answer zorunludur.") |
|
|
| if record["label"] == "positive": |
| |
| |
| reference = record.get("reference") |
| if not isinstance(reference, dict): |
| raise AssertionError(f"{test_id}: pozitif kayıtta reference zorunludur.") |
|
|
| chunk_id = reference.get("chunk_id") |
| if chunk_id not in chunks.index: |
| raise AssertionError(f"{test_id}: bilinmeyen chunk_id: {chunk_id}") |
|
|
| chunk = chunks.loc[chunk_id] |
| if reference.get("url") != chunk["url"] or reference.get("title") != chunk["title"]: |
| raise AssertionError(f"{test_id}: referans URL veya başlık chunk ile eşleşmiyor.") |
|
|
| evidence = normalize_text(reference.get("evidence", "")) |
| if not evidence or evidence not in normalize_text(chunk["chunk_text"]): |
| raise AssertionError(f"{test_id}: kanıt metni referans chunk içinde bulunamadı.") |
| else: |
| |
| |
| if record.get("reference") is not None: |
| raise AssertionError(f"{test_id}: negatif kaydın reference alanı null olmalı.") |
| if record["expected_answer"] != NO_ANSWER_RESPONSE: |
| raise AssertionError(f"{test_id}: negatif kayıt standart ret cevabını kullanmalı.") |
|
|
| |
| |
| absence_terms = record.get("absence_terms") |
| if not absence_terms: |
| raise AssertionError(f"{test_id}: absence_terms boş olamaz.") |
| found_terms = [ |
| term for term in absence_terms if normalize_text(term) in normalized_corpus |
| ] |
| if found_terms: |
| raise AssertionError( |
| f"{test_id}: negatif terimler korpusta bulundu: {found_terms}" |
| ) |
|
|
|
|
| def encode_questions( |
| model: SentenceTransformer, |
| questions: list[str], |
| batch_size: int, |
| ) -> np.ndarray: |
| """Soruları dokümanlarla aynı uzayda float32 ve birim normlu vektörlere çevirir. |
| |
| ``encode_query`` kullanımı modele girdinin bir arama sorgusu olduğunu bildirir. |
| ``normalize_embeddings=True`` cosine karşılaştırmasına uygun birim vektörler |
| ister; alttaki açık normalizasyon ise dtype dönüşümünden sonra bunu kesinleştirir. |
| """ |
| vectors = model.encode_query( |
| questions, |
| batch_size=batch_size, |
| show_progress_bar=True, |
| normalize_embeddings=True, |
| convert_to_numpy=True, |
| ).astype(np.float32) |
|
|
| |
| |
| norms = np.linalg.norm(vectors, axis=1, keepdims=True) |
| if not np.isfinite(norms).all() or not (norms > 0).all(): |
| raise AssertionError("Soru embedding'lerinde geçersiz veya sıfır norm bulundu.") |
| return vectors / norms |
|
|
|
|
| def run_retrieval( |
| records: list[dict[str, Any]], |
| threshold: float, |
| top_k: int, |
| batch_size: int, |
| device: str, |
| ) -> list[dict[str, Any]]: |
| """Soruları toplu encode eder, Chroma'yı sorgular ve karar kayıtlarını üretir.""" |
|
|
| |
| |
| model = SentenceTransformer(MODEL_NAME, device=device) |
| questions = [record["question"] for record in records] |
| query_vectors = encode_questions(model, questions, batch_size) |
|
|
| |
| |
| |
| with tempfile.TemporaryDirectory(prefix="atlas_rag_chroma_") as temp_dir: |
| test_chroma_path = Path(temp_dir) / "chroma_db" |
| shutil.copytree(CHROMA_PATH, test_chroma_path) |
|
|
| client = chromadb.PersistentClient(path=str(test_chroma_path)) |
| collection = client.get_collection(COLLECTION_NAME, embedding_function=None) |
| query_result = collection.query( |
| query_embeddings=query_vectors.tolist(), |
| n_results=top_k, |
| include=["documents", "metadatas", "distances"], |
| ) |
|
|
| results: list[dict[str, Any]] = [] |
| for index, record in enumerate(records): |
| |
| |
| retrieved_ids = query_result["ids"][index] |
| distances = query_result["distances"][index] |
| similarities = [1.0 - float(distance) for distance in distances] |
| top_similarity = similarities[0] |
|
|
| |
| |
| accepted = top_similarity >= threshold |
|
|
| |
| |
| |
| expected_chunk_id = None |
| expected_rank = None |
| if record["label"] == "positive": |
| expected_chunk_id = record["reference"]["chunk_id"] |
| if expected_chunk_id in retrieved_ids: |
| expected_rank = retrieved_ids.index(expected_chunk_id) + 1 |
|
|
| |
| |
| |
| system_response = None if accepted else NO_ANSWER_RESPONSE |
|
|
| |
| |
| passed = ( |
| accepted and expected_rank is not None |
| if record["label"] == "positive" |
| else not accepted and system_response == NO_ANSWER_RESPONSE |
| ) |
|
|
| |
| |
| results.append( |
| { |
| "id": record["id"], |
| "label": record["label"], |
| "question": record["question"], |
| "threshold": threshold, |
| "top_similarity": top_similarity, |
| "accepted": accepted, |
| "expected_chunk_id": expected_chunk_id, |
| "expected_chunk_rank": expected_rank, |
| "top_chunk_id": retrieved_ids[0], |
| "top_title": query_result["metadatas"][index][0]["title"], |
| "system_response": system_response, |
| "passed": passed, |
| } |
| ) |
| return results |
|
|
|
|
| def write_jsonl(path: Path, records: list[dict[str, Any]]) -> None: |
| """Sonuçları Türkçe karakterleri kaçış dizisine çevirmeden JSONL olarak yazar.""" |
| path.parent.mkdir(parents=True, exist_ok=True) |
| with path.open("w", encoding="utf-8") as handle: |
| for record in records: |
| handle.write(json.dumps(record, ensure_ascii=False) + "\n") |
|
|
|
|
| def print_report(results: list[dict[str, Any]], top_k: int) -> None: |
| """Tekil kararları ve retrieval/cevap vermeme metriklerini terminale basar.""" |
|
|
| |
| |
| for result in results: |
| status = "PASS" if result["passed"] else "FAIL" |
| rank = result["expected_chunk_rank"] or "-" |
| print( |
| f"[{status}] {result['id']} {result['label']:<8} " |
| f"score={result['top_similarity']:.4f} rank={rank} " |
| f"top={result['top_title']}" |
| ) |
|
|
| |
| |
| positives = [result for result in results if result["label"] == "positive"] |
| negatives = [result for result in results if result["label"] == "negative"] |
| positive_acceptance = sum(result["accepted"] for result in positives) / len(positives) |
| reference_recall = sum( |
| result["expected_chunk_rank"] is not None for result in positives |
| ) / len(positives) |
| negative_rejection = sum(not result["accepted"] for result in negatives) / len(negatives) |
| total_pass_rate = sum(result["passed"] for result in results) / len(results) |
|
|
| print("\nÖzet") |
| print(f"- Pozitif kabul oranı: {positive_acceptance:.1%}") |
| print(f"- Referans recall@{top_k}: {reference_recall:.1%}") |
| print(f"- Negatif ret oranı: {negative_rejection:.1%}") |
| print(f"- Toplam test başarı oranı: {total_pass_rate:.1%}") |
|
|
|
|
| def main() -> int: |
| """Doğrulama, retrieval, raporlama ve process exit code akışını yönetir.""" |
| args = parse_args() |
|
|
| |
| if not 0.0 <= args.threshold <= 1.0: |
| raise ValueError("--threshold 0 ile 1 arasında olmalı.") |
| if args.top_k < 1: |
| raise ValueError("--top-k en az 1 olmalı.") |
|
|
| |
| |
| records = load_jsonl(BENCHMARK_PATH) |
| validate_benchmark(records) |
| print("Benchmark doğrulandı: 20 pozitif + 10 negatif kayıt.") |
|
|
| if args.validate_only: |
| return 0 |
|
|
| results = run_retrieval( |
| records=records, |
| threshold=args.threshold, |
| top_k=args.top_k, |
| batch_size=args.batch_size, |
| device=args.device, |
| ) |
| write_jsonl(args.output, results) |
| print_report(results, args.top_k) |
| print(f"\nDetaylı sonuçlar: {args.output}") |
|
|
| |
| |
| failed_count = sum(not result["passed"] for result in results) |
| return 0 if args.no_fail or failed_count == 0 else 1 |
|
|
|
|
| if __name__ == "__main__": |
| |
| |
| try: |
| raise SystemExit(main()) |
| except (AssertionError, ValueError, FileNotFoundError) as error: |
| print(f"HATA: {error}", file=sys.stderr) |
| raise SystemExit(2) from error |
|
|