robotframework-doctestlibrary 0.32.0.dev2__py3-none-any.whl → 0.32.0.dev3__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.
@@ -17,6 +17,7 @@ from DocTest.PdfStructureModels import (
17
17
  PageStructure,
18
18
  StructureExtractionConfig,
19
19
  build_page_structure,
20
+ build_page_structure_from_words,
20
21
  )
21
22
  from DocTest.config import DEFAULT_DPI, OCR_ENGINE_DEFAULT, DEFAULT_CONFIDENCE, MINIMUM_OCR_RESOLUTION, ADD_PIXELS_TO_IGNORE_AREA, TESSERACT_CONFIG
22
23
  import tempfile
@@ -197,13 +198,27 @@ class Page:
197
198
  cached = self._structure_cache.get(config)
198
199
  if cached:
199
200
  return cached
200
- structure = build_page_structure(
201
- page_number=self.page_number,
202
- pdf_dict=self.pdf_text_dict,
203
- config=config,
204
- dpi=self.dpi,
205
- image_shape=self.image.shape,
206
- )
201
+ if config.spatial_word_sorting and self.pdf_text_words:
202
+ # Derive page dimensions from the dict if available.
203
+ pw = float(self.pdf_text_dict.get("width", 0)) if self.pdf_text_dict else 0.0
204
+ ph = float(self.pdf_text_dict.get("height", 0)) if self.pdf_text_dict else 0.0
205
+ structure = build_page_structure_from_words(
206
+ page_number=self.page_number,
207
+ pdf_text_words=self.pdf_text_words,
208
+ config=config,
209
+ page_width=pw,
210
+ page_height=ph,
211
+ dpi=self.dpi,
212
+ image_shape=self.image.shape,
213
+ )
214
+ else:
215
+ structure = build_page_structure(
216
+ page_number=self.page_number,
217
+ pdf_dict=self.pdf_text_dict,
218
+ config=config,
219
+ dpi=self.dpi,
220
+ image_shape=self.image.shape,
221
+ )
207
222
  self._structure_cache[config] = structure
208
223
  return structure
209
224
 
@@ -18,6 +18,7 @@ __all__ = [
18
18
  "collapse_whitespace",
19
19
  "round_bbox",
20
20
  "build_page_structure",
21
+ "build_page_structure_from_words",
21
22
  "flatten_document_text",
22
23
  "flatten_document_words",
23
24
  ]
@@ -82,6 +83,7 @@ class StructureExtractionConfig:
82
83
  round_precision: Optional[int] = 3
83
84
  normalize_ligatures: bool = False
84
85
  character_replacements: Optional[Dict[str, str]] = None
86
+ spatial_word_sorting: bool = False
85
87
 
86
88
  def __hash__(self) -> int: # Allow usage as dictionary key for caching.
87
89
  # Convert character_replacements dict to a hashable tuple of sorted items
@@ -100,6 +102,7 @@ class StructureExtractionConfig:
100
102
  self.round_precision,
101
103
  self.normalize_ligatures,
102
104
  replacements_hash,
105
+ self.spatial_word_sorting,
103
106
  )
104
107
  )
105
108
 
@@ -364,3 +367,151 @@ def build_page_structure(
364
367
  height=height,
365
368
  blocks=blocks,
366
369
  )
