File size: 2,420 Bytes
73a88f9 | 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 | import warnings
from dotenv import load_dotenv
import os
load_dotenv()
import streamlit as st
from PyPDF2 import PdfReader
import io
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.vectorstores import Chroma
from langchain.chains import RetrievalQA
from langchain.prompts import PromptTemplate
from langchain_openai import OpenAIEmbeddings
from langchain_openai import ChatOpenAI
# Suppress warnings
warnings.filterwarnings("ignore")
# Set up Streamlit interface
st.title("PDF Question Answering App")
# Initialize OpenAI model
model = ChatOpenAI(
model="gpt-3.5-turbo",
openai_api_key=os.getenv("OPENAI_API_KEY"),
temperature=0.2
)
# File uploader
uploaded_file = st.file_uploader("Upload a PDF file", type="pdf")
if uploaded_file is not None:
# Read PDF content
pdf_reader = PdfReader(io.BytesIO(uploaded_file.read()))
context = ""
for page_num in range(len(pdf_reader.pages)):
context += pdf_reader.pages[page_num].extract_text()
# Split text into chunks
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=10000,
chunk_overlap=1000
)
texts = text_splitter.split_text(context)
# Create embeddings using OpenAI
embeddings = OpenAIEmbeddings(
model="text-embedding-3-small",
openai_api_key=os.getenv("OPENAI_API_KEY")
)
# Create vector store and retriever
vector_index = Chroma.from_texts(
texts,
embeddings
).as_retriever(search_kwargs={"k": 5})
# Define prompt template
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.
{context}
Question: {question}
Helpful Answer:"""
QA_CHAIN_PROMPT = PromptTemplate.from_template(template)
# Create QA chain
qa_chain = RetrievalQA.from_chain_type(
model,
retriever=vector_index,
return_source_documents=True,
chain_type_kwargs={"prompt": QA_CHAIN_PROMPT}
)
# Question input
question = st.text_input("Enter your question about the PDF:")
if st.button("Get Answer"):
result = qa_chain({"query": question})
st.write("AI Response:")
st.write(result["result"]) |