-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1179 lines (981 loc) · 40.9 KB
/
Copy pathmain.py
File metadata and controls
1179 lines (981 loc) · 40.9 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
from __future__ import annotations
import math
import multiprocessing
import os
import queue
import shutil
import subprocess
import sys
import threading
import traceback
from concurrent.futures import FIRST_COMPLETED, Future, ProcessPoolExecutor, wait
from dataclasses import dataclass
from pathlib import Path
from typing import Callable, Iterable, List, Sequence, Tuple
import fitz # PyMuPDF
import cv2
import numpy as np
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
A4_W_PT = 595.2755905511812
A4_H_PT = 841.8897637795277
@dataclass
class ConvertOptions:
render_dpi: int = 600
output_dpi: int = 600
margin_mm: float = 24.0
crop_whitespace: bool = True
# Kept for compatibility with older direct callers. The GUI no longer exposes
# these knobs; convert_pdfs builds an automatic runtime plan per job.
worker_count: int = 0
opencv_threads: int = 0
use_gpu_acceleration: bool = False
@dataclass(frozen=True)
class RuntimePlan:
worker_count: int
opencv_threads: int
max_pending: int
use_opencl: bool
status: str
@dataclass(frozen=True)
class PageJob:
order_idx: int
doc_idx: int
doc_count: int
pdf_path: str
page_idx: int
doc_pages: int
@dataclass
class ProcessedPage:
order_idx: int
doc_idx: int
doc_count: int
pdf_path: str
page_idx: int
doc_pages: int
binary: np.ndarray
def mm_to_px(mm: float, dpi: int) -> int:
return max(0, int(round(mm / 25.4 * dpi)))
def reveal_output_file(path: str) -> None:
target = Path(path).expanduser()
if not target.exists():
raise FileNotFoundError(f"输出文件不存在:{target}")
target = target.resolve()
folder = target.parent
if sys.platform.startswith("win"):
subprocess.Popen(["explorer", f"/select,{target}"])
return
if sys.platform == "darwin":
subprocess.Popen(["open", "-R", str(target)])
return
linux_selectors = (
("nautilus", ["nautilus", "--select", str(target)]),
("dolphin", ["dolphin", "--select", str(target)]),
("nemo", ["nemo", str(folder)]),
("caja", ["caja", str(folder)]),
("thunar", ["thunar", str(folder)]),
)
for executable, command in linux_selectors:
if shutil.which(executable):
subprocess.Popen(command)
return
if shutil.which("xdg-open"):
subprocess.Popen(["xdg-open", str(folder)])
return
raise RuntimeError("未找到可用的文件管理器,无法打开输出文件夹")
def _configure_cv2_runtime(opencv_threads: int, use_opencl: bool = False) -> str:
try:
cv2.setUseOptimized(True)
except Exception:
pass
try:
cv2.setNumThreads(max(1, int(opencv_threads)))
except Exception:
pass
if not use_opencl:
try:
cv2.ocl.setUseOpenCL(False)
except Exception:
pass
return "OpenCL/GPU:自动关闭(当前图像管线使用 CPU 更稳定)"
opencl_available = False
try:
opencl_available = bool(cv2.ocl.haveOpenCL())
cv2.ocl.setUseOpenCL(opencl_available)
except Exception:
opencl_available = False
cuda_devices = 0
try:
if hasattr(cv2, "cuda"):
cuda_devices = int(cv2.cuda.getCudaEnabledDeviceCount())
except Exception:
cuda_devices = 0
if opencl_available:
return "GPU/OpenCL:已启用 OpenCV OpenCL 加速"
if cuda_devices > 0:
return "GPU/OpenCL:检测到 CUDA 设备,但当前 OpenCV 未启用 CUDA 算子,已回退 CPU"
return "GPU/OpenCL:当前环境不可用,已回退 CPU"
def _init_worker_runtime(opencv_threads: int, use_opencl: bool) -> None:
_configure_cv2_runtime(opencv_threads, use_opencl)
def _available_memory_bytes() -> int | None:
try:
pages = os.sysconf("SC_AVPHYS_PAGES")
page_size = os.sysconf("SC_PAGE_SIZE")
if pages > 0 and page_size > 0:
return int(pages * page_size)
except (AttributeError, OSError, ValueError):
pass
return None
def _estimate_a4_pixels(dpi: int) -> int:
w = int(round(A4_W_PT / 72.0 * dpi))
h = int(round(A4_H_PT / 72.0 * dpi))
return max(1, w * h)
def _estimate_worker_memory_bytes(dpi: int) -> int:
# Each worker may briefly hold gray, binary, adaptive/global intermediates,
# and optional connected-component labels. Keep the estimate conservative.
pixels = _estimate_a4_pixels(dpi)
return int(pixels * 8 + 160 * 1024 * 1024)
def _auto_runtime_plan(options: ConvertOptions, total_pages: int) -> RuntimePlan:
cpu_count = max(1, os.cpu_count() or 1)
if total_pages <= 1:
pixel_count = _estimate_a4_pixels(options.render_dpi)
opencv_threads = 1 if pixel_count < 4_000_000 else min(cpu_count, 4)
return RuntimePlan(
worker_count=1,
opencv_threads=max(1, opencv_threads),
max_pending=1,
use_opencl=False,
status="单页直通处理",
)
if options.render_dpi >= 500:
worker_ceiling = min(cpu_count, 8)
elif options.render_dpi >= 300:
worker_ceiling = min(cpu_count, 10)
else:
worker_ceiling = min(cpu_count, 12)
target_workers = min(total_pages, worker_ceiling)
available = _available_memory_bytes()
if available:
per_worker = _estimate_worker_memory_bytes(options.render_dpi)
memory_workers = max(1, int(available * 0.65 // per_worker))
target_workers = min(target_workers, memory_workers)
worker_count = max(1, target_workers)
opencv_threads = max(1, min(2, cpu_count // worker_count))
max_pending = worker_count + 1
return RuntimePlan(
worker_count=worker_count,
opencv_threads=opencv_threads,
max_pending=max_pending,
use_opencl=False,
status="多页自动并行处理",
)
def pdf_page_to_gray(page: fitz.Page, dpi: int) -> np.ndarray:
scale = dpi / 72.0
mat = fitz.Matrix(scale, scale)
pix = page.get_pixmap(matrix=mat, colorspace=fitz.csGRAY, alpha=False)
arr = np.frombuffer(pix.samples, dtype=np.uint8)
if pix.n == 1:
gray = arr.reshape(pix.height, pix.width).copy()
else:
arr = arr.reshape(pix.height, pix.width, pix.n)
gray = cv2.cvtColor(arr, cv2.COLOR_RGB2GRAY)
return gray
# =========================
# 二值化与裁边
# =========================
def _otsu_threshold(gray: np.ndarray) -> int:
hist = cv2.calcHist([gray], [0], None, [256], [0, 256]).ravel()
total = float(gray.size)
if total <= 0:
return 127
bins = np.arange(256, dtype=np.float64)
weight_bg = np.cumsum(hist)
weight_fg = total - weight_bg
sum_bg = np.cumsum(hist * bins)
sum_total = float(sum_bg[-1])
valid = (weight_bg > 0) & (weight_fg > 0)
scores = np.full(256, -1.0, dtype=np.float64)
numerator = (sum_total * weight_bg[valid] - sum_bg[valid] * total) ** 2
scores[valid] = numerator / (weight_bg[valid] * weight_fg[valid])
return int(np.argmax(scores))
def _border_mean(gray: np.ndarray) -> float:
h, w = gray.shape
if h == 0 or w == 0:
return 0.0
if h == 1:
return float(gray[0, :].mean())
if w == 1:
return float(gray[:, 0].mean())
total = (
int(gray[0, :].sum())
+ int(gray[-1, :].sum())
+ int(gray[1:-1, 0].sum())
+ int(gray[1:-1, -1].sum())
)
count = 2 * w + 2 * (h - 2)
return float(total / max(1, count))
def _analysis_sample(gray: np.ndarray, max_dim: int = 768) -> np.ndarray:
h, w = gray.shape
longest = max(h, w)
if longest <= max_dim:
return gray
scale = max_dim / float(longest)
size = (max(1, int(round(w * scale))), max(1, int(round(h * scale))))
return cv2.resize(gray, size, interpolation=cv2.INTER_AREA)
def _otsu_polarity(gray: np.ndarray) -> Tuple[int, bool]:
th = _otsu_threshold(gray)
border_mean = _border_mean(gray)
# 边缘通常更接近背景;若不明显,再回退到“大类即背景”的假设。
if abs(border_mean - th) >= 8:
background_is_white = border_mean > th
else:
hist = cv2.calcHist([gray], [0], None, [256], [0, 256]).ravel()
low = int(hist[: th + 1].sum())
high = int(hist[th + 1 :].sum())
background_is_white = high >= low
return int(th), background_is_white
def _needs_adaptive_threshold(gray: np.ndarray, th: int, background_is_white: bool) -> bool:
sample = _analysis_sample(gray)
if sample.size == 0:
return False
if background_is_white:
bg_mask = sample >= min(255, th + 10)
else:
bg_mask = sample <= max(0, th - 10)
bg_coverage = float(np.count_nonzero(bg_mask)) / float(sample.size)
if bg_coverage < 0.35:
return True
bg_values = sample[bg_mask]
bg_std = float(bg_values.std()) if bg_values.size else 0.0
delta = np.abs(sample.astype(np.int16) - int(th))
near_threshold = float(np.count_nonzero(delta <= 22)) / float(sample.size)
return bg_std > 10.0 or near_threshold > 0.025
def _remove_tiny_components(binary: np.ndarray) -> np.ndarray:
# binary: 255=背景, 0=笔迹
inv = 255 - binary
num, labels, stats, _ = cv2.connectedComponentsWithStats(inv, connectivity=8)
if num <= 1:
return binary
h, w = binary.shape
min_area = max(2, int(round(h * w * 0.000002)))
keep_labels = stats[:, cv2.CC_STAT_AREA] >= min_area
keep_labels[0] = False
if bool(np.all(keep_labels[1:])):
return binary
keep = keep_labels[labels]
cleaned = np.empty_like(binary)
cleaned.fill(255)
cleaned[keep] = 0
return cleaned
def binarize_handwriting(gray: np.ndarray) -> np.ndarray:
gray = np.ascontiguousarray(gray)
th, background_is_white = _otsu_polarity(gray)
mode = cv2.THRESH_BINARY if background_is_white else cv2.THRESH_BINARY_INV
_, binary = cv2.threshold(gray, th, 255, mode)
if _needs_adaptive_threshold(gray, th, background_is_white):
# 自适应阈值用于处理局部亮度不均。保持同一极性:255 背景,0 笔迹。
block = max(31, (min(gray.shape[:2]) // 20) | 1)
if block % 2 == 0:
block += 1
adaptive = cv2.adaptiveThreshold(
gray,
255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
mode,
block,
15,
)
# 取“更保守”的交集,减少灰边与阴影进入前景。
cv2.bitwise_or(binary, adaptive, dst=binary)
# 轻微闭运算,修补断裂;再次阈值确保纯黑白。
kernel = np.ones((2, 2), dtype=np.uint8)
binary = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel, iterations=1)
_, binary = cv2.threshold(binary, 127, 255, cv2.THRESH_BINARY)
return binary
def ink_count_axis(binary: np.ndarray, axis: int) -> np.ndarray:
if axis == 1:
sums = cv2.reduce(binary, 1, cv2.REDUCE_SUM, dtype=cv2.CV_32S).ravel()
total = binary.shape[1] * 255
elif axis == 0:
sums = cv2.reduce(binary, 0, cv2.REDUCE_SUM, dtype=cv2.CV_32S).ravel()
total = binary.shape[0] * 255
else:
raise ValueError("axis must be 0 or 1")
return ((total - sums) // 255).astype(np.int32, copy=False)
def crop_whitespace(binary: np.ndarray, pad_px: int = 8) -> np.ndarray:
row_counts = ink_count_axis(binary, axis=1)
col_counts = ink_count_axis(binary, axis=0)
row_threshold = max(1, int(round(binary.shape[1] * 0.0005)))
col_threshold = max(1, int(round(binary.shape[0] * 0.0005)))
rows = np.flatnonzero(row_counts >= row_threshold)
cols = np.flatnonzero(col_counts >= col_threshold)
if rows.size == 0 or cols.size == 0:
return binary
y0 = max(0, int(rows[0]) - pad_px)
y1 = min(binary.shape[0], int(rows[-1]) + 1 + pad_px)
x0 = max(0, int(cols[0]) - pad_px)
x1 = min(binary.shape[1], int(cols[-1]) + 1 + pad_px)
return binary[y0:y1, x0:x1].copy()
# =========================
# 行/片段分析
# =========================
def row_ink_count(binary: np.ndarray) -> np.ndarray:
return ink_count_axis(binary, axis=1)
def detect_bands(binary: np.ndarray) -> List[Tuple[int, int]]:
h, w = binary.shape
counts = row_ink_count(binary)
threshold = max(2, int(round(w * 0.002)))
active = counts >= threshold
bands: List[Tuple[int, int]] = []
start: int | None = None
for i, flag in enumerate(active):
if flag and start is None:
start = i
elif not flag and start is not None:
bands.append((start, i))
start = None
if start is not None:
bands.append((start, h))
if not bands:
return []
# 合并非常近的带,避免同一行被误切开。
merged: List[Tuple[int, int]] = [bands[0]]
merge_gap = max(2, int(round(h * 0.002)))
for y0, y1 in bands[1:]:
py0, py1 = merged[-1]
if y0 - py1 <= merge_gap:
merged[-1] = (py0, y1)
else:
merged.append((y0, y1))
# 过滤极细小噪声带。
filtered: List[Tuple[int, int]] = []
for y0, y1 in merged:
band_h = y1 - y0
band_max = int(counts[y0:y1].max()) if y1 > y0 else 0
if band_h <= 1 and band_max < max(4, threshold * 2):
continue
filtered.append((y0, y1))
return filtered
def best_cut_near_target(counts: np.ndarray, lo: int, hi: int, target: int) -> int:
lo = max(0, lo)
hi = min(len(counts), hi)
if hi - lo <= 1:
return min(max(target, lo), hi)
segment = counts[lo:hi]
min_value = int(segment.min())
candidates = np.where(segment == min_value)[0] + lo
if len(candidates) == 0:
return min(max(target, lo), hi)
return int(candidates[np.argmin(np.abs(candidates - target))])
def split_band_to_fit(
binary: np.ndarray,
band: Tuple[int, int],
max_src_h: int,
) -> List[np.ndarray]:
y0, y1 = band
if y1 - y0 <= max_src_h:
return [binary[y0:y1, :]]
counts = row_ink_count(binary)
parts: List[np.ndarray] = []
cur = y0
while cur < y1:
if cur + max_src_h >= y1:
parts.append(binary[cur:y1, :])
break
target = cur + max_src_h
lo = cur + int(max_src_h * 0.72)
hi = min(y1, cur + int(max_src_h * 1.10))
cut = best_cut_near_target(counts, lo=lo, hi=hi, target=target)
if cut <= cur + 10:
cut = min(y1, target)
parts.append(binary[cur:cut, :])
cur = cut
return [p for p in parts if p.size > 0]
def iter_smart_fragments(
binary: np.ndarray,
content_w_px: int,
content_h_px: int,
) -> Iterable[Tuple[str, object, int]]:
h, w = binary.shape
if h == 0 or w == 0:
return
scale = content_w_px / float(w)
max_src_h = max(32, int(math.floor(content_h_px / scale)))
bands = detect_bands(binary)
if not bands:
return
prev_end = 0
for band in bands:
y0, y1 = band
gap = y0 - prev_end
if gap > 0:
yield ("gap", int(gap), w)
for frag in split_band_to_fit(binary, band, max_src_h=max_src_h):
yield ("fragment", frag, w)
prev_end = y1
tail_gap = h - prev_end
if tail_gap > 0:
yield ("gap", int(tail_gap), w)
# =========================
# 连续排版到 A4
# =========================
class ContinuousPaginator:
def __init__(self, a4_w_px: int, a4_h_px: int, margin_px: int, out_doc: fitz.Document):
self.a4_w_px = a4_w_px
self.a4_h_px = a4_h_px
self.margin_px = margin_px
self.out_doc = out_doc
self.content_w_px = a4_w_px - 2 * margin_px
self.content_h_px = a4_h_px - 2 * margin_px
if self.content_w_px <= 0 or self.content_h_px <= 0:
raise ValueError("页边距过大,导致 A4 可用区域为 0")
self.output_page_count = 0
self._reset_current_page()
def _reset_current_page(self) -> None:
self.current = np.full((self.a4_h_px, self.a4_w_px), 255, dtype=np.uint8)
self.cursor_y = self.margin_px
self.page_has_content = False
@property
def remaining_h(self) -> int:
return self.margin_px + self.content_h_px - self.cursor_y
def _flush_current_page(self) -> None:
if self.page_has_content:
add_image_page_to_pdf(self.out_doc, self.current)
self.output_page_count += 1
self._reset_current_page()
def add_gap(self, src_rows: int, src_width: int, max_rows: int = 0) -> None:
if src_rows <= 0 or src_width <= 0:
return
scaled = int(round(src_rows * self.content_w_px / float(src_width)))
if max_rows > 0:
scaled = min(scaled, max_rows)
if scaled <= 0:
return
while scaled > 0:
rem = self.remaining_h
if rem <= 0:
self._flush_current_page()
rem = self.remaining_h
step = min(scaled, rem)
if self.page_has_content:
self.cursor_y += step
# 若当前页尚无内容,则忽略页首空白,不人为下移。
scaled -= step
if scaled > 0:
self._flush_current_page()
def _resize_fragment(self, fragment: np.ndarray) -> np.ndarray:
if fragment.shape[1] == self.content_w_px:
return fragment
scale = self.content_w_px / float(fragment.shape[1])
resized_h = max(1, int(round(fragment.shape[0] * scale)))
interp = cv2.INTER_AREA if scale < 1.0 else cv2.INTER_LINEAR
resized = cv2.resize(fragment, (self.content_w_px, resized_h), interpolation=interp)
_, resized = cv2.threshold(resized, 127, 255, cv2.THRESH_BINARY)
return resized
def _blit_rows(self, img: np.ndarray, y0: int, y1: int) -> None:
rows = y1 - y0
if rows <= 0:
return
dest_y0 = self.cursor_y
dest_y1 = dest_y0 + rows
self.current[dest_y0:dest_y1, self.margin_px : self.margin_px + self.content_w_px] = img[y0:y1, :]
self.cursor_y = dest_y1
self.page_has_content = True
def add_fragment(self, fragment: np.ndarray) -> None:
if fragment.size == 0:
return
resized = self._resize_fragment(fragment)
h = resized.shape[0]
if h <= self.remaining_h:
self._blit_rows(resized, 0, h)
return
if h <= self.content_h_px:
if self.page_has_content:
self._flush_current_page()
self._blit_rows(resized, 0, h)
return
# 兜底:若单块仍高于一整页,则在片段内部继续智能拆分。
scale = self.content_w_px / float(fragment.shape[1])
max_src_h = max(32, int(math.floor(self.content_h_px / scale)))
counts = row_ink_count(fragment)
start = 0
src_h = fragment.shape[0]
while start < src_h:
if start + max_src_h >= src_h:
sub = fragment[start:src_h, :]
self.add_fragment(sub)
break
target = start + max_src_h
lo = start + int(max_src_h * 0.72)
hi = min(src_h, start + int(max_src_h * 1.10))
cut = best_cut_near_target(counts, lo=lo, hi=hi, target=target)
if cut <= start + 10:
cut = min(src_h, target)
sub = fragment[start:cut, :]
if self.page_has_content:
self._flush_current_page()
self.add_fragment(sub)
start = cut
def finalize_to_pdf(self) -> int:
if self.page_has_content:
add_image_page_to_pdf(self.out_doc, self.current)
self.output_page_count += 1
self._reset_current_page()
return self.output_page_count
def add_image_page_to_pdf(out_doc: fitz.Document, gray_page: np.ndarray) -> None:
success, encoded = cv2.imencode(".png", gray_page, [cv2.IMWRITE_PNG_COMPRESSION, 1])
if not success:
raise RuntimeError("PNG 编码失败")
page = out_doc.new_page(width=A4_W_PT, height=A4_H_PT)
page.insert_image(page.rect, stream=encoded.tobytes())
def _process_pdf_page(job: PageJob, options: ConvertOptions) -> ProcessedPage:
with fitz.open(job.pdf_path) as src:
page = src.load_page(job.page_idx - 1)
gray = pdf_page_to_gray(page, dpi=options.render_dpi)
binary = binarize_handwriting(gray)
if options.crop_whitespace:
binary = crop_whitespace(binary, pad_px=max(6, options.render_dpi // 30))
binary = _remove_tiny_components(binary)
return ProcessedPage(
order_idx=job.order_idx,
doc_idx=job.doc_idx,
doc_count=job.doc_count,
pdf_path=job.pdf_path,
page_idx=job.page_idx,
doc_pages=job.doc_pages,
binary=binary,
)
def _paginate_processed_page(
processed: ProcessedPage,
paginator: ContinuousPaginator,
content_w_px: int,
content_h_px: int,
) -> int:
binary = processed.binary
local_fragment_count = 0
gap_cap = max(0, int(round(content_h_px * 0.015)))
for kind, payload, src_width in iter_smart_fragments(binary, content_w_px, content_h_px):
if kind == "gap":
paginator.add_gap(int(payload), src_width, max_rows=gap_cap)
else:
paginator.add_fragment(payload) # type: ignore[arg-type]
local_fragment_count += 1
# 仅加入很小的源页/文档间留白,但不强制换页。
if processed.page_idx != processed.doc_pages:
paginator.add_gap(max(1, binary.shape[0] // 120), binary.shape[1], max_rows=gap_cap)
elif processed.doc_idx != processed.doc_count:
paginator.add_gap(max(1, binary.shape[0] // 80), binary.shape[1], max_rows=max(2, gap_cap))
return local_fragment_count
# =========================
# 转换主逻辑
# =========================
def convert_pdfs(
input_pdfs: Sequence[str],
output_pdf: str,
options: ConvertOptions,
progress: Callable[[str], None] | None = None,
progress_value: Callable[[float, str], None] | None = None,
) -> None:
if not input_pdfs:
raise ValueError("未提供输入 PDF")
def log(msg: str) -> None:
if progress:
progress(msg)
def report_progress(fraction: float, msg: str) -> None:
if progress_value:
progress_value(min(1.0, max(0.0, fraction)), msg)
input_pdfs = [str(p) for p in input_pdfs]
output_pdf = str(output_pdf)
a4_w_px = int(round(A4_W_PT / 72.0 * options.output_dpi))
a4_h_px = int(round(A4_H_PT / 72.0 * options.output_dpi))
margin_px = mm_to_px(options.margin_mm, options.output_dpi)
content_w_px = a4_w_px - 2 * margin_px
content_h_px = a4_h_px - 2 * margin_px
if content_w_px <= 0 or content_h_px <= 0:
raise ValueError("页边距过大,导致 A4 可用区域为 0")
total_input_pages = 0
jobs: List[PageJob] = []
for doc_idx, pdf_path in enumerate(input_pdfs, start=1):
with fitz.open(pdf_path) as src:
doc_pages = len(src)
for page_idx in range(1, doc_pages + 1):
jobs.append(
PageJob(
order_idx=total_input_pages,
doc_idx=doc_idx,
doc_count=len(input_pdfs),
pdf_path=pdf_path,
page_idx=page_idx,
doc_pages=doc_pages,
)
)
total_input_pages += 1
out = fitz.open()
paginator = ContinuousPaginator(a4_w_px=a4_w_px, a4_h_px=a4_h_px, margin_px=margin_px, out_doc=out)
runtime = _auto_runtime_plan(options, total_input_pages)
worker_count = runtime.worker_count
runtime_status = _configure_cv2_runtime(runtime.opencv_threads, runtime.use_opencl)
preprocessed_pages = 0
paginated_pages = 0
def report_page_progress(stage: str) -> None:
if total_input_pages <= 0:
report_progress(0.0, stage)
return
fraction = (preprocessed_pages * 0.65 + paginated_pages * 0.30) / total_input_pages
report_progress(
fraction,
f"{stage}(预处理 {preprocessed_pages}/{total_input_pages},排版 {paginated_pages}/{total_input_pages})",
)
log(
f"运行配置:{runtime.status},页级并行={worker_count},"
f"OpenCV线程/处理单元={runtime.opencv_threads},待处理队列上限={runtime.max_pending},"
f"{runtime_status}。"
)
report_page_progress("准备处理")
try:
if worker_count <= 1:
for job in jobs:
report_page_progress(f"正在预处理第 {job.order_idx + 1}/{total_input_pages} 页")
log(
f"正在处理第 {job.order_idx + 1}/{total_input_pages} 个输入页 "
f"(文档 {job.doc_idx}/{job.doc_count},页 {job.page_idx}/{job.doc_pages}):渲染与识别中…"
)
processed = _process_pdf_page(job, options)
preprocessed_pages += 1
report_page_progress(f"正在排版第 {job.order_idx + 1}/{total_input_pages} 页")
log("连续排版中…")
local_fragment_count = _paginate_processed_page(processed, paginator, content_w_px, content_h_px)
paginated_pages += 1
log(
f"当前输入页完成,已抽取 {local_fragment_count} 个内容片段;"
f"当前已写入 {paginator.output_page_count} 张整页 A4。"
)
report_page_progress(f"已完成第 {job.order_idx + 1}/{total_input_pages} 页")
else:
next_submit = 0
next_emit = 0
completed: dict[int, ProcessedPage] = {}
pending: dict[Future[ProcessedPage], PageJob] = {}
max_pending = runtime.max_pending
with ProcessPoolExecutor(
max_workers=worker_count,
initializer=_init_worker_runtime,
initargs=(runtime.opencv_threads, runtime.use_opencl),
) as executor:
while next_emit < total_input_pages:
while next_submit < total_input_pages and len(pending) < max_pending:
job = jobs[next_submit]
log(
f"提交第 {job.order_idx + 1}/{total_input_pages} 个输入页 "
f"(文档 {job.doc_idx}/{job.doc_count},页 {job.page_idx}/{job.doc_pages}):并行渲染与识别中…"
)
pending[executor.submit(_process_pdf_page, job, options)] = job
next_submit += 1
report_page_progress(f"已提交 {next_submit}/{total_input_pages} 页")
if next_emit not in completed:
done, _ = wait(pending, return_when=FIRST_COMPLETED)
for future in done:
job = pending.pop(future)
processed = future.result()
completed[processed.order_idx] = processed
preprocessed_pages += 1
log(
f"预处理完成第 {job.order_idx + 1}/{total_input_pages} 个输入页 "
f"(文档 {job.doc_idx}/{job.doc_count},页 {job.page_idx}/{job.doc_pages})。"
)
report_page_progress("并行预处理进行中")
while next_emit in completed:
processed = completed.pop(next_emit)
report_page_progress(f"正在排版第 {processed.order_idx + 1}/{total_input_pages} 页")
log(
f"按顺序排版第 {processed.order_idx + 1}/{total_input_pages} 个输入页 "
f"(文档 {processed.doc_idx}/{processed.doc_count},页 {processed.page_idx}/{processed.doc_pages})…"
)
local_fragment_count = _paginate_processed_page(
processed,
paginator,
content_w_px,
content_h_px,
)
log(
f"当前输入页完成,已抽取 {local_fragment_count} 个内容片段;"
f"当前已写入 {paginator.output_page_count} 张整页 A4。"
)
paginated_pages += 1
next_emit += 1
report_page_progress(f"已完成第 {processed.order_idx + 1}/{total_input_pages} 页")
report_progress(0.96, "正在生成输出 PDF 页面…")
out_count = paginator.finalize_to_pdf()
if out_count <= 0:
raise RuntimeError("没有生成任何输出页")
report_progress(0.98, "正在保存输出 PDF…")
out.save(output_pdf, deflate=True, garbage=3)
report_progress(1.0, "转换完成")
log(f"完成:共生成 {out_count} 张 A4,输出文件已保存。")
finally:
out.close()
# 向后兼容单文件调用。
def convert_pdf(
input_pdf: str,
output_pdf: str,
options: ConvertOptions,
progress: Callable[[str], None] | None = None,
progress_value: Callable[[float, str], None] | None = None,
) -> None:
convert_pdfs([input_pdf], output_pdf, options, progress, progress_value)
# =========================
# GUI
# =========================
class ConverterApp:
def __init__(self, root: tk.Tk) -> None:
self.root = root
self.root.title("PDF 笔记打印转换器")
self.root.geometry("900x650")
self.queue: queue.Queue[Tuple[str, object]] = queue.Queue()
self.worker: threading.Thread | None = None
self.output_var = tk.StringVar()
self.render_dpi_var = tk.StringVar(value="600")
self.output_dpi_var = tk.StringVar(value="600")
self.margin_var = tk.StringVar(value="24")
self.crop_var = tk.BooleanVar(value=True)
self.progress_var = tk.DoubleVar(value=0.0)
self.progress_text_var = tk.StringVar(value="等待开始")
self.last_output_pdf: str | None = None
self._build_ui()
self.root.after(100, self._poll_queue)
def _build_ui(self) -> None:
main = ttk.Frame(self.root)
main.pack(fill="both", expand=True, padx=12, pady=12)
# 输入文件列表
lf = ttk.LabelFrame(main, text="输入 PDF(顺序即拼接顺序)")
lf.pack(fill="x")
list_wrap = ttk.Frame(lf)
list_wrap.pack(fill="x", padx=10, pady=10)
self.listbox = tk.Listbox(list_wrap, height=8, selectmode=tk.EXTENDED)
self.listbox.pack(side="left", fill="x", expand=True)
sb = ttk.Scrollbar(list_wrap, orient="vertical", command=self.listbox.yview)
sb.pack(side="left", fill="y")
self.listbox.configure(yscrollcommand=sb.set)
btns = ttk.Frame(list_wrap)
btns.pack(side="left", padx=(10, 0), fill="y")
ttk.Button(btns, text="添加…", command=self.choose_inputs).pack(fill="x", pady=2)
ttk.Button(btns, text="删除所选", command=self.remove_selected).pack(fill="x", pady=2)
ttk.Button(btns, text="上移", command=self.move_up).pack(fill="x", pady=2)
ttk.Button(btns, text="下移", command=self.move_down).pack(fill="x", pady=2)
ttk.Button(btns, text="清空", command=self.clear_inputs).pack(fill="x", pady=2)
# 输出文件
out_frame = ttk.LabelFrame(main, text="输出 PDF")
out_frame.pack(fill="x", pady=(10, 0))
ttk.Entry(out_frame, textvariable=self.output_var).pack(side="left", fill="x", expand=True, padx=10, pady=10)
ttk.Button(out_frame, text="选择…", command=self.choose_output).pack(side="left", padx=(0, 10), pady=10)
# 参数
opt = ttk.LabelFrame(main, text="参数")
opt.pack(fill="x", pady=(10, 0))
row = ttk.Frame(opt)
row.pack(fill="x", padx=10, pady=10)
ttk.Label(row, text="渲染 DPI").grid(row=0, column=0, sticky="w")
ttk.Entry(row, width=8, textvariable=self.render_dpi_var).grid(row=0, column=1, padx=(6, 16))
ttk.Label(row, text="输出 DPI").grid(row=0, column=2, sticky="w")
ttk.Entry(row, width=8, textvariable=self.output_dpi_var).grid(row=0, column=3, padx=(6, 16))
ttk.Label(row, text="页边距(mm)").grid(row=0, column=4, sticky="w")
ttk.Entry(row, width=8, textvariable=self.margin_var).grid(row=0, column=5, padx=(6, 16))
ttk.Checkbutton(row, text="裁掉外围空白", variable=self.crop_var).grid(row=0, column=6, sticky="w")
tip = ttk.Label(
opt,
text="默认保留 600/600 DPI;如更看重速度和体积,可手动降低到 300 DPI。",
foreground="#555555",
)
tip.pack(anchor="w", padx=10, pady=(0, 10))
# 进度
progress_frame = ttk.LabelFrame(main, text="实时进度")
progress_frame.pack(fill="x", pady=(10, 0))
self.progress_bar = ttk.Progressbar(
progress_frame,
variable=self.progress_var,
maximum=100.0,
mode="determinate",
)
self.progress_bar.pack(fill="x", padx=10, pady=(10, 4))
ttk.Label(progress_frame, textvariable=self.progress_text_var).pack(anchor="w", padx=10, pady=(0, 10))
# 操作按钮
action = ttk.Frame(main)
action.pack(fill="x", pady=(10, 0))
self.start_btn = ttk.Button(action, text="开始转换", command=self.start_convert)
self.start_btn.pack(side="left")
self.open_output_btn = ttk.Button(action, text="打开输出位置", command=self.open_output_location)
self.open_output_btn.pack(side="left", padx=(8, 0))
self.open_output_btn.configure(state="disabled")
# 日志
logf = ttk.LabelFrame(main, text="日志")
logf.pack(fill="both", expand=True, pady=(10, 0))
self.log_text = tk.Text(logf, height=16, wrap="word")
self.log_text.pack(side="left", fill="both", expand=True, padx=10, pady=10)
logsb = ttk.Scrollbar(logf, orient="vertical", command=self.log_text.yview)
logsb.pack(side="left", fill="y", pady=10)
self.log_text.configure(yscrollcommand=logsb.set)
def _get_inputs(self) -> List[str]:
return [self.listbox.get(i) for i in range(self.listbox.size())]
def choose_inputs(self) -> None:
files = filedialog.askopenfilenames(
title="选择一个或多个 PDF",
filetypes=[("PDF 文件", "*.pdf")],
)
if not files:
return
existing = self._get_inputs()
for f in files:
if f not in existing:
self.listbox.insert("end", f)
existing.append(f)