370
+
371
+
372
+ def build_page_structure_from_words(
373
+ page_number: int,
374
+ pdf_text_words: Optional[List],
375
+ config: Optional[StructureExtractionConfig] = None,
376
+ *,
377
+ page_width: float = 0.0,
378
+ page_height: float = 0.0,
379
+ dpi: Optional[int] = None,
380
+ image_shape: Optional[Tuple[int, int, int]] = None,
381
+ ) -> PageStructure:
382
+ """Build a ``PageStructure`` from PyMuPDF ``get_text("words")`` output.
383
+
384
+ This bypasses block-level extraction entirely, grouping individual word
385
+ bounding boxes into lines using adaptive Y-proximity. The result is
386
+ immune to block fragmentation caused by different PDF generators.
387
+
388
+ Each word tuple from PyMuPDF has the form::
389
+
390
+ (x0, y0, x1, y1, "word", block_no, line_no, word_no)
391
+
392
+ Words are grouped into lines when their vertical midpoints are within
393
+ half the minimum word height of each other. Within each line, words
394
+ are ordered left-to-right by ``x0``. Lines are ordered top-to-bottom.
395
+ Each line becomes its own ``TextBlock`` (single-line blocks).
396
+
397
+ Args:
398
+ page_number: Zero-based page index.
399
+ pdf_text_words: List of word tuples from ``page.get_text("words")``.
400
+ config: Normalization settings (whitespace, ligatures, etc.).
401
+ page_width: Page width in points.
402
+ page_height: Page height in points.
403
+ dpi: Optional DPI for computing page dimensions from ``image_shape``.
404
+ image_shape: ``(height, width, channels)`` array shape, used with *dpi*
405
+ to derive page dimensions when ``page_width``/``page_height`` are zero.
406
+
407
+ Returns:
408
+ A ``PageStructure`` with one block per reconstructed text line.
409
+ """
410
+ config = config or StructureExtractionConfig()
411
+
412
+ width = page_width
413
+ height = page_height
414
+ if (width == 0.0 or height == 0.0) and image_shape and dpi:
415
+ px_height, px_width = image_shape[:2]
416
+ width = px_width * 72.0 / dpi
417
+ height = px_height * 72.0 / dpi
418
+
419
+ if not pdf_text_words:
420
+ return PageStructure(
421
+ page_number=page_number,
422
+ width=width,
423
+ height=height,
424
+ blocks=[],
425
+ )
426
+
427
+ # --- Group words into visual lines by Y-proximity ---
428
+ # Sort by vertical midpoint first, then horizontal position.
429
+ sorted_words = sorted(pdf_text_words, key=lambda w: ((w[1] + w[3]) / 2.0, w[0]))
430
+
431
+ lines: List[List] = [] # Each element: list of word tuples
432
+ line_y_mid: List[float] = [] # Representative Y midpoint per line
433
+ line_min_height: List[float] = [] # Cached minimum word height per line
434
+
435
+ for word in sorted_words:
436
+ w_y0, w_y1 = float(word[1]), float(word[3])
437
+ w_mid = (w_y0 + w_y1) / 2.0
438
+ w_height = max(w_y1 - w_y0, 1.0)
439
+
440
+ # Search backward from most recent line (words are Y-sorted, so the
441
+ # most recent line is the most likely match). Break early once we
442
+ # move past the tolerance range.
443
+ merged = False
444
+ max_possible_tolerance = w_height * 0.5
445
+ for idx in range(len(lines) - 1, -1, -1):
446
+ ly_mid = line_y_mid[idx]
447
+ delta = abs(w_mid - ly_mid)
448
+ if delta > max_possible_tolerance and w_mid > ly_mid:
449
+ break # Past tolerance; earlier lines are even further away.
450
+ tolerance = min(line_min_height[idx], w_height) * 0.5
451
+ if delta <= tolerance:
452
+ lines[idx].append(word)
453
+ n = len(lines[idx])
454
+ line_y_mid[idx] = ly_mid + (w_mid - ly_mid) / n
455
+ if w_height < line_min_height[idx]:
456
+ line_min_height[idx] = w_height
457
+ merged = True
458
+ break
459
+ if not merged:
460
+ lines.append([word])
461
+ line_y_mid.append(w_mid)
462
+ line_min_height.append(w_height)
463
+
464
+ # Sort lines top-to-bottom by midpoint, words left-to-right within each.
465
+ indexed_lines = sorted(enumerate(lines), key=lambda pair: line_y_mid[pair[0]])
466
+
467
+ blocks: List[TextBlock] = []
468
+ global_line_index = 0
469
+ block_index = 0
470
+
471
+ for _orig_idx, line_words in indexed_lines:
472
+ line_words_sorted = sorted(line_words, key=lambda w: float(w[0]))
473
+
474
+ # Build text from words, applying normalization.
475
+ text_parts: List[str] = []
476
+ for w in line_words_sorted:
477
+ raw = str(w[4])
478
+ normalized = _sanitize_span_text(raw, config)
479
+ if normalized:
480
+ text_parts.append(normalized)
481
+
482
+ line_text = config.whitespace_replacement.join(text_parts) if text_parts else ""
483
+ if config.strip_line_edges:
484
+ line_text = line_text.strip()
485
+ if config.drop_empty_lines and not line_text:
486
+ continue
487
+
488
+ # Compute line bbox as union of all word bboxes.
489
+ x0 = min(float(w[0]) for w in line_words_sorted)
490
+ y0 = min(float(w[1]) for w in line_words_sorted)
491
+ x1 = max(float(w[2]) for w in line_words_sorted)
492
+ y1 = max(float(w[3]) for w in line_words_sorted)
493
+ bbox = round_bbox((x0, y0, x1, y1), config.round_precision)
494
+
495
+ text_line = TextLine(
496
+ index=global_line_index,
497
+ text=line_text,
498
+ bbox=bbox,
499
+ fonts=set(),
500
+ spans=[TextSpan(text=line_text, font=None, size=0.0)],
501
+ )
502
+ blocks.append(
503
+ TextBlock(
504
+ index=block_index,
505
+ bbox=bbox,
506
+ lines=[text_line],
507
+ )
508
+ )
509
+ global_line_index += 1
510
+ block_index += 1
511
+
512
+ return PageStructure(
513
+ page_number=page_number,
514
+ width=width,
515
+ height=height,
516
+ blocks=blocks,
517
+ )
DocTest/PdfTest.py CHANGED
@@ -577,6 +577,7 @@ class PdfTest(object):
577
577
  - ``compare_order`` (str, default ``"ordered"``): comparison strategy for word-level comparison. ``"ordered"`` uses sequence-sensitive matching; ``"unordered"`` uses bag-of-words frequency comparison that ignores word order, useful when text reflows across pages.
