SafePDF 1.2.0__tar.gz → 1.2.1__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 (87) hide show
  1. {safepdf-1.2.0/SafePDF.egg-info → safepdf-1.2.1}/PKG-INFO +8 -1
  2. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/__init__.py +1 -1
  3. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/build_installer.py +10 -0
  4. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/generate_test_keys.py +7 -5
  5. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/licensing/license_manager.py +3 -3
  6. safepdf-1.2.1/SafePDF/ops/pdf_ocr.py +379 -0
  7. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/test/test_licensing.py +23 -2
  8. safepdf-1.2.1/SafePDF/test/test_ocr.py +132 -0
  9. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/text/de/ui.json +1 -1
  10. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/text/en/ui.json +1 -1
  11. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/text/tr/ui.json +1 -1
  12. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/ui/common_elements.py +22 -0
  13. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/ui/help_ui.py +2 -2
  14. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/ui/operation_settings.py +1 -1
  15. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/ui/safe_pdf_ui.py +2 -0
  16. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/ui/settings_ui.py +1 -1
  17. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/ui/update_ui.py +4 -4
  18. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/version.txt +5 -5
  19. {safepdf-1.2.0 → safepdf-1.2.1/SafePDF.egg-info}/PKG-INFO +8 -1
  20. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF.egg-info/SOURCES.txt +1 -0
  21. safepdf-1.2.1/SafePDF.egg-info/requires.txt +22 -0
  22. safepdf-1.2.1/requirements.txt +21 -0
  23. {safepdf-1.2.0 → safepdf-1.2.1}/setup.py +7 -0
  24. safepdf-1.2.0/SafePDF/ops/pdf_ocr.py +0 -234
  25. safepdf-1.2.0/SafePDF.egg-info/requires.txt +0 -13
  26. safepdf-1.2.0/requirements.txt +0 -13
  27. {safepdf-1.2.0 → safepdf-1.2.1}/LICENSE +0 -0
  28. {safepdf-1.2.0 → safepdf-1.2.1}/MANIFEST.in +0 -0
  29. {safepdf-1.2.0 → safepdf-1.2.1}/README.md +0 -0
  30. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/assets/account_circle.svg +0 -0
  31. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/assets/back.png +0 -0
  32. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/assets/compress.png +0 -0
  33. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/assets/compression_err.gif +0 -0
  34. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/assets/crown.svg +0 -0
  35. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/assets/extract.png +0 -0
  36. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/assets/icon.ico +0 -0
  37. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/assets/icon.png +0 -0
  38. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/assets/jpg2pdf.png +0 -0
  39. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/assets/merge.png +0 -0
  40. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/assets/next.png +0 -0
  41. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/assets/notifications.svg +0 -0
  42. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/assets/pdf2jpg.png +0 -0
  43. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/assets/pdf2ocr.png +0 -0
  44. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/assets/pdf2txt.png +0 -0
  45. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/assets/pdf2word.png +0 -0
  46. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/assets/repair.png +0 -0
  47. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/assets/rotate.png +0 -0
  48. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/assets/settings.svg +0 -0
  49. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/assets/split.png +0 -0
  50. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/ctrl/__init__.py +0 -0
  51. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/ctrl/language_manager.py +0 -0
  52. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/ctrl/safe_pdf_controller.py +0 -0
  53. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/licensing/__init__.py +0 -0
  54. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/logger/__init__.py +0 -0
  55. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/logger/logging_config.py +0 -0
  56. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/ops/__init__.py +0 -0
  57. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/ops/pdf2docx.py +0 -0
  58. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/ops/pdf2jpeg.py +0 -0
  59. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/ops/pdf_compress.py +0 -0
  60. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/ops/pdf_merge.py +0 -0
  61. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/ops/pdf_operations.py +0 -0
  62. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/ops/pdf_rotate.py +0 -0
  63. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/ops/pdf_split.py +0 -0
  64. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/ops/updates.py +0 -0
  65. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/ops/watch_folder.py +0 -0
  66. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/safe_pdf_app.py +0 -0
  67. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/test/__init__.py +0 -0
  68. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/test/test_compression.py +0 -0
  69. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/test/test_pro_dialog.py +0 -0
  70. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/text/de/help_content.txt +0 -0
  71. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/text/de/pro_features.txt +0 -0
  72. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/text/de/welcome_content.txt +0 -0
  73. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/text/en/help_content.txt +0 -0
  74. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/text/en/pro_features.txt +0 -0
  75. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/text/en/welcome_content.txt +0 -0
  76. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/text/tr/help_content.txt +0 -0
  77. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/text/tr/pro_features.txt +0 -0
  78. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/text/tr/welcome_content.txt +0 -0
  79. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/ui/__init__.py +0 -0
  80. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/ui/language_elements.py +0 -0
  81. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/ui/tabs_manager.py +0 -0
  82. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF/ui/theme.py +0 -0
  83. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF.egg-info/dependency_links.txt +0 -0
  84. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF.egg-info/entry_points.txt +0 -0
  85. {safepdf-1.2.0 → safepdf-1.2.1}/SafePDF.egg-info/top_level.txt +0 -0
  86. {safepdf-1.2.0 → safepdf-1.2.1}/pyproject.toml +0 -0
  87. {safepdf-1.2.0 → safepdf-1.2.1}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: SafePDF
