perfaction commited on
Commit
73a88f9
·
verified ·
1 Parent(s): 4aa9eed

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +85 -0
app.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ from dotenv import load_dotenv
3
+ import os
4
+ load_dotenv()
5
+
6
+ import streamlit as st
7
+ from PyPDF2 import PdfReader
8
+ import io
9
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
10
+ from langchain.vectorstores import Chroma
11
+ from langchain.chains import RetrievalQA
12
+ from langchain.prompts import PromptTemplate
13
+ from langchain_openai import OpenAIEmbeddings
14
+ from langchain_openai import ChatOpenAI
15
+
16
+ # Suppress warnings
17
+ warnings.filterwarnings("ignore")
18
+
19
+ # Set up Streamlit interface
20
+ st.title("PDF Question Answering App")
21
+
22
+ # Initialize OpenAI model
23
+ model = ChatOpenAI(
24
+ model="gpt-3.5-turbo",
25
+ openai_api_key=os.getenv("OPENAI_API_KEY"),
26
+ temperature=0.2
27
+ )
28
+
29
+ # File uploader
30
+ uploaded_file = st.file_uploader("Upload a PDF file", type="pdf")
31
+
32
+ if uploaded_file is not None:
33
+ # Read PDF content
34
+ pdf_reader = PdfReader(io.BytesIO(uploaded_file.read()))
35
+ context = ""
36
+ for page_num in range(len(pdf_reader.pages)):
37
+ context += pdf_reader.pages[page_num].extract_text()
38
+
39
+ # Split text into chunks
40
+ text_splitter = RecursiveCharacterTextSplitter(
41
+ chunk_size=10000,
42
+ chunk_overlap=1000
43
+ )
44
+ texts = text_splitter.split_text(context)
45
+
46
+ # Create embeddings using OpenAI
47
+ embeddings = OpenAIEmbeddings(
48
+ model="text-embedding-3-small",
49
+ openai_api_key=os.getenv("OPENAI_API_KEY")
50
+ )
51
+
52
+ # Create vector store and retriever
53
+ vector_index = Chroma.from_texts(
54
+ texts,
55
+ embeddings
56
+ ).as_retriever(search_kwargs={"k": 5})
57
+
58
+ # Define prompt template
59
+ template = """Use the following pieces of context to answer the question at the end.
60
+ If you don't know the answer, just say that you don't know, don't try to make up an answer.
61
+ Keep the answer as concise as possible.
62
+ Always say "thanks for asking!" at the end of the answer.
63
+
64
+ {context}
65
+
66
+ Question: {question}
67
+ Helpful Answer:"""
68
+
69
+ QA_CHAIN_PROMPT = PromptTemplate.from_template(template)
70
+
71
+ # Create QA chain
72
+ qa_chain = RetrievalQA.from_chain_type(
73
+ model,
74
+ retriever=vector_index,
75
+ return_source_documents=True,
76
+ chain_type_kwargs={"prompt": QA_CHAIN_PROMPT}
77
+ )
78
+
79
+ # Question input
80
+ question = st.text_input("Enter your question about the PDF:")
81
+
82
+ if st.button("Get Answer"):
83
+ result = qa_chain({"query": question})
84
+ st.write("AI Response:")
85
+ st.write(result["result"])