File size: 2,397 Bytes
86c93d1
a30a2b8
86c93d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea172ab
 
 
86c93d1
ea172ab
 
 
 
 
86c93d1
ea172ab
86c93d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a30a2b8
86c93d1
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75

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")