Update app.py
Browse files
app.py
CHANGED
|
@@ -1,142 +1,14 @@
|
|
| 1 |
-
from langchain.embeddings.openai import OpenAIEmbeddings
|
| 2 |
-
from langchain.text_splitter import RecursiveCharacterTextSplitter, CharacterTextSplitter
|
| 3 |
-
from langchain.vectorstores import Chroma
|
| 4 |
-
from langchain.chains import RetrievalQAWithSourcesChain
|
| 5 |
-
from langchain.memory import ConversationBufferWindowMemory
|
| 6 |
-
from langchain.chains import ConversationalRetrievalChain
|
| 7 |
-
from langchain.chat_models import ChatOpenAI
|
| 8 |
-
from langchain.prompts.chat import (
|
| 9 |
-
ChatPromptTemplate,
|
| 10 |
-
SystemMessagePromptTemplate,
|
| 11 |
-
HumanMessagePromptTemplate,
|
| 12 |
-
)
|
| 13 |
-
from langchain.document_loaders import PyPDFLoader
|
| 14 |
-
import os
|
| 15 |
-
import chainlit as cl
|
| 16 |
-
from langchain.prompts import PromptTemplate
|
| 17 |
-
|
| 18 |
-
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
|
| 19 |
|
| 20 |
-
|
| 21 |
-
If you don't know the answer, just say that you don't know, don't try to make up an answer.
|
| 22 |
-
ALWAYS return a "SOURCES" part in your answer.
|
| 23 |
-
The "SOURCES" part should be a reference to the source of the document from which you got your answer.
|
| 24 |
-
Example of your response should be:
|
| 25 |
-
```
|
| 26 |
-
The answer is foo
|
| 27 |
-
SOURCES: xyz
|
| 28 |
-
```
|
| 29 |
-
Begin!
|
| 30 |
-
----------------
|
| 31 |
-
{summaries}"""
|
| 32 |
-
messages = [
|
| 33 |
-
SystemMessagePromptTemplate.from_template(system_template),
|
| 34 |
-
HumanMessagePromptTemplate.from_template("{question}"),
|
| 35 |
-
]
|
| 36 |
-
prompt = ChatPromptTemplate.from_messages(messages)
|
| 37 |
-
chain_type_kwargs = {"prompt": prompt}
|
| 38 |
|
| 39 |
@cl.on_chat_start
|
| 40 |
-
async def
|
| 41 |
-
await cl.Avatar(
|
| 42 |
-
name="ChatPDF",
|
| 43 |
-
url="https://avatars.githubusercontent.com/u/128686189?s=400&u=a1d1553023f8ea0921fba0debbe92a8c5f840dd9&v=4",
|
| 44 |
-
# path = r'assets/ChatPDFAvatar.jpg'
|
| 45 |
-
).send()
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
@cl.langchain_factory(use_async=True)
|
| 49 |
-
async def init():
|
| 50 |
-
files = None
|
| 51 |
-
|
| 52 |
-
# Wait for the user to upload a file
|
| 53 |
-
while files == None:
|
| 54 |
-
files = await cl.AskFileMessage(
|
| 55 |
-
content="Hey, Welcome to ChatPDF!\n\nChatPDF is a smart, user-friendly tool that integrates state-of-the-art AI models with text extraction and embedding capabilities to create a unique, conversational interaction with your PDF documents.\n\nSimply upload your PDF, ask your questions, and ChatPDF will deliver the most relevant answers directly from your document.\n\nPlease upload a PDF file to begin!",max_size_mb=100, accept=["application/pdf"]
|
| 56 |
-
).send()
|
| 57 |
-
|
| 58 |
-
file = files[0]
|
| 59 |
-
|
| 60 |
-
msg = cl.Message(content=f'''Processing "{file.name}"...''')
|
| 61 |
-
await msg.send()
|
| 62 |
-
|
| 63 |
-
#
|
| 64 |
-
|
| 65 |
-
with open(os.path.join(file.name), "wb") as f:
|
| 66 |
-
f.write(file.content)
|
| 67 |
-
|
| 68 |
-
print(file.name)
|
| 69 |
|
| 70 |
-
|
| 71 |
-
pages = loader.load_and_split()
|
| 72 |
-
|
| 73 |
-
# add page split info
|
| 74 |
-
# Initialize a dictionary to keep track of duplicate page numbers
|
| 75 |
-
page_counts = {}
|
| 76 |
-
|
| 77 |
-
for document in pages:
|
| 78 |
-
page_number = document.metadata['page']
|
| 79 |
-
|
| 80 |
-
# If this is the first occurrence of this page number, initialize its count to 1
|
| 81 |
-
# Otherwise, increment the count for this page number
|
| 82 |
-
page_counts[page_number] = page_counts.get(page_number, 0) + 1
|
| 83 |
|
| 84 |
-
|
| 85 |
-
|
| 86 |
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
# Create a Chroma vector store
|
| 93 |
-
embeddings = OpenAIEmbeddings()
|
| 94 |
-
docsearch = await cl.make_async(Chroma.from_documents)(
|
| 95 |
-
pages, embeddings
|
| 96 |
-
)
|
| 97 |
-
|
| 98 |
-
# define memory
|
| 99 |
-
memory = ConversationBufferWindowMemory(
|
| 100 |
-
k=5,
|
| 101 |
-
memory_key='chat_history',
|
| 102 |
-
return_messages=True,
|
| 103 |
-
output_key='answer'
|
| 104 |
-
)
|
| 105 |
-
|
| 106 |
-
# Create a chain that uses the Chroma vector store
|
| 107 |
-
chain = ConversationalRetrievalChain.from_llm(
|
| 108 |
-
ChatOpenAI(temperature=0, model="gpt-3.5-turbo-16k", streaming=True),
|
| 109 |
-
chain_type="stuff",
|
| 110 |
-
retriever=docsearch.as_retriever(search_kwargs={'k':10}),
|
| 111 |
-
memory=memory,
|
| 112 |
-
return_source_documents=True,
|
| 113 |
-
)
|
| 114 |
-
|
| 115 |
-
# Save the metadata and texts in the user session
|
| 116 |
-
# cl.user_session.set("metadatas", metadatas)
|
| 117 |
-
cl.user_session.set("texts", pages)
|
| 118 |
-
|
| 119 |
-
# Let the user know that the system is ready
|
| 120 |
-
await msg.update(content=f''' "{file.name}" processed. You can now ask questions!''')
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
return chain
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
@cl.langchain_postprocess
|
| 127 |
-
async def process_response(res):
|
| 128 |
-
answer = res["answer"]
|
| 129 |
-
source_documents = res['source_documents']
|
| 130 |
-
content = [source_documents[i].page_content for i in range(len(source_documents))]
|
| 131 |
-
name = [source_documents[i].metadata['page_split_info'] for i in range(len(source_documents))]
|
| 132 |
-
source_elements = [
|
| 133 |
-
cl.Text(content=content[i], name=name[i]) for i in range(len(source_documents))
|
| 134 |
-
]
|
| 135 |
-
|
| 136 |
-
if source_documents:
|
| 137 |
-
answer += f"\n\nSources: {', '.join([source_documents[i].metadata['page_split_info'] for i in range(len(source_documents))])}"
|
| 138 |
-
else:
|
| 139 |
-
answer += "\n\nNo sources found"
|
| 140 |
-
|
| 141 |
-
await cl.Message(content=answer, elements=source_elements).send()
|
| 142 |
-
# await cl.Message(content=answer).send()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
|
| 2 |
+
import chainlit as cl
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
@cl.on_chat_start
|
| 5 |
+
async def on_chat_start():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
+
await cl.Message(content=f'Hello, How can I help you today?').send()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
+
@cl.on_message
|
| 10 |
+
async def on_message(message: cl.Message):
|
| 11 |
|
| 12 |
+
await cl.Message(
|
| 13 |
+
content=f"Received: {message.content}",
|
| 14 |
+
).send()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|