robotframework-doctestlibrary 0.28.0__tar.gz → 0.28.2__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 (26) hide show
  1. {robotframework_doctestlibrary-0.28.0 → robotframework_doctestlibrary-0.28.2}/DocTest/DocumentRepresentation.py +4 -4
  2. {robotframework_doctestlibrary-0.28.0 → robotframework_doctestlibrary-0.28.2}/DocTest/PdfTest.py +164 -99
  3. {robotframework_doctestlibrary-0.28.0 → robotframework_doctestlibrary-0.28.2}/DocTest/VisualTest.py +3629 -3549
  4. {robotframework_doctestlibrary-0.28.0 → robotframework_doctestlibrary-0.28.2}/DocTest/llm/client.py +127 -127
  5. {robotframework_doctestlibrary-0.28.0 → robotframework_doctestlibrary-0.28.2}/PKG-INFO +1 -1
  6. {robotframework_doctestlibrary-0.28.0 → robotframework_doctestlibrary-0.28.2}/README.md +454 -454
  7. {robotframework_doctestlibrary-0.28.0 → robotframework_doctestlibrary-0.28.2}/pyproject.toml +1 -1
  8. {robotframework_doctestlibrary-0.28.0 → robotframework_doctestlibrary-0.28.2}/DocTest/Ai/__init__.py +0 -0
  9. {robotframework_doctestlibrary-0.28.0 → robotframework_doctestlibrary-0.28.2}/DocTest/Ai/prompts.py +0 -0
  10. {robotframework_doctestlibrary-0.28.0 → robotframework_doctestlibrary-0.28.2}/DocTest/Ai/renderers.py +0 -0
  11. {robotframework_doctestlibrary-0.28.0 → robotframework_doctestlibrary-0.28.2}/DocTest/Ai/responses.py +0 -0
  12. {robotframework_doctestlibrary-0.28.0 → robotframework_doctestlibrary-0.28.2}/DocTest/Downloader.py +0 -0
  13. {robotframework_doctestlibrary-0.28.0 → robotframework_doctestlibrary-0.28.2}/DocTest/IgnoreAreaManager.py +0 -0
  14. {robotframework_doctestlibrary-0.28.0 → robotframework_doctestlibrary-0.28.2}/DocTest/Ocr.py +0 -0
  15. {robotframework_doctestlibrary-0.28.0 → robotframework_doctestlibrary-0.28.2}/DocTest/PdfStructureComparator.py +0 -0
  16. {robotframework_doctestlibrary-0.28.0 → robotframework_doctestlibrary-0.28.2}/DocTest/PdfStructureModels.py +0 -0
  17. {robotframework_doctestlibrary-0.28.0 → robotframework_doctestlibrary-0.28.2}/DocTest/PrintJob.py +0 -0
  18. {robotframework_doctestlibrary-0.28.0 → robotframework_doctestlibrary-0.28.2}/DocTest/PrintJobTests.py +0 -0
  19. {robotframework_doctestlibrary-0.28.0 → robotframework_doctestlibrary-0.28.2}/DocTest/__init__.py +0 -0
  20. {robotframework_doctestlibrary-0.28.0 → robotframework_doctestlibrary-0.28.2}/DocTest/config.py +0 -0
  21. {robotframework_doctestlibrary-0.28.0 → robotframework_doctestlibrary-0.28.2}/DocTest/llm/__init__.py +0 -0
  22. {robotframework_doctestlibrary-0.28.0 → robotframework_doctestlibrary-0.28.2}/DocTest/llm/config.py +0 -0
  23. {robotframework_doctestlibrary-0.28.0 → robotframework_doctestlibrary-0.28.2}/DocTest/llm/exceptions.py +0 -0
  24. {robotframework_doctestlibrary-0.28.0 → robotframework_doctestlibrary-0.28.2}/DocTest/llm/prompts.py +0 -0
  25. {robotframework_doctestlibrary-0.28.0 → robotframework_doctestlibrary-0.28.2}/DocTest/llm/types.py +0 -0
  26. {robotframework_doctestlibrary-0.28.0 → robotframework_doctestlibrary-0.28.2}/LICENSE +0 -0
@@ -805,10 +805,10 @@ class DocumentRepresentation:
805
805
  image = cv2.imdecode(np.frombuffer(img_data, np.uint8), cv2.IMREAD_COLOR)
806
806
  page_obj = Page(image, page_number=page_num + 1, dpi=self.dpi)
