Spaces:
Sleeping
Sleeping
Download src/rag/vectorstore.py from FC-Bit/arkanum: direct link, hf CLI and curl.
- Browser
- Download file 5.86 kB
-
https://huggingface.co/spaces/FC-Bit/arkanum/resolve/main/src/rag/vectorstore.py
- Command line
-
hf download hf://spaces/FC-Bit/arkanum/src/rag/vectorstore.py
-
curl -L -o vectorstore.py https://huggingface.co/spaces/FC-Bit/arkanum/resolve/main/src/rag/vectorstore.py
5.86 kB
| """ | |
| Vektordatenbank (ChromaDB) | |
| ========================== | |
| Speichert und durchsucht Regeltext-Chunks via Embeddings. | |
| Verwendung: | |
| from src.rag.vectorstore import build_index, retrieve | |
| build_index(chunks, game="stalker") | |
| results = retrieve("Wie viele Aktionen hat ein Spieler?", game="stalker") | |
| """ | |
| import json | |
| import logging | |
| import os | |
| import chromadb | |
| import openai | |
| from dotenv import load_dotenv | |
| logger = logging.getLogger("arkanum") | |
| load_dotenv() | |
| CHROMA_BASE_DIR = "data/processed" | |
| EMBEDDING_MODEL = "text-embedding-3-small" | |
| COLLECTION_PREFIX = "rules" | |
| _openai_client = None | |
| def _get_openai_client() -> openai.OpenAI: | |
| global _openai_client | |
| if _openai_client is None: | |
| _openai_client = openai.OpenAI() | |
| return _openai_client | |
| def _embed(texts: list[str]) -> list[list[float]]: | |
| """Erzeugt Embeddings via OpenAI API.""" | |
| client = _get_openai_client() | |
| # OpenAI erlaubt max 2048 Inputs pro Request | |
| all_embeddings = [] | |
| batch_size = 512 | |
| for i in range(0, len(texts), batch_size): | |
| batch = texts[i : i + batch_size] | |
| resp = client.embeddings.create(model=EMBEDDING_MODEL, input=batch) | |
| all_embeddings.extend([d.embedding for d in resp.data]) | |
| return all_embeddings | |
| def _get_chroma_client(game: str) -> chromadb.ClientAPI: | |
| persist_dir = os.path.join(CHROMA_BASE_DIR, game, "chroma_db") | |
| os.makedirs(persist_dir, exist_ok=True) | |
| return chromadb.PersistentClient(path=persist_dir) | |
| def _get_collection(game: str) -> chromadb.Collection: | |
| client = _get_chroma_client(game) | |
| collection_name = f"{COLLECTION_PREFIX}_{game}" | |
| return client.get_or_create_collection( | |
| name=collection_name, | |
| metadata={"hnsw:space": "cosine"}, | |
| ) | |
| def build_index(chunks: list[dict], game: str) -> None: | |
| """ | |
| Baut den Vektorindex für ein Spiel auf. | |
| Args: | |
| chunks: Liste von Chunk-Dicts (aus src/ingestion/pdf.py) | |
| game: Spielname – bestimmt den Speicherort | |
| """ | |
| collection = _get_collection(game) | |
| client = _get_openai_client() | |
| # Bestehende Daten löschen für sauberen Rebuild | |
| existing = collection.count() | |
| if existing > 0: | |
| logger.info(f"Lösche {existing} bestehende Einträge...") | |
| all_ids = collection.get()["ids"] | |
| collection.delete(ids=all_ids) | |
| texts = [c["text"] for c in chunks] | |
| ids = [c["id"] for c in chunks] | |
| metadatas = [ | |
| { | |
| "source": c["source"], | |
| "page": c["page"], | |
| "section": c["section"], | |
| "game": c["game"], | |
| } | |
| for c in chunks | |
| ] | |
| # Embeddings in Batches erstellen mit Fortschritt | |
| logger.info(f"Erstelle Embeddings für {len(texts)} Chunks...") | |
| embeddings = [] | |
| embed_batch_size = 512 | |
| for i in range(0, len(texts), embed_batch_size): | |
| batch = texts[i : i + embed_batch_size] | |
| end = min(i + embed_batch_size, len(texts)) | |
| logger.info(f" Embeddings: {end}/{len(texts)} ({end * 100 // len(texts)}%)") | |
| resp = client.embeddings.create(model=EMBEDDING_MODEL, input=batch) | |
| embeddings.extend([d.embedding for d in resp.data]) | |
| # ChromaDB-Indexierung mit Fortschritt | |
| logger.info(f"Indexiere {len(ids)} Chunks in ChromaDB...") | |
| batch_size = 500 | |
| for i in range(0, len(ids), batch_size): | |
| end = min(i + batch_size, len(ids)) | |
| collection.add( | |
| ids=ids[i:end], | |
| embeddings=embeddings[i:end], | |
| documents=texts[i:end], | |
| metadatas=metadatas[i:end], | |
| ) | |
| logger.info(f" Indexiert: {end}/{len(ids)} ({end * 100 // len(ids)}%)") | |
| logger.info(f"✓ {len(ids)} Chunks indexiert in '{collection.name}'") | |
| return embeddings | |
| def load_cached_index(game: str) -> bool: | |
| """Lädt den Index aus der Cache-Datei. Returns True bei Erfolg.""" | |
| cache_path = os.path.join(CHROMA_BASE_DIR, game, "index_cache.json") | |
| if not os.path.exists(cache_path): | |
| return False | |
| logger.info(f"Lade Index aus Cache: {cache_path}") | |
| with open(cache_path, "r", encoding="utf-8") as f: | |
| cache = json.load(f) | |
| chunks = cache["chunks"] | |
| ids = [c["id"] for c in chunks] | |
| texts = [c["text"] for c in chunks] | |
| embeddings = [c["embedding"] for c in chunks] | |
| metadatas = [ | |
| { | |
| "source": c["source"], | |
| "page": c["page"], | |
| "section": c["section"], | |
| "game": c["game"], | |
| } | |
| for c in chunks | |
| ] | |
| collection = _get_collection(game) | |
| batch_size = 500 | |
| for i in range(0, len(ids), batch_size): | |
| end = min(i + batch_size, len(ids)) | |
| collection.add( | |
| ids=ids[i:end], | |
| embeddings=embeddings[i:end], | |
| documents=texts[i:end], | |
| metadatas=metadatas[i:end], | |
| ) | |
| logger.info(f" Cache-Import: {end}/{len(ids)} ({end * 100 // len(ids)}%)") | |
| logger.info(f"✓ {len(ids)} Chunks aus Cache geladen") | |
| return True | |
| def retrieve(query: str, game: str, k: int = 5) -> list[dict]: | |
| """ | |
| Sucht die k relevantesten Chunks für eine Frage. | |
| Args: | |
| query: Die Suchanfrage (Regelfrage des Nutzers) | |
| game: Spielname | |
| k: Anzahl zurückzugebender Chunks | |
| Returns: | |
| Liste der k relevantesten Chunks mit Metadaten und Score | |
| """ | |
| collection = _get_collection(game) | |
| query_embedding = _embed([query])[0] | |
| results = collection.query( | |
| query_embeddings=[query_embedding], | |
| n_results=k, | |
| include=["documents", "metadatas", "distances"], | |
| ) | |
| chunks = [] | |
| for i in range(len(results["ids"][0])): | |
| chunks.append({ | |
| "id": results["ids"][0][i], | |
| "text": results["documents"][0][i], | |
| "score": 1 - results["distances"][0][i], # Cosine similarity | |
| **results["metadatas"][0][i], | |
| }) | |
| return chunks | |