Spaces:
Sleeping
Sleeping
Update src/rag_engine.py
Browse files2 unmodified lines345678910111213141516171 unmodified line192021222324257 unmodified lines333435363738394041424344454647484950515253545556575859606112 unmodified lines74757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601613 unmodified lines1651661671681691701711 unmodified line17317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923019 unmodified lines25025125225325425511 unmodified lines2672682692702712722732742752762772 unmodified linesimport loggingfrom typing import List, Tuple, Optionalfrom huggingface_hub import snapshot_downloadfrom langchain_community.document_loaders import PyPDFLoader, TextLoader, UnstructuredWordDocumentLoader, UnstructuredPowerPointLoaderfrom langchain_text_splitters import RecursiveCharacterTextSplitterfrom langchain_huggingface import HuggingFaceEmbeddingsfrom langchain_openai import OpenAIEmbeddingsfrom langchain_community.vectorstores import Pinecone as LangchainPineconefrom langchain_core.documents import Documentfrom core.PineconeManager import PineconeManagerfrom core.AcronymManager import AcronymManagerfrom flashrank import Ranker, RerankRequest # NEW IMPORT# CONFIGURATIONPINECONE_KEY = os.getenv("PINECONE_API_KEY")1 unmodified linelogger = logging.getLogger(__name__)# Initialize Reranker (Small, fast CPU model)# Only initializes once when the app startstry:reranker = Ranker(model_name="ms-marco-TinyBERT-L-2-v2", cache_dir="/tmp/flashrank_cache")except Exception as e:7 unmodified linesif not os.getenv("OPENAI_API_KEY"): raise ValueError("OpenAI API Key not found.")return OpenAIEmbeddings(model=model_name)# CHECK 2: YOUR CUSTOM FINE-TUNE (Updated for Subfolders)elif "navy-custom-models" in model_name:logger.info(f"Downloading custom model from: {model_name}")# 1. Parse the repo and folder from your string# Input: "NavyDevilDoc/navy-custom-models/bge-finetuned"parts = model_name.split("/")# Repo ID is the first two parts: "NavyDevilDoc/navy-custom-models"repo_id = f"{parts[0]}/{parts[1]}"# Folder is the rest: "bge-finetuned"folder_name = parts[2]# 2. Download ONLY that folderstorage_path = snapshot_download(repo_id=repo_id,repo_type="model",allow_patterns=f"{folder_name}/*")# 3. Construct the local path to the inner folderlocal_model_path = os.path.join(storage_path, folder_name)# 4. Load from the local pathreturn HuggingFaceEmbeddings(model_name=local_model_path)# CHECK 3: Standard Public Models12 unmodified linesf.write(uploaded_file.getbuffer())return file_pathclass ParagraphChunker:def split_text(self, text):return [p.strip() for p in text.split('\n\n') if p.strip()]def process_file(file_path: str, chunking_strategy: str = "paragraph") -> List[Document]:ext = os.path.splitext(file_path)[1].lower()try:if ext == ".pdf": loader = PyPDFLoader(file_path)elif ext == ".txt": loader = TextLoader(file_path, encoding='utf-8')elif ext == ".docx": loader = UnstructuredWordDocumentLoader(file_path)elif ext == ".pptx": loader = UnstructuredPowerPointLoader(file_path)elif ext == ".md": loader = TextLoader(file_path, encoding='utf-8')else: return []raw_docs = loader.load()text = "\n\n".join([d.page_content for d in raw_docs])if chunking_strategy == "token":splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)chunks = splitter.create_documents([text])else:chunker = ParagraphChunker()texts = chunker.split_text(text)chunks = [Document(page_content=t) for t in texts]# Add metadatafilename = os.path.basename(file_path)for doc in chunks:doc.metadata["source"] = filenamedoc.metadata["strategy"] = chunking_strategyreturn chunksexcept Exception as e:logger.error(f"Error processing {file_path}: {e}")return []def search_knowledge_base(query: str, username: str, index_name: str, embed_model_name: str, k: int = 5, final_k: int = 5):"""Searches Pinecone with Reranking.1. Fetches 3x candidates (Top 15).2. Reranks using TinyBERT.3. Returns Top 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 BROAD (Fetch 3x what we need)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]# 2. RERANK (The Brain Upgrade)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)# 3. SELECT TOP Kfinal_docs = []for res in ranked_results[:final_k]:meta = res.get("meta", {})meta["rerank_score"] = res.get("score") # Useful for debuggingfinal_docs.append(Document(page_content=res["text"], metadata=meta))return final_docsexcept Exception as e:logger.error(f"Search failed: {e}")return []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 with a specific embedding model."""if not PINECONE_KEY or not index_name: return False, "Pinecone Configuration Missing."3 unmodified lines# 1. PRE-EMPTIVE DELETEpm.delete_file(index_name, source_name, namespace=username)# 2. SAVE 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, source_name)1 unmodified linewith open(backup_path, "w", encoding='utf-8') as f:f.write(text)# 3. UPLOAD (The Fix: Use the passed model name)emb_fn = get_embedding_func(embed_model_name)doc = Document(page_content=text,metadata={"source": source_name, "strategy": "flattened", "file_type": "generated"})vstore = pm.get_vectorstore(index_name, emb_fn, namespace=username)vstore.add_documents([doc], ids=[f"{source_name}_0"])return True, f"Updated: {source_name}"except Exception as e:logger.error(f"Error indexing text: {e}")return False, str(e)def ingest_file(file_path: str, username: str, index_name: str, embed_model_name: str = None, strategy: str = "paragraph") -> Tuple[bool, str]:if not PINECONE_KEY or not index_name: return False, "Pinecone Configuration Missing."try:# 1. Chunkingdocs = process_file(file_path, chunking_strategy=strategy)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)custom_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 delete_document(username: str, filename: str, index_name: str):user_dir = os.path.join(UPLOAD_DIR, username)19 unmodified linesids = pm.get_all_ids(index_name, username)if not ids: return False, "No data found in Pinecone."batch_size = 100reconstructed_files = {}for i in range(0, len(ids), batch_size):11 unmodified linesif source not in reconstructed_files: reconstructed_files[source] = []reconstructed_files[source].append((chunk_index, text))user_dir = os.path.join(UPLOAD_DIR, username)os.makedirs(user_dir, exist_ok=True)count = 0for filename, chunks in reconstructed_files.items():chunks.sort(key=lambda x: x[0]) # SORTING FIXfull_text = "\n\n".join([c[1] for c in chunks])file_path = os.path.join(user_dir, filename)with open(file_path, "w", encoding="utf-8") as f: f.write(full_text)2 unmodified lines3456789101112131415161718191 unmodified line2122232425267 unmodified lines3435363738394041424344454647484950515212 unmodified lines65666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471483 unmodified lines1521531541551561571581 unmodified line16016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622719 unmodified lines24724824925025125225325425525625711 unmodified lines2692702712722732742752762772 unmodified linesimport loggingfrom typing import List, Tuple, Optionalfrom huggingface_hub import snapshot_download# LangChain Importsfrom langchain_huggingface import HuggingFaceEmbeddingsfrom 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# CONFIGURATIONPINECONE_KEY = os.getenv("PINECONE_API_KEY")1 unmodified linelogger = 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:7 unmodified linesif not os.getenv("OPENAI_API_KEY"): raise ValueError("OpenAI API Key not found.")return OpenAIEmbeddings(model=model_name)# CHECK 2: YOUR CUSTOM FINE-TUNEelif "navy-custom-models" in model_name:logger.info(f"Downloading custom model from: {model_name}")parts = model_name.split("/")repo_id = f"{parts[0]}/{parts[1]}"folder_name = parts[2]storage_path = snapshot_download(repo_id=repo_id,repo_type="model",allow_patterns=f"{folder_name}/*")local_model_path = os.path.join(storage_path, folder_name)return HuggingFaceEmbeddings(model_name=local_model_path)# CHECK 3: Standard Public Models12 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 []def ingest_file(file_path: str, username: str, index_name: str, embed_model_name: str = "sentence-transformers/all-MiniLM-L6-v2", strategy: str = "paragraph") -> Tuple[bool, str]:if 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."3 unmodified lines# 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)1 unmodified linewith 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}")return False, str(e)def 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 []def delete_document(username: str, filename: str, index_name: str):user_dir = os.path.join(UPLOAD_DIR, username)19 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)batch_size = 100reconstructed_files = {}for i in range(0, len(ids), batch_size):11 unmodified linesif source not in reconstructed_files: reconstructed_files[source] = []reconstructed_files[source].append((chunk_index, text))count = 0for filename, chunks in reconstructed_files.items():chunks.sort(key=lambda x: x[0])full_text = "\n\n".join([c[1] for c in chunks])file_path = os.path.join(user_dir, filename)with open(file_path, "w", encoding="utf-8") as f: f.write(full_text)
src/rag_engine.py+118-118