robotframework-doctestlibrary 0.23.0.dev2__tar.gz → 0.24.0rc2__tar.gz

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 (17) hide show
  1. robotframework_doctestlibrary-0.24.0rc2/DocTest/DocumentRepresentation.py +744 -0
  2. {robotframework_doctestlibrary-0.23.0.dev2 → robotframework_doctestlibrary-0.24.0rc2}/DocTest/Downloader.py +3 -4
  3. robotframework_doctestlibrary-0.24.0rc2/DocTest/IgnoreAreaManager.py +129 -0
  4. {robotframework_doctestlibrary-0.23.0.dev2 → robotframework_doctestlibrary-0.24.0rc2}/DocTest/Ocr.py +25 -9
  5. {robotframework_doctestlibrary-0.23.0.dev2 → robotframework_doctestlibrary-0.24.0rc2}/DocTest/PdfTest.py +10 -11
  6. {robotframework_doctestlibrary-0.23.0.dev2 → robotframework_doctestlibrary-0.24.0rc2}/DocTest/PrintJobTests.py +10 -11
  7. robotframework_doctestlibrary-0.24.0rc2/DocTest/VisualTest.py +1144 -0
  8. robotframework_doctestlibrary-0.24.0rc2/DocTest/config.py +9 -0
  9. {robotframework_doctestlibrary-0.23.0.dev2 → robotframework_doctestlibrary-0.24.0rc2}/PKG-INFO +8 -7
  10. {robotframework_doctestlibrary-0.23.0.dev2 → robotframework_doctestlibrary-0.24.0rc2}/pyproject.toml +8 -6
  11. {robotframework_doctestlibrary-0.23.0.dev2 → robotframework_doctestlibrary-0.24.0rc2}/setup.py +12 -11
  12. robotframework_doctestlibrary-0.23.0.dev2/DocTest/CompareImage.py +0 -651
  13. robotframework_doctestlibrary-0.23.0.dev2/DocTest/VisualTest.py +0 -1010
  14. {robotframework_doctestlibrary-0.23.0.dev2 → robotframework_doctestlibrary-0.24.0rc2}/DocTest/PrintJob.py +0 -0
  15. {robotframework_doctestlibrary-0.23.0.dev2 → robotframework_doctestlibrary-0.24.0rc2}/DocTest/__init__.py +0 -0
  16. {robotframework_doctestlibrary-0.23.0.dev2 → robotframework_doctestlibrary-0.24.0rc2}/LICENSE +0 -0
  17. {robotframework_doctestlibrary-0.23.0.dev2 → robotframework_doctestlibrary-0.24.0rc2}/README.md +0 -0
