-
Notifications
You must be signed in to change notification settings - Fork 264
/
Copy pathprocess_pubmed.py
1946 lines (1634 loc) · 78.9 KB
/
process_pubmed.py
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Copyright (C) 2023 Microsoft Corporation
USAGE NOTES:
This code is our best attempt to piece together the code that was used to create PubTables-1M.
(PubTables-1M was originally created in multiple stages, not all in one script.)
This script processes pairs of PDF and NXML files in the PubMed Open Access corpus.
These need to be downloaded first.
Download tar.gz files from the FTP site:
https://ftp.ncbi.nlm.nih.gov/pub/pmc/oa_package/
Please pay attention to licensing. See the PubMed Central website for more information on
how to ensure you download data licensed for commercial use, if that is your need.
Before running this script, place the downloaded files in the same directory and unzip them.
This should create a collection of subdirectories each starting with "PMC..." like so:
parent_folder\
- PMC1234567\
- same_name.pdf
- same_name.nxml
- PMC2345678\
- PMC3456789\
Note that this script has a timeout for each file and skips ones that take too long to process.
If you use this code in your published work, we ask that you please cite our PubTables-1M paper
and table-transformer GitHub repo.
TODO:
- Add code for making or incorporating a train/test/val split
- Change the table padding for the test and val splits
"""
import os
import re
import xml.etree.ElementTree as ET
from xml.dom import minidom
import json
import functools
from collections import defaultdict
import traceback
import signal
import argparse
from PIL import Image
import numpy as np
import fitz
from fitz import Rect
import editdistance
class timeout:
def __init__(self, seconds=1, error_message='Timeout'):
self.seconds = seconds
self.error_message = error_message
def handle_timeout(self, signum, frame):
raise TimeoutError(self.error_message)
def __enter__(self):
signal.signal(signal.SIGALRM, self.handle_timeout)
signal.alarm(self.seconds)
def __exit__(self, type, value, traceback):
signal.alarm(0)
def read_xml(nxml_filepath):
'''
Read in XML as a string.
'''
with open(nxml_filepath, 'r') as file:
xml_string = file.read()
return xml_string
def read_pdf(pdf_filepath):
'''
Read in PDF file as a PyMyPDF doc.
'''
doc = fitz.open(pdf_filepath)
return doc
def compare_meta(word1, word2):
'''
For ordering words according to *some* reading order within the PDF.
'''
if word1[5] < word2[5]:
return -1
if word1[5] > word2[5]:
return 1
if word1[6] < word2[6]:
return -1
if word1[6] > word2[6]:
return 1
if word1[7] < word2[7]:
return -1
if word1[7] > word2[7]:
return 1
return 0
def get_page_words(page):
"""
Extract the words from the page, with bounding boxes,
as well as loose layout and style information.
"""
words = []
for text_word in page.get_text_words():
word = {'bbox': list(text_word[:4]),
'text': text_word[4],
'block_num': text_word[5],
'line_num': text_word[6],
'span_num': text_word[7],
'flags': 0}
words.append(word)
return words
def overlaps(bbox1, bbox2, threshold=0.5):
"""
Test if more than "threshold" fraction of bbox1 overlaps with bbox2.
"""
rect1 = Rect(bbox1)
area1 = rect1.get_area()
if area1 == 0:
return False
return rect1.intersect(bbox2).get_area()/area1 >= threshold
def get_bbox_span_subset(spans, bbox, threshold=0.5):
"""
Reduce the set of spans to those that fall within a bounding box.
threshold: the fraction of the span that must overlap with the bbox.
"""
span_subset = []
for span in spans:
if overlaps(span['bbox'], bbox, threshold):
span_subset.append(span)
return span_subset
def extract_text_from_spans(spans, join_with_space=True, remove_integer_superscripts=True):
"""
Convert a collection of page tokens/words/spans into a single text string.
"""
if join_with_space:
join_char = " "
else:
join_char = ""
spans_copy = spans[:]
if remove_integer_superscripts:
for span in spans:
flags = span['flags']
if flags & 2**0: # superscript flag
if is_int(span['text']):
spans_copy.remove(span)
else:
span['superscript'] = True
if len(spans_copy) == 0:
return ""
spans_copy.sort(key=lambda span: span['span_num'])
spans_copy.sort(key=lambda span: span['line_num'])
spans_copy.sort(key=lambda span: span['block_num'])
# Force the span at the end of every line within a block to have exactly one space
# unless the line ends with a space or ends with a non-space followed by a hyphen
line_texts = []
line_span_texts = [spans_copy[0]['text']]
for span1, span2 in zip(spans_copy[:-1], spans_copy[1:]):
if not span1['block_num'] == span2['block_num'] or not span1['line_num'] == span2['line_num']:
line_text = join_char.join(line_span_texts).strip()
if (len(line_text) > 0
and not line_text[-1] == ' '
and not (len(line_text) > 1 and line_text[-1] == "-" and not line_text[-2] == ' ')):
if not join_with_space:
line_text += ' '
line_texts.append(line_text)
line_span_texts = [span2['text']]
else:
line_span_texts.append(span2['text'])
line_text = join_char.join(line_span_texts)
line_texts.append(line_text)
return join_char.join(line_texts).strip()
def extract_text_inside_bbox(spans, bbox):
"""
Extract the text inside a bounding box.
"""
bbox_spans = get_bbox_span_subset(spans, bbox)
bbox_text = extract_text_from_spans(bbox_spans, remove_integer_superscripts=False)
return bbox_text, bbox_spans
def extract_table_xmls_from_document(xml_string):
table_dicts = []
table_starts = [m.start() for m in re.finditer("<table-wrap |<table-wrap>", xml_string)]
table_ends = [m.end() for m in re.finditer("</table-wrap>", xml_string)]
if not len(table_starts) == len(table_ends):
print("Could not match up all table-wrap begins and ends")
return None
for table_start, table_end in zip(table_starts, table_ends):
table_dict = {}
table_dict['xml_table_wrap_start_character_index'] = table_start
table_dict['xml_table_wrap_end_character_index'] = table_end
table_dicts.append(table_dict)
return table_dicts
def parse_xml_table(xml_string, table_dict):
start_index = table_dict['xml_table_wrap_start_character_index']
end_index = table_dict['xml_table_wrap_end_character_index']
table_xml = xml_string[start_index:end_index]
table_dict['xml_markup'] = table_xml
try:
table_xml = table_xml.replace("xlink:", "") # these break the xml parser
tree = ET.fromstring(table_xml)
except Exception as e:
print(e)
return None
table_cells = []
occupied_columns_by_row = defaultdict(set)
current_row = -1
caption_text = []
# Initialize empty values
table_dict['xml_tablewrap_raw_text'] = ""
table_dict['xml_table_raw_text'] = ""
table_dict['xml_graphic_filename'] = ""
table_dict['xml_table_footer_text'] = ""
table_dict['xml_caption_label_text'] = ""
table_dict['xml_caption_text'] = ""
# Get all td tags
stack = []
stack.append((tree, False))
while len(stack) > 0:
current, in_header = stack.pop()
if current.tag == 'table-wrap':
table_dict['xml_tablewrap_raw_text'] = ' '.join([elem.strip() for elem in current.itertext()]).strip()
if current.tag == 'table':
table_dict['xml_table_raw_text'] = ' '.join([elem.strip() for elem in current.itertext()]).strip()
if current.tag == 'graphic':
try:
table_dict['xml_graphic_filename'] = current.attrib['href']
except:
pass
if current.tag == 'table-wrap-foot':
table_dict['xml_table_footer_text'] = ''.join(current.itertext()).strip()
if current.tag == 'label':
table_dict['xml_caption_label_text'] = ''.join(current.itertext()).strip()
if current.tag == 'caption':
table_dict['xml_caption_text'] = ''.join(current.itertext()).strip()
if current.tag == 'tr':
current_row += 1
if current.tag == 'td' or current.tag =='th':
if "colspan" in current.attrib:
colspan = int(current.attrib["colspan"])
else:
colspan = 1
if "rowspan" in current.attrib:
rowspan = int(current.attrib["rowspan"])
else:
rowspan = 1
row_nums = list(range(current_row, current_row + rowspan))
try:
max_occupied_column = max(occupied_columns_by_row[current_row])
current_column = min(set(range(max_occupied_column+2)).difference(occupied_columns_by_row[current_row]))
except:
current_column = 0
column_nums = list(range(current_column, current_column + colspan))
for row_num in row_nums:
occupied_columns_by_row[row_num].update(column_nums)
if "align" in current.attrib:
align = current.attrib["align"]
else:
align = "unknown"
if "style" in current.attrib:
style = current.attrib["style"]
else:
style = "none"
graphics = [child for child in current if child.tag == 'graphic']
graphics_filenames = [graphic.attrib['href'] for graphic in graphics if "href" in graphic.attrib]
raw_text = ''.join(current.itertext())
text = ' '.join([elem.strip() for elem in current.itertext()])
cell_dict = dict()
cell_dict['row_nums'] = row_nums
cell_dict['column_nums'] = column_nums
cell_dict['is_column_header'] = current.tag == 'th' or in_header
cell_dict['align'] = align
cell_dict['style'] = style
# tab or space or padding
if (raw_text.startswith("\u2003") or raw_text.startswith("\u0020")
or raw_text.startswith("\t") or raw_text.startswith(" ")
or "padding-left" in style):
cell_dict['indented'] = True
else:
cell_dict['indented'] = False
cell_dict['xml_text_content'] = text
cell_dict['xml_raw_text_content'] = raw_text
cell_dict['xml_graphics_filenames'] = graphics_filenames
#cell_dict['pdf'] = {}
table_cells.append(cell_dict)
children = list(current)
for child in children[::-1]:
stack.append((child, in_header or current.tag == 'th' or current.tag == 'thead'))
#table_dict['rows'] = [{} for entry in range(row_num + 1)]
#table_dict['columns'] = [{} for entry in range(num_cols)]
if len(occupied_columns_by_row) > 0:
table_dict['num_rows'] = max(occupied_columns_by_row) + 1
table_dict['num_columns'] = max([max(elems) for row_num, elems in occupied_columns_by_row.items()]) + 1
else:
table_dict['num_rows'] = 0
table_dict['num_columns'] = 0
table_dict['cells'] = table_cells
return table_dict
# For traceback: -1 = up, 1 = left, 0 = diag up-left
def align(page_string="", table_string="", match_reward=2, mismatch_penalty=-5, new_gap_penalty=-2,
continue_gap_penalty=-0.05, page_boundary_gap_reward=0.01, gap_not_after_space_penalty=-1,
score_only=False, gap_character='_'):
scores = np.zeros((len(page_string) + 1, len(table_string) + 1))
pointers = np.zeros((len(page_string) + 1, len(table_string) + 1))
# Initialize first column
for row_idx in range(1, len(page_string) + 1):
scores[row_idx, 0] = scores[row_idx - 1, 0] + page_boundary_gap_reward
pointers[row_idx, 0] = -1
# Initialize first row
for col_idx in range(1, len(table_string) + 1):
#scores[0, col_idx] = scores[0, col_idx - 1] + 0
pointers[0, col_idx] = 1
for row_idx in range(1, len(page_string) + 1):
for col_idx in range(1, len(table_string) + 1):
if page_string[row_idx - 1] == table_string[col_idx - 1]:
diag_score = scores[row_idx - 1, col_idx - 1] + match_reward
else:
diag_score = scores[row_idx - 1, col_idx - 1] + mismatch_penalty
if pointers[row_idx, col_idx - 1] == 1:
same_row_score = scores[row_idx, col_idx - 1] + continue_gap_penalty
else:
same_row_score = scores[row_idx, col_idx - 1] + new_gap_penalty
if not table_string[col_idx - 1] == ' ':
same_row_score += gap_not_after_space_penalty
if col_idx == len(table_string):
same_col_score = scores[row_idx - 1, col_idx] + page_boundary_gap_reward
elif pointers[row_idx - 1, col_idx] == -1:
same_col_score = scores[row_idx - 1, col_idx] + continue_gap_penalty
else:
same_col_score = scores[row_idx - 1, col_idx] + new_gap_penalty
if not page_string[row_idx - 1] == ' ':
same_col_score += gap_not_after_space_penalty
max_score = max(diag_score, same_col_score, same_row_score)
scores[row_idx, col_idx] = max_score
if diag_score == max_score:
pointers[row_idx, col_idx] = 0
elif same_col_score == max_score:
pointers[row_idx, col_idx] = -1
else:
pointers[row_idx, col_idx] = 1
#print(scores[:, -1])
#print(pointers)
score = scores[len(page_string), len(table_string)]
if score_only:
return score
cur_row = len(page_string)
cur_col = len(table_string)
aligned_page_string = ""
aligned_table_string = ""
while not (cur_row == 0 and cur_col == 0):
if pointers[cur_row, cur_col] == -1:
cur_row -= 1
aligned_table_string += gap_character
aligned_page_string += page_string[cur_row]
elif pointers[cur_row, cur_col] == 1:
cur_col -= 1
aligned_page_string += gap_character
aligned_table_string += table_string[cur_col]
else:
cur_row -= 1
cur_col -= 1
aligned_table_string += table_string[cur_col]
aligned_page_string += page_string[cur_row]
aligned_page_string = aligned_page_string[::-1]
aligned_table_string = aligned_table_string[::-1]
alignment = [aligned_page_string, aligned_table_string]
return alignment, score
def get_table_page_fast(doc, table):
table_words = table['xml_tablewrap_raw_text'].split(" ")
table_words_set = set(table_words)
table_text = " ".join(table_words)
candidate_page_nums = []
scores = [0 for page in doc]
for page_num, page in enumerate(doc):
page_words_set = set([word[4] for word in page.get_text_words()])
scores[page_num] = len(table_words_set.intersection(page_words_set))
table_page = int(np.argmax(scores))
return table_page, scores
def get_table_page_slow(doc, table, candidate_page_nums=None):
table_words = []
table_text = table['xml_tablewrap_raw_text']
if not candidate_page_nums:
candidate_page_nums = range(len(doc))
scores = [0 for page_num in candidate_page_nums]
for idx, page in enumerate(candidate_page_nums):
page = doc[candidate_page_nums[idx]]
page_words = page.get_text_words()
sorted_words = sorted(page_words, key=functools.cmp_to_key(compare_meta))
page_text = " ".join([word[4] for word in sorted_words])
X = page_text.replace("~", "^")
Y = table_text.replace("~", "^")
score = align(X, Y, match_reward=2, mismatch_penalty=-2, new_gap_penalty=-10,
continue_gap_penalty = -0.0005, page_boundary_gap_reward = 0.0001, score_only=True,
gap_character='~')
scores[idx] = score
table_page = candidate_page_nums[int(np.argmax(scores))]
return table_page, scores
def get_table_page(doc, table):
table_page_num, scores = get_table_page_fast(doc, table)
max_score = max(scores)
candidate_page_nums = []
for idx, score in enumerate(scores):
if score >= max_score / 2:
candidate_page_nums.append(idx)
if len(candidate_page_nums) > 1:
table_page_num, scores = get_table_page_slow(doc, table,
candidate_page_nums=candidate_page_nums)
return table_page_num, scores
def locate_table(page, table):
words = page.get_text_words()
sorted_words = sorted(words, key=functools.cmp_to_key(compare_meta))
page_text = " ".join([word[4] for word in sorted_words])
page_text_source = []
for num, word in enumerate(sorted_words):
for c in word[4]:
page_text_source.append(num)
page_text_source.append(None)
page_text_source = page_text_source[:-1]
table_text = " ".join([entry['xml_text_content'].strip() for entry in table['cells']])
table_text_source = []
for num, cell in enumerate(table['cells']):
for c in cell['xml_text_content'].strip():
table_text_source.append(num)
table_text_source.append(None)
table_text_source = table_text_source[:-1]
X = page_text.replace("~", "^")
Y = table_text.replace("~", "^")
match_reward = 3
mismatch_penalty = -2
new_gap_penalty = -10
continue_gap_penalty = -0.05
page_boundary_gap_reward = 0.2
alignment, score = align(X, Y, match_reward=match_reward, mismatch_penalty=mismatch_penalty,
new_gap_penalty=new_gap_penalty, continue_gap_penalty=continue_gap_penalty,
page_boundary_gap_reward=page_boundary_gap_reward, score_only=False,
gap_character='~')
table_words = set()
column_words = dict()
row_words = dict()
cell_words = dict()
page_count = 0
table_count = 0
for char1, char2 in zip(alignment[0], alignment[1]):
if not char1 == "~":
if char1 == char2:
table_words.add(page_text_source[page_count])
cell_num = table_text_source[table_count]
if not cell_num is None:
if cell_num in cell_words:
cell_words[cell_num].add(page_text_source[page_count])
else:
cell_words[cell_num] = set([page_text_source[page_count]])
page_count += 1
if not char2 == "~":
table_count += 1
inliers = []
for word_num in table_words:
if word_num:
inliers.append(sorted_words[word_num])
if len(inliers) == 0:
return None, None
cell_bboxes = {}
for cell_num, cell in enumerate(table['cells']):
cell_bbox = None
if cell_num in cell_words:
for word_num in cell_words[cell_num]:
if word_num:
word_bbox = sorted_words[word_num][0:4]
if not cell_bbox:
cell_bbox = [entry for entry in word_bbox]
else:
cell_bbox[0] = min(cell_bbox[0], word_bbox[0])
cell_bbox[1] = min(cell_bbox[1], word_bbox[1])
cell_bbox[2] = max(cell_bbox[2], word_bbox[2])
cell_bbox[3] = max(cell_bbox[3], word_bbox[3])
cell_bboxes[cell_num] = cell_bbox
return cell_bboxes, inliers
def locate_caption(page, caption):
words = page.get_text_words()
sorted_words = sorted(words, key=functools.cmp_to_key(compare_meta))
page_text = " ".join([word[4] for word in sorted_words])
page_text_source = []
for num, word in enumerate(sorted_words):
for c in word[4]:
page_text_source.append(num)
page_text_source.append(None)
X = page_text.replace("~", "^")
Y = caption.replace("~", "^")
match_reward = 3
mismatch_penalty = -2
new_gap_penalty = -10
continue_gap_penalty = -0.05
page_boundary_gap_reward = 0.2
alignment, score = align(X, Y, match_reward=match_reward, mismatch_penalty=mismatch_penalty,
new_gap_penalty=new_gap_penalty, continue_gap_penalty=continue_gap_penalty,
page_boundary_gap_reward=page_boundary_gap_reward, score_only=False,
gap_character='~')
matching_words = set()
count = 0
for char1, char2 in zip(alignment[0], alignment[1]):
if not char1 == "~":
if char1 == char2:
matching_words.add(page_text_source[count])
count += 1
inliers = []
for word_num in matching_words:
if word_num:
inliers.append(sorted_words[word_num])
if len(inliers) == 0:
return [], []
bbox = list(inliers[0][0:4])
for word in inliers[1:]:
bbox[0] = min(bbox[0], word[0])
bbox[1] = min(bbox[1], word[1])
bbox[2] = max(bbox[2], word[2])
bbox[3] = max(bbox[3], word[3])
return bbox, inliers
def is_portrait(page, bbox):
if bbox:
bbox = fitz.Rect(bbox)
else:
bbox = page.rect
portrait_count = 0
landscape_count = 0
page_dict = page.get_text("dict")
for block in page_dict['blocks']:
if 'lines' in block:
for line in block['lines']:
line_bbox = fitz.Rect(line['bbox'])
if bbox and line_bbox in bbox:
direction = line['dir']
if direction[0] == 1 and direction[1] == 0:
portrait_count += 1
elif direction[0] == 0 and direction[1] == -1:
landscape_count += 1
return portrait_count >= landscape_count
def save_full_tables_annotation(tables, document_annotation_filepath):
# Remove "word_bboxes" field
for table_dict in tables:
if 'pdf_word_bboxes' in table_dict:
del table_dict['pdf_word_bboxes']
if 'pdf_caption_word_bboxes' in table_dict:
del table_dict['pdf_caption_word_bboxes']
with open(document_annotation_filepath, 'w', encoding='utf-8') as outfile:
json.dump(tables, outfile, ensure_ascii=False, indent=4)
# Attempt to fix the caption and footer
# 1. Caption should encompass all of the "lines" that intersect the caption.
# 2. Footer should encompass all of the "blocks" that intersect the footer.
def fix_caption_and_footer(doc, table_dict):
try:
page = doc[table_dict['pdf_page_index']]
except:
return
text = page.get_text('dict')
blocks = text['blocks']
block_bboxes = [block['bbox'] for block in blocks]
try:
caption_block_bboxes = []
caption_bbox = table_dict['pdf_caption_bbox']
for bbox in block_bboxes:
if Rect(bbox).intersects(caption_bbox):
caption_block_bboxes.append(bbox)
caption_rect = Rect(caption_bbox)
for bbox in caption_block_bboxes:
caption_rect.include_rect(bbox)
table_dict['pdf_caption_bbox'] = list(caption_rect)
except:
pass
try:
footer_block_bboxes = []
footer_bbox = table_dict['pdf_table_footer_bbox']
for bbox in block_bboxes:
if Rect(bbox).intersects(footer_bbox):
footer_block_bboxes.append(bbox)
footer_rect = Rect(footer_bbox)
for bbox in footer_block_bboxes:
footer_rect.include_rect(bbox)
table_dict['pdf_table_footer_bbox'] = list(footer_rect)
except:
pass
try:
table_wrap_rect = Rect(table_dict['pdf_table_wrap_bbox'])
try:
table_wrap_rect.include_rect(footer_rect)
except:
pass
try:
table_wrap_rect.include_rect(caption_rect)
except:
pass
table_dict['pdf_table_wrap_bbox'] = list(table_wrap_rect)
except:
pass
def clean_xml_annotation(table_dict):
num_columns = table_dict['num_columns']
num_rows = table_dict['num_rows']
header_rows = set()
for cell in table_dict['cells']:
if cell['is_column_header']:
header_rows = header_rows.union(set(cell['row_nums']))
num_header_rows = len(header_rows)
#---REMOVE EMPTY ROWS---
has_content_by_row = defaultdict(bool)
for cell in table_dict['cells']:
has_content = len(cell['xml_text_content'].strip()) > 0
for row_num in cell['row_nums']:
has_content_by_row[row_num] = has_content_by_row[row_num] or has_content
table_dict['section_last_rows'] = [num_header_rows-1]
row_count = num_header_rows
for row_num in range(num_header_rows+1, num_rows):
if not has_content_by_row[row_num]:
table_dict['section_last_rows'].append(row_count)
else:
row_count += 1
row_num_corrections = np.cumsum([int(not has_content_by_row[row_num]) for row_num in range(num_rows)]).tolist()
cells_to_delete = []
for cell in table_dict['cells']:
new_row_nums = []
for row_num in cell['row_nums']:
if has_content_by_row[row_num]:
new_row_nums.append(row_num - row_num_corrections[row_num])
cell['row_nums'] = new_row_nums
if len(new_row_nums) == 0:
cells_to_delete.append(cell)
for cell in cells_to_delete:
table_dict['cells'].remove(cell)
table_dict["num_rows"] = sum([int(elem) for idx, elem in has_content_by_row.items()])
#---REMOVE EMPTY COLUMNS---
has_content_by_column = defaultdict(bool)
for cell in table_dict['cells']:
has_content = len(cell['xml_text_content'].strip()) > 0
for column_num in cell['column_nums']:
has_content_by_column[column_num] = has_content_by_column[column_num] or has_content
column_num_corrections = np.cumsum([int(not has_content_by_column[column_num]) for column_num in range(num_columns)]).tolist()
cells_to_delete = []
for cell in table_dict['cells']:
new_column_nums = []
for column_num in cell['column_nums']:
if has_content_by_column[column_num]:
new_column_nums.append(column_num - column_num_corrections[column_num])
cell['column_nums'] = new_column_nums
if len(new_column_nums) == 0:
cells_to_delete.append(cell)
for cell in cells_to_delete:
table_dict['cells'].remove(cell)
table_dict["num_columns"] = sum([int(elem) for idx, elem in has_content_by_column.items()])
def standardize_and_fix_xml_annotation(table_dict):
num_columns = table_dict['num_columns']
num_rows = table_dict['num_rows']
#---IF FIRST ROW HAS CELL WITH COLSPAN > 1, MUST BE A HEADER
first_row_has_colspan = False
for cell in table_dict['cells']:
if 0 in cell['row_nums'] and len(cell['column_nums']) > 1:
first_row_has_colspan = True
if first_row_has_colspan:
for cell in table_dict['cells']:
if 0 in cell['row_nums']:
cell['is_column_header'] = True
#---STANDARDIZE HEADERS: HEADERS END WITH A ROW WITH NO SUPERCELLS---
cell_counts_by_row = defaultdict(int)
header_status_by_row = defaultdict(bool)
for cell in table_dict['cells']:
for row_num in cell['row_nums']:
if len(cell['xml_text_content'].strip()) == 0:
cell_count = len(cell['column_nums'])
else:
cell_count = 1
cell_counts_by_row[row_num] += cell_count
if cell['is_column_header']:
header_status_by_row[row_num] = True
true_header_status_by_row = defaultdict(bool)
if header_status_by_row[0]:
for row_num in range(num_rows):
true_header_status_by_row[row_num] = True
if cell_counts_by_row[row_num] == num_columns:
break
true_header_rows = set([row_num for row_num, header_status in true_header_status_by_row.items() if header_status])
for cell in table_dict['cells']:
cell['is_column_header'] = len(set(cell['row_nums']).intersection(true_header_rows)) > 0
#---STANDARDIZE HEADERS: IF FIRST COLUMN IN HEADER IS BLANK, HEADER CONTINUES UNTIL NON-BLANK CELL---
min_nonblank_first_column_row = num_rows
header_rows = set()
for cell in table_dict['cells']:
if cell['is_column_header']:
for row_num in cell['row_nums']:
header_rows.add(row_num)
if 0 in cell['column_nums'] and len(cell['xml_text_content'].strip()) > 0:
min_nonblank_first_column_row = min(min_nonblank_first_column_row, min(cell['row_nums']))
if len(header_rows) > 0 and min_nonblank_first_column_row > max(header_rows) + 1:
header_rows = set(range(min_nonblank_first_column_row))
for cell in table_dict['cells']:
if header_rows & set(cell['row_nums']):
cell['is_column_header'] = True
#---STANDARDIZE PROJECTED ROW HEADERS: ABSORB BLANK CELLS INTO NON-BLANK CELLS---
non_projected_row_header_status_by_row = defaultdict(bool)
first_cell_by_row = dict()
cells_to_delete = []
for cell in table_dict['cells']:
# If there is a non-blank cell after the first column in the body, can't be a projected row header
if (not cell['is_column_header'] and len(cell['xml_text_content'].strip()) > 0
and min(cell['column_nums']) > 0 and len(cell['row_nums']) == 1):
non_projected_row_header_status_by_row[cell['row_nums'][0]] = True
# Note the first cell in each row, if it's not a supercell
elif len(cell['xml_text_content'].strip()) > 0 and min(cell['column_nums']) == 0 and len(cell['row_nums']) == 1:
first_cell_by_row[cell['row_nums'][0]] = cell
for cell in table_dict['cells']:
if (not cell['is_column_header'] and len(cell['xml_text_content'].strip()) == 0
and min(cell['column_nums']) > 0 and len(cell['row_nums']) == 1):
try:
row_num = cell['row_nums'][0]
if non_projected_row_header_status_by_row[row_num]:
continue
cell_to_join_with = first_cell_by_row[row_num]
cell_to_join_with['pdf_bbox'] = list(
Rect(cell_to_join_with['pdf_bbox']).include_rect(cell['pdf_bbox']))
cell_to_join_with['column_nums'] = list(set(cell_to_join_with['column_nums'] + cell['column_nums']))
cells_to_delete.append(cell)
except:
pass
for cell in cells_to_delete:
table_dict['cells'].remove(cell)
#---LABEL PROJECTED ROW HEADERS---
for cell in table_dict['cells']:
if not cell['is_column_header'] and len(cell['column_nums']) == num_columns:
cell['is_projected_row_header'] = True
else:
cell['is_projected_row_header'] = False
#---STANDARDIZE SUPERCELLS IN FIRST COLUMN: ABSORB BLANK CELLS INTO NON-BLANK CELLS---
first_column_cells_with_content_by_row = dict()
# Determine cells with content
for cell in table_dict['cells']:
if 0 in cell['column_nums']:
if len(cell['xml_text_content'].strip()) == 0:
continue
for row_num in cell['row_nums']:
first_column_cells_with_content_by_row[row_num] = cell
# For cells without content, determine cell to combine with
cells_to_delete = []
for cell in table_dict['cells']:
if 0 in cell['column_nums']:
if len(cell['xml_text_content'].strip()) == 0:
cell_to_join_with = None
for row_num in range(min(cell['row_nums'])-1, -1, -1):
if row_num in first_column_cells_with_content_by_row:
cell_to_join_with = first_column_cells_with_content_by_row[row_num]
break
if not cell_to_join_with is None:
# Cells must have same header status and same column numbers to be joined
if not (set(cell_to_join_with['column_nums']) == set(cell['column_nums'])
and cell_to_join_with['is_column_header'] == cell['is_column_header']):
continue
cell_to_join_with['row_nums'] = list(set(cell_to_join_with['row_nums'] + cell['row_nums']))
try:
cell_to_join_with['pdf_bbox'] = list(
Rect(cell_to_join_with['pdf_bbox']).include_rect(cell['pdf_bbox']))
except:
pass
cells_to_delete.append(cell)
for cell in cells_to_delete:
table_dict['cells'].remove(cell)
def aggregate_cell_bboxes(page, table_dict, cell_bboxes, rotated=False):
table_bbox = None
row_bboxes = {}
col_bboxes = {}
expanded_cell_bboxes = {}
cells = table_dict['cells']
for cell_num, cell in enumerate(cells):
try:
cell_bbox = cell_bboxes[cell_num]
except:
continue
if not cell_bbox:
continue
if not table_bbox:
table_bbox = [entry for entry in cell_bbox]
else:
table_bbox = [min(table_bbox[0], cell_bbox[0]),
min(table_bbox[1], cell_bbox[1]),
max(table_bbox[2], cell_bbox[2]),
max(table_bbox[3], cell_bbox[3])]
if table_bbox:
if is_portrait(page, table_bbox):
table_dict['pdf_is_rotated'] = 0
else:
table_dict['pdf_is_rotated'] = 1
rotated = bool(table_dict['pdf_is_rotated'])
for cell_num, cell in enumerate(cells):
max_row = max(cell['row_nums'])
min_row = min(cell['row_nums'])
max_col = max(cell['column_nums'])
min_col = min(cell['column_nums'])
if not min_col in col_bboxes:
col_bboxes[min_col] = [None, None, None, None]
if not min_row in row_bboxes:
row_bboxes[min_row] = [None, None, None, None]
if not max_col in col_bboxes:
col_bboxes[max_col] = [None, None, None, None]
if not max_row in row_bboxes:
row_bboxes[max_row] = [None, None, None, None]
try:
cell_bbox = cell_bboxes[cell_num]
except:
continue
cell_bbox = cell_bboxes[cell_num]
if not cell_bbox:
continue
if not rotated:
if col_bboxes[min_col][0]:
col_bboxes[min_col][0] = min(col_bboxes[min_col][0], cell_bbox[0])
else:
col_bboxes[min_col][0] = cell_bbox[0]
if row_bboxes[min_row][1]:
row_bboxes[min_row][1] = min(row_bboxes[min_row][1], cell_bbox[1])
else:
row_bboxes[min_row][1] = cell_bbox[1]
if col_bboxes[max_col][2]:
col_bboxes[max_col][2] = max(col_bboxes[max_col][2], cell_bbox[2])
else:
col_bboxes[max_col][2] = cell_bbox[2]
if row_bboxes[max_row][3]:
row_bboxes[max_row][3] = max(row_bboxes[max_row][3], cell_bbox[3])
else:
row_bboxes[max_row][3] = cell_bbox[3]
else:
if col_bboxes[min_col][1]:
col_bboxes[min_col][1] = min(col_bboxes[min_col][1], cell_bbox[1])
else:
col_bboxes[min_col][1] = cell_bbox[1]
if row_bboxes[min_row][0]:
row_bboxes[min_row][0] = min(row_bboxes[min_row][0], cell_bbox[0])
else:
row_bboxes[min_row][0] = cell_bbox[0]
if col_bboxes[max_col][3]:
col_bboxes[max_col][3] = max(col_bboxes[max_col][3], cell_bbox[3])
else:
col_bboxes[max_col][3] = cell_bbox[3]
if row_bboxes[max_row][2]:
row_bboxes[max_row][2] = max(row_bboxes[max_row][2], cell_bbox[2])
else:
row_bboxes[max_row][2] = cell_bbox[2]
if not rotated:
for row_num in row_bboxes:
row_bboxes[row_num][0] = table_bbox[0]
row_bboxes[row_num][2] = table_bbox[2]
for col_num in col_bboxes:
col_bboxes[col_num][1] = table_bbox[1]
col_bboxes[col_num][3] = table_bbox[3]
else:
for row_num in row_bboxes:
row_bboxes[row_num][1] = table_bbox[1]
row_bboxes[row_num][3] = table_bbox[3]
for col_num in col_bboxes:
col_bboxes[col_num][0] = table_bbox[0]
col_bboxes[col_num][2] = table_bbox[2]