File size: 4,564 Bytes
ab773bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
"""
Vektör Veritabanı Katmanı — ChromaDB
------------------------------------------
ÖNEMLİ TASARIM KARARI: Chroma'nın kendi built-in embedding fonksiyonu
KULLANILMAZ. Embedding'ler her zaman src/embedder.py tarafından ayrı olarak
üretilir ve Chroma'ya hazır vektör olarak verilir (embedding_function=None).

Bunun nedeni: "vektör veritabanı" (nerede saklanacağı/aranacağı) ile
"embedding modeli" (vektörün nasıl üretileceği) birbirinden bağımsız iki karar
olmalı — ödev talimatında da özellikle belirtildiği gibi. Bu ayrım sayesinde
embedding backend'i (mock <-> real) değiştirmek Chroma katmanını hiç etkilemez.
"""
import sys
import os
import numpy as np

sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from src import config


class VectorStore:
    def __init__(self, persist_dir: str = None, collection_name: str = None, reset: bool = False):
        import chromadb

        self.persist_dir = persist_dir or config.CHROMA_PERSIST_DIR
        self.collection_name = collection_name or config.CHROMA_COLLECTION_NAME

        self.client = chromadb.PersistentClient(path=self.persist_dir)

        if reset:
            try:
                self.client.delete_collection(self.collection_name)
            except Exception:
                pass

        # embedding_function=None -> Chroma vektör üretmeye ÇALIŞMAZ, bizim
        # verdiğimiz hazır vektörleri kullanır.
        self.collection = self.client.get_or_create_collection(
            name=self.collection_name,
            metadata={"hnsw:space": "cosine"},
        )

    def upsert_chunks(self, chunks: list, vectors: np.ndarray):
        """
        chunks: list[dict] — her biri {chunk_id, url, title, __source, parent_id, chunk_text}
        vectors: np.ndarray (N, D) — chunks ile aynı sırada, aynı uzunlukta
        """
        assert len(chunks) == len(vectors), "chunks ve vectors uzunlukları eşleşmeli"
        if len(chunks) == 0:
            return

        self.collection.upsert(
            ids=[c["chunk_id"] for c in chunks],
            embeddings=[v.tolist() for v in vectors],
            documents=[c["chunk_text"] for c in chunks],
            metadatas=[
                {
                    "url": c["url"],
                    "title": c["title"],
                    "__source": c["__source"],
                    "parent_id": c["parent_id"],
                }
                for c in chunks
            ],
        )

    def query(self, query_vector: np.ndarray, top_k: int = None):
        """
        query_vector: np.ndarray (D,)
        Dönüş: list[dict] — [{chunk_id, chunk_text, url, title, __source, score}]
        score = cosine SIMILARITY (1'e yakın = çok benzer; Chroma "cosine" space'te
        distance = 1 - similarity döner, biz burada similarity'e çeviriyoruz).
        """
        top_k = top_k or config.TOP_K
        results = self.collection.query(
            query_embeddings=[query_vector.tolist()],
            n_results=top_k,
        )

        out = []
        ids = results["ids"][0]
        docs = results["documents"][0]
        metas = results["metadatas"][0]
        distances = results["distances"][0]
        for i in range(len(ids)):
            similarity = 1.0 - distances[i]  # cosine distance -> cosine similarity
            out.append({
                "chunk_id": ids[i],
                "chunk_text": docs[i],
                "url": metas[i]["url"],
                "title": metas[i]["title"],
                "__source": metas[i]["__source"],
                "parent_id": metas[i]["parent_id"],
                "score": similarity,
            })
        return out

    def count(self):
        return self.collection.count()


if __name__ == "__main__":
    import shutil
    test_dir = "/tmp/chroma_test"
    shutil.rmtree(test_dir, ignore_errors=True)

    store = VectorStore(persist_dir=test_dir, collection_name="test", reset=True)
    dummy_chunks = [
        {"chunk_id": "0_0", "url": "u1", "title": "t1", "__source": "s1", "parent_id": 0, "chunk_text": "diyabet insülin kan şekeri"},
        {"chunk_id": "1_0", "url": "u2", "title": "t2", "__source": "s2", "parent_id": 1, "chunk_text": "migren baş ağrısı tetikleyici"},
    ]
    dummy_vectors = np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
    store.upsert_chunks(dummy_chunks, dummy_vectors)
    print("count:", store.count())

    res = store.query(np.array([0.9, 0.1, 0.0]), top_k=2)
    for r in res:
        print(r["chunk_id"], round(r["score"], 3), r["chunk_text"])