@@ -0,0 +1,744 @@
1
+ import os
2
+ import cv2
3
+ import pytesseract
4
+ import numpy as np
5
+ import json
6
+ import logging
7
+ from pathlib import Path
8
+ from skimage import metrics
9
+ from typing import List, Dict, Optional, Tuple, Union, Literal
10
+ from concurrent.futures import ThreadPoolExecutor
11
+ from pytesseract import Output
12
+ from DocTest.IgnoreAreaManager import IgnoreAreaManager
13
+ from DocTest.config import DEFAULT_DPI, OCR_ENGINE_DEFAULT, DEFAULT_CONFIDENCE, MINIMUM_OCR_RESOLUTION, ADD_PIXELS_TO_IGNORE_AREA, TESSERACT_CONFIG
14
+ # Constants
15
+
16
+
17
+ class Page:
18
+ def __init__(self, image: np.ndarray, page_number: int, dpi: int = DEFAULT_DPI):
19
+ self.page_number = page_number
20
+ self.image = image # Image as NumPy array (OpenCV format)
21
+ self.dpi = dpi
22
+ self.ocr_text_data: Optional[Dict] = None
23
+ self.pdf_text_data: Optional[Dict] = None
24
+ self.pdf_text_dict: Optional[Dict] = None
25
+ self.pdf_text_blocks: Optional[Dict] = None
26
+ self.pdf_text_words: Optional[Dict] = None
27
+ self.text: str = ""
28
+ self.barcodes: List[Dict] = []
29
+ self.ocr_performed = False
30
+ self.pixel_ignore_areas = []
31
+ self.image_rescaled_for_ocr = False
32
+
33
+ def apply_ocr(self, ocr_engine: str = OCR_ENGINE_DEFAULT, tesseract_config: str = TESSERACT_CONFIG, confidence: int = DEFAULT_CONFIDENCE):
34
+ """Perform OCR on the page image."""
35
+ # re-scale the image to a standard resolution for OCR if needed
36
+ if self.dpi < MINIMUM_OCR_RESOLUTION:
37
+ # Rescale the image to a higher resolution for better OCR results
38
+ scale_factor = MINIMUM_OCR_RESOLUTION / self.dpi
39
+ if self.image.shape[0] * scale_factor < 32767 and self.image.shape[1] * scale_factor < 32767:
40
+ original_image = self.image.copy()
41
+ self.image = cv2.resize(self.image, (0, 0), fx=scale_factor, fy=scale_factor, interpolation=cv2.INTER_CUBIC)
42
+ self.image_rescaled_for_ocr = True
43
+ if ocr_engine == "tesseract":
44
+ config = tesseract_config
45
+ gray_image = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY)
46
+ thresholded_image = cv2.threshold(gray_image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
47
+ self.ocr_text_data = pytesseract.image_to_data(thresholded_image, config=config, output_type=Output.DICT)
48
+ self.ocr_performed = True
49
+ elif ocr_engine == "east":
50
+ from DocTest.Ocr import EastTextExtractor
51
+ self.east_text_extractor = EastTextExtractor()
52
+ text = self.east_text_extractor.get_image_text(self.image)
53
+ self.ocr_text_data= text
54
+ self.ocr_performed = True
55
+ if self.image_rescaled_for_ocr:
56
+ self.image = original_image
57
+
58
+ def get_area(self, area: Dict):
59
+ """Gets the area of the image specified by the coordinates."""
60
+ x, y, w, h = area['x'], area['y'], area['width'], area['height']
61
+ return self.image[y:y+h, x:x+w]
62
+
63
+ def rescale_image_for_ocr(self):
64
+ pass
65
+
66
+ def get_text_content(self):
67
+ """Return the OCR text content."""
68
+ return self.ocr_text_data['text'] if self.ocr_text_data else ""
69
+
70
+ def get_image_with_ignore_areas(self):
71
+ """Return the image with ignore areas highlighted."""
72
+ image_with_ignore_areas = self.image.copy()
73
+ for ignore_area in self.pixel_ignore_areas:
74
+ x, y, w, h = ignore_area.get('x'), ignore_area.get('y'), ignore_area.get('width'), ignore_area.get('height')
75
+ # Add ADD_PIXELS_TO_IGNORE_AREA to the ignore area dimensions
76
+ # Ensure that the ignore area is within the image bounds
77
+
78
+ x -= ADD_PIXELS_TO_IGNORE_AREA
79
+ y -= ADD_PIXELS_TO_IGNORE_AREA
80
+ w += 2 * ADD_PIXELS_TO_IGNORE_AREA
81
+ h += 2 * ADD_PIXELS_TO_IGNORE_AREA
82
+
83
+ x = max(0, x)
84
+ y = max(0, y)
85
+ w = min(w, image_with_ignore_areas.shape[1] - x)
86
+ h = min(h, image_with_ignore_areas.shape[0] - y)
87
+
88
+ # Draw a filled blue rectangle to cover the ignore area
89
+ cv2.rectangle(image_with_ignore_areas, (x, y), (x + w, y + h), (255, 0, 0), -1)
90
+ return image_with_ignore_areas
91
+
92
+ def compare_with(self, other_page: 'Page', threshold: float = 0.0, resize: bool = False, block_based_ssim: bool = False, block_size: int = 32, **kwargs):
93
+ """
94
+ Compare this page with another page and return a tuple of (similarity_result, diff_image).
95
+
96
+ | =Arguments= | =Description= |
97
+ | ``other_page`` | Another Page object to compare against. |
98
+ | ``threshold`` | The SSIM threshold to determine similarity. |
99
+ """
100
+ if self.dpi != other_page.dpi:
101
+ raise ValueError(f"Page DPI mismatch: {self.dpi} vs {other_page.dpi}")
102
+
103
+ blur = kwargs.get('blur', False)
104
+
105
+ if self.pixel_ignore_areas:
106
+ other_page.pixel_ignore_areas = self.pixel_ignore_areas
107
+ self.image = self.get_image_with_ignore_areas()
108
+ other_page.image = other_page.get_image_with_ignore_areas()
109
+
110
+ # Quick check: if the images are of different sizes, they are not similar
111
+ if self.image.shape != other_page.image.shape:
112
+ return False, None, None, None, None
113
+
114
+ # Quick check: if the images are identical, they are similar
115
+ if np.array_equal(self.image, other_page.image):
116
+ return True, None, None, None, None
117
+
118
+ # Perform SSIM (Structural Similarity Index) comparison and get the diff image
119
+ gray_self = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY)
120
+ gray_other = cv2.cvtColor(other_page.image, cv2.COLOR_BGR2GRAY)
121
+
122
+ if blur:
123
+ kernel_size = int(gray_self.shape[1]/30)
124
+ # must be odd if median
125
+ kernel_size += kernel_size%2-1
126
+ gray_self = cv2.GaussianBlur(gray_self, (kernel_size, kernel_size), 1.5)
127
+ gray_other = cv2.GaussianBlur(gray_other, (kernel_size, kernel_size), 1.5)
128
+
129
+ score, diff = metrics.structural_similarity(gray_self, gray_other, full=True)
130
+
131
+ diff = (diff * 255).astype("uint8")
132
+
133
+ thresh = cv2.threshold(diff, 0, 255,
134
+ cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
135
+ absolute_diff = cv2.absdiff(gray_self, gray_other)
136
+
137
+ if block_based_ssim:
138
+ block_based_ssim_result, block_based_ssim_score = self.block_based_ssim_comparison(other_page.image, threshold=threshold, block_size=block_size)
139
+ if not block_based_ssim_result:
140
+ return False, diff, thresh, absolute_diff, 1.0 - block_based_ssim_score
141
+ # Return a tuple: whether the pages are similar, and the difference image
142
+ return score >= (1.0 - threshold), diff, thresh, absolute_diff, 1.0 - score
143
+
144
+
145
+ def block_based_ssim_comparison(self, other_image, threshold: float = 0.0, block_size: int = 32) -> Tuple[bool, float]:
146
+ """
147
+ Perform a block-based SSIM comparison between this page's image and another image,
148
+ including partial blocks at the edges.
149
+
150
+ :param other_image: The image of the other Page to compare against.
151
+ :param threshold: The minimum SSIM score for a block to be considered similar.
152
+ :param block_size: The size of the blocks for block-based SSIM.
153
+ :return:
154
+ - A tuple of (similarity_result, lowest_score)
155
+ where similarity_result is a boolean indicating whether the pages are similar
156
+ - lowest_score is the lowest SSIM score found in any block
157
+ """
158
+
159
+ # Dimensions of the reference image
160
+ height, width = self.image.shape[:2]
161
+
162
+ # Initialize the lowest score to 1.0 (maximum SSIM)
163
+ lowest_score = 1.0
164
+
165
+ # Go row by row in increments of `block_size`
166
+ for y in range(0, height, block_size):
167
+ # Figure out how tall this block really should be (including partial blocks)
168
+ block_height = min(block_size, height - y)
169
+
170
+ # Go column by column in increments of `block_size`
171
+ for x in range(0, width, block_size):
172
+ # Figure out how wide this block really should be
173
+ block_width = min(block_size, width - x)
174
+
175
+ # Extract block from reference and candidate images
176
+ block_ref = self.image[y:y+block_height, x:x+block_width]
177
+ block_cand = other_image[y:y+block_height, x:x+block_width]
178
+
179
+ if np.array_equal(block_ref, block_cand):
180
+ continue
181
+
182
+ # Convert to grayscale
183
+ block_ref_gray = cv2.cvtColor(block_ref, cv2.COLOR_BGR2GRAY)
184
+ block_cand_gray = cv2.cvtColor(block_cand, cv2.COLOR_BGR2GRAY)
185
+
186
+ # If either block is zero-sized (shouldn't happen unless images mismatch), skip
187
+ if block_ref_gray.size == 0 or block_cand_gray.size == 0:
188
+ continue
189
+
190
+ # Determine a `win_size` that does not exceed the block's dimensions.
191
+ # structural_similarity requires:
192
+ # - an odd integer
193
+ # - <= the smallest dimension of the image/block
194
+ # Default is 7, so reduce only if needed.
195
+ min_side = min(block_ref_gray.shape[0], block_ref_gray.shape[1])
196
+ if min_side >= 7:
197
+ # Use default (7) if block is at least 7×7
198
+ win_size = 7
199
+ else:
200
+ # If block is smaller than 7 in any dimension, pick the largest odd integer <= min_side
201
+ # (This ensures we do not exceed the partial block dimensions)
202
+ if min_side % 2 == 0:
203
+ win_size = max(1, min_side - 1)
204
+ else:
205
+ win_size = min_side
206
+
207
+ # Compute SSIM score for the current block using the chosen window size
208
+ block_score = metrics.structural_similarity(
209
+ block_ref_gray,
210
+ block_cand_gray,
211
+ win_size=win_size
212
+ )
213
+
214
+ # Track the lowest block SSIM
215
+ lowest_score = abs(min(lowest_score, block_score))
216
+
217
+ # If any block's SSIM falls below (1.0 - threshold), return immediately
218
+ if lowest_score < (1.0 - threshold):
219
+ return False, lowest_score
220
+
221
+ # If we reach here, all blocks (including partials) are above the threshold
222
+ return True, lowest_score
223
+
224
+ def identify_barcodes(self):
225
+ """Detect and store barcodes for this page."""
226
+ self.identify_barcodes_with_zbar()
227
+ self.identify_datamatrices()
228
+
229
+ def identify_barcodes_with_zbar(self):
230
+ try:
231
+ from pyzbar import pyzbar
232
+ except:
233
+ logging.debug('Failed to import pyzbar', exc_info=True)
234
+ return
235
+ image_height = self.image.shape[0]
236
+ image_width = self.image.shape[1]
237
+ barcodes = pyzbar.decode(self.image)
238
+ #Add barcode as placehoder
239
+ for barcode in barcodes:
240
+ logging.debug(barcode)
241
+ x = barcode.rect.left
242
+ y = barcode.rect.top
243
+ h = barcode.rect.height
244
+ w = barcode.rect.width
245
+ value = barcode.data.decode("utf-8")
246
+ self.barcodes.append({"x":x, "y":y, "height":h, "width":w, "value":value})
247
+ self.pixel_ignore_areas.append({"x": x, "y": y, "height": h, "width": w})
248
+
249
+ def identify_datamatrices(self):
250
+ try:
251
+ from pylibdmtx import pylibdmtx
252
+ except:
253
+ logging.debug('Failed to import pylibdmtx', exc_info=True)
254
+ return
255
+ logging.debug("Identify datamatrices")
256
+ image_height = self.image.shape[0]
257
+ try:
258
+ barcodes = pylibdmtx.decode(self.image, timeout=5000)
259
+ except:
260
+ logging.debug("pylibdmtx could not be loaded",exc_info=True)
261
+ return
262
+ #Add barcode as placehoder
263
+ for barcode in barcodes:
264
+ print(barcode)
265
+ x = barcode.rect.left
266
+ y = image_height - barcode.rect.top - barcode.rect.height
267
+ h = barcode.rect.height
268
+ w = barcode.rect.width
269
+ value = barcode.data.decode("utf-8")
270
+ self.barcodes.append({"x":x, "y":y, "height":h, "width":w, "value":value})
271
+ self.pixel_ignore_areas.append({"x": x, "y:": y, "height": h, "width": w})
272
+
273
+ def _process_ignore_area(self, ignore_area: Dict):
274
+ """Process each ignore area based on its type and convert it into pixel-based coordinates."""
275
+ ignore_area_type = ignore_area.get('type')
276
+
277
+ if ignore_area_type in ['pattern', 'line_pattern', 'word_pattern']:
278
+ self._process_pattern_ignore_area(ignore_area)
279
+ elif ignore_area_type == 'coordinates':
280
+ self._process_coordinates_ignore_area(ignore_area)
281
+ elif ignore_area_type == 'area':
282
+ self._process_area_ignore_area(ignore_area)
283
+
284
+ def _process_pattern_ignore_area_from_ocr(self, ignore_area: Dict):
285
+ """Handle pattern-based ignore areas by searching the OCR text for text patterns."""
286
+ import re
287
+ pattern = ignore_area.get('pattern')
288
+ xoffset = int(ignore_area.get('xoffset', 0))
289
+ yoffset = int(ignore_area.get('yoffset', 0))
290
+
291
+ # Iterate through text data to identify matching patterns and mark as ignore areas
292
+ n_boxes = len(self.ocr_text_data['text'])
293
+ for j in range(n_boxes):
294
+ if int(self.ocr_text_data.get('conf', [0])[j]) > DEFAULT_CONFIDENCE and re.match(pattern, self.ocr_text_data['text'][j]):
295
+ x, y, w, h = self.ocr_text_data['left'][j], self.ocr_text_data['top'][j], self.ocr_text_data['width'][j], self.ocr_text_data['height'][j]
296
+ if self.image_rescaled_for_ocr:
297
+ pixel_factor = self.dpi / MINIMUM_OCR_RESOLUTION
298
+ (x, y, w, h) = (int(x * pixel_factor), int(y * pixel_factor), int(w * pixel_factor), int(h * pixel_factor))
299
+ text_mask = {"x": int(x) - xoffset, "y": int(y) - yoffset, "width": int(w) + 2 * xoffset, "height": int(h) + 2 * yoffset}
300
+ self.pixel_ignore_areas.append(text_mask)
301
+
302
+ def _process_pattern_ignore_area_from_pdf(self, ignore_area: Dict):
303
+ import re
304
+ pattern_type = ignore_area.get('pattern_type')
305
+ pattern = ignore_area.get('pattern')
306
+ xoffset = int(ignore_area.get('xoffset', 0))
307
+ yoffset = int(ignore_area.get('yoffset', 0))
308
+ search_pattern = re.compile(pattern)
309
+ if pattern_type == "word_pattern":
310
+ if self.pdf_text_words:
311
+ for word in self.pdf_text_words:
312
+ if search_pattern.match(word[4]):
313
+ (x, y, w, h) = (word[0]*self.dpi/72, word[1]*self.dpi/72, word[2]*self.dpi/72, word[3]*self.dpi/72)
314
+ text_mask = {"x": int(x) - xoffset, "y": int(y) - yoffset, "width": int(w) + 2 * xoffset, "height": int(h) + 2 * yoffset}
315
+ self.pixel_ignore_areas.append(text_mask)
316
+ else:
317
+ if self.pdf_text_dict:
318
+ for block in self.pdf_text_dict['blocks']:
319
+ if block['type'] == 0:
320
+ for line in block['lines']:
321
+ if len(line['spans']) != 0 and search_pattern.match(line['spans'][0]['text']):
322
+ (x, y, w, h) = (line['bbox'][0]*self.dpi/72, line['bbox'][1]*self.dpi/72,(line['bbox'][2]-line['bbox'][0])*self.dpi/72, (line['bbox'][3]-line['bbox'][1])*self.dpi/72)
323
+ text_mask = {"x": int(x) - xoffset, "y": int(y) - yoffset, "width": int(w) + 2 * xoffset, "height": int(h) + 2 * yoffset}
324
+ self.pixel_ignore_areas.append(text_mask)
325
+
326
+
327
+ def _process_pattern_ignore_area(self, ignore_area: Dict):
328
+ """Handle pattern-based ignore areas by searching the page for text patterns."""
329
+ # import re
330
+ # pattern = ignore_area.get('pattern')
331
+ # xoffset = int(ignore_area.get('xoffset', 0))
332
+ # yoffset = int(ignore_area.get('yoffset', 0))
333
+
334
+ if self.ocr_performed:
335
+ self._process_pattern_ignore_area_from_ocr(ignore_area)
336
+ elif self.pdf_text_data or self.pdf_text_dict or self.pdf_text_words:
337
+ self._process_pattern_ignore_area_from_pdf(ignore_area)
338
+
339
+ def _process_coordinates_ignore_area(self, ignore_area: Dict):
340
+ """Convert coordinate-based ignore areas into pixel-wise ignore areas."""
341
+ unit = ignore_area.get('unit', 'px')
342
+ x, y, w, h = self._convert_to_pixels(ignore_area, unit)
343
+ self.pixel_ignore_areas.append({"x": x, "y": y, "height": h, "width": w})
344
+
345
+ def _convert_to_pixels(self, area: Dict, unit: str):
346
+ """Convert dimensions from cm, mm, or px to pixel units."""
347
+ x, y, w, h = int(area['x']), int(area['y']), int(area['width']), int(area['height'])
348
+ if unit == 'mm':
349
+ constant = self.dpi / 25.4
350
+ x, y, w, h = int(x * constant), int(y * constant), int(w * constant), int(h * constant)
351
+ elif unit == 'cm':
352
+ constant = self.dpi / 2.54
353
+ x, y, w, h = int(x * constant), int(y * constant), int(w * constant), int(h * constant)
354
+ return x, y, w, h
355
+
356
+ def _process_area_ignore_area(self, ignore_area: Dict):
357
+ """Handle area-based ignore areas (e.g., 'top', 'bottom', 'left', 'right') as percentages."""
358
+ page = ignore_area.get('page', 'all')
359
+ # Cast the page number to an integer if it is not 'all'
360
+ if page != 'all':
361
+ page = int(page)
362
+ if page == 'all' or page == self.page_number:
363
+ location = ignore_area.get('location', None)
364
+ percent = int(ignore_area.get('percent', 10))
365
+ x, y, w, h = 0, 0, self.image.shape[1], self.image.shape[0]
366
+ if location == 'top':
367
+ h = int(self.image.shape[0] * percent / 100)
368
+ elif location == 'bottom':
369
+ h = int(self.image.shape[0] * percent / 100)
370
+ y = self.image.shape[0] - h
371
+ elif location == 'left':
372
+ w = int(self.image.shape[1] * percent / 100)
373
+ elif location == 'right':
374
+ w = int(self.image.shape[1] * percent / 100)
375
+ x = self.image.shape[1] - w
376
+ self.pixel_ignore_areas.append({"x": x, "y": y, "width": w, "height": h})
377
+
378
+ def _get_text(self, force_ocr: bool = False, ocr_engine: Literal['tesseract', 'east'] = 'tesseract', confidence: int = DEFAULT_CONFIDENCE, tesseract_config: str = TESSERACT_CONFIG, **kwargs):
379
+ """Extract text content from the page image."""
380
+ if force_ocr and not self.ocr_performed:
381
+ self.apply_ocr(ocr_engine=ocr_engine, confidence=confidence, tesseract_config=tesseract_config)
382
+ return " ".join(self.ocr_text_data['text'])
383
+ if self.ocr_performed:
384
+ return " ".join(self.ocr_text_data['text'])
385
+ elif self.pdf_text_words:
386
+ return make_text(self.pdf_text_words).split()
387
+ else:
388
+ self.apply_ocr(ocr_engine=ocr_engine, confidence=confidence, tesseract_config=tesseract_config)
389
+ return " ".join(self.ocr_text_data['text'])
390
+
391
+ def _get_text_from_area(self, area: Dict, force_ocr: bool = False):
392
+ """Extract text content from a specific area of the page:
393
+ Returns the text content within the specified area.
394
+ An area is defined by a dictionary with keys 'x', 'y', 'width', and 'height'.
395
+ It can also be a tuple with the format (x, y, width, height).
396
+ Units are in pixels by default.
397
+ Optional: Units can be specified as 'mm' or 'cm' via the 'unit' key.
398
+ """
399
+ if force_ocr:
400
+ # Shortcut: if OCR is forced, extract text using Tesseract
401
+ return self._get_text_from_area_with_tesseract(area)
402
+
403
+ try:
404
+ unit = area.get('unit', 'px')
405
+ except:
406
+ unit = 'px'
407
+ area_x, area_y, area_h, area_w = self._convert_to_pixels(area, unit)
408
+
409
+
410
+ if self.ocr_performed:
411
+ text = ""
412
+ for i, box in enumerate(self.ocr_text_data['text']):
413
+ x, y, w, h = self.ocr_text_data['left'][i], self.ocr_text_data['top'][i], self.ocr_text_data['width'][i], self.ocr_text_data['height'][i]
414
+ if x >= area_x and y >= area_y and x + w <= area_x + area_w and y + h <= area_y + area_h:
415
+ text += box + " "
416
+ return text.strip()
417
+
418
+ elif self.pdf_text_words:
419
+ text = ""
420
+ import fitz
421
+ rect = fitz.Rect(
422
+ area_x*72/self.dpi, area_y*72/self.dpi, (area_x+area_w)*72/self.dpi, (area_y+area_h)*72/self.dpi)
423
+ diff_area_ref_words = [
424
+ w for w in self.pdf_text_words if fitz.Rect(w[:4]).intersects(rect)]
425
+ return make_text(diff_area_ref_words).split()
426
+ else:
427
+ return self._get_text_from_area_with_tesseract(area)
428
+
429
+ def _get_text_from_area_with_tesseract(self, area: Dict):
430
+ """Extract text content from a specific area of the page using Tesseract OCR."""
431
+ x, y, w, h = self._convert_to_pixels(area, area.get('unit', 'px'))
432
+ image = self.image[y:y+h, x:x+w]
433
+ # upscale the image if the resolution is too low for OCR
434
+ if self.dpi < MINIMUM_OCR_RESOLUTION:
435
+ scale_factor = MINIMUM_OCR_RESOLUTION / self.dpi
436
+ image = cv2.resize(image, (0, 0), fx=scale_factor, fy=scale_factor, interpolation=cv2.INTER_CUBIC)
437
+ gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
438
+ thresholded_image = cv2.threshold(gray_image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
439
+ # Add a white border around the image to improve OCR accuracy
440
+ thresholded_image = cv2.copyMakeBorder(thresholded_image, 10, 10, 10, 10, cv2.BORDER_CONSTANT, value=(255, 255, 255))
441
+ config = f'--psm 11 -l eng'
442
+ text = pytesseract.image_to_string(thresholded_image, config=config)
443
+ return text.strip()
444
+
445
+ def _compare_text_content_in_area_with(self, other_page: 'Page', area: Dict, force_ocr: bool = False):
446
+ """Compare text content in a specific area of the page with another page.
447
+ Returns True if the text content in the specified area is the same between the two pages.
448
+ Also returns the text content from the area in both pages.
449
+ Area can be defined by a dictionary with keys 'x', 'y', 'width', and 'height'.
450
+ Or it can be a tuple like (124, 337, 287, 121) where the values are in pixels.
451
+
452
+ """
453
+ text_self = self._get_text_from_area(area, force_ocr)
454
+ text_other = other_page._get_text_from_area(area, force_ocr)
455
+ return text_self == text_other, text_self, text_other
456
+
457
+ def _get_area(self, area: Dict):
458
+ """Extract the specified area from the page image.
459
+ Area is a rectangle object from cv2
460
+ """
461
+ x, y, w, h = self._convert_to_pixels(area, area.get('unit', 'px'))
462
+ return self.image[y:y+h, x:x+w]
463
+
464
+ class DocumentRepresentation:
465
+ def __init__(self, file_path: str, dpi: int = DEFAULT_DPI, ocr_engine: Literal['tesseract', 'east'] = OCR_ENGINE_DEFAULT, tesseract_config: str = TESSERACT_CONFIG, ignore_area_file: Union[str, dict, list] = None, ignore_area: Union[str, dict, list] = None, force_ocr: bool = False, contains_barcodes: bool = False):
466
+ self.file_path = Path(file_path)
467
+ self.dpi = dpi
468
+ self.contains_barcodes = contains_barcodes
469
+ self.pages: List[Page] = []
470
+ self.ocr_engine = ocr_engine
471
+ self.abstract_ignore_areas = []
472
+ self.barcodes = []
473
+ self.load_document()
474
+ self.create_abstract_ignore_areas(ignore_area_file, ignore_area)
475
+ self.create_pixel_based_ignore_areas(force_ocr)
476
+ if self.contains_barcodes:
477
+ self.identify_barcodes()
478
+
479
+ def load_document(self):
480
+ """Load the document, either as an image or a multi-page PDF, into Page objects."""
481
+ if self.file_path.suffix == '.pdf':
482
+ self._load_pdf()
483
+ elif self.file_path.suffix == '.pcl':
484
+ self._load_pcl()
485
+ elif self.file_path.suffix == '.ps':
486
+ self._load_ps()
487
+ else:
488
+ self._load_image()
489
+
490
+ def _load_image(self):
491
+ """Load a single image file as a Page object."""
492
+ image = cv2.imread(str(self.file_path))
493
+ # For images, the dpi is always 72 (default for OpenCV)
494
+ self.dpi = 72
495
+ if image is None:
496
+ raise ValueError(f"Cannot load image from {self.file_path}")
497
+ page = Page(image, page_number=1, dpi=self.dpi)
498
+ self.pages.append(page)
499
+
500
+ def _load_pdf(self):
501
+ """Load a PDF document, converting each page into a Page object."""
502
+ try:
503
+ import fitz # PyMuPDF
504
+ doc = fitz.open(str(self.file_path))
505
+ for page_num in range(len(doc)):
506
+ page = doc.load_page(page_num)
507
+ pix = page.get_pixmap(dpi=self.dpi)
508
+ img_data = pix.tobytes("png")
509
+ image = cv2.imdecode(np.frombuffer(img_data, np.uint8), cv2.IMREAD_COLOR)
510
+ self.pages.append(Page(image, page_number=page_num + 1, dpi=self.dpi))
511
+ self.pages[-1].pdf_text_data = page.get_text("text")
512
+ self.pages[-1].pdf_text_dict = page.get_text("dict")
513
+ self.pages[-1].pdf_text_words = page.get_text("words")
514
+ self.pages[-1].pdf_text_blocks = page.get_text("blocks")
515
+ except ImportError:
516
+ raise ImportError("PyMuPDF (fitz) is required for PDF processing.")
517
+
518
+ def _load_pcl(self, resolution: int = None):
519
+ import subprocess
520
+ import shutil
521
+ import random
522
+ import tempfile
523
+ from os.path import splitext, split
524
+ try:
525
+ command = shutil.which('pcl6') or shutil.which('gpcl6win64') or shutil.which('gpcl6win32') or shutil.which('gpcl6')
526
+ except:
527
+ raise AssertionError("No pcl6 executable found in path. Please install ghostPCL")
528
+ filename_without_extension = self.file_path.stem
529
+ if resolution == None:
530
+ resolution = self.dpi
531
+ output_image_directory = os.path.join(tempfile.gettempdir(), filename_without_extension+str(random.randint(100, 999)))
532
+
533
+ is_exist = os.path.exists(output_image_directory)
534
+ if not is_exist:
535
+ os.makedirs(output_image_directory)
536
+ else:
537
+ shutil.rmtree(output_image_directory)
538
+ os.makedirs(output_image_directory)
539
+ Output_filepath = os.path.join(output_image_directory,'output-%d.png')
540
+
541
+ args = [
542
+ command,
543
+ '-dNOPAUSE',
544
+ "-sDEVICE=png16m",
545
+ f"-r{resolution}",
546
+ f"-sOutputFile={Output_filepath}",
547
+ self.file_path
548
+ ]
549
+ subprocess.run(args, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
550
+ page = 1
551
+ for image in os.listdir(output_image_directory):
552
+ image_file =os.path.join(output_image_directory, image)
553
+ data = cv2.imread(image_file)
554
+
555
+ if data is None:
556
+ raise AssertionError("No OpenCV Image could be created for file {} . Maybe the file is corrupt?".format(self.image))
557
+ self.pages.append(Page(data, page, resolution))
558
+ page += 1
559
+
560
+ shutil.rmtree(output_image_directory)
561
+
562
+ def _load_ps(self, resolution: int = None):
563
+ import subprocess
564
+ import shutil
565
+ import random
566
+ import tempfile
567
+ from os.path import splitext, split
568
+ try:
569
+ command = shutil.which('gs') or shutil.which('gswin64c') or shutil.which('gswin32c') or shutil.which('ghostscript')
570
+ except:
571
+ raise AssertionError("No ghostscript executable found in path. Please install ghostscript")
572
+ filename_without_extension = self.file_path.stem
573
+ if resolution == None:
574
+ resolution = self.dpi
575
+ output_image_directory = os.path.join(tempfile.gettempdir(), filename_without_extension+str(random.randint(100, 999)))
576
+ is_exist = os.path.exists(output_image_directory)
577
+ if not is_exist:
578
+ os.makedirs(output_image_directory)
579
+ else:
580
+ shutil.rmtree(output_image_directory)
581
+ os.makedirs(output_image_directory)
582
+ Output_filepath = os.path.join(output_image_directory, 'output-%d.png')
583
+ args = [
584
+ command,
585
+ '-dNOPAUSE',
586
+ "-dBATCH",
587
+ "-dSAFER",
588
+ "-sDEVICE=png16m",
589
+ f"-r{resolution}",
590
+ f"-sOutputFile={Output_filepath}",
591
+ self.file_path
592
+ ]
593
+ subprocess.run(args, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
594
+ page = 1
595
+ for image in os.listdir(output_image_directory):
596
+ image_file =os.path.join(output_image_directory, image)
597
+ data = cv2.imread(image_file)
598
+ if data is None:
599
+ raise AssertionError("No OpenCV Image could be created for file {} . Maybe the file is corrupt?".format(self.image))
600
+ self.pages.append(Page(data, page, resolution))
601
+ page += 1
602
+ shutil.rmtree(output_image_directory)
603
+
604
+ def get_barcodes(self):
605
+ """Return a list of barcodes detected in the document."""
606
+ barcodes = []
607
+ for page in self.pages:
608
+ barcodes.extend(page.barcodes)
609
+ return barcodes
610
+
611
+ def apply_ocr(self, parallel: bool = False):
612
+ """Apply OCR to each page of the document."""
613
+ if parallel:
614
+ with ThreadPoolExecutor() as executor:
615
+ executor.map(lambda page: page.apply_ocr(self.ocr_engine), self.pages)
616
+ else:
617
+ for page in self.pages:
618
+ page.apply_ocr(self.ocr_engine)
619
+
620
+ def extract_text_from_pdf(self) -> str:
621
+ """
622
+ Attempt to extract text directly from a PDF document.
623
+ Returns the text content if available, otherwise returns an empty string.
624
+ """
625
+ if not self.file_path.suffix == '.pdf':
626
+ return ""
627
+
628
+ try:
629
+ import fitz # PyMuPDF
630
+ with fitz.open(str(self.file_path)) as pdf:
631
+ text_content = ""
632
+ for page_num in range(len(pdf)):
633
+ page = pdf.load_page(page_num)
634
+ text_content += page.get_text("text")
635
+ return text_content if text_content.strip() else ""
636
+ except Exception as e:
637
+ print(f"Failed to extract text from PDF: {e}")
638
+ return ""
639
+
640
+ def compare_with(self, other_doc: 'DocumentRepresentation') -> bool:
641
+ """Compare this document with another document."""
642
+ if len(self.pages) != len(other_doc.pages):
643
+ raise ValueError("Documents have different number of pages.")
644
+
645
+ # Compare page by page
646
+ for page_self, page_other in zip(self.pages, other_doc.pages):
647
+ if not page_self.compare_with(page_other):
648
+ return False
649
+ return True
650
+
651
+ def create_abstract_ignore_areas(self, ignore_area_file: Union[str, dict, list], ignore_area: Union[str, dict, list]):
652
+ """Read ignore areas from the provided file or mask and return a list of ignore areas."""
653
+ if ignore_area_file:
654
+ ignore_area_manager = IgnoreAreaManager(ignore_area_file=ignore_area_file)
655
+ self.abstract_ignore_areas = ignore_area_manager.read_ignore_areas()
656
+ elif ignore_area:
657
+ ignore_area_manager = IgnoreAreaManager(mask=ignore_area)
658
+ self.abstract_ignore_areas = ignore_area_manager.read_ignore_areas()
659
+
660
+ def create_pixel_based_ignore_areas(self, force_ocr: bool = False):
661
+ """Apply ignore areas to each page of the document."""
662
+
663
+ for page in self.pages:
664
+ # If ignore area is of type pattern, line_pattern, or word_pattern
665
+ # and if filetype is PDF, read text directly from PDF
666
+ # to identify the pattern-based ignore areas
667
+ # If force_ocr is True or page.text_content is not available, apply OCR
668
+
669
+ for ignore_area in self.abstract_ignore_areas:
670
+ if ignore_area.get('type') in ['pattern', 'line_pattern', 'word_pattern']:
671
+ if (force_ocr or not page.pdf_text_data) and not page.ocr_performed:
672
+ page.apply_ocr(ocr_engine=self.ocr_engine)
673
+ page._process_ignore_area(ignore_area)
674
+
675
+
676
+ def get_text_from_area(self, area: Dict, force_ocr: bool = False):
677
+ """Extract text content from a specific area of the document."""
678
+ text_content = ""
679
+ for page in self.pages:
680
+ text_content += page._get_text_from_area(area, force_ocr) + " "
681
+ return text_content.strip()
682
+
683
+ def get_text(self, force_ocr: bool = False, tesseract_config: str = TESSERACT_CONFIG):
684
+ """Extract text content from the document."""
685
+ # If doc is pdf, extract text directly from pdf
686
+ text_content = ""
687
+ if force_ocr:
688
+ for page in self.pages:
689
+ text_content += page._get_text(force_ocr, ocr_engine=self.ocr_engine, tesseract_config=tesseract_config) + " "
690
+ return text_content.strip()
691
+ if self.file_path.suffix == '.pdf':
692
+ text_content = self.extract_text_from_pdf()
693
+ return text_content
694
+ else:
695
+ # If OCR is not forced, extract text from the OCR data
696
+ for page in self.pages:
697
+ text_content += page._get_text(force_ocr, ocr_engine=self.ocr_engine, tesseract_config=tesseract_config) + " "
698
+ return text_content.strip()
699
+
700
+ def identify_barcodes(self):
701
+ """Detect barcodes in all pages."""
702
+ for page in self.pages:
703
+ page.identify_barcodes()
704
+
705
+ def save_images(self, output_dir: str):
706
+ """Save all pages as images to the specified directory."""
707
+ os.makedirs(output_dir, exist_ok=True)
708
+ for page in self.pages:
709
+ output_path = os.path.join(output_dir, f'page_{page.page_number}.png')
710
+ cv2.imwrite(output_path, page.image)
711
+
712
+ def compare_visuals(self, other_doc: 'DocumentRepresentation'):
713
+ """Compare images between two documents."""
714
+ return self.compare_with(other_doc)
715
+
716
+ def assign_ignore_areas_to_pages(self, ignore_areas: List[Dict]):
717
+ """Assign each ignore area to the corresponding page."""
718
+ for page in self.pages:
719
+ for ignore_area in ignore_areas:
720
+ if ignore_area.get('page') == page.page_number or ignore_area.get('page') == 'all':
721
+ page.ignore_areas.append(ignore_area)
722
+
723
+
724
+ def identify_barcodes(self):
725
+ """Detect barcodes in all pages."""
726
+ for page in self.pages:
727
+ page.identify_barcodes()
728
+
729
+ def make_text(words):
730
+ """Return textstring output of get_text("words").
731
+ Word items are sorted for reading sequence left to right,
732
+ top to bottom.
733
+ """
734
+ line_dict = {} # key: vertical coordinate, value: list of words
735
+ words.sort(key=lambda w: w[0]) # sort by horizontal coordinate
736
+ for w in words: # fill the line dictionary
737
+ y1 = round(w[3], 1) # bottom of a word: don't be too picky!
738
+ word = w[4] # the text of the word
739
+ line = line_dict.get(y1, []) # read current line content
740
+ line.append(word) # append new word
741
+ line_dict[y1] = line # write back to dict
742
+ lines = list(line_dict.items())
743
+ lines.sort() # sort vertically
744
+ return "\n".join([" ".join(line[1]) for line in lines])