-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisual_ingestor.py
More file actions
6468 lines (6256 loc) · 295 KB
/
Copy pathvisual_ingestor.py
File metadata and controls
6468 lines (6256 loc) · 295 KB
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
# parse style
import copy
import operator
import pprint
import re
import string
import sys
from collections import OrderedDict, namedtuple
from itertools import groupby
from timeit import default_timer
from typing import Any, Dict, List
import numpy as np
from bs4 import BeautifulSoup
from warp_ingest.ingestor import line_parser
from warp_ingest.ingestor.visual_ingestor import (
block_renderer,
indent_parser,
order_fixer,
style_utils,
table_parser,
)
from warp_ingest.ingestor.visual_ingestor import vi_helper_utils as vhu
from warp_ingest.ingestor_utils.ing_named_tuples import (
BoxStyle,
LineStyle,
LocationKey,
)
from warp_ingest.ingestor_utils.parsing_utils import *
from warp_ingest.ingestor_utils.utils import sent_tokenize
base_font_size = 3
header_margin = 0.18 # don't touch this!
footer_margin = 0.1
line_height_threshold = 1.4 # used to be 1.8 - use statistics
table_col_threshold = 2.8 # 3.35# used to be 4.0 - use statistics
table_end_space_threshold = 2.2
JUSTIFIED_NORMAL_GAP_MULTIPLIER = 4.0
CURRENCY_TOKENS = ["$", "€", "£"]
LINE_DEBUG = False
LEVEL_DEBUG = False
MIXED_FONT_DEBUG = False
NO_INDENT = False
HF_DEBUG = False
REORDER_DEBUG = False
BLOCK_DEBUG = False
MERGE_DEBUG = False
PERFORMANCE_DEBUG = False
PROGRESS_DEBUG = True
pp = pprint.PrettyPrinter(indent=4, compact=True)
# List of items / p_tags which when returned need to be raised a flag
filter_out_pattern_list = [
".",
"_",
"�", # example ---> "start string . . . . . . . . .some other string"
]
PARENTHESIZED_HDR = r"^\s*\(([^\)]+)\)\s*$"
PAGE_NUM_HEADER = (
r"\s*[pP]age\s*\d+\s*" # Identify patterns like "Page 1" / "Page 1 of n"
)
filter_out_pattern = re.compile(
r"[" + "".join(filter_out_pattern_list) + "]{2,}"
) # 2 or more occurrences
filter_ls_pattern = re.compile(
r"^[" + "".join(filter_out_pattern_list) + "]{2,}"
) # Left side pattern
text_only_pattern = re.compile(r"[^a-zA-Z]+")
only_text_pattern = re.compile(r"^[^a-zA-Z$%]+$")
roman_only_pattern = re.compile(r"^[ixvIXV]+$")
not_a_number_pattern = re.compile(r"[^0-9]+")
single_char_pattern = re.compile(r"^[a-zA-Z]$")
non_alphanumeric_pattern = re.compile(r"[^A-Za-z0-9]+")
year_pattern = re.compile(r"^(1|2)\d{3}$")
number_in_braces_pattern = re.compile(r"(\(\d+\))")
page_num_pattern = re.compile(PAGE_NUM_HEADER, re.IGNORECASE)
parenthesized_hdr_pattern = re.compile(PARENTHESIZED_HDR)
ends_with_sentence_delimiter_pattern = re.compile(
r"(?<![.;:][a-zA-Z0-9])(?<!INC|inc|Inc)[.;:]+(?![\w])[\"“‘’”\'\s]*$"
)
section_num_pattern = re.compile(r"^\d+(\.\d+)*\.?$")
floating_number_pattern = re.compile(r"\d+([.]?\d+[.]?)*")
section_generic_pattern = re.compile(
r"section(?!\s+\d+\.*\d*\.*[(])(\s+\d+\.*\d*\.*[,\-;\w\s]+\.\s*)", re.MULTILINE
)
integer_pattern = re.compile(r"(?<![\d.])[0-9]+(?![\d.])")
start_punct_pattern = re.compile(r"^[.,;:\"“‘’”\']")
email_pattern = re.compile(
r"([A-Za-z0-9]+[.\-_])*[A-Za-z0-9]+@[A-Za-z0-9-]+(\.[A-Z|a-z]{2,})+"
)
def get_block_type(group_is_list, group_is_table_row, group_text):
block_type = "para"
line_props = line_parser.bare_line(group_text)
if group_is_list:
block_type = "list_item"
elif group_is_table_row:
block_type = "table_row"
elif line_props.is_header:
block_type = "header"
return block_type, line_props
class Doc:
def __init__(
self, pages, ignore_blocks, render_format: str = "all", audited_bbox=None
):
self.pages = pages
self.line_style_classes = dict()
self.class_line_styles = dict()
self.class_stats = dict()
self.render_format = render_format
self.html_str = ""
self.json_dict = None
self.blocks = []
self.header_styles = []
self.normal_styles = []
self.footnote_styles = []
self.blocks_by_page = []
self.ignore_blocks = ignore_blocks
self.class_levels = OrderedDict()
self.file_stats = {}
self.para_classes = set()
self.class_freq_order = {}
self.page_width = 0
self.page_height = 0
self.line_style_space_stats = {}
self.line_style_word_space_stats = {}
self.line_style_word_stats = {}
self.visual_line_word_stats = {}
self.is_justified = False
self.page_styles = (
[]
) # Style specific to a page. Height, width, space stats etc.
self.audited_bbox = audited_bbox
self.audited_table_bbox = {}
self.page_svg_tags = []
if PERFORMANCE_DEBUG:
self.wall_time = default_timer()
self.parse(pages)
def parse(self, pages):
pages = pages
group_buf = []
grouped_body_str = "<body>"
class_name = "none"
group_is_list = False
group_is_table_row = False
blocks = []
block_idx = 0
class_blocks = []
group_reason = ""
page_headers = dict()
page_footers = dict()
last_line_counts = {}
page_p_styles = []
page_idx = 0
blocks_by_page = []
page_blocks = []
vl_word_counts = []
soup = BeautifulSoup()
if self.audited_bbox:
# Group by page_idx for later usage.
table_query = {"block_type": "table"}
for page_id, bboxes in groupby(
audited_bbox, key=lambda bbox: bbox.page_idx
):
list_of_bbox = list(bboxes)
self.audited_bbox[page_id] = list_of_bbox
self.audited_table_bbox[page_id] = list(
self.filter_list_of_bbox(list_of_bbox, **table_query)
)
if BLOCK_DEBUG:
print("Audited Table Boxes: ", self.audited_table_bbox)
for page_idx, page in enumerate(pages):
all_p = page.find_all("p")
svg_children = page.find("svg") or []
lines_tag_list, rect_tag_list = Doc.remove_duplicate_svg_tags(
soup, svg_children
)
self.page_svg_tags.append([lines_tag_list, rect_tag_list])
# page_style = pages[0].attrs["style"]
page_style = (
pages[page_idx].attrs.get("style", None) or pages[0].attrs["style"]
)
page_style_kv = style_utils.get_style_kv(page_style)
page_width = style_utils.parse_px(page_style_kv["width"])
self.page_width = self.page_width or page_width
page_height = style_utils.parse_px(page_style_kv["height"])
self.page_height = self.page_height or page_height
header_cutoff = header_margin * page_height
footer_cutoff = self.page_height - footer_margin * self.page_height
# print("page_dims: ", page_width, page_height)
# print("margins: ", header_margin*page_height, footer_margin*page_height)
p_styles = []
prev_box_style = None
prev_line_style = None
page_line_stats = {}
prev_p_tag = None
for line_idx, orig_p in enumerate(all_p):
# Reformat p if the text contains items to be replaced.
new_p = None
changed = False
if filter_out_pattern.search(orig_p.text) is not None:
new_p, changed = style_utils.format_p_tag(
orig_p, filter_out_pattern, filter_ls_pattern, soup
)
if orig_p.text.strip() == "":
orig_p.decompose()
line_idx += 1
continue
p_list = [orig_p]
if new_p:
if prev_p_tag:
prev_p_tag.insert_after(new_p)
else:
page.insert(0, new_p)
p_list = [new_p, orig_p]
for p in p_list:
# One BS4 text walk per tag; p is not mutated below.
p_text = p.text
if line_idx > len(all_p) - 3:
text_only = text_only_pattern.sub("", p_text).strip()
if not (
text_only == "" and year_pattern.search(p_text) is None
):
# Possible year?
if text_only not in last_line_counts:
last_line_counts[text_only] = 1
else:
last_line_counts[text_only] = (
last_line_counts[text_only] + 1
)
box_style, line_style, word_line_styles = (
style_utils.parse_tika_style(p["style"], p_text, page_width)
)
is_page_header = box_style[0] < header_cutoff # Check box_style.top
is_page_footer = box_style[0] > footer_cutoff # Check box_style.top
loc_key = "N/A"
if is_page_header or is_page_footer:
loc_key = Doc.get_location_key(box_style, p.text)
if is_page_header:
if loc_key in page_headers:
page_headers[loc_key].append(page_idx)
else:
page_headers[loc_key] = [page_idx]
else:
if loc_key in page_footers:
page_footers[loc_key].append(page_idx)
else:
page_footers[loc_key] = [page_idx]
p_styles.append(
(
box_style,
line_style,
word_line_styles,
loc_key,
is_page_header,
is_page_footer,
changed,
),
)
if len(p_text) > 0:
word_count = len(p_text.split())
vl_word_counts.append(word_count)
if line_style not in self.line_style_word_stats:
self.line_style_word_stats[line_style] = []
self.line_style_word_stats[line_style].append(word_count)
if prev_line_style == line_style:
same_top = prev_box_style[0] == box_style[0]
if not same_top:
space = round(box_style[0] - prev_box_style[0], 1)
if space > 0:
if line_style not in self.line_style_space_stats:
self.line_style_space_stats[line_style] = []
self.line_style_space_stats[line_style].append(space)
# Add to page_line_stats.
if line_style not in page_line_stats:
page_line_stats[line_style] = {
"lines": 0,
"space_counts": {},
}
page_line_stats[line_style]["lines"] += 1
if (
space
not in page_line_stats[line_style]["space_counts"]
):
page_line_stats[line_style]["space_counts"][
space
] = 0
page_line_stats[line_style]["space_counts"][space] += 1
else:
word_space = round(box_style[1] - prev_box_style[2], 1)
if word_space > 0:
if line_style not in self.line_style_word_space_stats:
self.line_style_word_space_stats[line_style] = []
self.line_style_word_space_stats[line_style].append(
word_space
)
prev_box_style = box_style
prev_line_style = line_style
prev_p_tag = p
changed = False # Reset the change here. Change is meant for only the first p_tag
page_p_styles.append(p_styles)
# Calculate the page stats.
# Max number of lines and most frequent space gaps between lines etc
max_lines = 0
most_freq_spaces = {}
for line_style in page_line_stats:
max_lines = max(max_lines, page_line_stats[line_style]["lines"])
max_count = 0
ls_most_freq_space = -1
for space, space_count in page_line_stats[line_style][
"space_counts"
].items():
if space_count > max_count:
max_count = space_count
ls_most_freq_space = space
most_freq_spaces[ls_most_freq_space] = (
most_freq_spaces.get(ls_most_freq_space, 0) + max_count
)
most_freq_space = 0
if most_freq_spaces:
most_freq_space = max(
most_freq_spaces.items(), key=operator.itemgetter(1)
)[0]
page_stats = {"lines": max_lines, "most_frequent_space": most_freq_space}
self.page_styles.append(
(page_style_kv, page_width, page_height, page_stats)
)
if PERFORMANCE_DEBUG:
new_wall_time = default_timer()
print(
f"Checkpoint 1 Finished. Wall time: {((new_wall_time - self.wall_time) * 1000):.2f}ms"
)
self.wall_time = new_wall_time
for line_style in self.line_style_space_stats:
spaces = self.line_style_space_stats[line_style]
space_counts = {}
for space in spaces:
if space not in space_counts:
space_counts[space] = 0
space_counts[space] = space_counts[space] + 1
max_count = 0
most_frequent_space = -1
for space, space_count in space_counts.items():
if space_count > max_count:
max_count = space_count
most_frequent_space = space
self.line_style_space_stats[line_style] = {
"avg": np.mean(spaces) / line_style[2],
"median": np.median(spaces) / line_style[2],
"std": np.std(spaces),
"count": len(spaces),
"most_frequent_space": most_frequent_space,
"space_counts": space_counts,
}
for line_style in self.line_style_word_space_stats:
line_style_vl_word_spaces = self.line_style_word_space_stats[line_style]
self.line_style_word_space_stats[line_style] = {
"avg": np.mean(line_style_vl_word_spaces),
"median": np.median(line_style_vl_word_spaces),
"count": len(line_style_vl_word_spaces),
"std": np.std(line_style_vl_word_spaces),
}
for line_style in self.line_style_word_stats:
line_style_vl_word_counts = self.line_style_word_stats[line_style]
# print(line_style_vl_word_counts)
line_style_vl_word_stats_median = np.median(line_style_vl_word_counts)
self.line_style_word_stats[line_style] = {
"avg": np.mean(line_style_vl_word_counts),
"median": line_style_vl_word_stats_median,
"std": np.std(line_style_vl_word_counts),
"is_justified": line_style_vl_word_stats_median < 2,
"count": np.sum(line_style_vl_word_counts),
}
self.visual_line_word_stats = {
"avg": np.mean(vl_word_counts),
"median": np.median(vl_word_counts),
"std": np.std(vl_word_counts),
"count": np.sum(vl_word_counts),
}
self.is_justified = self.visual_line_word_stats["avg"] < 1.1
page_headers = Doc.find_true_header_footers(page_headers, len(pages))
page_footers = Doc.find_true_header_footers(
page_footers, len(pages), is_footer=True
)
if PERFORMANCE_DEBUG:
new_wall_time = default_timer()
print(
f"Checkpoint 2 Finished. Wall time: {((new_wall_time - self.wall_time) * 1000):.2f}ms"
)
self.wall_time = new_wall_time
for page_idx, page in enumerate(pages):
if not page_p_styles or not page_p_styles[page_idx]:
continue
# figure out page
all_p = page.find_all("p")
if PROGRESS_DEBUG:
print(
"processing page: ", page_idx, " Number of p_tags.... ", len(all_p)
)
line_idx = 0
oo_present = False
prev_filter_ignore = False
filter_pattern_ignored = False
has_lines_from_previous_page = len(group_buf) > 0
page_visual_lines = []
while line_idx < len(all_p):
if line_idx >= len(page_p_styles[page_idx]):
break
p = all_p[line_idx]
raw_p_text = p.text # one BS4 text walk per line
p_text = raw_p_text
for word, replacement in line_parser.unicode_list_types.items():
p_text = p_text.replace(word, replacement)
lp_line = line_parser.bare_line(p_text)
(
box_style,
line_style,
word_line_styles,
loc_key,
is_page_header,
is_page_footer,
changed,
) = page_p_styles[page_idx][line_idx]
# this section removes any unwanted lines e.g. line numbers, footers, ignore blocks etc.
should_ignore, filter_ignore = self.should_ignore_line(
all_p,
is_page_footer,
is_page_header,
last_line_counts,
line_idx,
loc_key,
lp_line,
raw_p_text,
page_footers,
page_headers,
page_idx,
box_style,
page_visual_lines,
)
# Items to be filtered out.
if prev_filter_ignore and len(page_visual_lines) > 0:
prev_filter_ignore = filter_ignore
# Check if the previous line is the same as the current one and both had to be filtered out.
if filter_ignore:
line_idx = line_idx + 1
filter_pattern_ignored = True
continue
elif filter_pattern_ignored:
# Flush out the last one remaining (the first one added to the list)
page_visual_lines = page_visual_lines[:-1]
if len(page_visual_lines) > 0:
last_vl = page_visual_lines[-1]
last_vl["changed"] = True
page_visual_lines[-1] = last_vl
filter_pattern_ignored = False
else:
prev_filter_ignore = filter_ignore
def check_ignore_line_within_retained(psv, bs):
if not len(psv):
return False
if (
abs(psv[-1]["box_style"][0] - bs[0]) <= bs[4]
and abs(psv[-1]["box_style"][2] - bs[1]) <= 20
):
return True
elif len(psv) > 1:
# Check for table cell elements
if (
abs(psv[-2]["box_style"][0] - psv[-1]["box_style"][0])
<= psv[-1]["box_style"][4]
):
if psv[-2]["box_style"][2] < psv[-1]["box_style"][1]:
gap = psv[-1]["box_style"][1] - psv[-2]["box_style"][2]
if (
abs(psv[-1]["box_style"][0] - bs[0]) <= bs[4]
and abs(psv[-1]["box_style"][2] - bs[1]) <= gap + 20
):
return True
return False
if (
should_ignore
and check_ignore_line_within_retained(page_visual_lines, box_style)
and p_text not in string.punctuation
):
should_ignore = False
if should_ignore:
if LINE_DEBUG:
print("Skipping curr line: ", p_text)
# Check we have some business to be taken care before we sign off the page.
if not (len(page_visual_lines) > 0 and line_idx == len(all_p) - 1):
line_idx = line_idx + 1
continue
# print(p.text, line_style)
line_info = {
"box_style": box_style,
"line_style": line_style,
"text": p_text,
"page_idx": page_idx,
"lp_line": lp_line,
"line_parser": lp_line.to_json(),
"should_ignore": should_ignore,
"changed": changed,
"ptag_idx": line_idx,
}
if LINE_DEBUG:
print("\n")
print("-" * 80)
print("curr line: ", line_info["text"])
# assign a style name to the font/line style (only font characteristics)
word_classes = []
prev_word_class = None
for word_idx, word_line_style in enumerate(word_line_styles):
word_class = self.get_class(word_line_style)
word_classes.append(word_class)
line_info["word_classes"] = word_classes
class_name = self.get_class(line_style)
line_info["class"] = class_name
page_visual_lines.append(line_info)
line_idx = line_idx + 1
(
page_blocks,
group_buf,
block_idx,
group_is_list,
vl_from_prev_page_discarded,
) = self.visual_lines_to_blocks(
page_visual_lines, group_buf, block_idx, group_is_list
)
# a page has ended
order_offset = 0
if has_lines_from_previous_page:
order_offset = 1
# Handle case with sections.
# header_modified & para
if (
len(page_blocks) > 1
and page_blocks[0]["page_idx"] == page_blocks[1]["page_idx"]
):
order_offset = 2
oo_fixer = order_fixer.OrderFixer(self, page_blocks, offset=order_offset)
page_blocks, is_reordered = oo_fixer.reorder()
for i in range(2):
if len(page_blocks) > 0 and Doc.has_page_number(
page_blocks[-1]["block_text"], last_line_counts
):
# print("---removing", page_blocks[-1]["block_text"])
page_blocks.pop()
# Last block in the previous page might get attached to the current page.
# Due to TIKA placing of p-tags, we might receive the first Visual Line as the last one,
# so try to correctly place them. Right now check only for top co-ordinate
page_block_start_block_num = 0
if (
has_lines_from_previous_page
and len(blocks_by_page[-1])
and len(page_blocks)
and not vl_from_prev_page_discarded
):
page_block_start_block_num = order_offset
last_page_blocks_len = len(blocks_by_page[-1])
t_blocks = []
page_block_added = False
block_top = page_blocks[0]["visual_lines"][0]["box_style"][0]
if order_offset == 1:
for count, b in enumerate(blocks[-last_page_blocks_len:]):
curr_box = b["visual_lines"][0]["box_style"]
curr_top = curr_box[0]
curr_bottom = curr_box[0] + curr_box[4]
if (
not page_block_added
and (
abs(block_top - curr_top) <= 15 or block_top < curr_top
)
and block_top < curr_bottom
):
page_blocks[0]["block_reordered"] = True
t_blocks.append(page_blocks[0])
t_blocks.append(b)
page_block_added = True
else:
t_blocks.append(b)
elif order_offset == 2:
t_blocks = blocks[-last_page_blocks_len:]
if not page_block_added:
t_blocks.extend(page_blocks[:page_block_start_block_num])
blocks = blocks[:-last_page_blocks_len] + t_blocks
blocks_by_page.append(page_blocks[page_block_start_block_num:])
# print(">>>>>>>>>>>>>>>last block: ", page_blocks[-1]['block_text'], group_buf[0]['page_idx'])
for pb in page_blocks[page_block_start_block_num:]:
blocks.append(pb)
page_blocks = []
if len(group_buf) > 0:
print("group buf still has: ", len(group_buf), group_buf[0]["text"])
group_text, group_props, page_idxs = self.collapse_group(
group_buf, class_name
)
block_type, line_props = get_block_type(
group_is_list,
group_is_table_row,
group_text,
)
if block_type == "para" and group_buf[0]["text"].lower().startswith(
"section"
):
result_list = [group_buf]
buf_texts = block_types = []
result_list, buf_texts, block_types = (
self.create_new_vl_group_for_sections(
result_list, buf_texts, block_types
)
)
for i, grp_buf in enumerate(result_list):
block_type = block_types[i]
block_modified = False
block_class = class_name
if block_types[i] == "header_modified":
block_type = "header"
block_modified = True
block_class = grp_buf[0]["class"]
block = {
"block_idx": block_idx,
"page_idx": page_idx,
"block_type": block_type,
"block_text": str(buf_texts[i]),
"visual_lines": grp_buf,
"block_class": block_class,
"block_modified": block_modified,
}
block["box_style"] = Doc.calc_block_span(block)
blocks.append(block)
page_blocks.append(block)
else:
block = {
"block_idx": block_idx,
"page_idx": page_idx,
"block_type": block_type,
"block_text": group_text,
"visual_lines": group_buf,
"block_class": class_name,
}
block["box_style"] = Doc.calc_block_span(block)
blocks.append(block)
page_blocks.append(block)
oo_fixer = order_fixer.OrderFixer(self, page_blocks, offset=0)
page_blocks, is_reordered = oo_fixer.reorder()
blocks_by_page.append(page_blocks)
if PERFORMANCE_DEBUG:
new_wall_time = default_timer()
print(
f"Checkpoint 3 Finished. Wall time: {((new_wall_time - self.wall_time) * 1000):.2f}ms"
)
self.wall_time = new_wall_time
self.blocks = blocks
self.blocks_by_page = blocks_by_page
self.save_file_stats()
self.organize_and_indent_blocks()
if PERFORMANCE_DEBUG:
new_wall_time = default_timer()
print(
f"Checkpoint 4 Finished. Wall time: {((new_wall_time - self.wall_time) * 1000):.2f}ms"
)
self.wall_time = new_wall_time
self.label_table_of_content()
if self.render_format == "json":
self.json_dict = block_renderer.BlockRenderer(self).render_json()
elif self.render_format == "html":
self.html_str = block_renderer.BlockRenderer(self).render_html()
else:
self.json_dict = block_renderer.BlockRenderer(self).render_json()
self.html_str = block_renderer.BlockRenderer(self).render_html()
def visual_lines_to_blocks(
self, visual_lines, group_buf=[], block_idx=0, group_is_list=False
):
prev_line_info = group_buf[-1] if len(group_buf) > 0 else None
has_vl_from_prev_page = True if prev_line_info else False
vl_from_prev_page_discarded = False
is_list_start = False
is_list_start_separate_line = False
is_list_start_same_line = False
group_is_fake_row = False
group_is_table_row = False
page_blocks = []
line_idx = 0
prev_block_footer_discarded = False
page_height = None
prev_discarded_block = None
while line_idx < len(visual_lines):
if not page_height:
_, page_width, page_height, _ = self.page_styles[
visual_lines[0]["page_idx"]
]
line_info = visual_lines[line_idx]
should_ignore = "should_ignore" in line_info and line_info["should_ignore"]
if "lp_line" not in line_info:
lp_line = line_parser.bare_line(line_info["text"])
line_info["lp_line"] = lp_line
line_info["line_parser"] = lp_line.to_json()
# is_multi_class_line = len(word_class) > 1
(
is_list_start,
is_list_start_separate_line,
is_mixed_font,
group_is_table_row,
is_new_group,
line_idx,
prev_line_info,
line_info,
) = self.detect_new_group(
line_idx,
line_info,
prev_line_info,
group_buf,
line_info["lp_line"],
group_is_table_row,
is_list_start,
page_blocks,
)
is_mixed_font = False # turn it off until fixed
if is_new_group or is_mixed_font or line_idx == len(visual_lines) - 1:
# if ((is_new_group or (is_new_group and (line_idx == len(visual_lines) - 1))) and not should_ignore) \
# or is_mixed_font:
if (
line_idx == len(visual_lines) - 1
and not is_new_group
and not should_ignore
):
group_buf.append(line_info)
# group only has everything until previous line
group_class_name = (
Counter(prev_line_info["word_classes"]).most_common()[0][0]
if prev_line_info
else line_info["class"]
) # prev_line_info['word_classes'][-1] if prev_line_info else class_name
inline_header_line_info = None
# process mixed font only
if is_mixed_font and not group_is_table_row:
header_line_info, normal_line_info = self.split_line(line_info)
is_continuing_header = group_class_name == header_line_info["class"]
line_info = normal_line_info
if is_continuing_header:
group_buf.append(header_line_info)
else:
# this will be written after closing the current group
inline_header_line_info = header_line_info
block_type = None
# merging stuff a table, remove merge vls when needed
if (
group_is_table_row and not group_is_fake_row
): # good place to fix justified text
group_text, group_props, page_idxs = self.collapse_group(
group_buf,
group_class_name,
)
prev_count = len(group_buf)
group_buf, row_count, check_fake_row = self.merge_vls_if_needed(
group_buf, group_is_table_row
)
new_count = len(group_buf)
if new_count == row_count and check_fake_row and prev_count > 1:
print(
"removing fake table row: ",
group_text,
line_info["text"],
prev_count,
row_count,
group_is_table_row,
)
if table_parser.TABLE_DEBUG:
print("removing fake table row: ", group_text)
block_type, _ = get_block_type(False, False, group_text)
group_is_table_row = False
group_is_fake_row = True
line_idx = line_idx + 1
continue
else:
group_text, group_props, page_idxs = self.collapse_group(
group_buf,
group_class_name,
)
group_page_idx = page_idxs[0]
if group_text.strip() == "":
prev_line_info = line_info
group_buf.append(line_info)
line_idx = line_idx + 1
continue
if not block_type:
if (
group_is_list
and len(page_blocks) > 0
and not group_is_table_row
and page_blocks[-1]["block_type"] == "table_row"
and len(group_buf) > 2
):
prev_vl = group_buf[0]
num_table_cells = 0
for vl in group_buf[1:]:
gap, normal_gap, act_normal_gap, _ = self.get_gaps_from_vls(
vl, prev_vl
)
if gap > normal_gap:
num_table_cells += 1
prev_vl = vl
if num_table_cells > 0.6 * len(group_buf):
group_is_list = False
group_is_table_row = True
elif group_is_list and group_is_table_row and len(group_buf) >= 2:
# find the difference between the last 2 VLs.
gap, normal_gap, _, _ = self.get_gaps_from_vls(
group_buf[-1], group_buf[-2]
)
if gap > normal_gap:
group_is_list = False
block_type, line_props = get_block_type(
group_is_list,
group_is_table_row,
group_text,
)
if block_type == "header":
cell_count = self.count_possible_cells(group_buf)
if cell_count > 2:
block_type = "table_row"
# Here we try to divide any "para" block which might have got created the way Tika output the tags
# Prepare variables here.
final_group_bufs = [group_buf]
block_types = [block_type]
buf_texts = [group_text]
last_para_with_delimeter = (
(line_idx == len(visual_lines) - 1)
and block_type == "para"
and not group_buf[-1]["line_parser"].get("incomplete_line", True)
)
if (
block_type != "table_row" and not last_para_with_delimeter
): # Not a table row
if line_idx == len(visual_lines) - 1: # Last line
if should_ignore: # If we have to ignore, don't add to list
line_idx = line_idx + 1
continue
elif (
not is_new_group
and len(group_buf)
and len(page_blocks) > 0
and page_blocks[-1]["box_style"][0]
> line_info["box_style"][0]
):
# Create a block anyways here
block = {
"block_idx": block_idx,
"page_idx": group_page_idx,
"block_type": block_type,
"block_text": group_text,
# 'line_props': line_props,
"visual_lines": group_buf,
"block_class": group_class_name,
"block_modified": False,
}
block["box_style"] = Doc.calc_block_span(block)
page_blocks.append(block)
if LINE_DEBUG:
print(
">>> adding block - 1: ",
block["block_text"],
block_type,
block["page_idx"],
len(group_buf),
block["block_class"],
)
print("-" * 80)
block_idx = block_idx + 1
line_idx = line_idx + 1
group_buf = []
group_is_list = False
continue
# Check the block type
if block_type == "para" and (
len(group_buf) > 2
or group_buf[0]["text"].lower().startswith("section ")
):
buf_texts = []
block_types = []
# Do we have a multi line para which has huge gap, due to the ordering of p_tags from Tika
prev_vl = group_buf[0]
result_list = [[prev_vl]]
buf_text = prev_vl["text"]
first_line_found = False
_, _, _, page_stats = self.page_styles[prev_vl["page_idx"]]
min_left = prev_vl["box_style"][1]
max_right = prev_vl["box_style"][2]
for vl in group_buf[1:]:
if not vhu.compare_top(vl, prev_vl):
gap_bw_lines = round(
vl["box_style"][0]
- (prev_vl["box_style"][0] + prev_vl["box_style"][4]),
1,
)
if vl["box_style"][1] > max_right and gap_bw_lines < 0:
min_left = vl["box_style"][1]
max_right = vl["box_style"][2]
if (not first_line_found) and result_list[0][0][
"text"
].lower().startswith("section"):
# Check whether we have a first line starting with "Section " and
# if there are more than 1 VL and if the second VL has a mixed font, perform the split
result_list, buf_texts, block_types = (
self.create_new_vl_group_for_sections(
result_list, buf_texts, block_types
)
)
if len(buf_texts) > 0:
buf_text = buf_texts[-1]
buf_texts.pop(-1)
first_line_found = True
if vl["page_idx"] != prev_vl["page_idx"]:
_, _, _, page_stats = self.page_styles[vl["page_idx"]]
def start_a_new_para():
prev_vl_ends_with_delim = (
ends_with_sentence_delimiter_pattern.search(
prev_vl["text"]
)
)
if (
max_right > 0.3 * page_width
and prev_vl["box_style"][2] < max_right
and min_left < vl["box_style"][1]
and prev_vl_ends_with_delim is not None
):
return True
elif (
max_right > 0.35 * page_width
and prev_vl["box_style"][2] < max_right
and min_left == vl["box_style"][1]
and prev_vl_ends_with_delim is not None
and abs(prev_vl["box_style"][2] - max_right)
> (len(vl["text"]) * vl["line_style"][5])
):
return True
return False
if (
page_stats["most_frequent_space"]
and gap_bw_lines
> -(5 * page_stats["most_frequent_space"])
and abs(gap_bw_lines)
> 1.2 * page_stats["most_frequent_space"]
and prev_vl["page_idx"] == vl["page_idx"]
) or start_a_new_para():
# 1.2 multiplier is just a magic number.
# Divide them to multiple blocks.
block_type, _ = get_block_type(False, False, buf_text)
block_types.append(block_type)
buf_texts.append(buf_text)
result_list.append([vl])
buf_text = vl["text"]
else:
buf_text = (
buf_text
+ self.check_add_space_btw_texts(
buf_text, vl["text"]
)
+ vl["text"]
)
result_list[-1].append(vl)
else:
min_left = min(min_left, vl["box_style"][1])
max_right = max(max_right, vl["box_style"][2])
buf_text = (
buf_text
+ self.check_add_space_btw_texts(buf_text, vl["text"])
+ vl["text"]
)
result_list[-1].append(vl)