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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
"""
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]
        
    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 rotated:
            expanded_cell_bbox = [col_bboxes[min_col][0],
                                  row_bboxes[min_row][1],
                                  col_bboxes[max_col][2],
                                  row_bboxes[max_row][3]]
        else:
            expanded_cell_bbox = [row_bboxes[min_row][0],
                                  col_bboxes[min_col][1],
                                  row_bboxes[max_row][2],
                                  col_bboxes[max_col][3]]
        expanded_cell_bboxes[cell_num] = expanded_cell_bbox
    
    return table_bbox, col_bboxes, row_bboxes, expanded_cell_bboxes


def table_text_edit_distance(cells):
    L = 0
    D = 0
    for cell in cells:
        xml_text = ''.join(cell['xml_text_content'].split())
        pdf_text = ''.join(cell['pdf_text_content'].split())
        L += len(xml_text) + len(pdf_text)
        D += 2 * editdistance.eval(xml_text, pdf_text)
    try:
        D = D / L
    except:
        D = 1
            
    return D, L


def is_good_bbox(bbox, page_bbox):
    if (not bbox[0] is None and not bbox[1] is None and not bbox[2] is None and not bbox[3] is None
            and bbox[0] >= 0 and bbox[1] >= 0 and bbox[2] <= page_bbox[2] and bbox[3] <= page_bbox[3]
            and bbox[0] < bbox[2]-1 and bbox[1] < bbox[3]-1):
        return True
    return False


def iob(bbox1, bbox2):
    """
    Compute the intersection area over box area, for bbox1.
    """
    intersection = Rect(bbox1).intersect(bbox2)
    return intersection.get_area() / Rect(bbox1).get_area()


def create_document_page_image(doc, page_num, output_image_max_dim=1000):
    page = doc[page_num]
    page_width = page.rect[2]
    page_height = page.rect[3]
    
    if page_height > page_width:
        zoom = output_image_max_dim / page_height
        output_image_height = output_image_max_dim
        output_image_width = int(round(output_image_max_dim * page_width / page_height))
    else:
        zoom = output_image_max_dim / page_width
        output_image_width = output_image_max_dim
        output_image_height = int(round(output_image_max_dim * page_height / page_width))
        
    mat = fitz.Matrix(zoom, zoom)
    pix = page.get_pixmap(matrix = mat, alpha = False)
    img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
    
    return img


def create_pascal_voc_page_element(image_filename, output_image_width, output_image_height, database):
    # Create XML of tables on PDF page in PASCAL VOC format
    annotation = ET.Element("annotation")

    folder = ET.SubElement(annotation, "folder").text = ""
    filename = ET.SubElement(annotation, "filename").text = image_filename
    path = ET.SubElement(annotation, "path").text = image_filename
    source = ET.SubElement(annotation, "source")
    database = ET.SubElement(source, "database").text = database
    size = ET.SubElement(annotation, "size")
    width = ET.SubElement(size, "width").text = str(output_image_width)
    height = ET.SubElement(size, "height").text = str(output_image_height)
    depth = ET.SubElement(size, "depth").text = "3"
    segmented = ET.SubElement(annotation, "segmented").text = "0"
    
    return annotation


def create_pascal_voc_object_element(class_name, bbox, page_bbox, output_image_max_dim=1000):
    bbox_area = fitz.Rect(bbox).get_area()
    if bbox_area == 0:
        raise Exception
    intersect_area = fitz.Rect(page_bbox).intersect(fitz.Rect(bbox)).get_area()
    if abs(intersect_area - bbox_area) > 0.1:
        print(bbox)
        print(bbox_area)
        print(page_bbox)
        print(intersect_area)
        raise Exception
    
    object_ = ET.Element("object")
    name = ET.SubElement(object_, "name").text = class_name
    pose = ET.SubElement(object_, "pose").text = "Frontal"
    truncated = ET.SubElement(object_, "truncated").text = "0"
    difficult = ET.SubElement(object_, "difficult").text = "0"
    occluded = ET.SubElement(object_, "occluded").text = "0"
    bndbox = ET.SubElement(object_, "bndbox")
    
    page_width = page_bbox[2] - page_bbox[0]
    page_height = page_bbox[3] - page_bbox[1]
    
    if page_width > page_height:
        output_image_width = output_image_max_dim
        output_image_height = int(output_image_max_dim * page_height / page_width)
    else:
        output_image_height = output_image_max_dim
        output_image_width = int(output_image_max_dim * page_width / page_height)

    xmin = (bbox[0] - page_bbox[0]) * output_image_width / page_width
    ymin = (bbox[1] - page_bbox[1]) * output_image_height / page_height
    xmax = (bbox[2] - page_bbox[0]) * output_image_width / page_width
    ymax = (bbox[3] - page_bbox[1]) * output_image_height / page_height
    
    ET.SubElement(bndbox, "xmin").text = "{0:.4f}".format(xmin)
    ET.SubElement(bndbox, "ymin").text = "{0:.4f}".format(ymin)
    ET.SubElement(bndbox, "xmax").text = "{0:.4f}".format(xmax)
    ET.SubElement(bndbox, "ymax").text = "{0:.4f}".format(ymax)
    
    return object_


def create_pascal_voc_object_element_direct(class_name, bbox):    
    object_ = ET.Element("object")
    name = ET.SubElement(object_, "name").text = class_name
    pose = ET.SubElement(object_, "pose").text = "Frontal"
    truncated = ET.SubElement(object_, "truncated").text = "0"
    difficult = ET.SubElement(object_, "difficult").text = "0"
    occluded = ET.SubElement(object_, "occluded").text = "0"
    bndbox = ET.SubElement(object_, "bndbox")
    
    ET.SubElement(bndbox, "xmin").text = "{0:.4f}".format(bbox[0])
    ET.SubElement(bndbox, "ymin").text = "{0:.4f}".format(bbox[1])
    ET.SubElement(bndbox, "xmax").text = "{0:.4f}".format(bbox[2])
    ET.SubElement(bndbox, "ymax").text = "{0:.4f}".format(bbox[3])
    
    return object_


def save_xml_pascal_voc(page_annotation, filepath):
    xmlstr = minidom.parseString(ET.tostring(page_annotation)).toprettyxml(indent="   ")
    with open(filepath, "w") as f:
        f.write(xmlstr)
        
        
def bbox_pdf_to_image(bbox, page_bbox, output_image_max_dim=1000):
    page_width = page_bbox[2] - page_bbox[0]
    page_height = page_bbox[3] - page_bbox[1]
    
    if page_width > page_height:
        output_image_width = output_image_max_dim
        output_image_height = int(output_image_max_dim * page_height / page_width)
    else:
        output_image_height = output_image_max_dim
        output_image_width = int(output_image_max_dim * page_width / page_height)

    xmin = (bbox[0] - page_bbox[0]) * output_image_width / page_width
    ymin = (bbox[1] - page_bbox[1]) * output_image_height / page_height
    xmax = (bbox[2] - page_bbox[0]) * output_image_width / page_width
    ymax = (bbox[3] - page_bbox[1]) * output_image_height / page_height
    
    return [xmin, ymin, xmax, ymax]


def save_json(page_annotation_json, filepath):
    with open(filepath, 'w') as outfile:
        json.dump(page_annotation_json, outfile, indent=4)


def get_tokens_in_table_img(page_words, table_img_bbox):
    tokens = []
    for word_num, word in enumerate(page_words):
        word['flags'] = 0
        word['span_num'] = word_num
        word['line_num'] = 0
        word['block_num'] = 0
        tokens.append(word)

    tokens_in_table = [token for token in tokens if iob(token['bbox'], table_img_bbox) >= 0.5]
    
    return tokens_in_table

def temp():
    count = 0
    good_count = 0
    annotation_files_by_pmc_id = [] # fix this
    total = len(annotation_files_by_pmc_id)
    for idx in range(0, total):
        pmc_id = pmc_ids[idx]
        annotation_file = annotation_files_by_pmc_id[pmc_id]
        count += 1
        if count < restart_point:
            continue

        annotation_filepath = os.path.join(annotations_directory, annotation_file)
            
        # Read table annotations, if they exist
        # Open table file
        with open(annotation_filepath, 'r', encoding='utf-8') as infile:
            table_dicts = json.load(infile)
            
        # Each table has associated bounding boxes
        for table_num, table_entry in enumerate(table_dicts):
            try:
                if not 'pdf' in table_entry:
                    continue
                split = table_entry['split']
                rotated = table_entry['pdf']['rotated']
                
                page_num = table_entry['pdf']['page_num']          
        
                # Create detection PASCAL VOC XML file and page image
                page_bbox = table_entry['pdf']['page']['bbox']

                # Get page image            
                table_image_filename = pmc_id + "_table_" + str(table_num) + ".jpg"
                table_image_filepath = os.path.join(structure_image_directory, table_image_filename)
                if os.path.exists(table_image_filepath):
                    img = Image.open(table_image_filepath)
                else:
                    print(table_image_filepath)
                    
                xml_filename = pmc_id + "_table_" + str(table_num) + ".xml"
                xml_filepath = os.path.join(structure_pascal_voc_directory, split, xml_filename)
                if not os.path.exists(xml_filepath):
                    print(xml_filepath)
                    
                page_words_filepath = os.path.join(page_words_data_directory, pmc_id + "_" + str(page_num) + ".json")
                with open(page_words_filepath, 'r') as f:
                    page_words = json.load(f)
                if 'words' in page_words:
                    page_words = page_words['words']
                    
                # Crop
                table_bbox = table_entry['pdf_bbox']
                crop_bbox = [table_bbox[0]-padding,
                            table_bbox[1]-padding,
                            table_bbox[2]+padding,
                            table_bbox[3]+padding]
                zoom = 1000 / max(page_bbox)
                
                tokens_in_table_img = get_tokens_in_table_img(page_words, crop_bbox)
                #print(tokens_in_table_img)
                
                for token in tokens_in_table_img:
                    bbox = token['bbox']
                    bbox[0] = bbox[0] * zoom
                    bbox[1] = bbox[1] * zoom
                    bbox[2] = bbox[2] * zoom
                    bbox[3] = bbox[3] * zoom
                    token['bbox'] = bbox
                
                # Convert to image coordinates
                crop_bbox = [int(round(zoom*elem)) for elem in crop_bbox]
                
                # Keep within image
                crop_bbox = [max(0, crop_bbox[0]),
                            max(0, crop_bbox[1]),
                            min(img.size[0], crop_bbox[2]),
                            min(img.size[1], crop_bbox[3])]
                
                for token in tokens_in_table_img:
                    bbox = token['bbox']
                    bbox[0] = (bbox[0] - crop_bbox[0] - 1)
                    bbox[1] = (bbox[1] - crop_bbox[1] - 1)
                    bbox[2] = (bbox[2] - crop_bbox[0] - 1)
                    bbox[3] = (bbox[3] - crop_bbox[1] - 1)
                    token['bbox'] = bbox
                
                #img = img.crop(crop_bbox)                    
                    
                # If rotated, rotate:
                if rotated:
                    for entry in tokens_in_table_img:
                        bbox = entry['bbox']
                        bbox = [img.size[0]-bbox[3]-2,bbox[0],img.size[0]-bbox[1]-2,bbox[2]]
                        entry['bbox'] = bbox
                        
                table_words_filename = pmc_id + "_table_" + str(table_num) + "_words.json"
                table_words_filepath = os.path.join(table_words_data_directory, table_words_filename)
                #print(table_words_filepath)
                with open(table_words_filepath, 'w', encoding='utf8') as f:
                    json.dump(tokens_in_table_img, f)

            except KeyboardInterrupt:
                break
            except FileNotFoundError:
                print("error")
                print(traceback.format_exc())
                pass
            except Exception as err:
                print("error")
                print(traceback.format_exc())
                print("idx: {}".format(idx))
            
        print("{}/{}".format(idx, total), end="\r")

def get_args():
    parser = argparse.ArgumentParser()

    parser.add_argument('--data_dir',
                        help="Root directory for source data to process")
    parser.add_argument('--output_dir',
                        help="Root directory for output data")
    parser.add_argument('--verbose', action='store_true')
    parser.add_argument('--timeout_seconds', type=int, default=90)
    parser.add_argument('--det_db_name', default='My-PubTables-Detection')
    parser.add_argument('--str_db_name', default='My-PubTables-Structure')
    parser.add_argument('--train_padding', type=int, default=30,
                        help="The amount of padding to add around a table in the training set when cropping.")
    parser.add_argument('--test_padding', type=int, default=5,
                        help="The amount of padding to add around a table in the val and test sets when cropping.")
    return parser.parse_args()


def main():
    args = get_args()

    source_directory = args.data_dir
    timeout_seconds = args.timeout_seconds
    detection_db_name = args.det_db_name
    structure_db_name = args.str_db_name
    VERBOSE = args.verbose
    # TODO: Incorporate a train/test/val split and change padding for test/val sets
    padding = args.train_padding

    output_directory = args.output_dir # root location where to save data
    det_xml_dir = os.path.join(output_directory, detection_db_name, "unsplit_xml")
    det_img_dir = os.path.join(output_directory, detection_db_name, "images")
    det_words_dir = os.path.join(output_directory, detection_db_name, "words")
    str_xml_dir = os.path.join(output_directory, structure_db_name, "unsplit_xml")
    str_img_dir = os.path.join(output_directory, structure_db_name, "images")
    str_words_dir = os.path.join(output_directory, structure_db_name, "words")
    pdf_annot_dir = os.path.join(output_directory, "My-PubTables-PDF-Annotations")

    dirs = [det_xml_dir, det_img_dir, det_words_dir,
            str_xml_dir, str_img_dir, str_words_dir, pdf_annot_dir]
    for di in dirs:
        if not os.path.exists(di):
            os.makedirs(di)

    '''
    Get a list of all PDF-XML document pairs
    '''
    xml_files_by_pmc_id = {}
    pdf_files_by_pmc_id = {}

    pdf_list_filepath = os.path.join(source_directory, "pdf_filelist.txt")
    if os.path.exists(pdf_list_filepath):
        with open(pdf_list_filepath) as f:
            for elem in f.readlines():
                elem = elem.strip()
                elem_xml = elem.replace(".pdf", ".nxml")
                pmc_id = elem.split("/")[0]
                xml_files_by_pmc_id[pmc_id] = elem_xml
                pdf_files_by_pmc_id[pmc_id] = elem
    else:
        dirs = os.listdir(source_directory)
        print(dirs)
        for d in dirs:
            if d.startswith("PMC"):
                dir_path = os.path.join(source_directory, d)
                if not os.path.isdir(dir_path):
                    continue
                dir_files = os.listdir(dir_path)
                for fi in dir_files:
                    if fi.endswith(".pdf"):
                        if fi.replace(".pdf", ".nxml") in dir_files:
                            pdf_file = os.path.join(d, fi)
                            pdf_files_by_pmc_id[d] = pdf_file
                            xml_files_by_pmc_id[d] = pdf_file.replace(".pdf", ".nxml")

    pdf_files = list(pdf_files_by_pmc_id.values())

    num_files = len(pdf_files)
    print(num_files)

    output_image_max_dim = 1000

    start_point = 0
    end_point = 10 #start_point + 2

    # Progress tracking
    skipped_files = 0
    parsed_instances = 0
    annotated_tables = 0
    exception_count = 0
    timeout_count = 0
    table_encounters = 0
    low_quality_tables = 0
    tables_for_detection = 0
    table_image_count = 0

    '''
    Process each PDF-XML file pair to annotate the tables in the PDF.
    '''
    print("Num files total: {}".format(num_files))
    print("Annotating files {}-{}".format(start_point, end_point-1))
    for idx, pdf_file in enumerate(pdf_files):
        if idx < start_point:
            continue
        if idx >= end_point:
            break
        
        pmc_id = pdf_file.split("/")[0]
        split = "train" # fix this: split_by_pmc_id[pmc_id]
        save_filepath = os.path.join(pdf_annot_dir, pmc_id + "_tables.json")
        
        print(pdf_file)
        pdf_path = os.path.join(source_directory, pdf_file)
        xml_path = pdf_path.replace(".pdf", ".nxml")
        
        print("PROGRESS: {}/{} ({}/{}). {} files skipped. Table instances: {} parsed, {} fully annotated.  ".format(
            idx-start_point+1, end_point-start_point, idx, num_files, skipped_files, parsed_instances, 
            annotated_tables), flush=True)
        
        try:       
            if VERBOSE: print("Reading XML...", end='')
            xml_string = read_xml(xml_path)
            #print(xml_string)
            table_dicts = extract_table_xmls_from_document(xml_string)
            
            num_tables_parsed = len(table_dicts)
            parsed_instances += num_tables_parsed
            if VERBOSE: print(" {} tables found.".format(num_tables_parsed))
        except Exception as e:
            print(e)
            print("Error during XML reading/parsing.")
            skipped_files += 1
            continue
            
        if num_tables_parsed == 0:
            continue

        try:
            print("Reading PDF")
            doc = read_pdf(pdf_path)
        except:
            print("Error during PDF reading.")
            skipped_files += 1
            continue

        annotated_table_dicts = []
        for table_idx, table_dict in enumerate(table_dicts):
            table_dict['xml_table_index'] = table_idx
            
            table_encounters += 1
            try:
                #-------------------#
                # PARSING
                #-------------------#
                if VERBOSE: print("Parsing table XML...")
                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]
                #print(table_xml)
                table_dict = parse_xml_table(xml_string, table_dict)
                #print(table_dict)

                if table_dict:
                    if len(table_dict['cells']) == 0:
                        print("Table has no annotated cells; could be a graphic")
                        continue
                    clean_xml_annotation(table_dict)
                    
                    #-------------------#
                    # ALIGNMENT
                    #-------------------#                
                    if VERBOSE: print("Locating table page...")
                    with timeout(seconds=timeout_seconds):
                        table_page_num, scores = get_table_page(doc, table_dict)
                        table_dict['pdf_page_index'] = table_page_num
                    print(table_page_num)

                    page = doc[table_page_num]
                    page_words = get_page_words(page)
                    table_dict['pdf_full_page_bbox'] = list(page.rect)

                    if VERBOSE: print("Locating table bounding box...")
                    with timeout(seconds=timeout_seconds):
                        cell_bboxes, word_bboxes = locate_table(page, table_dict)

                    if not cell_bboxes:
                        print("No cell bboxes")
                        continue

                    #-------------------#
                    # COMPLETION
                    #-------------------#
                    table_bbox, col_bboxes, row_bboxes, expanded_cell_bboxes = aggregate_cell_bboxes(page, table_dict,
                                                                                cell_bboxes)
                    if VERBOSE:
                        print("Table frame bbox: {}".format(table_bbox))
                    table_dict['pdf_table_bbox'] = table_bbox

                    caption_pieces = []
                    try:
                        label = table_dict['xml_caption_label_text']
                        if len(label) > 0:
                            caption_pieces.append(label)
                    except:
                        print(traceback.format_exc())

                    try:
                        text = table_dict['xml_caption_text']
                        if len(text) > 0:
                            caption_pieces.append(text)
                    except:
                        print(traceback.format_exc())
                    caption = " ".join(caption_pieces)

                    caption_bbox = []
                    table_dict['pdf_caption_page_num'] = None
                    table_dict['pdf_caption_bbox'] = []
                    table_dict['pdf_caption_word_bboxes'] = []
                    if len(caption) > 9:
                        if VERBOSE: print("Locating caption bounding box...")
                        with timeout(seconds=60):
                            caption_bbox, caption_word_bboxes = locate_caption(page, caption)

                        if len(caption_bbox) == 4:
                            table_dict['pdf_caption_page_num'] = table_page_num
                            table_dict['pdf_caption_bbox'] = caption_bbox
                            table_dict['pdf_caption_word_bboxes'] = caption_word_bboxes
                    if VERBOSE: print("Caption bbox: {}".format(caption_bbox))

                    footer_bbox = []
                    footer = table_dict['xml_table_footer_text']
                    table_dict['pdf_table_footer_page_num'] = None
                    table_dict['pdf_table_footer_bbox'] = []
                    table_dict['pdf_table_footer_word_bboxes'] = []
                    if len(footer) > 9:
                        if VERBOSE: print("Locating footer bounding box...")
                        with timeout(seconds=60):
                            footer_bbox, footer_word_bboxes = locate_caption(page, footer)

                        if len(footer_bbox) == 4:
                            table_dict['pdf_table_footer_page_num'] = table_page_num
                            table_dict['pdf_table_footer_bbox'] = footer_bbox
                            table_dict['pdf_table_footer_word_bboxes'] = footer_word_bboxes
                    if VERBOSE: print("Footer bbox: {}".format(footer_bbox))
                        
                    header_rows = set()
                    for cell in table_dict['cells']:
                        if cell['is_column_header']:
                            header_rows = header_rows.union(set(cell['row_nums']))

                    table_wrap_bbox = Rect(table_bbox)
                    if len(caption_bbox) == 4:
                        table_wrap_bbox.include_rect(caption_bbox)
                    if len(footer_bbox) == 4:
                        table_wrap_bbox.include_rect(footer_bbox)
                    table_dict['pdf_table_wrap_bbox'] = list(table_wrap_bbox)
                    table_dict['rows'] = [{} for row_num in row_bboxes]
                    for row_num in row_bboxes:
                        table_dict['rows'][row_num]['pdf_row_bbox'] = row_bboxes[row_num]
                        table_dict['rows'][row_num]['is_column_header'] = row_num in header_rows
                    table_dict['columns'] = [{} for col_num in col_bboxes]
                    for column_num in col_bboxes:
                        table_dict['columns'][column_num]['pdf_column_bbox'] = col_bboxes[column_num]
                    for cell_num, cell in enumerate(table_dict['cells']):
                        cell['pdf_bbox'] = expanded_cell_bboxes[cell_num]
                        cell['pdf_text_tight_bbox'] = cell_bboxes[cell_num]
                        if not cell_bboxes[cell_num] is None:
                            pdf_text_content, _ = extract_text_inside_bbox(page_words, cell_bboxes[cell_num])
                        else:
                            pdf_text_content = ""
                        cell['pdf_text_content'] = pdf_text_content
                    table_dict['pdf_word_bboxes'] = word_bboxes

                    #-------------------#
                    # CANONICALIZATION
                    #-------------------#
                    try:
                        fix_caption_and_footer(doc, table_dict)
                        
                        if VERBOSE:
                            print("Adjusted caption bbox: {}".format(table_dict['pdf_caption_bbox']))
                            print("Adjusted footer bbox: {}".format(table_dict['pdf_table_footer_bbox']))
                    except:
                        print(traceback.format_exc())
                    try:
                        standardize_and_fix_xml_annotation(table_dict)
                    except:
                        print(traceback.format_exc())
                        
                    #-------------------#
                    # QUALITY CONTROL
                    #-------------------#
                    D, _ = table_text_edit_distance(table_dict['cells'])
                    if VERBOSE:
                        print("Table text content annotation disagreement score: {}".format(D))
                    if D > 0.05:
                        low_quality_tables += 1
                        print(">>>> LOW QUALITY TABLE ANNOTATION <<<<")
                        continue
                        
                    #-------------------#
                    # CLEANUP
                    #-------------------#
                    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']
                    if 'pdf_table_footer_word_bboxes' in table_dict:
                        del table_dict['pdf_table_footer_word_bboxes']
                        
                    #-------------------#
                    # SAVE
                    #-------------------#
                        
                    table_dict['pmc_id'] = pmc_id
                    table_dict['pdf_file_name'] = pdf_file.split("/")[-1]
                    table_dict['xml_file_name'] = table_dict['pdf_file_name'].replace(".pdf", ".nxml")
                    table_dict['split'] = split
                    table_dict['structure_id'] = pmc_id + "_table_" + str(table_idx)

                    annotated_tables += 1
                    annotated_table_dicts.append(table_dict)
            except KeyboardInterrupt:
                break
            except TimeoutError:
                table_dict['timeout'] = True
                print("#### TIMEOUT ####")
                annotated_table_dicts.append(table_dict)
                timeout_count += 1
            except:
                print("**** EXCEPTION ****")
                print(traceback.format_exc())
                exception_count += 1
                
        # While this is pretty strict and will exclude some tables for detection that could be included,
        # it's the only way to ensure that tables included for detection are correct using an automated method.
        # If every table in the XML passes the checks, then we know that no page image will have a missing or
        # incomplete table annotation.
        if len(annotated_table_dicts) == len(table_dicts):
            exclude_for_detection = False
            tables_for_detection += len(table_dicts)
        else:
            exclude_for_detection = True
            if VERBOSE:
                print("Not all tables fully annotated and passed quality control. Exclude these for detection.")
        for table_dict in annotated_table_dicts:
            table_dict['exclude_for_detection'] = exclude_for_detection
            
        #-----------------------------------#
        # TABLE DETECTION IMAGE DATA
        #-----------------------------------#
        if not exclude_for_detection:
            detection_boxes_by_page = defaultdict(list)     
            
            # Each table has associated bounding boxes
            for table_dict in annotated_table_dicts:
                if 'timeout' in table_dict and table_dict['timeout']:
                    continue
                try:
                    table_boxes = []

                    rotated = table_dict['pdf_is_rotated']
                    page_num = table_dict['pdf_page_index']

                    # Create detection data
                    if rotated:
                        class_label = 'table rotated'
                    else:
                        class_label = 'table'
                    dict_entry = {'class_label': class_label, 'bbox': table_dict['pdf_table_bbox']}
                    detection_boxes_by_page[page_num].append(dict_entry)
                except Exception as err:
                    print(traceback.format_exc())

                # Create detection PASCAL VOC XML file and page image
                for page_num, boxes in detection_boxes_by_page.items():
                    try:
                        page_bbox = list(doc[page_num].rect)
                        if not all([is_good_bbox(entry['bbox'], page_bbox) for entry in boxes]):
                            raise Exception("At least one bounding box has non-positive area or is outside of image")

                        # Create page image            
                        image_filename = pmc_id + "_" + str(page_num) + ".jpg"
                        image_filepath = os.path.join(det_img_dir, image_filename)
                        img = create_document_page_image(doc, page_num, output_image_max_dim=output_image_max_dim)
                        img.save(image_filepath)

                        # Initialize PASCAL VOC XML
                        page_annotation = create_pascal_voc_page_element(image_filename, img.width, img.height,
                                                                        database=detection_db_name)

                        for entry in boxes:
                            # Add to PASCAl VOC
                            element = create_pascal_voc_object_element(entry['class_label'],
                                                                    entry['bbox'], page_bbox,
                                                                    output_image_max_dim=output_image_max_dim)
                            page_annotation.append(element)   
                            
                        xml_filename = pmc_id + "_" + str(page_num) + ".xml"
                        xml_filepath = os.path.join(det_xml_dir, xml_filename)
                        save_xml_pascal_voc(page_annotation, xml_filepath)

                        page_words_filename = xml_filename.replace(".xml", "_words.json")
                        page_words_filepath = os.path.join(det_words_dir, page_words_filename)

                        page = doc[page_num]
                        page_words = get_page_words(page)
                        zoom = 1000 / max(page.rect)
                        for word in page_words:
                            word['bbox'] = [zoom*elem for elem in word['bbox']]
                        with open(page_words_filepath, 'w') as f:
                            json.dump(page_words, f)
                    except Exception as err:
                        print(traceback.format_exc())

        # Save results for this document
        if VERBOSE: print(save_filepath)
        save_full_tables_annotation(annotated_table_dicts, save_filepath)
        if VERBOSE: print("DETECTION SAMPLE SAVED!")

        #-----------------------------------#
        # TABLE STRUCTURE IMAGE DATA
        #-----------------------------------#
        for table_num, table_entry in enumerate(annotated_table_dicts):
            if 'timeout' in table_entry and table_entry['timeout']:
                continue

            try:
                table_boxes = []
                    
                # Check if table has at least two columns
                num_columns = table_entry['num_columns']
                if num_columns < 2:
                    continue
                if not 'columns' in table_entry:
                    continue
                    
                # Check if table has at least one row
                num_rows = table_entry['num_rows']
                if num_rows < 1:
                    continue
                if not 'rows' in table_entry:
                    continue
                
                rotated = table_entry['pdf_is_rotated']
                
                page_num = table_entry['pdf_page_index']          

                # Create structure recognition data
                dict_entry = {'class_label': 'table', 'bbox': table_entry['pdf_table_bbox']}
                table_boxes.append(dict_entry)
                
                # Dilation
                if rotated:
                    row1_idx = 2
                    row2_idx = 0
                    col1_idx = 1
                    col2_idx = 3
                else:
                    row1_idx = 3
                    row2_idx = 1
                    col1_idx = 2
                    col2_idx = 0
                rows = table_entry['rows']
                rows = sorted(rows, key=lambda k: k['pdf_row_bbox'][row1_idx]) 
                if len(rows) > 1:
                    for row1, row2 in zip(rows[:-1], rows[1:]):
                        mid_point = (row1['pdf_row_bbox'][row1_idx] + row2['pdf_row_bbox'][row2_idx]) / 2
                        row1['pdf_row_bbox'][row1_idx] = mid_point
                        row2['pdf_row_bbox'][row2_idx] = mid_point
                columns = table_entry['columns']
                if rotated:
                    columns = sorted(columns, key=lambda k: -k['pdf_column_bbox'][col1_idx])
                else:
                    columns = sorted(columns, key=lambda k: k['pdf_column_bbox'][col1_idx]) 
                if len(columns) > 1:
                    for col1, col2 in zip(columns[:-1], columns[1:]):
                        mid_point = (col1['pdf_column_bbox'][col1_idx] + col2['pdf_column_bbox'][col2_idx]) / 2
                        col1['pdf_column_bbox'][col1_idx] = mid_point
                        col2['pdf_column_bbox'][col2_idx] = mid_point
                for cell in table_entry['cells']:
                    column_nums = cell['column_nums']
                    row_nums = cell['row_nums']
                    column_rect = Rect()
                    row_rect = Rect()
                    for column_num in column_nums:
                        column_rect.include_rect(columns[column_num]['pdf_column_bbox'])
                    for row_num in row_nums:
                        row_rect.include_rect(rows[row_num]['pdf_row_bbox'])
                    cell_rect = column_rect.intersect(row_rect)
                    cell['pdf_bbox'] = list(cell_rect)
                
                header_rect = Rect()
                for cell in table_entry['cells']:
                    cell_bbox = cell['pdf_bbox']
                    blank = len(cell['xml_text_content'].strip()) == 0
                    supercell = len(cell['row_nums']) > 1 or len(cell['column_nums']) > 1
                    header = cell['is_column_header']
                    if not header and len(cell['column_nums']) == num_columns:
                        dict_entry = {'class_label': 'table projected row header', 'bbox': cell['pdf_bbox']}
                        table_boxes.append(dict_entry)                      
                    elif supercell and not blank:
                        dict_entry = {'class_label': 'table spanning cell', 'bbox': cell['pdf_bbox']}
                        table_boxes.append(dict_entry)                     
                        
                    if header:
                        header_rect.include_rect(cell_bbox)

                if header_rect.get_area() > 0:
                    dict_entry = {'class_label': 'table column header', 'bbox': list(header_rect)}
                    table_boxes.append(dict_entry)
                        
                for row in table_entry['rows']:
                    row_bbox = row['pdf_row_bbox']
                    dict_entry = {'class_label': 'table row', 'bbox': row_bbox}
                    table_boxes.append(dict_entry) 
                
                # table_entry['columns']
                for column in table_entry['columns']:
                    dict_entry = {'class_label': 'table column', 'bbox': column['pdf_column_bbox']}
                    table_boxes.append(dict_entry) 
        
                # Create detection PASCAL VOC XML file and page image
                page_bbox = table_entry['pdf_full_page_bbox']

                # Get page image            
                page_image_filename = pmc_id + "_" + str(page_num) + ".jpg"
                page_image_filepath = os.path.join(det_img_dir, page_image_filename)
                if os.path.exists(page_image_filepath):
                    img = Image.open(page_image_filepath)
                else:
                    #print("Creating image")
                    img = create_document_page_image(doc, page_num, output_image_max_dim=1000)
                    
                # Crop
                table_bbox = table_entry['pdf_table_bbox']
                crop_bbox = [table_bbox[0]-padding,
                            table_bbox[1]-padding,
                            table_bbox[2]+padding,
                            table_bbox[3]+padding]
                zoom = 1000 / max(page_bbox)
                
                # Convert to image coordinates
                crop_bbox = [int(round(zoom*elem)) for elem in crop_bbox]
                
                # Keep within image
                crop_bbox = [max(0, crop_bbox[0]),
                            max(0, crop_bbox[1]),
                            min(img.size[0], crop_bbox[2]),
                            min(img.size[1], crop_bbox[3])]
                
                img = img.crop(crop_bbox)                    
                for entry in table_boxes:
                    bbox = entry['bbox']
                    bbox = [zoom*elem for elem in bbox]
                    bbox = [bbox[0]-crop_bbox[0]-1,
                            bbox[1]-crop_bbox[1]-1,
                            bbox[2]-crop_bbox[0]-1,
                            bbox[3]-crop_bbox[1]-1]
                    entry['bbox'] = bbox
                    
                # If rotated, rotate:
                if rotated:
                    img = img.rotate(270, expand=True)
                    for entry in table_boxes:
                        bbox = entry['bbox']
                        bbox = [img.size[0]-bbox[3]-1,bbox[0],img.size[0]-bbox[1]-1,bbox[2]]
                        entry['bbox'] = bbox
                
                # Initialize PASCAL VOC XML
                table_image_filename = pmc_id + "_table_" + str(table_num) + ".jpg"
                table_image_filepath = os.path.join(str_img_dir, table_image_filename)
                table_annotation = create_pascal_voc_page_element(table_image_filename,
                                                                 img.width, img.height,
                                                                 database=structure_db_name)

                for entry in table_boxes:
                    bbox = entry['bbox']

                    # Add to PASCAl VOC
                    element = create_pascal_voc_object_element_direct(entry['class_label'],
                                                                      entry['bbox'])
                    table_annotation.append(element)              

                img.save(table_image_filepath)

                xml_filename = pmc_id + "_table_" + str(table_num) + ".xml"
                xml_filepath = os.path.join(str_xml_dir, xml_filename)
                if VERBOSE: print(xml_filepath)
                save_xml_pascal_voc(table_annotation, xml_filepath)

                table_words_filename = xml_filename.replace(".xml", "_words.json")
                table_words_filepath = os.path.join(str_words_dir, table_words_filename)

                page_words = get_page_words(doc[page_num])
                table_words = []
                for word_num, word in enumerate(page_words):
                    token = {}
                    token['flags'] = 0
                    token['span_num'] = word_num
                    token['line_num'] = 0
                    token['block_num'] = 0
                    bbox = [round(zoom * v, 5) for v in word['bbox']]
                    if iob(bbox, crop_bbox) > 0.75:
                        bbox = [max(0, bbox[0]-crop_bbox[0]-1),
                                max(0, bbox[1]-crop_bbox[1]-1),
                                min(img.size[0], bbox[2]-crop_bbox[0]-1),
                                min(img.size[1], bbox[3]-crop_bbox[1]-1)]
                        if (bbox[0] < 0 or bbox[1] < 0 or bbox[2] > img.size[0] or bbox[3] > img.size[1]
                            or bbox[0] > bbox[2] or bbox[1] > bbox[3]):
                            bad_box = True
                        else:
                            token['bbox'] = bbox
                            token['text'] = word['text']
                            table_words.append(token)
                with open(table_words_filepath, 'w') as f:
                    json.dump(table_words, f)

                table_image_count += 1
                if VERBOSE: print("STRUCTURE SAMPLE SAVED!")
            except KeyboardInterrupt:
                break
            except Exception as err:
                print("error")
                print(traceback.format_exc())
                print("idx: {}".format(idx))

    print("Number of table encounters: {}".format(table_encounters))
    print("Number of table annotations completed: {}".format(annotated_tables))
    print("Number of tables eligible for detection: {}".format(tables_for_detection))
    print("Number of low quality tables removed: {}".format(low_quality_tables))
    print("Number of exceptions: {}".format(exception_count))
    print("Numer of timeouts: {}".format(timeout_count))
    print("Numer of cropped tables saved in PASCAL VOC format: {}".format(table_image_count))

if __name__ == "__main__":
    main()