SafePDF 1.0.12__tar.gz → 1.0.13__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.
- {safepdf-1.0.12/SafePDF.egg-info → safepdf-1.0.13}/PKG-INFO +2 -1
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/__init__.py +1 -1
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/ctrl/safe_pdf_controller.py +84 -34
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/ops/pdf2docx.py +1 -1
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/ops/pdf_compress.py +144 -21
- safepdf-1.0.13/SafePDF/ops/pdf_ocr.py +257 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/ops/pdf_operations.py +41 -2
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/ops/updates.py +71 -71
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/safe_pdf_app.py +13 -3
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/test/test_pro_dialog.py +6 -5
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/text/de/pro_features.txt +2 -1
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/text/de/ui.json +50 -6
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/text/en/pro_features.txt +2 -1
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/text/en/ui.json +50 -6
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/text/tr/pro_features.txt +2 -1
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/text/tr/ui.json +50 -6
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/ui/__init__.py +1 -1
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/ui/common_elements.py +1 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/ui/help_ui.py +1 -1
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/ui/operation_settings.py +149 -16
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/ui/safe_pdf_ui.py +158 -47
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/ui/update_ui.py +36 -36
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/version.txt +6 -6
- {safepdf-1.0.12 → safepdf-1.0.13/SafePDF.egg-info}/PKG-INFO +2 -1
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF.egg-info/SOURCES.txt +1 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF.egg-info/requires.txt +1 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/requirements.txt +2 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/LICENSE +0 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/MANIFEST.in +0 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/README.md +0 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/ctrl/__init__.py +0 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/ctrl/language_manager.py +0 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/logger/__init__.py +0 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/logger/logging_config.py +0 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/ops/__init__.py +0 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/ops/license_manager.py +0 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/ops/pdf2jpeg.py +0 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/ops/pdf_merge.py +0 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/ops/pdf_rotate.py +0 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/ops/pdf_split.py +0 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/test/__init__.py +0 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/test/test_compression.py +0 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/text/de/help_content.txt +0 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/text/de/welcome_content.txt +0 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/text/en/help_content.txt +0 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/text/en/welcome_content.txt +0 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/text/tr/help_content.txt +0 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/text/tr/welcome_content.txt +0 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/ui/language_elements.py +0 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/ui/settings_ui.py +0 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF/ui/tabs_manager.py +0 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF.egg-info/dependency_links.txt +0 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF.egg-info/entry_points.txt +0 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/SafePDF.egg-info/top_level.txt +0 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/setup.cfg +0 -0
- {safepdf-1.0.12 → safepdf-1.0.13}/setup.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: SafePDF
|
|
3
|
-
Version: 1.0.
|
|
3
|
+
Version: 1.0.13
|
|
4
4
|
Summary: A safe PDF manipulation tool
|
|
5
5
|
Home-page: https://github.com/mcagriaksoy/safepdf
|
|
6
6
|
Author: Mehmet Cagri Aksoy
|
|
@@ -22,6 +22,7 @@ Requires-Dist: python-docx>=0.8.11
|
|
|
22
22
|
Requires-Dist: requests>=2.25.0
|
|
23
23
|
Requires-Dist: PyGitHub>=1.55.0
|
|
24
24
|
Requires-Dist: python-gnupg>=0.4.8
|
|
25
|
+
Requires-Dist: easyocr
|
|
25
26
|
Dynamic: author
|
|
26
27
|
Dynamic: author-email
|
|
27
28
|
Dynamic: classifier
|
|
@@ -52,25 +52,36 @@ class SafePDFController:
|
|
|
52
52
|
self._load_pro_status()
|
|
53
53
|
|
|
54
54
|
# PDF operations handler
|
|
55
|
-
self.pdf_ops = PDFOperations(
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
55
|
+
self.pdf_ops = PDFOperations(
|
|
56
|
+
progress_callback=progress_callback,
|
|
57
|
+
language_manager=language_manager,
|
|
58
|
+
status_callback=self._emit_status,
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
# Updates handler for GitHub releases and signed keys.
|
|
62
|
+
# Never let update subsystem failures block app startup.
|
|
63
|
+
try:
|
|
64
|
+
self.updates = SafePDFUpdates()
|
|
65
|
+
except Exception as e:
|
|
66
|
+
self.logger.error(f"Failed to initialize update subsystem: {e}", exc_info=True)
|
|
67
|
+
self.updates = None
|
|
64
68
|
|
|
65
69
|
# Callbacks for UI updates
|
|
66
70
|
self.progress_callback = progress_callback
|
|
67
71
|
self.update_ui_callback = None
|
|
68
72
|
self.completion_callback = None
|
|
73
|
+
self.status_callback = None
|
|
69
74
|
|
|
70
|
-
def set_ui_callbacks(self, update_ui_callback=None, completion_callback=None):
|
|
75
|
+
def set_ui_callbacks(self, update_ui_callback=None, completion_callback=None, status_callback=None):
|
|
71
76
|
"""Set callback functions for UI updates"""
|
|
72
77
|
self.update_ui_callback = update_ui_callback
|
|
73
78
|
self.completion_callback = completion_callback
|
|
79
|
+
self.status_callback = status_callback
|
|
80
|
+
|
|
81
|
+
def _emit_status(self, message):
|
|
82
|
+
"""Send a live status update to the UI if available."""
|
|
83
|
+
if self.status_callback and message:
|
|
84
|
+
self.status_callback(message)
|
|
74
85
|
|
|
75
86
|
def select_file(self, file_path):
|
|
76
87
|
"""Select and validate PDF file(s)"""
|
|
@@ -109,6 +120,7 @@ class SafePDFController:
|
|
|
109
120
|
"repair",
|
|
110
121
|
"to_word",
|
|
111
122
|
"to_txt",
|
|
123
|
+
"to_ocr",
|
|
112
124
|
"extract_info",
|
|
113
125
|
]
|
|
114
126
|
if operation in valid_operations:
|
|
@@ -142,12 +154,16 @@ class SafePDFController:
|
|
|
142
154
|
return custom_output_path, None
|
|
143
155
|
|
|
144
156
|
# Default paths with minimal processing
|
|
145
|
-
if self.selected_operation in ["compress", "rotate", "repair", "to_word", "to_txt", "extract_info", "merge"]:
|
|
157
|
+
if self.selected_operation in ["compress", "rotate", "repair", "to_word", "to_txt", "to_ocr", "extract_info", "merge"]:
|
|
146
158
|
base_name = os_path.splitext(self.selected_file)[0]
|
|
147
159
|
if self.selected_operation == "to_word":
|
|
148
160
|
return f"{base_name}.docx", None
|
|
149
161
|
elif self.selected_operation == "to_txt":
|
|
150
162
|
return f"{base_name}.txt", None
|
|
163
|
+
elif self.selected_operation == "to_ocr":
|
|
164
|
+
ocr_format = self.operation_settings.get("ocr_output_format", "txt")
|
|
165
|
+
extension = ".docx" if ocr_format == "docx" else ".txt"
|
|
166
|
+
return f"{base_name}_ocr{extension}", None
|
|
151
167
|
elif self.selected_operation == "extract_info":
|
|
152
168
|
return f"{base_name}_info.txt", None
|
|
153
169
|
elif self.selected_operation == "merge":
|
|
@@ -224,20 +240,54 @@ class SafePDFController:
|
|
|
224
240
|
|
|
225
241
|
elif self.selected_operation == "to_word":
|
|
226
242
|
# PDF to Word conversion
|
|
227
|
-
|
|
228
|
-
|
|
243
|
+
self._emit_status(
|
|
244
|
+
self.language_manager.get(
|
|
245
|
+
"status_to_word_running",
|
|
246
|
+
"Converting PDF text to DOCX...",
|
|
247
|
+
)
|
|
248
|
+
if self.language_manager
|
|
249
|
+
else "Converting PDF text to DOCX..."
|
|
250
|
+
)
|
|
229
251
|
success, message = self.pdf_ops.pdf_to_word(self.selected_file, output_path)
|
|
230
252
|
|
|
231
253
|
elif self.selected_operation == "to_txt":
|
|
232
254
|
# PDF to TXT conversion
|
|
233
|
-
|
|
234
|
-
|
|
255
|
+
self._emit_status(
|
|
256
|
+
self.language_manager.get(
|
|
257
|
+
"status_to_txt_running",
|
|
258
|
+
"Extracting selectable text from PDF...",
|
|
259
|
+
)
|
|
260
|
+
if self.language_manager
|
|
261
|
+
else "Extracting selectable text from PDF..."
|
|
262
|
+
)
|
|
235
263
|
success, message = self.pdf_ops.pdf_to_txt(self.selected_file, output_path)
|
|
236
264
|
|
|
265
|
+
elif self.selected_operation == "to_ocr":
|
|
266
|
+
# OCR-based PDF conversion
|
|
267
|
+
self._emit_status(
|
|
268
|
+
self.language_manager.get(
|
|
269
|
+
"status_to_ocr_running",
|
|
270
|
+
"Preparing OCR engine...",
|
|
271
|
+
)
|
|
272
|
+
if self.language_manager
|
|
273
|
+
else "Preparing OCR engine..."
|
|
274
|
+
)
|
|
275
|
+
ocr_format = self.operation_settings.get("ocr_output_format", "txt")
|
|
276
|
+
if ocr_format == "docx":
|
|
277
|
+
success, message = self.pdf_ops.pdf_ocr_to_docx(self.selected_file, output_path)
|
|
278
|
+
else:
|
|
279
|
+
success, message = self.pdf_ops.pdf_ocr_to_txt(self.selected_file, output_path)
|
|
280
|
+
|
|
237
281
|
elif self.selected_operation == "extract_info":
|
|
238
282
|
# Extract hidden information
|
|
239
|
-
|
|
240
|
-
|
|
283
|
+
self._emit_status(
|
|
284
|
+
self.language_manager.get(
|
|
285
|
+
"status_extract_info_running",
|
|
286
|
+
"Extracting PDF metadata and hidden information...",
|
|
287
|
+
)
|
|
288
|
+
if self.language_manager
|
|
289
|
+
else "Extracting PDF metadata and hidden information..."
|
|
290
|
+
)
|
|
241
291
|
success, message = self.pdf_ops.extract_hidden_info(self.selected_file, output_path)
|
|
242
292
|
|
|
243
293
|
# Store current output location
|
|
@@ -340,23 +390,23 @@ class SafePDFController:
|
|
|
340
390
|
"""Check if pro features are enabled, optionally for a specific feature"""
|
|
341
391
|
return self.is_pro_activated
|
|
342
392
|
|
|
343
|
-
def check_for_updates(self):
|
|
344
|
-
"""Check for available updates from GitHub Releases"""
|
|
345
|
-
if not self.updates:
|
|
346
|
-
return {"available": False, "error": "updates_unavailable"}
|
|
347
|
-
return self.updates.check_for_updates()
|
|
348
|
-
|
|
349
|
-
def download_update(self, download_url, signature_url):
|
|
350
|
-
"""Download and verify an update"""
|
|
351
|
-
if not self.updates:
|
|
352
|
-
return False, None, "Update subsystem unavailable."
|
|
353
|
-
return self.updates.download_and_verify(download_url, signature_url)
|
|
354
|
-
|
|
355
|
-
def get_release_info(self, version=None):
|
|
356
|
-
"""Get information about a specific release"""
|
|
357
|
-
if not self.updates:
|
|
358
|
-
return None
|
|
359
|
-
return self.updates.get_release_info(version)
|
|
393
|
+
def check_for_updates(self):
|
|
394
|
+
"""Check for available updates from GitHub Releases"""
|
|
395
|
+
if not self.updates:
|
|
396
|
+
return {"available": False, "error": "updates_unavailable"}
|
|
397
|
+
return self.updates.check_for_updates()
|
|
398
|
+
|
|
399
|
+
def download_update(self, download_url, signature_url):
|
|
400
|
+
"""Download and verify an update"""
|
|
401
|
+
if not self.updates:
|
|
402
|
+
return False, None, "Update subsystem unavailable."
|
|
403
|
+
return self.updates.download_and_verify(download_url, signature_url)
|
|
404
|
+
|
|
405
|
+
def get_release_info(self, version=None):
|
|
406
|
+
"""Get information about a specific release"""
|
|
407
|
+
if not self.updates:
|
|
408
|
+
return None
|
|
409
|
+
return self.updates.get_release_info(version)
|
|
360
410
|
|
|
361
411
|
def apply_settings(self, settings_dict):
|
|
362
412
|
"""Apply application settings"""
|
|
@@ -88,7 +88,7 @@ class PDFToWordConverter:
|
|
|
88
88
|
) if self.language_manager else "Operation cancelled"
|
|
89
89
|
|
|
90
90
|
page = reader.pages[page_num]
|
|
91
|
-
text = page.extract_text()
|
|
91
|
+
text = page.extract_text() or ""
|
|
92
92
|
|
|
93
93
|
# Add page content to document
|
|
94
94
|
doc.add_heading(f"Page {page_num + 1}", level=1)
|
|
@@ -6,9 +6,11 @@ Handles all PDF compression operations
|
|
|
6
6
|
import tkinter as tk
|
|
7
7
|
from os import path as os_path
|
|
8
8
|
from pathlib import Path
|
|
9
|
+
from tempfile import TemporaryDirectory
|
|
9
10
|
from tkinter import Button, Label, Toplevel, messagebox
|
|
10
11
|
from typing import Tuple
|
|
11
12
|
|
|
13
|
+
import pypdfium2 as pdfium
|
|
12
14
|
from PIL import Image, ImageTk
|
|
13
15
|
from PyPDF2 import PdfReader, PdfWriter
|
|
14
16
|
|
|
@@ -19,6 +21,13 @@ from SafePDF.ui.common_elements import CommonElements
|
|
|
19
21
|
class PDFCompressor:
|
|
20
22
|
"""Class handling PDF compression operations"""
|
|
21
23
|
|
|
24
|
+
QUALITY_PROFILES = {
|
|
25
|
+
"low": {"dpi": 110, "jpeg_quality": 45},
|
|
26
|
+
"medium": {"dpi": 140, "jpeg_quality": 60},
|
|
27
|
+
"high": {"dpi": 180, "jpeg_quality": 75},
|
|
28
|
+
"ultra": {"dpi": 220, "jpeg_quality": 88},
|
|
29
|
+
}
|
|
30
|
+
|
|
22
31
|
def __init__(self, progress_callback=None, language_manager=None, atomic_write_file=None, validate_pdf=None):
|
|
23
32
|
"""
|
|
24
33
|
Initialize PDF compressor
|
|
@@ -45,6 +54,110 @@ class PDFCompressor:
|
|
|
45
54
|
"""Request cancellation of a running operation."""
|
|
46
55
|
self._cancel_requested = True
|
|
47
56
|
|
|
57
|
+
def _compress_streams_only(self, input_path: str, output_path: str) -> Tuple[bool, str]:
|
|
58
|
+
"""Try lightweight stream compression first."""
|
|
59
|
+
reader = PdfReader(input_path)
|
|
60
|
+
writer = PdfWriter()
|
|
61
|
+
total_pages = len(reader.pages)
|
|
62
|
+
|
|
63
|
+
for i, page in enumerate(reader.pages):
|
|
64
|
+
if self._cancel_requested:
|
|
65
|
+
return False, self.language_manager.get(
|
|
66
|
+
"op_cancelled", "Operation cancelled by user"
|
|
67
|
+
) if self.language_manager else "Operation cancelled by user"
|
|
68
|
+
try:
|
|
69
|
+
page.compress_content_streams()
|
|
70
|
+
except Exception:
|
|
71
|
+
pass
|
|
72
|
+
writer.add_page(page)
|
|
73
|
+
self.update_progress(10 + (25 * i // max(1, total_pages)))
|
|
74
|
+
|
|
75
|
+
def _write_compressed(tmpf):
|
|
76
|
+
writer.write(tmpf)
|
|
77
|
+
|
|
78
|
+
if self._atomic_write_file:
|
|
79
|
+
self._atomic_write_file(output_path, _write_compressed)
|
|
80
|
+
else:
|
|
81
|
+
with open(output_path, "wb") as f:
|
|
82
|
+
_write_compressed(f)
|
|
83
|
+
|
|
84
|
+
return True, output_path
|
|
85
|
+
|
|
86
|
+
def _compress_by_rasterizing(self, input_path: str, output_path: str, quality: str) -> Tuple[bool, str]:
|
|
87
|
+
"""Rebuild the PDF from downsampled JPEG page renders."""
|
|
88
|
+
if not pdfium or not Image:
|
|
89
|
+
return False, self.language_manager.get(
|
|
90
|
+
"op_pdfium_unavailable", "pypdfium2 not available"
|
|
91
|
+
) if self.language_manager else "pypdfium2 not available"
|
|
92
|
+
|
|
93
|
+
profile = self.QUALITY_PROFILES.get(quality, self.QUALITY_PROFILES["medium"])
|
|
94
|
+
dpi = profile["dpi"]
|
|
95
|
+
jpeg_quality = profile["jpeg_quality"]
|
|
96
|
+
scale = max(dpi, 72) / 72.0
|
|
97
|
+
|
|
98
|
+
with TemporaryDirectory(prefix="safepdf_compress_") as temp_dir:
|
|
99
|
+
pdf = pdfium.PdfDocument(input_path)
|
|
100
|
+
try:
|
|
101
|
+
total_pages = len(pdf)
|
|
102
|
+
image_paths = []
|
|
103
|
+
|
|
104
|
+
for i in range(total_pages):
|
|
105
|
+
if self._cancel_requested:
|
|
106
|
+
return False, self.language_manager.get(
|
|
107
|
+
"op_cancelled", "Operation cancelled by user"
|
|
108
|
+
) if self.language_manager else "Operation cancelled by user"
|
|
109
|
+
|
|
110
|
+
page = pdf[i]
|
|
111
|
+
pil_image = page.render(scale=scale).to_pil()
|
|
112
|
+
if pil_image.mode != "RGB":
|
|
113
|
+
pil_image = pil_image.convert("RGB")
|
|
114
|
+
|
|
115
|
+
page_path = os_path.join(temp_dir, f"page_{i:04d}.jpg")
|
|
116
|
+
pil_image.save(page_path, "JPEG", quality=jpeg_quality, optimize=True)
|
|
117
|
+
pil_image.close()
|
|
118
|
+
image_paths.append(page_path)
|
|
119
|
+
self.update_progress(35 + (55 * (i + 1) // max(1, total_pages)))
|
|
120
|
+
finally:
|
|
121
|
+
pdf.close()
|
|
122
|
+
|
|
123
|
+
if not image_paths:
|
|
124
|
+
return False, self.language_manager.get(
|
|
125
|
+
"op_invalid_output", "Compression completed but output file is invalid"
|
|
126
|
+
) if self.language_manager else "Compression completed but output file is invalid"
|
|
127
|
+
|
|
128
|
+
images = []
|
|
129
|
+
try:
|
|
130
|
+
for image_path in image_paths:
|
|
131
|
+
image = Image.open(image_path)
|
|
132
|
+
if image.mode != "RGB":
|
|
133
|
+
image = image.convert("RGB")
|
|
134
|
+
images.append(image)
|
|
135
|
+
|
|
136
|
+
first_image, remaining_images = images[0], images[1:]
|
|
137
|
+
|
|
138
|
+
def _write_pdf(tmpf):
|
|
139
|
+
first_image.save(
|
|
140
|
+
tmpf,
|
|
141
|
+
"PDF",
|
|
142
|
+
save_all=True,
|
|
143
|
+
append_images=remaining_images,
|
|
144
|
+
resolution=dpi,
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
if self._atomic_write_file:
|
|
148
|
+
self._atomic_write_file(output_path, _write_pdf)
|
|
149
|
+
else:
|
|
150
|
+
with open(output_path, "wb") as f:
|
|
151
|
+
_write_pdf(f)
|
|
152
|
+
finally:
|
|
153
|
+
for image in images:
|
|
154
|
+
try:
|
|
155
|
+
image.close()
|
|
156
|
+
except Exception:
|
|
157
|
+
pass
|
|
158
|
+
|
|
159
|
+
return True, output_path
|
|
160
|
+
|
|
48
161
|
def compress_pdf(self, input_path: str, output_path: str, quality: str = "medium") -> Tuple[bool, str]:
|
|
49
162
|
"""
|
|
50
163
|
Compress PDF file
|
|
@@ -76,31 +189,41 @@ class PDFCompressor:
|
|
|
76
189
|
"op_invalid_pdf", "Input file is not a valid PDF"
|
|
77
190
|
) if self.language_manager else "Input file is not a valid PDF"
|
|
78
191
|
|
|
79
|
-
# Use PyPDF2 stream compression approach
|
|
80
192
|
self.update_progress(10)
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
193
|
+
|
|
194
|
+
with TemporaryDirectory(prefix="safepdf_compress_compare_") as temp_dir:
|
|
195
|
+
stream_path = os_path.join(temp_dir, "stream_compressed.pdf")
|
|
196
|
+
raster_path = os_path.join(temp_dir, "raster_compressed.pdf")
|
|
197
|
+
|
|
198
|
+
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
|
+
)
|
|
202
|
+
if not raster_success:
|
|
203
|
+
return False, raster_result
|
|
204
|
+
|
|
205
|
+
candidates = []
|
|
206
|
+
if stream_success and os_path.exists(stream_path):
|
|
207
|
+
candidates.append(stream_path)
|
|
208
|
+
if os_path.exists(raster_path):
|
|
209
|
+
candidates.append(raster_path)
|
|
210
|
+
|
|
211
|
+
if not candidates:
|
|
86
212
|
return False, self.language_manager.get(
|
|
87
|
-
"
|
|
88
|
-
) if self.language_manager else "
|
|
89
|
-
try:
|
|
90
|
-
page.compress_content_streams()
|
|
91
|
-
except Exception:
|
|
92
|
-
pass
|
|
93
|
-
writer.add_page(page)
|
|
94
|
-
self.update_progress(10 + (80 * i // max(1, total_pages)))
|
|
213
|
+
"op_invalid_output", "Compression completed but output file is invalid"
|
|
214
|
+
) if self.language_manager else "Compression completed but output file is invalid"
|
|
95
215
|
|
|
96
|
-
|
|
97
|
-
writer.write(tmpf)
|
|
216
|
+
best_output = min(candidates, key=os_path.getsize)
|
|
98
217
|
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
218
|
+
def _copy_best(tmpf):
|
|
219
|
+
with open(best_output, "rb") as src:
|
|
220
|
+
tmpf.write(src.read())
|
|
221
|
+
|
|
222
|
+
if self._atomic_write_file:
|
|
223
|
+
self._atomic_write_file(output_path, _copy_best)
|
|
224
|
+
else:
|
|
225
|
+
with open(output_path, "wb") as f:
|
|
226
|
+
_copy_best(f)
|
|
104
227
|
|
|
105
228
|
self.update_progress(100)
|
|
106
229
|
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
"""
|
|
2
|
+
PDF OCR conversion module for SafePDF.
|
|
3
|
+
Handles scanned/image-based PDF text extraction using EasyOCR.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import warnings
|
|
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 easyocr
|
|
15
|
+
import numpy as np
|
|
16
|
+
except ImportError:
|
|
17
|
+
easyocr = None
|
|
18
|
+
np = None
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class PDFOCRConverter:
|
|
22
|
+
"""Class handling OCR-based PDF conversions."""
|
|
23
|
+
|
|
24
|
+
OCR_LANG_MAP = {
|
|
25
|
+
"en": ["en"],
|
|
26
|
+
"de": ["de", "en"],
|
|
27
|
+
"tr": ["tr", "en"],
|
|
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._easyocr_readers = {}
|
|
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 request_cancel(self):
|
|
58
|
+
"""Request cancellation of a running operation."""
|
|
59
|
+
self._cancel_requested = True
|
|
60
|
+
|
|
61
|
+
def _get_ocr_langs(self):
|
|
62
|
+
if not self.language_manager:
|
|
63
|
+
return ["en"]
|
|
64
|
+
return self.OCR_LANG_MAP.get(getattr(self.language_manager, "lang", "en"), ["en"])
|
|
65
|
+
|
|
66
|
+
def _get_easyocr_reader(self, langs):
|
|
67
|
+
"""Cache EasyOCR readers because model loading is expensive."""
|
|
68
|
+
lang_key = tuple(langs)
|
|
69
|
+
reader = self._easyocr_readers.get(lang_key)
|
|
70
|
+
if reader is None:
|
|
71
|
+
self.update_status(
|
|
72
|
+
self.language_manager.get("ocr_status_loading_model", "Loading OCR model...")
|
|
73
|
+
if self.language_manager
|
|
74
|
+
else "Loading OCR model..."
|
|
75
|
+
)
|
|
76
|
+
with warnings.catch_warnings():
|
|
77
|
+
warnings.filterwarnings(
|
|
78
|
+
"ignore",
|
|
79
|
+
message=".*pin_memory.*no accelerator is found.*",
|
|
80
|
+
category=UserWarning,
|
|
81
|
+
)
|
|
82
|
+
reader = easyocr.Reader(list(langs), gpu=False)
|
|
83
|
+
self._easyocr_readers[lang_key] = reader
|
|
84
|
+
self.update_status(
|
|
85
|
+
self.language_manager.get("ocr_status_model_ready", "OCR model ready.")
|
|
86
|
+
if self.language_manager
|
|
87
|
+
else "OCR model ready."
|
|
88
|
+
)
|
|
89
|
+
return reader
|
|
90
|
+
|
|
91
|
+
def _extract_page_text_chunks(self, input_path: str, dpi: int = 300):
|
|
92
|
+
"""Run OCR on each PDF page and return per-page text chunks."""
|
|
93
|
+
pdf = pdfium.PdfDocument(input_path)
|
|
94
|
+
try:
|
|
95
|
+
total_pages = len(pdf)
|
|
96
|
+
ocr_langs = self._get_ocr_langs()
|
|
97
|
+
reader = self._get_easyocr_reader(ocr_langs)
|
|
98
|
+
scale = max(dpi, 72) / 72.0
|
|
99
|
+
text_chunks = []
|
|
100
|
+
|
|
101
|
+
for page_num in range(total_pages):
|
|
102
|
+
page_index = page_num + 1
|
|
103
|
+
self.update_status(
|
|
104
|
+
(
|
|
105
|
+
self.language_manager.get(
|
|
106
|
+
"ocr_status_rendering_page",
|
|
107
|
+
"Rendering page {page} of {total}...",
|
|
108
|
+
)
|
|
109
|
+
if self.language_manager
|
|
110
|
+
else "Rendering page {page} of {total}..."
|
|
111
|
+
).format(page=page_index, total=total_pages)
|
|
112
|
+
)
|
|
113
|
+
self.update_progress(int((page_num / total_pages) * 100))
|
|
114
|
+
if self._cancel_requested:
|
|
115
|
+
return False, self.language_manager.get(
|
|
116
|
+
"op_word_cancelled", "Operation cancelled"
|
|
117
|
+
) if self.language_manager else "Operation cancelled"
|
|
118
|
+
|
|
119
|
+
page = pdf[page_num]
|
|
120
|
+
pil_image = page.render(scale=scale).to_pil()
|
|
121
|
+
image_array = np.array(pil_image)
|
|
122
|
+
self.update_status(
|
|
123
|
+
(
|
|
124
|
+
self.language_manager.get(
|
|
125
|
+
"ocr_status_recognizing_page",
|
|
126
|
+
"Recognizing text on page {page} of {total}...",
|
|
127
|
+
)
|
|
128
|
+
if self.language_manager
|
|
129
|
+
else "Recognizing text on page {page} of {total}..."
|
|
130
|
+
).format(page=page_index, total=total_pages)
|
|
131
|
+
)
|
|
132
|
+
results = reader.readtext(image_array, detail=0, paragraph=True)
|
|
133
|
+
text = "\n".join(line.strip() for line in results if line and line.strip())
|
|
134
|
+
text_chunks.append((page_index, text))
|
|
135
|
+
self.update_progress(int((page_index / total_pages) * 100))
|
|
136
|
+
|
|
137
|
+
return True, text_chunks
|
|
138
|
+
finally:
|
|
139
|
+
pdf.close()
|
|
140
|
+
|
|
141
|
+
def _save_text_output(self, text_chunks, output_path: str):
|
|
142
|
+
"""Write OCR text output to a TXT file."""
|
|
143
|
+
self.update_status(
|
|
144
|
+
self.language_manager.get("ocr_status_saving_txt", "Saving OCR text as TXT...")
|
|
145
|
+
if self.language_manager
|
|
146
|
+
else "Saving OCR text as TXT..."
|
|
147
|
+
)
|
|
148
|
+
text_content = "\n".join(
|
|
149
|
+
f"--- Page {page_num} ---\n{text.strip()}\n" for page_num, text in text_chunks
|
|
150
|
+
).strip() + "\n"
|
|
151
|
+
|
|
152
|
+
def _write_text(tmpf):
|
|
153
|
+
tmpf.write(text_content.encode("utf-8"))
|
|
154
|
+
|
|
155
|
+
if self._atomic_write_file:
|
|
156
|
+
self._atomic_write_file(output_path, _write_text)
|
|
157
|
+
else:
|
|
158
|
+
with open(output_path, "wb") as out_file:
|
|
159
|
+
_write_text(out_file)
|
|
160
|
+
|
|
161
|
+
def _save_docx_output(self, text_chunks, output_path: str):
|
|
162
|
+
"""Write OCR text output to a DOCX file."""
|
|
163
|
+
self.update_status(
|
|
164
|
+
self.language_manager.get("ocr_status_saving_docx", "Saving OCR text as DOCX...")
|
|
165
|
+
if self.language_manager
|
|
166
|
+
else "Saving OCR text as DOCX..."
|
|
167
|
+
)
|
|
168
|
+
try:
|
|
169
|
+
from docx import Document
|
|
170
|
+
except ImportError:
|
|
171
|
+
return False, self.language_manager.get(
|
|
172
|
+
"op_docx_unavailable", "python-docx not installed. Please install with: pip install python-docx"
|
|
173
|
+
) if self.language_manager else "python-docx not installed. Please install with: pip install python-docx"
|
|
174
|
+
|
|
175
|
+
doc = Document()
|
|
176
|
+
doc.add_heading("OCR Output", level=1)
|
|
177
|
+
for page_num, text in text_chunks:
|
|
178
|
+
doc.add_heading(f"Page {page_num}", level=2)
|
|
179
|
+
doc.add_paragraph(text if text.strip() else "[No text detected on this page]")
|
|
180
|
+
|
|
181
|
+
def _save_docx(tmp_path):
|
|
182
|
+
doc.save(tmp_path)
|
|
183
|
+
|
|
184
|
+
if self._atomic_write_via_path:
|
|
185
|
+
self._atomic_write_via_path(output_path, _save_docx)
|
|
186
|
+
else:
|
|
187
|
+
doc.save(output_path)
|
|
188
|
+
return True, None
|
|
189
|
+
|
|
190
|
+
def pdf_ocr_to_txt(self, input_path: str, output_path: str, dpi: int = 300) -> Tuple[bool, str]:
|
|
191
|
+
"""Run OCR on each PDF page and save the extracted text to a TXT file."""
|
|
192
|
+
if not pdfium:
|
|
193
|
+
return False, self.language_manager.get(
|
|
194
|
+
"op_pdfium_unavailable", "pypdfium2 not available"
|
|
195
|
+
) if self.language_manager else "pypdfium2 not available"
|
|
196
|
+
|
|
197
|
+
if not easyocr or np is None:
|
|
198
|
+
return False, self.language_manager.get(
|
|
199
|
+
"op_ocr_unavailable", "OCR dependencies missing. Please install with: pip install easyocr"
|
|
200
|
+
) if self.language_manager else "OCR dependencies missing. Please install with: pip install easyocr"
|
|
201
|
+
|
|
202
|
+
try:
|
|
203
|
+
success, result = self._extract_page_text_chunks(input_path, dpi=dpi)
|
|
204
|
+
if not success:
|
|
205
|
+
return False, result
|
|
206
|
+
self._save_text_output(result, output_path)
|
|
207
|
+
|
|
208
|
+
success_msg = (
|
|
209
|
+
self.language_manager.get("op_ocr_success", "OCR text extracted to {output_path}")
|
|
210
|
+
if self.language_manager
|
|
211
|
+
else "OCR text extracted to {output_path}"
|
|
212
|
+
)
|
|
213
|
+
return True, success_msg.format(output_path=output_path)
|
|
214
|
+
|
|
215
|
+
except Exception as e:
|
|
216
|
+
self.logger.error("OCR conversion failed", exc_info=True)
|
|
217
|
+
error_msg = (
|
|
218
|
+
self.language_manager.get("op_ocr_failed", "PDF OCR failed: {error}")
|
|
219
|
+
if self.language_manager
|
|
220
|
+
else "PDF OCR failed: {error}"
|
|
221
|
+
)
|
|
222
|
+
return False, error_msg.format(error=str(e))
|
|
223
|
+
|
|
224
|
+
def pdf_ocr_to_docx(self, input_path: str, output_path: str, dpi: int = 300) -> Tuple[bool, str]:
|
|
225
|
+
"""Run OCR on each PDF page and save the extracted text to a DOCX file."""
|
|
226
|
+
if not pdfium:
|
|
227
|
+
return False, self.language_manager.get(
|
|
228
|
+
"op_pdfium_unavailable", "pypdfium2 not available"
|
|
229
|
+
) if self.language_manager else "pypdfium2 not available"
|
|
230
|
+
|
|
231
|
+
if not easyocr or np is None:
|
|
232
|
+
return False, self.language_manager.get(
|
|
233
|
+
"op_ocr_unavailable", "OCR dependencies missing. Please install with: pip install easyocr"
|
|
234
|
+
) if self.language_manager else "OCR dependencies missing. Please install with: pip install easyocr"
|
|
235
|
+
|
|
236
|
+
try:
|
|
237
|
+
success, result = self._extract_page_text_chunks(input_path, dpi=dpi)
|
|
238
|
+
if not success:
|
|
239
|
+
return False, result
|
|
240
|
+
success, error = self._save_docx_output(result, output_path)
|
|
241
|
+
if not success:
|
|
242
|
+
return False, error
|
|
243
|
+
|
|
244
|
+
success_msg = (
|
|
245
|
+
self.language_manager.get("op_word_success", "PDF converted to DOCX document: {output_path}")
|
|
246
|
+
if self.language_manager
|
|
247
|
+
else "PDF converted to DOCX document: {output_path}"
|
|
248
|
+
)
|
|
249
|
+
return True, success_msg.format(output_path=output_path)
|
|
250
|
+
except Exception as e:
|
|
251
|
+
self.logger.error("OCR DOCX conversion failed", exc_info=True)
|
|
252
|
+
error_msg = (
|
|
253
|
+
self.language_manager.get("op_ocr_failed", "PDF OCR failed: {error}")
|
|
254
|
+
if self.language_manager
|
|
255
|
+
else "PDF OCR failed: {error}"
|
|
256
|
+
)
|
|
257
|
+
return False, error_msg.format(error=str(e))
|