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
| import math import re from typing import List
from pdf2image import convert_from_bytes from matplotlib.patches import Rectangle
from src.models.block import Block from src.models.line import Line from src.ocr.util.functions import read_json_file from matplotlib import pyplot as plt
class ColumnType: """ Column type, based on the column type of pdf. """ SINGLE = "SINGLE" MULTI = "MULTI"
def get_lines_from_json(file_path: str) -> List[Line]: """ Get all type "LINE" from json file generated by textract. :param file_path: json file generated by textract. :return: list of Line. """ lines: List[Line] = [] json_res = read_json_file(file_path) for item in json_res["Blocks"]: if item["BlockType"] == "LINE": box = item["Geometry"]["BoundingBox"] lines.append( Line( item["Id"], item["Page"], item["Text"], box["Top"], box["Left"], box["Width"], box["Height"])) return lines
def print_blocks(blocks: List[Block]) -> None: """ print block and line information :param blocks: blocks to print """ for block in blocks: print(f"{block.__str__()}") for line in block.lines: print(f"{line.__str__()}") print("\n")
class LineSimilarityChecker: """ This class is used to check the similarity between two lines. """
def __init__(self, column_type: ColumnType, distance_tolerance: float = 0.03, width_tolerance: float = 0.01, left_tolerance: float = 0.02, height_tolerance: float = 0.02, same_line_tolerance: float = 0.005 ) -> None: self.column_type = column_type
self.distance_tolerance = distance_tolerance self.width_tolerance = width_tolerance self.left_tolerance = left_tolerance self.height_tolerance = height_tolerance self.same_line_tolerance = same_line_tolerance
def is_left_similar(self, line1, line2, tolerance=None): tolerance = tolerance or self.left_tolerance return self.pretty_similar(line1.left, line2.left, tolerance)
def is_width_similar(self, line1, line2, tolerance=None): tolerance = tolerance or self.width_tolerance return self.pretty_similar(line1.width, line2.width, tolerance)
def is_height_similar(self, line1, line2, tolerance=None): tolerance = tolerance or self.height_tolerance return self.two_point_height(line1.top, line2.top) < tolerance
def is_center_close(self, line1: Line, line2: Line) -> bool: return self.two_point_distance( line1.center[0], line1.center[1], line2.center[0], line2.center[1]) < self.distance_tolerance
@staticmethod def pretty_similar(x: float, x1: float, tolerance: float): return abs(x - x1) < tolerance
@staticmethod def two_point_distance(x: float, y: float, x1: float, y1: float): distance = math.sqrt((x - x1) ** 2 + (y - y1) ** 2) return distance
@staticmethod def two_point_height(y: float, y1: float): return abs(y - y1)
class LineMerger: """ This class is used to turn lines to blocks by compare each line's similarity. """
def __init__(self, lines, column_type: ColumnType = ColumnType.SINGLE): self.column_type = column_type self.line_check = LineSimilarityChecker(self.column_type) self.lines: List[Line] = lines
def get_blocks(self) -> List[Block]: """ Get all blocks after turning lines into blocks. :param column_type: column is SINGLE or MULTI default is SINGLE :return: blocks """ blocks = self.merge_lines_to_block(self.lines) return self.find_block_corners(blocks)
def merge_lines_to_block(self, lines) -> List[Block]: blocks: List[Block] = [] while lines: block = Block() block.add_line(lines.pop(0)) block.page = block.lines[0].page target_line = block.lines[0] index = 0 while index < len(lines): cur_line = lines[index] if target_line.page == cur_line.page: if self.column_type == ColumnType.SINGLE and self.is_start_special_word( cur_line): print("---Found special word---") print(cur_line.text) print("---End special word: Jump to next block---") break else: if self.is_two_line_close(block, cur_line): block.add_line(cur_line) lines.pop(index) index = 0 continue index += 1 blocks.append(block) return blocks
def is_start_special_word(self, cur_line: Line): curStart = cur_line.text.strip().split(" ")[0] pattern = self._regex_pattern()
if re.match(pattern, curStart): return True else: return False
@staticmethod def _regex_pattern() -> str: GENERAL_WORD_DOT_PATTERN = r'^[a-zA-Z0-9]\..*' NON_ALPHANUMERIC_WORD_PATTERN = r'[^a-zA-Z0-9][a-zA-Z0-9][^a-zA-Z0-9].*'
return '{}|{}'.format( GENERAL_WORD_DOT_PATTERN, NON_ALPHANUMERIC_WORD_PATTERN)
def is_two_line_close(self, block, cur_line): last_line: Line = block.lines[-1] target_line: Line = block.lines[0]
if self.is_on_same_page(target_line, cur_line): if self.column_type == ColumnType.MULTI: if (self.is_same_paragraph(last_line, cur_line) or self.is_text_center_context(last_line, cur_line)): return True
elif self.column_type == ColumnType.SINGLE: if (self.is_on_same_line(last_line, cur_line) or self.is_same_paragraph(last_line, cur_line)): return True
return False
@staticmethod def is_on_same_page(line1, line2) -> bool: return line1.page == line2.page
def is_on_same_line(self, last_line, cur_line) -> bool: return self.line_check.is_height_similar(last_line, cur_line)
def is_same_paragraph( self, last_line: Line, cur_line: Line) -> bool: if (self.line_check.is_left_similar(last_line, cur_line) and self.line_check.is_height_similar(last_line, cur_line)): return True
return False
def is_text_center_context(self, last_line: Line, cur_line: Line) -> bool: return (self.line_check.is_center_close(last_line, cur_line) and self.line_check.is_height_similar(last_line, cur_line))
@staticmethod def find_block_corners(blocks: List[Block]) -> List[Block]: for index, block in enumerate(blocks): min_top = min(line.top for line in block.lines) min_left = min(line.left for line in block.lines) max_bottom = max(line.top + line.height for line in block.lines) max_right = max(line.left + line.width for line in block.lines)
block.height = max_bottom - min_top block.width = max_right - min_left block.top = min_top block.left = min_left block.id = index
return blocks
def show_image_bbox(pdf_file, blocks) -> None: """ show image bounding box :param pdf_file: the pdf file location :param blocks: the list of blocks we want to draw """ with open(pdf_file, 'rb') as file: images = convert_from_bytes(file.read())
for index, image in enumerate(images): width, height = image.size page = index + 1 print(f"Process Page Index: {page}")
plt.figure(figsize=(20, 16)) plt.imshow(image)
for i, block in enumerate(blocks): if block.page == page: rect = Rectangle( (width * block.left, height * block.top), block.width * width, block.height * height, edgecolor='r', facecolor='none') plt.text( width * block.left, height * block.top, block.id, fontsize=12, color='red') plt.gca().add_patch(rect) plt.show()
|