Spaces:
Configuration error
Configuration error
Commit ·
55eaac5
1
Parent(s): 4242631
Upload 4 files
Browse files- README.md +21 -11
- app.py +115 -0
- prompt_template.txt +14 -0
- requirements.txt +7 -0
README.md
CHANGED
|
@@ -1,12 +1,22 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
colorFrom: yellow
|
| 5 |
-
colorTo: gray
|
| 6 |
-
sdk: gradio
|
| 7 |
-
sdk_version: 3.50.0
|
| 8 |
-
app_file: app.py
|
| 9 |
-
pinned: false
|
| 10 |
-
---
|
| 11 |
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# PDF AI Assistant
|
| 2 |
+
This codebase is built for the purpose of interacting with PDF documents through a chat interface and getting instant answers to your queries.<br>
|
| 3 |
+
This project uses Langchain for question-answer retrieval, Qdrant Vector DB to store embeddings and Gradio for frontend demo.<br>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
+
This project is hosted on HuggingFace Spaces: [Live Demo of PDF AI Assistant](https://huggingface.co/spaces/heliosbrahma/ai-pdf-assistant).
|
| 6 |
+
|
| 7 |
+
## Steps:-
|
| 8 |
+
- Load PDF document using Langchain's PyMuPDFLoader and then split it into chunks of text using RecursiveCharacterTextSplitter
|
| 9 |
+
- Upload chunks of text into Qdrant Vector DB
|
| 10 |
+
- Retrieve the top 3 similar chunks for each query using RetrievalQA and using a custom prompt by PromptTemplate, answer those queries
|
| 11 |
+
|
| 12 |
+
## How to run it locally:-
|
| 13 |
+
To run this app locally, first clone this repo using `git clone`.<br><br>
|
| 14 |
+
Now, install all libraries by running the following command in the terminal:<br>
|
| 15 |
+
```python
|
| 16 |
+
pip install -r requirements.txt
|
| 17 |
+
```
|
| 18 |
+
<br><br>
|
| 19 |
+
Now, run the app from the terminal:<br>
|
| 20 |
+
```python
|
| 21 |
+
gradio app.py
|
| 22 |
+
```
|
app.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import warnings
|
| 2 |
+
|
| 3 |
+
warnings.filterwarnings("ignore")
|
| 4 |
+
import os, openai, cohere
|
| 5 |
+
import gradio as gr
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from langchain.document_loaders import PyMuPDFLoader
|
| 8 |
+
from langchain.docstore.document import Document
|
| 9 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 10 |
+
from langchain.embeddings import CohereEmbeddings
|
| 11 |
+
from langchain.vectorstores import Qdrant
|
| 12 |
+
from langchain.chat_models import ChatOpenAI
|
| 13 |
+
from langchain.prompts import PromptTemplate
|
| 14 |
+
from langchain.chains import RetrievalQA
|
| 15 |
+
|
| 16 |
+
COHERE_API_KEY = os.environ["COHERE_API_KEY"]
|
| 17 |
+
QDRANT_API_KEY = os.environ["QDRANT_API_KEY"]
|
| 18 |
+
QDRANT_CLUSTER_URL = os.environ["QDRANT_CLUSTER_URL"]
|
| 19 |
+
QDRANT_COLLECTION_NAME = os.environ["QDRANT_COLLECTION_NAME"]
|
| 20 |
+
OPENAI_API_KEY = os.environ["OPENAI_API_KEY"]
|
| 21 |
+
prompt_file = "prompt_template.txt"
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def pdf_loader(pdf_file):
|
| 25 |
+
yield "Extracting contents from PDF document..."
|
| 26 |
+
|
| 27 |
+
loader_mu = PyMuPDFLoader(pdf_file.name)
|
| 28 |
+
pages = loader_mu.load()
|
| 29 |
+
docs = []
|
| 30 |
+
for i in range(len(pages)):
|
| 31 |
+
raw_page_content = pages[i].page_content
|
| 32 |
+
metadata_source = {"source": str(i + 1)}
|
| 33 |
+
doc = Document(
|
| 34 |
+
page_content=pages[i].page_content, metadata={"source": str(i + 1)}
|
| 35 |
+
)
|
| 36 |
+
docs.append(doc)
|
| 37 |
+
|
| 38 |
+
yield "Splitting contents into chunks of text..."
|
| 39 |
+
text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
|
| 40 |
+
model_name="gpt-3.5-turbo",
|
| 41 |
+
chunk_size=1024,
|
| 42 |
+
chunk_overlap=64,
|
| 43 |
+
separators=["\n\n", "\n", " "],
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
docs_splitter = text_splitter.split_documents(docs)
|
| 47 |
+
cohere_embeddings = CohereEmbeddings(model="large", cohere_api_key=COHERE_API_KEY)
|
| 48 |
+
|
| 49 |
+
yield "Uploading chunks of text into Qdrant..."
|
| 50 |
+
qdrant = Qdrant.from_documents(
|
| 51 |
+
docs_splitter,
|
| 52 |
+
cohere_embeddings,
|
| 53 |
+
url=QDRANT_CLUSTER_URL,
|
| 54 |
+
prefer_grpc=True,
|
| 55 |
+
api_key=QDRANT_API_KEY,
|
| 56 |
+
collection_name=QDRANT_COLLECTION_NAME,
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
with open(prompt_file, "r") as file:
|
| 60 |
+
prompt_template = file.read()
|
| 61 |
+
|
| 62 |
+
PROMPT = PromptTemplate(
|
| 63 |
+
template=prompt_template, input_variables=["question", "context"]
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
llm = ChatOpenAI(
|
| 67 |
+
model_name="gpt-3.5-turbo", temperature=0, openai_api_key=OPENAI_API_KEY
|
| 68 |
+
)
|
| 69 |
+
global qa
|
| 70 |
+
qa = RetrievalQA.from_chain_type(
|
| 71 |
+
llm=llm,
|
| 72 |
+
chain_type="stuff",
|
| 73 |
+
retriever=qdrant.as_retriever(),
|
| 74 |
+
chain_type_kwargs={"prompt": PROMPT},
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
yield "Success! You can now click on the 'AI Assistant' tab to interact with your document"
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def chat(chat_history, query):
|
| 81 |
+
res = qa.run(query)
|
| 82 |
+
progressive_response = ""
|
| 83 |
+
|
| 84 |
+
for ele in "".join(res):
|
| 85 |
+
progressive_response += ele + ""
|
| 86 |
+
yield chat_history + [(query, progressive_response)]
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
with gr.Blocks() as demo:
|
| 90 |
+
gr.HTML(
|
| 91 |
+
"""<h1>Welcome to AI PDF Assistant</h1>"""
|
| 92 |
+
)
|
| 93 |
+
gr.Markdown(
|
| 94 |
+
"AI Assistant for PDF documents. Upload your pdf document, click 'Process PDF docs' and wait for success confirmation message.<br>"
|
| 95 |
+
"After success confirmation, click on the 'AI Assistant' tab to interact with your document.<br>"
|
| 96 |
+
"Type your query, and hit enter. Click on 'Clear Chat History' to delete all previous conversations."
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
with gr.Tab("Upload/Process PDF documents"):
|
| 100 |
+
text_input = gr.File(label="Upload PDF file", file_types=[".pdf"], type="file")
|
| 101 |
+
text_output = gr.Textbox(label="Status...")
|
| 102 |
+
text_button = gr.Button("Process PDF docs!")
|
| 103 |
+
text_button.click(pdf_loader, text_input, text_output)
|
| 104 |
+
|
| 105 |
+
with gr.Tab("AI Assistant"):
|
| 106 |
+
chatbot = gr.Chatbot()
|
| 107 |
+
query = gr.Textbox(
|
| 108 |
+
label="Type your query here, then press 'enter' and scroll up for response"
|
| 109 |
+
)
|
| 110 |
+
clear = gr.Button("Clear Chat History!")
|
| 111 |
+
query.submit(chat, [chatbot, query], chatbot)
|
| 112 |
+
clear.click(lambda: None, None, chatbot, queue=False)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
demo.queue().launch()
|
prompt_template.txt
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""You are an AI assistant chatting with a user.
|
| 2 |
+
Given the following extracted parts of a long document and a question, answer the question truthfully at the end.
|
| 3 |
+
If you don't know the answer, reply that 'Answer is not available in the document provided'. Don't try to make up an answer.
|
| 4 |
+
|
| 5 |
+
Example Format:
|
| 6 |
+
CONTEXT: context here
|
| 7 |
+
QUESTION: question here
|
| 8 |
+
ANSWER: answer here
|
| 9 |
+
|
| 10 |
+
Answer should be detailed and be based explicitly on information in the context provided. Begin!
|
| 11 |
+
|
| 12 |
+
CONTEXT: {context}
|
| 13 |
+
QUESTION: {question}
|
| 14 |
+
ANSWER:"""
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
langchain
|
| 2 |
+
openai
|
| 3 |
+
tiktoken
|
| 4 |
+
cohere
|
| 5 |
+
gradio
|
| 6 |
+
pymupdf
|
| 7 |
+
qdrant-client
|