-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtiff_processor.py
More file actions
1701 lines (1396 loc) · 81 KB
/
tiff_processor.py
File metadata and controls
1701 lines (1396 loc) · 81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import time
import shutil
import threading
import platform
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import fitz # PyMuPDF
from PIL import Image, ImageFile
import numpy as np
import cv2
import argparse
import logging
from concurrent.futures import ThreadPoolExecutor, as_completed
import gc # for garbage collection
import traceback
# make PIL handle broken images better
ImageFile.LOAD_TRUNCATED_IMAGES = True
# GPU acceleration detection and setup (will be initialized after logging setup)
GPU_AVAILABLE = False
# setup basic logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s",
handlers=[
logging.FileHandler("tiff_processor.log", encoding="utf-8"),
logging.StreamHandler(sys.stdout)
]
)
# Initialize GPU acceleration after logging is set up
try:
if cv2.cuda.getCudaEnabledDeviceCount() > 0:
GPU_AVAILABLE = True
logging.info(f"GPU acceleration available: {cv2.cuda.getCudaEnabledDeviceCount()} CUDA device(s) detected")
else:
logging.info("No CUDA devices detected, using CPU processing")
except Exception as e:
logging.info(f"GPU acceleration not available: {str(e)}, using CPU processing")
GPU_AVAILABLE = False
def check_folder_stability(folder_path):
"""
Check if folder is stable - wait 5 seconds and see if it changed.
Keeps retrying immediately until stable.
"""
if not os.path.exists(folder_path):
logging.warning(f"Folder does not exist: {folder_path}")
return False
while True: # keep checking until stable
# get initial state
try:
initial_files = os.listdir(folder_path)
initial_size = sum(os.path.getsize(os.path.join(folder_path, f))
for f in initial_files if os.path.isfile(os.path.join(folder_path, f)))
# wait 5 seconds
logging.info(f"Waiting 5 seconds for folder stability: {folder_path}")
time.sleep(5)
# check if folder changed
if not os.path.exists(folder_path):
logging.warning(f"Folder disappeared during stability check: {folder_path}")
return False
current_files = os.listdir(folder_path)
current_size = sum(os.path.getsize(os.path.join(folder_path, f))
for f in current_files if os.path.isfile(os.path.join(folder_path, f)))
if len(initial_files) != len(current_files) or initial_size != current_size:
# changed - immediately try again
logging.info(f"Folder still changing, retrying stability check immediately...")
continue
else:
# unchanged, stable
logging.info(f"Folder is stable, proceeding with processing")
return True
except Exception as e:
logging.error(f"Error checking folder stability: {str(e)}")
return False
def needs_resizing(image_path, target_width=1700, target_height=2200):
"""Check if image already meets target dimensions"""
try:
with Image.open(image_path) as img:
width, height = img.size
# Check if already correct size (either orientation)
if ((width == target_width and height == target_height) or
(width == target_height and height == target_width)):
return False
return True
except Exception:
return True # If we can't check, assume it needs resizing
def resize_image_inplace(file_path, target_width=1700, target_height=2200, target_dpi=200):
"""Resize image in place with retries"""
for attempt in range(3):
try:
with Image.open(file_path) as img:
original_width, original_height = img.size
original_is_landscape = original_width > original_height
# Adjust target based on orientation
if original_is_landscape and target_width < target_height:
target_width, target_height = target_height, target_width
elif not original_is_landscape and target_width > target_height:
target_width, target_height = target_height, target_width
# Calculate scaling
scale = min(target_width / original_width, target_height / original_height)
new_width = int(original_width * scale)
new_height = int(original_height * scale)
# Resize and center
scaled_img = img.resize((new_width, new_height), Image.LANCZOS)
final_img = Image.new('RGB', (target_width, target_height), 'white')
x_offset = (target_width - new_width) // 2
y_offset = (target_height - new_height) // 2
final_img.paste(scaled_img, (x_offset, y_offset))
# Convert to grayscale for TIFF processing
final_img = final_img.convert('L')
# Save as temporary file first (will be processed to TIFF later)
final_img.save(file_path, "JPEG", quality=95, dpi=(target_dpi, target_dpi))
del scaled_img, final_img
gc.collect()
return True
except Exception as e:
if attempt < 2:
time.sleep(1) # 1 second delay before retry
continue
else:
logging.warning(f"Failed to resize {file_path} after 3 attempts: {e}")
return False
return False
def gpu_adaptive_threshold(img_array, use_gpu=True):
"""Apply adaptive thresholding with GPU acceleration if available"""
global GPU_AVAILABLE
if use_gpu and GPU_AVAILABLE:
try:
# Upload to GPU
gpu_img = cv2.cuda_GpuMat()
gpu_img.upload(img_array)
# Apply adaptive threshold on GPU
gpu_result = cv2.cuda.adaptiveThreshold(gpu_img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 15, 5)
# Download result
result = gpu_result.download()
# Clean up GPU memory
gpu_img.release()
gpu_result.release()
return result
except Exception as e:
logging.warning(f"GPU adaptive threshold failed, falling back to CPU: {str(e)}")
# Fall through to CPU processing
# CPU fallback
return cv2.adaptiveThreshold(img_array, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 15, 5)
def gpu_resize(img_array, new_size, use_gpu=True):
"""Resize image with GPU acceleration if available"""
global GPU_AVAILABLE
if use_gpu and GPU_AVAILABLE:
try:
# Upload to GPU
gpu_img = cv2.cuda_GpuMat()
gpu_img.upload(img_array)
# Resize on GPU
gpu_result = cv2.cuda.resize(gpu_img, new_size, interpolation=cv2.INTER_LANCZOS4)
# Download result
result = gpu_result.download()
# Clean up GPU memory
gpu_img.release()
gpu_result.release()
return result
except Exception as e:
logging.warning(f"GPU resize failed, falling back to CPU: {str(e)}")
# Fall through to CPU processing
# CPU fallback
return cv2.resize(img_array, new_size, interpolation=cv2.INTER_LANCZOS4)
def gpu_threshold(img_array, thresh_val, max_val, thresh_type, use_gpu=True):
"""Apply threshold with GPU acceleration if available"""
global GPU_AVAILABLE
if use_gpu and GPU_AVAILABLE:
try:
# Upload to GPU
gpu_img = cv2.cuda_GpuMat()
gpu_img.upload(img_array)
# Apply threshold on GPU
gpu_result = cv2.cuda.threshold(gpu_img, thresh_val, max_val, thresh_type)[1]
# Download result
result = gpu_result.download()
# Clean up GPU memory
gpu_img.release()
gpu_result.release()
return result
except Exception as e:
logging.warning(f"GPU threshold failed, falling back to CPU: {str(e)}")
# Fall through to CPU processing
# CPU fallback
return cv2.threshold(img_array, thresh_val, max_val, thresh_type)[1]
def gpu_process_image_pipeline(img_array, target_size=None, is_dark=False, use_gpu=True):
"""Process entire image pipeline on GPU to minimize transfers"""
global GPU_AVAILABLE
if use_gpu and GPU_AVAILABLE:
try:
# Upload to GPU once
gpu_img = cv2.cuda_GpuMat()
gpu_img.upload(img_array)
# Resize on GPU if needed
if target_size is not None:
gpu_img = cv2.cuda.resize(gpu_img, target_size, interpolation=cv2.INTER_LANCZOS4)
# Apply thresholding on GPU
if is_dark:
gpu_result = cv2.cuda.threshold(gpu_img, 40, 255, cv2.THRESH_BINARY)[1]
else:
gpu_result = cv2.cuda.adaptiveThreshold(gpu_img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 15, 5)
# Download final result
result = gpu_result.download()
# Clean up GPU memory
gpu_img.release()
gpu_result.release()
return result
except Exception as e:
logging.warning(f"GPU pipeline processing failed, falling back to CPU: {str(e)}")
# Fall through to CPU processing
# CPU fallback - process entire pipeline
if target_size is not None:
img_array = cv2.resize(img_array, target_size, interpolation=cv2.INTER_LANCZOS4)
if is_dark:
return cv2.threshold(img_array, 40, 255, cv2.THRESH_BINARY)[1]
else:
return cv2.adaptiveThreshold(img_array, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 15, 5)
def parse_args():
parser = argparse.ArgumentParser(description="TIFF Processor for PDFs and JPEGs")
parser.add_argument('--watch-dir', required=True, help='Directory to watch for PDF/JPEG folders')
parser.add_argument('--output-dir', required=True, help='Output directory for processed folders')
parser.add_argument('--max-workers', type=int, default=1, help='Maximum number of worker threads for processing (default: 1)')
parser.add_argument('--dpi', type=int, default=200, help='DPI for TIFF conversion (default: 200)')
return parser.parse_args()
class PDFProcessor:
def __init__(self, watch_directory, output_directory, dpi=200):
self.watch_directory = watch_directory
self.output_directory = output_directory
self.dpi = dpi
self.success_count = 0
self.failure_count = 0
self.processed_folders = set() # track folders we've already processed
self.stable_folders = set() # track folders that have been verified as stable
self.lock = threading.Lock() # lock for thread-safe operations
self.file_locks = {} # for per-PDF locks
self.folder_locks = {} # for per-folder locks
def _validate_tiff(self, file_path):
"""check if tiff file is valid and can be opened with write completion verification"""
try:
# Wait for file write completion with multiple checks
max_wait_attempts = 10
wait_interval = 0.5
for attempt in range(max_wait_attempts):
# Check if file exists
if not os.path.exists(file_path):
if attempt < max_wait_attempts - 1:
time.sleep(wait_interval)
continue
else:
logging.error(f"TIFF file {file_path} doesn't exist after {max_wait_attempts} attempts")
return False
# Check file size
try:
file_size = os.path.getsize(file_path)
if file_size == 0:
if attempt < max_wait_attempts - 1:
time.sleep(wait_interval)
continue
else:
logging.error(f"TIFF file {file_path} is empty after {max_wait_attempts} attempts")
return False
# Check if file size is stable (write completed)
time.sleep(0.1) # Brief pause
stable_size = os.path.getsize(file_path)
if file_size != stable_size:
if attempt < max_wait_attempts - 1:
time.sleep(wait_interval)
continue
else:
logging.error(f"TIFF file {file_path} still being written after {max_wait_attempts} attempts")
return False
except OSError as e:
if attempt < max_wait_attempts - 1:
time.sleep(wait_interval)
continue
else:
logging.error(f"Cannot access TIFF file {file_path}: {str(e)}")
return False
# File exists and has stable size, break out of wait loop
break
# Additional validation delay to ensure write handles are released
time.sleep(0.2)
# Try opening the file multiple times with retries
validation_attempts = 3
for val_attempt in range(validation_attempts):
try:
with Image.open(file_path) as img:
img.verify() # verify instead of load to catch corrupted data
# make sure it's actually a tiff
if img.format != "TIFF":
logging.error(f"File {file_path} is not a valid TIFF format")
return False
return True
except Exception as e:
if val_attempt < validation_attempts - 1:
logging.warning(f"TIFF validation attempt {val_attempt + 1} failed for {file_path}: {str(e)}, retrying...")
time.sleep(0.3)
continue
else:
logging.error(f"Invalid TIFF file {file_path} after {validation_attempts} attempts: {str(e)}")
return False
except Exception as e:
logging.error(f"TIFF validation error for {file_path}: {str(e)}")
return False
def _safe_remove(self, file_path, max_retries=3, retry_delay=1):
"""try to remove a file with retries in case it's locked"""
if not os.path.exists(file_path):
return
for attempt in range(max_retries):
try:
os.remove(file_path)
return
except Exception as e:
if attempt < max_retries - 1:
logging.debug(f"Retry {attempt+1} removing file {file_path}: {str(e)}")
time.sleep(retry_delay)
else:
logging.warning(f"Failed to remove file {file_path}: {str(e)}")
def _convert_page(self, page_or_data, output_path, should_resize=True):
"""convert one pdf page to tiff with opencv adaptive thresholding and group4 compression"""
temp_resize_png = None
try:
# Check if we got page data (bytes) or a page object
if isinstance(page_or_data, bytes):
# Use the page data directly (already extracted) - no temp files needed
nparr = np.frombuffer(page_or_data, np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_GRAYSCALE)
if img is None:
raise ValueError(f"Failed to decode page data")
else:
# Original page object handling (fallback for compatibility)
page = page_or_data
# generate pixmap with our dpi settings
pix = page.get_pixmap(dpi=self.dpi, alpha=False)
# Try memory buffer approach first
try:
img_data = pix.tobytes("png")
nparr = np.frombuffer(img_data, np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_GRAYSCALE)
# Explicitly release pixmap memory
pix = None
# Ensure we got a valid image
if img is None:
raise ValueError("Failed to decode image from memory buffer")
except Exception:
# This shouldn't happen with the new approach, but keep as fallback
raise ValueError("Page object processing failed - should use byte data instead")
# Check if the page is predominantly dark before processing
avg_brightness = np.mean(img)
is_dark_page = avg_brightness < 50
# Determine target size if resizing is needed
target_size = None
if should_resize:
# Get current dimensions
height, width = img.shape
original_is_landscape = width > height
# Set target dimensions based on orientation
target_width = 1700
target_height = 2200
if original_is_landscape and target_width < target_height:
target_width, target_height = target_height, target_width
elif not original_is_landscape and target_width > target_height:
target_width, target_height = target_height, target_width
# Calculate scaling
scale = min(target_width / width, target_height / height)
new_width = int(width * scale)
new_height = int(height * scale)
target_size = (new_width, new_height)
if is_dark_page:
logging.info(f"Detected predominantly dark page, using special processing")
# Use GPU pipeline for resize + threshold in one GPU upload/download
resized_binary = gpu_process_image_pipeline(img, target_size, is_dark_page)
# Create final image with padding
final_img = np.full((target_height, target_width), 255, dtype=np.uint8) # White background
# Calculate centering offsets
y_offset = (target_height - new_height) // 2
x_offset = (target_width - new_width) // 2
# Place resized image in center
final_img[y_offset:y_offset+new_height, x_offset:x_offset+new_width] = resized_binary
# Update binary to the final padded version
binary = final_img
else:
# No resize needed, just apply thresholding
if is_dark_page:
logging.info(f"Detected predominantly dark page, using special processing")
binary = gpu_threshold(img, 40, 255, cv2.THRESH_BINARY)
else:
binary = gpu_adaptive_threshold(img)
# Free memory
img = None
# convert to pil for saving with group 4 compression
binary_img = Image.fromarray(binary).convert('1')
binary = None
# Create temporary file first to avoid race conditions
temp_output = output_path + ".tmp"
# save with group4 compression to temp file
binary_img.save(temp_output, "TIFF", compression="group4", dpi=(self.dpi, self.dpi))
binary_img = None
# Force garbage collection
gc.collect()
# Brief delay to ensure write completion
time.sleep(0.05)
# Atomically move temp file to final location
try:
if os.path.exists(output_path):
os.remove(output_path)
shutil.move(temp_output, output_path)
except Exception as e:
if os.path.exists(temp_output):
os.remove(temp_output)
raise e
# verify the tiff is good
if not self._validate_tiff(output_path):
raise ValueError(f"TIFF validation failed for {output_path}")
return True
except Exception as e:
logging.error(f"PDF page conversion failed: {str(e)}")
if os.path.exists(output_path):
self._safe_remove(output_path)
return False
finally:
# Clean up any temp files if they were created (shouldn't happen with new approach)
if temp_resize_png and os.path.exists(temp_resize_png):
self._safe_remove(temp_resize_png)
def _convert_jpeg_to_tiff(self, jpeg_path, output_path, should_resize=True):
"""convert a jpeg file to tiff using opencv adaptive thresholding with group4 compression - NO TEMP FILES"""
try:
# Normalize paths
jpeg_path = os.path.normpath(jpeg_path)
output_path = os.path.normpath(output_path)
# Check if file exists
if not os.path.exists(jpeg_path):
logging.error(f"JPEG file does not exist: {jpeg_path}")
return False
# Check if output already exists in a valid form
if os.path.exists(output_path):
# Check file size first - if it's 0 bytes, remove it
try:
existing_size = os.path.getsize(output_path)
if existing_size == 0:
logging.warning(f"Removing empty TIFF file: {output_path}")
self._safe_remove(output_path)
elif existing_size < 100: # TIFF files should be at least 100 bytes
logging.warning(f"Removing suspiciously small TIFF file ({existing_size} bytes): {output_path}")
self._safe_remove(output_path)
elif self._validate_tiff(output_path):
logging.info(f"Valid TIFF already exists at {output_path}, skipping conversion")
return True
else:
# Remove invalid output file
logging.warning(f"Removing invalid existing TIFF: {output_path}")
self._safe_remove(output_path)
except OSError as e:
logging.warning(f"Error checking existing TIFF file {output_path}: {str(e)}")
self._safe_remove(output_path)
# Load and process image entirely in memory
with Image.open(jpeg_path) as img:
# Convert to RGB if not already
if img.mode != 'RGB':
img = img.convert('RGB')
# Handle resizing in memory if needed
if should_resize:
original_width, original_height = img.size
original_is_landscape = original_width > original_height
# Set target dimensions based on orientation
target_width = 1700
target_height = 2200
if original_is_landscape and target_width < target_height:
target_width, target_height = target_height, target_width
elif not original_is_landscape and target_width > target_height:
target_width, target_height = target_height, target_width
# Calculate scaling
scale = min(target_width / original_width, target_height / original_height)
new_width = int(original_width * scale)
new_height = int(original_height * scale)
# Resize image in memory
img = img.resize((new_width, new_height), Image.LANCZOS)
# Create final image with white background
final_img = Image.new('RGB', (target_width, target_height), 'white')
# Calculate centering offsets
x_offset = (target_width - new_width) // 2
y_offset = (target_height - new_height) // 2
# Paste resized image in center
final_img.paste(img, (x_offset, y_offset))
# Update img to the final resized version
img = final_img
# Convert to grayscale for OpenCV processing
img = img.convert('L')
# Convert PIL image to numpy array for OpenCV
img_array = np.array(img)
# Process with OpenCV thresholding
avg_brightness = np.mean(img_array)
is_dark_image = avg_brightness < 50
if is_dark_image:
logging.info(f"Detected predominantly dark JPEG, using special processing")
binary = gpu_threshold(img_array, 40, 255, cv2.THRESH_BINARY)
else:
binary = gpu_adaptive_threshold(img_array)
# Convert to PIL and save to temp file first
binary_img = Image.fromarray(binary).convert('1')
temp_output = output_path + ".tmp"
binary_img.save(temp_output, "TIFF", compression="group4", dpi=(self.dpi, self.dpi))
# Clean up memory
img_array = None
binary = None
binary_img = None
gc.collect()
# Brief delay to ensure write completion
time.sleep(0.05)
# Atomically move temp file to final location
try:
if os.path.exists(output_path):
os.remove(output_path)
shutil.move(temp_output, output_path)
except Exception as e:
if os.path.exists(temp_output):
os.remove(temp_output)
raise e
# Validate the final output
if not self._validate_tiff(output_path):
raise ValueError("TIFF validation failed")
return True
except Exception as e:
logging.error(f"JPEG to TIFF conversion failed for {jpeg_path}: {str(e)}")
if os.path.exists(output_path):
self._safe_remove(output_path)
return False
def process_jpeg(self, jpeg_path):
"""process a single jpeg file to tiff - must succeed"""
# Normalize the path for consistent locking
jpeg_path = os.path.normpath(jpeg_path)
# Create file lock if it doesn't exist
if jpeg_path not in self.file_locks:
self.file_locks[jpeg_path] = threading.Lock()
# Lock this specific JPEG file for exclusive access
with self.file_locks[jpeg_path]:
try:
logging.info(f"Processing jpeg: {jpeg_path}")
# Check if folder wants resizing
folder_name = os.path.basename(os.path.dirname(jpeg_path))
should_resize = not folder_name.lower().endswith('--noresize')
# Check if output already exists (from a previous run)
output_path = jpeg_path.rsplit('.', 1)[0] + '.tif'
if os.path.exists(output_path):
# Check file size first - if it's 0 bytes, remove it
try:
existing_size = os.path.getsize(output_path)
if existing_size == 0:
logging.warning(f"Removing empty TIFF file: {output_path}")
self._safe_remove(output_path)
elif existing_size < 100: # TIFF files should be at least 100 bytes
logging.warning(f"Removing suspiciously small TIFF file ({existing_size} bytes): {output_path}")
self._safe_remove(output_path)
elif self._validate_tiff(output_path):
logging.info(f"TIFF already exists and is valid, skipping conversion: {output_path}")
# Still count this as a success
with self.lock:
self.success_count += 1
# CRITICAL: Force handle release before attempting deletion
gc.collect()
time.sleep(0.5) # Give time for handles to release
# Remove the JPEG since TIFF already exists
removal_success = self._safe_remove_with_retries(jpeg_path, max_retries=5, retry_delay=2)
if not removal_success:
logging.error(f"CRITICAL: Failed to remove JPEG after validation: {jpeg_path}")
return False
return True
else:
# Remove invalid output file
logging.warning(f"Removing invalid existing TIFF: {output_path}")
self._safe_remove(output_path)
except OSError as e:
logging.warning(f"Error checking existing TIFF file {output_path}: {str(e)}")
self._safe_remove(output_path)
# Attempt conversion with retries
attempt = 0
success = False
while not success and attempt < 5:
attempt += 1
if attempt > 1:
logging.warning(f"Retry attempt {attempt} for jpeg: {jpeg_path}")
time.sleep(1)
try:
success = self._convert_jpeg_to_tiff(jpeg_path, output_path, should_resize)
# Verify the file exists and is valid
if success and os.path.exists(output_path) and self._validate_tiff(output_path):
# Conversion worked, break out of retry loop
break
else:
success = False
except Exception as e:
logging.error(f"Attempt {attempt} failed: {str(e)}")
success = False
time.sleep(1)
if not success:
logging.error(f"Failed after {attempt} attempts: {jpeg_path}")
return False
# Conversion succeeded
with self.lock:
self.success_count += 1
logging.info(f"Successfully converted jpeg: {jpeg_path}")
# CRITICAL: Force handle release before attempting deletion
gc.collect()
time.sleep(0.5) # Give time for handles to release
# Use the more robust removal method
removal_success = self._safe_remove_with_retries(jpeg_path, max_retries=5, retry_delay=2)
if not removal_success:
logging.error(f"CRITICAL: Failed to remove JPEG after successful conversion: {jpeg_path}")
return False
return True
except Exception as e:
with self.lock:
self.failure_count += 1
logging.error(f"CRITICAL ERROR: jpeg processing failed for {jpeg_path}: {str(e)}")
return False
def _convert_page_with_retries(self, page_data, output_path, page_num, total_pages, should_resize=True):
"""Process a single page with intelligent retries using page data (bytes) instead of page object"""
attempt = 0
max_attempts = 10 # Limit retries to prevent infinite loops
while attempt < max_attempts:
attempt += 1
if attempt > 1:
# Progressive delay: longer waits for more attempts
delay = min(attempt * 0.5, 3.0) # 0.5s, 1s, 1.5s, 2s, 2.5s, 3s, 3s...
logging.warning(f"retry attempt {attempt} for page {page_num} of {total_pages}, waiting {delay}s")
time.sleep(delay)
try:
# Clean up any existing partial file
if os.path.exists(output_path):
self._safe_remove(output_path)
time.sleep(0.1) # Brief pause after cleanup
# process the page using page data (pass bytes directly)
page_success = self._convert_page(page_data, output_path, should_resize)
if page_success and os.path.exists(output_path) and self._validate_tiff(output_path):
# page converted successfully
logging.info(f"successfully converted page {page_num} of {total_pages}")
return True
else:
logging.warning(f"failed attempt {attempt} for page {page_num}")
# Clean up failed attempt
if os.path.exists(output_path):
self._safe_remove(output_path)
except Exception as e:
logging.error(f"error on attempt {attempt} for page {page_num}: {str(e)}")
# Clean up failed attempt
if os.path.exists(output_path):
self._safe_remove(output_path)
# All attempts failed
logging.error(f"CRITICAL: Page {page_num} failed after {max_attempts} attempts")
return False
def process_pdf(self, pdf_path):
"""convert pdf file to tiff files - must convert ALL pages using chunked processing"""
# Create file lock if it doesn't exist
if pdf_path not in self.file_locks:
self.file_locks[pdf_path] = threading.Lock()
# Lock this PDF for exclusive access
with self.file_locks[pdf_path]:
success = True
created_files = []
# Check if folder wants resizing
folder_name = os.path.basename(os.path.dirname(pdf_path))
should_resize = not folder_name.lower().endswith('--noresize')
try:
# Check file size to determine if memory mapping would be beneficial
file_size = os.path.getsize(pdf_path)
# open the pdf file - try to use memory mapping if available
try:
doc = fitz.open(pdf_path, filetype="pdf", memory=file_size > 50_000_000)
except TypeError:
doc = fitz.open(pdf_path)
total_pages = len(doc)
digits = len(str(total_pages)) + 1
base_name = os.path.splitext(os.path.basename(pdf_path))[0]
output_dir = os.path.dirname(pdf_path)
logging.info(f"processing pdf: {pdf_path} ({total_pages} pages)")
# Process in chunks of 10,000 pages
chunk_size = 250
max_workers = min(os.cpu_count() or 4, 4)
for chunk_start in range(0, total_pages, chunk_size):
chunk_end = min(chunk_start + chunk_size, total_pages)
chunk_pages = chunk_end - chunk_start
logging.info(f"Processing chunk {chunk_start//chunk_size + 1}/{(total_pages + chunk_size - 1)//chunk_size}: pages {chunk_start + 1}-{chunk_end}")
# Extract page data for this chunk only
page_data_list = []
output_paths = []
for page_num in range(chunk_start, chunk_end):
try:
page = doc[page_num]
pix = page.get_pixmap(dpi=self.dpi, alpha=False)
page_data = pix.tobytes("png")
page_data_list.append(page_data)
# Generate output path for this page
output_path = os.path.join(output_dir, f"{base_name}_page_{page_num+1:0{digits}d}.tif")
output_paths.append(output_path)
# Explicitly release pixmap and page
pix = None
page = None
except Exception as e:
logging.error(f"Failed to extract page {page_num+1}: {str(e)}")
page_data_list.append(None)
output_paths.append(None)
# Process this chunk with ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=max_workers) as executor:
page_futures = {}
# Submit pages in this chunk for processing
for i, (page_data, output_path) in enumerate(zip(page_data_list, output_paths)):
if page_data is not None and output_path is not None:
page_num = chunk_start + i
future = executor.submit(
self._convert_page_with_retries,
page_data,
output_path,
page_num + 1,
total_pages,
should_resize
)
page_futures[future] = (page_num, output_path)
# Collect results for this chunk
for future in as_completed(page_futures):
page_num, output_path = page_futures[future]
try:
page_success = future.result()
if page_success:
created_files.append(output_path)
with self.lock:
self.success_count += 1
else:
logging.error(f"Failed to process page {page_num+1} despite retries")
success = False
except Exception as e:
logging.error(f"Error processing page {page_num+1}: {str(e)}")
success = False
# Clear chunk data from memory
page_data_list.clear()
page_data_list = None
output_paths = None
# Force garbage collection after each chunk
for _ in range(3):
gc.collect()
time.sleep(0.1)
logging.info(f"Completed chunk {chunk_start//chunk_size + 1}, processed {chunk_pages} pages")
# Close document after all chunks are processed
if doc:
try:
doc.close()
logging.info(f"PDF document closed")
except Exception as e:
logging.warning(f"Error closing PDF document: {str(e)}")
finally:
doc = None
# Final cleanup
for _ in range(5):
gc.collect()
time.sleep(0.5)
# Additional Windows-specific cleanup
if platform.system() == 'Windows':
try:
import ctypes
ctypes.windll.kernel32.SetProcessWorkingSetSize(-1, -1)
time.sleep(2)
except Exception as e:
logging.warning(f"Error with Windows memory management: {str(e)}")
# final status check - all pages must be converted
if len(created_files) == total_pages:
logging.info(f"all {total_pages} pages of {pdf_path} processed successfully")
# Additional wait before PDF deletion
logging.info("Waiting additional time before attempting PDF deletion...")
time.sleep(5)
# Try delete with maximum retries
delete_success = self._safe_remove_with_retries(pdf_path, max_retries=15, retry_delay=5)
if not delete_success:
logging.error(f"Could not delete PDF after multiple attempts: {pdf_path}")
return False
return True
else:
logging.error(f"CRITICAL ERROR: Not all pages converted for {pdf_path}, original preserved")
return False
except Exception as e:
success = False
with self.lock:
self.failure_count += 1
logging.error(f"CRITICAL ERROR: pdf processing failed for {pdf_path}: {str(e)}")
return False
finally:
# Final cleanup in finally block
if 'doc' in locals() and doc:
try:
doc.close()
logging.info(f"PDF document force closed in finally block")
except Exception as e:
logging.warning(f"error closing pdf document in finally: {str(e)}")
finally:
doc = None
# Final garbage collection
for _ in range(3):
gc.collect()
time.sleep(0.5)
def _safe_remove_with_retries(self, file_path, max_retries=5, retry_delay=2):
"""try harder to remove a file with more retries and delay"""
if not os.path.exists(file_path):
return True
for attempt in range(max_retries):
try:
os.remove(file_path)
logging.info(f"Successfully removed file after attempt {attempt+1}: {file_path}")
return True
except Exception as e:
logging.warning(f"Attempt {attempt+1} to remove file failed: {file_path}, Error: {str(e)}")
# Force garbage collection on each attempt
gc.collect()
if attempt < max_retries - 1:
logging.info(f"Waiting {retry_delay} seconds before retry...")
time.sleep(retry_delay)
logging.error(f"Failed to remove file after {max_retries} attempts: {file_path}")
return False
def process_folder(self, folder_path):
"""process all pdfs and jpegs in a folder with proper tracking and chunked processing"""
# Create folder lock if it doesn't exist
if folder_path not in self.folder_locks:
self.folder_locks[folder_path] = threading.Lock()
# Lock this folder for exclusive access