SafePDF 1.0.13__tar.gz → 1.0.14__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 (76) hide show
  1. safepdf-1.0.14/MANIFEST.in +5 -0
  2. {safepdf-1.0.13/SafePDF.egg-info → safepdf-1.0.14}/PKG-INFO +35 -10
  3. {safepdf-1.0.13 → safepdf-1.0.14}/README.md +53 -31
  4. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/__init__.py +1 -1
  5. safepdf-1.0.14/SafePDF/assets/back.png +0 -0
  6. safepdf-1.0.14/SafePDF/assets/compress.png +0 -0
  7. safepdf-1.0.14/SafePDF/assets/compression_err.gif +0 -0
  8. safepdf-1.0.14/SafePDF/assets/crown.svg +1 -0
  9. safepdf-1.0.14/SafePDF/assets/extract.png +0 -0
  10. safepdf-1.0.14/SafePDF/assets/icon.ico +0 -0
  11. safepdf-1.0.14/SafePDF/assets/jpg2pdf.png +0 -0
  12. safepdf-1.0.14/SafePDF/assets/merge.png +0 -0
  13. safepdf-1.0.14/SafePDF/assets/next.png +0 -0
  14. safepdf-1.0.14/SafePDF/assets/pdf2jpg.png +0 -0
  15. safepdf-1.0.14/SafePDF/assets/pdf2ocr.png +0 -0
  16. safepdf-1.0.14/SafePDF/assets/pdf2txt.png +0 -0
  17. safepdf-1.0.14/SafePDF/assets/pdf2word.png +0 -0
  18. safepdf-1.0.14/SafePDF/assets/repair.png +0 -0
  19. safepdf-1.0.14/SafePDF/assets/rotate.png +0 -0
  20. safepdf-1.0.14/SafePDF/assets/split.png +0 -0
  21. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/ctrl/safe_pdf_controller.py +22 -3
  22. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/ops/pdf_compress.py +4 -5
  23. safepdf-1.0.14/SafePDF/ops/pdf_ocr.py +234 -0
  24. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/ops/pdf_operations.py +60 -1
  25. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/test/test_compression.py +1 -1
  26. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/text/de/ui.json +20 -7
  27. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/text/en/ui.json +20 -7
  28. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/text/tr/ui.json +20 -7
  29. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/ui/help_ui.py +7 -16
  30. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/ui/operation_settings.py +93 -62
  31. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/ui/safe_pdf_ui.py +606 -331
  32. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/ui/settings_ui.py +26 -26
  33. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/ui/tabs_manager.py +16 -42
  34. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/ui/update_ui.py +2 -2
  35. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/version.txt +5 -5
  36. {safepdf-1.0.13 → safepdf-1.0.14/SafePDF.egg-info}/PKG-INFO +35 -10
  37. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF.egg-info/SOURCES.txt +17 -0
  38. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF.egg-info/requires.txt +7 -3
  39. safepdf-1.0.14/pyproject.toml +3 -0
  40. safepdf-1.0.14/requirements.txt +13 -0
  41. {safepdf-1.0.13 → safepdf-1.0.14}/setup.py +21 -10
  42. safepdf-1.0.13/MANIFEST.in +0 -1
  43. safepdf-1.0.13/SafePDF/ops/pdf_ocr.py +0 -257
  44. safepdf-1.0.13/requirements.txt +0 -29
  45. {safepdf-1.0.13 → safepdf-1.0.14}/LICENSE +0 -0
  46. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/ctrl/__init__.py +0 -0
  47. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/ctrl/language_manager.py +0 -0
  48. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/logger/__init__.py +0 -0
  49. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/logger/logging_config.py +0 -0
  50. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/ops/__init__.py +0 -0
  51. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/ops/license_manager.py +0 -0
  52. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/ops/pdf2docx.py +0 -0
  53. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/ops/pdf2jpeg.py +0 -0
  54. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/ops/pdf_merge.py +0 -0
  55. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/ops/pdf_rotate.py +0 -0
  56. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/ops/pdf_split.py +0 -0
  57. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/ops/updates.py +0 -0
  58. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/safe_pdf_app.py +0 -0
  59. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/test/__init__.py +0 -0
  60. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/test/test_pro_dialog.py +0 -0
  61. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/text/de/help_content.txt +0 -0
  62. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/text/de/pro_features.txt +0 -0
  63. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/text/de/welcome_content.txt +0 -0
  64. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/text/en/help_content.txt +0 -0
  65. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/text/en/pro_features.txt +0 -0
  66. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/text/en/welcome_content.txt +0 -0
  67. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/text/tr/help_content.txt +0 -0
  68. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/text/tr/pro_features.txt +0 -0
  69. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/text/tr/welcome_content.txt +0 -0
  70. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/ui/__init__.py +0 -0
  71. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/ui/common_elements.py +0 -0
  72. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF/ui/language_elements.py +0 -0
  73. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF.egg-info/dependency_links.txt +0 -0
  74. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF.egg-info/entry_points.txt +0 -0
  75. {safepdf-1.0.13 → safepdf-1.0.14}/SafePDF.egg-info/top_level.txt +0 -0
  76. {safepdf-1.0.13 → safepdf-1.0.14}/setup.cfg +0 -0
