custom-layoutparser 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. custom_layoutparser-0.1.0.dist-info/METADATA +5 -0
  2. custom_layoutparser-0.1.0.dist-info/RECORD +36 -0
  3. custom_layoutparser-0.1.0.dist-info/WHEEL +5 -0
  4. custom_layoutparser-0.1.0.dist-info/top_level.txt +1 -0
  5. layoutparser/__init__.py +89 -0
  6. layoutparser/elements/__init__.py +25 -0
  7. layoutparser/elements/base.py +275 -0
  8. layoutparser/elements/errors.py +26 -0
  9. layoutparser/elements/layout.py +348 -0
  10. layoutparser/elements/layout_elements.py +1352 -0
  11. layoutparser/elements/utils.py +82 -0
  12. layoutparser/file_utils.py +235 -0
  13. layoutparser/io/__init__.py +2 -0
  14. layoutparser/io/basic.py +148 -0
  15. layoutparser/io/pdf.py +225 -0
  16. layoutparser/models/__init__.py +18 -0
  17. layoutparser/models/auto_layoutmodel.py +70 -0
  18. layoutparser/models/base_catalog.py +34 -0
  19. layoutparser/models/base_layoutmodel.py +88 -0
  20. layoutparser/models/detectron2/__init__.py +18 -0
  21. layoutparser/models/detectron2/catalog.py +142 -0
  22. layoutparser/models/detectron2/layoutmodel.py +168 -0
  23. layoutparser/models/effdet/__init__.py +16 -0
  24. layoutparser/models/effdet/catalog.py +88 -0
  25. layoutparser/models/effdet/layoutmodel.py +256 -0
  26. layoutparser/models/model_config.py +133 -0
  27. layoutparser/models/paddledetection/__init__.py +17 -0
  28. layoutparser/models/paddledetection/catalog.py +214 -0
  29. layoutparser/models/paddledetection/layoutmodel.py +297 -0
  30. layoutparser/ocr/__init__.py +16 -0
  31. layoutparser/ocr/base.py +41 -0
  32. layoutparser/ocr/gcv_agent.py +288 -0
  33. layoutparser/ocr/tesseract_agent.py +193 -0
  34. layoutparser/tools/__init__.py +5 -0
  35. layoutparser/tools/shape_operations.py +167 -0
  36. layoutparser/visualization.py +571 -0
