Spaces:
Build error
Build error
SHAMIL SHAHBAZ AWAN commited on
Update app.py
Browse files1 unmodified line23456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778791 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 installed# Load Hugging Face SecretsHUGGINGFACE_KEY = os.getenv("HUGGINGFACE_KEY") # Set in Hugging Face Spaces secret managerif 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 modelsembedder = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')# Pathsfile_path = "RagBaseApp/Atomic habits ( PDFDrive ).pdf"VECTORSTORE_FOLDER = "vectorstore"# Initialize FAISS vector storeif not os.path.exists(VECTORSTORE_FOLDER):os.makedirs(VECTORSTORE_FOLDER)vectorstore_path = os.path.join(VECTORSTORE_FOLDER, "index.faiss")if 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 filedef load_pdf_text(file_path):"""Extract text from a PDF file."""text = ""with pdfplumber.open(file_path) as pdf:for page in pdf.pages:text += page.extract_text()return textdef chunk_text(text, chunk_size=500, overlap=100):"""Split text into overlapping chunks."""chunks = []for i in range(0, len(text), chunk_size - overlap):chunks.append(text[i:i + chunk_size])return chunksif st.button("Process PDF"):st.info("Processing PDF document...")text = load_pdf_text(file_path)chunks = chunk_text(text)embeddings = embedder.encode(chunks, show_progress_bar=True)index.add(np.array(embeddings))faiss.write_index(index, vectorstore_path)st.success("PDF processed and vectorstore updated!")# User interfacest.title("Atomic Habits RAG Application")user_query = st.text_input("Enter your query:")if user_query:query_embedding = embedder.encode([user_query])distances, indices = index.search(np.array(query_embedding), k=5)retrieved_chunks = [chunks[idx] for idx in indices[0]]st.subheader("Retrieved Chunks")for chunk in retrieved_chunks:st.write(chunk)combined_input = " ".join(retrieved_chunks) + user_queryresponse = groq_client.generate(model="llama3-8b-8192", prompt=combined_input, max_tokens=200)st.subheader("Generated Response")st.write(response["text"])1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071 unmodified lineimport streamlit as stimport pdfplumberfrom sentence_transformers import SentenceTransformerimport faissimport numpy as npfrom groq import Client# Load Hugging Face SecretsHUGGINGFACE_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 the SentenceTransformer model for embedding generationembedder = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')# Define file path and vector store folderfile_path = "Atomic habits ( PDFDrive ).pdf" # File directly in the root directory of the appVECTORSTORE_FOLDER = "vectorstore"# 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())# Function to load text from PDFdef load_pdf_text(file_path):"""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):"""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# 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 filetext = load_pdf_text(file_path)# Chunk the text into smaller pieceschunks = chunk_text(text)# Generate embeddings for each chunkembeddings = embedder.encode(chunks, show_progress_bar=True)# Add the embeddings to the FAISS indexindex.add(np.array(embeddings))# Save the updated FAISS indexfaiss.write_index(index, vectorstore_path)st.success("Document processed and vector store updated!")# 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 queryquery_embedding = embedder.encode([user_query])# Perform the search on the FAISS indexdistances, indices = index.search(np.array(query_embedding), k=5)# Retrieve the most relevant chunks based on the indicesretrieved_chunks = [chunks[idx] for idx in indices[0]]# Display the retrieved chunksst.subheader("Retrieved Chunks")for chunk in retrieved_chunks:st.write(chunk)# Combine the retrieved chunks with the query and generate a response using Groqcombined_input = " ".join(retrieved_chunks) + user_queryresponse = groq_client.generate(model="llama3-8b-8192", prompt=combined_input, max_tokens=200)# Display the generated responsest.subheader("Generated Response")st.write(response["text"])
app.py+41-13