578
578
  - ``check_geometry`` (bool, default ``True``): when ``False``, skip line position/size comparison. Useful for comparing content when layout may differ. Automatically set to ``False`` when ``ignore_page_boundaries`` is ``True``.
579
579
  - ``check_block_count`` (bool, default ``True``): when ``False``, skip block count validation per page. Automatically set to ``False`` when ``ignore_page_boundaries`` is ``True``.
580
+ - ``spatial_word_sorting`` (bool, default ``False``): when ``True``, build page structure from individual word bounding boxes instead of text blocks. This bypasses block fragmentation differences caused by different PDF generators and produces consistent word ordering. Recommended when ``ignore_page_boundaries`` is ``True``.
580
581
 
581
582
  Examples:
582
583
  | `Compare Pdf Structure` reference.pdf candidate.pdf
@@ -584,6 +585,7 @@ class PdfTest(object):
584
585
  | `Compare Pdf Structure` reference.pdf candidate.pdf mask=${CURDIR}${/}mask.json text_mask_patterns=\\d{4}-\\d{4} ignore_ligatures=${True}
585
586
  | `Compare Pdf Structure` reference.pdf candidate.pdf ignore_page_boundaries=${True}
586
587
  | `Compare Pdf Structure` reference.pdf candidate.pdf check_geometry=${False} check_block_count=${False}
588
+ | `Compare Pdf Structure` reference.pdf candidate.pdf ignore_page_boundaries=${True} spatial_word_sorting=${True}
587
589
  | `Run Keyword And Expect Error` The compared PDF structure is different. Compare Pdf Structure reference.pdf candidate_with_changed_text.pdf
588
590
 