807
807
  page_obj.is_pdf = True
808
- page_obj.pdf_text_data = page.get_text("text")
809
- page_obj.pdf_text_dict = page.get_text("dict")
810
- page_obj.pdf_text_words = page.get_text("words")
811
- page_obj.pdf_text_blocks = page.get_text("blocks")
808
+ page_obj.pdf_text_data = page.get_text("text", sort=True)
809
+ page_obj.pdf_text_dict = page.get_text("dict", sort=True)
810
+ page_obj.pdf_text_words = page.get_text("words", sort=True)
811
+ page_obj.pdf_text_blocks = page.get_text("blocks", sort=True)
812
812
  self.pages.append(page_obj)
813
813
  except ImportError:
814
814
  raise ImportError("PyMuPDF (fitz) is required for PDF processing.")
@@ -6,15 +6,51 @@ from robot.api.deco import keyword, library
6
6
  import fitz
7
7
  import re
8
8
  from pathlib import Path
9
- from typing import Any, Dict, List, Optional
9
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
10
10
  from DocTest.config import DEFAULT_DPI
11
11
  from DocTest.DocumentRepresentation import DocumentRepresentation
12
12
  from DocTest.Downloader import is_url, download_file_from_url
13
13
  from DocTest.PdfStructureComparator import StructureTolerance, compare_document_structures
14
14
  from DocTest.PdfStructureModels import StructureExtractionConfig
15
- from DocTest.llm import LLMDependencyError, load_llm_settings
16
- from DocTest.llm.client import assess_pdf_diff, create_binary_content
17
- from DocTest.llm.types import LLMDecision, LLMDecisionLabel
15
+ from DocTest.llm import LLMDependencyError, load_llm_settings
16
+
17
+ if TYPE_CHECKING: # pragma: no cover - typing only
18
+ from DocTest.llm.types import LLMDecision, LLMDecisionLabel
19
+ else: # pragma: no cover - runtime fallback
20
+ LLMDecision = Any # type: ignore[misc, assignment]
21
+ LLMDecisionLabel = Any # type: ignore[misc, assignment]
22
+
23
+
24
+ _PDF_LLM_RUNTIME: Optional[Tuple[Any, Any, Any]] = None
25
+
26
+
27
+ def _coerce_label_value(label: Any) -> str:
28
+ value = getattr(label, "value", label)
29
+ return str(value)
30
+
31
+
32
+ def _decision_equals_flag(label: Any, enum_cls: Any) -> bool:
33
+ candidate = _coerce_label_value(label).lower()
34
+ if enum_cls is None:
35
+ return candidate == "flag"
36
+ flag_member = getattr(enum_cls, "FLAG", None)
37
+ if flag_member is None:
38
+ return candidate == "flag"
39
+ flag_value = _coerce_label_value(flag_member).lower()
40
+ return candidate == flag_value
41
+
42
+
43
+ def _load_pdf_llm_runtime() -> Tuple[Any, Any, Any]:
44
+ global _PDF_LLM_RUNTIME
45
+ if _PDF_LLM_RUNTIME is not None:
46
+ return _PDF_LLM_RUNTIME
47
+ try:
48
+ from DocTest.llm.client import assess_pdf_diff, create_binary_content
49
+ from DocTest.llm.types import LLMDecisionLabel as _LLMDecisionLabel
50
+ except Exception as exc: # pragma: no cover - optional dependency missing
51
+ raise LLMDependencyError() from exc
52
+ _PDF_LLM_RUNTIME = (assess_pdf_diff, create_binary_content, _LLMDecisionLabel)
53
+ return _PDF_LLM_RUNTIME
18
54
 
19
55
 
20
56
  def _as_bool(value, default=False):
@@ -75,28 +111,28 @@ class PdfTest(object):
75
111
  - ``signatures``
76
112
  - ``structure`` (layout + line/geometry comparison that ignores font subset differences)
77
113
 