3
- Version: 1.2.0
3
+ Version: 1.2.1
4
4
  Summary: A safe PDF manipulation tool
5
5
  Home-page: https://github.com/mcagriaksoy/safepdf
6
6
  Author: Mehmet Cagri Aksoy
@@ -15,12 +15,19 @@ Requires-Python: >=3.8
15
15
  Description-Content-Type: text/markdown
16
16
  License-File: LICENSE
17
17
  Requires-Dist: PyPDF2>=3.0.0
18
+ Requires-Dist: PyMuPDF<2.0.0,>=1.24.0
18
19
  Requires-Dist: Pillow>=9.0.0
19
20
  Requires-Dist: pypdfium2>=4.0.0
20
21
  Requires-Dist: python-docx>=0.8.11
22
+ Requires-Dist: pytesseract>=0.3.10
21
23
  Requires-Dist: PyGitHub>=1.55.0
22
24
  Requires-Dist: python-gnupg>=0.4.8
23
25
  Requires-Dist: tkinterdnd2>=0.3.0
26
+ Requires-Dist: cryptography>=41.0.0
27
+ Requires-Dist: winrt-Windows.Media.Ocr>=3.0.0; sys_platform == "win32"
28
+ Requires-Dist: winrt-Windows.Graphics.Imaging>=3.0.0; sys_platform == "win32"
29
+ Requires-Dist: winrt-Windows.Storage.Streams>=3.0.0; sys_platform == "win32"
30
+ Requires-Dist: winrt-Windows.Globalization>=3.0.0; sys_platform == "win32"
24
31
  Provides-Extra: ocr
25
32
  Requires-Dist: pytesseract>=0.3.10; extra == "ocr"
26
33
  Provides-Extra: full
@@ -5,6 +5,6 @@ This file makes the `SafePDF` directory a proper Python package so
5
5
  absolute imports like `from SafePDF.ui...` work consistently.
6
6
  """
7
7
 
8
- __version__ = "1.2.0"
8
+ __version__ = "1.2.1"
9
9
 
10
10
  __all__ = []
@@ -20,6 +20,7 @@ def build_executable(version, safe_pdf_dir, dist_dir):
20
20
  "pyinstaller",
21
21
  "--noconfirm",
22
22
  "--windowed",
23
+ "--noupx",
23
24
  "--onefile",
24
25
  "--name", portable_name,
25
26
  "--icon", os.path.join(safe_pdf_dir, "assets", "icon.ico"),
@@ -33,6 +34,15 @@ def build_executable(version, safe_pdf_dir, dist_dir):
33
34
  "--add-data", f"{os.path.join(safe_pdf_dir, 'keys')};keys/",
34
35
  "--exclude-module", "scipy",
35
36
  "--exclude-module", "networkx",
37
+ "--exclude-module", "matplotlib",
38
+ "--exclude-module", "pandas",
39
+ "--exclude-module", "numpy",
40
+ "--exclude-module", "pytest",
41
+ "--exclude-module", "IPython",
42
+ "--exclude-module", "jupyter",
43
+ "--exclude-module", "notebook",
44
+ "--exclude-module", "tkinter.test",
45
+ "--exclude-module", "test",
36
46
  os.path.join(safe_pdf_dir, "safe_pdf_app.py")
37
47
  ]
38
48
 
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env python3
2
2
  """
3
- Test License Key Generator for SafePDF (Development / QA Only).
3
+ Test License Key Generator for SafePDF (Automated Unit Tests Only).
4
4
 
5
5
  Generates Ed25519-signed `SPDF-...` keys and `.key` files for:
6
6
  - pro_annual
@@ -8,9 +8,10 @@ Generates Ed25519-signed `SPDF-...` keys and `.key` files for:
8
8
  - b2b_team
9
9
  - b2b_enterprise
10
10
 
