Spaces:
Sleeping
Sleeping
Download backend/vector_store.py from codedawakening/cognitive-ai-tutor: direct link, hf CLI and curl.
- Browser
- Download file 6.83 kB
-
https://huggingface.co/spaces/codedawakening/cognitive-ai-tutor/resolve/main/backend/vector_store.py
- Command line
-
hf download hf://spaces/codedawakening/cognitive-ai-tutor/backend/vector_store.py
-
curl -L -o vector_store.py https://huggingface.co/spaces/codedawakening/cognitive-ai-tutor/resolve/main/backend/vector_store.py
6.83 kB
| import os | |
| from typing import List, Dict, Any | |
| import hashlib | |
| from datetime import datetime | |
| class VectorStoreManager: | |
| def __init__(self, persist_directory="./data/chroma_db", model_name="all-MiniLM-L6-v2"): | |
| self.persist_directory = persist_directory | |
| os.makedirs(persist_directory, exist_ok=True) | |
| # Initialize embedding model | |
| try: | |
| from sentence_transformers import SentenceTransformer | |
| self.embedding_model = SentenceTransformer(model_name) | |
| self.embedding_available = True | |
| print(f"β Loaded embedding model: {model_name}") | |
| except Exception as e: | |
| print(f"β οΈ Could not load embedding model: {e}") | |
| self.embedding_model = None | |
| self.embedding_available = False | |
| # Initialize ChromaDB with NEW API (correct way) | |
| try: | |
| import chromadb | |
| print("π Initializing ChromaDB with new API...") | |
| # NEW: Simple persistent client | |
| self.client = chromadb.PersistentClient(path=persist_directory) | |
| # Get or create collection | |
| self.collection = self.client.get_or_create_collection( | |
| name="knowledge_base", | |
| metadata={"hnsw:space": "cosine"} | |
| ) | |
| self.chroma_available = True | |
| print(f"β ChromaDB initialized successfully!") | |
| print(f"β Collection: {self.collection.name}") | |
| print(f"β Collection count: {self.collection.count()}") | |
| except Exception as e: | |
| print(f"β Error initializing vector store: {e}") | |
| import traceback | |
| traceback.print_exc() | |
| self.client = None | |
| self.collection = None | |
| self.chroma_available = False | |
| def is_ready(self) -> bool: | |
| return self.embedding_available and self.chroma_available | |
| def generate_embedding(self, text: str) -> List[float]: | |
| if not self.embedding_available: | |
| # Return dummy embedding | |
| return [0.1] * 384 | |
| try: | |
| return self.embedding_model.encode(text).tolist() | |
| except: | |
| return [0.1] * 384 | |
| def add_documents(self, documents: List[Dict]) -> bool: | |
| print(f"π₯ Attempting to add {len(documents)} documents to vector store") | |
| if not self.is_ready(): | |
| print("β Vector store not ready") | |
| return False | |
| try: | |
| ids = [] | |
| embeddings = [] | |
| metadatas = [] | |
| documents_text = [] | |
| for i, doc in enumerate(documents): | |
| text = doc.get("text", doc.get("content", "")) | |
| if not text or not text.strip(): | |
| print(f"β οΈ Document {i}: Empty text, skipping") | |
| continue | |
| # Truncate very long text | |
| if len(text) > 10000: | |
| text = text[:10000] | |
| print(f"π Document {i}: Truncated to 10,000 chars") | |
| # Generate unique ID | |
| doc_id = f"doc_{i}_{hashlib.md5(text.encode()).hexdigest()[:8]}" | |
| ids.append(doc_id) | |
| # Generate embedding | |
| embedding = self.generate_embedding(text) | |
| embeddings.append(embedding) | |
| # Store metadata | |
| metadata = doc.get("metadata", {}) | |
| metadata.update({ | |
| "text_length": len(text), | |
| "processed_at": datetime.now().isoformat(), | |
| "source": metadata.get("source", "unknown") | |
| }) | |
| metadatas.append(metadata) | |
| # Store text (truncated for display) | |
| display_text = text[:200] + "..." if len(text) > 200 else text | |
| documents_text.append(display_text) | |
| print(f"β Prepared document {i}: {len(text)} chars") | |
| if not ids: | |
| print("β No valid documents to add") | |
| return False | |
| print(f"π Adding {len(ids)} documents to collection...") | |
| # Add to collection using new API | |
| self.collection.add( | |
| ids=ids, | |
| embeddings=embeddings, | |
| metadatas=metadatas, | |
| documents=documents_text | |
| ) | |
| print(f"π Successfully added {len(ids)} documents to vector store!") | |
| print(f"π Total documents in collection: {self.collection.count()}") | |
| return True | |
| except Exception as e: | |
| print(f"β Error adding documents: {str(e)}") | |
| import traceback | |
| traceback.print_exc() | |
| return False | |
| def similarity_search(self, query: str, k: int = 3) -> List[Dict]: | |
| if not self.is_ready(): | |
| print("β οΈ Vector store not ready, returning simulated results") | |
| # Return simulated results | |
| return [ | |
| { | |
| "document": "This is a simulated response. Upload documents to get real answers.", | |
| "score": 0.95, | |
| "metadata": {"source": "demo", "type": "simulated"} | |
| } | |
| ] | |
| try: | |
| print(f"π Searching for: '{query}'") | |
| # Generate query embedding | |
| query_embedding = self.generate_embedding(query) | |
| # Query the collection | |
| results = self.collection.query( | |
| query_embeddings=[query_embedding], | |
| n_results=min(k, 5), | |
| include=["documents", "metadatas", "distances"] | |
| ) | |
| if not results["documents"] or not results["documents"][0]: | |
| print("β οΈ No results found in vector store") | |
| return [] | |
| formatted_results = [] | |
| for doc, meta, distance in zip( | |
| results["documents"][0], | |
| results["metadatas"][0], | |
| results["distances"][0] | |
| ): | |
| formatted_results.append({ | |
| "document": doc, | |
| "metadata": meta, | |
| "score": 1 - distance if distance else 0.9 | |
| }) | |
| print(f"β Found {len(formatted_results)} relevant documents") | |
| return formatted_results | |
| except Exception as e: | |
| print(f"β Search error: {str(e)}") | |
| import traceback | |
| traceback.print_exc() | |
| return [] |