78
- When ``structure`` is requested the following optional kwargs control behaviour:
79
-
80
- - ``structure_position_tolerance`` (float, default ``15.0``) – max positional delta in points
81
- - ``structure_size_tolerance`` (float, default equals position tolerance) – max width/height delta in points
82
- - ``structure_relative_tolerance`` (float, default ``0.05``) – fallback percentage tolerance
83
- - ``structure_case_sensitive`` (bool, default ``True``) – toggle case-sensitive text matching
84
- - ``structure_strip_font_subset`` (bool, default ``True``) – drop font subset prefixes
85
- - ``structure_collapse_whitespace`` (bool, default ``True``)
86
- - ``structure_strip_line_edges`` (bool, default ``True``)
87
- - ``structure_drop_empty_lines`` (bool, default ``True``)
88
- - ``structure_whitespace_replacement`` (str, default single space)
89
- - ``structure_round_precision`` (int or ``None``, default ``3``) – rounding precision for coordinates
90
- - ``structure_dpi`` (int, default: library DPI) – DPI used when rasterising PDFs prior to structure extraction
91
-
92
- Optional LLM integration parameters:
93
-
94
- | =Arguments= | =Description= |
95
- | ``llm`` / ``llm_enabled`` | When ``${True}``, forward detected differences to the configured LLM. Default ``${False}``. |
96
- | ``llm_override`` | Allow an approving LLM verdict to override baseline comparison failures. Default ``${False}``. |
97
- | ``llm_prompt`` / ``llm_pdf_prompt`` | Custom prompt for this comparison. Default ``None`` uses the built-in prompt. |
98
-
99
- Result passes only if every requested facet matches.
114
+ When ``structure`` is requested the following optional kwargs control behaviour:
115
+
116
+ - ``structure_position_tolerance`` (float, default ``15.0``) – max positional delta in points
117
+ - ``structure_size_tolerance`` (float, default equals position tolerance) – max width/height delta in points
118
+ - ``structure_relative_tolerance`` (float, default ``0.05``) – fallback percentage tolerance
119
+ - ``structure_case_sensitive`` (bool, default ``True``) – toggle case-sensitive text matching
120
+ - ``structure_strip_font_subset`` (bool, default ``True``) – drop font subset prefixes
121
+ - ``structure_collapse_whitespace`` (bool, default ``True``)
122
+ - ``structure_strip_line_edges`` (bool, default ``True``)
123
+ - ``structure_drop_empty_lines`` (bool, default ``True``)
124
+ - ``structure_whitespace_replacement`` (str, default single space)
125
+ - ``structure_round_precision`` (int or ``None``, default ``3``) – rounding precision for coordinates
126
+ - ``structure_dpi`` (int, default: library DPI) – DPI used when rasterising PDFs prior to structure extraction
127
+
128
+ Optional LLM integration parameters:
129
+
130
+ | =Arguments= | =Description= |
131
+ | ``llm`` / ``llm_enabled`` | When ``${True}``, forward detected differences to the configured LLM. Default ``${False}``. |
132
+ | ``llm_override`` | Allow an approving LLM verdict to override baseline comparison failures. Default ``${False}``. |
133
+ | ``llm_prompt`` / ``llm_pdf_prompt`` | Custom prompt for this comparison. Default ``None`` uses the built-in prompt. |
134
+
135
+ Result passes only if every requested facet matches.
100
136
 
101
137
  Examples:
102
138
  | `Compare Pdf Documents` reference.pdf candidate.pdf
@@ -344,30 +380,42 @@ class PdfTest(object):
344
380
  }
345
381
  )
346
382
 
