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