ArjunSoniK commited on
Commit
e79047c
·
1 Parent(s): ada955d

pdf_QA_app

Browse files
Files changed (2) hide show
  1. app.py +61 -0
  2. requirements.txt +9 -0
app.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ from dotenv import load_dotenv
3
+ import os
4
+ load_dotenv()
5
+
6
+ from langchain import PromptTemplate
7
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
8
+ from langchain.vectorstores import Chroma
9
+ from langchain.chains import RetrievalQA
10
+ import streamlit as st
11
+ from PyPDF2 import PdfReader
12
+ from langchain_google_genai import GoogleGenerativeAIEmbeddings
13
+ from langchain_google_genai import ChatGoogleGenerativeAI
14
+ import io
15
+
16
+ warnings.filterwarnings("ignore")
17
+
18
+
19
+
20
+ st.title("PDF Question Answering App")
21
+
22
+ model = ChatGoogleGenerativeAI(model="gemini-1.5-pro",google_api_key=os.getenv("GEMINI_API_KEY"),
23
+ temperature=0.2,convert_system_message_to_human=True)
24
+
25
+ uploaded_file = st.file_uploader("Upload a PDF file", type="pdf")
26
+
27
+ if uploaded_file is not None:
28
+ pdf_reader = PdfReader(io.BytesIO(uploaded_file.read()))
29
+ context = ""
30
+ for page_num in range(len(pdf_reader.pages)):
31
+ context += pdf_reader.pages[page_num].extract_text()
32
+
33
+
34
+
35
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=10000, chunk_overlap=1000)
36
+ texts = text_splitter.split_text(context)
37
+
38
+ embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001",google_api_key=os.getenv("GEMINI_API_KEY"))
39
+
40
+ vector_index = Chroma.from_texts(texts, embeddings).as_retriever(search_kwargs={"k":5})
41
+
42
+
43
+
44
+ template = """Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer. Keep the answer as concise as possible. Always say "thanks for asking!" at the end of the answer.
45
+ {context}
46
+ Question: {question}
47
+ Helpful Answer:"""
48
+ QA_CHAIN_PROMPT = PromptTemplate.from_template(template)
49
+ qa_chain = RetrievalQA.from_chain_type(
50
+ model,
51
+ retriever=vector_index,
52
+ return_source_documents=True,
53
+ chain_type_kwargs={"prompt": QA_CHAIN_PROMPT},
54
+ )
55
+
56
+ question = st.text_input("Enter your question about the PDF:")
57
+
58
+ if st.button("Get Answer"):
59
+ result = qa_chain({"query": question})
60
+ st.write("AI Response:")
61
+ st.write(result["result"])
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ google-generativeai
2
+ chromadb
3
+ pypdf
4
+ langchain-google-genai
5
+ python-dotenv
6
+ streamlit
7
+ langchain
8
+ langchain-community
9
+ pypdf2