11
- WARNING: This script contains the *development* private key matching the
12
- public key in `SafePDF/licensing/license_manager.py`. Replace both keys
13
- with your production keypair stored securely offline before release.
11
+ SECURITY NOTE: This script uses an isolated *development* keypair that does NOT
12
+ match the production public key embedded in `SafePDF/licensing/license_manager.py`.
13
+ Keys generated by this script are intentionally rejected by production SafePDF
14
+ builds and are only valid when unit tests inject `DEV_PUBLIC_KEY_B64`.
14
15
  """
15
16
 
16
17
  from __future__ import annotations
@@ -25,8 +26,9 @@ from typing import Any, Dict, Optional
25
26
 
26
27
  from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
27
28
 
28
- # Development Ed25519 Private Key (matches EMBEDDED_PUBLIC_KEY_B64 in license_manager.py)
29
+ # Isolated Development Ed25519 Keypair (for unit tests only; rejected in production builds)
29
30
  DEV_PRIVATE_KEY_B64 = "rfZs2biCxTCraS_X4EO_9wxa-RIyXZ8sVFxtArimhlQ="
31
+ DEV_PUBLIC_KEY_B64 = "CZO_Cj-Ckp6CTea7pEN3Nqw5xTca8KSct7XcCwBS0k8="
30
32
 
31
33
 
32
34
  def _b64url_encode(data: bytes) -> str:
@@ -17,9 +17,9 @@ from typing import Any, Dict, List, Optional, Tuple
17
17
  from cryptography.exceptions import InvalidSignature
18
18
  from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
19
19
 
20
- # Embedded Ed25519 Public Key (raw 32 bytes, URL-safe base64).
21
- # Replace with your production public key; never ship the private key in the app.
22
- EMBEDDED_PUBLIC_KEY_B64 = "CZO_Cj-Ckp6CTea7pEN3Nqw5xTca8KSct7XcCwBS0k8="
20
+ # Embedded Production Ed25519 Public Key (raw 32 bytes, URL-safe base64).
21
+ # Private key is stored offline outside this repository; never ship it in the app.
22
+ EMBEDDED_PUBLIC_KEY_B64 = "9u4-5M1tocsIL7J7n4IrBw9MRpZLCTNG7wb-umgyQLE="
23
23
 
24
24
  VALID_TIERS = ("pro_annual", "pro_lifetime", "b2b_team", "b2b_enterprise")
25
25
  B2B_TIERS = ("b2b_team", "b2b_enterprise")
@@ -0,0 +1,379 @@
1
+ """
2
+ PDF OCR conversion module for SafePDF.
3
+
4
+ Extracts text from scanned/image-based PDFs 100% locally using:
5
+ 1. Built-in Windows OCR (`Windows.Media.Ocr` via `winrt`) on Windows 10/11 — zero external install.
6
+ 2. Tesseract OCR (`pytesseract`) on Linux/macOS or as a fallback when installed.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import asyncio
12
+ import sys
13
+ from pathlib import Path
14
+ from typing import Any, List, Optional, Tuple
15
+
16
+ import pypdfium2 as pdfium
17
+
18
+ from SafePDF.logger.logging_config import get_logger
19
+
20
+ try:
21
+ import pytesseract
22
+ from pytesseract import TesseractNotFoundError
23
+ except ImportError:
24
+ pytesseract = None
25
+ TesseractNotFoundError = RuntimeError
26
+
27
+ try:
28
+ if sys.platform == "win32":
29
+ from winrt.windows.globalization import Language as WinRTGlobalizationLanguage
30
+ from winrt.windows.graphics.imaging import BitmapPixelFormat, SoftwareBitmap
31
+ from winrt.windows.media.ocr import OcrEngine as WinRTOcrEngine
32
+ from winrt.windows.storage.streams import DataWriter as WinRTDataWriter
33
+ else:
34
+ WinRTGlobalizationLanguage = None
35
+ BitmapPixelFormat = None
36
+ SoftwareBitmap = None
37
+ WinRTOcrEngine = None
38
+ WinRTDataWriter = None
39
+ except ImportError:
40
+ WinRTGlobalizationLanguage = None
41
+ BitmapPixelFormat = None
42
+ SoftwareBitmap = None
43
+ WinRTOcrEngine = None
44
+ WinRTDataWriter = None
45
+
46
+
47
+ class OCREngineUnavailableError(RuntimeError):
48
+ """Raised when no offline OCR engine is available on the current system."""
49
+
50
+
51
+ class PDFOCRConverter:
52
+ """Class handling OCR-based PDF conversions."""
53
+
54
+ OCR_LANG_MAP = {
55
+ "en": "eng",
56
+ "de": "deu+eng",
57
+ "tr": "tur+eng",
58
+ }
59
+
60
+ WINRT_LANG_CANDIDATES = {
61
+ "en": ("en-US", "en-GB", "en"),
62
+ "de": ("de-DE", "de-AT", "de-CH", "en-US"),
63
+ "tr": ("tr-TR", "en-US"),
64
+ }
65
+
66
+ def __init__(
67
+ self,
68
+ progress_callback=None,
69
+ status_callback=None,
70
+ language_manager=None,
71
+ atomic_write_file=None,
72
+ atomic_write_via_path=None,
73
+ ):
74
+ self.progress_callback = progress_callback
75
+ self.status_callback = status_callback
76
+ self.language_manager = language_manager
77
+ self._atomic_write_file = atomic_write_file
78
+ self._atomic_write_via_path = atomic_write_via_path
79
+ self._cancel_requested = False
80
+ self.logger = get_logger("SafePDF.PDFOCR")
81
+ self._tesseract_checked = False
82
+ self._winrt_engine: Any = None
83
+ self._active_backend: Optional[str] = None
84
+
85
+ def update_progress(self, value):
86
+ """Update progress if callback is available."""
87
+ if self.progress_callback:
88
+ self.progress_callback(value)
89
+
90
+ def update_status(self, message):
91
+ """Update live status if callback is available."""
92
+ if self.status_callback:
93
+ self.status_callback(message)
94
+
95
+ def _lang_text(self, key: str, default: str) -> str:
96
+ """Return a localized string when a language manager is available."""
97
+ if self.language_manager:
98
+ return self.language_manager.get(key, default)
99
+ return default
100
+
101
+ def request_cancel(self):
102
+ """Request cancellation of a running operation."""
103
+ self._cancel_requested = True
104
+
105
+ def _get_app_lang(self) -> str:
106
+ if not self.language_manager:
107
+ return "en"
108
+ return str(getattr(self.language_manager, "lang", "en") or "en").lower()
109
+
110
+ def _get_ocr_langs(self) -> str:
111
+ return self.OCR_LANG_MAP.get(self._get_app_lang(), "eng")
112
+
113
+ def _configure_tesseract_binary(self):
114
+ """Use the default Windows Tesseract install if it exists."""
115
+ if pytesseract is None or pytesseract.pytesseract.tesseract_cmd != "tesseract":
116
+ return
117
+
118
+ candidate_paths = [
119
+ Path(r"C:\Program Files\Tesseract-OCR\tesseract.exe"),
120
+ Path(r"C:\Program Files (x86)\Tesseract-OCR\tesseract.exe"),
121
+ ]
122
+ for candidate in candidate_paths:
123
+ if candidate.exists():
124
+ pytesseract.pytesseract.tesseract_cmd = str(candidate)
125
+ return
126
+
127
+ def _init_winrt_engine(self) -> Tuple[Any, bool]:
128
+ """Try to initialize Windows.Media.Ocr engine. Returns (engine, exact_lang_matched)."""
129
+ if WinRTOcrEngine is None or WinRTGlobalizationLanguage is None:
130
+ return None, False
131
+
132
+ app_lang = self._get_app_lang()
133
+ candidates = self.WINRT_LANG_CANDIDATES.get(app_lang, ("en-US", "en-GB", "en"))
134
+ primary_prefix = app_lang.lower()
135
+
136
+ for idx, tag in enumerate(candidates):
137
+ try:
138
+ lang_obj = WinRTGlobalizationLanguage(tag)
139
+ if WinRTOcrEngine.is_language_supported(lang_obj):
140
+ engine = WinRTOcrEngine.try_create_from_language(lang_obj)
141
+ if engine is not None:
142
+ exact = tag.lower().startswith(primary_prefix) or idx == 0
143
+ return engine, exact
144
+ except Exception:
145
+ continue
146
+
147
+ try:
148
+ engine = WinRTOcrEngine.try_create_from_user_profile_languages()
149
+ if engine is not None:
150
+ return engine, False
151
+ except Exception:
152
+ pass
153
+
154
+ try:
155
+ avail = list(WinRTOcrEngine.available_recognizer_languages or [])
156
+ for lang_obj in avail:
157
+ engine = WinRTOcrEngine.try_create_from_language(lang_obj)
158
+ if engine is not None:
159
+ return engine, False
160
+ except Exception:
161
+ pass
162
+
163
+ return None, False
164
+
165
+ def _try_tesseract(self) -> bool:
166
+ """Check whether pytesseract + tesseract binary are usable."""
167
+ if pytesseract is None:
168
+ return False
169
+ self._configure_tesseract_binary()
170
+ if self._tesseract_checked:
171
+ return True
172
+ try:
173
+ pytesseract.get_tesseract_version()
174
+ self._tesseract_checked = True
175
+ return True
176
+ except Exception:
177
+ return False
178
+
179
+ def _ensure_ocr_available(self):
180
+ """Select and initialize an available offline OCR engine (Windows OCR or Tesseract)."""
181
+ self.update_status(self._lang_text("ocr_status_loading_model", "Loading OCR model..."))
182
+
183
+ winrt_engine, exact_match = self._init_winrt_engine()
184
+ if winrt_engine is not None and (exact_match or not self._try_tesseract()):
185
+ self._winrt_engine = winrt_engine
186
+ self._active_backend = "winrt"
187
+ self.logger.info("Using built-in Windows.Media.Ocr engine")
188
+ self.update_status(self._lang_text("ocr_status_model_ready", "OCR model ready."))
189
+ return
190
+
191
+ if self._try_tesseract():
192
+ self._winrt_engine = None
193
+ self._active_backend = "tesseract"
194
+ self.logger.info("Using Tesseract OCR engine")
195
+ self.update_status(self._lang_text("ocr_status_model_ready", "OCR model ready."))
196
+ return
197
+
198
+ if winrt_engine is not None:
199
+ self._winrt_engine = winrt_engine
200
+ self._active_backend = "winrt"
201
+ self.logger.info("Using built-in Windows.Media.Ocr engine (fallback language)")
202
+ self.update_status(self._lang_text("ocr_status_model_ready", "OCR model ready."))
203
+ return
204
+
205
+ raise OCREngineUnavailableError(
206
+ self._lang_text(
207
+ "op_ocr_engine_missing",
208
+ "No offline OCR engine available. On Linux/macOS install Tesseract OCR; on Windows enable an OS OCR language pack.",
209
+ )
210
+ )
211
+
212
+ @staticmethod
213
+ def _prepare_winrt_image(pil_image: Any, max_dim: int) -> Any:
214
+ """Ensure image is RGBA8 and within Windows.Media.Ocr max_image_dimension."""
215
+ img = pil_image.convert("RGBA")
216
+ limit = int(max_dim or 2600)
217
+ longest = max(img.width, img.height)
218
+ if longest > limit > 0:
219
+ scale = limit / float(longest)
220
+ new_w = max(1, int(img.width * scale))
221
+ new_h = max(1, int(img.height * scale))
222
+ img = img.resize((new_w, new_h))
223
+ return img
224
+
225
+ def _recognize_with_winrt(self, pil_image: Any) -> str:
226
+ """Run built-in Windows.Media.Ocr on an in-memory PIL image."""
227
+ if (
228
+ self._winrt_engine is None
229
+ or WinRTDataWriter is None
230
+ or SoftwareBitmap is None
231
+ or BitmapPixelFormat is None
232
+ ):
233
+ raise OCREngineUnavailableError("Windows.Media.Ocr engine is not initialized.")
234
+
235
+ max_dim = getattr(WinRTOcrEngine, "max_image_dimension", 2600)
236
+ rgba = self._prepare_winrt_image(pil_image, max_dim)
237
+
238
+ writer = WinRTDataWriter()
239
+ writer.write_bytes(rgba.tobytes())
240
+ buffer = writer.detach_buffer()
241
+
242
+ bitmap = SoftwareBitmap(BitmapPixelFormat.RGBA8, rgba.width, rgba.height)
243
+ bitmap.copy_from_buffer(buffer)
244
+
245
+ async def _recognize():
246
+ return await self._winrt_engine.recognize_async(bitmap)
247
+
248
+ result = asyncio.run(_recognize())
249
+ lines: List[str] = []
250
+ for line in getattr(result, "lines", None) or []:
251
+ line_text = str(getattr(line, "text", "") or "").strip()
252
+ if line_text:
253
+ lines.append(line_text)
254
+ if lines:
255
+ return "\n".join(lines).strip()
256
+ return str(getattr(result, "text", "") or "").strip()
257
+
258
+ def _recognize_page(self, pil_image: Any, ocr_langs: str) -> str:
259
+ """Recognize text from a PIL image using the active OCR backend."""
260
+ if self._active_backend == "winrt":
261
+ return self._recognize_with_winrt(pil_image)
262
+ if pytesseract is None:
263
+ raise OCREngineUnavailableError("pytesseract is not installed.")
264
+ return pytesseract.image_to_string(pil_image, lang=ocr_langs).strip()
265
+
266
+ def _extract_page_text_chunks(self, input_path: str, dpi: int = 300):
267
+ """Run OCR on each PDF page and return per-page text chunks."""
268
+ pdf = pdfium.PdfDocument(input_path)
269
+ try:
270
+ total_pages = len(pdf)
271
+ ocr_langs = self._get_ocr_langs()
272
+ self._ensure_ocr_available()
273
+ scale = max(dpi, 72) / 72.0
274
+ text_chunks = []
275
+
276
+ for page_num in range(total_pages):
277
+ page_index = page_num + 1
278
+ self.update_status(
279
+ self._lang_text(
280
+ "ocr_status_rendering_page",
281
+ "Rendering page {page} of {total}...",
282
+ ).format(page=page_index, total=total_pages)
283
+ )
284
+ self.update_progress(int((page_num / total_pages) * 100))
285
+ if self._cancel_requested:
286
+ return False, self._lang_text("op_word_cancelled", "Operation cancelled")
287
+
288
+ page = pdf[page_num]
289
+ pil_image = page.render(scale=scale).to_pil()
290
+ self.update_status(
291
+ self._lang_text(
292
+ "ocr_status_recognizing_page",
293
+ "Recognizing text on page {page} of {total}...",
294
+ ).format(page=page_index, total=total_pages)
295
+ )
296
+ text = self._recognize_page(pil_image, ocr_langs)
297
+ text_chunks.append((page_index, text))
298
+ self.update_progress(int((page_index / total_pages) * 100))
299
+
300
+ return True, text_chunks
301
+ finally:
302
+ pdf.close()
303
+
304
+ def _save_text_output(self, text_chunks, output_path: str):
305
+ """Write OCR text output to a TXT file."""
306
+ self.update_status(self._lang_text("ocr_status_saving_txt", "Saving OCR text as TXT..."))
307
+ text_content = (
308
+ "\n".join(f"--- Page {page_num} ---\n{text.strip()}\n" for page_num, text in text_chunks).strip() + "\n"
309
+ )
310
+
311
+ def _write_text(tmpf):
312
+ tmpf.write(text_content.encode("utf-8"))
313
+
314
+ if self._atomic_write_file:
315
+ self._atomic_write_file(output_path, _write_text)
316
+ else:
317
+ with open(output_path, "wb") as out_file:
318
+ _write_text(out_file)
319
+
320
+ def _save_docx_output(self, text_chunks, output_path: str):
321
+ """Write OCR text output to a DOCX file."""
322
+ self.update_status(self._lang_text("ocr_status_saving_docx", "Saving OCR text as DOCX..."))
323
+ try:
324
+ from docx import Document
325
+ except ImportError:
326
+ return False, self._lang_text(
327
+ "op_docx_unavailable",
328
+ "python-docx not installed. Please install with: pip install python-docx",
329
+ )
330
+
331
+ doc = Document()
332
+ doc.add_heading("OCR Output", level=1)
333
+ for page_num, text in text_chunks:
334
+ doc.add_heading(f"Page {page_num}", level=2)
335
+ doc.add_paragraph(text if text.strip() else "[No text detected on this page]")
336
+
337
+ def _save_docx(tmp_path):
338
+ doc.save(tmp_path)
339
+
340
+ if self._atomic_write_via_path:
341
+ self._atomic_write_via_path(output_path, _save_docx)
342
+ else:
343
+ doc.save(output_path)
344
+ return True, None
345
+
346
+ def _run_ocr_pipeline(self, input_path: str, output_path: str, output_format: str, dpi: int = 300) -> Tuple[bool, str]:
347
+ """Shared OCR execution pipeline for TXT and DOCX output."""
348
+ if not pdfium:
349
+ return False, self._lang_text("op_pdfium_unavailable", "pypdfium2 not available")
350
+
351
+ try:
352
+ success, result = self._extract_page_text_chunks(input_path, dpi=dpi)
353
+ if not success:
354
+ return False, result
355
+
356
+ if output_format == "docx":
357
+ ok_save, error = self._save_docx_output(result, output_path)
358
+ if not ok_save:
359
+ return False, error
360
+ success_msg = self._lang_text("op_word_success", "PDF converted to DOCX document: {output_path}")
361
+ else:
362
+ self._save_text_output(result, output_path)
363
+ success_msg = self._lang_text("op_ocr_success", "OCR text extracted to {output_path}")
364
+
365
+ return True, success_msg.format(output_path=output_path)
366
+ except (TesseractNotFoundError, OCREngineUnavailableError) as e:
367
+ return False, str(e) or self._lang_text("op_ocr_engine_missing", "OCR engine not found.")
368
+ except Exception as e:
369
+ self.logger.error("OCR conversion failed", exc_info=True)
370
+ error_msg = self._lang_text("op_ocr_failed", "PDF OCR failed: {error}")
371
+ return False, error_msg.format(error=str(e))
372
+
373
+ def pdf_ocr_to_txt(self, input_path: str, output_path: str, dpi: int = 300) -> Tuple[bool, str]:
374
+ """Run OCR on each PDF page and save the extracted text to a TXT file."""
375
+ return self._run_ocr_pipeline(input_path, output_path, output_format="txt", dpi=dpi)
376
+
377
+ def pdf_ocr_to_docx(self, input_path: str, output_path: str, dpi: int = 300) -> Tuple[bool, str]:
378
+ """Run OCR on each PDF page and save the extracted text to a DOCX file."""
379
+ return self._run_ocr_pipeline(input_path, output_path, output_format="docx", dpi=dpi)
@@ -6,6 +6,7 @@ import sys
6
6
  import tempfile
