robotframework-doctestlibrary 0.32.0.dev2__tar.gz → 0.33.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.
- robotframework_doctestlibrary-0.33.0/DocTest/CapabilityCheck.py +271 -0
- {robotframework_doctestlibrary-0.32.0.dev2 → robotframework_doctestlibrary-0.33.0}/DocTest/DocumentRepresentation.py +20 -18
- robotframework_doctestlibrary-0.33.0/DocTest/Downloader.py +167 -0
- robotframework_doctestlibrary-0.33.0/DocTest/IgnoreAreaManager.py +84 -0
- {robotframework_doctestlibrary-0.32.0.dev2 → robotframework_doctestlibrary-0.33.0}/DocTest/Ocr.py +6 -3
- {robotframework_doctestlibrary-0.32.0.dev2 → robotframework_doctestlibrary-0.33.0}/DocTest/PdfStructureComparator.py +3 -229
- {robotframework_doctestlibrary-0.32.0.dev2 → robotframework_doctestlibrary-0.33.0}/DocTest/PdfStructureModels.py +0 -82
- {robotframework_doctestlibrary-0.32.0.dev2 → robotframework_doctestlibrary-0.33.0}/DocTest/PdfTest.py +76 -208
- {robotframework_doctestlibrary-0.32.0.dev2 → robotframework_doctestlibrary-0.33.0}/DocTest/PrintJobTests.py +25 -31
- robotframework_doctestlibrary-0.33.0/DocTest/TextNormalization.py +54 -0
- {robotframework_doctestlibrary-0.32.0.dev2 → robotframework_doctestlibrary-0.33.0}/DocTest/VisualTest.py +151 -105
- {robotframework_doctestlibrary-0.32.0.dev2 → robotframework_doctestlibrary-0.33.0}/PKG-INFO +39 -23
- robotframework_doctestlibrary-0.33.0/pyproject.toml +68 -0
- robotframework_doctestlibrary-0.32.0.dev2/.gitignore +0 -82
- robotframework_doctestlibrary-0.32.0.dev2/DocTest/Downloader.py +0 -47
- robotframework_doctestlibrary-0.32.0.dev2/DocTest/HeaderFooterDetector.py +0 -230
- robotframework_doctestlibrary-0.32.0.dev2/DocTest/IgnoreAreaManager.py +0 -129
- robotframework_doctestlibrary-0.32.0.dev2/DocTest/StructureReportBuilder.py +0 -558
- robotframework_doctestlibrary-0.32.0.dev2/DocTest/TextNormalization.py +0 -117
- robotframework_doctestlibrary-0.32.0.dev2/pyproject.toml +0 -61
- {robotframework_doctestlibrary-0.32.0.dev2 → robotframework_doctestlibrary-0.33.0}/DocTest/Ai/__init__.py +0 -0
- {robotframework_doctestlibrary-0.32.0.dev2 → robotframework_doctestlibrary-0.33.0}/DocTest/Ai/prompts.py +0 -0
- {robotframework_doctestlibrary-0.32.0.dev2 → robotframework_doctestlibrary-0.33.0}/DocTest/Ai/renderers.py +0 -0
- {robotframework_doctestlibrary-0.32.0.dev2 → robotframework_doctestlibrary-0.33.0}/DocTest/Ai/responses.py +0 -0
- {robotframework_doctestlibrary-0.32.0.dev2 → robotframework_doctestlibrary-0.33.0}/DocTest/PrintJob.py +0 -0
- {robotframework_doctestlibrary-0.32.0.dev2 → robotframework_doctestlibrary-0.33.0}/DocTest/__init__.py +0 -0
- {robotframework_doctestlibrary-0.32.0.dev2 → robotframework_doctestlibrary-0.33.0}/DocTest/config.py +0 -0
- {robotframework_doctestlibrary-0.32.0.dev2 → robotframework_doctestlibrary-0.33.0}/DocTest/llm/__init__.py +0 -0
- {robotframework_doctestlibrary-0.32.0.dev2 → robotframework_doctestlibrary-0.33.0}/DocTest/llm/client.py +0 -0
- {robotframework_doctestlibrary-0.32.0.dev2 → robotframework_doctestlibrary-0.33.0}/DocTest/llm/config.py +0 -0
- {robotframework_doctestlibrary-0.32.0.dev2 → robotframework_doctestlibrary-0.33.0}/DocTest/llm/exceptions.py +0 -0
- {robotframework_doctestlibrary-0.32.0.dev2 → robotframework_doctestlibrary-0.33.0}/DocTest/llm/prompts.py +0 -0
- {robotframework_doctestlibrary-0.32.0.dev2 → robotframework_doctestlibrary-0.33.0}/DocTest/llm/types.py +0 -0
- {robotframework_doctestlibrary-0.32.0.dev2 → robotframework_doctestlibrary-0.33.0}/LICENSE +0 -0
- {robotframework_doctestlibrary-0.32.0.dev2 → robotframework_doctestlibrary-0.33.0}/README.md +0 -0
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
"""Preflight capability checker for DocTest library.
|
|
2
|
+
|
|
3
|
+
Detects whether optional external binaries (Tesseract, Ghostscript, GhostPCL,
|
|
4
|
+
ImageMagick) and Python packages (PyMuPDF, pyzbar, openai) are available before
|
|
5
|
+
tests run. This avoids cryptic runtime errors when a dependency is missing.
|
|
6
|
+
|
|
7
|
+
Usage from Robot Framework::
|
|
8
|
+
|
|
9
|
+
Library DocTest.CapabilityCheck
|
|
10
|
+
|
|
11
|
+
*** Test Cases ***
|
|
12
|
+
Verify Environment
|
|
13
|
+
${caps}= Check DocTest Environment
|
|
14
|
+
Log ${caps}
|
|
15
|
+
|
|
16
|
+
Usage from Python::
|
|
17
|
+
|
|
18
|
+
from DocTest.CapabilityCheck import check_all_capabilities, format_capability_report
|
|
19
|
+
caps = check_all_capabilities()
|
|
20
|
+
print(format_capability_report(caps))
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
import importlib
|
|
24
|
+
import logging
|
|
25
|
+
import shutil
|
|
26
|
+
import subprocess
|
|
27
|
+
from typing import Dict, List, Optional
|
|
28
|
+
|
|
29
|
+
from robot.api.deco import keyword, library
|
|
30
|
+
|
|
31
|
+
logger = logging.getLogger(__name__)
|
|
32
|
+
|
|
33
|
+
# ---------------------------------------------------------------------------
|
|
34
|
+
# Capability registry
|
|
35
|
+
# ---------------------------------------------------------------------------
|
|
36
|
+
|
|
37
|
+
CAPABILITY_REGISTRY: Dict[str, Dict[str, str]] = {
|
|
38
|
+
"tesseract": {
|
|
39
|
+
"binary": "tesseract",
|
|
40
|
+
"feature": "OCR text extraction",
|
|
41
|
+
"install_hint": "apt install tesseract-ocr (Linux) / brew install tesseract (macOS)",
|
|
42
|
+
},
|
|
43
|
+
"ghostscript": {
|
|
44
|
+
"binary": "gs",
|
|
45
|
+
"fallback_binaries": "gswin64c,gswin32c,ghostscript",
|
|
46
|
+
"feature": "PDF/PostScript rendering",
|
|
47
|
+
"install_hint": "apt install ghostscript (Linux) / brew install ghostscript (macOS)",
|
|
48
|
+
},
|
|
49
|
+
"ghostpcl": {
|
|
50
|
+
"binary": "pcl6",
|
|
51
|
+
"fallback_binaries": "gpcl6win64,gpcl6win32,gpcl6",
|
|
52
|
+
"feature": "PCL document rendering",
|
|
53
|
+
"install_hint": (
|
|
54
|
+
"Install GhostPCL from https://ghostscript.com/releases/gpcldnld.html"
|
|
55
|
+
),
|
|
56
|
+
},
|
|
57
|
+
"imagemagick": {
|
|
58
|
+
"binary": "magick",
|
|
59
|
+
"fallback_binaries": "convert",
|
|
60
|
+
"feature": "Image format conversion",
|
|
61
|
+
"install_hint": (
|
|
62
|
+
"apt install imagemagick (Linux) / brew install imagemagick (macOS)"
|
|
63
|
+
),
|
|
64
|
+
},
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
PYTHON_PACKAGE_REGISTRY: Dict[str, Dict[str, str]] = {
|
|
68
|
+
"pymupdf": {
|
|
69
|
+
"import_name": "fitz",
|
|
70
|
+
"feature": "PDF rendering and text extraction",
|
|
71
|
+
"install_hint": "pip install PyMuPDF",
|
|
72
|
+
},
|
|
73
|
+
"pyzbar": {
|
|
74
|
+
"import_name": "pyzbar",
|
|
75
|
+
"feature": "Barcode detection and decoding",
|
|
76
|
+
"install_hint": "pip install pyzbar",
|
|
77
|
+
},
|
|
78
|
+
"openai": {
|
|
79
|
+
"import_name": "openai",
|
|
80
|
+
"feature": "LLM-assisted image comparison",
|
|
81
|
+
"install_hint": 'pip install "robotframework-doctestlibrary[ai]"',
|
|
82
|
+
},
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
# ---------------------------------------------------------------------------
|
|
86
|
+
# Helper functions
|
|
87
|
+
# ---------------------------------------------------------------------------
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def check_binary(name: str) -> Optional[str]:
|
|
91
|
+
"""Return the absolute path of *name* if it is on ``$PATH``, else ``None``.
|
|
92
|
+
|
|
93
|
+
Uses :func:`shutil.which` internally.
|
|
94
|
+
"""
|
|
95
|
+
try:
|
|
96
|
+
return shutil.which(name)
|
|
97
|
+
except Exception:
|
|
98
|
+
return None
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def check_python_package(name: str) -> bool:
|
|
102
|
+
"""Return ``True`` if the Python package *name* can be imported."""
|
|
103
|
+
try:
|
|
104
|
+
importlib.import_module(name)
|
|
105
|
+
return True
|
|
106
|
+
except Exception:
|
|
107
|
+
return False
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _get_version(binary_path: str) -> Optional[str]:
|
|
111
|
+
"""Try to obtain a version string from *binary_path*.
|
|
112
|
+
|
|
113
|
+
Attempts ``--version`` first, then ``-version``. Returns ``None`` on
|
|
114
|
+
any failure so the caller can proceed without version info.
|
|
115
|
+
"""
|
|
116
|
+
for flag in ("--version", "-version"):
|
|
117
|
+
try:
|
|
118
|
+
result = subprocess.run(
|
|
119
|
+
[binary_path, flag],
|
|
120
|
+
capture_output=True,
|
|
121
|
+
text=True,
|
|
122
|
+
timeout=5,
|
|
123
|
+
)
|
|
124
|
+
output = (result.stdout or result.stderr or "").strip()
|
|
125
|
+
if output:
|
|
126
|
+
# Return the first non-empty line.
|
|
127
|
+
return output.splitlines()[0]
|
|
128
|
+
except Exception:
|
|
129
|
+
continue
|
|
130
|
+
return None
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def check_all_capabilities() -> Dict[str, Dict]:
|
|
134
|
+
"""Check every registered capability and return a structured report.
|
|
135
|
+
|
|
136
|
+
Returns a ``dict`` keyed by capability name. Each value is a ``dict``
|
|
137
|
+
containing at least ``"available"`` (bool) and ``"feature"`` (str).
|
|
138
|
+
"""
|
|
139
|
+
results: Dict[str, Dict] = {}
|
|
140
|
+
|
|
141
|
+
# -- Binary capabilities --
|
|
142
|
+
for name, info in CAPABILITY_REGISTRY.items():
|
|
143
|
+
entry: Dict = {
|
|
144
|
+
"available": False,
|
|
145
|
+
"feature": info["feature"],
|
|
146
|
+
"path": None,
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
# Try the primary binary first, then any fallbacks.
|
|
150
|
+
binaries_to_try: List[str] = [info["binary"]]
|
|
151
|
+
fallback_str = info.get("fallback_binaries", "")
|
|
152
|
+
if fallback_str:
|
|
153
|
+
binaries_to_try.extend(
|
|
154
|
+
b.strip() for b in fallback_str.split(",") if b.strip()
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
used_fallback = False
|
|
158
|
+
for idx, binary_name in enumerate(binaries_to_try):
|
|
159
|
+
path = check_binary(binary_name)
|
|
160
|
+
if path is not None:
|
|
161
|
+
entry["available"] = True
|
|
162
|
+
entry["path"] = path
|
|
163
|
+
version = _get_version(path)
|
|
164
|
+
if version:
|
|
165
|
+
entry["version"] = version
|
|
166
|
+
if idx > 0:
|
|
167
|
+
used_fallback = True
|
|
168
|
+
entry["note"] = f"Using fallback '{binary_name}' command"
|
|
169
|
+
break
|
|
170
|
+
|
|
171
|
+
if not entry["available"]:
|
|
172
|
+
entry["install_hint"] = info["install_hint"]
|
|
173
|
+
|
|
174
|
+
results[name] = entry
|
|
175
|
+
|
|
176
|
+
# -- Python package capabilities --
|
|
177
|
+
for name, info in PYTHON_PACKAGE_REGISTRY.items():
|
|
178
|
+
import_name = info["import_name"]
|
|
179
|
+
available = check_python_package(import_name)
|
|
180
|
+
entry = {
|
|
181
|
+
"available": available,
|
|
182
|
+
"feature": info["feature"],
|
|
183
|
+
"package": import_name,
|
|
184
|
+
}
|
|
185
|
+
if not available:
|
|
186
|
+
entry["install_hint"] = info["install_hint"]
|
|
187
|
+
results[name] = entry
|
|
188
|
+
|
|
189
|
+
return results
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def format_capability_report(capabilities: Dict[str, Dict]) -> str:
|
|
193
|
+
"""Format *capabilities* into a human-readable report string."""
|
|
194
|
+
lines: List[str] = []
|
|
195
|
+
lines.append("DocTest Environment Capability Report")
|
|
196
|
+
lines.append("=" * 42)
|
|
197
|
+
|
|
198
|
+
available_items: List[str] = []
|
|
199
|
+
missing_items: List[str] = []
|
|
200
|
+
|
|
201
|
+
for name, info in capabilities.items():
|
|
202
|
+
status = "OK" if info["available"] else "MISSING"
|
|
203
|
+
feature = info.get("feature", "")
|
|
204
|
+
line = f" [{status:>7}] {name:<15} - {feature}"
|
|
205
|
+
if info["available"]:
|
|
206
|
+
path = info.get("path")
|
|
207
|
+
version = info.get("version")
|
|
208
|
+
note = info.get("note")
|
|
209
|
+
details: List[str] = []
|
|
210
|
+
if path:
|
|
211
|
+
details.append(f"path: {path}")
|
|
212
|
+
if version:
|
|
213
|
+
details.append(f"version: {version}")
|
|
214
|
+
if note:
|
|
215
|
+
details.append(note)
|
|
216
|
+
if details:
|
|
217
|
+
line += f" ({', '.join(details)})"
|
|
218
|
+
available_items.append(line)
|
|
219
|
+
else:
|
|
220
|
+
hint = info.get("install_hint", "")
|
|
221
|
+
if hint:
|
|
222
|
+
line += f"\n{'':>28}Install: {hint}"
|
|
223
|
+
missing_items.append(line)
|
|
224
|
+
|
|
225
|
+
if available_items:
|
|
226
|
+
lines.append("")
|
|
227
|
+
lines.append("Available:")
|
|
228
|
+
lines.extend(available_items)
|
|
229
|
+
|
|
230
|
+
if missing_items:
|
|
231
|
+
lines.append("")
|
|
232
|
+
lines.append("Missing:")
|
|
233
|
+
lines.extend(missing_items)
|
|
234
|
+
|
|
235
|
+
lines.append("")
|
|
236
|
+
total = len(capabilities)
|
|
237
|
+
ok_count = sum(1 for v in capabilities.values() if v["available"])
|
|
238
|
+
lines.append(f"Summary: {ok_count}/{total} capabilities available")
|
|
239
|
+
return "\n".join(lines)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
# ---------------------------------------------------------------------------
|
|
243
|
+
# Robot Framework library
|
|
244
|
+
# ---------------------------------------------------------------------------
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
@library(scope="GLOBAL")
|
|
248
|
+
class CapabilityCheck:
|
|
249
|
+
"""Preflight capability checker for the DocTest library.
|
|
250
|
+
|
|
251
|
+
Provides a keyword to detect whether optional external binaries and
|
|
252
|
+
Python packages required by various DocTest features are installed.
|
|
253
|
+
"""
|
|
254
|
+
|
|
255
|
+
ROBOT_LIBRARY_VERSION = "1.0"
|
|
256
|
+
|
|
257
|
+
@keyword("Check DocTest Environment")
|
|
258
|
+
def check_doctest_environment(self) -> Dict[str, Dict]:
|
|
259
|
+
"""Check and report available capabilities for DocTest library.
|
|
260
|
+
|
|
261
|
+
Returns a structured ``dict`` keyed by capability name and logs a
|
|
262
|
+
human-readable report.
|
|
263
|
+
|
|
264
|
+
Example:
|
|
265
|
+
| ${caps}= | Check DocTest Environment |
|
|
266
|
+
| Log | ${caps} |
|
|
267
|
+
"""
|
|
268
|
+
capabilities = check_all_capabilities()
|
|
269
|
+
report = format_capability_report(capabilities)
|
|
270
|
+
logger.info(report)
|
|
271
|
+
return capabilities
|
|
@@ -21,6 +21,8 @@ from DocTest.PdfStructureModels import (
|
|
|
21
21
|
from DocTest.config import DEFAULT_DPI, OCR_ENGINE_DEFAULT, DEFAULT_CONFIDENCE, MINIMUM_OCR_RESOLUTION, ADD_PIXELS_TO_IGNORE_AREA, TESSERACT_CONFIG
|
|
22
22
|
import tempfile
|
|
23
23
|
|
|
24
|
+
logger = logging.getLogger(__name__)
|
|
25
|
+
|
|
24
26
|
# Constants
|
|
25
27
|
|
|
26
28
|
|
|
@@ -569,7 +571,7 @@ class Page:
|
|
|
569
571
|
def identify_barcodes_with_zbar(self):
|
|
570
572
|
try:
|
|
571
573
|
from pyzbar import pyzbar
|
|
572
|
-
except:
|
|
574
|
+
except ImportError:
|
|
573
575
|
logging.debug('Failed to import pyzbar', exc_info=True)
|
|
574
576
|
return
|
|
575
577
|
image_height = self.image.shape[0]
|
|
@@ -592,19 +594,19 @@ class Page:
|
|
|
592
594
|
def identify_datamatrices(self):
|
|
593
595
|
try:
|
|
594
596
|
from pylibdmtx import pylibdmtx
|
|
595
|
-
except:
|
|
597
|
+
except ImportError:
|
|
596
598
|
logging.debug('Failed to import pylibdmtx', exc_info=True)
|
|
597
599
|
return
|
|
598
600
|
logging.debug("Identify datamatrices")
|
|
599
601
|
image_height = self.image.shape[0]
|
|
600
602
|
try:
|
|
601
603
|
barcodes = pylibdmtx.decode(self.image, timeout=5000)
|
|
602
|
-
except:
|
|
604
|
+
except Exception:
|
|
603
605
|
logging.debug("pylibdmtx could not be loaded",exc_info=True)
|
|
604
606
|
return
|
|
605
607
|
#Add barcode as placehoder
|
|
606
608
|
for barcode in barcodes:
|
|
607
|
-
|
|
609
|
+
logger.debug("Detected barcode: %s", barcode)
|
|
608
610
|
x = barcode.rect.left
|
|
609
611
|
y = image_height - barcode.rect.top - barcode.rect.height
|
|
610
612
|
h = barcode.rect.height
|
|
@@ -614,7 +616,7 @@ class Page:
|
|
|
614
616
|
w += 1
|
|
615
617
|
value = barcode.data.decode("utf-8")
|
|
616
618
|
self.barcodes.append({"x":x, "y":y, "height":h, "width":w, "value":value})
|
|
617
|
-
self.pixel_ignore_areas.append({"x": x, "y
|
|
619
|
+
self.pixel_ignore_areas.append({"x": x, "y": y, "height": h, "width": w})
|
|
618
620
|
|
|
619
621
|
def _process_ignore_area(self, ignore_area: Dict):
|
|
620
622
|
"""Process each ignore area based on its type and convert it into pixel-based coordinates."""
|
|
@@ -771,7 +773,7 @@ class Page:
|
|
|
771
773
|
|
|
772
774
|
try:
|
|
773
775
|
unit = area.get('unit', 'px')
|
|
774
|
-
except:
|
|
776
|
+
except (AttributeError, TypeError):
|
|
775
777
|
unit = 'px'
|
|
776
778
|
area_x, area_y, area_w, area_h = self._convert_to_pixels(area, unit)
|
|
777
779
|
|
|
@@ -1053,7 +1055,7 @@ class DocumentRepresentation:
|
|
|
1053
1055
|
def __del__(self): # pragma: no cover - defensive cleanup
|
|
1054
1056
|
try:
|
|
1055
1057
|
self.close()
|
|
1056
|
-
except Exception:
|
|
1058
|
+
except Exception: # defensive: destructor must never raise
|
|
1057
1059
|
pass
|
|
1058
1060
|
|
|
1059
1061
|
def _load_pcl(self):
|
|
@@ -1066,7 +1068,7 @@ class DocumentRepresentation:
|
|
|
1066
1068
|
import subprocess
|
|
1067
1069
|
try:
|
|
1068
1070
|
command = shutil.which('pcl6') or shutil.which('gpcl6win64') or shutil.which('gpcl6win32') or shutil.which('gpcl6')
|
|
1069
|
-
except
|
|
1071
|
+
except (OSError, TypeError):
|
|
1070
1072
|
command = None
|
|
1071
1073
|
if not command:
|
|
1072
1074
|
raise AssertionError("No pcl6 executable found in path. Please install ghostPCL")
|
|
@@ -1095,12 +1097,12 @@ class DocumentRepresentation:
|
|
|
1095
1097
|
]
|
|
1096
1098
|
subprocess.run(args, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
|
|
1097
1099
|
toc = time.perf_counter()
|
|
1098
|
-
|
|
1100
|
+
logger.info("Rendering pcl document to Image with ghostPCL performed in %.4f seconds", toc - tic)
|
|
1099
1101
|
tic = time.perf_counter()
|
|
1100
1102
|
file_num =len(os.listdir(output_image_directory))
|
|
1101
1103
|
for index in range(file_num):
|
|
1102
1104
|
if (index == 0 or index == int(file_num-1)) and self.ignore_printfactory_envelope is True:
|
|
1103
|
-
|
|
1105
|
+
logger.info("The printfactory envelope is ignored in page %s", index+1)
|
|
1104
1106
|
continue
|
|
1105
1107
|
else:
|
|
1106
1108
|
filename = 'output-' + str(index+1)+'.png'
|
|
@@ -1115,8 +1117,8 @@ class DocumentRepresentation:
|
|
|
1115
1117
|
self.pages.append(page)
|
|
1116
1118
|
|
|
1117
1119
|
toc = time.perf_counter()
|
|
1118
|
-
|
|
1119
|
-
shutil.rmtree(output_image_directory)
|
|
1120
|
+
logger.info("Conversion from Image to OpenCV Image performed in %.4f seconds", toc - tic)
|
|
1121
|
+
shutil.rmtree(output_image_directory)
|
|
1120
1122
|
|
|
1121
1123
|
def _load_ps(self):
|
|
1122
1124
|
import subprocess
|
|
@@ -1127,7 +1129,7 @@ class DocumentRepresentation:
|
|
|
1127
1129
|
from os.path import splitext, split
|
|
1128
1130
|
try:
|
|
1129
1131
|
command = shutil.which('gs') or shutil.which('gswin64c') or shutil.which('gswin32c') or shutil.which('ghostscript')
|
|
1130
|
-
except
|
|
1132
|
+
except (OSError, TypeError):
|
|
1131
1133
|
command = None
|
|
1132
1134
|
if not command:
|
|
1133
1135
|
raise AssertionError("No ghostscript executable found in path. Please install ghostscript")
|
|
@@ -1156,7 +1158,7 @@ class DocumentRepresentation:
|
|
|
1156
1158
|
]
|
|
1157
1159
|
subprocess.run(args, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
|
|
1158
1160
|
toc = time.perf_counter()
|
|
1159
|
-
|
|
1161
|
+
logger.info("Rendering ps document to Image with ghostscript performed in %.4f seconds", toc - tic)
|
|
1160
1162
|
tic = time.perf_counter()
|
|
1161
1163
|
file_num =len(os.listdir(output_image_directory))
|
|
1162
1164
|
for index in range(file_num):
|
|
@@ -1170,7 +1172,7 @@ class DocumentRepresentation:
|
|
|
1170
1172
|
self.pages.append(page)
|
|
1171
1173
|
|
|
1172
1174
|
toc = time.perf_counter()
|
|
1173
|
-
|
|
1175
|
+
logger.info("Conversion from Image to OpenCV Image performed in %.4f seconds", toc - tic)
|
|
1174
1176
|
shutil.rmtree(output_image_directory)
|
|
1175
1177
|
|
|
1176
1178
|
def get_barcodes(self):
|
|
@@ -1212,8 +1214,8 @@ class DocumentRepresentation:
|
|
|
1212
1214
|
page = pdf.load_page(page_num)
|
|
1213
1215
|
text_content += page.get_text("text")
|
|
1214
1216
|
return text_content if text_content.strip() else ""
|
|
1215
|
-
except Exception as e:
|
|
1216
|
-
|
|
1217
|
+
except Exception as e: # defensive: covers ImportError, fitz internal errors, and I/O failures
|
|
1218
|
+
logger.error("Failed to extract text from PDF: %s", e)
|
|
1217
1219
|
return ""
|
|
1218
1220
|
|
|
1219
1221
|
def compare_with(self, other_doc: 'DocumentRepresentation') -> bool:
|
|
@@ -1323,7 +1325,7 @@ class DocumentRepresentation:
|
|
|
1323
1325
|
signatures = []
|
|
1324
1326
|
try:
|
|
1325
1327
|
widgets = page.widgets()
|
|
1326
|
-
except Exception:
|
|
1328
|
+
except Exception: # defensive: PyMuPDF may raise varied errors on malformed PDFs
|
|
1327
1329
|
widgets = []
|
|
1328
1330
|
if not widgets:
|
|
1329
1331
|
return signatures
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import os
|
|
3
|
+
import re
|
|
4
|
+
import tempfile
|
|
5
|
+
import urllib.parse
|
|
6
|
+
import urllib.request
|
|
7
|
+
import uuid
|
|
8
|
+
|
|
9
|
+
logger = logging.getLogger(__name__)
|
|
10
|
+
|
|
11
|
+
ALLOWED_SCHEMES = ("http", "https", "ftp")
|
|
12
|
+
DEFAULT_MAX_SIZE = 100 * 1024 * 1024 # 100 MB
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def is_url(url, allowed_schemes=None):
|
|
16
|
+
"""
|
|
17
|
+
Check if the provided string is a valid URL.
|
|
18
|
+
|
|
19
|
+
Args:
|
|
20
|
+
url: The string to check.
|
|
21
|
+
allowed_schemes: Optional tuple/list of allowed URL schemes.
|
|
22
|
+
If provided, the URL's scheme must be in this collection.
|
|
23
|
+
If None, any scheme with a netloc is accepted (backward compatible).
|
|
24
|
+
"""
|
|
25
|
+
try:
|
|
26
|
+
result = urllib.parse.urlparse(url)
|
|
27
|
+
if not all([result.scheme, result.netloc]):
|
|
28
|
+
return False
|
|
29
|
+
if allowed_schemes is not None and result.scheme not in allowed_schemes:
|
|
30
|
+
return False
|
|
31
|
+
return True
|
|
32
|
+
except (ValueError, AttributeError):
|
|
33
|
+
return False
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def convert_github_blob_to_raw(url):
|
|
37
|
+
"""
|
|
38
|
+
Convert a GitHub blob URL to a raw content URL.
|
|
39
|
+
|
|
40
|
+
For example:
|
|
41
|
+
https://github.com/user/repo/blob/main/path/file.png
|
|
42
|
+
becomes:
|
|
43
|
+
https://raw.githubusercontent.com/user/repo/main/path/file.png
|
|
44
|
+
|
|
45
|
+
If the URL is not a GitHub blob URL, returns the original URL unchanged.
|
|
46
|
+
"""
|
|
47
|
+
pattern = r"^https?://github\.com/([^/]+)/([^/]+)/blob/(.+)$"
|
|
48
|
+
match = re.match(pattern, url)
|
|
49
|
+
if match:
|
|
50
|
+
user = match.group(1)
|
|
51
|
+
repo = match.group(2)
|
|
52
|
+
rest = match.group(3)
|
|
53
|
+
raw_url = f"https://raw.githubusercontent.com/{user}/{repo}/{rest}"
|
|
54
|
+
logger.info("Converted GitHub blob URL to raw URL: %s", raw_url)
|
|
55
|
+
return raw_url
|
|
56
|
+
return url
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def download_file_from_url(url, directory=None, filename=None, max_size=None):
|
|
60
|
+
"""
|
|
61
|
+
Download the file from the url and save it in the provided directory.
|
|
62
|
+
If directory is None, save it in a temp directory.
|
|
63
|
+
Save the file with the provided filename.
|
|
64
|
+
If the filename is None, derive a filename from the URL using a UUID
|
|
65
|
+
and the file extension from the URL path.
|
|
66
|
+
GitHub blob URLs are automatically converted to raw content URLs.
|
|
67
|
+
|
|
68
|
+
Args:
|
|
69
|
+
url: The URL to download the file from.
|
|
70
|
+
directory: The directory to save the file in. Defaults to temp dir.
|
|
71
|
+
filename: The filename to save the file as. Defaults to UUID + ext.
|
|
72
|
+
max_size: Maximum allowed file size in bytes. Defaults to
|
|
73
|
+
DEFAULT_MAX_SIZE (100 MB). If the downloaded file exceeds this
|
|
74
|
+
size, it is deleted and a ValueError is raised.
|
|
75
|
+
|
|
76
|
+
Raises:
|
|
77
|
+
ValueError: If the URL scheme is not in ALLOWED_SCHEMES or if the
|
|
78
|
+
downloaded file exceeds max_size.
|
|
79
|
+
"""
|
|
80
|
+
# Validate URL scheme
|
|
81
|
+
parsed = urllib.parse.urlparse(url)
|
|
82
|
+
if parsed.scheme not in ALLOWED_SCHEMES:
|
|
83
|
+
raise ValueError(
|
|
84
|
+
f"URL scheme '{parsed.scheme}' is not allowed. "
|
|
85
|
+
f"Allowed schemes: {', '.join(ALLOWED_SCHEMES)}"
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
if max_size is None:
|
|
89
|
+
max_size = DEFAULT_MAX_SIZE
|
|
90
|
+
|
|
91
|
+
if directory is None:
|
|
92
|
+
directory = tempfile.gettempdir()
|
|
93
|
+
if filename is None:
|
|
94
|
+
_, ext = os.path.splitext(os.path.basename(parsed.path))
|
|
95
|
+
if ext:
|
|
96
|
+
filename = str(uuid.uuid4()) + ext
|
|
97
|
+
else:
|
|
98
|
+
logger.warning(
|
|
99
|
+
"Could not determine file extension from URL: %s", url
|
|
100
|
+
)
|
|
101
|
+
filename = str(uuid.uuid4())
|
|
102
|
+
file_path = os.path.join(directory, filename)
|
|
103
|
+
download_url = convert_github_blob_to_raw(url)
|
|
104
|
+
urllib.request.urlretrieve(download_url, file_path)
|
|
105
|
+
|
|
106
|
+
# Validate downloaded file size
|
|
107
|
+
file_size = os.path.getsize(file_path)
|
|
108
|
+
if file_size > max_size:
|
|
109
|
+
os.remove(file_path)
|
|
110
|
+
raise ValueError(
|
|
111
|
+
f"Downloaded file size ({file_size} bytes) exceeds maximum "
|
|
112
|
+
f"allowed size ({max_size} bytes). File has been deleted."
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
# Sniff for HTML content when we likely expected a document/image
|
|
116
|
+
_warn_if_html_content(file_path, url)
|
|
117
|
+
|
|
118
|
+
return file_path
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _warn_if_html_content(file_path, url):
|
|
122
|
+
"""
|
|
123
|
+
Check if the downloaded file appears to be HTML when we likely expected
|
|
124
|
+
something else (e.g., an image, PDF, or other binary document).
|
|
125
|
+
|
|
126
|
+
Logs a warning if HTML markers are detected but does not raise an error,
|
|
127
|
+
since the content could be legitimately HTML.
|
|
128
|
+
"""
|
|
129
|
+
_, ext = os.path.splitext(file_path)
|
|
130
|
+
html_extensions = {".html", ".htm"}
|
|
131
|
+
if ext.lower() in html_extensions:
|
|
132
|
+
return # HTML was expected, no warning needed
|
|
133
|
+
|
|
134
|
+
try:
|
|
135
|
+
with open(file_path, "rb") as f:
|
|
136
|
+
header = f.read(512)
|
|
137
|
+
# Look for common HTML markers in the first 512 bytes
|
|
138
|
+
header_lower = header.lstrip().lower()
|
|
139
|
+
if header_lower.startswith(b"<!doctype") or header_lower.startswith(
|
|
140
|
+
b"<html"
|
|
141
|
+
):
|
|
142
|
+
logger.warning(
|
|
143
|
+
"Downloaded file from %s appears to contain HTML content "
|
|
144
|
+
"but was expected to be a different file type (extension: %s). "
|
|
145
|
+
"This may indicate a redirect to a login page or error page.",
|
|
146
|
+
url,
|
|
147
|
+
ext if ext else "(none)",
|
|
148
|
+
)
|
|
149
|
+
except OSError:
|
|
150
|
+
pass # If we can't read the file for sniffing, skip the check
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def get_filename_from_url(url):
|
|
154
|
+
"""
|
|
155
|
+
Check if the URL contains a valid filename.
|
|
156
|
+
If the URL contains a valid filename, return the filename.
|
|
157
|
+
If the URL does not contain a filename, return None.
|
|
158
|
+
|
|
159
|
+
Uses proper URL parsing to strip query parameters and fragments.
|
|
160
|
+
"""
|
|
161
|
+
if not url:
|
|
162
|
+
return None
|
|
163
|
+
parsed = urllib.parse.urlparse(url)
|
|
164
|
+
basename = os.path.basename(parsed.path)
|
|
165
|
+
if not basename or "." not in basename:
|
|
166
|
+
return None
|
|
167
|
+
return basename
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import logging
|
|
3
|
+
from typing import List, Dict, Optional, Union
|
|
4
|
+
|
|
5
|
+
logger = logging.getLogger(__name__)
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class IgnoreAreaManager:
|
|
9
|
+
def __init__(self, ignore_area_file=None, mask=None):
|
|
10
|
+
self.ignore_area_file = ignore_area_file
|
|
11
|
+
self.mask = mask
|
|
12
|
+
self.ignore_areas = []
|
|
13
|
+
|
|
14
|
+
def read_ignore_areas(self):
|
|
15
|
+
"""
|
|
16
|
+
Read ignore areas from the provided file or mask and return a list of ignore areas.
|
|
17
|
+
"""
|
|
18
|
+
ignore_areas = None
|
|
19
|
+
if self.ignore_area_file:
|
|
20
|
+
ignore_areas = self._load_ignore_area_file()
|
|
21
|
+
elif self.mask:
|
|
22
|
+
ignore_areas = self._parse_mask()
|
|
23
|
+
|
|
24
|
+
if ignore_areas:
|
|
25
|
+
if not isinstance(ignore_areas, list):
|
|
26
|
+
ignore_areas = [ignore_areas]
|
|
27
|
+
return ignore_areas
|
|
28
|
+
return []
|
|
29
|
+
|
|
30
|
+
def _load_ignore_area_file(self):
|
|
31
|
+
"""Load ignore areas from the provided JSON file."""
|
|
32
|
+
try:
|
|
33
|
+
with open(self.ignore_area_file, 'r') as f:
|
|
34
|
+
return json.load(f)
|
|
35
|
+
except IOError as err:
|
|
36
|
+
logger.error("Ignore Area File %s is not accessible.", self.ignore_area_file)
|
|
37
|
+
logger.error("I/O error: %s", err)
|
|
38
|
+
|
|
39
|
+
def _parse_mask(self):
|
|
40
|
+
"""Parse mask if provided as a string, dict, or list."""
|
|
41
|
+
if isinstance(self.mask, dict) or isinstance(self.mask, list):
|
|
42
|
+
return self.mask
|
|
43
|
+
elif isinstance(self.mask, str):
|
|
44
|
+
try:
|
|
45
|
+
return json.loads(self.mask)
|
|
46
|
+
except json.JSONDecodeError:
|
|
47
|
+
return self._parse_mask_string(self.mask)
|
|
48
|
+
|
|
49
|
+
def _parse_mask_string(self, mask_str):
|
|
50
|
+
"""Parse a mask string that uses a custom format, e.g., 'top:10;bottom:10'."""
|
|
51
|
+
ignore_areas = []
|
|
52
|
+
mask_list = mask_str.split(';')
|
|
53
|
+
valid_locations = ('top', 'bottom', 'left', 'right')
|
|
54
|
+
for mask in mask_list:
|
|
55
|
+
if not mask:
|
|
56
|
+
continue
|
|
57
|
+
parts = mask.split(':', 1)
|
|
58
|
+
if len(parts) != 2:
|
|
59
|
+
logger.warning(
|
|
60
|
+
"The mask '%s' is not valid. Expected format 'location:percent' "
|
|
61
|
+
"(e.g., 'top:10').", mask
|
|
62
|
+
)
|
|
63
|
+
continue
|
|
64
|
+
location, percent = parts
|
|
65
|
+
if location not in valid_locations:
|
|
66
|
+
logger.warning(
|
|
67
|
+
"The mask '%s' has an invalid location '%s'. "
|
|
68
|
+
"Valid locations are: %s.",
|
|
69
|
+
mask, location, ', '.join(valid_locations)
|
|
70
|
+
)
|
|
71
|
+
continue
|
|
72
|
+
if not percent.isnumeric():
|
|
73
|
+
logger.warning(
|
|
74
|
+
"The mask '%s' is not valid. The percent value '%s' is not a number.",
|
|
75
|
+
mask, percent
|
|
76
|
+
)
|
|
77
|
+
continue
|
|
78
|
+
ignore_areas.append({
|
|
79
|
+
'page': 'all',
|
|
80
|
+
'type': 'area',
|
|
81
|
+
'location': location,
|
|
82
|
+
'percent': percent,
|
|
83
|
+
})
|
|
84
|
+
return ignore_areas
|