347
- if differences_detected and llm_requested:
348
- llm_general_notes.append(f"mask_applied={'yes' if mask else 'no'}")
349
- decision = self._handle_llm_for_pdf_differences(
350
- reference_document=reference_document,
351
- candidate_document=candidate_document,
352
- differences=llm_differences,
353
- overrides=llm_overrides,
354
- notes=llm_general_notes,
355
- custom_prompt=custom_llm_prompt,
356
- )
357
- if decision:
358
- print(
359
- f"LLM decision: {decision.decision.value} "
360
- f"(confidence={decision.confidence!r}) - {decision.reason}"
361
- )
362
- if decision.notes:
363
- print(f"LLM notes: {decision.notes}")
364
- if llm_override_result and decision.is_positive:
365
- print("LLM approved PDF differences. Overriding baseline failure.")
366
- differences_detected = False
367
- elif decision.decision == LLMDecisionLabel.FLAG:
368
- print("LLM returned FLAG - keeping original PDF comparison result.")
369
- elif not decision.is_positive and llm_override_result:
370
- print("LLM rejected PDF differences. Baseline failure will stand.")
383
+ llm_decision = None
384
+ llm_label_enum = None
385
+ if differences_detected and llm_requested:
386
+ llm_general_notes.append(f"mask_applied={'yes' if mask else 'no'}")
387
+ try:
388
+ assess_pdf_diff_fn, create_binary_content_fn, llm_label_enum = (
389
+ _load_pdf_llm_runtime()
390
+ )
391
+ except LLMDependencyError as exc:
392
+ print(str(exc))
393
+ else:
394
+ llm_decision = self._handle_llm_for_pdf_differences(
395
+ reference_document=reference_document,
396
+ candidate_document=candidate_document,
397
+ differences=llm_differences,
398
+ overrides=llm_overrides,
399
+ notes=llm_general_notes,
400
+ custom_prompt=custom_llm_prompt,
401
+ create_binary_content_fn=create_binary_content_fn,
402
+ assess_pdf_diff_fn=assess_pdf_diff_fn,
403
+ )
404
+ if llm_decision:
405
+ decision_value = _coerce_label_value(llm_decision.decision)
406
+ print(
407
+ f"LLM decision: {decision_value} "
408
+ f"(confidence={llm_decision.confidence!r}) - {llm_decision.reason}"
409
+ )
410
+ if llm_decision.notes:
411
+ print(f"LLM notes: {llm_decision.notes}")
412
+ if llm_override_result and llm_decision.is_positive:
413
+ print("LLM approved PDF differences. Overriding baseline failure.")
414
+ differences_detected = False
415
+ elif _decision_equals_flag(llm_decision.decision, llm_label_enum):
416
+ print("LLM returned FLAG - keeping original PDF comparison result.")
417
+ elif not llm_decision.is_positive and llm_override_result:
418
+ print("LLM rejected PDF differences. Baseline failure will stand.")
371
419
 
372
420
  if differences_detected:
373
421
  ref_doc = None
@@ -568,17 +616,17 @@ class PdfTest(object):
568
616
  print(f"Missing Texts:\n{missing_text_list}")
569
617
 
570
618
  @keyword
571
- def compare_pdf_documents_with_llm(self, *args, llm_override: bool = False, **kwargs):
572
- """Compare PDF files and consult the configured LLM before failing.
573
-
574
- | =Arguments= | =Description= |
575
- | ``*args`` | Positional arguments forwarded to ``Compare Pdf Documents`` (reference and candidate). |
576
- | ``llm_override`` | When ``${True}``, allow an approving LLM verdict to override baseline failures. Default ``${False}``. |
577
- | ``**kwargs`` | Keyword arguments forwarded to ``Compare Pdf Documents``. ``llm_prompt`` / ``llm_pdf_prompt`` may be used to customise the LLM prompt. |
578
-
579
- Example:
580
- | `Compare Pdf Documents With LLM` reference.pdf candidate.pdf compare=text llm_override=${True}
581
- """
619
+ def compare_pdf_documents_with_llm(self, *args, llm_override: bool = False, **kwargs):
620
+ """Compare PDF files and consult the configured LLM before failing.
621
+
622
+ | =Arguments= | =Description= |
623
+ | ``*args`` | Positional arguments forwarded to ``Compare Pdf Documents`` (reference and candidate). |
624
+ | ``llm_override`` | When ``${True}``, allow an approving LLM verdict to override baseline failures. Default ``${False}``. |
625
+ | ``**kwargs`` | Keyword arguments forwarded to ``Compare Pdf Documents``. ``llm_prompt`` / ``llm_pdf_prompt`` may be used to customise the LLM prompt. |
626
+
627
+ Example:
628
+ | `Compare Pdf Documents With LLM` reference.pdf candidate.pdf compare=text llm_override=${True}
629
+ """
582
630
  kwargs["llm_enabled"] = kwargs.get("llm_enabled", True)
583
631
  if "llm_override" not in kwargs:
584
632
  kwargs["llm_override"] = llm_override
@@ -632,18 +680,20 @@ class PdfTest(object):
632
680
  def _ensure_local_document(self, document):
633
681
  return download_file_from_url(document) if is_url(document) else document
634
682
 