@@ -0,0 +1,5 @@
1
+ recursive-include SafePDF/text *.txt *.json *.md
2
+ recursive-include SafePDF/assets *
3
+ include SafePDF/version.txt
4
+ global-exclude __pycache__
5
+ include requirements.txt
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: SafePDF
3
- Version: 1.0.13
3
+ Version: 1.0.14
4
4
  Summary: A safe PDF manipulation tool
5
5
  Home-page: https://github.com/mcagriaksoy/safepdf
6
6
  Author: Mehmet Cagri Aksoy
@@ -17,12 +17,14 @@ License-File: LICENSE
17
17
  Requires-Dist: PyPDF2>=3.0.0
18
18
  Requires-Dist: Pillow>=9.0.0
19
19
  Requires-Dist: pypdfium2>=4.0.0
20
- Requires-Dist: tkinterdnd2>=0.3.0
21
20
  Requires-Dist: python-docx>=0.8.11
22
- Requires-Dist: requests>=2.25.0
23
21
  Requires-Dist: PyGitHub>=1.55.0
24
22
  Requires-Dist: python-gnupg>=0.4.8
25
- Requires-Dist: easyocr
23
+ Requires-Dist: tkinterdnd2>=0.3.0
24
+ Provides-Extra: ocr
25
+ Requires-Dist: pytesseract>=0.3.10; extra == "ocr"
26
+ Provides-Extra: full
27
+ Requires-Dist: pytesseract>=0.3.10; extra == "full"
26
28
  Dynamic: author
27
29
  Dynamic: author-email
28
30
  Dynamic: classifier
@@ -30,6 +32,7 @@ Dynamic: description
30
32
  Dynamic: description-content-type
31
33
  Dynamic: home-page
32
34
  Dynamic: license-file
35
+ Dynamic: provides-extra
33
36
  Dynamic: requires-dist
34
37
  Dynamic: requires-python
35
38
  Dynamic: summary
@@ -78,7 +81,7 @@ Dynamic: summary
78
81
  - Real-time progress tracking
79
82
  - Multi-language UI
80
83
  - Modern, intuitive design
81
- -
84
+
82
85
  ![Screenshot](img/UI_v1.avif)
83
86
 
84
87
  ![How to Use](img/HowToUse.gif)
@@ -90,25 +93,45 @@ Dynamic: summary
90
93
  2. Extract the ZIP file
91
94
  3. Run `SafePDF.exe`
92
95
 
93
- ### Option 2: Run from Source
96
+ ### Option 2: Install from PyPI
94
97
 
95
98
  **Requirements:**
96
- - Python 3.7+
99
+ - Python 3.8+
97
100
  - pip
98
101
 
99
102
  **Installation:**
