Spaces:
Build error
Build error
Update app.py
Browse files123456734567828 unmodified lines373839434041424313 unmodified lines575859636061656263686465664 unmodified lines7172737980818283747576777879808182898391929384858687979888100101899091921059310794951099697985 unmodified lines104105106121107108109125126110111112113129114115116133117135136137138139140118119import osimport requestsimport numpy as npimport faissfrom PyPDF2 import PdfReaderfrom sentence_transformers import SentenceTransformerfrom transformers import AutoTokenizer, AutoModelimport torchfrom transformers import AutoTokenizer, AutoModelfrom PyPDF2 import PdfReaderfrom langchain.vectorstores import FAISSfrom langchain.chains import RetrievalQAfrom langchain.prompts import PromptTemplate28 unmodified lines data = response.json() return data["choices"][0]["message"]["content"]
# Initialize Groq API LLM with explicit API key# Initialize Groq API LLMllm = GroqLLM(api_key="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")
# Function to extract content from a public Google Drive PDF link13 unmodified lines text += page.extract_text() return text
# Function to create a FAISS vector store from the document content# Function to create a FAISS vector storedef create_vector_store(text): # Split the text into sentences and clean it sentences = [sentence.strip() for sentence in text.split(". ") if sentence.strip()]
# Use Hugging Face transformer model for embeddings model_name = "sentence-transformers/all-MiniLM-L6-v2" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModel.from_pretrained(model_name)4 unmodified lines embeddings = model(**tokens).last_hidden_state.mean(dim=1).squeeze().numpy() return embeddings
# Create a FAISS vector store with sentences and their embeddings vector_store = FAISS.from_texts( texts=sentences, embedding_function=embed ) embeddings = [embed(sentence) for sentence in sentences] text_embeddings = [(sentences[i], embeddings[i]) for i in range(len(sentences))] vector_store = FAISS.from_embeddings(text_embeddings)
return vector_store, sentences
# Streamlit appst.title("RAG-based Application with Focused Context")
# Predefined Google Drive linkdrive_url = "https://drive.google.com/file/d/1XvqA1OIssRs2gbmOtKFKj-02yQ5X2yg0/view?usp=sharing"
# Extract document contentst.write("Extracting content from the document...")text = extract_pdf_content(drive_url)
if text: st.write("Document extracted successfully!")
st.write("Creating vector store...") vector_store, sentences = create_vector_store(text)
st.write("Vector store created successfully!") st.write("Vector store created!")
query = st.text_input("Enter your query:") if query: st.write("Retrieving relevant context from the document...") retriever = vector_store.as_retriever() retriever.search_kwargs["k"] = 3 # Retrieve top 3 matches retriever.search_kwargs["k"] = 3
# Define a prompt template to guide LLM response generation prompt_template = PromptTemplate( template=""" Use the following context to answer the question:5 unmodified lines input_variables=["context", "question"] )
# Create a RetrievalQA chain qa_chain = RetrievalQA.from_chain_type( retriever=retriever, llm=llm, chain_type="stuff", # Use the default chain type return_source_documents=True # Optional chain_type="stuff", return_source_documents=True )
# Run the query through the QA chain and get the outputs response = qa_chain({"query": query}) answer = response["result"]
# Display the result st.write("Answer:", answer)
# Optionally display the source documents if "source_documents" in response: st.write("Source Documents:") for doc in response["source_documents"]: st.write(doc.page_content)else: st.error("Failed to extract content from the document.")app.py+13-36