635
- def _handle_llm_for_pdf_differences(
636
- self,
637
- reference_document: str,
638
- candidate_document: str,
639
- differences: List[Dict[str, Any]],
640
- overrides: Dict[str, Optional[str]],
641
- notes: List[str],
642
- custom_prompt: Optional[str],
643
- ) -> Optional[LLMDecision]:
644
- overrides = {key: (str(value) if value is not None else None) for key, value in overrides.items()}
645
- overrides.setdefault("llm_enabled", "true")
646
- overrides.setdefault("llm_pdf_enabled", "true")
683
+ def _handle_llm_for_pdf_differences(
684
+ self,
685
+ reference_document: str,
686
+ candidate_document: str,
687
+ differences: List[Dict[str, Any]],
688
+ overrides: Dict[str, Optional[str]],
689
+ notes: List[str],
690
+ custom_prompt: Optional[str],
691
+ create_binary_content_fn: Optional[Any] = None,
692
+ assess_pdf_diff_fn: Optional[Any] = None,
693
+ ) -> Optional[LLMDecision]:
694
+ overrides = {key: (str(value) if value is not None else None) for key, value in overrides.items()}
695
+ overrides.setdefault("llm_enabled", "true")
696
+ overrides.setdefault("llm_pdf_enabled", "true")
647
697
 
648
698
  try:
649
699
  settings = load_llm_settings(overrides)
@@ -651,29 +701,44 @@ class PdfTest(object):
651
701
  logger.warn(f"Failed to load LLM settings: {exc}")
652
702
  return None
653
703
 
654
- if not settings.pdf_enabled:
655
- print("LLM PDF evaluation requested but disabled via settings.")
656
- return None
657
-
658
- summary_lines = [
659
- f"Reference document: {reference_document}",
660
- f"Candidate document: {candidate_document}",
661
- ]
662
- attachments = []
663
- try:
664
- reference_bytes = Path(reference_document).read_bytes()
665
- attachments.append(create_binary_content(reference_bytes, "application/pdf"))
704
+ if not settings.pdf_enabled:
705
+ print("LLM PDF evaluation requested but disabled via settings.")
706
+ return None
707
+
708
+ if create_binary_content_fn is None or assess_pdf_diff_fn is None:
709
+ try:
710
+ default_assess, default_create, _ = _load_pdf_llm_runtime()
711
+ except LLMDependencyError as exc:
712
+ print(str(exc))
713
+ return None
714
+ if assess_pdf_diff_fn is None:
715
+ assess_pdf_diff_fn = default_assess
716
+ if create_binary_content_fn is None:
717
+ create_binary_content_fn = default_create
718
+
719
+ summary_lines = [
720
+ f"Reference document: {reference_document}",
721
+ f"Candidate document: {candidate_document}",
722
+ ]
723
+ attachments = []
724
+ try:
725
+ reference_bytes = Path(reference_document).read_bytes()
726
+ attachments.append(
727
+ create_binary_content_fn(reference_bytes, "application/pdf")
728
+ )
666
729
  except FileNotFoundError:
667
730
  logger.warn("Reference document not found for LLM attachment: %s", reference_document)
668
731
  except LLMDependencyError as exc:
669
732
  print(str(exc))
670
733
  return None
671
734
  except Exception as exc: # pragma: no cover - defensive
672
- logger.warn("Failed to attach reference document for LLM: %s", exc)
673
-
674
- try:
675
- candidate_bytes = Path(candidate_document).read_bytes()
676
- attachments.append(create_binary_content(candidate_bytes, "application/pdf"))
735
+ logger.warn("Failed to attach reference document for LLM: %s", exc)
736
+
737
+ try:
738
+ candidate_bytes = Path(candidate_document).read_bytes()
739
+ attachments.append(
740
+ create_binary_content_fn(candidate_bytes, "application/pdf")
741
+ )
677
742
  except FileNotFoundError:
678
743
  logger.warn("Candidate document not found for LLM attachment: %s", candidate_document)
679
744
  except LLMDependencyError as exc:
@@ -693,15 +758,15 @@ class PdfTest(object):
693
758
  detail_text = f"{detail_text[:2000]} ... (truncated)"
694
759
  summary_lines.append(detail_text)
695
760
 
696
- extra_messages = list(notes or [])
697
-
698
- try:
699
- decision = assess_pdf_diff(
700
- settings=settings,
701
- textual_summary="\n".join(summary_lines),
702
- attachments=tuple(attachments),
703
- extra_messages=extra_messages,
704
- system_prompt=custom_prompt,
761
+ extra_messages = list(notes or [])
762
+
763
+ try:
764
+ decision = assess_pdf_diff_fn(
765
+ settings=settings,
766
+ textual_summary="\n".join(summary_lines),
767
+ attachments=tuple(attachments),
768
+ extra_messages=extra_messages,
769
+ system_prompt=custom_prompt,
705
770
  )
706
771
  except LLMDependencyError as exc:
707
772
  print(str(exc))