7
7
  import unittest
8
8
  from pathlib import Path
9
+ from unittest.mock import patch
9
10
 
10
11
  repo_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
12
  if repo_root not in sys.path:
@@ -18,13 +19,33 @@ os.environ["HOME"] = _TEST_TMP
18
19
  os.environ["SAFEPDF_CONFIG_DIR"] = os.path.join(_TEST_TMP, ".safepdf")
19
20
 
20
21
  from SafePDF.ctrl.safe_pdf_controller import SafePDFController # noqa: E402
21
- from SafePDF.generate_test_keys import generate_license_key # noqa: E402
22
- from SafePDF.licensing.license_manager import LicenseManager # noqa: E402
22
+ from SafePDF.generate_test_keys import DEV_PUBLIC_KEY_B64, generate_license_key # noqa: E402
23
+ from SafePDF.licensing.license_manager import EMBEDDED_PUBLIC_KEY_B64, LicenseManager # noqa: E402
23
24
  from SafePDF.safe_pdf_app import handle_cli_activation, parse_args # noqa: E402
24
25
 
25
26
 
27
+ class TestProductionKeySecurity(unittest.TestCase):
28
+ def test_dev_key_rejected_by_production_public_key(self):
29
+ """Production builds must never accept keys signed with the public repo dev key."""
30
+ self.assertNotEqual(EMBEDDED_PUBLIC_KEY_B64, DEV_PUBLIC_KEY_B64)
31
+ prod_lm = LicenseManager()
32
+ for tier in ("pro_annual", "pro_lifetime", "b2b_team", "b2b_enterprise"):
33
+ dev_key = generate_license_key(tier=tier, seats=10, org_name="Forged Corp")
34
+ ok, msg, data = prod_lm.verify_license(dev_key)
35
+ self.assertFalse(ok, f"Dev key for tier={tier} must be rejected by production public key")
36
+ self.assertIn("signature", msg.lower())
37
+ self.assertIsNone(data)
38
+
39
+
26
40
  class TestOfflineLicensing(unittest.TestCase):
