File size: 3,542 Bytes
a8da5c6
 
a3286b2
 
a8da5c6
a3286b2
a8da5c6
 
 
85b3a3f
a8da5c6
 
 
 
 
 
 
 
 
 
 
 
a3286b2
a8da5c6
a3286b2
a8da5c6
 
a3286b2
a8da5c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a3286b2
 
 
 
 
 
a8da5c6
a3286b2
 
 
 
 
 
 
 
85b3a3f
 
45377d4
 
 
a3286b2
 
 
 
a8da5c6
012600d
a8da5c6
4f711ce
012600d
4f711ce
012600d
4f711ce
df226f2
a3286b2
a8da5c6
 
 
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
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.chains import RetrievalQA 

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

st.markdown("""
## Document Genie: Get instant insights from your Documents

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 Documents**: The system accepts multiple PDF files at once, analyzing the content to provide comprehensive insights.

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

GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")

def get_conversational_chain():
    prompt_template = """
    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", don't provide the wrong answer\n\n
    Context:\n {context}?\n
    Question: \n{question}\n

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


def get_pdf(pdf_docs,query):
    text = ""
    for pdf in pdf_docs:
        pdf_reader = PdfReader(pdf)
        for page in pdf_reader.pages:
            text += page.extract_text()

    text_splitter = RecursiveCharacterTextSplitter(
    # Set a really small chunk size, just to show.
    chunk_size=500,
    chunk_overlap=20,
    separators=["\n\n","\n"," ",".",","])
    chunks=text_splitter.split_text(text)
    embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
    vector = Chroma.from_documents(chunk, embeddings)
    #docs = vector.similarity_search(query)
    docs = vector_store.as_retriever(search_type='similarity', search_kwargs={'k': 3}) 
    chain = get_conversational_chain()
    response = chain({"input_documents": docs, "question": query}, return_only_outputs=True)
    return response
  #st.write("Reply: ", response["output_text"])

def main():
    st.header("Chat with your pdf💁")

    question = st.text_input("Ask a Question from the PDF Files", key="query")

    pdf_docs = st.file_uploader("Upload your PDF Files and Click on the Submit & Process Button", accept_multiple_files=True, key="pdf_uploader")
    if question and st.button("Submit & Process", key="process_button"):
        with st.spinner("Processing..."):
            output = get_pdf(pdf_docs,question)
            st.success("Done")
            st.write("Reply: ", output["output_text"])             
    

if __name__ == "__main__":
    main()