Spaces:
Build error
Build error
SHAMIL SHAHBAZ AWAN commited on
Update app.py
Browse files1 unmodified line234556878911101112131415161817181921222021222325242526272829303132333435363537383739404142434445464745484950515253515455565758596061626364656667686970717273597475617677787980818283848586878889909192939495969798991001011021031041051061071 unmodified lineimport streamlit as stimport pdfplumberfrom sentence_transformers import SentenceTransformerfrom transformers import pipelineimport faissimport numpy as npfrom groq import Client # Assuming Groq API client is installedfrom groq import Client
# Load Hugging Face SecretsHUGGINGFACE_KEY = os.getenv("HUGGINGFACE_KEY") # Set in Hugging Face Spaces secret managerHUGGINGFACE_KEY = os.getenv("HUGGINGFACE_KEY")if not HUGGINGFACE_KEY: st.error("Hugging Face API token not found. Please set it in the Hugging Face Secrets.")
# Initialize Groq clientgroq_client = Client(api_key=HUGGINGFACE_KEY)
# Load models# Load the SentenceTransformer model for embedding generationembedder = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
# Pathsfile_path = "RagBaseApp/Atomic habits ( PDFDrive ).pdf"# Define file path and vector store folderfile_path = "Atomic habits ( PDFDrive ).pdf" # File directly in the root directory of the appVECTORSTORE_FOLDER = "vectorstore"
# Initialize FAISS vector store# Ensure the vector store folder existsif not os.path.exists(VECTORSTORE_FOLDER): os.makedirs(VECTORSTORE_FOLDER)
# Define the vector store pathvectorstore_path = os.path.join(VECTORSTORE_FOLDER, "index.faiss")
# Load or create FAISS indexif os.path.exists(vectorstore_path): index = faiss.read_index(vectorstore_path)else: index = faiss.IndexFlatL2(embedder.get_sentence_embedding_dimension())
# Load and process the PDF file# Function to load text from PDFdef load_pdf_text(file_path): """Extract text from a PDF file.""" """Extract text from the given PDF file.""" text = "" with pdfplumber.open(file_path) as pdf: for page in pdf.pages: text += page.extract_text() return text
# Function to chunk text into smaller piecesdef chunk_text(text, chunk_size=500, overlap=100): """Split text into overlapping chunks.""" """Chunk the text into overlapping chunks.""" chunks = [] for i in range(0, len(text), chunk_size - overlap): chunks.append(text[i:i + chunk_size]) return chunks
if st.button("Process PDF"):# Process the document and update vector storedef process_and_store_document(file_path): """Process the PDF document, chunk text, generate embeddings, and store them in FAISS.""" st.info("Processing PDF document...") # Extract text from the PDF file text = load_pdf_text(file_path) # Chunk the text into smaller pieces chunks = chunk_text(text) # Generate embeddings for each chunk embeddings = embedder.encode(chunks, show_progress_bar=True) # Add the embeddings to the FAISS index index.add(np.array(embeddings)) # Save the updated FAISS index faiss.write_index(index, vectorstore_path) st.success("PDF processed and vectorstore updated!") st.success("Document processed and vector store updated!")
# User interface# User interface for Streamlitst.title("Atomic Habits RAG Application")
# Button to trigger document processingif st.button("Process PDF"): process_and_store_document(file_path)
# Query input for the useruser_query = st.text_input("Enter your query:")
if user_query: # Generate embedding for the user query query_embedding = embedder.encode([user_query]) # Perform the search on the FAISS index distances, indices = index.search(np.array(query_embedding), k=5) # Retrieve the most relevant chunks based on the indices retrieved_chunks = [chunks[idx] for idx in indices[0]] # Display the retrieved chunks st.subheader("Retrieved Chunks") for chunk in retrieved_chunks: st.write(chunk) # Combine the retrieved chunks with the query and generate a response using Groq combined_input = " ".join(retrieved_chunks) + user_query response = groq_client.generate(model="llama3-8b-8192", prompt=combined_input, max_tokens=200) # Display the generated response st.subheader("Generated Response") st.write(response["text"])app.py+41-13