🧠 Personal Knowledge Navigator
Your AI-powered document search and Q&A assistant
# ============================================================================== # Personal Knowledge Navigator - No Cache Version # ============================================================================== # This Streamlit application loads a pre-built knowledge base and allows users # to query it without any caching mechanisms for maximum compatibility. import streamlit as st import faiss import numpy as np import pickle import os from typing import List, Optional, Tuple import json from datetime import datetime # Simple imports without cache configuration from sentence_transformers import SentenceTransformer import google.generativeai as genai # --- Page Configuration --- st.set_page_config( page_title="🧠 Knowledge Navigator", page_icon="🧠", layout="wide", initial_sidebar_state="expanded" ) # --- Custom CSS for Aesthetics --- st.markdown(""" """, unsafe_allow_html=True) # --- Constants --- DEFAULT_MODEL = 'all-MiniLM-L6-v2' KNOWLEDGE_BASE_DIR = 'knowledge_base' INDEX_FILE = 'faiss_index.index' CHUNKS_FILE = 'text_chunks.pkl' METADATA_FILE = 'metadata.json' TOP_K_DEFAULT = 5 # --- Session State Initialization --- def init_session_state(): """Initialize session state variables.""" if 'model_loaded' not in st.session_state: st.session_state.model_loaded = False if 'model' not in st.session_state: st.session_state.model = None if 'knowledge_base_loaded' not in st.session_state: st.session_state.knowledge_base_loaded = False if 'index' not in st.session_state: st.session_state.index = None if 'text_chunks' not in st.session_state: st.session_state.text_chunks = None if 'metadata' not in st.session_state: st.session_state.metadata = {} # --- Helper Functions --- def load_embedding_model(): """Load the sentence transformer model without caching.""" if st.session_state.model_loaded and st.session_state.model is not None: return st.session_state.model try: with st.spinner("🤖 Loading AI model (this may take a moment)..."): model = SentenceTransformer(DEFAULT_MODEL) st.session_state.model = model st.session_state.model_loaded = True return model except Exception as e: st.error(f"❌ Failed to load embedding model: {e}") st.session_state.model_loaded = False return None def load_knowledge_base(): """Load the pre-built knowledge base from files.""" if st.session_state.knowledge_base_loaded: return st.session_state.index, st.session_state.text_chunks, st.session_state.metadata try: index_path = os.path.join(KNOWLEDGE_BASE_DIR, INDEX_FILE) chunks_path = os.path.join(KNOWLEDGE_BASE_DIR, CHUNKS_FILE) metadata_path = os.path.join(KNOWLEDGE_BASE_DIR, METADATA_FILE) if not all(os.path.exists(p) for p in [index_path, chunks_path]): return None, None, {} with st.spinner("📚 Loading knowledge base..."): # Load FAISS index index = faiss.read_index(index_path) # Load text chunks with open(chunks_path, 'rb') as f: text_chunks = pickle.load(f) # Load metadata if available metadata = {} if os.path.exists(metadata_path): with open(metadata_path, 'r') as f: metadata = json.load(f) # Store in session state st.session_state.index = index st.session_state.text_chunks = text_chunks st.session_state.metadata = metadata st.session_state.knowledge_base_loaded = True return index, text_chunks, metadata except Exception as e: st.error(f"❌ Error loading knowledge base: {e}") return None, None, {} def save_uploaded_knowledge_base(index_file, chunks_file, metadata_file=None): """Save uploaded knowledge base files to the repository structure.""" try: os.makedirs(KNOWLEDGE_BASE_DIR, exist_ok=True) # Save index file if index_file: index_bytes = index_file.read() with open(os.path.join(KNOWLEDGE_BASE_DIR, INDEX_FILE), 'wb') as f: f.write(index_bytes) # Save chunks file if chunks_file: chunks_bytes = chunks_file.read() with open(os.path.join(KNOWLEDGE_BASE_DIR, CHUNKS_FILE), 'wb') as f: f.write(chunks_bytes) # Save metadata file if metadata_file: metadata_bytes = metadata_file.read() with open(os.path.join(KNOWLEDGE_BASE_DIR, METADATA_FILE), 'wb') as f: f.write(metadata_bytes) # Reset session state to reload new knowledge base st.session_state.knowledge_base_loaded = False st.session_state.index = None st.session_state.text_chunks = None st.session_state.metadata = {} return True except Exception as e: st.error(f"❌ Error saving knowledge base: {e}") return False def search_knowledge_base(query: str, model: SentenceTransformer, index: faiss.Index, text_chunks: List[str], k: int = TOP_K_DEFAULT) -> Tuple[List[str], List[float]]: """Search the knowledge base and return relevant chunks with scores.""" try: query_embedding = model.encode([query]) query_embedding = np.array(query_embedding).astype('float32') faiss.normalize_L2(query_embedding) scores, indices = index.search(query_embedding, min(k, len(text_chunks))) retrieved_chunks = [] chunk_scores = [] for score, idx in zip(scores[0], indices[0]): if idx < len(text_chunks): retrieved_chunks.append(text_chunks[idx]) chunk_scores.append(float(score)) return retrieved_chunks, chunk_scores except Exception as e: st.error(f"❌ Search error: {e}") return [], [] def generate_answer(question: str, context: str, api_key: str) -> str: """Generate answer using Gemini API.""" try: genai.configure(api_key=api_key) prompt = f""" You are an intelligent assistant with access to a curated knowledge base. Answer the question based ONLY on the provided context. Be comprehensive yet concise. If the answer isn't in the context, say "I couldn't find that information in the knowledge base." CONTEXT: {context} QUESTION: {question} ANSWER: """ model = genai.GenerativeModel('gemini-pro') response = model.generate_content(prompt) return response.text except Exception as e: return f"❌ Error generating answer: {str(e)}" # --- Main Application --- def main(): # Initialize session state init_session_state() # Header st.markdown("""
Your AI-powered document search and Q&A assistant
Text Chunks
Vectors
Please upload your knowledge base files in the "Upload Knowledge Base" tab
Or create one using our Google Colab notebook
Please wait for the model to load or click "Load Model" in the sidebar
{answer}
{chunk[:400]}{'...' if len(chunk) > 400 else ''}
Upload the files generated from your Google Colab notebook