Spaces:
Running
Running
first commit
Browse files- .env +12 -0
- .github/workflows/ci-build.yml +45 -0
- .gitignore +7 -0
- .streamlit/config.toml +5 -0
- Dockerfile +33 -0
- README.md +3 -1
- document_qa_engine.py +251 -0
- requirements.txt +31 -0
- streamlit_app.py +173 -0
.env
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
GROBID_URL=https://lfoppiano-grobid.hf.space
|
2 |
+
PROMPTLAYER_API_KEY=pl_89d0213d12cde8162f75c4da00e74094
|
3 |
+
|
4 |
+
HTTP_PROXY=
|
5 |
+
http_proxy=
|
6 |
+
HTTPS_PROXY=
|
7 |
+
https_proxy=
|
8 |
+
NO_PROXY=
|
9 |
+
no_proxy=
|
10 |
+
REQUEST_CA_BUNDLE=
|
11 |
+
REQUESTS_CA_BUNDLE=
|
12 |
+
CURL_CA_BUNDLE=
|
.github/workflows/ci-build.yml
ADDED
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: Build unstable
|
2 |
+
|
3 |
+
on: [push]
|
4 |
+
|
5 |
+
concurrency:
|
6 |
+
group: unstable
|
7 |
+
# cancel-in-progress: true
|
8 |
+
|
9 |
+
|
10 |
+
jobs:
|
11 |
+
build:
|
12 |
+
runs-on: ubuntu-latest
|
13 |
+
|
14 |
+
steps:
|
15 |
+
- uses: actions/checkout@v2
|
16 |
+
- name: Set up Python 3.9
|
17 |
+
uses: actions/setup-python@v2
|
18 |
+
with:
|
19 |
+
python-version: "3.9"
|
20 |
+
- name: Install dependencies
|
21 |
+
run: |
|
22 |
+
python -m pip install --upgrade pip
|
23 |
+
pip install --upgrade flake8 pytest pycodestyle
|
24 |
+
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
|
25 |
+
- name: Lint with flake8
|
26 |
+
run: |
|
27 |
+
# stop the build if there are Python syntax errors or undefined names
|
28 |
+
flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
|
29 |
+
# exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
|
30 |
+
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
|
31 |
+
# - name: Test with pytest
|
32 |
+
# run: |
|
33 |
+
# pytest
|
34 |
+
|
35 |
+
docker-build-documentqa:
|
36 |
+
needs: [build]
|
37 |
+
|
38 |
+
runs-on: self-hosted
|
39 |
+
|
40 |
+
steps:
|
41 |
+
- uses: actions/checkout@v2
|
42 |
+
- name: Build the Docker image
|
43 |
+
run: docker build . --file Dockerfile.qa --tag lfoppiano/documentqa:develop-latest
|
44 |
+
- name: Cleanup older than 24h images and containers
|
45 |
+
run: docker system prune --filter "until=24h" --force
|
.gitignore
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
.idea
|
2 |
+
.env
|
3 |
+
.env.docker
|
4 |
+
**/**/.chroma
|
5 |
+
grobid_magneto/reverse_qa/.chroma
|
6 |
+
exploration_llm
|
7 |
+
resources/db
|
.streamlit/config.toml
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[logger]
|
2 |
+
level = "info"
|
3 |
+
|
4 |
+
[browser]
|
5 |
+
gatherUsageStats = false
|
Dockerfile
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
FROM python:3.9-slim
|
2 |
+
|
3 |
+
WORKDIR /app
|
4 |
+
|
5 |
+
RUN apt-get update && apt-get install -y \
|
6 |
+
build-essential \
|
7 |
+
curl \
|
8 |
+
software-properties-common \
|
9 |
+
git \
|
10 |
+
&& rm -rf /var/lib/apt/lists/*
|
11 |
+
|
12 |
+
COPY requirements.txt .
|
13 |
+
|
14 |
+
RUN pip3 install -r requirements.txt --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host=files.pythonhosted.org
|
15 |
+
|
16 |
+
COPY grobid_magneto/ grobid_magneto
|
17 |
+
COPY commons/ commons
|
18 |
+
COPY resources/nims_proxy.cer .
|
19 |
+
COPY tiktoken_cache ./tiktoken_cache
|
20 |
+
COPY grobid_magneto/document_qa/.streamlit ./.streamlit
|
21 |
+
|
22 |
+
# extract version
|
23 |
+
COPY .git ./.git
|
24 |
+
RUN git rev-parse --short HEAD > revision.txt
|
25 |
+
RUN rm -rf ./.git
|
26 |
+
|
27 |
+
EXPOSE 8501
|
28 |
+
|
29 |
+
HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health
|
30 |
+
|
31 |
+
ENV PYTHONPATH "${PYTHONPATH}:."
|
32 |
+
|
33 |
+
ENTRYPOINT ["streamlit", "run", "document_qa/streamlit_app.py", "--server.port=8501", "--server.address=0.0.0.0"]
|
README.md
CHANGED
@@ -1 +1,3 @@
|
|
1 |
-
#
|
|
|
|
|
|
1 |
+
# DocumentIQA: Document Insight Question/Answer
|
2 |
+
|
3 |
+
Small demo for performing data extraction at document level using small context.
|
document_qa_engine.py
ADDED
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import copy
|
2 |
+
import os
|
3 |
+
from pathlib import Path
|
4 |
+
from typing import Union, Any
|
5 |
+
|
6 |
+
from grobid_client.grobid_client import GrobidClient
|
7 |
+
from langchain.chains import create_extraction_chain
|
8 |
+
from langchain.chains.question_answering import load_qa_chain
|
9 |
+
from langchain.prompts import SystemMessagePromptTemplate, HumanMessagePromptTemplate, ChatPromptTemplate
|
10 |
+
from langchain.retrievers import MultiQueryRetriever
|
11 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
12 |
+
from langchain.vectorstores import Chroma
|
13 |
+
from tqdm import tqdm
|
14 |
+
|
15 |
+
from commons.annotations_utils import GrobidProcessor
|
16 |
+
|
17 |
+
|
18 |
+
class DocumentQAEngine:
|
19 |
+
llm = None
|
20 |
+
qa_chain_type = None
|
21 |
+
embedding_function = None
|
22 |
+
embeddings_dict = {}
|
23 |
+
embeddings_map_from_md5 = {}
|
24 |
+
embeddings_map_to_md5 = {}
|
25 |
+
|
26 |
+
def __init__(self, llm, embedding_function, qa_chain_type="stuff", embeddings_root_path=None, grobid_url=None):
|
27 |
+
self.embedding_function = embedding_function
|
28 |
+
self.llm = llm
|
29 |
+
self.chain = load_qa_chain(llm, chain_type=qa_chain_type)
|
30 |
+
|
31 |
+
if embeddings_root_path is not None:
|
32 |
+
self.embeddings_root_path = embeddings_root_path
|
33 |
+
if not os.path.exists(embeddings_root_path):
|
34 |
+
os.makedirs(embeddings_root_path)
|
35 |
+
else:
|
36 |
+
self.load_embeddings(self.embeddings_root_path)
|
37 |
+
|
38 |
+
if grobid_url:
|
39 |
+
self.grobid_url = grobid_url
|
40 |
+
grobid_client = GrobidClient(
|
41 |
+
grobid_server=self.grobid_url,
|
42 |
+
batch_size=1000,
|
43 |
+
coordinates=["p"],
|
44 |
+
sleep_time=5,
|
45 |
+
timeout=60,
|
46 |
+
check_server=True
|
47 |
+
)
|
48 |
+
self.grobid_processor = GrobidProcessor(grobid_client)
|
49 |
+
|
50 |
+
def load_embeddings(self, embeddings_root_path: Union[str, Path]) -> None:
|
51 |
+
"""
|
52 |
+
Load the embeddings assuming they are all persisted and stored in a single directory.
|
53 |
+
The root path of the embeddings containing one data store for each document in each subdirectory
|
54 |
+
"""
|
55 |
+
|
56 |
+
embeddings_directories = [f for f in os.scandir(embeddings_root_path) if f.is_dir()]
|
57 |
+
|
58 |
+
if len(embeddings_directories) == 0:
|
59 |
+
print("No available embeddings")
|
60 |
+
return
|
61 |
+
|
62 |
+
for embedding_document_dir in embeddings_directories:
|
63 |
+
self.embeddings_dict[embedding_document_dir.name] = Chroma(persist_directory=embedding_document_dir.path,
|
64 |
+
embedding_function=self.embedding_function)
|
65 |
+
|
66 |
+
filename_list = list(Path(embedding_document_dir).glob('*.storage_filename'))
|
67 |
+
if filename_list:
|
68 |
+
filenam = filename_list[0].name.replace(".storage_filename", "")
|
69 |
+
self.embeddings_map_from_md5[embedding_document_dir.name] = filenam
|
70 |
+
self.embeddings_map_to_md5[filenam] = embedding_document_dir.name
|
71 |
+
|
72 |
+
print("Embedding loaded: ", len(self.embeddings_dict.keys()))
|
73 |
+
|
74 |
+
def get_loaded_embeddings_ids(self):
|
75 |
+
return list(self.embeddings_dict.keys())
|
76 |
+
|
77 |
+
def get_md5_from_filename(self, filename):
|
78 |
+
return self.embeddings_map_to_md5[filename]
|
79 |
+
|
80 |
+
def get_filename_from_md5(self, md5):
|
81 |
+
return self.embeddings_map_from_md5[md5]
|
82 |
+
|
83 |
+
def query_document(self, query: str, doc_id, output_parser=None, context_size=4, extraction_schema=None,
|
84 |
+
verbose=False) -> (
|
85 |
+
Any, str):
|
86 |
+
# self.load_embeddings(self.embeddings_root_path)
|
87 |
+
|
88 |
+
if verbose:
|
89 |
+
print(query)
|
90 |
+
|
91 |
+
response = self._run_query(doc_id, query, context_size=context_size)
|
92 |
+
response = response['output_text'] if 'output_text' in response else response
|
93 |
+
|
94 |
+
if verbose:
|
95 |
+
print(doc_id, "->", response)
|
96 |
+
|
97 |
+
if output_parser:
|
98 |
+
try:
|
99 |
+
return self._parse_json(response, output_parser), response
|
100 |
+
except Exception as oe:
|
101 |
+
print("Failing to parse the response", oe)
|
102 |
+
return None, response
|
103 |
+
elif extraction_schema:
|
104 |
+
try:
|
105 |
+
chain = create_extraction_chain(extraction_schema, self.llm)
|
106 |
+
parsed = chain.run(response)
|
107 |
+
return parsed, response
|
108 |
+
except Exception as oe:
|
109 |
+
print("Failing to parse the response", oe)
|
110 |
+
return None, response
|
111 |
+
else:
|
112 |
+
return None, response
|
113 |
+
|
114 |
+
def query_storage(self, query: str, doc_id, context_size=4):
|
115 |
+
documents = self._get_context(doc_id, query, context_size)
|
116 |
+
|
117 |
+
context_as_text = [doc.page_content for doc in documents]
|
118 |
+
return context_as_text
|
119 |
+
|
120 |
+
def _parse_json(self, response, output_parser):
|
121 |
+
system_message = "You are an useful assistant expert in materials science, physics, and chemistry " \
|
122 |
+
"that can process text and transform it to JSON."
|
123 |
+
human_message = """Transform the text between three double quotes in JSON.\n\n\n\n
|
124 |
+
{format_instructions}\n\nText: \"\"\"{text}\"\"\""""
|
125 |
+
|
126 |
+
system_message_prompt = SystemMessagePromptTemplate.from_template(system_message)
|
127 |
+
human_message_prompt = HumanMessagePromptTemplate.from_template(human_message)
|
128 |
+
|
129 |
+
prompt_template = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])
|
130 |
+
|
131 |
+
results = self.llm(
|
132 |
+
prompt_template.format_prompt(
|
133 |
+
text=response,
|
134 |
+
format_instructions=output_parser.get_format_instructions()
|
135 |
+
).to_messages()
|
136 |
+
)
|
137 |
+
parsed_output = output_parser.parse(results.content)
|
138 |
+
|
139 |
+
return parsed_output
|
140 |
+
|
141 |
+
def _run_query(self, doc_id, query, context_size=4):
|
142 |
+
relevant_documents = self._get_context(doc_id, query, context_size)
|
143 |
+
return self.chain.run(input_documents=relevant_documents, question=query)
|
144 |
+
# return self.chain({"input_documents": relevant_documents, "question": prompt_chat_template}, return_only_outputs=True)
|
145 |
+
|
146 |
+
def _get_context(self, doc_id, query, context_size=4):
|
147 |
+
db = self.embeddings_dict[doc_id]
|
148 |
+
retriever = db.as_retriever(search_kwargs={"k": context_size})
|
149 |
+
relevant_documents = retriever.get_relevant_documents(query)
|
150 |
+
return relevant_documents
|
151 |
+
|
152 |
+
def get_all_context_by_document(self, doc_id):
|
153 |
+
db = self.embeddings_dict[doc_id]
|
154 |
+
docs = db.get()
|
155 |
+
return docs['documents']
|
156 |
+
|
157 |
+
def _get_context_multiquery(self, doc_id, query, context_size=4):
|
158 |
+
db = self.embeddings_dict[doc_id].as_retriever(search_kwargs={"k": context_size})
|
159 |
+
multi_query_retriever = MultiQueryRetriever.from_llm(retriever=db, llm=self.llm)
|
160 |
+
relevant_documents = multi_query_retriever.get_relevant_documents(query)
|
161 |
+
return relevant_documents
|
162 |
+
|
163 |
+
def get_text_from_document(self, pdf_file_path, chunk_size=-1, perc_overlap=0.1, verbose=False):
|
164 |
+
if verbose:
|
165 |
+
print("File", pdf_file_path)
|
166 |
+
filename = Path(pdf_file_path).stem
|
167 |
+
structure = self.grobid_processor.process_structure(pdf_file_path)
|
168 |
+
|
169 |
+
biblio = structure['biblio']
|
170 |
+
biblio['filename'] = filename.replace(" ", "_")
|
171 |
+
|
172 |
+
if verbose:
|
173 |
+
print("Generating embeddings for:", hash, ", filename: ", filename)
|
174 |
+
|
175 |
+
texts = []
|
176 |
+
metadatas = []
|
177 |
+
ids = []
|
178 |
+
if chunk_size < 0:
|
179 |
+
for passage in structure['passages']:
|
180 |
+
biblio_copy = copy.copy(biblio)
|
181 |
+
if len(str.strip(passage['text'])) > 0:
|
182 |
+
texts.append(passage['text'])
|
183 |
+
|
184 |
+
biblio_copy['type'] = passage['type']
|
185 |
+
biblio_copy['section'] = passage['section']
|
186 |
+
biblio_copy['subSection'] = passage['subSection']
|
187 |
+
metadatas.append(biblio_copy)
|
188 |
+
|
189 |
+
ids.append(passage['passage_id'])
|
190 |
+
else:
|
191 |
+
document_text = " ".join([passage['text'] for passage in structure['passages']])
|
192 |
+
# text_splitter = CharacterTextSplitter.from_tiktoken_encoder(
|
193 |
+
text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
|
194 |
+
chunk_size=chunk_size,
|
195 |
+
chunk_overlap=chunk_size * perc_overlap
|
196 |
+
)
|
197 |
+
texts = text_splitter.split_text(document_text)
|
198 |
+
metadatas = [biblio for _ in range(len(texts))]
|
199 |
+
ids = [id for id, t in enumerate(texts)]
|
200 |
+
|
201 |
+
return texts, metadatas, ids
|
202 |
+
|
203 |
+
def create_memory_embeddings(self, pdf_path, doc_id=None):
|
204 |
+
texts, metadata, ids = self.get_text_from_document(pdf_path, chunk_size=500, perc_overlap=0.1)
|
205 |
+
if doc_id:
|
206 |
+
hash = doc_id
|
207 |
+
else:
|
208 |
+
hash = metadata[0]['hash']
|
209 |
+
|
210 |
+
self.embeddings_dict[hash] = Chroma.from_texts(texts, embedding=self.embedding_function, metadatas=metadata)
|
211 |
+
self.embeddings_root_path = None
|
212 |
+
|
213 |
+
return hash
|
214 |
+
|
215 |
+
def create_embeddings(self, pdfs_dir_path: Path):
|
216 |
+
input_files = []
|
217 |
+
for root, dirs, files in os.walk(pdfs_dir_path, followlinks=False):
|
218 |
+
for file_ in files:
|
219 |
+
if not (file_.lower().endswith(".pdf")):
|
220 |
+
continue
|
221 |
+
input_files.append(os.path.join(root, file_))
|
222 |
+
|
223 |
+
for input_file in tqdm(input_files, total=len(input_files), unit='document',
|
224 |
+
desc="Grobid + embeddings processing"):
|
225 |
+
|
226 |
+
md5 = self.calculate_md5(input_file)
|
227 |
+
data_path = os.path.join(self.embeddings_root_path, md5)
|
228 |
+
|
229 |
+
if os.path.exists(data_path):
|
230 |
+
print(data_path, "exists. Skipping it ")
|
231 |
+
continue
|
232 |
+
|
233 |
+
texts, metadata, ids = self.get_text_from_document(input_file, chunk_size=500, perc_overlap=0.1)
|
234 |
+
filename = metadata[0]['filename']
|
235 |
+
|
236 |
+
vector_db_document = Chroma.from_texts(texts,
|
237 |
+
metadatas=metadata,
|
238 |
+
embedding=self.embedding_function,
|
239 |
+
persist_directory=data_path)
|
240 |
+
vector_db_document.persist()
|
241 |
+
|
242 |
+
with open(os.path.join(data_path, filename + ".storage_filename"), 'w') as fo:
|
243 |
+
fo.write("")
|
244 |
+
|
245 |
+
@staticmethod
|
246 |
+
def calculate_md5(input_file: Union[Path, str]):
|
247 |
+
import hashlib
|
248 |
+
md5_hash = hashlib.md5()
|
249 |
+
with open(input_file, 'rb') as fi:
|
250 |
+
md5_hash.update(fi.read())
|
251 |
+
return md5_hash.hexdigest().upper()
|
requirements.txt
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
grobid-quantities-client
|
2 |
+
scikit-learn
|
3 |
+
Flask
|
4 |
+
openai
|
5 |
+
tqdm
|
6 |
+
textdistance[extras]
|
7 |
+
grobid-client-python
|
8 |
+
grobid_tei_xml
|
9 |
+
BeautifulSoup4
|
10 |
+
grobid-quantities-client
|
11 |
+
pymongo
|
12 |
+
pyyaml
|
13 |
+
waitress
|
14 |
+
apiflask
|
15 |
+
dateparser
|
16 |
+
tiktoken
|
17 |
+
pytest
|
18 |
+
langchain==0.0.244
|
19 |
+
streamlit
|
20 |
+
lxml
|
21 |
+
Beautifulsoup4
|
22 |
+
python-dotenv
|
23 |
+
lxml
|
24 |
+
Beautifulsoup4
|
25 |
+
python-dotenv
|
26 |
+
chromadb==0.3.25
|
27 |
+
promptlayer
|
28 |
+
watchdog
|
29 |
+
typing-inspect==0.8.0
|
30 |
+
typing_extensions==4.5.0
|
31 |
+
pydantic==1.10.8
|
streamlit_app.py
ADDED
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from datetime import datetime
|
3 |
+
from hashlib import blake2b
|
4 |
+
from tempfile import NamedTemporaryFile
|
5 |
+
|
6 |
+
import dotenv
|
7 |
+
import streamlit as st
|
8 |
+
from langchain.chat_models import PromptLayerChatOpenAI
|
9 |
+
from langchain.embeddings import OpenAIEmbeddings
|
10 |
+
|
11 |
+
from document_qa_engine import DocumentQAEngine
|
12 |
+
|
13 |
+
dotenv.load_dotenv(override=True)
|
14 |
+
|
15 |
+
if 'rqa' not in st.session_state:
|
16 |
+
st.session_state['rqa'] = None
|
17 |
+
|
18 |
+
if 'openai_key' not in st.session_state:
|
19 |
+
st.session_state['openai_key'] = False
|
20 |
+
|
21 |
+
if 'doc_id' not in st.session_state:
|
22 |
+
st.session_state['doc_id'] = None
|
23 |
+
|
24 |
+
if 'loaded_embeddings' not in st.session_state:
|
25 |
+
st.session_state['loaded_embeddings'] = None
|
26 |
+
|
27 |
+
if 'hash' not in st.session_state:
|
28 |
+
st.session_state['hash'] = None
|
29 |
+
|
30 |
+
if 'git_rev' not in st.session_state:
|
31 |
+
st.session_state['git_rev'] = "unknown"
|
32 |
+
if os.path.exists("revision.txt"):
|
33 |
+
with open("revision.txt", 'r') as fr:
|
34 |
+
from_file = fr.read()
|
35 |
+
st.session_state['git_rev'] = from_file if len(from_file) > 0 else "unknown"
|
36 |
+
|
37 |
+
if "messages" not in st.session_state:
|
38 |
+
st.session_state.messages = []
|
39 |
+
|
40 |
+
|
41 |
+
def new_file():
|
42 |
+
st.session_state['loaded_embeddings'] = None
|
43 |
+
st.session_state['doc_id'] = None
|
44 |
+
|
45 |
+
|
46 |
+
@st.cache_resource
|
47 |
+
def init_qa(openai_api_key):
|
48 |
+
chat = PromptLayerChatOpenAI(model_name="gpt-3.5-turbo",
|
49 |
+
temperature=0,
|
50 |
+
return_pl_id=True,
|
51 |
+
pl_tags=["streamlit", "chatgpt"],
|
52 |
+
openai_api_key=openai_api_key)
|
53 |
+
# chat = ChatOpenAI(model_name="gpt-3.5-turbo",
|
54 |
+
# temperature=0)
|
55 |
+
return DocumentQAEngine(chat, OpenAIEmbeddings(openai_api_key=openai_api_key), grobid_url=os.environ['GROBID_URL'])
|
56 |
+
|
57 |
+
|
58 |
+
def get_file_hash(fname):
|
59 |
+
hash_md5 = blake2b()
|
60 |
+
with open(fname, "rb") as f:
|
61 |
+
for chunk in iter(lambda: f.read(4096), b""):
|
62 |
+
hash_md5.update(chunk)
|
63 |
+
return hash_md5.hexdigest()
|
64 |
+
|
65 |
+
|
66 |
+
def play_old_messages():
|
67 |
+
if st.session_state['messages']:
|
68 |
+
for message in st.session_state['messages']:
|
69 |
+
if message['role'] == 'user':
|
70 |
+
with st.chat_message("user"):
|
71 |
+
st.markdown(message['content'])
|
72 |
+
elif message['role'] == 'assistant':
|
73 |
+
with st.chat_message("assistant"):
|
74 |
+
if mode == "LLM":
|
75 |
+
st.markdown(message['content'])
|
76 |
+
else:
|
77 |
+
st.write(message['content'])
|
78 |
+
|
79 |
+
|
80 |
+
has_openai_api_key = False
|
81 |
+
if not st.session_state['openai_key']:
|
82 |
+
openai_api_key = st.sidebar.text_input('OpenAI API Key')
|
83 |
+
if openai_api_key:
|
84 |
+
st.session_state['openai_key'] = has_openai_api_key = True
|
85 |
+
st.session_state['rqa'] = init_qa(openai_api_key)
|
86 |
+
else:
|
87 |
+
has_openai_api_key = st.session_state['openai_key']
|
88 |
+
|
89 |
+
st.title("π Document insight Q&A")
|
90 |
+
st.subheader("Upload a PDF document, ask questions, get insights.")
|
91 |
+
|
92 |
+
upload_col, radio_col, context_col = st.columns([7, 2, 2])
|
93 |
+
with upload_col:
|
94 |
+
uploaded_file = st.file_uploader("Upload an article", type=("pdf", "txt"), on_change=new_file,
|
95 |
+
disabled=not has_openai_api_key,
|
96 |
+
help="The file will be uploaded to Grobid, extracted the text and calculated "
|
97 |
+
"embeddings of each paragraph which are then stored to a Db for be picked "
|
98 |
+
"to answer specific questions. ")
|
99 |
+
with radio_col:
|
100 |
+
mode = st.radio("Query mode", ("LLM", "Embeddings"), disabled=not uploaded_file, index=0,
|
101 |
+
help="LLM will respond the question, Embedding will show the "
|
102 |
+
"paragraphs relevant to the question in the paper.")
|
103 |
+
with context_col:
|
104 |
+
context_size = st.slider("Context size", 3, 10, value=4,
|
105 |
+
help="Number of paragraphs to consider when answering a question",
|
106 |
+
disabled=not uploaded_file)
|
107 |
+
|
108 |
+
question = st.chat_input(
|
109 |
+
"Ask something about the article",
|
110 |
+
# placeholder="Can you give me a short summary?",
|
111 |
+
disabled=not uploaded_file
|
112 |
+
)
|
113 |
+
|
114 |
+
with st.sidebar:
|
115 |
+
st.header("Documentation")
|
116 |
+
st.write("""To upload the PDF file, click on the designated button and select the file from your device.""")
|
117 |
+
|
118 |
+
st.write(
|
119 |
+
"""After uploading, please wait for the PDF to be processed. You will see a spinner or loading indicator while the processing is in progress. Once the spinner stops, you can proceed to ask your questions.""")
|
120 |
+
|
121 |
+
st.markdown("**Revision number**: [" + st.session_state[
|
122 |
+
'git_rev'] + "](https://github.com/lfoppiano/grobid-magneto/commit/" + st.session_state['git_rev'] + ")")
|
123 |
+
|
124 |
+
st.header("Query mode (Advanced use)")
|
125 |
+
st.write(
|
126 |
+
"""By default, the mode is set to LLM (Language Model) which enables question/answering. You can directly ask questions related to the PDF content, and the system will provide relevant answers.""")
|
127 |
+
|
128 |
+
st.write(
|
129 |
+
"""If you switch the mode to "Embedding," the system will return specific paragraphs from the document that are semantically similar to your query. This mode focuses on providing relevant excerpts rather than answering specific questions.""")
|
130 |
+
|
131 |
+
if uploaded_file and not st.session_state.loaded_embeddings:
|
132 |
+
with st.spinner('Reading file, calling Grobid, and creating memory embeddings...'):
|
133 |
+
binary = uploaded_file.getvalue()
|
134 |
+
tmp_file = NamedTemporaryFile()
|
135 |
+
tmp_file.write(bytearray(binary))
|
136 |
+
# hash = get_file_hash(tmp_file.name)[:10]
|
137 |
+
st.session_state['doc_id'] = hash = st.session_state['rqa'].create_memory_embeddings(tmp_file.name)
|
138 |
+
st.session_state['loaded_embeddings'] = True
|
139 |
+
|
140 |
+
# timestamp = datetime.utcnow()
|
141 |
+
|
142 |
+
if st.session_state.loaded_embeddings and question and len(question) > 0 and st.session_state.doc_id:
|
143 |
+
for message in st.session_state.messages:
|
144 |
+
with st.chat_message(message["role"]):
|
145 |
+
if message['mode'] == "LLM":
|
146 |
+
st.markdown(message["content"])
|
147 |
+
elif message['mode'] == "Embeddings":
|
148 |
+
st.write(message["content"])
|
149 |
+
|
150 |
+
text_response = None
|
151 |
+
if mode == "Embeddings":
|
152 |
+
text_response = st.session_state['rqa'].query_storage(question, st.session_state.doc_id,
|
153 |
+
context_size=context_size)
|
154 |
+
elif mode == "LLM":
|
155 |
+
_, text_response = st.session_state['rqa'].query_document(question, st.session_state.doc_id,
|
156 |
+
context_size=context_size)
|
157 |
+
|
158 |
+
if not text_response:
|
159 |
+
st.error("Something went wrong. Contact Luca Foppiano ([email protected]) to report the issue.")
|
160 |
+
|
161 |
+
with st.chat_message("user"):
|
162 |
+
st.markdown(question)
|
163 |
+
st.session_state.messages.append({"role": "user", "mode": mode, "content": question})
|
164 |
+
|
165 |
+
with st.chat_message("assistant"):
|
166 |
+
if mode == "LLM":
|
167 |
+
st.markdown(text_response)
|
168 |
+
else:
|
169 |
+
st.write(text_response)
|
170 |
+
st.session_state.messages.append({"role": "assistant", "mode": mode, "content": text_response})
|
171 |
+
|
172 |
+
elif st.session_state.loaded_embeddings and st.session_state.doc_id:
|
173 |
+
play_old_messages()
|