Spaces:
Sleeping
Sleeping
Update src/rag_engine.py
Browse files8 unmodified lines91011121314151617181 unmodified line2021222324252638 unmodified lines65666768697071727374757677787980818283848586878889909192939495969798991002 unmodified lines1031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861 unmodified line1881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242 unmodified lines22722822923023123223313 unmodified lines2472482492502512522532545 unmodified lines2602612622632642652669 unmodified lines2762772782792802812828 unmodified linesfrom langchain_openai import OpenAIEmbeddingsfrom langchain_core.documents import Document# Internal Core Imports (The Good Stuff)from core.PineconeManager import PineconeManagerfrom core.AcronymManager import AcronymManagerfrom core.ChunkingManager import ChunkingManager, ChunkingStrategy # NEW: The Traffic Copfrom flashrank import Ranker, RerankRequest# CONFIGURATION1 unmodified lineUPLOAD_DIR = "source_documents"logger = logging.getLogger(__name__)# Initialize Reranker (Small, fast CPU model)try:reranker = Ranker(model_name="ms-marco-TinyBERT-L-2-v2", cache_dir="/tmp/flashrank_cache")except Exception as e:38 unmodified linesf.write(uploaded_file.getbuffer())return file_path# --- CORE LOGIC UPGRADE ---def process_file(file_path: str, chunking_strategy: str = "paragraph", embed_model_name: str = "all-mpnet-base-v2") -> List[Document]:"""Delegates processing to the robust ChunkingManager in src/core."""try:logger.info(f"Initializing ChunkingManager for {file_path} using {chunking_strategy}")# Initialize the Manager (it handles loading the right tokenizers/embedders)manager = ChunkingManager(embedding_model_name=embed_model_name)# Execute the robust processing pipeline# This now uses your ParagraphChunker.py or TokenChunker.py logic!chunks = manager.process_document(file_path=file_path,strategy=chunking_strategy,preprocess=True)# Handle case where process_document returns a Dict (e.g. hierarchical) vs Listif isinstance(chunks, dict):# For now, flatten dictionary returns if any (future proofing)flat_chunks = []for key, val in chunks.items():if isinstance(val, list): flat_chunks.extend(val)return flat_chunksreturn chunksexcept Exception as e:logger.error(f"Error processing {file_path}: {e}")return []2 unmodified linesif not PINECONE_KEY or not index_name: return False, "Pinecone Configuration Missing."try:# 1. Chunking (Delegated to Core)# Note: We pass the embedding model name so the chunker can initialize correctlydocs = process_file(file_path, chunking_strategy=strategy, embed_model_name=embed_model_name)if not docs: return False, "No valid chunks generated."# 2. Acronym Learningacronym_mgr = AcronymManager()for doc in docs:acronym_mgr.scan_text_for_acronyms(doc.page_content)# 3. Pinecone Managerpm = PineconeManager(PINECONE_KEY)# 4. SAFETY CHECKemb_fn = get_embedding_func(embed_model_name)test_vec = emb_fn.embed_query("test")model_dim = len(test_vec)if not pm.check_dimension_compatibility(index_name, model_dim):return False, f"Dimension Mismatch! Index '{index_name}' expects {model_dim}d vectors."# 5. PRE-EMPTIVE DELETEfilename = os.path.basename(file_path)pm.delete_file(index_name, filename, namespace=username)# 6. UPLOADvstore = pm.get_vectorstore(index_name, emb_fn, namespace=username)# Generate stable IDs using the metadata source or filenamecustom_ids = [f"{doc.metadata.get('source', filename)}_{i}" for i, doc in enumerate(docs)]vstore.add_documents(docs, ids=custom_ids)return True, f"Successfully updated {filename} ({len(docs)} chunks)."except Exception as e:logger.error(f"Ingestion failed: {e}")return False, str(e)def process_and_add_text(text: str, source_name: str, username: str, index_name: str, embed_model_name: str = None) -> Tuple[bool, str]:"""Ingests raw text (e.g. flattened summaries) using the ChunkingManager."""if not PINECONE_KEY or not index_name: return False, "Pinecone Configuration Missing."try:pm = PineconeManager(PINECONE_KEY)# 1. PRE-EMPTIVE DELETEpm.delete_file(index_name, source_name, namespace=username)# 2. SAVE BACKUP (Critical: ChunkingManager works best with files)user_docs_dir = os.path.join(UPLOAD_DIR, username)os.makedirs(user_docs_dir, exist_ok=True)backup_path = os.path.join(user_docs_dir, source_name)with open(backup_path, "w", encoding='utf-8') as f:f.write(text)# 3. CHUNK & PROCESS (Using the Manager on the backup file)# This ensures flattened text gets the same robust metadata/cleaning as regular fileslogger.info(f"Processing flattened text via ChunkingManager: {source_name}")manager = ChunkingManager(embedding_model_name=embed_model_name)# We use 'token' strategy for summaries usually, or 'paragraph' if preferreddocs = manager.process_document(backup_path, strategy="paragraph", preprocess=True)# Override metadata to ensure it's marked as generatedfor doc in docs:doc.metadata["file_type"] = "generated"doc.metadata["strategy"] = "flattened"# 4. UPLOADemb_fn = get_embedding_func(embed_model_name)vstore = pm.get_vectorstore(index_name, emb_fn, namespace=username)custom_ids = [f"{source_name}_{i}" for i in enumerate(docs)]vstore.add_documents(docs, ids=custom_ids)return True, f"Updated: {source_name} ({len(docs)} chunks)"except Exception as e:logger.error(f"Error indexing text: {e}")1 unmodified linedef search_knowledge_base(query: str, username: str, index_name: str, embed_model_name: str, k: int = 5, final_k: int = 5):if not PINECONE_KEY or not index_name: return []try:pm = PineconeManager(PINECONE_KEY)emb_fn = get_embedding_func(embed_model_name)vstore = pm.get_vectorstore(index_name, emb_fn, namespace=username)# 1. RETRIEVE BROADbroad_k = final_k * 3initial_docs = vstore.similarity_search(query, k=broad_k)if not initial_docs or not reranker:return initial_docs[:final_k]# 2. RERANKpassages = [{"id": str(i), "text": doc.page_content, "meta": doc.metadata}for i, doc in enumerate(initial_docs)]rerank_request = RerankRequest(query=query, passages=passages)ranked_results = reranker.rerank(rerank_request)# 3. SELECT TOP Kfinal_docs = []for res in ranked_results[:final_k]:meta = res.get("meta", {})meta["rerank_score"] = res.get("score")final_docs.append(Document(page_content=res["text"], metadata=meta))return final_docsexcept Exception as e:logger.error(f"Search failed: {e}")return []2 unmodified linesuser_dir = os.path.join(UPLOAD_DIR, username)file_path = os.path.join(user_dir, filename)if os.path.exists(file_path): os.remove(file_path)if PINECONE_KEY and index_name:try:pm = PineconeManager(PINECONE_KEY)13 unmodified linesids = pm.get_all_ids(index_name, username)if not ids: return False, "No data found in Pinecone."# Nuke local folder first to handle deletionsuser_dir = os.path.join(UPLOAD_DIR, username)if os.path.exists(user_dir): shutil.rmtree(user_dir)os.makedirs(user_dir, exist_ok=True)5 unmodified linesvectors = response.vectorsfor vec_id, vec_data in vectors.items():meta = vec_data.metadata or {}source = meta.get('source', 'unknown.txt')text = meta.get('text') or meta.get('page_content') or ''try:if "_" in vec_id: chunk_index = int(vec_id.rsplit('_', 1)[-1])9 unmodified linesfile_path = os.path.join(user_dir, filename)with open(file_path, "w", encoding="utf-8") as f: f.write(full_text)count += 1return True, f"Restored {count} files (Sorted) from Pinecone!"except Exception as e:logger.error(f"Cache rebuild failed: {e}")return False, str(e)8 unmodified lines91011121314151617181 unmodified line2021222324252638 unmodified lines65666768697071727374757677787980818283842 unmodified lines878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691 unmodified line1711721731741751761771781791801811821831841851861871881891901911921931941951961972 unmodified lines20020120220320420513 unmodified lines2192202212222232242252265 unmodified lines2322332342352362372382392402419 unmodified lines2512522532542552562578 unmodified linesfrom langchain_openai import OpenAIEmbeddingsfrom langchain_core.documents import Document# Internal Core Importsfrom core.PineconeManager import PineconeManagerfrom core.AcronymManager import AcronymManagerfrom core.ChunkingManager import ChunkingManagerfrom flashrank import Ranker, RerankRequest# CONFIGURATION1 unmodified lineUPLOAD_DIR = "source_documents"logger = logging.getLogger(__name__)# Initialize Rerankertry:reranker = Ranker(model_name="ms-marco-TinyBERT-L-2-v2", cache_dir="/tmp/flashrank_cache")except Exception as e:38 unmodified linesf.write(uploaded_file.getbuffer())return file_pathdef process_file(file_path: str, chunking_strategy: str = "paragraph", embed_model_name: str = "all-mpnet-base-v2") -> List[Document]:"""Delegates to ChunkingManager."""try:logger.info(f"Initializing ChunkingManager for {file_path} using {chunking_strategy}")manager = ChunkingManager(embedding_model_name=embed_model_name)chunks = manager.process_document(file_path=file_path, strategy=chunking_strategy, preprocess=True)if isinstance(chunks, dict):flat_chunks = []for key, val in chunks.items():if isinstance(val, list): flat_chunks.extend(val)return flat_chunksreturn chunksexcept Exception as e:logger.error(f"Error processing {file_path}: {e}")return []2 unmodified linesif not PINECONE_KEY or not index_name: return False, "Pinecone Configuration Missing."try:# 1. Chunkingdocs = process_file(file_path, chunking_strategy=strategy, embed_model_name=embed_model_name)if not docs: return False, "No valid chunks generated."# 2. METADATA SANITIZATION (The Fix for Pinecone IDs)# We enforce that 'source' is just the filename, stripping the path.clean_filename = os.path.basename(file_path)for doc in docs:doc.metadata["source"] = clean_filename# Remove any absolute paths that might have leaked into metadataif "file_path" in doc.metadata: del doc.metadata["file_path"]# 3. Acronym Learningacronym_mgr = AcronymManager()for doc in docs:acronym_mgr.scan_text_for_acronyms(doc.page_content)# 4. Pinecone Managerpm = PineconeManager(PINECONE_KEY)# 5. SAFETY CHECKemb_fn = get_embedding_func(embed_model_name)test_vec = emb_fn.embed_query("test")model_dim = len(test_vec)if not pm.check_dimension_compatibility(index_name, model_dim):return False, f"Dimension Mismatch! Index '{index_name}' expects {model_dim}d vectors."# 6. PRE-EMPTIVE DELETEpm.delete_file(index_name, clean_filename, namespace=username)# 7. UPLOADvstore = pm.get_vectorstore(index_name, emb_fn, namespace=username)# Now IDs will be "filename.txt_0", "filename.txt_1" etc.custom_ids = [f"{clean_filename}_{i}" for i, doc in enumerate(docs)]vstore.add_documents(docs, ids=custom_ids)return True, f"Successfully updated {clean_filename} ({len(docs)} chunks)."except Exception as e:logger.error(f"Ingestion failed: {e}")return False, str(e)def process_and_add_text(text: str, source_name: str, username: str, index_name: str, embed_model_name: str = None) -> Tuple[bool, str]:if not PINECONE_KEY or not index_name: return False, "Pinecone Configuration Missing."try:pm = PineconeManager(PINECONE_KEY)clean_source = os.path.basename(source_name)# 1. DELETE OLDpm.delete_file(index_name, clean_source, namespace=username)# 2. BACKUPuser_docs_dir = os.path.join(UPLOAD_DIR, username)os.makedirs(user_docs_dir, exist_ok=True)backup_path = os.path.join(user_docs_dir, clean_source)with open(backup_path, "w", encoding='utf-8') as f:f.write(text)# 3. CHUNKmanager = ChunkingManager(embedding_model_name=embed_model_name)docs = manager.process_document(backup_path, strategy="paragraph", preprocess=True)# 4. SANITIZE METADATAfor doc in docs:doc.metadata["source"] = clean_sourcedoc.metadata["file_type"] = "generated"doc.metadata["strategy"] = "flattened"# 5. UPLOADemb_fn = get_embedding_func(embed_model_name)vstore = pm.get_vectorstore(index_name, emb_fn, namespace=username)custom_ids = [f"{clean_source}_{i}" for i, _ in enumerate(docs)]vstore.add_documents(docs, ids=custom_ids)return True, f"Updated: {clean_source} ({len(docs)} chunks)"except Exception as e:logger.error(f"Error indexing text: {e}")1 unmodified linedef search_knowledge_base(query: str, username: str, index_name: str, embed_model_name: str, k: int = 5, final_k: int = 5):if not PINECONE_KEY or not index_name: return []try:pm = PineconeManager(PINECONE_KEY)emb_fn = get_embedding_func(embed_model_name)vstore = pm.get_vectorstore(index_name, emb_fn, namespace=username)broad_k = final_k * 3initial_docs = vstore.similarity_search(query, k=broad_k)if not initial_docs or not reranker:return initial_docs[:final_k]passages = [{"id": str(i), "text": doc.page_content, "meta": doc.metadata} for i, doc in enumerate(initial_docs)]rerank_request = RerankRequest(query=query, passages=passages)ranked_results = reranker.rerank(rerank_request)final_docs = []for res in ranked_results[:final_k]:meta = res.get("meta", {})meta["rerank_score"] = res.get("score")final_docs.append(Document(page_content=res["text"], metadata=meta))return final_docsexcept Exception as e:logger.error(f"Search failed: {e}")return []2 unmodified linesuser_dir = os.path.join(UPLOAD_DIR, username)file_path = os.path.join(user_dir, filename)if os.path.exists(file_path): os.remove(file_path)if PINECONE_KEY and index_name:try:pm = PineconeManager(PINECONE_KEY)13 unmodified linesids = pm.get_all_ids(index_name, username)if not ids: return False, "No data found in Pinecone."user_dir = os.path.join(UPLOAD_DIR, username)# We wipe it clean firstif os.path.exists(user_dir): shutil.rmtree(user_dir)os.makedirs(user_dir, exist_ok=True)5 unmodified linesvectors = response.vectorsfor vec_id, vec_data in vectors.items():meta = vec_data.metadata or {}# THE RESYNC FIX: Force basename to avoid "dir/dir/file" bugsraw_source = meta.get('source', 'unknown.txt')source = os.path.basename(raw_source)text = meta.get('text') or meta.get('page_content') or ''try:if "_" in vec_id: chunk_index = int(vec_id.rsplit('_', 1)[-1])9 unmodified linesfile_path = os.path.join(user_dir, filename)with open(file_path, "w", encoding="utf-8") as f: f.write(full_text)count += 1return True, f"Restored {count} files from Pinecone!"except Exception as e:logger.error(f"Cache rebuild failed: {e}")return False, str(e)
src/rag_engine.py+41-66