@@ -0,0 +1,193 @@
1
+ # Copyright 2021 The Layout Parser team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import io
16
+ import csv
17
+ import pickle
18
+
19
+ import pandas as pd
20
+
21
+ from .base import BaseOCRAgent, BaseOCRElementType
22
+ from ..io import load_dataframe
23
+ from ..file_utils import is_pytesseract_available
24
+
25
+ if is_pytesseract_available():
26
+ import pytesseract
27
+
28
+
29
+ class TesseractFeatureType(BaseOCRElementType):
30
+ """
31
+ The element types for Tesseract Detection API
32
+ """
33
+
34
+ PAGE = 0
35
+ BLOCK = 1
36
+ PARA = 2
37
+ LINE = 3
38
+ WORD = 4
39
+
40
+ @property
41
+ def attr_name(self):
42
+ name_cvt = {
43
+ TesseractFeatureType.PAGE: "page_num",
44
+ TesseractFeatureType.BLOCK: "block_num",
45
+ TesseractFeatureType.PARA: "par_num",
46
+ TesseractFeatureType.LINE: "line_num",
47
+ TesseractFeatureType.WORD: "word_num",
48
+ }
49
+ return name_cvt[self]
50
+
51
+ @property
52
+ def group_levels(self):
53
+ levels = ["page_num", "block_num", "par_num", "line_num", "word_num"]
54
+ return levels[: self + 1]
55
+
56
+
57
+ class TesseractAgent(BaseOCRAgent):
58
+ """
59
+ A wrapper for `Tesseract <https://github.com/tesseract-ocr/tesseract>`_ Text
60
+ Detection APIs based on `PyTesseract <https://github.com/tesseract-ocr/tesseract>`_.
61
+ """
62
+
63
+ DEPENDENCIES = ["pytesseract"]
64
+
65
+ def __init__(self, languages="eng", **kwargs):
66
+ """Create a Tesseract OCR Agent.
67
+
68
+ Args:
69
+ languages (:obj:`list` or :obj:`str`, optional):
70
+ You can specify the language code(s) of the documents to detect to improve
71
+ accuracy. The supported language and their code can be found on
72
+ `its github repo <https://github.com/tesseract-ocr/langdata>`_.
73
+ It supports two formats: 1) you can pass in the languages code as a string
74
+ of format like `"eng+fra"`, or 2) you can pack them as a list of strings
75
+ `["eng", "fra"]`.
76
+ Defaults to 'eng'.
77
+ """
78
+ self.lang = languages if isinstance(languages, str) else "+".join(languages)
79
+ self.configs = kwargs
80
+
81
+ @classmethod
82
+ def with_tesseract_executable(cls, tesseract_cmd_path, **kwargs):
83
+
84
+ pytesseract.pytesseract.tesseract_cmd = tesseract_cmd_path
85
+ return cls(**kwargs)
86
+
87
+ def _detect(self, img_content):
88
+ res = {}
89
+ res["text"] = pytesseract.image_to_string(
90
+ img_content, lang=self.lang, **self.configs
91
+ )
92
+ _data = pytesseract.image_to_data(img_content, lang=self.lang, **self.configs)
93
+ res["data"] = pd.read_csv(
94
+ io.StringIO(_data),
95
+ quoting=csv.QUOTE_NONE,
96
+ encoding="utf-8",
97
+ sep="\t",
98
+ converters={"text": str},
99
+ )
100
+ return res
101
+
102
+ def detect(
103
+ self, image, return_response=False, return_only_text=True, agg_output_level=None
104
+ ):
105
+ """Send the input image for OCR.
106
+
107
+ Args:
108
+ image (:obj:`np.ndarray` or :obj:`str`):
109
+ The input image array or the name of the image file
110
+ return_response (:obj:`bool`, optional):
111
+ Whether directly return all output (string and boxes
112
+ info) from Tesseract.
113
+ Defaults to `False`.
114
+ return_only_text (:obj:`bool`, optional):
115
+ Whether return only the texts in the OCR results.
116
+ Defaults to `False`.
117
+ agg_output_level (:obj:`~TesseractFeatureType`, optional):
118
+ When set, aggregate the GCV output with respect to the
119
+ specified aggregation level. Defaults to `None`.
120
+ """
121
+
122
+ res = self._detect(image)
123
+
124
+ if return_response:
125
+ return res
126
+
127
+ if return_only_text:
128
+ return res["text"]
129
+
130
+ if agg_output_level is not None:
131
+ return self.gather_data(res, agg_output_level)
132
+
133
+ return res["text"]
134
+
135
+ @staticmethod
136
+ def gather_data(response, agg_level):
137
+ """
138
+ Gather the OCR'ed text, bounding boxes, and confidence
139
+ in a given aggeragation level.
140
+ """
141
+ assert isinstance(
142
+ agg_level, TesseractFeatureType
143
+ ), f"Invalid agg_level {agg_level}"
144
+ res = response["data"]
145
+ df = (
146
+ res[~res.text.isna()]
147
+ .groupby(agg_level.group_levels)
148
+ .apply(
149
+ lambda gp: pd.Series(
150
+ [
151
+ gp["left"].min(),
152
+ gp["top"].min(),
153
+ gp["width"].max(),
154
+ gp["height"].max(),
155
+ gp["conf"].mean(),
156
+ gp["text"].str.cat(sep=" "),
157
+ ]
158
+ )
159
+ )
160
+ .reset_index(drop=True)
161
+ .reset_index()
162
+ .rename(
163
+ columns={
164
+ 0: "x_1",
165
+ 1: "y_1",
166
+ 2: "w",
167
+ 3: "h",
168
+ 4: "score",
169
+ 5: "text",
170
+ "index": "id",
171
+ }
172
+ )
173
+ .assign(
174
+ x_2=lambda x: x.x_1 + x.w,
175
+ y_2=lambda x: x.y_1 + x.h,
176
+ block_type="rectangle",
177
+ )
178
+ .drop(columns=["w", "h"])
179
+ )
180
+
181
+ return load_dataframe(df)
182
+
183
+ @staticmethod
184
+ def load_response(filename):
185
+ with open(filename, "rb") as fp:
186
+ res = pickle.load(fp)
187
+ return res
188
+
189
+ @staticmethod
190
+ def save_response(res, file_name):
191
+
192
+ with open(file_name, "wb") as fp:
193
+ pickle.dump(res, fp, protocol=pickle.HIGHEST_PROTOCOL)
@@ -0,0 +1,5 @@
1
+ from .shape_operations import (
2
+ generalized_connected_component_analysis_1d,
3
+ simple_line_detection,
4
+ group_textblocks_based_on_category,
5
+ )
@@ -0,0 +1,167 @@
1
+ # Copyright 2021 The Layout Parser team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import List, Union, Any, Callable, Iterable
16
+ from functools import partial, reduce
17
+
18
+ import numpy as np
19
+ from scipy.sparse import csr_matrix
20
+ from scipy.sparse.csgraph import connected_components
21
+
22
+ from ..elements import BaseLayoutElement, TextBlock
23
+
24
+
25
+ def generalized_connected_component_analysis_1d(
26
+ sequence: List[Any],
27
+ scoring_func: Callable[[Any, Any], int],
28
+ aggregation_func: Callable[[List[Any]], Any] = None,
29
+ default_score_value: int = 0,
30
+ ) -> List[Any]:
31
+ """Perform connected componenet analysis for any 1D sequence based on
32
+ the scoring function and the aggregation function.
33
+ It will generate the adjacency_matrix for the 1D sequence object using
34
+ the provided `scoring_func` and find the connected componenets.
35
+ The `aggregation_func` will be used to aggregate all elements within
36
+ identified components (when not set, it will be the identity function).
37
+
38
+ Args:
39
+ sequence (List[Any]):
40
+ The provided 1D sequence of objects.
41
+ scoring_func (Callable[[Any, Any], int]):
42
+ The scoring function used to construct the adjacency_matrix.
43
+ It should take two objects in the sequence and produe a integer.
44
+ aggregation_func (Callable[[List[Any]], Any], optional):
45
+ The function used to aggregate the elements within an identified
46
+ component.
47
+ Defaults to the identify function: `lambda x: x`.
48
+ default_score_value (int, optional):
49
+ Used to set the default (background) score values that should be
50
+ not considered when running connected component analysis.
51
+ Defaults to 0.
52
+
53
+ Returns:
54
+ List[Any]: A list of length n - the number of the detected componenets.
55
+ """
56
+
57
+ if aggregation_func is None:
58
+ aggregation_func = lambda x: x # Identity Function
59
+
60
+ seq_len = len(sequence)
61
+ adjacency_matrix = np.ones((seq_len, seq_len)) * default_score_value
62
+
63
+ for i in range(seq_len):
64
+ for j in range(i + 1, seq_len):
65
+ adjacency_matrix[i][j] = scoring_func(sequence[i], sequence[j])
66
+
67
+ graph = csr_matrix(adjacency_matrix)
68
+ n_components, labels = connected_components(
69
+ csgraph=graph, directed=False, return_labels=True
70
+ )
71
+
72
+ grouped_sequence = []
73
+ for comp_idx in range(n_components):
74
+ element_idx = np.where(labels == comp_idx)[0]
75
+ grouped_sequence.append(aggregation_func([sequence[i] for i in element_idx]))
76
+
77
+ return grouped_sequence
78
+
79
+
80
+ def simple_line_detection(
81
+ layout: Iterable[BaseLayoutElement], x_tolerance: int = 10, y_tolerance: int = 10
82
+ ) -> List[BaseLayoutElement]:
83
+ """Perform line detection based on connected component analysis.
84
+
85
+ The is_line_wise_close is the scoring function, which returns True
86
+ if the y-difference is smaller than the y_tolerance AND the
87
+ x-difference (the horizontal gap between two boxes) is also smaller
88
+ than the x_tolerance, and False otherwise.
89
+
90
+ All the detected components will then be passed into aggregation_func,
91
+ which returns the overall union box of all the elements, or the line
92
+ box.
93
+
94
+ Args:
95
+ layout (Iterable):
96
+ A list (or Layout) of BaseLayoutElement
97
+ x_tolerance (int, optional):
98
+ The value used for specifying the maximum allowed y-difference
99
+ when considered whether two tokens are from the same line.
100
+ Defaults to 10.
101
+ y_tolerance (int, optional):
102
+ The value used for specifying the maximum allowed horizontal gap
103
+ when considered whether two tokens are from the same line.
104
+ Defaults to 10.
105
+
106
+ Returns:
107
+ List[BaseLayoutElement]: A list of BaseLayoutElement, denoting the line boxes.
108
+ """
109
+
110
+ def is_line_wise_close(token_a, token_b, x_tolerance, y_tolerance):
111
+ y_a = token_a.block.center[1]
112
+ y_b = token_b.block.center[1]
113
+
114
+ a_left, a_right = token_a.block.coordinates[0::2]
115
+ b_left, b_right = token_b.block.coordinates[0::2]
116
+
117
+ return (
118
+ abs(y_a - y_b) <= y_tolerance
119
+ and min(abs(a_left - b_right), abs(a_right - b_left)) <= x_tolerance
120
+ )
121
+ # If the y-difference is smaller than the y_tolerance AND
122
+ # the x-difference (the horizontal gap between two boxes)
123
+ # is also smaller than the x_tolerance threshold, then
124
+ # these two tokens are considered as line-wise close.
125
+
126
+ detected_lines = generalized_connected_component_analysis_1d(
127
+ layout,
128
+ scoring_func=partial(
129
+ is_line_wise_close, y_tolerance=x_tolerance, x_tolerance=y_tolerance
130
+ ),
131
+ aggregation_func=lambda seq: reduce(layout[0].__class__.union, seq),
132
+ )
133
+
134
+ return detected_lines
135
+
136
+
137
+ def group_textblocks_based_on_category(
138
+ layout: Iterable[TextBlock], union_group: bool = True
139
+ ) -> Union[List[TextBlock], List[List[TextBlock]]]:
140
+ """Group textblocks based on their category (block.type).
141
+
142
+ Args:
143
+ layout (Iterable):
144
+ A list (or Layout) of BaseLayoutElement
145
+ union_group (bool):
146
+ Whether to union the boxes within each group.
147
+ Defaults to True.
148
+
149
+ Returns:
150
+ List[TextBlock]: When `union_group=True`, it produces a list of
151
+ TextBlocks, denoting the boundaries of each texblock group.
152
+ List[List[TextBlock]]: When `union_group=False`, it preserves
153
+ the elements within each group for further processing.
154
+ """
155
+
156
+ if union_group:
157
+ aggregation_func = lambda seq: reduce(layout[0].__class__.union, seq)
158
+ else:
159
+ aggregation_func = None
160
+
161
+ detected_group_boxes = generalized_connected_component_analysis_1d(
162
+ layout,
163
+ scoring_func=lambda a, b: a.type == b.type,
164
+ aggregation_func=aggregation_func,
165
+ )
166
+
167
+ return detected_group_boxes