589
591
  """
@@ -623,6 +625,7 @@ class PdfTest(object):
623
625
  compare_word_level = _as_bool(kwargs.get('compare_word_level', True), True)
624
626
  check_geometry = _as_bool(kwargs.get('check_geometry', True), True)
625
627
  check_block_count = _as_bool(kwargs.get('check_block_count', True), True)
628
+ spatial_word_sorting = _as_bool(kwargs.get('spatial_word_sorting', False), False)
626
629
 
627
630
  header_scan_height = _as_float(kwargs.get('header_scan_height', 0), 0)
628
631
  footer_scan_height = _as_float(kwargs.get('footer_scan_height', 0), 0)
@@ -647,6 +650,7 @@ class PdfTest(object):
647
650
  round_precision=round_precision,
648
651
  normalize_ligatures=ignore_ligatures,
649
652
  character_replacements=char_replacements,
653
+ spatial_word_sorting=spatial_word_sorting,
650
654
  )
651
655
  tolerance = StructureTolerance(
652
656
  position=position_tolerance,
@@ -64,10 +64,12 @@ def merge_split_words(
64
64
  curr_token = tokens[i]
65
65
  prev_word = merged_words[-1]
66
66
 
67
- # Only merge if tokens are from different lines AND previous word ends with connector
67
+ # Only merge if tokens are from different lines AND previous word ends with connector.
68
+ # Skip standalone connectors (e.g. a bare "-" used as punctuation, not a split word).
68
69
  if (prev_token.source_line_index != curr_token.source_line_index
69
70
  and prev_word
70
- and prev_word[-1] in connectors):
71
+ and prev_word[-1] in connectors
72
+ and len(prev_word) > 1):
71
73
  # Merge: concatenate words, keep first token's provenance
72
74
  merged_words[-1] = prev_word + words[i]
73
75
  # Update token with merged text
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: robotframework-doctestlibrary
3
- Version: 0.32.0.dev2
3
+ Version: 0.32.0.dev3
4
4
  Summary: A library for Visual Document Testing
5
5
  Project-URL: Homepage, https://github.com/manykarim/robotframework-doctestlibrary
6
6
  Author-email: Many Kasiriha <many.kasiriha@dbschenker.com>
@@ -1,15 +1,15 @@
1
- DocTest/DocumentRepresentation.py,sha256=DU3AJl_VvN05FQpa3p8W-DUXHrn7F3lmvglq_p02QJo,58794
1
+ DocTest/DocumentRepresentation.py,sha256=6hhKETC3WcI0RSIWAGCTQx7Nms9LGoee9I0cSH0p9C0,59522
2
2
  DocTest/Downloader.py,sha256=9koiAy2izk_v92ZUMFJ9Ktaq2lq5QCHLgeohSYV4z8Y,1389
3
3
  DocTest/HeaderFooterDetector.py,sha256=tYB01648Liiyu42BtUkUE7uywtlz1KNMSUrZU4f22HM,7341
4
4
  DocTest/IgnoreAreaManager.py,sha256=Tkb7_lbVqWkon1KWOMbRXc5DdglR2VS4h9xFvwplBws,6211
5
5
  DocTest/Ocr.py,sha256=d08MlwtdMfdJ3c3_vp_rWNbXyq4Es5ixoHLrqH5j2GQ,9745
6
6
  DocTest/PdfStructureComparator.py,sha256=VYXCcUIWK2Ge0fUqCCcRKg_L2vRMn_1DyjT-ziS3cvU,24722
7
- DocTest/PdfStructureModels.py,sha256=PuscWNlgWlyL2wWoG4tdmlIiIDe0WMmH7vNU1x7GbRo,11602
8
- DocTest/PdfTest.py,sha256=8uHD6ZsN4jkWvbs6tK-aJsracq_AYv47-akjPSDARcI,63253
7
+ DocTest/PdfStructureModels.py,sha256=HQ9V3n6PXVdXXQCxp_fRGRHxqxUbqWE0wm7QMNyhHT4,17316
8
+ DocTest/PdfTest.py,sha256=JxCxjUaFmDpWTTJJ8AQpaXe8xAMogDe2DWNHsEIcKX8,63871
9
9
  DocTest/PrintJob.py,sha256=RoKII3edyd_9TqVuM7gbubdEBv--ZUpxG1ET0mOWDSo,142
10
10
  DocTest/PrintJobTests.py,sha256=Md3tZ6G0RVEFaJSQEsxl2YMDnfrpN3GkmPsabGSiWQE,18779
11
11
  DocTest/StructureReportBuilder.py,sha256=HBIDr6lP75gdJbqhPyM_AR9s-oO-p0Hi8_WjUwU425A,24242
12
- DocTest/TextNormalization.py,sha256=FYuPob05Jfy0r45w_d3PZIfcfmCb-Z3jLimREp8F1rs,4023
12
+ DocTest/TextNormalization.py,sha256=Lqi92EktPnWDQp-jeenCxOt8Xj6aBW2Qdu50_99UC6c,4157
13
13
  DocTest/VisualTest.py,sha256=B8N4tnsWbv-Df9n2Qh6QMJW_yXgjksudjo6FUmYL4ek,168465
14
14
  DocTest/__init__.py,sha256=q9xdZ1XbfBiAdI492jNW7WN3WcLHzohnNnVyAQb54-g,15700
15
15
  DocTest/config.py,sha256=jhFerJDyU0Wu4ZbNqD9U4a0a8QzdKhCJ5mMwYfVAwmk,310
@@ -23,7 +23,7 @@ DocTest/llm/config.py,sha256=TerG1LGMbF68fR5LP2tl5K4MLSpzEqe2qZ-ix3XM9yI,7368
23
23
  DocTest/llm/exceptions.py,sha256=wbRtgbEdqQR94eim98S1oqZfEpvFtcqnTHTJ044iWD0,427
24
24
  DocTest/llm/prompts.py,sha256=D--DcGvpWWxkgs_gvRLdBF5tHc-XhYOlXzQTZwlX7Z4,1585
25
25
  DocTest/llm/types.py,sha256=ZNDpovnsQtHYz2yCFjBJSy1XNTtYb6BQpURi_eANxXo,611
26
- robotframework_doctestlibrary-0.32.0.dev2.dist-info/METADATA,sha256=oz5lV0hcHQVi80P_F4-6bMmuSNSW78rF67K6bTqXTI4,22418
27
- robotframework_doctestlibrary-0.32.0.dev2.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
28
- robotframework_doctestlibrary-0.32.0.dev2.dist-info/licenses/LICENSE,sha256=JYVY8Ud4KW4U2VPHP9RPpbvCcpSlXsX2SF2D_MJ7LmU,10243
29
- robotframework_doctestlibrary-0.32.0.dev2.dist-info/RECORD,,
26
+ robotframework_doctestlibrary-0.32.0.dev3.dist-info/METADATA,sha256=JubVhFtssKLvj_bMVTE49f67AHhHdQCYM_4M9SKGmV0,22418
27
+ robotframework_doctestlibrary-0.32.0.dev3.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
28
+ robotframework_doctestlibrary-0.32.0.dev3.dist-info/licenses/LICENSE,sha256=JYVY8Ud4KW4U2VPHP9RPpbvCcpSlXsX2SF2D_MJ7LmU,10243
29
+ robotframework_doctestlibrary-0.32.0.dev3.dist-info/RECORD,,