103
+ ```bash
104
+ # Install from PyPI
105
+ pip install SafePDF
106
+
107
+ # Optional extras
108
+ # OCR support: pip install "SafePDF[ocr]"
109
+ # All optional extras: pip install "SafePDF[full]"
110
+
111
+ # Run the app
112
+ safepdf
113
+ ```
114
+
115
+ ### Option 3: Run from Source
116
+
100
117
  ```bash
101
118
  # Clone the repository
102
119
  git clone https://github.com/mcagriaksoy/SafePDF.git
103
120
  cd SafePDF
104
121
 
105
- # Install dependencies
122
+ # Install core dependencies
106
123
  pip install -r requirements.txt
107
124
 
125
+ # Optional extras
126
+ # OCR support: pip install ".[ocr]"
127
+ # All optional extras: pip install ".[full]"
128
+
108
129
  # Run the application
109
130
  python run_safe_pdf.py
110
131
  ```
111
132
 
133
+ **OCR note:** OCR uses Tesseract. Install the Python extra with `SafePDF[ocr]` and make sure the Tesseract OCR application is installed on your system as well.
134
+
112
135
  ## How to Use
113
136
 
114
137
  1. **Select Operation** - Choose what you want to do (compress, split, merge, etc.)
@@ -141,9 +164,11 @@ Contributions are welcome! Please:
141
164
 
142
165
  ## Support
143
166
 
