RAG_PDF_CHAT / src /streamlit_app.py
MOHITH2001's picture
Update src/streamlit_app.py
ea172ab verified
Raw History Blame Contribute Delete
2.4 kB
import streamlit as st
import os
from dotenv import load_dotenv
from langchain_community.vectorstores import FAISS
from langchain_community.document_loaders import PyPDFLoader
from langchain_text_splitters import CharacterTextSplitter
# For free, we will use lightweight OpenAI or HuggingFace embeddings
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain.chains import RetrievalQA
import tempfile
import sys
import subprocess
# Temporary installation command
subprocess.check_call([sys.executable, "-m", "pip", "install", "langchain", "langchain-community", "langchain-google-genai", "faiss-cpu", "pypdf"])
st.set_page_config(page_title="RAG Document Chat",layout="wide")
st.title("Text only Pdf Assisstant")
st.write("Upload the document")
upload_file=st.sidebar.file_uploader("Upload the file",type="pdf")
@st.cache_resource
def load_embeddings():
return HuggingFaceEmbeddings(model_name="all-MiniLm-L6-v2")
gemini_api_key = st.secrets["GOOGLE_API_KEY"]
@st.cache_resource
def load_llm():
return ChatGoogleGenerativeAI(
model="gemini-1.5-flash",
temperature=0,
google_api_key=gemini_api_key # Pass the key here
)
llm = load_llm()
embeddings=load_embeddings()
if upload_file:
with tempfile.TemporaryDirectory() as temp_file:
temp_pdf_path=os.path.join(temp_file,"input.pdf")
with open(temp_pdf_path,"wb") as f:
f.write(upload_file.getvalue())
loader=PyPDFLoader(temp_pdf_path)
docs=loader.load()
text_splitter=CharacterTextSplitter(chunk_size=1000,chunk_overlap=200)
chunks=text_splitter.split_documents(docs)
@st.cache_resource
def vector_database(_doc,_embeddings):
return FAISS.from_documents(_doc,_embeddings)
vector_store=vector_database(chunks,embeddings)
st.success("PDF Proceeded ! U can ask the questions")
query=st.text_input("Ask your query")
if query and st.button("Search"):
with st.spinner("Searching...."):
qa_chain=RetrievalQA.from_chain_type(
llm=llm,
chain_type="stuff",
retreiver=vector_store.as_retriever()
)
response=qa_chain.invoke(query)
st.write(response["Result"])
else:
st.info("Please Provide the pdf")