27
41
  def setUp(self):
42
+ self._pub_patcher = patch(
43
+ "SafePDF.licensing.license_manager.EMBEDDED_PUBLIC_KEY_B64",
44
+ DEV_PUBLIC_KEY_B64,
45
+ )
46
+ self._pub_patcher.start()
47
+ self.addCleanup(self._pub_patcher.stop)
48
+
28
49
  self.config_dir = Path(os.environ["SAFEPDF_CONFIG_DIR"])
29
50
  self.config_dir.mkdir(parents=True, exist_ok=True)
30
51
  for item in self.config_dir.glob("*.key"):
@@ -0,0 +1,132 @@
1
+ #!/usr/bin/env python3
2
+ """Unit tests for SafePDF OCR backend selection (Windows.Media.Ocr + Tesseract fallback)."""
3
+
4
+ import os
5
+ import sys
6
+ from pathlib import Path # noqa: E402
7
+ import tempfile
8
+ import types
9
+ import unittest
10
+ from unittest.mock import MagicMock, patch
11
+
12
+ repo_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
13
+ if repo_root not in sys.path:
14
+ sys.path.insert(0, repo_root)
15
+
16
+ import fitz # noqa: E402
17
+ from PIL import Image # noqa: E402
18
+
19
+ import SafePDF.ops.pdf_ocr as pdf_ocr_mod # noqa: E402
20
+ from SafePDF.ops.pdf_ocr import PDFOCRConverter # noqa: E402
21
+
22
+
23
+ def _make_sample_pdf(path: str) -> None:
24
+ doc = fitz.open()
25
+ page = doc.new_page(width=400, height=600)
26
+ page.insert_text((40, 80), "SafePDF OCR Test")
27
+ doc.save(path)
28
+ doc.close()
29
+
30
+
31
+ class TestPDFOCR(unittest.TestCase):
32
+ def test_prepare_winrt_image_scales_down_above_max_dimension(self):
33
+ large = Image.new("RGB", (3000, 4000), "white")
34
+ prepared = PDFOCRConverter._prepare_winrt_image(large, max_dim=2600)
35
+ self.assertEqual(prepared.mode, "RGBA")
36
+ self.assertLessEqual(max(prepared.width, prepared.height), 2600)
37
+ self.assertEqual(prepared.height, 2600)
38
+ self.assertEqual(prepared.width, 1950)
39
+
40
+ def test_winrt_ocr_backend_used_without_tesseract(self):
41
+ fake_engine = MagicMock()
42
+
43
+ async def _fake_recognize(_bitmap):
44
+ line1 = types.SimpleNamespace(text="Invoice #2026")
45
+ line2 = types.SimpleNamespace(text="Total: EUR 14.00")
46
+ return types.SimpleNamespace(lines=[line1, line2], text="")
47
+
48
+ fake_engine.recognize_async = _fake_recognize
49
+
50
+ class FakeOcrEngineCls:
51
+ max_image_dimension = 2600
52
+ available_recognizer_languages = []
53
+
54
+ @staticmethod
55
+ def is_language_supported(_lang):
56
+ return True
57
+
58
+ @staticmethod
59
+ def try_create_from_language(_lang):
60
+ return fake_engine
61
+
62
+ @staticmethod
63
+ def try_create_from_user_profile_languages():
64
+ return fake_engine
65
+
66
+ fake_writer = MagicMock()
67
+ fake_writer.detach_buffer.return_value = b"buf"
68
+
69
+ with (
70
+ patch.object(pdf_ocr_mod, "WinRTOcrEngine", FakeOcrEngineCls),
71
+ patch.object(pdf_ocr_mod, "WinRTGlobalizationLanguage", side_effect=lambda t: t),
72
+ patch.object(pdf_ocr_mod, "WinRTDataWriter", return_value=fake_writer),
73
+ patch.object(pdf_ocr_mod, "SoftwareBitmap", return_value=MagicMock()),
74
+ patch.object(pdf_ocr_mod, "BitmapPixelFormat", types.SimpleNamespace(RGBA8="rgba8")),
75
+ patch.object(pdf_ocr_mod, "pytesseract", None),
76
+ ):
77
+ with tempfile.TemporaryDirectory() as tmpdir:
78
+ pdf_path = os.path.join(tmpdir, "scan.pdf")
79
+ txt_path = os.path.join(tmpdir, "out.txt")
80
+ docx_path = os.path.join(tmpdir, "out.docx")
81
+ _make_sample_pdf(pdf_path)
82
+
83
+ conv = PDFOCRConverter()
84
+ ok_txt, msg_txt = conv.pdf_ocr_to_txt(pdf_path, txt_path, dpi=150)
85
+ self.assertTrue(ok_txt, msg_txt)
86
+ content = Path(txt_path).read_text(encoding="utf-8")
87
+ self.assertIn("Invoice #2026", content)
88
+ self.assertIn("Total: EUR 14.00", content)
89
+
90
+ ok_docx, msg_docx = conv.pdf_ocr_to_docx(pdf_path, docx_path, dpi=150)
91
+ self.assertTrue(ok_docx, msg_docx)
92
+ self.assertTrue(os.path.exists(docx_path))
93
+
94
+ def test_tesseract_fallback_when_winrt_unavailable(self):
95
+ fake_pytess = MagicMock()
96
+ fake_pytess.pytesseract = types.SimpleNamespace(tesseract_cmd="tesseract")
97
+ fake_pytess.get_tesseract_version.return_value = "5.4.0"
98
+ fake_pytess.image_to_string.return_value = "Fallback Tesseract Text"
99
+
100
+ with (
101
+ patch.object(pdf_ocr_mod, "WinRTOcrEngine", None),
102
+ patch.object(pdf_ocr_mod, "pytesseract", fake_pytess),
103
+ ):
104
+ with tempfile.TemporaryDirectory() as tmpdir:
105
+ pdf_path = os.path.join(tmpdir, "scan.pdf")
106
+ txt_path = os.path.join(tmpdir, "out.txt")
107
+ _make_sample_pdf(pdf_path)
108
+
109
+ conv = PDFOCRConverter()
110
+ ok, msg = conv.pdf_ocr_to_txt(pdf_path, txt_path, dpi=150)
111
+ self.assertTrue(ok, msg)
112
+ self.assertEqual(conv._active_backend, "tesseract")
113
+ self.assertIn("Fallback Tesseract Text", Path(txt_path).read_text(encoding="utf-8"))
114
+
115
+ def test_missing_both_engines_returns_clear_error(self):
116
+ with (
117
+ patch.object(pdf_ocr_mod, "WinRTOcrEngine", None),
118
+ patch.object(pdf_ocr_mod, "pytesseract", None),
119
+ ):
120
+ with tempfile.TemporaryDirectory() as tmpdir:
121
+ pdf_path = os.path.join(tmpdir, "scan.pdf")
122
+ txt_path = os.path.join(tmpdir, "out.txt")
123
+ _make_sample_pdf(pdf_path)
124
+
125
+ conv = PDFOCRConverter()
126
+ ok, msg = conv.pdf_ocr_to_txt(pdf_path, txt_path, dpi=150)
127
+ self.assertFalse(ok)
128
+ self.assertIn("OCR", msg)
129
+
130
+
131
+ if __name__ == "__main__":
132
+ unittest.main()
@@ -117,7 +117,7 @@
117
117
  "settings_to_ocr_bullet_language": "• Verwendet die App-Sprache, wenn ein OCR-Sprachpaket verfugbar ist",
118
118
  "settings_to_ocr_bullet_output_hint": "• TXT ist am besten zum schnellen Kopieren/Bearbeiten, DOCX besser zum Teilen",
119
119
  "settings_to_ocr_bullet_future_pdf": "• Durchsuchbares OCR-PDF kann spater als separate Ausgabeoption hinzugefugt werden",
120
- "settings_to_ocr_bullet_requires": "• Benotigt Tesseract OCR und pypdfium2",
120
+ "settings_to_ocr_bullet_requires": "• Nutzt integriertes Windows-OCR (oder Tesseract OCR) lokal",
121
121
  "settings_ocr_output_format": "OCR-Ausgabeformat",
122
122
  "settings_ocr_output_txt": "TXT (Empfohlen)",
123
123
  "settings_ocr_output_docx": "DOCX",