Chandranshu Jain commited on
Commit
8f8a8f6
1 Parent(s): 13f22e4

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +93 -0
app.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from PyPDF2 import PdfReader
3
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
4
+ import os
5
+ from langchain_google_genai import GoogleGenerativeAIEmbeddings
6
+ from langchain_community.vectorstores import Chroma
7
+ from langchain_google_genai import ChatGoogleGenerativeAI
8
+ from langchain.chains.question_answering import load_qa_chain
9
+ from langchain.prompts import PromptTemplate
10
+
11
+
12
+ st.set_page_config(page_title="PDF CHATBOT", layout="wide")
13
+
14
+ st.markdown("""
15
+ ## Document Genie: Get instant insights from your Documents
16
+
17
+ 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.
18
+
19
+ ### How It Works
20
+
21
+ Follow these simple steps to interact with the chatbot:
22
+
23
+ 1. **Upload Your Documents**: The system accepts multiple PDF files at once, analyzing the content to provide comprehensive insights.
24
+
25
+ 2. **Ask a Question**: After processing the documents, ask any question related to the content of your uploaded documents for a precise answer.
26
+ """)
27
+
28
+ def get_pdf(pdf_docs):
29
+ text = ""
30
+ for pdf in pdf_docs:
31
+ pdf_reader = PdfReader(pdf)
32
+ for page in pdf_reader.pages:
33
+ text += page.extract_text()
34
+ return text
35
+
36
+ GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
37
+
38
+ def response_generate(text,query):
39
+ text_splitter = RecursiveCharacterTextSplitter(
40
+ # Set a really small chunk size, just to show.
41
+ chunk_size=500,
42
+ chunk_overlap=20,
43
+ separators=["\n\n","\n"," ",".",","])
44
+ chunks=text_splitter.split_text(text)
45
+ embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
46
+ db = Chroma.from_documents(chunks, embeddings)
47
+ # Create retriever interface
48
+ retriever = db.as_retriever()
49
+ qa = RetrievalQA.from_chain_type(llm = GoogleGenerativeAI(model="gemini-pro", google_api_key=GOOGLE_API_KEY ), chain_type='stuff', retriever=retriever)
50
+ return qa.run(query_text)
51
+
52
+ def get_conversational_chain():
53
+ prompt_template = """
54
+ Answer the question as detailed as possible from the provided context, make sure to provide all the details, if the answer is not in
55
+ provided context just say, "answer is not available in the context", don't provide the wrong answer\n\n
56
+ Context:\n {context}?\n
57
+ Question: \n{question}\n
58
+
59
+ Answer:
60
+ """
61
+ model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3, google_api_key=GOOGLE_API_KEY)
62
+ prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
63
+ chain = load_qa_chain(model, chain_type="stuff", prompt=prompt)
64
+ return chain
65
+
66
+ def user_call(query):
67
+ embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
68
+ db3 = Chroma(persist_directory="./chroma_db", embedding_function=embeddings)
69
+ docs = db3.similarity_search(query)
70
+ chain = get_conversational_chain()
71
+ response = chain({"input_documents": docs, "question": query}, return_only_outputs=True)
72
+ #st.write("Reply: ", response["output_text"])
73
+
74
+ def main():
75
+ st.header("Chat with your pdf💁")
76
+
77
+ query = st.text_input("Ask a Question from the PDF Files", key="query")
78
+
79
+ #if query:
80
+ # user_call(query)
81
+
82
+ st.title("Menu:")
83
+ pdf_docs = st.file_uploader("Upload your PDF Files and Click on the Submit & Process Button", accept_multiple_files=True, key="pdf_uploader")
84
+ if st.button("Submit & Process", key="process_button"):
85
+ with st.spinner("Processing..."):
86
+ raw_text = get_pdf(pdf_docs)
87
+ #text_chunks = text_splitter(raw_text)
88
+ response = response_generate(raw_text,query)
89
+ st.success("Done")
90
+ st.write("Reply: ", response)
91
+
92
+ if __name__ == "__main__":
93
+ main()