Create app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485import warningsfrom dotenv import load_dotenvimport osload_dotenv()
import streamlit as stfrom PyPDF2 import PdfReaderimport iofrom langchain.text_splitter import RecursiveCharacterTextSplitterfrom langchain.vectorstores import Chromafrom langchain.chains import RetrievalQAfrom langchain.prompts import PromptTemplatefrom langchain_openai import OpenAIEmbeddingsfrom langchain_openai import ChatOpenAI
# Suppress warningswarnings.filterwarnings("ignore")
# Set up Streamlit interfacest.title("PDF Question Answering App")
# Initialize OpenAI modelmodel = ChatOpenAI( model="gpt-3.5-turbo", openai_api_key=os.getenv("OPENAI_API_KEY"), temperature=0.2)
# File uploaderuploaded_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"])app.pyAdded+85