robotframework-doctestlibrary 0.32.0.dev3__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.dev3 → robotframework_doctestlibrary-0.33.0}/DocTest/DocumentRepresentation.py +27 -40
- 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.dev3 → robotframework_doctestlibrary-0.33.0}/DocTest/Ocr.py +6 -3
- {robotframework_doctestlibrary-0.32.0.dev3 → robotframework_doctestlibrary-0.33.0}/DocTest/PdfStructureComparator.py +3 -229
- {robotframework_doctestlibrary-0.32.0.dev3 → robotframework_doctestlibrary-0.33.0}/DocTest/PdfStructureModels.py +0 -233
- {robotframework_doctestlibrary-0.32.0.dev3 → robotframework_doctestlibrary-0.33.0}/DocTest/PdfTest.py +76 -212
- {robotframework_doctestlibrary-0.32.0.dev3 → 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.dev3 → robotframework_doctestlibrary-0.33.0}/DocTest/VisualTest.py +151 -105
- {robotframework_doctestlibrary-0.32.0.dev3 → robotframework_doctestlibrary-0.33.0}/PKG-INFO +39 -23
- robotframework_doctestlibrary-0.33.0/pyproject.toml +68 -0
- robotframework_doctestlibrary-0.32.0.dev3/.gitignore +0 -82
- robotframework_doctestlibrary-0.32.0.dev3/DocTest/Downloader.py +0 -47
- robotframework_doctestlibrary-0.32.0.dev3/DocTest/HeaderFooterDetector.py +0 -230
- robotframework_doctestlibrary-0.32.0.dev3/DocTest/IgnoreAreaManager.py +0 -129
- robotframework_doctestlibrary-0.32.0.dev3/DocTest/StructureReportBuilder.py +0 -558
- robotframework_doctestlibrary-0.32.0.dev3/DocTest/TextNormalization.py +0 -119
- robotframework_doctestlibrary-0.32.0.dev3/pyproject.toml +0 -61
- {robotframework_doctestlibrary-0.32.0.dev3 → robotframework_doctestlibrary-0.33.0}/DocTest/Ai/__init__.py +0 -0
- {robotframework_doctestlibrary-0.32.0.dev3 → robotframework_doctestlibrary-0.33.0}/DocTest/Ai/prompts.py +0 -0
- {robotframework_doctestlibrary-0.32.0.dev3 → robotframework_doctestlibrary-0.33.0}/DocTest/Ai/renderers.py +0 -0
- {robotframework_doctestlibrary-0.32.0.dev3 → robotframework_doctestlibrary-0.33.0}/DocTest/Ai/responses.py +0 -0
- {robotframework_doctestlibrary-0.32.0.dev3 → robotframework_doctestlibrary-0.33.0}/DocTest/PrintJob.py +0 -0
- {robotframework_doctestlibrary-0.32.0.dev3 → robotframework_doctestlibrary-0.33.0}/DocTest/__init__.py +0 -0
- {robotframework_doctestlibrary-0.32.0.dev3 → robotframework_doctestlibrary-0.33.0}/DocTest/config.py +0 -0
- {robotframework_doctestlibrary-0.32.0.dev3 → robotframework_doctestlibrary-0.33.0}/DocTest/llm/__init__.py +0 -0
- {robotframework_doctestlibrary-0.32.0.dev3 → robotframework_doctestlibrary-0.33.0}/DocTest/llm/client.py +0 -0
- {robotframework_doctestlibrary-0.32.0.dev3 → robotframework_doctestlibrary-0.33.0}/DocTest/llm/config.py +0 -0
- {robotframework_doctestlibrary-0.32.0.dev3 → robotframework_doctestlibrary-0.33.0}/DocTest/llm/exceptions.py +0 -0
- {robotframework_doctestlibrary-0.32.0.dev3 → robotframework_doctestlibrary-0.33.0}/DocTest/llm/prompts.py +0 -0
- {robotframework_doctestlibrary-0.32.0.dev3 → robotframework_doctestlibrary-0.33.0}/DocTest/llm/types.py +0 -0
- {robotframework_doctestlibrary-0.32.0.dev3 → robotframework_doctestlibrary-0.33.0}/LICENSE +0 -0
- {robotframework_doctestlibrary-0.32.0.dev3 → 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
|
|
@@ -17,11 +17,12 @@ from DocTest.PdfStructureModels import (
|
|
|
17
17
|
PageStructure,
|
|
18
18
|
StructureExtractionConfig,
|
|
19
19
|
build_page_structure,
|
|
20
|
-
build_page_structure_from_words,
|
|
21
20
|
)
|
|
22
21
|
from DocTest.config import DEFAULT_DPI, OCR_ENGINE_DEFAULT, DEFAULT_CONFIDENCE, MINIMUM_OCR_RESOLUTION, ADD_PIXELS_TO_IGNORE_AREA, TESSERACT_CONFIG
|
|
23
22
|
import tempfile
|
|
24
23
|
|
|
24
|
+
logger = logging.getLogger(__name__)
|
|
25
|
+
|
|
25
26
|
# Constants
|
|
26
27
|
|
|
27
28
|
|
|
@@ -198,27 +199,13 @@ class Page:
|
|
|
198
199
|
cached = self._structure_cache.get(config)
|
|
199
200
|
if cached:
|
|
200
201
|
return cached
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
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
|
-
)
|
|
202
|
+
structure = build_page_structure(
|
|
203
|
+
page_number=self.page_number,
|
|
204
|
+
pdf_dict=self.pdf_text_dict,
|
|
205
|
+
config=config,
|
|
206
|
+
dpi=self.dpi,
|
|
207
|
+
image_shape=self.image.shape,
|
|
208
|
+
)
|
|
222
209
|
self._structure_cache[config] = structure
|
|
223
210
|
return structure
|
|
224
211
|
|
|
@@ -584,7 +571,7 @@ class Page:
|
|
|
584
571
|
def identify_barcodes_with_zbar(self):
|
|
585
572
|
try:
|
|
586
573
|
from pyzbar import pyzbar
|
|
587
|
-
except:
|
|
574
|
+
except ImportError:
|
|
588
575
|
logging.debug('Failed to import pyzbar', exc_info=True)
|
|
589
576
|
return
|
|
590
577
|
image_height = self.image.shape[0]
|
|
@@ -607,19 +594,19 @@ class Page:
|
|
|
607
594
|
def identify_datamatrices(self):
|
|
608
595
|
try:
|
|
609
596
|
from pylibdmtx import pylibdmtx
|
|
610
|
-
except:
|
|
597
|
+
except ImportError:
|
|
611
598
|
logging.debug('Failed to import pylibdmtx', exc_info=True)
|
|
612
599
|
return
|
|
613
600
|
logging.debug("Identify datamatrices")
|
|
614
601
|
image_height = self.image.shape[0]
|
|
615
602
|
try:
|
|
616
603
|
barcodes = pylibdmtx.decode(self.image, timeout=5000)
|
|
617
|
-
except:
|
|
604
|
+
except Exception:
|
|
618
605
|
logging.debug("pylibdmtx could not be loaded",exc_info=True)
|
|
619
606
|
return
|
|
620
607
|
#Add barcode as placehoder
|
|
621
608
|
for barcode in barcodes:
|
|
622
|
-
|
|
609
|
+
logger.debug("Detected barcode: %s", barcode)
|
|
623
610
|
x = barcode.rect.left
|
|
624
611
|
y = image_height - barcode.rect.top - barcode.rect.height
|
|
625
612
|
h = barcode.rect.height
|
|
@@ -629,7 +616,7 @@ class Page:
|
|
|
629
616
|
w += 1
|
|
630
617
|
value = barcode.data.decode("utf-8")
|
|
631
618
|
self.barcodes.append({"x":x, "y":y, "height":h, "width":w, "value":value})
|
|
632
|
-
self.pixel_ignore_areas.append({"x": x, "y
|
|
619
|
+
self.pixel_ignore_areas.append({"x": x, "y": y, "height": h, "width": w})
|
|
633
620
|
|
|
634
621
|
def _process_ignore_area(self, ignore_area: Dict):
|
|
635
622
|
"""Process each ignore area based on its type and convert it into pixel-based coordinates."""
|
|
@@ -786,7 +773,7 @@ class Page:
|
|
|
786
773
|
|
|
787
774
|
try:
|
|
788
775
|
unit = area.get('unit', 'px')
|
|
789
|
-
except:
|
|
776
|
+
except (AttributeError, TypeError):
|
|
790
777
|
unit = 'px'
|
|
791
778
|
area_x, area_y, area_w, area_h = self._convert_to_pixels(area, unit)
|
|
792
779
|
|
|
@@ -1068,7 +1055,7 @@ class DocumentRepresentation:
|
|
|
1068
1055
|
def __del__(self): # pragma: no cover - defensive cleanup
|
|
1069
1056
|
try:
|
|
1070
1057
|
self.close()
|
|
1071
|
-
except Exception:
|
|
1058
|
+
except Exception: # defensive: destructor must never raise
|
|
1072
1059
|
pass
|
|
1073
1060
|
|
|
1074
1061
|
def _load_pcl(self):
|
|
@@ -1081,7 +1068,7 @@ class DocumentRepresentation:
|
|
|
1081
1068
|
import subprocess
|
|
1082
1069
|
try:
|
|
1083
1070
|
command = shutil.which('pcl6') or shutil.which('gpcl6win64') or shutil.which('gpcl6win32') or shutil.which('gpcl6')
|
|
1084
|
-
except
|
|
1071
|
+
except (OSError, TypeError):
|
|
1085
1072
|
command = None
|
|
1086
1073
|
if not command:
|
|
1087
1074
|
raise AssertionError("No pcl6 executable found in path. Please install ghostPCL")
|
|
@@ -1110,12 +1097,12 @@ class DocumentRepresentation:
|
|
|
1110
1097
|
]
|
|
1111
1098
|
subprocess.run(args, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
|
|
1112
1099
|
toc = time.perf_counter()
|
|
1113
|
-
|
|
1100
|
+
logger.info("Rendering pcl document to Image with ghostPCL performed in %.4f seconds", toc - tic)
|
|
1114
1101
|
tic = time.perf_counter()
|
|
1115
1102
|
file_num =len(os.listdir(output_image_directory))
|
|
1116
1103
|
for index in range(file_num):
|
|
1117
1104
|
if (index == 0 or index == int(file_num-1)) and self.ignore_printfactory_envelope is True:
|
|
1118
|
-
|
|
1105
|
+
logger.info("The printfactory envelope is ignored in page %s", index+1)
|
|
1119
1106
|
continue
|
|
1120
1107
|
else:
|
|
1121
1108
|
filename = 'output-' + str(index+1)+'.png'
|
|
@@ -1130,8 +1117,8 @@ class DocumentRepresentation:
|
|
|
1130
1117
|
self.pages.append(page)
|
|
1131
1118
|
|
|
1132
1119
|
toc = time.perf_counter()
|
|
1133
|
-
|
|
1134
|
-
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)
|
|
1135
1122
|
|
|
1136
1123
|
def _load_ps(self):
|
|
1137
1124
|
import subprocess
|
|
@@ -1142,7 +1129,7 @@ class DocumentRepresentation:
|
|
|
1142
1129
|
from os.path import splitext, split
|
|
1143
1130
|
try:
|
|
1144
1131
|
command = shutil.which('gs') or shutil.which('gswin64c') or shutil.which('gswin32c') or shutil.which('ghostscript')
|
|
1145
|
-
except
|
|
1132
|
+
except (OSError, TypeError):
|
|
1146
1133
|
command = None
|
|
1147
1134
|
if not command:
|
|
1148
1135
|
raise AssertionError("No ghostscript executable found in path. Please install ghostscript")
|
|
@@ -1171,7 +1158,7 @@ class DocumentRepresentation:
|
|
|
1171
1158
|
]
|
|
1172
1159
|
subprocess.run(args, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
|
|
1173
1160
|
toc = time.perf_counter()
|
|
1174
|
-
|
|
1161
|
+
logger.info("Rendering ps document to Image with ghostscript performed in %.4f seconds", toc - tic)
|
|
1175
1162
|
tic = time.perf_counter()
|
|
1176
1163
|
file_num =len(os.listdir(output_image_directory))
|
|
1177
1164
|
for index in range(file_num):
|
|
@@ -1185,7 +1172,7 @@ class DocumentRepresentation:
|
|
|
1185
1172
|
self.pages.append(page)
|
|
1186
1173
|
|
|
1187
1174
|
toc = time.perf_counter()
|
|
1188
|
-
|
|
1175
|
+
logger.info("Conversion from Image to OpenCV Image performed in %.4f seconds", toc - tic)
|
|
1189
1176
|
shutil.rmtree(output_image_directory)
|
|
1190
1177
|
|
|
1191
1178
|
def get_barcodes(self):
|
|
@@ -1227,8 +1214,8 @@ class DocumentRepresentation:
|
|
|
1227
1214
|
page = pdf.load_page(page_num)
|
|
1228
1215
|
text_content += page.get_text("text")
|
|
1229
1216
|
return text_content if text_content.strip() else ""
|
|
1230
|
-
except Exception as e:
|
|
1231
|
-
|
|
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)
|
|
1232
1219
|
return ""
|
|
1233
1220
|
|
|
1234
1221
|
def compare_with(self, other_doc: 'DocumentRepresentation') -> bool:
|
|
@@ -1338,7 +1325,7 @@ class DocumentRepresentation:
|
|
|
1338
1325
|
signatures = []
|
|
1339
1326
|
try:
|
|
1340
1327
|
widgets = page.widgets()
|
|
1341
|
-
except Exception:
|
|
1328
|
+
except Exception: # defensive: PyMuPDF may raise varied errors on malformed PDFs
|
|
1342
1329
|
widgets = []
|
|
1343
1330
|
if not widgets:
|
|
1344
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
|