File size: 4,698 Bytes
cfcca1d
 
 
 
 
 
 
 
 
3d8ce2d
 
834ae1c
b9e3f13
3d8ce2d
cfcca1d
 
 
798ece9
cfcca1d
 
 
 
 
 
 
798ece9
cfcca1d
798ece9
cfcca1d
 
67fdf41
 
 
 
 
7a9dcc4
 
 
785158e
 
 
7a9dcc4
 
 
 
352a5fd
06aea67
cfcca1d
 
f942880
cfcca1d
0878545
f3203dc
cfcca1d
3096731
f942880
cfcca1d
0ee6b9d
ba528d5
cfcca1d
 
 
050845c
cfcca1d
261e2dd
 
050845c
df9ddf2
cfcca1d
 
 
 
 
ef57dfe
 
cfcca1d
 
 
 
364b225
b9e3f13
 
352a5fd
0315eec
6dd4f19
f942880
0315eec
 
1e6b6ed
cfcca1d
364b225
 
 
cfcca1d
 
364b225
528fe2d
798ece9
364b225
 
 
 
8abd5b9
 
7c5b0a3
1e6b6ed
782c184
 
 
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import streamlit as st
from PyPDF2 import PdfReader
from langchain_text_splitters import RecursiveCharacterTextSplitter
import os
from langchain_google_genai import GoogleGenerativeAIEmbeddings
from langchain_community.vectorstores import Chroma
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain.chains.question_answering import load_qa_chain
from langchain.prompts import PromptTemplate
from langchain_community.document_loaders import PyPDFLoader
from langchain_chroma import Chroma
import tempfile
from langchain_cohere import CohereEmbeddings

st.set_page_config(page_title="Document Genie", layout="wide")

st.markdown("""
## PDFChat: Get instant insights from your PDF

This chatbot is built using the Retrieval-Augmented Generation (RAG) framework, leveraging Google's Generative AI model Gemini-PRO. It processes uploaded PDF documents by breaking them down into manageable chunks, creates a searchable vector store, and generates accurate answers to user queries. This advanced approach ensures high-quality, contextually relevant responses for an efficient and effective user experience.

### How It Works

Follow these simple steps to interact with the chatbot:

1. **Upload Your Document**: The system accepts a PDF file at one time, analyzing the content to provide comprehensive insights.

2. **Ask a Question**: After processing the document, ask any question related to the content of your uploaded document for a precise answer.
""")

#def get_pdf(pdf_docs):
#   loader = PyPDFLoader(pdf_docs)
#    docs = loader.load()
#    return docs

def get_pdf(uploaded_file):
    if uploaded_file :
        temp_file = "./temp.pdf"
        # Delete the existing temp.pdf file if it exists
        if os.path.exists(temp_file):
            os.remove(temp_file)
        with open(temp_file, "wb") as file:
            file.write(uploaded_file.getvalue())
            file_name = uploaded_file.name
    loader = PyPDFLoader(temp_file)
    docs = loader.load()
    return docs

def text_splitter(text):
    text_splitter = RecursiveCharacterTextSplitter(
    # Set a really small chunk size, just to show.
    chunk_size=100000,
    chunk_overlap=50000,
    separators=["\n\n","\n"," ",".",","])
    chunks=text_splitter.split_documents(text)
    return chunks

GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
COHERE_API_KEY = os.getenv("COHERE_API_KEY")

def get_conversational_chain():
    prompt_template = """
    Given the following extracted parts of a long document and a question, create a final answer.
    Answer the question as detailed as possible from the provided context, make sure to provide all the details, if the answer is not in
    provided context just say, "answer is not available in the context", and then ignore the context and add the answer from your knowledge like a simple llm prompt.
    Try to give atleast the basic information.Donot return blank answer.\n\n
    Make sure to understand the question and answer as per the question.
    If the question involves terms like detailed or explained , give answer which involves complete detail about the question.\n\n
    Context:\n {context}?\n
    Question: \n{question}\n

    Answer:
    """
    #model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3, google_api_key=GOOGLE_API_KEY)
    model = ChatGoogleGenerativeAI(model="gemini-1.0-pro-latest", temperature=0.3, google_api_key=GOOGLE_API_KEY)
    prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
    chain = load_qa_chain(model, chain_type="stuff", prompt=prompt)
    return chain

def embedding(chunk,query):
    #embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
    embeddings = CohereEmbeddings(model="embed-english-v3.0")
    db = Chroma.from_documents(chunk,embeddings)
    doc = db.similarity_search(query)
    print(doc)
    chain = get_conversational_chain()
    response = chain({"input_documents": doc, "question": query}, return_only_outputs=True)
    print(response)
    st.write("Reply: ", response["output_text"])


    

def main():
    st.header("Chat with your pdf💁")
    st.title("Menu:")
    pdf_docs = st.file_uploader("Upload your PDF File and Click on the Submit & Process Button", accept_multiple_files=False, key="pdf_uploader")
    query = st.text_input("Ask a Question from the PDF File", key="query")
    if st.button("Submit & Process", key="process_button"):
        with st.spinner("Processing..."):
            raw_text = get_pdf(pdf_docs)
            text_chunks = text_splitter(raw_text)
            if query:
                embedding(text_chunks,query)
            st.success("Done")


if __name__ == "__main__":
    main()