144
- - Email: [info@safepdf.de](mailto:info@safepdf.de)
167
+ - Website: [safepdf.com](https://safepdf.com)
168
+ - More information is available at [safepdf.com](https://safepdf.com)
169
+ - Email: [info@safepdf.com](mailto:info@safepdf.com)
145
170
  - Report Issues: [GitHub Issues](https://github.com/mcagriaksoy/SafePDF/issues)
146
- - Documentation: [safepdf.de](https://safepdf.de)
171
+ - Documentation: [safepdf.com](https://safepdf.com)
147
172
 
148
173
  ## License
149
174
 
@@ -25,7 +25,7 @@
25
25
 
26
26
  ![SafePDF Interface](img/SafePDF_Ad.avif)
27
27
 
28
- ## Features
28
+ ## Features
29
29
 
30
30
  - **Compress** - Reduce PDF file size with quality control
31
31
  - **Split** - Separate PDFs by pages or custom ranges
@@ -37,13 +37,13 @@
37
37
  - **Extract Text** - Extract plain text from PDFs
38
38
  - **Extract Info** - View PDF metadata and properties
39
39
 
40
- **Interface Features:**
41
- - Drag & drop file selection
42
- - Real-time progress tracking
43
- - Multi-language UI
44
- - Modern, intuitive design
45
- -
46
- ![Screenshot](img/UI_v1.avif)
40
+ **Interface Features:**
41
+ - Drag & drop file selection
42
+ - Real-time progress tracking
43
+ - Multi-language UI
44
+ - Modern, intuitive design
45
+
46
+ ![Screenshot](img/UI_v1.avif)
47
47
 
48
48
  ![How to Use](img/HowToUse.gif)
49
49
 
@@ -54,24 +54,44 @@
54
54
  2. Extract the ZIP file
55
55
  3. Run `SafePDF.exe`
56
56
 
57
- ### Option 2: Run from Source
58
-
59
- **Requirements:**
60
- - Python 3.7+
61
- - pip
62
-
63
- **Installation:**
64
- ```bash
65
- # Clone the repository
66
- git clone https://github.com/mcagriaksoy/SafePDF.git
67
- cd SafePDF
68
-
69
- # Install dependencies
70
- pip install -r requirements.txt
71
-
72
- # Run the application
73
- python run_safe_pdf.py
74
- ```
57
+ ### Option 2: Install from PyPI
58
+
59
+ **Requirements:**
60
+ - Python 3.8+
61
+ - pip
62
+
63
+ **Installation:**
64
+ ```bash
65
+ # Install from PyPI
66
+ pip install SafePDF
67
+
68
+ # Optional extras
69
+ # OCR support: pip install "SafePDF[ocr]"
70
+ # All optional extras: pip install "SafePDF[full]"
71
+
72
+ # Run the app
73
+ safepdf
74
+ ```
75
+
76
+ ### Option 3: Run from Source
77
+
78
+ ```bash
79
+ # Clone the repository
80
+ git clone https://github.com/mcagriaksoy/SafePDF.git
81
+ cd SafePDF
82
+
83
+ # Install core dependencies
84
+ pip install -r requirements.txt
85
+
86
+ # Optional extras
87
+ # OCR support: pip install ".[ocr]"
88
+ # All optional extras: pip install ".[full]"
89
+
90
+ # Run the application
91
+ python run_safe_pdf.py
92
+ ```
93
+
94
+ **OCR note:** OCR uses Tesseract. Install the Python extra with `SafePDF[ocr]` and make sure the Tesseract OCR application is installed on your system as well.
75
95
 
76
96
  ## How to Use
77
97
 
@@ -103,11 +123,13 @@ Contributions are welcome! Please:
103
123
  - Submit pull requests for improvements
104
124
  - Follow existing code style
105
125
 
106
- ## Support
107
-
108
- - Email: [info@safepdf.de](mailto:info@safepdf.de)
109
- - Report Issues: [GitHub Issues](https://github.com/mcagriaksoy/SafePDF/issues)
110
- - Documentation: [safepdf.de](https://safepdf.de)
126
+ ## Support
127
+
128
+ - Website: [safepdf.com](https://safepdf.com)
129
+ - More information is available at [safepdf.com](https://safepdf.com)
130
+ - Email: [info@safepdf.com](mailto:info@safepdf.com)
131
+ - Report Issues: [GitHub Issues](https://github.com/mcagriaksoy/SafePDF/issues)
132
+ - Documentation: [safepdf.com](https://safepdf.com)
111
133
 
112
134
  ## License
113
135
 
@@ -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.0.13"
8
+ __version__ = "1.0.14"
9
9
 
10
10
  __all__ = []
Binary file
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#EAC452"><path d="M200-160v-80h560v80H200Zm0-140-51-321q-2 0-4.5.5t-4.5.5q-25 0-42.5-17.5T80-680q0-25 17.5-42.5T140-740q25 0 42.5 17.5T200-680q0 7-1.5 13t-3.5 11l125 56 125-171q-11-8-18-21t-7-28q0-25 17.5-42.5T480-880q25 0 42.5 17.5T540-820q0 15-7 28t-18 21l125 171 125-56q-2-5-3.5-11t-1.5-13q0-25 17.5-42.5T820-740q25 0 42.5 17.5T880-680q0 25-17.5 42.5T820-620q-2 0-4.5-.5t-4.5-.5l-51 321H200Zm68-80h424l26-167-105 46-133-183-133 183-105-46 26 167Zm212 0Z"/></svg>
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
@@ -84,7 +84,7 @@ class SafePDFController:
84
84
  self.status_callback(message)
85
85
 
86
86
  def select_file(self, file_path):
87
- """Select and validate PDF file(s)"""
87
+ """Select and validate file(s) for the active operation"""
88
88
  if isinstance(file_path, list):
89
89
  self.selected_files = file_path
90
90
  else:
@@ -96,7 +96,10 @@ class SafePDFController:
96
96
  for f in self.selected_files:
97
97
  if not os_path.exists(f):
98
98
  return False, f"File does not exist: {f}"
99
- if not f.lower().endswith(".pdf"):
99
+ if self.selected_operation == "jpg_to_pdf":
100
+ if not f.lower().endswith((".jpg", ".jpeg")):
101
+ return False, f"Please select JPG files only. Invalid: {os_path.basename(f)}"
102
+ elif not f.lower().endswith(".pdf"):
100
103
  return False, f"Please select PDF files only. Invalid: {os_path.basename(f)}"
101
104
 
102
105
  filenames = [os_path.basename(f) for f in self.selected_files]
@@ -115,6 +118,7 @@ class SafePDFController:
115
118
  "compress",
116
119
  "split",
117
120
  "merge",
121
+ "jpg_to_pdf",
118
122
  "to_jpg",
119
123
  "rotate",
120
124
  "repair",
@@ -154,7 +158,17 @@ class SafePDFController:
154
158
  return custom_output_path, None
155
159
 
156
160
  # Default paths with minimal processing
157
- if self.selected_operation in ["compress", "rotate", "repair", "to_word", "to_txt", "to_ocr", "extract_info", "merge"]:
161
+ if self.selected_operation in [
162
+ "compress",
163
+ "rotate",
164
+ "repair",
165
+ "to_word",
166
+ "to_txt",
167
+ "to_ocr",
168
+ "extract_info",
169
+ "merge",
170
+ "jpg_to_pdf",
171
+ ]:
158
172
  base_name = os_path.splitext(self.selected_file)[0]
159
173
  if self.selected_operation == "to_word":
160
174
  return f"{base_name}.docx", None
@@ -168,6 +182,8 @@ class SafePDFController:
168
182
  return f"{base_name}_info.txt", None
169
183
  elif self.selected_operation == "merge":
170
184
  return f"{base_name}_merged.pdf", None
185
+ elif self.selected_operation == "jpg_to_pdf":
186
+ return f"{base_name}.pdf", None
171
187
  else:
172
188
  return f"{base_name}_{self.selected_operation}.pdf", None
173
189
  else:
@@ -218,6 +234,9 @@ class SafePDFController:
218
234
  dpi = int(self.operation_settings.get("dpi", 200))
219
235
  success, message = self.pdf_ops.pdf_to_jpg(self.selected_file, output_dir, dpi)
220
236
 
237
+ elif self.selected_operation == "jpg_to_pdf":
238
+ success, message = self.pdf_ops.jpg_to_pdf(self.selected_file, output_path)
239
+
221
240
  elif self.selected_operation == "merge":
222
241
  # Merge operation: use all selected files
223
242
  if len(self.selected_files) < 2:
@@ -25,7 +25,8 @@ class PDFCompressor:
25
25
  "low": {"dpi": 110, "jpeg_quality": 45},
26
26
  "medium": {"dpi": 140, "jpeg_quality": 60},
27
27
  "high": {"dpi": 180, "jpeg_quality": 75},
28
- "ultra": {"dpi": 220, "jpeg_quality": 88},
28
+ "very_high": {"dpi": 210, "jpeg_quality": 90},
29
+ "ultra": {"dpi": 240, "jpeg_quality": 95},
29
30
  }
30
31
 
31
32
  def __init__(self, progress_callback=None, language_manager=None, atomic_write_file=None, validate_pdf=None):
@@ -165,7 +166,7 @@ class PDFCompressor:
165
166
  Args:
166
167
  input_path: Input PDF file path
167
168
  output_path: Output PDF file path
168
- quality: Compression quality ("low", "medium", "high")
169
+ quality: Compression quality ("low", "medium", "high", "very_high", "ultra")
169
170
 
170
171
  Returns:
171
172
  Tuple of (success, message)
@@ -196,9 +197,7 @@ class PDFCompressor:
196
197
  raster_path = os_path.join(temp_dir, "raster_compressed.pdf")
197
198
 
198
199
  stream_success, _ = self._compress_streams_only(input_path, stream_path)
199
- raster_success, raster_result = self._compress_by_rasterizing(
200
- input_path, raster_path, quality
201
- )
200
+ raster_success, raster_result = self._compress_by_rasterizing(input_path, raster_path, quality)
202
201
  if not raster_success:
203
202
  return False, raster_result
204
203
 
@@ -0,0 +1,234 @@
1
+ """
2
+ PDF OCR conversion module for SafePDF.
3
+ Handles scanned/image-based PDF text extraction using Tesseract OCR.
4
+ """
5
+
6
+ from pathlib import Path
7
+ from typing import Tuple
8
+
9
+ import pypdfium2 as pdfium
10
+
11
+ from SafePDF.logger.logging_config import get_logger
12
+
13
+ try:
14
+ import pytesseract
15
+ from pytesseract import TesseractNotFoundError
16
+ except ImportError:
17
+ pytesseract = None
18
+ TesseractNotFoundError = RuntimeError
19
+
20
+
21
+ class PDFOCRConverter:
22
+ """Class handling OCR-based PDF conversions."""
23
+
24
+ OCR_LANG_MAP = {
25
+ "en": "eng",
26
+ "de": "deu+eng",
27
+ "tr": "tur+eng",
28
+ }
29
+
30
+ def __init__(
31
+ self,
32
+ progress_callback=None,
33
+ status_callback=None,
34
+ language_manager=None,
35
+ atomic_write_file=None,
36
+ atomic_write_via_path=None,
37
+ ):
38
+ self.progress_callback = progress_callback
39
+ self.status_callback = status_callback
40
+ self.language_manager = language_manager
41
+ self._atomic_write_file = atomic_write_file
42
+ self._atomic_write_via_path = atomic_write_via_path
43
+ self._cancel_requested = False
44
+ self.logger = get_logger("SafePDF.PDFOCR")
45
+ self._tesseract_checked = False
46
+
47
+ def update_progress(self, value):
48
+ """Update progress if callback is available."""
49
+ if self.progress_callback:
50
+ self.progress_callback(value)
51
+
52
+ def update_status(self, message):
53
+ """Update live status if callback is available."""
54
+ if self.status_callback:
55
+ self.status_callback(message)
56
+
57
+ def _lang_text(self, key: str, default: str) -> str:
58
+ """Return a localized string when a language manager is available."""
59
+ if self.language_manager:
60
+ return self.language_manager.get(key, default)
61
+ return default
62
+
63
+ def request_cancel(self):
64
+ """Request cancellation of a running operation."""
65
+ self._cancel_requested = True
66
+
67
+ def _get_ocr_langs(self):
68
+ if not self.language_manager:
69
+ return "eng"
70
+ return self.OCR_LANG_MAP.get(getattr(self.language_manager, "lang", "en"), "eng")
71
+
72
+ def _configure_tesseract_binary(self):
73
+ """Use the default Windows Tesseract install if it exists."""
74
+ if pytesseract is None or pytesseract.pytesseract.tesseract_cmd != "tesseract":
75
+ return
76
+
77
+ candidate_paths = [
78
+ Path(r"C:\Program Files\Tesseract-OCR\tesseract.exe"),
79
+ Path(r"C:\Program Files (x86)\Tesseract-OCR\tesseract.exe"),
80
+ ]
81
+ for candidate in candidate_paths:
82
+ if candidate.exists():
83
+ pytesseract.pytesseract.tesseract_cmd = str(candidate)
84
+ return
85
+
86
+ def _ensure_ocr_available(self):
87
+ """Validate that pytesseract is importable and the Tesseract binary is installed."""
88
+ if pytesseract is None:
89
+ raise ImportError("pytesseract is not installed")
90
+
91
+ self._configure_tesseract_binary()
92
+
93
+ if self._tesseract_checked:
94
+ return
95
+
96
+ self.update_status(self._lang_text("ocr_status_loading_model", "Loading OCR model..."))
97
+ pytesseract.get_tesseract_version()
98
+ self._tesseract_checked = True
99
+ self.update_status(self._lang_text("ocr_status_model_ready", "OCR model ready."))
100
+
101
+ def _extract_page_text_chunks(self, input_path: str, dpi: int = 300):
102
+ """Run OCR on each PDF page and return per-page text chunks."""
103
+ pdf = pdfium.PdfDocument(input_path)
104
+ try:
105
+ total_pages = len(pdf)
106
+ ocr_langs = self._get_ocr_langs()
107
+ self._ensure_ocr_available()
108
+ scale = max(dpi, 72) / 72.0
109
+ text_chunks = []
110
+
111
+ for page_num in range(total_pages):
112
+ page_index = page_num + 1
113
+ self.update_status(
114
+ self._lang_text(
115
+ "ocr_status_rendering_page",
116
+ "Rendering page {page} of {total}...",
117
+ ).format(page=page_index, total=total_pages)
118
+ )
119
+ self.update_progress(int((page_num / total_pages) * 100))
120
+ if self._cancel_requested:
121
+ return False, self._lang_text("op_word_cancelled", "Operation cancelled")
122
+
123
+ page = pdf[page_num]
124
+ pil_image = page.render(scale=scale).to_pil()
125
+ self.update_status(
126
+ self._lang_text(
127
+ "ocr_status_recognizing_page",
128
+ "Recognizing text on page {page} of {total}...",
129
+ ).format(page=page_index, total=total_pages)
130
+ )
131
+ text = pytesseract.image_to_string(pil_image, lang=ocr_langs).strip()
132
+ text_chunks.append((page_index, text))
133
+ self.update_progress(int((page_index / total_pages) * 100))
134
+
135
+ return True, text_chunks
136
+ finally:
137
+ pdf.close()
138
+
139
+ def _save_text_output(self, text_chunks, output_path: str):
140
+ """Write OCR text output to a TXT file."""
141
+ self.update_status(self._lang_text("ocr_status_saving_txt", "Saving OCR text as TXT..."))
142
+ text_content = (
143
+ "\n".join(f"--- Page {page_num} ---\n{text.strip()}\n" for page_num, text in text_chunks).strip() + "\n"
144
+ )
145
+
146
+ def _write_text(tmpf):
147
+ tmpf.write(text_content.encode("utf-8"))
148
+
149
+ if self._atomic_write_file:
150
+ self._atomic_write_file(output_path, _write_text)
151
+ else:
152
+ with open(output_path, "wb") as out_file:
153
+ _write_text(out_file)
154
+
155
+ def _save_docx_output(self, text_chunks, output_path: str):
156
+ """Write OCR text output to a DOCX file."""
157
+ self.update_status(self._lang_text("ocr_status_saving_docx", "Saving OCR text as DOCX..."))
158
+ try:
159
+ from docx import Document
160
+ except ImportError:
161
+ return False, self._lang_text(
162
+ "op_docx_unavailable",
163
+ "python-docx not installed. Please install with: pip install python-docx",
164
+ )
165
+
166
+ doc = Document()
167
+ doc.add_heading("OCR Output", level=1)
168
+ for page_num, text in text_chunks:
169
+ doc.add_heading(f"Page {page_num}", level=2)
170
+ doc.add_paragraph(text if text.strip() else "[No text detected on this page]")
171
+
172
+ def _save_docx(tmp_path):
173
+ doc.save(tmp_path)
174
+
175
+ if self._atomic_write_via_path:
176
+ self._atomic_write_via_path(output_path, _save_docx)
177
+ else:
178
+ doc.save(output_path)
179
+ return True, None
180
+
181
+ def pdf_ocr_to_txt(self, input_path: str, output_path: str, dpi: int = 300) -> Tuple[bool, str]:
182
+ """Run OCR on each PDF page and save the extracted text to a TXT file."""
183
+ if not pdfium:
184
+ return False, self._lang_text("op_pdfium_unavailable", "pypdfium2 not available")
185
+
186
+ if pytesseract is None:
187
+ return False, self._lang_text(
188
+ "op_ocr_unavailable",
189
+ "OCR dependencies missing. Install with: pip install SafePDF[ocr] and install Tesseract OCR.",
190
+ )
191
+
192
+ try:
193
+ success, result = self._extract_page_text_chunks(input_path, dpi=dpi)
194
+ if not success:
195
+ return False, result
196
+ self._save_text_output(result, output_path)
197
+
198
+ success_msg = self._lang_text("op_ocr_success", "OCR text extracted to {output_path}")
199
+ return True, success_msg.format(output_path=output_path)
200
+
201
+ except TesseractNotFoundError:
202
+ return False, self._lang_text("op_ocr_engine_missing", "OCR engine not found.")
203
+ except Exception as e:
204
+ self.logger.error("OCR conversion failed", exc_info=True)
205
+ error_msg = self._lang_text("op_ocr_failed", "PDF OCR failed: {error}")
206
+ return False, error_msg.format(error=str(e))
207
+
208
+ def pdf_ocr_to_docx(self, input_path: str, output_path: str, dpi: int = 300) -> Tuple[bool, str]:
209
+ """Run OCR on each PDF page and save the extracted text to a DOCX file."""
210
+ if not pdfium:
211
+ return False, self._lang_text("op_pdfium_unavailable", "pypdfium2 not available")
212
+
213
+ if pytesseract is None:
214
+ return False, self._lang_text(
215
+ "op_ocr_unavailable",
216
+ "OCR dependencies missing. Install with: pip install SafePDF[ocr] and install Tesseract OCR.",
217
+ )
218
+
219
+ try:
220
+ success, result = self._extract_page_text_chunks(input_path, dpi=dpi)
221
+ if not success:
222
+ return False, result
223
+ success, error = self._save_docx_output(result, output_path)
224
+ if not success:
225
+ return False, error
226
+
227
+ success_msg = self._lang_text("op_word_success", "PDF converted to DOCX document: {output_path}")
228
+ return True, success_msg.format(output_path=output_path)
229
+ except TesseractNotFoundError:
230
+ return False, self._lang_text("op_ocr_engine_missing", "OCR engine not found.")
231
+ except Exception as e:
232
+ self.logger.error("OCR DOCX conversion failed", exc_info=True)
233
+ error_msg = self._lang_text("op_ocr_failed", "PDF OCR failed: {error}")
234
+ return False, error_msg.format(error=str(e))
@@ -275,7 +275,7 @@ class PDFOperations:
275
275
  Args:
276
276
  input_path: Input PDF file path
277
277
  output_path: Output PDF file path
278
- quality: Compression quality ("low", "medium", "high")
278
+ quality: Compression quality ("low", "medium", "high", "very_high", "ultra")
279
279
 
280
280
  Returns:
281
281
  Tuple of (success, message)
@@ -334,6 +334,65 @@ class PDFOperations:
334
334
  self.jpeg_converter._cancel_requested = self._cancel_requested
335
335
  return self.jpeg_converter.pdf_to_jpg(input_path, output_dir, dpi)
336
336
 
337
+ def jpg_to_pdf(self, input_path: str, output_path: str) -> Tuple[bool, str]:
338
+ """
339
+ Convert a JPG/JPEG image to a single-page PDF.
340
+
341
+ Args:
342
+ input_path: Input image file path
343
+ output_path: Output PDF file path
344
+
345
+ Returns:
346
+ Tuple of (success, message)
347
+ """
348
+ try:
349
+ if not Image:
350
+ return False, self.language_manager.get(
351
+ "op_pil_unavailable", "PIL/Pillow not available"
352
+ ) if self.language_manager else "PIL/Pillow not available"
353
+
354
+ if not os_path.exists(input_path):
355
+ return False, self.language_manager.get(
356
+ "op_input_file_not_exist", "Input file does not exist"
357
+ ) if self.language_manager else "Input file does not exist"
358
+
359
+ self.update_progress(20)
360
+ self._ensure_parent_dir(output_path)
361
+
362
+ with Image.open(input_path) as source_image:
363
+ # PDF export requires an RGB-compatible image; flatten alpha if needed.
364
+ if source_image.mode in ("RGBA", "LA") or (
365
+ source_image.mode == "P" and "transparency" in source_image.info
366
+ ):
367
+ rgba_image = source_image.convert("RGBA")
368
+ flattened = Image.new("RGB", source_image.size, (255, 255, 255))
369
+ flattened.paste(rgba_image, mask=rgba_image.getchannel("A"))
370
+ pdf_image = flattened
371
+ else:
372
+ pdf_image = source_image.convert("RGB")
373
+
374
+ self.update_progress(70)
375
+
376
+ def _write_pdf(tmpf):
377
+ pdf_image.save(tmpf, "PDF", resolution=100.0)
378
+
379
+ self._atomic_write_file(output_path, _write_pdf)
380
+
381
+ self.update_progress(100)
382
+ success_msg = (
383
+ self.language_manager.get("op_jpg_to_pdf_success", "Image converted to PDF successfully")
384
+ if self.language_manager
385
+ else "Image converted to PDF successfully"
386
+ )
387
+ return True, success_msg
388
+ except Exception as e:
389
+ error_msg = (
390
+ self.language_manager.get("op_jpg_to_pdf_failed", "JPG to PDF conversion failed: {error}")
391
+ if self.language_manager
392
+ else "JPG to PDF conversion failed: {error}"
393
+ )
394
+ return False, error_msg.format(error=str(e))
395
+
337
396
  def rotate_pdf(self, input_path: str, output_path: str, angle: int = 90) -> Tuple[bool, str]:
338
397
  """
339
398
  Rotate PDF pages (delegates to PDFRotator)