-
Notifications
You must be signed in to change notification settings - Fork 735
Expand file tree
/
Copy pathtable.py
More file actions
2815 lines (2366 loc) · 96.3 KB
/
table.py
File metadata and controls
2815 lines (2366 loc) · 96.3 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
"""
Copyright (C) 2023 Artifex Software, Inc.
This file is part of PyMuPDF.
PyMuPDF is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option)
any later version.
PyMuPDF is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License
along with MuPDF. If not, see <https://www.gnu.org/licenses/agpl-3.0.en.html>
Alternative licensing terms are available from the licensor.
For commercial licensing, see <https://www.artifex.com/> or contact
Artifex Software, Inc., 39 Mesa Street, Suite 108A, San Francisco,
CA 94129, USA, for further information.
---------------------------------------------------------------------
Portions of this code have been ported from pdfplumber, see
https://pypi.org/project/pdfplumber/.
The ported code is under the following MIT license:
---------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2015, Jeremy Singer-Vine
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---------------------------------------------------------------------
Also see here: https://github.com/jsvine/pdfplumber/blob/stable/LICENSE.txt
---------------------------------------------------------------------
The porting mainly pertains to files "table.py" and relevant parts of
"utils/text.py" within pdfplumber's repository on Github.
With respect to "text.py", we have removed functions or features that are not
used by table processing. Examples are:
* the text search function
* simple text extraction
* text extraction by lines
Original pdfplumber code does neither detect, nor identify table headers.
This PyMuPDF port adds respective code to the 'Table' class as method '_get_header'.
This is implemented as new class TableHeader with the properties:
* bbox: A tuple for the header's bbox
* cells: A tuple for each bbox of a column header
* names: A list of strings with column header text
* external: A bool indicating whether the header is outside the table cells.
"""
import os
import inspect
import itertools
import string
import html
from collections.abc import Sequence
from dataclasses import dataclass
from operator import itemgetter
import weakref
import pathlib
import pymupdf
from pymupdf import mupdf
# -------------------------------------------------------------------
# Start of PyMuPDF interface code
# -------------------------------------------------------------------
# pylint: disable=no-name-in-module
# Optionally use the TGIF table grid finder.
# This replace fz_find_table_within_bounds.
USE_TGIF = os.getenv("USE_TGIF", "0")
EXTRACTOR_V4 = None # Keep pylint happy.
if USE_TGIF == "0":
if os.environ.get('PYMUPDF_LEGACY_TABLE_DIAGNOSTIC') != '0':
print("Using legacy table grid extraction.")
elif USE_TGIF == "1":
print("Using TGIFVx for table grid extraction.")
import pymupdf.tgif # pylint: disable=import-error
elif USE_TGIF == "4":
print("Using TGEV4 for table grid extraction.")
from pymupdf.TableGridExtractorV4 import TableGridExtractorV4
EXTRACTOR_V4 = TableGridExtractorV4(
grid_onnx_path=str(pathlib.Path(__file__).parent / "table_grid_model_v4.onnx"),
# conn_onnx_path=None,
# h_on_threshold=args.h_on_threshold,
# v_on_threshold=args.v_on_threshold,
# conn_threshold=args.conn_threshold,
# nms_min_dist=args.nms_min_dist,
# filter_empty_lines=not args.no_filter_empty,
)
else:
raise Exception(f"Unrecognised {USE_TGIF=}, should be unset, '0', '1' or '4'.")
EDGES = [] # vector graphics from PyMuPDF
CHARS = [] # text characters from PyMuPDF
TEXTPAGE = None # textpage for cell text extraction
TEXT_BOLD = mupdf.FZ_STEXT_BOLD
TEXT_STRIKEOUT = mupdf.FZ_STEXT_STRIKEOUT
FLAGS = (
0
| pymupdf.TEXTFLAGS_TEXT
| pymupdf.TEXT_COLLECT_STYLES
| pymupdf.TEXT_ACCURATE_BBOXES
| pymupdf.TEXT_MEDIABOX_CLIP
)
# needed by mupdf function fz_find_table_within_bounds().
TABLE_DETECTOR_FLAGS = (
0
| pymupdf.TEXT_ACCURATE_BBOXES
| pymupdf.TEXT_SEGMENT
| pymupdf.TEXT_COLLECT_VECTORS
| pymupdf.TEXT_MEDIABOX_CLIP
)
white_spaces = set(string.whitespace) # for checking white space only cells
def rect_in_rect(inner, outer):
"""Check whether rectangle 'inner' is fully inside rectangle 'outer'."""
return (
1
and inner[0] >= outer[0]
and inner[1] >= outer[1]
and inner[2] <= outer[2]
and inner[3] <= outer[3]
)
def chars_in_rect(CHARS, rect):
"""Check whether any of the chars in CHAR are inside rectangle 'rect'."""
return any(
1
and rect[0] <= c["x0"]
and c["x1"] <= rect[2]
and rect[1] <= c["y0"]
and rect[3] >= c["y1"]
for c in CHARS
)
def _iou(r1, r2):
"""Compute intersection over union of two rectangles."""
ix = max(0, min(r1[2], r2[2]) - max(r1[0], r2[0]))
iy = max(0, min(r1[3], r2[3]) - max(r1[1], r2[1]))
intersection = ix * iy # intersection area
if not intersection:
return 0
area1 = (r1[2] - r1[0]) * (r1[3] - r1[1])
area2 = (r2[2] - r2[0]) * (r2[3] - r2[1])
return intersection / (area1 + area2 - intersection)
def intersects_words_h(bbox, y, word_rects) -> bool:
"""Check whether any of the words in bbox are cut through by
horizontal line y.
"""
return any(r.y0 < y < r.y1 for r in word_rects if rect_in_rect(r, bbox))
def get_table_dict_from_rect(textpage, rect):
"""Extract MuPDF table structure information from a given rectangle."""
table_dict = {}
pymupdf.extra.make_table_dict(textpage.this.m_internal, table_dict, rect)
return table_dict
def get_table_cells_from_rect_tgif1(page, word_rects, rect):
cells = []
bound = mupdf.FzRect(*rect)
try:
r, xpos, ypos = pymupdf.tgif.fz_visual_table_grid_finder(page, bound) # pylint: disable=no-member
x_count = int(xpos.m_internal.len)
x_values = [xpos.list(i).pos for i in range(x_count)]
y_count = int(ypos.m_internal.len)
y_values = [ypos.list(i).pos for i in range(y_count)]
if xpos.m_internal.max_uncertainty > 0 or ypos.m_internal.max_uncertainty > 0:
print(f"{page.number=}: grid with uncertainty for {bound=}")
except Exception:
return cells
for i in range(y_count - 1):
for j in range(x_count - 1):
cell = (x_values[j], y_values[i], x_values[j + 1], y_values[i + 1])
cells.append(cell)
return cells
def get_table_cells_from_rect_tgif4(page, word_rects, rect):
"""Use TableGridExtractorV4 to detect table structure."""
pix = page.get_pixmap(clip=rect) # make Pixmap from passed-in rect
# make transformation matrix from pixmap to rect coordinates
pclip = pymupdf.IRect(pix.irect)
matrix = pclip.torect(rect) # in case we want to change resolution
pred = EXTRACTOR_V4.predict_grid(pix) # call GRID extractor
h_lines = [pclip.y0, pclip.y1] # include top and bottom of the rect
# add predicted h lines
h_lines.extend(y + pclip.y0 for y in pred.h_lines)
h_lines = sorted(h_lines)
v_lines = [pclip.x0, pclip.x1] # include left and right of the rect
# add predicted v lines
v_lines.extend(x + pclip.x0 for x in pred.v_lines)
v_lines = sorted(v_lines)
# we now have the horizontal and vertical lines and make the cells
cells = []
for i in range(len(h_lines) - 1):
for j in range(len(v_lines) - 1):
cell = pymupdf.Rect(v_lines[j], h_lines[i], v_lines[j + 1], h_lines[i + 1])
cells.append(cell * matrix)
return cells
def make_table_from_bbox(page, textpage, word_rects, rect):
"""Detect table structure within a given rectangle."""
cells = [] # table cells as (x0,y0,x1,y1) tuples
if USE_TGIF == "1":
return get_table_cells_from_rect_tgif1(page, word_rects, rect)
elif USE_TGIF == "4":
return get_table_cells_from_rect_tgif4(page, word_rects, rect)
# calls fz_find_table_within_bounds
block = get_table_dict_from_rect(textpage, rect)
# No table structure found if not a grid block
if block.get("type") != mupdf.FZ_STEXT_BLOCK_GRID:
return cells
bbox = pymupdf.Rect(block["bbox"]) # resulting table bbox
# lists of (pos,uncertainty) tuples
xpos = sorted(block["xpos"], key=lambda x: x[0])
ypos = sorted(block["ypos"], key=lambda y: y[0])
# maximum uncertainties in x and y directions
xmaxu, ymaxu = block["max_uncertain"]
# Modify ypos to remove uncertain positions, and y positions
# that cut through words.
nypos = []
for y, yunc in ypos:
if yunc > 0: # allow no uncertain y values
continue
if intersects_words_h(bbox, y, word_rects):
continue # allow no y that cuts through words
if nypos and (y - nypos[-1] < 3):
nypos[-1] = y # snap close positions
else:
nypos.append(y)
# New max y uncertainty: 35% of remaining y positions.
# Omit x positions that intersect too many words, otherwise
# only remove x for the affected cells.
ymaxu = max(0, round((len(nypos) - 2) * 0.35))
# Exclude x positions with too high uncertainty
# (we allow more uncertainty in x direction)
nxpos = [x[0] for x in xpos if x[1] <= ymaxu]
if bbox.x1 > nxpos[-1] + 3:
nxpos.append(bbox.x1) # ensure right table border
# Compose cells from the remaining x and y positions.
for i in range(len(nypos) - 1):
row_box = pymupdf.Rect(bbox.x0, nypos[i], bbox.x1, nypos[i + 1])
# Sub-select words in this row and sort them by left coordinate
row_words = sorted(
[r for r in word_rects if rect_in_rect(r, row_box)], key=lambda r: r.x0
)
# Sub-select x values that do not cut through words
this_xpos = [x for x in nxpos if not any(r.x0 < x < r.x1 for r in row_words)]
for j in range(len(this_xpos) - 1):
cell = pymupdf.Rect(this_xpos[j], nypos[i], this_xpos[j + 1], nypos[i + 1])
if not cell.is_empty: # valid cell
cells.append(tuple(cell))
# Add new table to TableFinder tables
return cells
def extract_cells(textpage, cell, markdown=False):
"""Extract text from a rect-like 'cell' as plain or MD styled text.
This function should ultimately be used to extract text from a table cell.
Markdown output will only work correctly if extraction flag bit
TEXT_COLLECT_STYLES is set.
Args:
textpage: A PyMuPDF TextPage object. Must have been created with
TEXTFLAGS_TEXT | TEXT_COLLECT_STYLES.
cell: A tuple (x0, y0, x1, y1) defining the cell's bbox.
markdown: If True, return text formatted for Markdown.
Returns:
A string with the text extracted from the cell.
"""
text = ""
for block in textpage.extractRAWDICT()["blocks"]:
if block["type"] != 0:
continue
block_bbox = block["bbox"]
if (
0
or block_bbox[0] > cell[2]
or block_bbox[2] < cell[0]
or block_bbox[1] > cell[3]
or block_bbox[3] < cell[1]
):
continue # skip block outside cell
for line in block["lines"]:
lbbox = line["bbox"]
if (
0
or lbbox[0] > cell[2]
or lbbox[2] < cell[0]
or lbbox[1] > cell[3]
or lbbox[3] < cell[1]
):
continue # skip line outside cell
if text: # must be a new line in the cell
text += "<br>" if markdown else "\n"
# strikeout detection only works with horizontal text
horizontal = line["dir"] == (0, 1) or line["dir"] == (1, 0)
for span in line["spans"]:
sbbox = span["bbox"]
if (
0
or sbbox[0] > cell[2]
or sbbox[2] < cell[0]
or sbbox[1] > cell[3]
or sbbox[3] < cell[1]
):
continue # skip spans outside cell
# only include chars with more than 50% bbox overlap
span_text = ""
for char in span["chars"]:
this_char = char["c"]
bbox = pymupdf.Rect(char["bbox"])
if abs(bbox & cell) > 0.5 * abs(bbox):
span_text += this_char
elif this_char in white_spaces:
span_text += " "
if not span_text:
continue # skip empty span
if not markdown: # no MD styling
text += span_text
continue
prefix = ""
suffix = ""
if horizontal and span["char_flags"] & TEXT_STRIKEOUT:
prefix += "~~"
suffix = "~~" + suffix
if span["char_flags"] & TEXT_BOLD:
prefix += "**"
suffix = "**" + suffix
if span["flags"] & pymupdf.TEXT_FONT_ITALIC:
prefix += "_"
suffix = "_" + suffix
if span["flags"] & pymupdf.TEXT_FONT_MONOSPACED:
prefix += "`"
suffix = "`" + suffix
if len(span["chars"]) > 2:
span_text = span_text.rstrip()
# if span continues previous styling: extend cell text
if (ls := len(suffix)) and text.endswith(suffix):
text = text[:-ls] + span_text + suffix
else: # append the span with new styling
if not span_text.strip():
text += " "
else:
text += prefix + span_text + suffix
return text.strip()
# -------------------------------------------------------------------
# End of PyMuPDF interface code
# -------------------------------------------------------------------
class UnsetFloat(float):
pass
NON_NEGATIVE_SETTINGS = [
"snap_tolerance",
"snap_x_tolerance",
"snap_y_tolerance",
"join_tolerance",
"join_x_tolerance",
"join_y_tolerance",
"edge_min_length",
"min_words_vertical",
"min_words_horizontal",
"intersection_tolerance",
"intersection_x_tolerance",
"intersection_y_tolerance",
]
TABLE_STRATEGIES = ["lines", "lines_strict", "text", "explicit"]
UNSET = UnsetFloat(0)
DEFAULT_SNAP_TOLERANCE = 3
DEFAULT_JOIN_TOLERANCE = 3
DEFAULT_MIN_WORDS_VERTICAL = 3
DEFAULT_MIN_WORDS_HORIZONTAL = 1
DEFAULT_X_TOLERANCE = 3
DEFAULT_Y_TOLERANCE = 3
DEFAULT_X_DENSITY = 7.25
DEFAULT_Y_DENSITY = 13
bbox_getter = itemgetter("x0", "top", "x1", "bottom")
LIGATURES = {
"ff": "ff",
"ffi": "ffi",
"ffl": "ffl",
"fi": "fi",
"fl": "fl",
"st": "st",
"ſt": "st",
}
def to_list(collection) -> list:
if isinstance(collection, list):
return collection
elif isinstance(collection, Sequence):
return list(collection)
elif hasattr(collection, "to_dict"):
res = collection.to_dict("records") # pragma: nocover
return res
else:
return list(collection)
class TextMap:
"""
A TextMap maps each unicode character in the text to an individual `char`
object (or, in the case of layout-implied whitespace, `None`).
"""
def __init__(self, tuples=None) -> None:
self.tuples = tuples
self.as_string = "".join(map(itemgetter(0), tuples))
def match_to_dict(
self,
m,
main_group: int = 0,
return_groups: bool = True,
return_chars: bool = True,
) -> dict:
subset = self.tuples[m.start(main_group) : m.end(main_group)]
chars = [c for (text, c) in subset if c is not None]
x0, top, x1, bottom = objects_to_bbox(chars)
result = {
"text": m.group(main_group),
"x0": x0,
"top": top,
"x1": x1,
"bottom": bottom,
}
if return_groups:
result["groups"] = m.groups()
if return_chars:
result["chars"] = chars
return result
class WordMap:
"""
A WordMap maps words->chars.
"""
def __init__(self, tuples) -> None:
self.tuples = tuples
def to_textmap(
self,
layout: bool = False,
layout_width=0,
layout_height=0,
layout_width_chars: int = 0,
layout_height_chars: int = 0,
x_density=DEFAULT_X_DENSITY,
y_density=DEFAULT_Y_DENSITY,
x_shift=0,
y_shift=0,
y_tolerance=DEFAULT_Y_TOLERANCE,
use_text_flow: bool = False,
presorted: bool = False,
expand_ligatures: bool = True,
) -> TextMap:
"""
Given a list of (word, chars) tuples (i.e., a WordMap), return a list of
(char-text, char) tuples (i.e., a TextMap) that can be used to mimic the
structural layout of the text on the page(s), using the following approach:
- Sort the words by (doctop, x0) if not already sorted.
- Calculate the initial doctop for the starting page.
- Cluster the words by doctop (taking `y_tolerance` into account), and
iterate through them.
- For each cluster, calculate the distance between that doctop and the
initial doctop, in points, minus `y_shift`. Divide that distance by
`y_density` to calculate the minimum number of newlines that should come
before this cluster. Append that number of newlines *minus* the number of
newlines already appended, with a minimum of one.
- Then for each cluster, iterate through each word in it. Divide each
word's x0, minus `x_shift`, by `x_density` to calculate the minimum
number of characters that should come before this cluster. Append that
number of spaces *minus* the number of characters and spaces already
appended, with a minimum of one. Then append the word's text.
- At the termination of each line, add more spaces if necessary to
mimic `layout_width`.
- Finally, add newlines to the end if necessary to mimic to
`layout_height`.
Note: This approach currently works best for horizontal, left-to-right
text, but will display all words regardless of orientation. There is room
for improvement in better supporting right-to-left text, as well as
vertical text.
"""
_textmap = []
if not len(self.tuples):
return TextMap(_textmap)
expansions = LIGATURES if expand_ligatures else {}
if layout:
if layout_width_chars:
if layout_width:
raise ValueError(
"`layout_width` and `layout_width_chars` cannot both be set."
)
else:
layout_width_chars = int(round(layout_width / x_density))
if layout_height_chars:
if layout_height:
raise ValueError(
"`layout_height` and `layout_height_chars` cannot both be set."
)
else:
layout_height_chars = int(round(layout_height / y_density))
blank_line = [(" ", None)] * layout_width_chars
else:
blank_line = []
num_newlines = 0
words_sorted_doctop = (
self.tuples
if presorted or use_text_flow
else sorted(self.tuples, key=lambda x: float(x[0]["doctop"]))
)
first_word = words_sorted_doctop[0][0]
doctop_start = first_word["doctop"] - first_word["top"]
for i, ws in enumerate(
cluster_objects(
words_sorted_doctop, lambda x: float(x[0]["doctop"]), y_tolerance
)
):
y_dist = (
(ws[0][0]["doctop"] - (doctop_start + y_shift)) / y_density
if layout
else 0
)
num_newlines_prepend = max(
# At least one newline, unless this iis the first line
int(i > 0),
# ... or as many as needed to get the imputed "distance" from the top
round(y_dist) - num_newlines,
)
for i in range(num_newlines_prepend):
if not len(_textmap) or _textmap[-1][0] == "\n":
_textmap += blank_line
_textmap.append(("\n", None))
num_newlines += num_newlines_prepend
line_len = 0
line_words_sorted_x0 = (
ws
if presorted or use_text_flow
else sorted(ws, key=lambda x: float(x[0]["x0"]))
)
for word, chars in line_words_sorted_x0:
x_dist = (word["x0"] - x_shift) / x_density if layout else 0
num_spaces_prepend = max(min(1, line_len), round(x_dist) - line_len)
_textmap += [(" ", None)] * num_spaces_prepend
line_len += num_spaces_prepend
for c in chars:
letters = expansions.get(c["text"], c["text"])
for letter in letters:
_textmap.append((letter, c))
line_len += 1
# Append spaces at end of line
if layout:
_textmap += [(" ", None)] * (layout_width_chars - line_len)
# Append blank lines at end of text
if layout:
num_newlines_append = layout_height_chars - (num_newlines + 1)
for i in range(num_newlines_append):
if i > 0:
_textmap += blank_line
_textmap.append(("\n", None))
# Remove terminal newline
if _textmap[-1] == ("\n", None):
_textmap = _textmap[:-1]
return TextMap(_textmap)
class WordExtractor:
def __init__(
self,
x_tolerance=DEFAULT_X_TOLERANCE,
y_tolerance=DEFAULT_Y_TOLERANCE,
keep_blank_chars: bool = False,
use_text_flow=False,
horizontal_ltr=True, # Should words be read left-to-right?
vertical_ttb=False, # Should vertical words be read top-to-bottom?
extra_attrs=None,
split_at_punctuation=False,
expand_ligatures=True,
):
self.x_tolerance = x_tolerance
self.y_tolerance = y_tolerance
self.keep_blank_chars = keep_blank_chars
self.use_text_flow = use_text_flow
self.horizontal_ltr = horizontal_ltr
self.vertical_ttb = vertical_ttb
self.extra_attrs = [] if extra_attrs is None else extra_attrs
# Note: string.punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
self.split_at_punctuation = (
string.punctuation
if split_at_punctuation is True
else (split_at_punctuation or "")
)
self.expansions = LIGATURES if expand_ligatures else {}
def merge_chars(self, ordered_chars: list):
x0, top, x1, bottom = objects_to_bbox(ordered_chars)
doctop_adj = ordered_chars[0]["doctop"] - ordered_chars[0]["top"]
upright = ordered_chars[0]["upright"]
direction = 1 if (self.horizontal_ltr if upright else self.vertical_ttb) else -1
matrix = ordered_chars[0]["matrix"]
rotation = 0
if not upright and matrix[1] < 0:
ordered_chars = reversed(ordered_chars)
rotation = 270
if matrix[0] < 0 and matrix[3] < 0:
rotation = 180
elif matrix[1] > 0:
rotation = 90
word = {
"text": "".join(
self.expansions.get(c["text"], c["text"]) for c in ordered_chars
),
"x0": x0,
"x1": x1,
"top": top,
"doctop": top + doctop_adj,
"bottom": bottom,
"upright": upright,
"direction": direction,
"rotation": rotation,
}
for key in self.extra_attrs:
word[key] = ordered_chars[0][key]
return word
def char_begins_new_word(
self,
prev_char,
curr_char,
) -> bool:
"""This method takes several factors into account to determine if
`curr_char` represents the beginning of a new word:
- Whether the text is "upright" (i.e., non-rotated)
- Whether the user has specified that horizontal text runs
left-to-right (default) or right-to-left, as represented by
self.horizontal_ltr
- Whether the user has specified that vertical text the text runs
top-to-bottom (default) or bottom-to-top, as represented by
self.vertical_ttb
- The x0, top, x1, and bottom attributes of prev_char and
curr_char
- The self.x_tolerance and self.y_tolerance settings. Note: In
this case, x/y refer to those directions for non-rotated text.
For vertical text, they are flipped. A more accurate terminology
might be "*intra*line character distance tolerance" and
"*inter*line character distance tolerance"
An important note: The *intra*line distance is measured from the
*end* of the previous character to the *beginning* of the current
character, while the *inter*line distance is measured from the
*top* of the previous character to the *top* of the next
character. The reasons for this are partly repository-historical,
and partly logical, as successive text lines' bounding boxes often
overlap slightly (and we don't want that overlap to be interpreted
as the two lines being the same line).
The upright-ness of the character determines the attributes to
compare, while horizontal_ltr/vertical_ttb determine the direction
of the comparison.
"""
# Note: Due to the grouping step earlier in the process,
# curr_char["upright"] will always equal prev_char["upright"].
if curr_char["upright"]:
x = self.x_tolerance
y = self.y_tolerance
ay = prev_char["top"]
cy = curr_char["top"]
if self.horizontal_ltr:
ax = prev_char["x0"]
bx = prev_char["x1"]
cx = curr_char["x0"]
else:
ax = -prev_char["x1"]
bx = -prev_char["x0"]
cx = -curr_char["x1"]
else:
x = self.y_tolerance
y = self.x_tolerance
ay = prev_char["x0"]
cy = curr_char["x0"]
if self.vertical_ttb:
ax = prev_char["top"]
bx = prev_char["bottom"]
cx = curr_char["top"]
else:
ax = -prev_char["bottom"]
bx = -prev_char["top"]
cx = -curr_char["bottom"]
return bool(
# Intraline test
(cx < ax)
or (cx > bx + x)
# Interline test
or (cy > ay + y)
)
def iter_chars_to_words(self, ordered_chars):
current_word: list = []
def start_next_word(new_char=None):
nonlocal current_word
if current_word:
yield current_word
current_word = [] if new_char is None else [new_char]
for char in ordered_chars:
text = char["text"]
if not self.keep_blank_chars and text.isspace():
yield from start_next_word(None)
elif text in self.split_at_punctuation:
yield from start_next_word(char)
yield from start_next_word(None)
elif current_word and self.char_begins_new_word(current_word[-1], char):
yield from start_next_word(char)
else:
current_word.append(char)
# Finally, after all chars processed
if current_word:
yield current_word
def iter_sort_chars(self, chars):
def upright_key(x) -> int:
return -int(x["upright"])
for upright_cluster in cluster_objects(list(chars), upright_key, 0):
upright = upright_cluster[0]["upright"]
cluster_key = "doctop" if upright else "x0"
# Cluster by line
subclusters = cluster_objects(
upright_cluster, itemgetter(cluster_key), self.y_tolerance
)
for sc in subclusters:
# Sort within line
sort_key = "x0" if upright else "doctop"
to_yield = sorted(sc, key=itemgetter(sort_key))
# Reverse order if necessary
if not (self.horizontal_ltr if upright else self.vertical_ttb):
yield from reversed(to_yield)
else:
yield from to_yield
def iter_extract_tuples(self, chars):
ordered_chars = chars if self.use_text_flow else self.iter_sort_chars(chars)
grouping_key = itemgetter("upright", *self.extra_attrs)
grouped_chars = itertools.groupby(ordered_chars, grouping_key)
for keyvals, char_group in grouped_chars:
for word_chars in self.iter_chars_to_words(char_group):
yield (self.merge_chars(word_chars), word_chars)
def extract_wordmap(self, chars) -> WordMap:
return WordMap(list(self.iter_extract_tuples(chars)))
def extract_words(self, chars: list) -> list:
words = list(word for word, word_chars in self.iter_extract_tuples(chars))
return words
def extract_words(chars: list, **kwargs) -> list:
return WordExtractor(**kwargs).extract_words(chars)
TEXTMAP_KWARGS = inspect.signature(WordMap.to_textmap).parameters.keys()
WORD_EXTRACTOR_KWARGS = inspect.signature(WordExtractor).parameters.keys()
def chars_to_textmap(chars: list, **kwargs) -> TextMap:
kwargs.update({"presorted": True})
extractor = WordExtractor(
**{k: kwargs[k] for k in WORD_EXTRACTOR_KWARGS if k in kwargs}
)
wordmap = extractor.extract_wordmap(chars)
textmap = wordmap.to_textmap(
**{k: kwargs[k] for k in TEXTMAP_KWARGS if k in kwargs}
)
return textmap
def extract_text(chars: list, **kwargs) -> str:
chars = to_list(chars)
if len(chars) == 0:
return ""
if kwargs.get("layout"):
return chars_to_textmap(chars, **kwargs).as_string
else:
y_tolerance = kwargs.get("y_tolerance", DEFAULT_Y_TOLERANCE)
extractor = WordExtractor(
**{k: kwargs[k] for k in WORD_EXTRACTOR_KWARGS if k in kwargs}
)
words = extractor.extract_words(chars)
if words:
rotation = words[0]["rotation"] # rotation cannot change within a cell
else:
rotation = 0
if rotation == 90:
words.sort(key=lambda w: (w["x1"], -w["top"]))
lines = " ".join([w["text"] for w in words])
elif rotation == 270:
words.sort(key=lambda w: (-w["x1"], w["top"]))
lines = " ".join([w["text"] for w in words])
else:
lines = cluster_objects(words, itemgetter("doctop"), y_tolerance)
lines = "\n".join(" ".join(word["text"] for word in line) for line in lines)
if rotation == 180: # needs extra treatment
lines = "".join([(c if c != "\n" else " ") for c in reversed(lines)])
return lines
def collate_line(
line_chars: list,
tolerance=DEFAULT_X_TOLERANCE,
) -> str:
coll = ""
last_x1 = None
for char in sorted(line_chars, key=itemgetter("x0")):
if (last_x1 is not None) and (char["x0"] > (last_x1 + tolerance)):
coll += " "
last_x1 = char["x1"]
coll += char["text"]
return coll
def dedupe_chars(chars: list, tolerance=1) -> list:
"""
Removes duplicate chars — those sharing the same text, fontname, size,
and positioning (within `tolerance`) as other characters in the set.
"""
key = itemgetter("fontname", "size", "upright", "text")
pos_key = itemgetter("doctop", "x0")
def yield_unique_chars(chars: list):
sorted_chars = sorted(chars, key=key)
for grp, grp_chars in itertools.groupby(sorted_chars, key=key):
for y_cluster in cluster_objects(
list(grp_chars), itemgetter("doctop"), tolerance
):
for x_cluster in cluster_objects(
y_cluster, itemgetter("x0"), tolerance
):
yield sorted(x_cluster, key=pos_key)[0]
deduped = yield_unique_chars(chars)
return sorted(deduped, key=chars.index)
def line_to_edge(line):
edge = dict(line)
edge["orientation"] = "h" if (line["top"] == line["bottom"]) else "v"
return edge
def rect_to_edges(rect) -> list:
top, bottom, left, right = [dict(rect) for x in range(4)]
top.update(
{
"object_type": "rect_edge",
"height": 0,
"y0": rect["y1"],
"bottom": rect["top"],
"orientation": "h",
}
)
bottom.update(
{
"object_type": "rect_edge",
"height": 0,
"y1": rect["y0"],
"top": rect["top"] + rect["height"],
"doctop": rect["doctop"] + rect["height"],