Download src/vector_store.py from Talayhan/task4.2: direct link, hf CLI and curl.
- Browser
- Download file 4.56 kB
-
https://huggingface.co/datasets/Talayhan/task4.2/resolve/main/src/vector_store.py
- Command line
-
hf download hf://datasets/Talayhan/task4.2/src/vector_store.py
-
curl -L -o vector_store.py https://huggingface.co/datasets/Talayhan/task4.2/resolve/main/src/vector_store.py
4.56 kB
| """ | |
| 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"]) | |