Spaces:
Running
Running
add missing dependencies
Browse files- document_qa_engine.py +0 -2
- grobid_processors.py +726 -0
- streamlit_app.py +3 -3
document_qa_engine.py
CHANGED
@@ -12,8 +12,6 @@ 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
|
|
|
12 |
from langchain.vectorstores import Chroma
|
13 |
from tqdm import tqdm
|
14 |
|
|
|
|
|
15 |
|
16 |
class DocumentQAEngine:
|
17 |
llm = None
|
grobid_processors.py
ADDED
@@ -0,0 +1,726 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
from collections import OrderedDict
|
3 |
+
from html import escape
|
4 |
+
from pathlib import Path
|
5 |
+
|
6 |
+
import dateparser
|
7 |
+
import grobid_tei_xml
|
8 |
+
from bs4 import BeautifulSoup
|
9 |
+
from tqdm import tqdm
|
10 |
+
|
11 |
+
from commons import supermat_tei_parser
|
12 |
+
|
13 |
+
|
14 |
+
def get_span_start(type, title=None):
|
15 |
+
title_ = ' title="' + title + '"' if title is not None else ""
|
16 |
+
return '<span class="label ' + type + '"' + title_ + '>'
|
17 |
+
|
18 |
+
|
19 |
+
def get_span_end():
|
20 |
+
return '</span>'
|
21 |
+
|
22 |
+
|
23 |
+
def get_rs_start(type):
|
24 |
+
return '<rs type="' + type + '">'
|
25 |
+
|
26 |
+
|
27 |
+
def get_rs_end():
|
28 |
+
return '</rs>'
|
29 |
+
|
30 |
+
|
31 |
+
def has_space_between_value_and_unit(quantity):
|
32 |
+
return quantity['offsetEnd'] < quantity['rawUnit']['offsetStart']
|
33 |
+
|
34 |
+
|
35 |
+
def decorate_text_with_annotations(text, spans, tag="span"):
|
36 |
+
"""
|
37 |
+
Decorate a text using spans, using two style defined by the tag:
|
38 |
+
- "span" generated HTML like annotated text
|
39 |
+
- "rs" generate XML like annotated text (format SuperMat)
|
40 |
+
"""
|
41 |
+
sorted_spans = list(sorted(spans, key=lambda item: item['offset_start']))
|
42 |
+
annotated_text = ""
|
43 |
+
start = 0
|
44 |
+
for span in sorted_spans:
|
45 |
+
type = span['type'].replace("<", "").replace(">", "")
|
46 |
+
if 'unit_type' in span and span['unit_type'] is not None:
|
47 |
+
type = span['unit_type'].replace(" ", "_")
|
48 |
+
annotated_text += escape(text[start: span['offset_start']])
|
49 |
+
title = span['quantified'] if 'quantified' in span else None
|
50 |
+
annotated_text += get_span_start(type, title) if tag == "span" else get_rs_start(type)
|
51 |
+
annotated_text += escape(text[span['offset_start']: span['offset_end']])
|
52 |
+
annotated_text += get_span_end() if tag == "span" else get_rs_end()
|
53 |
+
|
54 |
+
start = span['offset_end']
|
55 |
+
annotated_text += escape(text[start: len(text)])
|
56 |
+
return annotated_text
|
57 |
+
|
58 |
+
|
59 |
+
def extract_quantities(client, x_all, column_text_index):
|
60 |
+
# relevant_items = ['magnetic field strength', 'magnetic induction', 'maximum energy product',
|
61 |
+
# "magnetic flux density", "magnetic flux"]
|
62 |
+
# property_keywords = ['coercivity', 'remanence']
|
63 |
+
|
64 |
+
output_data = []
|
65 |
+
|
66 |
+
for idx, example in tqdm(enumerate(x_all), desc="extract quantities"):
|
67 |
+
text = example[column_text_index]
|
68 |
+
spans = GrobidQuantitiesProcessor(client).extract_quantities(text)
|
69 |
+
|
70 |
+
data_record = {
|
71 |
+
"id": example[0],
|
72 |
+
"filename": example[1],
|
73 |
+
"passage_id": example[2],
|
74 |
+
"text": text,
|
75 |
+
"spans": spans
|
76 |
+
}
|
77 |
+
|
78 |
+
output_data.append(data_record)
|
79 |
+
|
80 |
+
return output_data
|
81 |
+
|
82 |
+
|
83 |
+
def extract_materials(client, x_all, column_text_index):
|
84 |
+
output_data = []
|
85 |
+
|
86 |
+
for idx, example in tqdm(enumerate(x_all), desc="extract materials"):
|
87 |
+
text = example[column_text_index]
|
88 |
+
spans = GrobidMaterialsProcessor(client).extract_materials(text)
|
89 |
+
data_record = {
|
90 |
+
"id": example[0],
|
91 |
+
"filename": example[1],
|
92 |
+
"passage_id": example[2],
|
93 |
+
"text": text,
|
94 |
+
"spans": spans
|
95 |
+
}
|
96 |
+
|
97 |
+
output_data.append(data_record)
|
98 |
+
|
99 |
+
return output_data
|
100 |
+
|
101 |
+
|
102 |
+
def get_parsed_value_type(quantity):
|
103 |
+
if 'parsedValue' in quantity and 'structure' in quantity['parsedValue']:
|
104 |
+
return quantity['parsedValue']['structure']['type']
|
105 |
+
|
106 |
+
|
107 |
+
class BaseProcessor(object):
|
108 |
+
# def __init__(self, grobid_superconductors_client=None, grobid_quantities_client=None):
|
109 |
+
# self.grobid_superconductors_client = grobid_superconductors_client
|
110 |
+
# self.grobid_quantities_client = grobid_quantities_client
|
111 |
+
|
112 |
+
patterns = [
|
113 |
+
r'\d+e\d+'
|
114 |
+
]
|
115 |
+
|
116 |
+
def post_process(self, text):
|
117 |
+
output = text.replace('À', '-')
|
118 |
+
output = output.replace('¼', '=')
|
119 |
+
output = output.replace('þ', '+')
|
120 |
+
output = output.replace('Â', 'x')
|
121 |
+
output = output.replace('$', '~')
|
122 |
+
output = output.replace('−', '-')
|
123 |
+
output = output.replace('–', '-')
|
124 |
+
|
125 |
+
for pattern in self.patterns:
|
126 |
+
output = re.sub(pattern, lambda match: match.group().replace('e', '-'), output)
|
127 |
+
|
128 |
+
return output
|
129 |
+
|
130 |
+
|
131 |
+
class GrobidProcessor(BaseProcessor):
|
132 |
+
def __init__(self, grobid_client):
|
133 |
+
# super().__init__()
|
134 |
+
self.grobid_client = grobid_client
|
135 |
+
|
136 |
+
def process_structure(self, input_path):
|
137 |
+
pdf_file, status, text = self.grobid_client.process_pdf("processFulltextDocument",
|
138 |
+
input_path,
|
139 |
+
consolidate_header=True,
|
140 |
+
consolidate_citations=False,
|
141 |
+
segment_sentences=False,
|
142 |
+
tei_coordinates=False,
|
143 |
+
include_raw_citations=False,
|
144 |
+
include_raw_affiliations=False,
|
145 |
+
generateIDs=True)
|
146 |
+
|
147 |
+
if status != 200:
|
148 |
+
return
|
149 |
+
|
150 |
+
output_data = self.parse_grobid_xml(text)
|
151 |
+
output_data['filename'] = Path(pdf_file).stem.replace(".tei", "")
|
152 |
+
|
153 |
+
return output_data
|
154 |
+
|
155 |
+
def process_single(self, input_file):
|
156 |
+
doc = self.process_structure(input_file)
|
157 |
+
|
158 |
+
for paragraph in doc['passages']:
|
159 |
+
entities = self.process_single_text(paragraph['text'])
|
160 |
+
paragraph['spans'] = entities
|
161 |
+
|
162 |
+
return doc
|
163 |
+
|
164 |
+
def parse_grobid_xml(self, text):
|
165 |
+
output_data = OrderedDict()
|
166 |
+
|
167 |
+
doc_biblio = grobid_tei_xml.parse_document_xml(text)
|
168 |
+
biblio = {
|
169 |
+
"doi": doc_biblio.header.doi if doc_biblio.header.doi is not None else "",
|
170 |
+
"authors": ", ".join([author.full_name for author in doc_biblio.header.authors]),
|
171 |
+
"title": doc_biblio.header.title,
|
172 |
+
"hash": doc_biblio.pdf_md5
|
173 |
+
}
|
174 |
+
try:
|
175 |
+
year = dateparser.parse(doc_biblio.header.date).year
|
176 |
+
biblio["year"] = year
|
177 |
+
except:
|
178 |
+
pass
|
179 |
+
|
180 |
+
output_data['biblio'] = biblio
|
181 |
+
|
182 |
+
passages = []
|
183 |
+
output_data['passages'] = passages
|
184 |
+
# if biblio['title'] is not None and len(biblio['title']) > 0:
|
185 |
+
# passages.append({
|
186 |
+
# "text": self.post_process(biblio['title']),
|
187 |
+
# "type": "paragraph",
|
188 |
+
# "section": "<header>",
|
189 |
+
# "subSection": "<title>",
|
190 |
+
# "passage_id": "title0"
|
191 |
+
# })
|
192 |
+
|
193 |
+
if doc_biblio.abstract is not None and len(doc_biblio.abstract) > 0:
|
194 |
+
passages.append({
|
195 |
+
"text": self.post_process(doc_biblio.abstract),
|
196 |
+
"type": "paragraph",
|
197 |
+
"section": "<header>",
|
198 |
+
"subSection": "<abstract>",
|
199 |
+
"passage_id": "abstract0"
|
200 |
+
})
|
201 |
+
|
202 |
+
soup = BeautifulSoup(text, 'xml')
|
203 |
+
text_blocks_body = get_children_body(soup, verbose=False)
|
204 |
+
|
205 |
+
passages.extend([
|
206 |
+
{
|
207 |
+
"text": self.post_process(''.join(text for text in sentence.find_all(text=True) if
|
208 |
+
text.parent.name != "ref" or (
|
209 |
+
text.parent.name == "ref" and text.parent.attrs[
|
210 |
+
'type'] != 'bibr'))),
|
211 |
+
"type": "paragraph",
|
212 |
+
"section": "<body>",
|
213 |
+
"subSection": "<paragraph>",
|
214 |
+
"passage_id": str(paragraph_id) + str(sentence_id)
|
215 |
+
}
|
216 |
+
for paragraph_id, paragraph in enumerate(text_blocks_body) for
|
217 |
+
sentence_id, sentence in enumerate(paragraph)
|
218 |
+
])
|
219 |
+
|
220 |
+
text_blocks_figures = get_children_figures(soup, verbose=False)
|
221 |
+
|
222 |
+
passages.extend([
|
223 |
+
{
|
224 |
+
"text": self.post_process(''.join(text for text in sentence.find_all(text=True) if
|
225 |
+
text.parent.name != "ref" or (
|
226 |
+
text.parent.name == "ref" and text.parent.attrs[
|
227 |
+
'type'] != 'bibr'))),
|
228 |
+
"type": "paragraph",
|
229 |
+
"section": "<body>",
|
230 |
+
"subSection": "<figure>",
|
231 |
+
"passage_id": str(paragraph_id) + str(sentence_id)
|
232 |
+
}
|
233 |
+
for paragraph_id, paragraph in enumerate(text_blocks_figures) for
|
234 |
+
sentence_id, sentence in enumerate(paragraph)
|
235 |
+
])
|
236 |
+
|
237 |
+
return output_data
|
238 |
+
|
239 |
+
|
240 |
+
class GrobidQuantitiesProcessor(BaseProcessor):
|
241 |
+
def __init__(self, grobid_quantities_client):
|
242 |
+
self.grobid_quantities_client = grobid_quantities_client
|
243 |
+
|
244 |
+
def extract_quantities(self, text):
|
245 |
+
status, result = self.grobid_quantities_client.process_text(text.strip())
|
246 |
+
|
247 |
+
if status != 200:
|
248 |
+
result = {}
|
249 |
+
|
250 |
+
spans = []
|
251 |
+
|
252 |
+
if 'measurements' in result:
|
253 |
+
found_measurements = self.parse_measurements_output(result)
|
254 |
+
|
255 |
+
for m in found_measurements:
|
256 |
+
item = {
|
257 |
+
"text": text[m['offset_start']:m['offset_end']],
|
258 |
+
'offset_start': m['offset_start'],
|
259 |
+
'offset_end': m['offset_end']
|
260 |
+
}
|
261 |
+
|
262 |
+
if 'raw' in m and m['raw'] != item['text']:
|
263 |
+
item['text'] = m['raw']
|
264 |
+
|
265 |
+
if 'quantified_substance' in m:
|
266 |
+
item['quantified'] = m['quantified_substance']
|
267 |
+
|
268 |
+
if 'type' in m:
|
269 |
+
item["unit_type"] = m['type']
|
270 |
+
|
271 |
+
item['type'] = 'property'
|
272 |
+
# if 'raw_value' in m:
|
273 |
+
# item['raw_value'] = m['raw_value']
|
274 |
+
|
275 |
+
spans.append(item)
|
276 |
+
|
277 |
+
return spans
|
278 |
+
|
279 |
+
@staticmethod
|
280 |
+
def parse_measurements_output(result):
|
281 |
+
measurements_output = []
|
282 |
+
|
283 |
+
for measurement in result['measurements']:
|
284 |
+
type = measurement['type']
|
285 |
+
measurement_output_object = {}
|
286 |
+
quantity_type = None
|
287 |
+
has_unit = False
|
288 |
+
parsed_value_type = None
|
289 |
+
|
290 |
+
if 'quantified' in measurement:
|
291 |
+
if 'normalizedName' in measurement['quantified']:
|
292 |
+
quantified_substance = measurement['quantified']['normalizedName']
|
293 |
+
measurement_output_object["quantified_substance"] = quantified_substance
|
294 |
+
|
295 |
+
if 'measurementOffsets' in measurement:
|
296 |
+
measurement_output_object["offset_start"] = measurement["measurementOffsets"]['start']
|
297 |
+
measurement_output_object["offset_end"] = measurement["measurementOffsets"]['end']
|
298 |
+
else:
|
299 |
+
# If there are no offsets we skip the measurement
|
300 |
+
continue
|
301 |
+
|
302 |
+
# if 'measurementRaw' in measurement:
|
303 |
+
# measurement_output_object['raw_value'] = measurement['measurementRaw']
|
304 |
+
|
305 |
+
if type == 'value':
|
306 |
+
quantity = measurement['quantity']
|
307 |
+
|
308 |
+
parsed_value = GrobidQuantitiesProcessor.get_parsed(quantity)
|
309 |
+
if parsed_value:
|
310 |
+
measurement_output_object['parsed'] = parsed_value
|
311 |
+
|
312 |
+
normalized_value = GrobidQuantitiesProcessor.get_normalized(quantity)
|
313 |
+
if normalized_value:
|
314 |
+
measurement_output_object['normalized'] = normalized_value
|
315 |
+
|
316 |
+
raw_value = GrobidQuantitiesProcessor.get_raw(quantity)
|
317 |
+
if raw_value:
|
318 |
+
measurement_output_object['raw'] = raw_value
|
319 |
+
|
320 |
+
if 'type' in quantity:
|
321 |
+
quantity_type = quantity['type']
|
322 |
+
|
323 |
+
if 'rawUnit' in quantity:
|
324 |
+
has_unit = True
|
325 |
+
|
326 |
+
parsed_value_type = get_parsed_value_type(quantity)
|
327 |
+
|
328 |
+
elif type == 'interval':
|
329 |
+
if 'quantityMost' in measurement:
|
330 |
+
quantityMost = measurement['quantityMost']
|
331 |
+
if 'type' in quantityMost:
|
332 |
+
quantity_type = quantityMost['type']
|
333 |
+
|
334 |
+
if 'rawUnit' in quantityMost:
|
335 |
+
has_unit = True
|
336 |
+
|
337 |
+
parsed_value_type = get_parsed_value_type(quantityMost)
|
338 |
+
|
339 |
+
if 'quantityLeast' in measurement:
|
340 |
+
quantityLeast = measurement['quantityLeast']
|
341 |
+
|
342 |
+
if 'type' in quantityLeast:
|
343 |
+
quantity_type = quantityLeast['type']
|
344 |
+
|
345 |
+
if 'rawUnit' in quantityLeast:
|
346 |
+
has_unit = True
|
347 |
+
|
348 |
+
parsed_value_type = get_parsed_value_type(quantityLeast)
|
349 |
+
|
350 |
+
elif type == 'listc':
|
351 |
+
quantities = measurement['quantities']
|
352 |
+
|
353 |
+
if 'type' in quantities[0]:
|
354 |
+
quantity_type = quantities[0]['type']
|
355 |
+
|
356 |
+
if 'rawUnit' in quantities[0]:
|
357 |
+
has_unit = True
|
358 |
+
|
359 |
+
parsed_value_type = get_parsed_value_type(quantities[0])
|
360 |
+
|
361 |
+
if quantity_type is not None or has_unit:
|
362 |
+
measurement_output_object['type'] = quantity_type
|
363 |
+
|
364 |
+
if parsed_value_type is None or parsed_value_type not in ['ALPHABETIC', 'TIME']:
|
365 |
+
measurements_output.append(measurement_output_object)
|
366 |
+
|
367 |
+
return measurements_output
|
368 |
+
|
369 |
+
@staticmethod
|
370 |
+
def get_parsed(quantity):
|
371 |
+
parsed_value = parsed_unit = None
|
372 |
+
if 'parsedValue' in quantity and 'parsed' in quantity['parsedValue']:
|
373 |
+
parsed_value = quantity['parsedValue']['parsed']
|
374 |
+
if 'parsedUnit' in quantity and 'name' in quantity['parsedUnit']:
|
375 |
+
parsed_unit = quantity['parsedUnit']['name']
|
376 |
+
|
377 |
+
if parsed_value and parsed_unit:
|
378 |
+
if has_space_between_value_and_unit(quantity):
|
379 |
+
return str(parsed_value) + str(parsed_unit)
|
380 |
+
else:
|
381 |
+
return str(parsed_value) + " " + str(parsed_unit)
|
382 |
+
|
383 |
+
@staticmethod
|
384 |
+
def get_normalized(quantity):
|
385 |
+
normalized_value = normalized_unit = None
|
386 |
+
if 'normalizedQuantity' in quantity:
|
387 |
+
normalized_value = quantity['normalizedQuantity']
|
388 |
+
if 'normalizedUnit' in quantity and 'name' in quantity['normalizedUnit']:
|
389 |
+
normalized_unit = quantity['normalizedUnit']['name']
|
390 |
+
|
391 |
+
if normalized_value and normalized_unit:
|
392 |
+
if has_space_between_value_and_unit(quantity):
|
393 |
+
return str(normalized_value) + " " + str(normalized_unit)
|
394 |
+
else:
|
395 |
+
return str(normalized_value) + str(normalized_unit)
|
396 |
+
|
397 |
+
@staticmethod
|
398 |
+
def get_raw(quantity):
|
399 |
+
raw_value = raw_unit = None
|
400 |
+
if 'rawValue' in quantity:
|
401 |
+
raw_value = quantity['rawValue']
|
402 |
+
if 'rawUnit' in quantity and 'name' in quantity['rawUnit']:
|
403 |
+
raw_unit = quantity['rawUnit']['name']
|
404 |
+
|
405 |
+
if raw_value and raw_unit:
|
406 |
+
if has_space_between_value_and_unit(quantity):
|
407 |
+
return str(raw_value) + " " + str(raw_unit)
|
408 |
+
else:
|
409 |
+
return str(raw_value) + str(raw_unit)
|
410 |
+
|
411 |
+
|
412 |
+
class GrobidMaterialsProcessor(BaseProcessor):
|
413 |
+
def __init__(self, grobid_superconductors_client):
|
414 |
+
self.grobid_superconductors_client = grobid_superconductors_client
|
415 |
+
|
416 |
+
def extract_materials(self, text):
|
417 |
+
status, result = self.grobid_superconductors_client.process_text(text.strip(), "processText_disable_linking")
|
418 |
+
|
419 |
+
if status != 200:
|
420 |
+
result = {}
|
421 |
+
|
422 |
+
spans = []
|
423 |
+
|
424 |
+
if 'passages' in result:
|
425 |
+
materials = self.parse_superconductors_output(result, text)
|
426 |
+
|
427 |
+
for m in materials:
|
428 |
+
item = {"text": text[m['offset_start']:m['offset_end']]}
|
429 |
+
|
430 |
+
item['offset_start'] = m['offset_start']
|
431 |
+
item['offset_end'] = m['offset_end']
|
432 |
+
|
433 |
+
if 'formula' in m:
|
434 |
+
item["formula"] = m['formula']
|
435 |
+
|
436 |
+
item['type'] = 'material'
|
437 |
+
item['raw_value'] = m['text']
|
438 |
+
|
439 |
+
spans.append(item)
|
440 |
+
|
441 |
+
return spans
|
442 |
+
|
443 |
+
def parse_materials(self, text):
|
444 |
+
status, result = self.grobid_superconductors_client.process_texts(text.strip(), "parseMaterials")
|
445 |
+
|
446 |
+
if status != 200:
|
447 |
+
result = []
|
448 |
+
|
449 |
+
results = []
|
450 |
+
for position_material in result:
|
451 |
+
compositions = []
|
452 |
+
for material in position_material:
|
453 |
+
if 'resolvedFormulas' in material:
|
454 |
+
for resolved_formula in material['resolvedFormulas']:
|
455 |
+
if 'formulaComposition' in resolved_formula:
|
456 |
+
compositions.append(resolved_formula['formulaComposition'])
|
457 |
+
elif 'formula' in material:
|
458 |
+
if 'formulaComposition' in material['formula']:
|
459 |
+
compositions.append(material['formula']['formulaComposition'])
|
460 |
+
results.append(compositions)
|
461 |
+
|
462 |
+
return results
|
463 |
+
|
464 |
+
def parse_material(self, text):
|
465 |
+
status, result = self.grobid_superconductors_client.process_text(text.strip(), "parseMaterial")
|
466 |
+
|
467 |
+
if status != 200:
|
468 |
+
result = []
|
469 |
+
|
470 |
+
compositions = []
|
471 |
+
for material in result:
|
472 |
+
if 'resolvedFormulas' in material:
|
473 |
+
for resolved_formula in material['resolvedFormulas']:
|
474 |
+
if 'formulaComposition' in resolved_formula:
|
475 |
+
compositions.append(resolved_formula['formulaComposition'])
|
476 |
+
elif 'formula' in material:
|
477 |
+
if 'formulaComposition' in material['formula']:
|
478 |
+
compositions.append(material['formula']['formulaComposition'])
|
479 |
+
|
480 |
+
return compositions
|
481 |
+
|
482 |
+
@staticmethod
|
483 |
+
def parse_superconductors_output(result, original_text):
|
484 |
+
materials = []
|
485 |
+
|
486 |
+
for passage in result['passages']:
|
487 |
+
sentence_offset = original_text.index(passage['text'])
|
488 |
+
if 'spans' in passage:
|
489 |
+
spans = passage['spans']
|
490 |
+
for material_span in filter(lambda s: s['type'] == '<material>', spans):
|
491 |
+
text_ = material_span['text']
|
492 |
+
|
493 |
+
base_material_information = {
|
494 |
+
"text": text_,
|
495 |
+
"offset_start": sentence_offset + material_span['offset_start'],
|
496 |
+
'offset_end': sentence_offset + material_span['offset_end']
|
497 |
+
}
|
498 |
+
|
499 |
+
materials.append(base_material_information)
|
500 |
+
|
501 |
+
return materials
|
502 |
+
|
503 |
+
|
504 |
+
class GrobidAggregationProcessor(GrobidProcessor, GrobidQuantitiesProcessor, GrobidMaterialsProcessor):
|
505 |
+
def __init__(self, grobid_client, grobid_quantities_client=None, grobid_superconductors_client=None):
|
506 |
+
GrobidProcessor.__init__(self, grobid_client)
|
507 |
+
GrobidQuantitiesProcessor.__init__(self, grobid_quantities_client)
|
508 |
+
GrobidMaterialsProcessor.__init__(self, grobid_superconductors_client)
|
509 |
+
|
510 |
+
def process_single_text(self, text):
|
511 |
+
extracted_quantities_spans = extract_quantities(self.grobid_quantities_client, text)
|
512 |
+
extracted_materials_spans = extract_materials(self.grobid_superconductors_client, text)
|
513 |
+
all_entities = extracted_quantities_spans + extracted_materials_spans
|
514 |
+
entities = self.prune_overlapping_annotations(all_entities)
|
515 |
+
return entities
|
516 |
+
|
517 |
+
@staticmethod
|
518 |
+
def prune_overlapping_annotations(entities: list) -> list:
|
519 |
+
# Sorting by offsets
|
520 |
+
sorted_entities = sorted(entities, key=lambda d: d['offset_start'])
|
521 |
+
|
522 |
+
if len(entities) <= 1:
|
523 |
+
return sorted_entities
|
524 |
+
|
525 |
+
to_be_removed = []
|
526 |
+
|
527 |
+
previous = None
|
528 |
+
first = True
|
529 |
+
|
530 |
+
for current in sorted_entities:
|
531 |
+
if first:
|
532 |
+
first = False
|
533 |
+
previous = current
|
534 |
+
continue
|
535 |
+
|
536 |
+
if previous['offset_start'] < current['offset_start'] \
|
537 |
+
and previous['offset_end'] < current['offset_end'] \
|
538 |
+
and (previous['offset_end'] < current['offset_start'] \
|
539 |
+
and not (previous['text'] == "-" and current['text'][0].isdigit())):
|
540 |
+
previous = current
|
541 |
+
continue
|
542 |
+
|
543 |
+
if previous['offset_end'] < current['offset_end']:
|
544 |
+
if current['type'] == previous['type']:
|
545 |
+
# Type is the same
|
546 |
+
if current['offset_start'] == previous['offset_end']:
|
547 |
+
if current['type'] == 'property':
|
548 |
+
if current['text'].startswith("."):
|
549 |
+
print(
|
550 |
+
f"Merging. {current['text']} <{current['type']}> with {previous['text']} <{previous['type']}>")
|
551 |
+
# current entity starts with a ".", suspiciously look like a truncated value
|
552 |
+
to_be_removed.append(previous)
|
553 |
+
current['text'] = previous['text'] + current['text']
|
554 |
+
current['raw_value'] = current['text']
|
555 |
+
current['offset_start'] = previous['offset_start']
|
556 |
+
elif previous['text'].endswith(".") and current['text'][0].isdigit():
|
557 |
+
print(
|
558 |
+
f"Merging. {current['text']} <{current['type']}> with {previous['text']} <{previous['type']}>")
|
559 |
+
# previous entity ends with ".", current entity starts with a number
|
560 |
+
to_be_removed.append(previous)
|
561 |
+
current['text'] = previous['text'] + current['text']
|
562 |
+
current['raw_value'] = current['text']
|
563 |
+
current['offset_start'] = previous['offset_start']
|
564 |
+
elif previous['text'].startswith("-"):
|
565 |
+
print(
|
566 |
+
f"Merging. {current['text']} <{current['type']}> with {previous['text']} <{previous['type']}>")
|
567 |
+
# previous starts with a `-`, sherlock this is another truncated value
|
568 |
+
current['text'] = previous['text'] + current['text']
|
569 |
+
current['raw_value'] = current['text']
|
570 |
+
current['offset_start'] = previous['offset_start']
|
571 |
+
to_be_removed.append(previous)
|
572 |
+
else:
|
573 |
+
print("Other cases to be considered: ", previous, current)
|
574 |
+
else:
|
575 |
+
if current['text'].startswith("-"):
|
576 |
+
print(
|
577 |
+
f"Merging. {current['text']} <{current['type']}> with {previous['text']} <{previous['type']}>")
|
578 |
+
# previous starts with a `-`, sherlock this is another truncated value
|
579 |
+
current['text'] = previous['text'] + current['text']
|
580 |
+
current['raw_value'] = current['text']
|
581 |
+
current['offset_start'] = previous['offset_start']
|
582 |
+
to_be_removed.append(previous)
|
583 |
+
else:
|
584 |
+
print("Other cases to be considered: ", previous, current)
|
585 |
+
|
586 |
+
elif previous['text'] == "-" and current['text'][0].isdigit():
|
587 |
+
print(
|
588 |
+
f"Merging. {current['text']} <{current['type']}> with {previous['text']} <{previous['type']}>")
|
589 |
+
# previous starts with a `-`, sherlock this is another truncated value
|
590 |
+
current['text'] = previous['text'] + " " * (current['offset_start'] - previous['offset_end']) + \
|
591 |
+
current['text']
|
592 |
+
current['raw_value'] = current['text']
|
593 |
+
current['offset_start'] = previous['offset_start']
|
594 |
+
to_be_removed.append(previous)
|
595 |
+
else:
|
596 |
+
print(
|
597 |
+
f"Overlapping. {current['text']} <{current['type']}> with {previous['text']} <{previous['type']}>")
|
598 |
+
|
599 |
+
# take the largest one
|
600 |
+
if len(previous['text']) > len(current['text']):
|
601 |
+
to_be_removed.append(current)
|
602 |
+
elif len(previous['text']) < len(current['text']):
|
603 |
+
to_be_removed.append(previous)
|
604 |
+
else:
|
605 |
+
to_be_removed.append(previous)
|
606 |
+
elif current['type'] != previous['type']:
|
607 |
+
print(
|
608 |
+
f"Overlapping. {current['text']} <{current['type']}> with {previous['text']} <{previous['type']}>")
|
609 |
+
|
610 |
+
if len(previous['text']) > len(current['text']):
|
611 |
+
to_be_removed.append(current)
|
612 |
+
elif len(previous['text']) < len(current['text']):
|
613 |
+
to_be_removed.append(previous)
|
614 |
+
else:
|
615 |
+
if current['type'] == "material":
|
616 |
+
to_be_removed.append(previous)
|
617 |
+
else:
|
618 |
+
to_be_removed.append(current)
|
619 |
+
previous = current
|
620 |
+
|
621 |
+
elif previous['offset_end'] > current['offset_end']:
|
622 |
+
to_be_removed.append(current)
|
623 |
+
# the previous goes after the current, so we keep the previous and we discard the current
|
624 |
+
else:
|
625 |
+
if current['type'] == "material":
|
626 |
+
to_be_removed.append(previous)
|
627 |
+
else:
|
628 |
+
to_be_removed.append(current)
|
629 |
+
previous = current
|
630 |
+
|
631 |
+
new_sorted_entities = [e for e in sorted_entities if e not in to_be_removed]
|
632 |
+
|
633 |
+
return new_sorted_entities
|
634 |
+
|
635 |
+
|
636 |
+
class XmlProcessor(BaseProcessor):
|
637 |
+
def __init__(self, grobid_superconductors_client, grobid_quantities_client):
|
638 |
+
super().__init__(grobid_superconductors_client, grobid_quantities_client)
|
639 |
+
|
640 |
+
def process_structure(self, input_file):
|
641 |
+
text = ""
|
642 |
+
with open(input_file, encoding='utf-8') as fi:
|
643 |
+
text = fi.read()
|
644 |
+
|
645 |
+
output_data = self.parse_xml(text)
|
646 |
+
output_data['filename'] = Path(input_file).stem.replace(".tei", "")
|
647 |
+
|
648 |
+
return output_data
|
649 |
+
|
650 |
+
def process_single(self, input_file):
|
651 |
+
doc = self.process_structure(input_file)
|
652 |
+
|
653 |
+
for paragraph in doc['passages']:
|
654 |
+
entities = self.process_single_text(paragraph['text'])
|
655 |
+
paragraph['spans'] = entities
|
656 |
+
|
657 |
+
return doc
|
658 |
+
|
659 |
+
def parse_xml(self, text):
|
660 |
+
output_data = OrderedDict()
|
661 |
+
soup = BeautifulSoup(text, 'xml')
|
662 |
+
text_blocks_children = supermat_tei_parser.get_children_list(soup, verbose=False)
|
663 |
+
|
664 |
+
passages = []
|
665 |
+
output_data['passages'] = passages
|
666 |
+
passages.extend([
|
667 |
+
{
|
668 |
+
"text": self.post_process(''.join(text for text in sentence.find_all(text=True) if
|
669 |
+
text.parent.name != "ref" or (
|
670 |
+
text.parent.name == "ref" and text.parent.attrs[
|
671 |
+
'type'] != 'bibr'))),
|
672 |
+
"type": "paragraph",
|
673 |
+
"section": "<body>",
|
674 |
+
"subSection": "<paragraph>",
|
675 |
+
"passage_id": str(paragraph_id) + str(sentence_id)
|
676 |
+
}
|
677 |
+
for paragraph_id, paragraph in enumerate(text_blocks_children) for
|
678 |
+
sentence_id, sentence in enumerate(paragraph)
|
679 |
+
])
|
680 |
+
|
681 |
+
return output_data
|
682 |
+
|
683 |
+
|
684 |
+
def get_children_list(soup: object, use_paragraphs: object = True, verbose: object = False) -> object:
|
685 |
+
children = []
|
686 |
+
|
687 |
+
child_name = "p" if use_paragraphs else "s"
|
688 |
+
for child in soup.TEI.children:
|
689 |
+
if child.name == 'teiHeader':
|
690 |
+
pass
|
691 |
+
# children.extend(child.find_all("title", attrs={"level": "a"}, limit=1))
|
692 |
+
# children.extend([subchild.find_all(child_name) for subchild in child.find_all("abstract")])
|
693 |
+
elif child.name == 'text':
|
694 |
+
children.extend([subchild.find_all(child_name) for subchild in child.find_all("body")])
|
695 |
+
children.extend([subchild.find_all("figDesc") for subchild in child.find_all("body")])
|
696 |
+
|
697 |
+
if verbose:
|
698 |
+
print(str(children))
|
699 |
+
|
700 |
+
return children
|
701 |
+
|
702 |
+
|
703 |
+
def get_children_body(soup: object, use_paragraphs: object = True, verbose: object = False) -> object:
|
704 |
+
children = []
|
705 |
+
child_name = "p" if use_paragraphs else "s"
|
706 |
+
for child in soup.TEI.children:
|
707 |
+
if child.name == 'text':
|
708 |
+
children.extend([subchild.find_all(child_name) for subchild in child.find_all("body")])
|
709 |
+
|
710 |
+
if verbose:
|
711 |
+
print(str(children))
|
712 |
+
|
713 |
+
return children
|
714 |
+
|
715 |
+
|
716 |
+
def get_children_figures(soup: object, use_paragraphs: object = True, verbose: object = False) -> object:
|
717 |
+
children = []
|
718 |
+
child_name = "p" if use_paragraphs else "s"
|
719 |
+
for child in soup.TEI.children:
|
720 |
+
if child.name == 'text':
|
721 |
+
children.extend([subchild.find_all("figDesc") for subchild in child.find_all("body")])
|
722 |
+
|
723 |
+
if verbose:
|
724 |
+
print(str(children))
|
725 |
+
|
726 |
+
return children
|
streamlit_app.py
CHANGED
@@ -1,17 +1,17 @@
|
|
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 |
|
|
|
1 |
import os
|
|
|
2 |
from hashlib import blake2b
|
3 |
from tempfile import NamedTemporaryFile
|
4 |
|
5 |
import dotenv
|
6 |
+
|
7 |
+
dotenv.load_dotenv(override=True)
|
8 |
+
|
9 |
import streamlit as st
|
10 |
from langchain.chat_models import PromptLayerChatOpenAI
|
11 |
from langchain.embeddings import OpenAIEmbeddings
|
12 |
|
13 |
from document_qa_engine import DocumentQAEngine
|
14 |
|
|
|
|
|
15 |
if 'rqa' not in st.session_state:
|
16 |
st.session_state['rqa'] = None
|
17 |
|