forked from Mrinank-Bhowmick/python-beginner-projects
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPDF_Reader.py
More file actions
68 lines (53 loc) · 2 KB
/
PDF_Reader.py
File metadata and controls
68 lines (53 loc) · 2 KB
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
import os
import re
import openai
from dotenv import load_dotenv
from langchain.document_loaders import PyPDFLoader
from langchain.chat_models import ChatOpenAI
from langchain.chains.summarize import load_summarize_chain
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.vectorstores import Chroma
from langchain.text_splitter import CharacterTextSplitter
from langchain.llms import OpenAI
from langchain.chains import ConversationalRetrievalChain
from langchain.memory import ConversationBufferMemory
load_dotenv()
openai_api_key = os.getenv("API_KEY")
openai.openai_api_key = openai_api_key
loader = PyPDFLoader("promptEngineering.pdf")
docs = loader.load_and_split()
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
documents = text_splitter.split_documents(docs)
embeddings = OpenAIEmbeddings()
vectorstore = Chroma.from_documents(documents, embeddings)
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
def originalText(docs):
text = str(docs)
regex = r"(Document)|(page_content=)|(metadata={'source':)|('page': \d})\)|(\\n)"
text = re.sub(regex, "", text)
return text
text = originalText(docs)
print("Text in pdf", text)
def summarizeText():
llm = ChatOpenAI(temperature=0, model_name="gpt-3.5-turbo-16k")
chain = load_summarize_chain(llm, chain_type="stuff")
return chain.run(docs)
summary = summarizeText()
print("Summary of text in pdf", summary)
def QA(query):
qa = ConversationalRetrievalChain.from_llm(
OpenAI(temperature=0), vectorstore.as_retriever(), memory=memory
)
query = "What is prompt engineering?"
result = qa({"question": query})
result = str(result["chat_history"][1])
result = result.split("content='")[1]
return result
print("INSTRUCTIONS:")
print('Enter the question you want to ask from pdf text OR press "-1" to STOP')
while True:
user_input = input("Enter your question: ")
if user_input == "-1":
break
else:
print(QA(user_input))