Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
14365d10b8 | ||
|
|
5e5320020f | ||
|
|
103c3e0cd6 | ||
|
|
7a1c89edd9 | ||
|
|
a5ff3d2f42 | ||
|
|
0b6fb62967 | ||
|
|
1db8b0b943 | ||
|
|
f38aebb3d5 | ||
|
|
7162c36d37 | ||
|
|
f4d4ea46c8 | ||
|
|
2fd1a0f178 | ||
|
|
73ed33a086 | ||
|
|
e6095a9949 | ||
|
|
16f05af401 | ||
|
|
1631afc878 | ||
|
|
63d87fc440 | ||
|
|
9489c01259 | ||
|
|
30d92ad83f | ||
|
|
a4987733c4 | ||
|
|
39eee05230 | ||
|
|
5b2f2e6290 | ||
|
|
445617a1a5 | ||
|
|
f6e90a5934 | ||
|
|
43618e6b3f | ||
|
|
e97f89de3b | ||
|
|
11d3e32f1e | ||
|
|
2affa83efe | ||
|
|
c90d5cd84b | ||
|
|
aacaba3d26 | ||
|
|
fec53be841 | ||
|
|
3f7b540f76 | ||
|
|
d217856166 | ||
|
|
e2be457e9b | ||
|
|
4850f486d2 | ||
|
|
729c7febd9 | ||
|
|
6c6aca2f1e | ||
|
|
c69823f496 | ||
|
|
73f8f6aac8 | ||
|
|
d944254e45 | ||
|
|
f7ddffe554 | ||
|
|
8a73ed5d5a | ||
|
|
03669183d7 | ||
|
|
74e101a2fa | ||
|
|
532cf18ad3 | ||
|
|
0b90b697e2 | ||
|
|
6be7c5f7c8 | ||
|
|
db2e5132e6 | ||
|
|
b14f6f778a | ||
|
|
415de77457 | ||
|
|
a9466c4f58 | ||
|
|
d9ae453a63 | ||
|
|
9841e09233 | ||
|
|
0ca314e066 | ||
|
|
d7680cae27 | ||
|
|
491b6bdb1f | ||
|
|
c591f9601a | ||
|
|
8d1e75017e | ||
|
|
94615f7ad4 | ||
|
|
e5df8e1315 | ||
|
|
d739b91aef | ||
|
|
686cfb2539 | ||
|
|
2633716bb7 | ||
|
|
0a07c0a44e | ||
|
|
2ca6e110ca | ||
|
|
334a07c839 | ||
|
|
a57c39358d | ||
|
|
30a0c315fb | ||
|
|
b860f0d94c | ||
|
|
14f4c19f5a | ||
|
|
7ab5c55d46 | ||
|
|
8b6ecd5971 | ||
|
|
7b0871ae4c | ||
|
|
b73af7ce10 | ||
|
|
60645717e2 | ||
|
|
1cbf578538 | ||
|
|
e966c1fceb | ||
|
|
d0133f8641 | ||
|
|
6d30b497dc | ||
|
|
f3b89e66eb | ||
|
|
04154e207c | ||
|
|
9898904be7 | ||
|
|
27d5229842 | ||
|
|
4a9a575ef0 | ||
|
|
52fd9a630d | ||
|
|
a596ccf844 | ||
|
|
e7fa97731f | ||
|
|
290aa28108 | ||
|
|
a95640ed9e | ||
|
|
f69267bb67 | ||
|
|
e36d5a309f | ||
|
|
55566d9830 | ||
|
|
f02ea20678 | ||
|
|
372c22d42b | ||
|
|
949265bbd0 | ||
|
|
916106733c | ||
|
|
44bcafd3aa | ||
|
|
71166f7be8 | ||
|
|
580252a1a0 | ||
|
|
c0b60dae6a | ||
|
|
ae123fd209 | ||
|
|
454ad0acc5 | ||
|
|
0c306ac328 | ||
|
|
52d99732b1 | ||
|
|
5b5827983b | ||
|
|
56f9bc311d | ||
|
|
eb17dc1ecf | ||
|
|
6f8115a052 | ||
|
|
aac913c666 | ||
|
|
b5e73ac4e4 | ||
|
|
9e98c90891 | ||
|
|
ca2592c1d9 | ||
|
|
a31f17bb9d | ||
|
|
1cb46afa94 | ||
|
|
5a759947dd | ||
|
|
db3df13e95 | ||
|
|
2a8bc03167 | ||
|
|
d2297b39d0 | ||
|
|
e4cd081d4d | ||
|
|
d2dbea6cf8 | ||
|
|
46a279a49a | ||
|
|
299f0c4003 | ||
|
|
9ffb45f283 | ||
|
|
cd61c4efd9 | ||
|
|
a06ab2a1c5 | ||
|
|
dfa4ebf1a6 | ||
|
|
58f388c69d | ||
|
|
990b462a94 | ||
|
|
b928dc0808 | ||
|
|
8916955f45 | ||
|
|
82bef40aa6 | ||
|
|
1c45f32941 | ||
|
|
fadc0cf69b | ||
|
|
7ce9d08b2d | ||
|
|
eb3a51e33a | ||
|
|
f3dd733773 | ||
|
|
4dbc5e1dba | ||
|
|
c0637c287e | ||
|
|
6127f7abd6 | ||
|
|
a4059762e6 | ||
|
|
40afcd68a7 | ||
|
|
f238e721ed | ||
|
|
16eb5627a7 | ||
|
|
fbf0674189 | ||
|
|
62c4f65fc3 | ||
|
|
e400112f32 | ||
|
|
7935914f55 | ||
|
|
ad3a1dbbad | ||
|
|
0655f8e7ae | ||
|
|
04a9372584 | ||
|
|
b9646b6f85 | ||
|
|
53c953a561 | ||
|
|
c278fecb34 | ||
|
|
23951c9e38 | ||
|
|
e8ae370ceb | ||
|
|
67be4d1904 | ||
|
|
6f82097d14 | ||
|
|
fc6f959d21 | ||
|
|
e38d569d8f | ||
|
|
0856750ee2 | ||
|
|
05721ba84a | ||
|
|
38c3422e5e | ||
|
|
d153a6f6df | ||
|
|
1a7738a925 | ||
|
|
8985c0dfe9 | ||
|
|
ebfe008432 | ||
|
|
1f16eb6f50 | ||
|
|
cbb0868ae3 | ||
|
|
68bb38d0ad | ||
|
|
0443e87345 | ||
|
|
b3de5833d3 | ||
|
|
95b14ee282 | ||
|
|
07b89e6a19 | ||
|
|
8991d2cb33 | ||
|
|
86a20c4130 | ||
|
|
6827a6efe8 | ||
|
|
c6b5332699 | ||
|
|
68610046c6 | ||
|
|
880326868d | ||
|
|
c6be3ba076 | ||
|
|
0565cb0b10 | ||
|
|
dc49906704 | ||
|
|
93fda0dd00 | ||
|
|
d4110e78cb | ||
|
|
5285d68fcc | ||
|
|
2b0e149809 | ||
|
|
b7ce5b0d7d | ||
|
|
ffd6a64ce9 | ||
|
|
5727f1e081 | ||
|
|
b75a7eca2a | ||
|
|
2b01676434 | ||
|
|
e11c386c58 | ||
|
|
9346d1f970 | ||
|
|
012cbef865 | ||
|
|
0687568e1b | ||
|
|
3086cfc3d9 | ||
|
|
91a14660b3 | ||
|
|
539f0ee0ce | ||
|
|
7172817cd6 | ||
|
|
d9cc759142 | ||
|
|
364799fc3e | ||
|
|
f4c211fa2d | ||
|
|
113a6b45bd | ||
|
|
e9419d2c40 | ||
|
|
fb006ef39f | ||
|
|
890b994403 | ||
|
|
01bbf7d144 | ||
|
|
468de5324a | ||
|
|
072db75fa3 | ||
|
|
8519b3f625 | ||
|
|
dd7c4f3eaa | ||
|
|
c8e6f20f8d | ||
|
|
10530a8698 | ||
|
|
207866abf5 | ||
|
|
3829af16fb | ||
|
|
24db31b4c5 | ||
|
|
8132a4ae10 | ||
|
|
d5128c5cf5 | ||
|
|
270e31fa67 | ||
|
|
85e31d0a19 | ||
|
|
ea36aedb5f | ||
|
|
bd4d44e182 | ||
|
|
8fcf358934 | ||
|
|
47b0f28564 | ||
|
|
7018e2b247 | ||
|
|
8d12ecb798 | ||
|
|
0ab29ec0ba | ||
|
|
179714770a | ||
|
|
f04f45545c | ||
|
|
a3a083c125 | ||
|
|
d855f63985 | ||
|
|
d4863cbf0f | ||
|
|
7b8f081fbf | ||
|
|
7d33039bcd | ||
|
|
fde886baf4 | ||
|
|
146da79c00 | ||
|
|
2fc3b0d973 | ||
|
|
5667424530 | ||
|
|
8add531ffd | ||
|
|
0388c23ae7 | ||
|
|
9b77daae7c | ||
|
|
3e1b3ec98d | ||
|
|
0f0ca6f517 | ||
|
|
c93349c350 | ||
|
|
0c287929c2 | ||
|
|
23a37fc35c | ||
|
|
162a47f98e | ||
|
|
0239f69912 | ||
|
|
2ad8961d0b | ||
|
|
eec8a2b574 | ||
|
|
6c78076bea | ||
|
|
2637e84691 | ||
|
|
e8c82ee4b6 | ||
|
|
de2bb5ce8c | ||
|
|
ec1c377532 | ||
|
|
173428e81a | ||
|
|
67ed29dcea | ||
|
|
3454c050ed | ||
|
|
5ee99b26e7 | ||
|
|
ac3aa67d8a | ||
|
|
1768a1eda9 | ||
|
|
5902fe45c1 | ||
|
|
78981641f0 | ||
|
|
c77ae4b34c | ||
|
|
b2cbbf0099 | ||
|
|
6b6c34af01 | ||
|
|
be12f7a728 | ||
|
|
e3c813fc67 | ||
|
|
35a1eaf62a | ||
|
|
d393d18c13 | ||
|
|
54e622ad10 | ||
|
|
330352aeed | ||
|
|
ac2fc49208 | ||
|
|
4bee7355e9 | ||
|
|
86f2b1f9a7 | ||
|
|
3002409e49 | ||
|
|
0cf6828c20 | ||
|
|
331c829b6e | ||
|
|
06a5e0c3f6 | ||
|
|
811f23381a | ||
|
|
a371655052 | ||
|
|
a6ce35b13a | ||
|
|
45added738 | ||
|
|
6e20439c91 | ||
|
|
72e056436c | ||
|
|
e02ba19097 | ||
|
|
d3b858f994 | ||
|
|
19045c4f21 | ||
|
|
f4d89fe6cc | ||
|
|
ab85c0f5a9 | ||
|
|
32693b683d | ||
|
|
b5dc276ba1 | ||
|
|
7c38c71794 | ||
|
|
a80e7a127b | ||
|
|
cf3309555f | ||
|
|
f80dd0d86a | ||
|
|
1ba2bce486 | ||
|
|
050dd1f5a8 | ||
|
|
e44a57aec0 | ||
|
|
d94d2671c3 | ||
|
|
5124daa79f | ||
|
|
7293847da7 | ||
|
|
59fd0ac587 | ||
|
|
90619b308c | ||
|
|
d0d49ce989 | ||
|
|
bf0224faa4 | ||
|
|
ae2f8ed8f1 | ||
|
|
14ac9b0560 | ||
|
|
dbe6148d41 | ||
|
|
36d4c2dbbc | ||
|
|
adbffb7bd9 | ||
|
|
05ecb6ca46 | ||
|
|
0a7b60cda5 | ||
|
|
5f211ecf6f | ||
|
|
417ee067a2 | ||
|
|
c4649dabef | ||
|
|
6eadd65dfb | ||
|
|
e8ed510543 | ||
|
|
22d35c199d | ||
|
|
5a82ad63c9 | ||
|
|
4769a6c50b | ||
|
|
9004009adc | ||
|
|
11221f9912 | ||
|
|
177349cc84 | ||
|
|
070c9772ce | ||
|
|
1bc09045a5 | ||
|
|
e46a18dd2f | ||
|
|
c64871c2ed | ||
|
|
de909fb99a | ||
|
|
731b2fc477 | ||
|
|
214f6ec759 | ||
|
|
080aa4dbd1 | ||
|
|
7af5dcd4a4 | ||
|
|
fe9f52fbe7 | ||
|
|
fcbdeb8dbe | ||
|
|
cb251a8d03 | ||
|
|
3731fdfd72 | ||
|
|
b2e6a6431e | ||
|
|
9ff1e56bf6 | ||
|
|
2b30f74fce | ||
|
|
10f4c48e0b | ||
|
|
37d5c086bb | ||
|
|
91830627e5 | ||
|
|
f2fc37b257 | ||
|
|
a99e40fa84 | ||
|
|
9ce692a6f1 | ||
|
|
a3c49b8f31 | ||
|
|
33b70be7d5 | ||
|
|
4924b11b6b | ||
|
|
1d0e4e7c9f | ||
|
|
9b8d14d16e | ||
|
|
b7eb93eb79 | ||
|
|
42c0d0f48f | ||
|
|
5fce50ff7c | ||
|
|
765ed4c386 | ||
|
|
1b2849ec0a | ||
|
|
4f604591b4 | ||
|
|
01dc8e23ff | ||
|
|
b432770cfc | ||
|
|
5502fb8d9f | ||
|
|
e66922b030 | ||
|
|
00e9759b16 | ||
|
|
ba10c5345b | ||
|
|
8a5f94988a | ||
|
|
aa73e3c69f | ||
|
|
9d5fa05a00 | ||
|
|
997380e567 | ||
|
|
2685f910b1 | ||
|
|
bfcc586032 | ||
|
|
2d77b95fd9 | ||
|
|
f072e91120 | ||
|
|
efa2bca8a3 | ||
|
|
b039010d3e | ||
|
|
3f7cefcf5d | ||
|
|
45f97d1565 | ||
|
|
1281f8eb68 | ||
|
|
9ef61864fb | ||
|
|
90b2119ad3 | ||
|
|
f0cc7f2230 | ||
|
|
d60a384aab | ||
|
|
14a6093636 | ||
|
|
54b42d73ab | ||
|
|
9abed14f1f | ||
|
|
d09f61d4fe | ||
|
|
4a0130649e | ||
|
|
a0224d94ca | ||
|
|
9e7b9de830 | ||
|
|
08fc5fc01d | ||
|
|
110c75cba2 | ||
|
|
5afca3f342 | ||
|
|
d9eb0ba7ef | ||
|
|
46d0978a09 | ||
|
|
4e35100978 | ||
|
|
7bd0e43243 | ||
|
|
9cd97da5f2 | ||
|
|
d002703c41 | ||
|
|
b1fecf3b05 | ||
|
|
c2ccc7f29d | ||
|
|
36dfd12e2c | ||
|
|
7da4e6ca7f | ||
|
|
16fc52079d | ||
|
|
f37decf3b3 | ||
|
|
4ad4a13ef0 | ||
|
|
6f61f69a8d | ||
|
|
88831e8ab1 | ||
|
|
2ebc36fcec | ||
|
|
1709e23701 | ||
|
|
2e55cb5980 | ||
|
|
6dbaebdc0c | ||
|
|
5156fe7662 | ||
|
|
2c99c89e45 | ||
|
|
74286e7e1e | ||
|
|
2e937dee9f | ||
|
|
23f3830533 | ||
|
|
305e6594be | ||
|
|
f4155dca77 | ||
|
|
545cd031b0 | ||
|
|
a1c7826336 | ||
|
|
c5359bd990 | ||
|
|
7f77308846 | ||
|
|
8e7c5f3001 | ||
|
|
79db985181 | ||
|
|
7d23a661fc | ||
|
|
99e94807c5 | ||
|
|
8412de9344 | ||
|
|
b458b1422b | ||
|
|
76bd8cab13 | ||
|
|
ef70c9499e | ||
|
|
47dcb6fcd0 | ||
|
|
88d2949e6b | ||
|
|
c9389c7713 | ||
|
|
4d2f499f97 | ||
|
|
4104904a1e | ||
|
|
1a0a797ca6 | ||
|
|
670ce2b969 | ||
|
|
7e97981114 | ||
|
|
53db866ef9 | ||
|
|
d591a3e059 | ||
|
|
37c050aa4f | ||
|
|
4b9ea40a0c | ||
|
|
165432486b | ||
|
|
d619fac0bd | ||
|
|
acc70036cc | ||
|
|
80b7cf6330 | ||
|
|
8a8c06c79c | ||
|
|
67773da309 | ||
|
|
d5a9861d5c | ||
|
|
9ffe829a10 | ||
|
|
8a3b82e364 | ||
|
|
580822a6a2 | ||
|
|
9f3a52fd12 | ||
|
|
52e829d845 | ||
|
|
2b2e5c271a | ||
|
|
5fe3102e4e | ||
|
|
5b57520c98 |
+13
-4
@@ -1,5 +1,5 @@
|
|||||||
# OCRmyPDF
|
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
||||||
#
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
|
|
||||||
FROM ubuntu:22.04 as base
|
FROM ubuntu:22.04 as base
|
||||||
|
|
||||||
@@ -25,7 +25,9 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
|||||||
libffi-dev \
|
libffi-dev \
|
||||||
ca-certificates \
|
ca-certificates \
|
||||||
curl \
|
curl \
|
||||||
git
|
git \
|
||||||
|
libcairo2-dev \
|
||||||
|
pkg-config
|
||||||
|
|
||||||
# Get the latest pip (Ubuntu version doesn't support manylinux2010)
|
# Get the latest pip (Ubuntu version doesn't support manylinux2010)
|
||||||
RUN \
|
RUN \
|
||||||
@@ -50,8 +52,15 @@ RUN pip3 install --no-cache-dir .[test,webservice,watcher]
|
|||||||
|
|
||||||
FROM base
|
FROM base
|
||||||
|
|
||||||
|
# For Tesseract 5
|
||||||
|
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||||
|
software-properties-common gpg-agent
|
||||||
|
RUN add-apt-repository -y ppa:alex-p/tesseract-ocr-devel
|
||||||
|
|
||||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||||
ghostscript \
|
ghostscript \
|
||||||
|
fonts-droid-fallback \
|
||||||
|
jbig2dec \
|
||||||
img2pdf \
|
img2pdf \
|
||||||
libsm6 libxext6 libxrender-dev \
|
libsm6 libxext6 libxrender-dev \
|
||||||
pngquant \
|
pngquant \
|
||||||
@@ -74,7 +83,7 @@ COPY --from=builder /app/misc/webservice.py /app/
|
|||||||
COPY --from=builder /app/misc/watcher.py /app/
|
COPY --from=builder /app/misc/watcher.py /app/
|
||||||
|
|
||||||
# Copy minimal project files to get the test suite.
|
# Copy minimal project files to get the test suite.
|
||||||
COPY --from=builder /app/setup.cfg /app/setup.py /app/README.md /app/
|
COPY --from=builder /app/pyproject.toml /app/README.md /app/
|
||||||
COPY --from=builder /app/tests /app/tests
|
COPY --from=builder /app/tests /app/tests
|
||||||
|
|
||||||
ENTRYPOINT ["/usr/local/bin/ocrmypdf"]
|
ENTRYPOINT ["/usr/local/bin/ocrmypdf"]
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
# SPDX-FileCopyrightText: 2023 James R. Barlow
|
||||||
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
|
|
||||||
|
FROM alpine:3.18 as base
|
||||||
|
|
||||||
|
ENV LANG=C.UTF-8
|
||||||
|
ENV TZ=UTC
|
||||||
|
|
||||||
|
RUN apk add --no-cache \
|
||||||
|
python3 \
|
||||||
|
zlib
|
||||||
|
|
||||||
|
FROM base as builder
|
||||||
|
|
||||||
|
RUN apk add --no-cache \
|
||||||
|
ca-certificates \
|
||||||
|
git \
|
||||||
|
python3-dev \
|
||||||
|
py3-pip
|
||||||
|
|
||||||
|
# On arm64, we need to build cffi from source.
|
||||||
|
ARG TARGETPLATFORM
|
||||||
|
|
||||||
|
RUN if [ "${TARGETPLATFORM}" == "linux/arm64" ]; then \
|
||||||
|
apk add --no-cache \
|
||||||
|
build-base \
|
||||||
|
autoconf \
|
||||||
|
automake \
|
||||||
|
libtool \
|
||||||
|
zlib-dev \
|
||||||
|
libffi-dev \
|
||||||
|
cairo-dev \
|
||||||
|
pkgconfig \
|
||||||
|
; \
|
||||||
|
fi
|
||||||
|
|
||||||
|
COPY . /app
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
RUN python3 -m venv .venv
|
||||||
|
|
||||||
|
RUN source .venv/bin/activate \
|
||||||
|
&& python3 -m pip install --no-cache-dir --upgrade pip \
|
||||||
|
&& python3 -m pip install --no-cache-dir wheel \
|
||||||
|
&& python3 -m pip install --no-cache-dir .[test,webservice,watcher]
|
||||||
|
|
||||||
|
FROM base
|
||||||
|
|
||||||
|
RUN apk add --no-cache \
|
||||||
|
ghostscript \
|
||||||
|
jbig2dec \
|
||||||
|
jbig2enc \
|
||||||
|
pngquant \
|
||||||
|
tesseract-ocr \
|
||||||
|
tesseract-ocr-data-chi_sim \
|
||||||
|
tesseract-ocr-data-deu \
|
||||||
|
tesseract-ocr-data-eng \
|
||||||
|
tesseract-ocr-data-fra \
|
||||||
|
tesseract-ocr-data-osd \
|
||||||
|
tesseract-ocr-data-por \
|
||||||
|
tesseract-ocr-data-spa \
|
||||||
|
ttf-droid \
|
||||||
|
unpaper \
|
||||||
|
&& rm -rf /var/cache/apk/*
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY --from=builder /usr/local/lib/ /usr/local/lib/
|
||||||
|
COPY --from=builder /usr/local/bin/ /usr/local/bin/
|
||||||
|
|
||||||
|
COPY --from=builder /app/.venv/ /app/.venv/
|
||||||
|
|
||||||
|
COPY --from=builder /app/misc/webservice.py /app/
|
||||||
|
COPY --from=builder /app/misc/watcher.py /app/
|
||||||
|
|
||||||
|
# Copy minimal project files to get the test suite.
|
||||||
|
COPY --from=builder /app/pyproject.toml /app/README.md /app/
|
||||||
|
COPY --from=builder /app/tests /app/tests
|
||||||
|
|
||||||
|
ENV PATH="/app/.venv/bin:${PATH}"
|
||||||
|
|
||||||
|
ENTRYPOINT ["/app/.venv/bin/ocrmypdf"]
|
||||||
@@ -1,3 +1,6 @@
|
|||||||
|
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
||||||
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
|
|
||||||
# dotfiles
|
# dotfiles
|
||||||
.*
|
.*
|
||||||
!.coveragerc
|
!.coveragerc
|
||||||
|
|||||||
@@ -1,3 +1,6 @@
|
|||||||
|
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
||||||
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
|
|
||||||
# Always use Unix convention for new lines
|
# Always use Unix convention for new lines
|
||||||
* text eol=lf
|
* text eol=lf
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,6 @@
|
|||||||
|
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
||||||
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
|
|
||||||
# These are supported funding model platforms
|
# These are supported funding model platforms
|
||||||
|
|
||||||
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
|
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
name: Installation, packaging, dependencies
|
||||||
|
description: Installation, packages, dependencies, "nothing works", test suite failures...
|
||||||
|
title: "[Bug]: "
|
||||||
|
labels: ["bug", "triage"]
|
||||||
|
assignees:
|
||||||
|
- jbarlow83
|
||||||
|
body:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
Thanks for taking the time to fill out this bug report!
|
||||||
|
|
||||||
|
If your issue involves using OCRmyPDF on specific file(s) and not getting
|
||||||
|
good results, this is the *wrong* issue template. Please use the recommended
|
||||||
|
template to ensure we have enough information to help.
|
||||||
|
- type: textarea
|
||||||
|
id: what-happened
|
||||||
|
attributes:
|
||||||
|
label: What were you trying to do?
|
||||||
|
description: Also tell us, what did you expect to happen?
|
||||||
|
placeholder: Tell us what you see!
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: dropdown
|
||||||
|
id: packaging-system
|
||||||
|
attributes:
|
||||||
|
label: Where are you installing from?
|
||||||
|
multiple: true
|
||||||
|
options:
|
||||||
|
- PyPI (pip, poetry, pipx, etc.)
|
||||||
|
- Linux package manager (apt, dnf, etc.)
|
||||||
|
- Wndows package manager (chocolatey, etc.)
|
||||||
|
- Homebrew
|
||||||
|
- Docker container
|
||||||
|
- Ubuntu snap
|
||||||
|
- Conda
|
||||||
|
- source build
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: dropdown
|
||||||
|
id: operating-system
|
||||||
|
attributes:
|
||||||
|
label: What operating system are you working on?
|
||||||
|
multiple: true
|
||||||
|
options:
|
||||||
|
- Linux
|
||||||
|
- Windows
|
||||||
|
- macOS
|
||||||
|
- BSD
|
||||||
|
- type: textarea
|
||||||
|
id: logs
|
||||||
|
attributes:
|
||||||
|
label: Relevant log output
|
||||||
|
description: Please copy and paste any relevant log output. This will be automatically formatted into code, so no need for backticks.
|
||||||
|
render: plain text
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
---
|
|
||||||
name: General issues
|
|
||||||
about: Installation, packages, dependencies, "nothing works", test suite failures...
|
|
||||||
title: ''
|
|
||||||
labels: ''
|
|
||||||
assignees: ''
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
**Describe the bug**
|
|
||||||
What's the problem?
|
|
||||||
|
|
||||||
**To Reproduce**
|
|
||||||
Steps to reproduce the behavior.
|
|
||||||
|
|
||||||
**Expected behavior**
|
|
||||||
What did you expected to happen?
|
|
||||||
|
|
||||||
**Screenshots**
|
|
||||||
If applicable, add screenshots to help explain your problem.
|
|
||||||
|
|
||||||
**System (please complete the following information):**
|
|
||||||
- OS:
|
|
||||||
- Python version:
|
|
||||||
- OCRmyPDF version:
|
|
||||||
|
|
||||||
**Installation**
|
|
||||||
How did you install OCRmyPDF? Did you install it from your operating system's
|
|
||||||
package manager, or using pip?
|
|
||||||
|
|
||||||
**Additional context**
|
|
||||||
Add any other context about the problem here.
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
---
|
|
||||||
name: Problem with a specific input file
|
|
||||||
about: Something went wrong while trying to OCR a specific file
|
|
||||||
title: ''
|
|
||||||
labels: ''
|
|
||||||
assignees: ''
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
**Describe the bug**
|
|
||||||
A clear and concise description of what the bug is.
|
|
||||||
|
|
||||||
**To Reproduce**
|
|
||||||
What command line or API call were you trying to run?
|
|
||||||
|
|
||||||
```bash
|
|
||||||
ocrmypdf ...arguments... input.pdf output.pdf
|
|
||||||
```
|
|
||||||
|
|
||||||
Run with verbosity or higher `-v1` to see more detailed logging. This information may be helpful.
|
|
||||||
|
|
||||||
**Example file**
|
|
||||||
If your issue is a problem that affects only certain files, and we will require an input file (PDF or image) that demonstrates your issue.
|
|
||||||
|
|
||||||
Please provide an input file with no personal or confidential information. At your option you may [GPG-encrypt the file](https://github.com/ocrmypdf/OCRmyPDF/wiki) for OCRmyPDF's author only.
|
|
||||||
|
|
||||||
Links to files hosted elsewhere are perfectly acceptable. You could also look in ``tests/resources`` and see if any of those files reproduce your issue.
|
|
||||||
|
|
||||||
*(Issues without example files usually cannot be resolved. It's like reporting an issue against a web browser without providing a URL.)*
|
|
||||||
|
|
||||||
**Expected behavior**
|
|
||||||
A clear and concise description of what you expected to happen.
|
|
||||||
|
|
||||||
**Screenshots**
|
|
||||||
If applicable, add screenshots to help explain your problem.
|
|
||||||
|
|
||||||
**System**
|
|
||||||
- OS: [e.g. Linux, Windows, macOS]
|
|
||||||
- OCRmyPDF Version: ``ocrmypdf --version``
|
|
||||||
- How did you install ocrmypdf? Did you use a system package manager, `pip`, or a Docker image?
|
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
name: Problem with specific file
|
||||||
|
description: Something went wrong while trying to OCR a specific file
|
||||||
|
title: "[Bug]: "
|
||||||
|
labels: ["bug", "triage"]
|
||||||
|
assignees:
|
||||||
|
- jbarlow83
|
||||||
|
body:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
Thanks for taking the time to describe this issue with a particular file.
|
||||||
|
- type: textarea
|
||||||
|
id: what-happened
|
||||||
|
attributes:
|
||||||
|
label: Describe the bug
|
||||||
|
description: A clear and concise description of what the bug is.
|
||||||
|
placeholder: Tell us what you see!
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: reproduce
|
||||||
|
attributes:
|
||||||
|
label: Steps to reproduce
|
||||||
|
description: Please include steps to reproduce
|
||||||
|
value: |
|
||||||
|
1. Run ocrmypdf -v1 ...arguments... input.pdf output.pdf
|
||||||
|
2. Open output.pdf
|
||||||
|
3. ...
|
||||||
|
render: plain text
|
||||||
|
- type: textarea
|
||||||
|
id: files
|
||||||
|
attributes:
|
||||||
|
label: Files
|
||||||
|
description: Please attach the input and output files, or any screenshots that may be helpful.
|
||||||
|
placeholder: |
|
||||||
|
Drag and drop files here.
|
||||||
|
|
||||||
|
If you cannot provide a test file, we probably won't be able to help with the issue.
|
||||||
|
PDF is a complex file format, and there may be technical details in the PDF that are
|
||||||
|
causing the issue. There's really no substitute for a test file.
|
||||||
|
|
||||||
|
We understand files may contain personal or sensitive information. Here are some options:
|
||||||
|
- Try reproducing the issue with a file from the test suite. (See tests/resources)
|
||||||
|
- Try to create another file in the same way as your private file.
|
||||||
|
- Encrypt the file to OCRmyPDF's private GPG key.
|
||||||
|
- Use ``qpdf --json yourfile.pdf`` to produce a JSON representation of your file that
|
||||||
|
omits personal information.
|
||||||
|
|
||||||
|
- type: dropdown
|
||||||
|
id: packaging-system
|
||||||
|
attributes:
|
||||||
|
label: How did you download and install the software?
|
||||||
|
multiple: true
|
||||||
|
options:
|
||||||
|
- PyPI (pip, poetry, pipx, etc.)
|
||||||
|
- Linux package manager (apt, dnf, etc.)
|
||||||
|
- Windows package manager (chocolatey, etc.)
|
||||||
|
- Homebrew
|
||||||
|
- Docker container
|
||||||
|
- Ubuntu snap
|
||||||
|
- Conda
|
||||||
|
- source build
|
||||||
|
- type: input
|
||||||
|
id: version
|
||||||
|
attributes:
|
||||||
|
label: OCRmyPDF version
|
||||||
|
description: Paste "ocrmypdf --version" here
|
||||||
|
placeholder: ocrmypdf --version
|
||||||
|
- type: textarea
|
||||||
|
id: logs
|
||||||
|
attributes:
|
||||||
|
label: Relevant log output
|
||||||
|
description: Please copy and paste any relevant log output. This will be automatically formatted into code, so no need for backticks.
|
||||||
|
placeholder: Run OCRmyPDF with verbosity `-v1` to get more detailed logging output.
|
||||||
|
render: plain text
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
name: Feature request
|
||||||
|
description: Suggest an idea for this project
|
||||||
|
title: "[Feature]: "
|
||||||
|
labels: ["enhancement", "triage"]
|
||||||
|
assignees:
|
||||||
|
- jbarlow83
|
||||||
|
body:
|
||||||
|
- type: textarea
|
||||||
|
id: feature
|
||||||
|
attributes:
|
||||||
|
label: Describe the proposed feature
|
||||||
|
description: A clear and concise description of what the desired is.
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
---
|
|
||||||
name: Feature request
|
|
||||||
about: Suggest an idea for this project
|
|
||||||
title: ''
|
|
||||||
labels: ''
|
|
||||||
assignees: ''
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
**Is your feature request related to a problem? Please describe.**
|
|
||||||
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
|
||||||
|
|
||||||
**Describe the solution you'd like**
|
|
||||||
A clear and concise description of what you want to happen.
|
|
||||||
|
|
||||||
**Describe alternatives you've considered**
|
|
||||||
A clear and concise description of any alternative solutions or features you've considered. Please include the versions of OCRmyPDF and other supporting programs (Tesseract OCR, Ghostscript) - maybe an alternative already exists in a newer version.
|
|
||||||
|
|
||||||
**Example file**
|
|
||||||
If your issue concerns how OCRmyPDF processes certain files, and please provide an example file that helps illustrate how OCRmyPDF's output could be improve.
|
|
||||||
|
|
||||||
Please provide an input file with no personal or confidential information. At your option you may [GPG-encrypt the file](https://github.com/ocrmypdf/OCRmyPDF/wiki) for OCRmyPDF's author only.
|
|
||||||
|
|
||||||
Links to files hosted elsewhere are perfectly acceptable. You could also look in ``tests/resources`` and see if any of those files reproduce your issue.
|
|
||||||
|
|
||||||
**Additional context**
|
|
||||||
Add any other context or screenshots about the feature request here.
|
|
||||||
@@ -1,3 +1,6 @@
|
|||||||
|
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
||||||
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
|
|
||||||
# To get started with Dependabot version updates, you'll need to specify which
|
# To get started with Dependabot version updates, you'll need to specify which
|
||||||
# package ecosystems to update and where the package manifests are located.
|
# package ecosystems to update and where the package manifests are located.
|
||||||
# Please see the documentation for all configuration options:
|
# Please see the documentation for all configuration options:
|
||||||
|
|||||||
+134
-66
@@ -1,9 +1,11 @@
|
|||||||
|
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
||||||
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
name: Test and deploy
|
name: Test and deploy
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- master
|
- main
|
||||||
- ci
|
- ci
|
||||||
- release/*
|
- release/*
|
||||||
- feature/*
|
- feature/*
|
||||||
@@ -20,40 +22,38 @@ jobs:
|
|||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
include:
|
include:
|
||||||
- os: ubuntu-18.04
|
- os: ubuntu-22.04
|
||||||
python: "3.7"
|
python: "3.10"
|
||||||
- os: ubuntu-20.04
|
- os: ubuntu-22.04
|
||||||
python: "3.8"
|
python: "3.11"
|
||||||
- os: ubuntu-20.04
|
- os: ubuntu-22.04
|
||||||
python: "3.9"
|
|
||||||
- os: ubuntu-20.04
|
|
||||||
python: "3.10"
|
python: "3.10"
|
||||||
- os: ubuntu-latest
|
|
||||||
python: "3.9"
|
|
||||||
- os: ubuntu-latest
|
|
||||||
python: "pypy-3.8"
|
|
||||||
- os: ubuntu-latest
|
|
||||||
python: "3.9"
|
|
||||||
tesseract5: true
|
tesseract5: true
|
||||||
|
- os: ubuntu-latest
|
||||||
|
python: "3.12"
|
||||||
|
tesseract5: true
|
||||||
|
# - os: ubuntu-latest
|
||||||
|
# python: "pypy3.10"
|
||||||
|
|
||||||
env:
|
env:
|
||||||
OS: ${{ matrix.os }}
|
OS: ${{ matrix.os }}
|
||||||
PYTHON: ${{ matrix.python }}
|
PYTHON: ${{ matrix.python }}
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
fetch-depth: "0" # 0=all, needed for setuptools-scm to resolve version tags
|
fetch-depth: "0" # 0=all, needed for setuptools-scm to resolve version tags
|
||||||
|
|
||||||
- uses: actions/setup-python@v4
|
- uses: actions/setup-python@v5
|
||||||
name: Install Python
|
name: Setup Python
|
||||||
with:
|
with:
|
||||||
python-version: ${{ matrix.python }}
|
python-version: ${{ matrix.python }}
|
||||||
|
cache: "pip"
|
||||||
|
|
||||||
- name: Install Tesseract 5
|
- name: Install Tesseract 5
|
||||||
if: matrix.tesseract5
|
if: matrix.tesseract5
|
||||||
run: |
|
run: |
|
||||||
sudo add-apt-repository ppa:alex-p/tesseract-ocr-devel
|
sudo add-apt-repository -y ppa:alex-p/tesseract-ocr-devel
|
||||||
|
|
||||||
- name: Install common packages
|
- name: Install common packages
|
||||||
run: |
|
run: |
|
||||||
@@ -62,6 +62,7 @@ jobs:
|
|||||||
curl \
|
curl \
|
||||||
ghostscript \
|
ghostscript \
|
||||||
img2pdf \
|
img2pdf \
|
||||||
|
libexempi8 \
|
||||||
libffi-dev \
|
libffi-dev \
|
||||||
libsm6 libxext6 libxrender-dev \
|
libsm6 libxext6 libxrender-dev \
|
||||||
pngquant \
|
pngquant \
|
||||||
@@ -73,18 +74,6 @@ jobs:
|
|||||||
unpaper \
|
unpaper \
|
||||||
zlib1g
|
zlib1g
|
||||||
|
|
||||||
- name: Install Ubuntu 18.04 packages
|
|
||||||
if: matrix.os == 'ubuntu-18.04'
|
|
||||||
run: |
|
|
||||||
sudo apt-get install -y --no-install-recommends \
|
|
||||||
libexempi3
|
|
||||||
|
|
||||||
- name: Install Ubuntu 20.04 packages
|
|
||||||
if: matrix.os == 'ubuntu-20.04' || matrix.os == 'ubuntu-latest'
|
|
||||||
run: |
|
|
||||||
sudo apt-get install -y --no-install-recommends \
|
|
||||||
libexempi8
|
|
||||||
|
|
||||||
- name: Install Ubuntu packages for PyPy
|
- name: Install Ubuntu packages for PyPy
|
||||||
if: startsWith(matrix.python, 'pypy')
|
if: startsWith(matrix.python, 'pypy')
|
||||||
run: |
|
run: |
|
||||||
@@ -96,7 +85,7 @@ jobs:
|
|||||||
- name: Install Python packages
|
- name: Install Python packages
|
||||||
run: |
|
run: |
|
||||||
python -m pip install --upgrade pip wheel
|
python -m pip install --upgrade pip wheel
|
||||||
python -m pip install .[test]
|
python -m pip install --prefer-binary .[test]
|
||||||
|
|
||||||
- name: Report versions
|
- name: Report versions
|
||||||
run: |
|
run: |
|
||||||
@@ -122,23 +111,19 @@ jobs:
|
|||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
os: [macos-latest]
|
os: [macos-latest]
|
||||||
python: ["3.9", "3.10"]
|
python: ["3.10", "3.11", "3.12"]
|
||||||
|
|
||||||
env:
|
env:
|
||||||
OS: ${{ matrix.os }}
|
OS: ${{ matrix.os }}
|
||||||
PYTHON: ${{ matrix.python }}
|
PYTHON: ${{ matrix.python }}
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
fetch-depth: "0" # 0=all, needed for setuptools-scm to resolve version tags
|
fetch-depth: "0" # 0=all, needed for setuptools-scm to resolve version tags
|
||||||
|
|
||||||
- uses: actions/setup-python@v4
|
|
||||||
name: Install Python
|
|
||||||
with:
|
|
||||||
python-version: ${{ matrix.python }}
|
|
||||||
|
|
||||||
- name: Install Homebrew deps
|
- name: Install Homebrew deps
|
||||||
|
continue-on-error: true
|
||||||
run: |
|
run: |
|
||||||
brew update
|
brew update
|
||||||
brew install \
|
brew install \
|
||||||
@@ -146,13 +131,20 @@ jobs:
|
|||||||
ghostscript \
|
ghostscript \
|
||||||
jbig2enc \
|
jbig2enc \
|
||||||
openjpeg \
|
openjpeg \
|
||||||
|
openssl \
|
||||||
pngquant \
|
pngquant \
|
||||||
tesseract
|
tesseract
|
||||||
|
|
||||||
|
- uses: actions/setup-python@v5
|
||||||
|
name: Setup Python
|
||||||
|
with:
|
||||||
|
python-version: ${{ matrix.python }}
|
||||||
|
cache: "pip"
|
||||||
|
|
||||||
- name: Install Python packages
|
- name: Install Python packages
|
||||||
run: |
|
run: |
|
||||||
python -m pip install --upgrade pip wheel
|
python -m pip install --upgrade pip wheel
|
||||||
python -m pip install .[test]
|
python -m pip install --prefer-binary .[test]
|
||||||
|
|
||||||
- name: Report versions
|
- name: Report versions
|
||||||
run: |
|
run: |
|
||||||
@@ -177,21 +169,22 @@ jobs:
|
|||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
os: [windows-latest]
|
os: [windows-latest]
|
||||||
python: ["3.9", "3.10"]
|
python: ["3.10", "3.11", "3.12"]
|
||||||
|
|
||||||
env:
|
env:
|
||||||
OS: ${{ matrix.os }}
|
OS: ${{ matrix.os }}
|
||||||
PYTHON: ${{ matrix.python }}
|
PYTHON: ${{ matrix.python }}
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
fetch-depth: "0" # 0=all, needed for setuptools-scm to resolve version tags
|
fetch-depth: "0" # 0=all, needed for setuptools-scm to resolve version tags
|
||||||
|
|
||||||
- uses: actions/setup-python@v4
|
- uses: actions/setup-python@v5
|
||||||
name: Install Python
|
name: Setup Python
|
||||||
with:
|
with:
|
||||||
python-version: ${{ matrix.python }}
|
python-version: ${{ matrix.python }}
|
||||||
|
cache: "pip"
|
||||||
|
|
||||||
- name: Install system packages
|
- name: Install system packages
|
||||||
run: |
|
run: |
|
||||||
@@ -201,7 +194,7 @@ jobs:
|
|||||||
- name: Install Python packages
|
- name: Install Python packages
|
||||||
run: |
|
run: |
|
||||||
python -m pip install --upgrade pip wheel
|
python -m pip install --upgrade pip wheel
|
||||||
python -m pip install .[test]
|
python -m pip install --prefer-binary .[test]
|
||||||
|
|
||||||
- name: Test
|
- name: Test
|
||||||
run: |
|
run: |
|
||||||
@@ -217,23 +210,24 @@ jobs:
|
|||||||
name: Build sdist and wheels
|
name: Build sdist and wheels
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
fetch-depth: "0" # 0=all, needed for setuptools-scm to resolve version tags
|
fetch-depth: "0" # 0=all, needed for setuptools-scm to resolve version tags
|
||||||
|
|
||||||
- uses: actions/setup-python@v4
|
- uses: actions/setup-python@v5
|
||||||
name: Install Python
|
name: Setup Python
|
||||||
with:
|
with:
|
||||||
python-version: "3.7"
|
python-version: "3.10"
|
||||||
|
cache: "pip"
|
||||||
|
|
||||||
- name: Make wheels and sdist
|
- name: Make wheels and sdist
|
||||||
run: |
|
run: |
|
||||||
python -m pip install --upgrade pip wheel
|
python -m pip install --upgrade pip wheel build
|
||||||
python setup.py sdist
|
python -m build --sdist --wheel
|
||||||
python setup.py bdist_wheel
|
|
||||||
|
|
||||||
- uses: actions/upload-artifact@v3
|
- uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
|
name: artifact
|
||||||
path: |
|
path: |
|
||||||
./dist/*.whl
|
./dist/*.whl
|
||||||
./dist/*.tar.gz
|
./dist/*.tar.gz
|
||||||
@@ -242,21 +236,47 @@ jobs:
|
|||||||
name: Deploy artifacts to PyPI
|
name: Deploy artifacts to PyPI
|
||||||
needs: [wheel_sdist_linux, test_linux, test_macos, test_windows]
|
needs: [wheel_sdist_linux, test_linux, test_macos, test_windows]
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
environment: release
|
||||||
|
permissions:
|
||||||
|
id-token: write # mandatory for PyPI publishing
|
||||||
if: github.event_name == 'push' && startsWith(github.event.ref, 'refs/tags/v')
|
if: github.event_name == 'push' && startsWith(github.event.ref, 'refs/tags/v')
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/download-artifact@v3
|
- uses: actions/download-artifact@v4
|
||||||
with:
|
with:
|
||||||
name: artifact
|
name: artifact
|
||||||
path: dist
|
path: dist
|
||||||
|
|
||||||
- uses: pypa/gh-action-pypi-publish@master
|
- name: Publish to PyPI
|
||||||
with:
|
uses: pypa/gh-action-pypi-publish@release/v1
|
||||||
user: __token__
|
|
||||||
password: ${{ secrets.TOKEN_PYPI }}
|
|
||||||
# repository_url: https://test.pypi.org/legacy/
|
|
||||||
|
|
||||||
docker:
|
create_release:
|
||||||
name: Build Docker images
|
name: Create GitHub release
|
||||||
|
needs: [wheel_sdist_linux, test_linux, test_macos, test_windows]
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
if: github.event_name == 'push' && startsWith(github.event.ref, 'refs/tags/v')
|
||||||
|
permissions:
|
||||||
|
# Required to create a release
|
||||||
|
contents: write
|
||||||
|
steps:
|
||||||
|
- uses: actions/download-artifact@v4
|
||||||
|
with:
|
||||||
|
name: artifact
|
||||||
|
path: dist
|
||||||
|
|
||||||
|
- name: Create Release
|
||||||
|
id: create-release
|
||||||
|
uses: shogo82148/actions-create-release@v1
|
||||||
|
|
||||||
|
- name: Upload Assets
|
||||||
|
uses: shogo82148/actions-upload-release-asset@v1
|
||||||
|
with:
|
||||||
|
upload_url: ${{ steps.create-release.outputs.upload_url }}
|
||||||
|
asset_path: |
|
||||||
|
./dist/*.whl
|
||||||
|
./dist/*.tar.gz
|
||||||
|
|
||||||
|
docker_ubuntu:
|
||||||
|
name: Build Ubuntu-based Docker image
|
||||||
needs: [wheel_sdist_linux, test_linux, test_macos, test_windows]
|
needs: [wheel_sdist_linux, test_linux, test_macos, test_windows]
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
if: github.event_name != 'pull_request'
|
if: github.event_name != 'pull_request'
|
||||||
@@ -264,9 +284,9 @@ jobs:
|
|||||||
- name: Set image tag to release or branch
|
- name: Set image tag to release or branch
|
||||||
run: echo "DOCKER_IMAGE_TAG=${GITHUB_REF##*/}" >> $GITHUB_ENV
|
run: echo "DOCKER_IMAGE_TAG=${GITHUB_REF##*/}" >> $GITHUB_ENV
|
||||||
|
|
||||||
- name: If master, set to latest
|
- name: If main, set to latest
|
||||||
run: echo 'DOCKER_IMAGE_TAG=latest' >> $GITHUB_ENV
|
run: echo 'DOCKER_IMAGE_TAG=latest' >> $GITHUB_ENV
|
||||||
if: env.DOCKER_IMAGE_TAG == 'master'
|
if: env.DOCKER_IMAGE_TAG == 'main'
|
||||||
|
|
||||||
- name: Set Docker Hub repository to username
|
- name: Set Docker Hub repository to username
|
||||||
run: echo "DOCKER_REPOSITORY=jbarlow83" >> $GITHUB_ENV
|
run: echo "DOCKER_REPOSITORY=jbarlow83" >> $GITHUB_ENV
|
||||||
@@ -274,22 +294,22 @@ jobs:
|
|||||||
- name: Set image name
|
- name: Set image name
|
||||||
run: echo "DOCKER_IMAGE_NAME=ocrmypdf" >> $GITHUB_ENV
|
run: echo "DOCKER_IMAGE_NAME=ocrmypdf" >> $GITHUB_ENV
|
||||||
|
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
fetch-depth: "0" # 0=all, needed for setuptools-scm to resolve version tags
|
fetch-depth: "0" # 0=all, needed for setuptools-scm to resolve version tags
|
||||||
|
|
||||||
- name: Login to Docker Hub
|
- name: Login to Docker Hub
|
||||||
uses: docker/login-action@v2
|
uses: docker/login-action@v3
|
||||||
with:
|
with:
|
||||||
username: jbarlow83
|
username: jbarlow83
|
||||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||||
|
|
||||||
- name: Set up QEMU
|
- name: Set up QEMU
|
||||||
uses: docker/setup-qemu-action@v2
|
uses: docker/setup-qemu-action@v3
|
||||||
|
|
||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
id: buildx
|
id: buildx
|
||||||
uses: docker/setup-buildx-action@v2
|
uses: docker/setup-buildx-action@v3
|
||||||
|
|
||||||
- name: Print image tag
|
- name: Print image tag
|
||||||
run: echo "Building image ${DOCKER_REPOSITORY}/${DOCKER_IMAGE_NAME}:${DOCKER_IMAGE_TAG}"
|
run: echo "Building image ${DOCKER_REPOSITORY}/${DOCKER_IMAGE_NAME}:${DOCKER_IMAGE_TAG}"
|
||||||
@@ -300,4 +320,52 @@ jobs:
|
|||||||
--push \
|
--push \
|
||||||
--platform linux/arm64/v8,linux/amd64 \
|
--platform linux/arm64/v8,linux/amd64 \
|
||||||
--tag "${DOCKER_REPOSITORY}/${DOCKER_IMAGE_NAME}:${DOCKER_IMAGE_TAG}" \
|
--tag "${DOCKER_REPOSITORY}/${DOCKER_IMAGE_NAME}:${DOCKER_IMAGE_TAG}" \
|
||||||
|
--tag "${DOCKER_REPOSITORY}/${DOCKER_IMAGE_NAME}-ubuntu:${DOCKER_IMAGE_TAG}" \
|
||||||
--file .docker/Dockerfile .
|
--file .docker/Dockerfile .
|
||||||
|
|
||||||
|
docker_alpine:
|
||||||
|
name: Build Alpine-based Docker images
|
||||||
|
needs: [wheel_sdist_linux, test_linux, test_macos, test_windows]
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
if: github.event_name != 'pull_request'
|
||||||
|
steps:
|
||||||
|
- name: Set image tag to release or branch
|
||||||
|
run: echo "DOCKER_IMAGE_TAG=${GITHUB_REF##*/}" >> $GITHUB_ENV
|
||||||
|
|
||||||
|
- name: If main, set to latest
|
||||||
|
run: echo 'DOCKER_IMAGE_TAG=latest' >> $GITHUB_ENV
|
||||||
|
if: env.DOCKER_IMAGE_TAG == 'main'
|
||||||
|
|
||||||
|
- name: Set Docker Hub repository to username
|
||||||
|
run: echo "DOCKER_REPOSITORY=jbarlow83" >> $GITHUB_ENV
|
||||||
|
|
||||||
|
- name: Set image name
|
||||||
|
run: echo "DOCKER_IMAGE_NAME=ocrmypdf-alpine" >> $GITHUB_ENV
|
||||||
|
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: "0" # 0=all, needed for setuptools-scm to resolve version tags
|
||||||
|
|
||||||
|
- name: Login to Docker Hub
|
||||||
|
uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
username: jbarlow83
|
||||||
|
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Set up QEMU
|
||||||
|
uses: docker/setup-qemu-action@v3
|
||||||
|
|
||||||
|
- name: Set up Docker Buildx
|
||||||
|
id: buildx
|
||||||
|
uses: docker/setup-buildx-action@v3
|
||||||
|
|
||||||
|
- name: Print image tag
|
||||||
|
run: echo "Building image ${DOCKER_REPOSITORY}/${DOCKER_IMAGE_NAME}:${DOCKER_IMAGE_TAG}"
|
||||||
|
|
||||||
|
- name: Build
|
||||||
|
run: |
|
||||||
|
docker buildx build \
|
||||||
|
--push \
|
||||||
|
--platform linux/amd64 \
|
||||||
|
--tag "${DOCKER_REPOSITORY}/${DOCKER_IMAGE_NAME}:${DOCKER_IMAGE_TAG}" \
|
||||||
|
--file .docker/Dockerfile.alpine .
|
||||||
|
|||||||
+12
-11
@@ -1,14 +1,15 @@
|
|||||||
|
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
||||||
|
# SPDX-License-Identifier: CC-BY-SA-4.0
|
||||||
|
|
||||||
# dotfiles
|
# dotfiles
|
||||||
.*
|
.coverage
|
||||||
!.coveragerc
|
.venv*/
|
||||||
!.dockerignore
|
.tox/
|
||||||
!.git_archival.txt
|
.vscode/
|
||||||
!.gitattributes
|
.hypothesis/
|
||||||
!.gitignore
|
.ipynb_checkpoints/
|
||||||
!.pre-commit-config.yaml
|
.mypy_cache/
|
||||||
!.readthedocs.yaml
|
.pytest_cache/
|
||||||
!.github/
|
|
||||||
!.docker/
|
|
||||||
|
|
||||||
# Dev scratch
|
# Dev scratch
|
||||||
*.ipynb
|
*.ipynb
|
||||||
@@ -26,6 +27,7 @@ venv*/
|
|||||||
*.traineddata
|
*.traineddata
|
||||||
/private
|
/private
|
||||||
/coverage.xml
|
/coverage.xml
|
||||||
|
/issuepdf
|
||||||
|
|
||||||
# Package building
|
# Package building
|
||||||
*.egg-info/
|
*.egg-info/
|
||||||
@@ -42,4 +44,3 @@ docs/_build/
|
|||||||
docs/_static/
|
docs/_static/
|
||||||
docs/_templates/
|
docs/_templates/
|
||||||
docs/Makefile
|
docs/Makefile
|
||||||
ocrmypdf/lib/_*.py
|
|
||||||
|
|||||||
+11
-16
@@ -1,33 +1,28 @@
|
|||||||
|
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
||||||
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
|
|
||||||
repos:
|
repos:
|
||||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||||
rev: v4.3.0
|
rev: v4.4.0
|
||||||
hooks:
|
hooks:
|
||||||
- id: check-case-conflict
|
- id: check-case-conflict
|
||||||
- id: check-merge-conflict
|
- id: check-merge-conflict
|
||||||
- id: check-toml
|
- id: check-toml
|
||||||
- id: check-yaml
|
- id: check-yaml
|
||||||
- id: debug-statements
|
- id: debug-statements
|
||||||
- repo: https://github.com/pycqa/isort
|
- repo: https://github.com/charliermarsh/ruff-pre-commit
|
||||||
rev: 5.10.1
|
rev: "v0.0.261"
|
||||||
hooks:
|
hooks:
|
||||||
- id: isort
|
- id: ruff
|
||||||
args: ["--profile", "black", "-a", "from __future__ import annotations"]
|
files: "src/.*\\.pyi?$"
|
||||||
|
args: [--fix, --exit-non-zero-on-fix]
|
||||||
- repo: https://github.com/psf/black
|
- repo: https://github.com/psf/black
|
||||||
rev: 22.6.0
|
rev: 23.3.0
|
||||||
hooks:
|
hooks:
|
||||||
- id: black
|
- id: black
|
||||||
language_version: python
|
language_version: python
|
||||||
- repo: https://github.com/asottile/setup-cfg-fmt
|
|
||||||
rev: v1.20.2
|
|
||||||
hooks:
|
|
||||||
- id: setup-cfg-fmt
|
|
||||||
- repo: https://github.com/asottile/pyupgrade
|
|
||||||
rev: v2.37.2
|
|
||||||
hooks:
|
|
||||||
- id: pyupgrade
|
|
||||||
args: ["--py37-plus"]
|
|
||||||
- repo: https://github.com/pre-commit/mirrors-mypy
|
- repo: https://github.com/pre-commit/mirrors-mypy
|
||||||
rev: v0.971
|
rev: v1.2.0
|
||||||
hooks:
|
hooks:
|
||||||
- id: mypy
|
- id: mypy
|
||||||
additional_dependencies:
|
additional_dependencies:
|
||||||
|
|||||||
+8
-1
@@ -1,3 +1,6 @@
|
|||||||
|
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
||||||
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
|
|
||||||
# Read the Docs configuration file
|
# Read the Docs configuration file
|
||||||
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
|
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
|
||||||
|
|
||||||
@@ -13,8 +16,12 @@ formats:
|
|||||||
- pdf
|
- pdf
|
||||||
|
|
||||||
# Optionally set the version of Python and requirements required to build your docs
|
# Optionally set the version of Python and requirements required to build your docs
|
||||||
|
build:
|
||||||
|
os: ubuntu-22.04
|
||||||
|
tools:
|
||||||
|
python: "3.10"
|
||||||
|
|
||||||
python:
|
python:
|
||||||
version: "3.7"
|
|
||||||
install:
|
install:
|
||||||
- method: pip
|
- method: pip
|
||||||
path: .
|
path: .
|
||||||
|
|||||||
+140
@@ -0,0 +1,140 @@
|
|||||||
|
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
|
||||||
|
Upstream-Name: OCRmyPDF
|
||||||
|
Upstream-Contact: James R. Barlow <james@purplerock.ca>
|
||||||
|
Source: https://github.com/ocrmypdf/OCRmyPDF
|
||||||
|
|
||||||
|
Files:
|
||||||
|
.git_archival.txt
|
||||||
|
docs/images/logo-social.png
|
||||||
|
docs/images/logo-square-256.svg
|
||||||
|
docs/images/logo-square.png
|
||||||
|
docs/images/logo-square.svg
|
||||||
|
docs/images/logo.svg
|
||||||
|
Copyright: (C) 2022 James R. Barlow
|
||||||
|
License: MPL-2.0
|
||||||
|
|
||||||
|
Files:
|
||||||
|
.github/ISSUE_TEMPLATE/*.yml
|
||||||
|
docs/images/macos-workflow.png
|
||||||
|
Copyright: (C) 2023 James R. Barlow
|
||||||
|
License: CC-BY-SA-4.0
|
||||||
|
|
||||||
|
Files:
|
||||||
|
tests/resources/acroform.pdf
|
||||||
|
tests/resources/aspect.pdf
|
||||||
|
tests/resources/blank.pdf
|
||||||
|
tests/resources/cmyk.pdf
|
||||||
|
tests/resources/crom.png
|
||||||
|
tests/resources/enormous.pdf
|
||||||
|
tests/resources/formxobject.pdf
|
||||||
|
tests/resources/francais.pdf
|
||||||
|
tests/resources/hugemono.pdf
|
||||||
|
tests/resources/invalid.pdf
|
||||||
|
tests/resources/kcs.pdf
|
||||||
|
tests/resources/livecycle.pdf
|
||||||
|
tests/resources/meta.pdf
|
||||||
|
tests/resources/missing_docinfo.pdf
|
||||||
|
tests/resources/negzero.pdf
|
||||||
|
tests/resources/no_contents.pdf
|
||||||
|
tests/resources/tagged*
|
||||||
|
tests/resources/toc.pdf
|
||||||
|
tests/resources/trivial.pdf
|
||||||
|
tests/resources/truetype_font_nomapping.pdf
|
||||||
|
tests/resources/type3_font_nomapping.pdf
|
||||||
|
Copyright: (C) 2023 James R. Barlow
|
||||||
|
License: CC-BY-SA-4.0
|
||||||
|
|
||||||
|
Files:
|
||||||
|
tests/resources/graph.pdf
|
||||||
|
tests/resources/graph_ocred.pdf
|
||||||
|
Copyright: (C) 2012 SmokeyJoe
|
||||||
|
License: GFDL-1.2-or-later or CC-BY-SA-3.0
|
||||||
|
|
||||||
|
Files: tests/resources/c02-22.pdf
|
||||||
|
tests/resources/multipage.pdf
|
||||||
|
Copyright: Public domain
|
||||||
|
License: public-domain
|
||||||
|
Copyright on these files has expired.
|
||||||
|
|
||||||
|
Files: docs/images/bitmap_vs_svg.svg
|
||||||
|
Copyright: (C) 2006 Yug
|
||||||
|
License: CC-BY-SA-2.5
|
||||||
|
|
||||||
|
Files: tests/cache/*
|
||||||
|
Copyright: (C) 2022 James R. Barlow
|
||||||
|
License: CC-BY-SA-4.0
|
||||||
|
|
||||||
|
Files: tests/resources/linn.png
|
||||||
|
tests/resources/linn.pdf
|
||||||
|
tests/resources/linn.txt
|
||||||
|
tests/resources/ccitt.pdf
|
||||||
|
tests/resources/cardinal.pdf
|
||||||
|
tests/resources/jbig2.pdf
|
||||||
|
tests/resources/jbig2_baddevicen.pdf
|
||||||
|
tests/resources/skew.pdf
|
||||||
|
tests/resources/rotated_skew.pdf
|
||||||
|
tests/resources/poster.pdf
|
||||||
|
Copyright: (C) 1985 Forat Electronics
|
||||||
|
License: GFDL-1.2-or-later or CC-BY-SA-3.0
|
||||||
|
|
||||||
|
Files: tests/resources/lichtenstein.pdf
|
||||||
|
Copyright: (C) 2001 Andreas Tille
|
||||||
|
(C) 2007 Alessio Damato
|
||||||
|
License: GFDL-1.2-or-later or CC-BY-SA-3.0
|
||||||
|
|
||||||
|
Files: tests/resources/masks.pdf
|
||||||
|
Copyright: held by the contributors to the German Wikipedia article "Linux"
|
||||||
|
see: https://de.wikipedia.org/w/index.php?title=Linux&action=history
|
||||||
|
(masks.pdf generated from Wikipedia article as of 2016-08-24)
|
||||||
|
License: CC-BY-SA-3.0
|
||||||
|
|
||||||
|
Files: tests/resources/epson.pdf
|
||||||
|
Copyright: held by the contributors to the Wikipedia article "Optical character recognition"
|
||||||
|
see: https://en.wikipedia.org/w/index.php?title=Optical_character_recognition&action=history
|
||||||
|
(epson.pdf generated from Wikipedia article as of 2016-09-14)
|
||||||
|
License: CC-BY-SA-3.0
|
||||||
|
|
||||||
|
Files: tests/resources/typewriter.png tests/resources/2400dpi.pdf
|
||||||
|
Copyright: (C) 2005 Ellywa
|
||||||
|
License: GFDL-1.2-or-later or CC-BY-SA-1.0 or CC-BY-SA-2.0 or CC-BY-SA-2.5 or CC-BY-SA-3.0
|
||||||
|
Comment:
|
||||||
|
Obtained from: https://commons.wikimedia.org/wiki/File:Triumph.typewriter_text_Linzensoep.gif
|
||||||
|
|
||||||
|
Files: tests/resources/overlay.pdf
|
||||||
|
Copyright: (C) 2017 Max Anderson
|
||||||
|
License: MIT
|
||||||
|
|
||||||
|
Files:
|
||||||
|
tests/resources/baiona*.png
|
||||||
|
tests/resources/baiona*.jpg
|
||||||
|
tests/resources/link.pdf
|
||||||
|
tests/resources/palette.pdf
|
||||||
|
Copyright: (C) 2014 Euskaldunaa
|
||||||
|
License: CC-BY-SA-4.0
|
||||||
|
|
||||||
|
Files: tests/resources/vector.pdf
|
||||||
|
Copyright: (C) 2018 Catscratch
|
||||||
|
License: MIT
|
||||||
|
|
||||||
|
Files: src/ocrmypdf/data/sRGB.icc
|
||||||
|
Copyright: Kai-Uwe Behrmann <www.behrmann.name>
|
||||||
|
Marti Maria <www.littlecms.com>
|
||||||
|
Photogamut <www.photogamut.org>
|
||||||
|
Graeme Gill <www.argyllcms.com>
|
||||||
|
ColorSolutions <www.basICColor.com>
|
||||||
|
License: Zlib
|
||||||
|
|
||||||
|
Files: src/ocrmypdf/data/pdf.ttf
|
||||||
|
Copyright: (C) 2014 Ray Smith
|
||||||
|
(C) 2015 Ken Sharp
|
||||||
|
(C) 2016 James R. Barlow
|
||||||
|
(C) 2016 Jeff Breidenbach
|
||||||
|
(C) 2017 Zdenko Podobný
|
||||||
|
License: Apache-2.0
|
||||||
|
|
||||||
|
Files: tests/resources/3small.pdf
|
||||||
|
Copyright: (C) 2014 Euskaldunaa
|
||||||
|
(C) 2017 James R. Barlow
|
||||||
|
(C) 2005 Ellywa
|
||||||
|
License: CC-BY-SA-4.0 and (GFDL-1.2-or-later or CC-BY-SA-1.0 or CC-BY-SA-2.0 or CC-BY-SA-2.5 or CC-BY-SA-3.0)
|
||||||
|
Comment: concatenation of baiona_gray.png, crom.png and typewriter.png/2400dpi.pdf
|
||||||
@@ -1,3 +1,7 @@
|
|||||||
|
<!-- SPDX-FileCopyrightText: 2014 Julien Pfefferkorn -->
|
||||||
|
<!-- SPDX-FileCopyrightText: 2015 James R. Barlow -->
|
||||||
|
<!-- SPDX-License-Identifier: CC-BY-SA-4.0 -->
|
||||||
|
|
||||||
<img src="docs/images/logo.svg" width="240" alt="OCRmyPDF">
|
<img src="docs/images/logo.svg" width="240" alt="OCRmyPDF">
|
||||||
|
|
||||||
[](https://github.com/ocrmypdf/OCRmyPDF/actions/workflows/build.yml) [![PyPI version][pypi]](https://pypi.org/project/ocrmypdf/) ![Homebrew version][homebrew] ![ReadTheDocs][docs] ![Python versions][pyversions]
|
[](https://github.com/ocrmypdf/OCRmyPDF/actions/workflows/build.yml) [![PyPI version][pypi]](https://pypi.org/project/ocrmypdf/) ![Homebrew version][homebrew] ![ReadTheDocs][docs] ![Python versions][pyversions]
|
||||||
@@ -35,8 +39,10 @@ ocrmypdf # it's a scriptable command line program
|
|||||||
- Distributes work across all available CPU cores
|
- Distributes work across all available CPU cores
|
||||||
- Uses [Tesseract OCR](https://github.com/tesseract-ocr/tesseract) engine to recognize more than [100 languages](https://github.com/tesseract-ocr/tessdata)
|
- Uses [Tesseract OCR](https://github.com/tesseract-ocr/tesseract) engine to recognize more than [100 languages](https://github.com/tesseract-ocr/tessdata)
|
||||||
- Keeps your private data private.
|
- Keeps your private data private.
|
||||||
- Scales properly to handle files with thousands of pages
|
- Scales properly to handle files with thousands of pages.
|
||||||
- Battle-tested on millions of PDFs
|
- Battle-tested on millions of PDFs.
|
||||||
|
|
||||||
|
<img src="misc/screencast/demo.svg" alt="Demo of OCRmyPDF in a terminal session">
|
||||||
|
|
||||||
For details: please consult the [documentation](https://ocrmypdf.readthedocs.io/en/latest/).
|
For details: please consult the [documentation](https://ocrmypdf.readthedocs.io/en/latest/).
|
||||||
|
|
||||||
@@ -64,9 +70,9 @@ Linux, Windows, macOS and FreeBSD are supported. Docker images are also availabl
|
|||||||
| Windows Subsystem for Linux | ``apt install ocrmypdf`` |
|
| Windows Subsystem for Linux | ``apt install ocrmypdf`` |
|
||||||
| Fedora | ``dnf install ocrmypdf`` |
|
| Fedora | ``dnf install ocrmypdf`` |
|
||||||
| macOS (Homebrew) | ``brew install ocrmypdf`` |
|
| macOS (Homebrew) | ``brew install ocrmypdf`` |
|
||||||
| macOS (nix) | ``nix-env -i ocrmypdf`` |
|
| macOS (nix) | ``nix-env -i ocrmypdf`` |
|
||||||
| LinuxBrew | ``brew install ocrmypdf`` |
|
| LinuxBrew | ``brew install ocrmypdf`` |
|
||||||
| FreeBSD | ``pkg install py37-ocrmypdf`` |
|
| FreeBSD | ``pkg install py-ocrmypdf`` |
|
||||||
| Conda | ``conda install ocrmypdf`` |
|
| Conda | ``conda install ocrmypdf`` |
|
||||||
| Ubuntu Snap | ``snap install ocrmypdf`` |
|
| Ubuntu Snap | ``snap install ocrmypdf`` |
|
||||||
|
|
||||||
@@ -92,10 +98,7 @@ brew install tesseract-lang
|
|||||||
|
|
||||||
You can then pass the `-l LANG` argument to OCRmyPDF to give a hint as to what languages it should search for. Multiple languages can be requested.
|
You can then pass the `-l LANG` argument to OCRmyPDF to give a hint as to what languages it should search for. Multiple languages can be requested.
|
||||||
|
|
||||||
OCRmyPDF supports Tesseract 4.0 and the beta versions of Tesseract 5.0. It will
|
OCRmyPDF supports Tesseract 4.1.1+. It will automatically use whichever version it finds first on the `PATH` environment variable. On Windows, if `PATH` does not provide a Tesseract binary, we use the highest version number that is installed according to the Windows Registry.
|
||||||
automatically use whichever version it finds first on the `PATH` environment
|
|
||||||
variable. On Windows, if `PATH` does not provide a Tesseract binary, we use
|
|
||||||
the highest version number that is installed according to the Windows Registry.
|
|
||||||
|
|
||||||
## Documentation and support
|
## Documentation and support
|
||||||
|
|
||||||
@@ -111,7 +114,7 @@ Please report issues on our [GitHub issues](https://github.com/ocrmypdf/OCRmyPDF
|
|||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
|
||||||
In addition to the required Python version (3.7+), OCRmyPDF requires external program installations of Ghostscript and Tesseract OCR. OCRmyPDF is pure Python, and runs on pretty much everything: Linux, macOS, Windows and FreeBSD.
|
In addition to the required Python version (3.8+), OCRmyPDF requires external program installations of Ghostscript and Tesseract OCR. OCRmyPDF is pure Python, and runs on pretty much everything: Linux, macOS, Windows and FreeBSD.
|
||||||
|
|
||||||
## Press & Media
|
## Press & Media
|
||||||
|
|
||||||
@@ -122,6 +125,7 @@ In addition to the required Python version (3.7+), OCRmyPDF requires external pr
|
|||||||
- [heise Durchsuchbare PDF-Dokumente mit OCRmyPDF erstellen](https://www.heise.de/ratgeber/Durchsuchbare-PDF-Dokumente-mit-OCRmyPDF-erstellen-4607592.html)
|
- [heise Durchsuchbare PDF-Dokumente mit OCRmyPDF erstellen](https://www.heise.de/ratgeber/Durchsuchbare-PDF-Dokumente-mit-OCRmyPDF-erstellen-4607592.html)
|
||||||
- [Excellent Utilities: OCRmyPDF](https://www.linuxlinks.com/excellent-utilities-ocrmypdf-add-ocr-text-layer-scanned-pdfs/)
|
- [Excellent Utilities: OCRmyPDF](https://www.linuxlinks.com/excellent-utilities-ocrmypdf-add-ocr-text-layer-scanned-pdfs/)
|
||||||
- [LinuxUser Texterkennung mit OCRmyPDF und Scanbd automatisieren](https://www.linux-community.de/ausgaben/linuxuser/2021/06/texterkennung-mit-ocrmypdf-und-scanbd-automatisieren/)
|
- [LinuxUser Texterkennung mit OCRmyPDF und Scanbd automatisieren](https://www.linux-community.de/ausgaben/linuxuser/2021/06/texterkennung-mit-ocrmypdf-und-scanbd-automatisieren/)
|
||||||
|
- [Y Combinator discussion](https://news.ycombinator.com/item?id=32028752)
|
||||||
|
|
||||||
## Business enquiries
|
## Business enquiries
|
||||||
|
|
||||||
|
|||||||
+129
-44
@@ -10,7 +10,7 @@ Control of unpaper
|
|||||||
|
|
||||||
OCRmyPDF uses ``unpaper`` to provide the implementation of the
|
OCRmyPDF uses ``unpaper`` to provide the implementation of the
|
||||||
``--clean`` and ``--clean-final`` arguments.
|
``--clean`` and ``--clean-final`` arguments.
|
||||||
`unpaper <https://github.com/Flameeyes/unpaper/blob/master/doc/basic-concepts.md>`__
|
`unpaper <https://github.com/Flameeyes/unpaper/blob/main/doc/basic-concepts.md>`__
|
||||||
provides a variety of image processing filters to improve images.
|
provides a variety of image processing filters to improve images.
|
||||||
|
|
||||||
By default, OCRmyPDF uses only ``unpaper`` arguments that were found to
|
By default, OCRmyPDF uses only ``unpaper`` arguments that were found to
|
||||||
@@ -47,8 +47,8 @@ and clean up the margins of both.
|
|||||||
|
|
||||||
Some ``unpaper`` features cause multiple input or output files to be
|
Some ``unpaper`` features cause multiple input or output files to be
|
||||||
consumed or produced. OCRmyPDF requires ``unpaper`` to consume one
|
consumed or produced. OCRmyPDF requires ``unpaper`` to consume one
|
||||||
file and produce one file. An deviation from that condition will
|
file and produce one file; errors will result if this assumption is not
|
||||||
result in errors.
|
met.
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
|
|
||||||
@@ -82,14 +82,17 @@ is stripped out. Then an image of each page is created with visible text
|
|||||||
masked out. The page image is sent for OCR, and any additional text is
|
masked out. The page image is sent for OCR, and any additional text is
|
||||||
inserted as OCR. If a file contains a mix of text and bitmap images that
|
inserted as OCR. If a file contains a mix of text and bitmap images that
|
||||||
contain text, OCRmyPDF will locate the additional text in images without
|
contain text, OCRmyPDF will locate the additional text in images without
|
||||||
disrupting the existing text.
|
disrupting the existing text. Some PDF OCR solutions render text as
|
||||||
|
technically printable or visible in some way, perhaps by drawing it and
|
||||||
|
then painting over it. OCRmyPDF cannot distinguish this type of OCR
|
||||||
|
text from real text, so it will not be "redone".
|
||||||
|
|
||||||
If ``--force-ocr`` is issued, then all pages will be rasterized to
|
If ``--force-ocr`` is issued, then all pages will be rasterized to
|
||||||
images, discarding any hidden OCR text, and rasterizing any printable
|
images, discarding any hidden OCR text, rasterizing any printable
|
||||||
text. This is useful for redoing OCR, for fixing OCR text with a damaged
|
text, and flattening form fields or interactive objects into their visual
|
||||||
character map (text is selectable but not searchable), and destroying
|
representation. This is useful for redoing OCR, for fixing OCR text
|
||||||
redacted information. Any forms and vector graphics will be rasterized
|
with a damaged character map (text is selectable but not searchable),
|
||||||
as well.
|
and destroying redacted information.
|
||||||
|
|
||||||
Time and image size limits
|
Time and image size limits
|
||||||
--------------------------
|
--------------------------
|
||||||
@@ -104,13 +107,48 @@ was requested, the preprocessed image layer will be inserted.
|
|||||||
If you want to adjust the amount of time spent on OCR, change
|
If you want to adjust the amount of time spent on OCR, change
|
||||||
``--tesseract-timeout``. You can also automatically skip images that
|
``--tesseract-timeout``. You can also automatically skip images that
|
||||||
exceed a certain number of megapixels with ``--skip-big``. (A 300 DPI,
|
exceed a certain number of megapixels with ``--skip-big``. (A 300 DPI,
|
||||||
8.5×11" page is 8.4 megapixels.)
|
8.5×11" page image is 8.4 megapixels.)
|
||||||
|
|
||||||
.. code-block:: bash
|
.. code-block:: bash
|
||||||
|
|
||||||
# Allow 300 seconds for OCR; skip any page larger than 50 megapixels
|
# Allow 300 seconds for OCR; skip any page larger than 50 megapixels
|
||||||
ocrmypdf --tesseract-timeout 300 --skip-big 50 bigfile.pdf output.pdf
|
ocrmypdf --tesseract-timeout 300 --skip-big 50 bigfile.pdf output.pdf
|
||||||
|
|
||||||
|
OCR for huge images
|
||||||
|
-------------------
|
||||||
|
|
||||||
|
Tesseract has internal limits on the size
|
||||||
|
of images it will process. If you issue
|
||||||
|
``--tesseract-downsample-large-images``, OCRmyPDF will downsample images
|
||||||
|
to fit Tesseract limits. (The limits are usually entered only for scanned
|
||||||
|
images of oversized media, such as large maps or blueprints exceeding
|
||||||
|
110 cm or 43 inches in either dimension, and at high DPI.)
|
||||||
|
|
||||||
|
``--tesseract-downsample-above Npixels`` adjusts the threshold at which images
|
||||||
|
will be downsampled. By default, only images that exceed any of Tesseract's
|
||||||
|
internal limits are downsampled.
|
||||||
|
|
||||||
|
You will also need to set ``--tesseract-timeout`` high enough to allow
|
||||||
|
for processing.
|
||||||
|
|
||||||
|
Only the image sent for OCR is downsampled. The original image is
|
||||||
|
preserved.
|
||||||
|
|
||||||
|
.. code-block:: bash
|
||||||
|
|
||||||
|
# Allow 600 seconds for OCR on huge images
|
||||||
|
ocrmypdf --tesseract-timeout 600 \
|
||||||
|
--tesseract-downsample-large-images \
|
||||||
|
bigfile.pdf output.pdf
|
||||||
|
|
||||||
|
# Downsample images above 5000 pixels on the longest dimension to
|
||||||
|
# 5000 pixels
|
||||||
|
ocrmypdf --tesseract-timeout 120 \
|
||||||
|
--tesseract-downsample-large-images \
|
||||||
|
--tesseract-downsample-above 5000 \
|
||||||
|
bigfile.pdf output_downsampled_ocr.pdf
|
||||||
|
|
||||||
|
|
||||||
Overriding default tesseract
|
Overriding default tesseract
|
||||||
----------------------------
|
----------------------------
|
||||||
|
|
||||||
@@ -154,13 +192,14 @@ In addition to tesseract, OCRmyPDF uses the following external binaries:
|
|||||||
- ``jbig2``
|
- ``jbig2``
|
||||||
|
|
||||||
In each case OCRmyPDF will search the ``PATH`` environment variable to
|
In each case OCRmyPDF will search the ``PATH`` environment variable to
|
||||||
locate the binaries.
|
locate the binaries. By modifying the ``PATH`` environment variable, you
|
||||||
|
can override the binaries that OCRmyPDF uses.
|
||||||
|
|
||||||
Changing tesseract configuration variables
|
Changing Tesseract configuration variables
|
||||||
------------------------------------------
|
------------------------------------------
|
||||||
|
|
||||||
You can override tesseract's default `control
|
You can override Tesseract's default `control
|
||||||
parameters <https://github.com/tesseract-ocr/tesseract/wiki/ControlParams>`__
|
parameters <https://tesseract-ocr.github.io/tessdoc/tess3/ControlParams.html>`__
|
||||||
with a configuration file.
|
with a configuration file.
|
||||||
|
|
||||||
As an example, this configuration will disable Tesseract's dictionary
|
As an example, this configuration will disable Tesseract's dictionary
|
||||||
@@ -200,46 +239,77 @@ rendering
|
|||||||
OCRmyPDF has these PDF renderers: ``sandwich`` and ``hocr``. The
|
OCRmyPDF has these PDF renderers: ``sandwich`` and ``hocr``. The
|
||||||
renderer may be selected using ``--pdf-renderer``. The default is
|
renderer may be selected using ``--pdf-renderer``. The default is
|
||||||
``auto`` which lets OCRmyPDF select the renderer to use. Currently,
|
``auto`` which lets OCRmyPDF select the renderer to use. Currently,
|
||||||
``auto`` always selects ``sandwich``.
|
``auto`` always selects ``hocr``.
|
||||||
|
|
||||||
|
The ``hocr`` renderer
|
||||||
|
---------------------
|
||||||
|
|
||||||
|
.. versionchanged:: 16.0.0
|
||||||
|
|
||||||
|
In both renderers, a text-only layer is rendered and sandwiched (overlaid)
|
||||||
|
on to either the original PDF page, or newly rasterized version of the
|
||||||
|
original PDF page (when ``--force-ocr`` is used). In this way, loss
|
||||||
|
of PDF information is generally avoided. (You may need to disable PDF/A
|
||||||
|
conversion and optimization to eliminate all lossy transformations.)
|
||||||
|
|
||||||
|
The current approach used by the new hOCR renderer is a re-implementation
|
||||||
|
of Tesseract's PDF renderer, using the same Glyphless font and general
|
||||||
|
ideas, but fixing many technical issues that impeded it. The new hocr
|
||||||
|
provides better text placement accuracy, avoids issues with word
|
||||||
|
segmentation, and provides better positioning of skewed text.
|
||||||
|
|
||||||
|
Using the experimental API, it is also possible to edit the OCR output
|
||||||
|
from Tesseract, using any tool that is capable of editing hOCR files.
|
||||||
|
|
||||||
|
Older versions of this renderer did not support non-Latin languages, but
|
||||||
|
it is now universal.
|
||||||
|
|
||||||
The ``sandwich`` renderer
|
The ``sandwich`` renderer
|
||||||
-------------------------
|
-------------------------
|
||||||
|
|
||||||
The ``sandwich`` renderer uses Tesseract's new text-only PDF feature,
|
The ``sandwich`` renderer uses Tesseract's text-only PDF feature,
|
||||||
which produces a PDF page that lays out the OCR in invisible text. This
|
which produces a PDF page that lays out the OCR in invisible text.
|
||||||
page is then "sandwiched" onto the original PDF page, allowing lossless
|
|
||||||
application of OCR even to PDF pages that contain other vector objects.
|
|
||||||
|
|
||||||
Currently this is the best renderer for most uses, however it is
|
Currently some problematic PDF viewers like Mozilla PDF.js and macOS
|
||||||
implemented in Tesseract so OCRmyPDF cannot influence it. Currently some
|
Preview have problems with segmenting its text output, and
|
||||||
problematic PDF viewers like Mozilla PDF.js and macOS Preview have
|
mightrunseveralwordstogether. It also does not implement right to left
|
||||||
problems with segmenting its text output, and
|
fonts (Arabic, Hebrew, Persian). The output of this renderer cannot
|
||||||
mightrunseveralwordstogether.
|
be edited. The sandwich renderer is retained for testing.
|
||||||
|
|
||||||
When image preprocessing features like ``--deskew`` are used, the
|
When image preprocessing features like ``--deskew`` are used, the
|
||||||
original PDF will be rendered as a full page and the OCR layer will be
|
original PDF will be rendered as a full page and the OCR layer will be
|
||||||
placed on top.
|
placed on top.
|
||||||
|
|
||||||
The ``hocr`` renderer
|
Rendering and rasterizing options
|
||||||
---------------------
|
=================================
|
||||||
|
|
||||||
The ``hocr`` renderer works with older versions of Tesseract. The image
|
.. versionadded:: 14.3.0
|
||||||
layer is copied from the original PDF page if possible, avoiding
|
|
||||||
potentially lossy transcoding or loss of other PDF information. If
|
|
||||||
preprocessing is specified, then the image layer is a new PDF. (You may
|
|
||||||
need to disable PDF/A conversion nad optimization to eliminate all
|
|
||||||
lossy transformations.)
|
|
||||||
|
|
||||||
Unlike ``sandwich`` this renderer is implemented within OCRmyPDF; anyone
|
The ``--continue-on-soft-render-error`` option allows OCRmyPDF to
|
||||||
looking to customize how OCR is presented should look here. A major
|
proceed if a page cannot be rasterized/rendered. This is useful if you are
|
||||||
disadvantage of this renderer is it not capable of correctly handling
|
trying to get the best possible OCR from a PDF that is not well-formed,
|
||||||
text outside the Latin alphabet (specifically, it supports the ISO 8859-1
|
and you are willing to accept some pages that may not visually match the
|
||||||
character). Pull requests to improve the situation are welcome.
|
input, and that may not OCR well.
|
||||||
|
|
||||||
Currently, this renderer has the best compatibility with Mozilla's
|
Color conversion strategy
|
||||||
PDF.js viewer.
|
=========================
|
||||||
|
|
||||||
This works in all versions of Tesseract.
|
.. versionadded:: 15.0.0
|
||||||
|
|
||||||
|
OCRmyPDF uses Ghostscript to convert PDF to PDF/A. In some cases, this
|
||||||
|
conversion requires color conversion. The default strategy is to convert
|
||||||
|
using the ``LeaveColorUnchanged`` strategy, which preserves the original
|
||||||
|
color space wherever possible (some rare color spaces might still be
|
||||||
|
converted).
|
||||||
|
|
||||||
|
Usually document scanners produce PDFs in the sRGB color space, and do
|
||||||
|
not need to be converted, so the default strategy is appropriate.
|
||||||
|
|
||||||
|
Suppose that you have a document that was prepared for professional
|
||||||
|
printing in a Separation or CMYK color space, and text was converted to
|
||||||
|
curves. In this case, you may want to use a different color conversion
|
||||||
|
strategy. The ``--color-conversion-strategy`` option allows you to select a
|
||||||
|
different strategy, such as ``RGB``.
|
||||||
|
|
||||||
Return code policy
|
Return code policy
|
||||||
==================
|
==================
|
||||||
@@ -299,16 +369,31 @@ stable user interface. They may be imported from
|
|||||||
- The program was interrupted by pressing Ctrl+C.
|
- The program was interrupted by pressing Ctrl+C.
|
||||||
|
|
||||||
|
|
||||||
|
.. _tmpdir:
|
||||||
|
|
||||||
|
Changing temporary storage location
|
||||||
|
===================================
|
||||||
|
|
||||||
|
OCRmyPDF generates many temporary files during processing.
|
||||||
|
|
||||||
|
To change where temporary files are stored, change the ``TMPDIR``
|
||||||
|
environment variable for ocrmypdf's environment. (Python's
|
||||||
|
``tempfile.gettempdir()`` returns the root directory in which temporary
|
||||||
|
files will be stored.) For example, one could redirect ``TMPDIR`` to a
|
||||||
|
large RAM disk to avoid wear on HDD/SSD and potentially improve
|
||||||
|
performance.
|
||||||
|
|
||||||
|
On Windows, the ``TEMP`` environment variable is used instead.
|
||||||
|
|
||||||
Debugging the intermediate files
|
Debugging the intermediate files
|
||||||
================================
|
================================
|
||||||
|
|
||||||
OCRmyPDF normally saves its intermediate results to a temporary folder
|
OCRmyPDF normally saves its intermediate results to a temporary folder
|
||||||
and deletes this folder when it exits, whether it succeeded or failed.
|
and deletes this folder when it exits, whether it succeeded or failed.
|
||||||
|
|
||||||
If the ``-k`` argument is issued on the command line, OCRmyPDF will keep
|
If the ``--keep-temporary-files`` (``-k```) argument is issued on the
|
||||||
the temporary folder and print the location, whether it succeeded or
|
command line, OCRmyPDF will keep the temporary folder and print the location,
|
||||||
failed (provided the Python interpreter did not crash). An example
|
whether it succeeded or failed. An example message is:
|
||||||
message is:
|
|
||||||
|
|
||||||
.. code-block:: none
|
.. code-block:: none
|
||||||
|
|
||||||
|
|||||||
+24
-27
@@ -39,9 +39,7 @@ Parent process requirements
|
|||||||
The :func:`ocrmypdf.ocr` function runs OCRmyPDF similar to command line
|
The :func:`ocrmypdf.ocr` function runs OCRmyPDF similar to command line
|
||||||
execution. To do this, it will:
|
execution. To do this, it will:
|
||||||
|
|
||||||
- create a monitoring thread
|
- create worker processes or threads
|
||||||
- create worker processes (on Linux, forking itself; on Windows and macOS, by
|
|
||||||
spawning)
|
|
||||||
- manage the signal flags of its worker processes
|
- manage the signal flags of its worker processes
|
||||||
- execute other subprocesses (forking and executing other programs)
|
- execute other subprocesses (forking and executing other programs)
|
||||||
|
|
||||||
@@ -54,7 +52,19 @@ processes.
|
|||||||
|
|
||||||
Creating a child process to call :func:`ocrmypdf.ocr()` is suggested. That
|
Creating a child process to call :func:`ocrmypdf.ocr()` is suggested. That
|
||||||
way your application will survive and remain interactive even if
|
way your application will survive and remain interactive even if
|
||||||
OCRmyPDF fails for any reason.
|
OCRmyPDF fails for any reason. For example:
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
from multiprocessing import Process
|
||||||
|
|
||||||
|
def ocrmypdf_process():
|
||||||
|
ocrmypdf.ocr('input.pdf', 'output.pdf')
|
||||||
|
|
||||||
|
def call_ocrmypdf_from_my_app():
|
||||||
|
p = Process(target=ocrmypdf_process)
|
||||||
|
p.start()
|
||||||
|
p.join()
|
||||||
|
|
||||||
Programs that call :func:`ocrmypdf.ocr()` should also install a SIGBUS signal
|
Programs that call :func:`ocrmypdf.ocr()` should also install a SIGBUS signal
|
||||||
handler (except on Windows), to raise an exception if access to a memory
|
handler (except on Windows), to raise an exception if access to a memory
|
||||||
@@ -72,14 +82,6 @@ OCRmyPDF, use processes.
|
|||||||
not take at least one of these steps, process semantics will prevent
|
not take at least one of these steps, process semantics will prevent
|
||||||
OCRmyPDF from working correctly.
|
OCRmyPDF from working correctly.
|
||||||
|
|
||||||
.. warning::
|
|
||||||
|
|
||||||
On macOS with Python 3.7, you must call
|
|
||||||
:func:`multiprocessing.set_start_method("spawn")`. Without this, multiprocessing
|
|
||||||
will be unstable. From the command line, OCRmyPDF does this automatically,
|
|
||||||
but as an API user you must do this. See Python bpo-33725 for details.
|
|
||||||
Python 3.8+ also resolve this automatically.
|
|
||||||
|
|
||||||
Logging
|
Logging
|
||||||
-------
|
-------
|
||||||
|
|
||||||
@@ -97,12 +99,21 @@ your use case.
|
|||||||
Progress monitoring
|
Progress monitoring
|
||||||
-------------------
|
-------------------
|
||||||
|
|
||||||
OCRmyPDF uses the ``tqdm`` package to implement its progress bars.
|
OCRmyPDF uses the ``rich`` package to implement its progress bars.
|
||||||
:func:`ocrmypdf.configure_logging` will set up logging output to
|
:func:`ocrmypdf.configure_logging` will set up logging output to
|
||||||
``sys.stderr`` in a way that is compatible with the display of the
|
``sys.stderr`` in a way that is compatible with the display of the
|
||||||
progress bar. Use ``ocrmypdf.ocr(...progress_bar=False)`` to disable
|
progress bar. Use ``ocrmypdf.ocr(...progress_bar=False)`` to disable
|
||||||
the progress bar.
|
the progress bar.
|
||||||
|
|
||||||
|
Standard output
|
||||||
|
---------------
|
||||||
|
|
||||||
|
OCRmyPDF is strict about not writing to standard output so that
|
||||||
|
users can safely use it in a pipeline and produce a valid output
|
||||||
|
file. A caller application will have to ensure it does not write to
|
||||||
|
standard output either, if it wants to be compatible with this
|
||||||
|
behavior and support piping to a file.
|
||||||
|
|
||||||
Exceptions
|
Exceptions
|
||||||
----------
|
----------
|
||||||
|
|
||||||
@@ -112,18 +123,4 @@ exceptions, some exceptions related to multiprocessing, and
|
|||||||
handler. OCRmyPDF will clean up its temporary files and worker processes
|
handler. OCRmyPDF will clean up its temporary files and worker processes
|
||||||
automatically when an exception occurs.
|
automatically when an exception occurs.
|
||||||
|
|
||||||
Programs that call OCRmyPDF should consider trapping KeyboardInterrupt
|
|
||||||
so that they allow OCR to terminate with the whole program terminating.
|
|
||||||
|
|
||||||
When OCRmyPDF succeeds conditionally, it returns an integer exit code.
|
When OCRmyPDF succeeds conditionally, it returns an integer exit code.
|
||||||
|
|
||||||
Reference
|
|
||||||
---------
|
|
||||||
|
|
||||||
.. autofunction:: ocrmypdf.ocr
|
|
||||||
|
|
||||||
.. autoclass:: ocrmypdf.Verbosity
|
|
||||||
:members:
|
|
||||||
:undoc-members:
|
|
||||||
|
|
||||||
.. autofunction:: ocrmypdf.configure_logging
|
|
||||||
|
|||||||
+14
-2
@@ -3,11 +3,11 @@
|
|||||||
.. SPDX-License-Identifier: CC-BY-SA-4.0
|
.. SPDX-License-Identifier: CC-BY-SA-4.0
|
||||||
|
|
||||||
=============
|
=============
|
||||||
API Reference
|
API reference
|
||||||
=============
|
=============
|
||||||
|
|
||||||
This page summarizes the rest of the public API. Generally speaking this
|
This page summarizes the rest of the public API. Generally speaking this
|
||||||
should mainly of interest to plugin developers.
|
should be mainly of interest to plugin developers.
|
||||||
|
|
||||||
ocrmypdf
|
ocrmypdf
|
||||||
========
|
========
|
||||||
@@ -18,6 +18,18 @@ ocrmypdf
|
|||||||
.. autoclass:: ocrmypdf.PdfContext
|
.. autoclass:: ocrmypdf.PdfContext
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
|
.. autoclass:: ocrmypdf.Verbosity
|
||||||
|
:members:
|
||||||
|
:undoc-members:
|
||||||
|
|
||||||
|
.. autofunction:: ocrmypdf.configure_logging
|
||||||
|
|
||||||
|
.. autofunction:: ocrmypdf.ocr
|
||||||
|
|
||||||
|
.. autofunction:: ocrmypdf.pdf_to_hocr
|
||||||
|
|
||||||
|
.. autofunction:: ocrmypdf.hocr_to_ocr_pdf
|
||||||
|
|
||||||
ocrmypdf.exceptions
|
ocrmypdf.exceptions
|
||||||
===================
|
===================
|
||||||
|
|
||||||
|
|||||||
+31
-32
@@ -21,8 +21,8 @@ processors. To maximize parallelism without overloading your system with
|
|||||||
processes, consider using ``parallel -j 2`` to limit parallel to running
|
processes, consider using ``parallel -j 2`` to limit parallel to running
|
||||||
two jobs at once.
|
two jobs at once.
|
||||||
|
|
||||||
This command will run all ocrmypdf all files named ``*.pdf`` in the
|
This command will run ``ocrmypdf`` on all files named ``*.pdf`` in the
|
||||||
current directory and write them to the previous created ``output/``
|
current directory and write them to the previously created ``output/``
|
||||||
folder. It will not search subdirectories.
|
folder. It will not search subdirectories.
|
||||||
|
|
||||||
The ``--tag`` argument tells parallel to print the filename as a prefix
|
The ``--tag`` argument tells parallel to print the filename as a prefix
|
||||||
@@ -46,16 +46,6 @@ place, and printing each filename in between runs:
|
|||||||
|
|
||||||
find . -printf '%p\n' -name '*.pdf' -exec ocrmypdf '{}' '{}' \;
|
find . -printf '%p\n' -name '*.pdf' -exec ocrmypdf '{}' '{}' \;
|
||||||
|
|
||||||
Alternatively, with a Docker container and streaming the file through
|
|
||||||
standard input and output:
|
|
||||||
|
|
||||||
.. code-block:: bash
|
|
||||||
|
|
||||||
find . -name '*.pdf' -print0 | xargs -0 | while read pdf; do
|
|
||||||
pdfout=$(mktemp)
|
|
||||||
docker run --rm -i jbarlow83/ocrmypdf - - <$pdf >$pdfout && cp $pdfout $pdf
|
|
||||||
done
|
|
||||||
|
|
||||||
This only runs one ``ocrmypdf`` process at a time. This variation uses
|
This only runs one ``ocrmypdf`` process at a time. This variation uses
|
||||||
``find`` to create a directory list and ``parallel`` to parallelize runs
|
``find`` to create a directory list and ``parallel`` to parallelize runs
|
||||||
of ``ocrmypdf``, again updating files in place.
|
of ``ocrmypdf``, again updating files in place.
|
||||||
@@ -70,6 +60,15 @@ In a Windows batch file, use
|
|||||||
|
|
||||||
for /r %%f in (*.pdf) do ocrmypdf %%f %%f
|
for /r %%f in (*.pdf) do ocrmypdf %%f %%f
|
||||||
|
|
||||||
|
With a Docker container, you will need to stream through standard input and output:
|
||||||
|
|
||||||
|
.. code-block:: bash
|
||||||
|
|
||||||
|
find . -name '*.pdf' -print0 | xargs -0 | while read pdf; do
|
||||||
|
pdfout=$(mktemp)
|
||||||
|
docker run --rm -i jbarlow83/ocrmypdf - - <$pdf >$pdfout && cp $pdfout $pdf
|
||||||
|
done
|
||||||
|
|
||||||
Sample script
|
Sample script
|
||||||
-------------
|
-------------
|
||||||
|
|
||||||
@@ -88,9 +87,9 @@ package <https://www.synology.com/en-global/dsm/packages/Docker>`__ is
|
|||||||
installed. Attached is a script to address particular quirks of using
|
installed. Attached is a script to address particular quirks of using
|
||||||
OCRmyPDF on one of these devices.
|
OCRmyPDF on one of these devices.
|
||||||
|
|
||||||
This is only possible for x86-based Synology products. Some Synology
|
At the time this script was written, it only worked for x86-based Synology
|
||||||
products use ARM or Power processors and do not support Docker. Further
|
products. It is not known if it will work on ARM-based Synology products.
|
||||||
adjustments might be needed to deal with the Synology's relatively
|
Further adjustments might be needed to deal with the Synology's relatively
|
||||||
limited CPU and RAM.
|
limited CPU and RAM.
|
||||||
|
|
||||||
.. literalinclude:: ../misc/synology.py
|
.. literalinclude:: ../misc/synology.py
|
||||||
@@ -133,7 +132,7 @@ Users may need to customize the script to meet their requirements.
|
|||||||
"OCR_OUTPUT_DIRECTORY", "Set output directory (should not be under input)"
|
"OCR_OUTPUT_DIRECTORY", "Set output directory (should not be under input)"
|
||||||
"OCR_ARCHIVE_DIRECTORY", "Set archive directory for processed originals (should not be under input, requires ``OCR_ON_SUCCESS_ARCHIVE`` to be set)"
|
"OCR_ARCHIVE_DIRECTORY", "Set archive directory for processed originals (should not be under input, requires ``OCR_ON_SUCCESS_ARCHIVE`` to be set)"
|
||||||
"OCR_ON_SUCCESS_DELETE", "This will delete the input file if the exit code is 0 (OK)"
|
"OCR_ON_SUCCESS_DELETE", "This will delete the input file if the exit code is 0 (OK)"
|
||||||
"OCR_ON_SUCCESS_ARCHIVE", "This will move the processed orignal file to ``OCR_ARCHIVE_DIRECTORY`` if the exit code is 0 (OK). Note that ``OCR_ON_SUCCESS_DELETE`` takes precedence over this option, i.e. if both options are set, the input file will be deleted."
|
"OCR_ON_SUCCESS_ARCHIVE", "This will move the processed original file to ``OCR_ARCHIVE_DIRECTORY`` if the exit code is 0 (OK). Note that ``OCR_ON_SUCCESS_DELETE`` takes precedence over this option, i.e. if both options are set, the input file will be deleted."
|
||||||
"OCR_OUTPUT_DIRECTORY_YEAR_MONTH", "This will place files in the output in ``{output}/{year}/{month}/{filename}``"
|
"OCR_OUTPUT_DIRECTORY_YEAR_MONTH", "This will place files in the output in ``{output}/{year}/{month}/{filename}``"
|
||||||
"OCR_DESKEW", "Apply deskew to crooked input PDFs"
|
"OCR_DESKEW", "Apply deskew to crooked input PDFs"
|
||||||
"OCR_JSON_SETTINGS", "A JSON string specifying any other arguments for ``ocrmypdf.ocr``, e.g. ``'OCR_JSON_SETTINGS={""rotate_pages"": true}'``."
|
"OCR_JSON_SETTINGS", "A JSON string specifying any other arguments for ``ocrmypdf.ocr``, e.g. ``'OCR_JSON_SETTINGS={""rotate_pages"": true}'``."
|
||||||
@@ -151,32 +150,32 @@ The watcher service is included in the OCRmyPDF Docker image. To run it:
|
|||||||
.. code-block:: bash
|
.. code-block:: bash
|
||||||
|
|
||||||
docker run \
|
docker run \
|
||||||
-v <path to files to convert>:/input \
|
--volume <path to files to convert>:/input \
|
||||||
-v <path to store results>:/output \
|
--volume <path to store results>:/output \
|
||||||
-v <path to store processed originals>:/archive \
|
--volume <path to store processed originals>:/processed \
|
||||||
-e OCR_OUTPUT_DIRECTORY_YEAR_MONTH=1 \
|
--env OCR_OUTPUT_DIRECTORY_YEAR_MONTH=1 \
|
||||||
-e OCR_ON_SUCCESS_ARCHIVE=1 \
|
--env OCR_ON_SUCCESS_ARCHIVE=1 \
|
||||||
-e OCR_DESKEW=1 \
|
--env OCR_DESKEW=1 \
|
||||||
-e PYTHONUNBUFFERED=1 \
|
--env PYTHONUNBUFFERED=1 \
|
||||||
-it --entrypoint python3 \
|
--interactive --tty --entrypoint python3 \
|
||||||
jbarlow83/ocrmypdf \
|
jbarlow83/ocrmypdf \
|
||||||
watcher.py
|
watcher.py
|
||||||
|
|
||||||
This service will watch for a file that matches ``/input/\*.pdf``,
|
This service will watch for a file that matches ``/input/\*.pdf``,
|
||||||
convert it to a OCRed PDF in ``/output/``, and move the processed
|
convert it to a OCRed PDF in ``/output/``, and move the processed
|
||||||
original to ``/archive``. The parameters to this image are:
|
original to ``/processed``. The parameters to this image are:
|
||||||
|
|
||||||
.. csv-table:: watcher.py parameters for Docker
|
.. csv-table:: watcher.py parameters for Docker
|
||||||
:header: "Parameter", "Description"
|
:header: "Parameter", "Description"
|
||||||
:widths: 50, 50
|
:widths: 50, 50
|
||||||
|
|
||||||
"``-v <path to files to convert>:/input``", "Files placed in this location will be OCRed"
|
"``--volume <path to files to convert>:/input``", "Files placed in this location will be OCRed"
|
||||||
"``-v <path to store results>:/output``", "This is where OCRed files will be stored"
|
"``--volume <path to store results>:/output``", "This is where OCRed files will be stored"
|
||||||
"``-v <path to store processed originals>:/archive``", "Archive processed originals here"
|
"``--volume <path to store processed originals>:/processed``", "Archive processed originals here"
|
||||||
"``-e OCR_OUTPUT_DIRECTORY_YEAR_MONTH=1``", "Define environment variable ``OCR_OUTPUT_DIRECTORY_YEAR_MONTH=1`` to place files in the output in ``{output}/{year}/{month}/{filename}``"
|
"``--env OCR_OUTPUT_DIRECTORY_YEAR_MONTH=1``", "Define environment variable ``OCR_OUTPUT_DIRECTORY_YEAR_MONTH=1`` to place files in the output in ``{output}/{year}/{month}/{filename}``"
|
||||||
"``-e OCR_ON_SUCCESS_ARCHIVE=1``", "Define environment variable ``OCR_ON_SUCCESS_ARCHIVE`` to move processed originals"
|
"``--env OCR_ON_SUCCESS_ARCHIVE=1``", "Define environment variable ``OCR_ON_SUCCESS_ARCHIVE`` to move processed originals"
|
||||||
"``-e OCR_DESKEW=1``", "Define environment variable ``OCR_DESKEW`` to apply deskew to crooked input PDFs"
|
"``--env OCR_DESKEW=1``", "Define environment variable ``OCR_DESKEW`` to apply deskew to crooked input PDFs"
|
||||||
"``-e PYTHONBUFFERED=1``", "This will force ``STDOUT`` to be unbuffered and allow you to see messages in docker logs"
|
"``--env PYTHONBUFFERED=1``", "This will force ``STDOUT`` to be unbuffered and allow you to see messages in docker logs"
|
||||||
|
|
||||||
This service relies on polling to check for changes to the filesystem. It
|
This service relies on polling to check for changes to the filesystem. It
|
||||||
may not be suitable for some environments, such as filesystems shared on a
|
may not be suitable for some environments, such as filesystems shared on a
|
||||||
|
|||||||
@@ -0,0 +1,92 @@
|
|||||||
|
.. SPDX-FileCopyrightText: 2023 James R. Barlow
|
||||||
|
..
|
||||||
|
.. SPDX-License-Identifier: CC-BY-SA-4.0
|
||||||
|
|
||||||
|
|
||||||
|
.. _ocr-service:
|
||||||
|
|
||||||
|
==================
|
||||||
|
Online deployments
|
||||||
|
==================
|
||||||
|
|
||||||
|
OCRmyPDF is designed to be used as a command line tool, but it can be
|
||||||
|
used in a web service. This document describes some considerations for
|
||||||
|
doing so.
|
||||||
|
|
||||||
|
A basic web service implementation is provided in the source code
|
||||||
|
repository, as ``misc/webservice.py``. It is only demonstration quality
|
||||||
|
and is not intended for production use.
|
||||||
|
|
||||||
|
OCRmyPDF is not designed for use as a public web service where a
|
||||||
|
malicious user could upload a chosen PDF. In particular, it is not
|
||||||
|
necessarily secure against PDF malware or PDFs that cause denial of
|
||||||
|
service. For further discussino of security, see :ref:`security`.
|
||||||
|
|
||||||
|
OCRmyPDF relies on Ghostscript, and therefore, if deployed
|
||||||
|
online one should be prepared to comply with Ghostscript's Affero GPL
|
||||||
|
license, and any other licenses.
|
||||||
|
|
||||||
|
Setting aside these concerns, a side effect of OCRmyPDF is that it may
|
||||||
|
incidentally sanitize PDFs containing certain types of malware. It
|
||||||
|
repairs the PDF with pikepdf/libqpdf, which could correct malformed PDF
|
||||||
|
structures that are part of an attack. When PDF/A output is selected
|
||||||
|
(the default), the input PDF is partially reconstructed by Ghostscript.
|
||||||
|
When ``--force-ocr`` is used, all pages are rasterized and reconverted
|
||||||
|
to PDF, which could remove malware in embedded images.
|
||||||
|
|
||||||
|
Limiting CPU usage
|
||||||
|
------------------
|
||||||
|
|
||||||
|
OCRmyPDF will attempt to use all available CPUs and storage, so
|
||||||
|
executing ``nice ocrmypdf`` or limiting the number of jobs with the
|
||||||
|
``--jobs`` argument may ensure the server remains responsive. Another option
|
||||||
|
would be to run OCRmyPDF jobs inside a Docker container, a virtual machine,
|
||||||
|
or a cloud instance, which can impose its own limits on CPU usage and be
|
||||||
|
terminated "from orbit" if it fails to complete.
|
||||||
|
|
||||||
|
Temporary storage requirements
|
||||||
|
------------------------------
|
||||||
|
|
||||||
|
OCRmyPDF will use a large amount of temporary storage for its work,
|
||||||
|
proportional to the total number of pixels needed to rasterize the PDF.
|
||||||
|
The raster image of a 8.5×11" color page at 300 DPI takes 25 MB
|
||||||
|
uncompressed; OCRmyPDF saves its intermediates as PNG, but that still
|
||||||
|
means it requires about 9 MB per intermediate based on average
|
||||||
|
compression ratios. Multiple intermediates per page are also required,
|
||||||
|
depending on the command line given. A rule of thumb would be to allow
|
||||||
|
100 MB of temporary storage per page in a file – meaning that a small
|
||||||
|
cloud servers or small VM partitions should be provisioned with plenty
|
||||||
|
of extra space, if say, a 500 page file might be sent.
|
||||||
|
|
||||||
|
To change the temporary directory, see :ref:`tmpdir`.
|
||||||
|
|
||||||
|
On Amazon Web Services or other cloud vendors, consider setting your
|
||||||
|
temporary directory to `empheral
|
||||||
|
storage <https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/InstanceStorage.html>`__.
|
||||||
|
|
||||||
|
Timeouts
|
||||||
|
--------
|
||||||
|
|
||||||
|
To prevent excessively long OCR jobs consider setting
|
||||||
|
``--tesseract-timeout`` and/or ``--skip-big`` arguments. ``--skip-big``
|
||||||
|
is particularly helpful if your PDFs include documents such as reports
|
||||||
|
on standard page sizes with large images attached - often large images
|
||||||
|
are not worth OCR'ing anyway.
|
||||||
|
|
||||||
|
Document management systems
|
||||||
|
---------------------------
|
||||||
|
|
||||||
|
If you are looking for a full document management system, consider
|
||||||
|
`paperless-ngx <https://github.com/paperless-ngx/paperless-ngx>`__,
|
||||||
|
which is a web application that uses OCRmyPDF to automatically OCR and
|
||||||
|
archive documents.
|
||||||
|
|
||||||
|
Commercial OCR alternatives
|
||||||
|
---------------------------
|
||||||
|
|
||||||
|
The author also provides professional services that include OCR and
|
||||||
|
building databases around PDFs, and is happy to provide consultation.
|
||||||
|
|
||||||
|
Abbyy Cloud OCR is viable commercial alternative with a web services
|
||||||
|
API. Amazon Textract, Google Cloud Vision, and Microsoft Azure
|
||||||
|
Computer Vision provide advanced OCR but have less PDF rendering capability.
|
||||||
+4
-7
@@ -2,6 +2,8 @@
|
|||||||
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
||||||
# SPDX-License-Identifier: CC-BY-SA-4.0
|
# SPDX-License-Identifier: CC-BY-SA-4.0
|
||||||
|
|
||||||
|
# ruff: noqa: E402
|
||||||
|
|
||||||
# ocrmypdf documentation build configuration file, created by
|
# ocrmypdf documentation build configuration file, created by
|
||||||
# sphinx-quickstart on Sun Sep 4 14:29:43 2016.
|
# sphinx-quickstart on Sun Sep 4 14:29:43 2016.
|
||||||
#
|
#
|
||||||
@@ -22,8 +24,6 @@
|
|||||||
# import sys
|
# import sys
|
||||||
# sys.path.insert(0, os.path.abspath('.'))
|
# sys.path.insert(0, os.path.abspath('.'))
|
||||||
|
|
||||||
"""isort:skip_file"""
|
|
||||||
|
|
||||||
# -- General configuration ------------------------------------------------
|
# -- General configuration ------------------------------------------------
|
||||||
|
|
||||||
# If your documentation needs a minimal Sphinx version, state it here.
|
# If your documentation needs a minimal Sphinx version, state it here.
|
||||||
@@ -65,7 +65,7 @@ master_doc = 'index'
|
|||||||
# General information about the project.
|
# General information about the project.
|
||||||
project = 'ocrmypdf'
|
project = 'ocrmypdf'
|
||||||
copyright = (
|
copyright = (
|
||||||
'2022, James R. Barlow. Licensed under Creative Commons Attribution-ShareAlike 4.0.'
|
'2023, James R. Barlow. Licensed under Creative Commons Attribution-ShareAlike 4.0.'
|
||||||
)
|
)
|
||||||
author = 'James R. Barlow'
|
author = 'James R. Barlow'
|
||||||
|
|
||||||
@@ -76,6 +76,7 @@ author = 'James R. Barlow'
|
|||||||
# The short X.Y version.
|
# The short X.Y version.
|
||||||
|
|
||||||
import os
|
import os
|
||||||
|
from importlib.metadata import version as package_version
|
||||||
|
|
||||||
on_rtd = os.environ.get('READTHEDOCS') == 'True'
|
on_rtd = os.environ.get('READTHEDOCS') == 'True'
|
||||||
|
|
||||||
@@ -96,10 +97,6 @@ if on_rtd:
|
|||||||
]
|
]
|
||||||
sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES)
|
sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES)
|
||||||
|
|
||||||
try:
|
|
||||||
from importlib_metadata import version as package_version
|
|
||||||
except ModuleNotFoundError:
|
|
||||||
from importlib.metadata import version as package_version
|
|
||||||
|
|
||||||
# The full version, including alpha/beta/rc tags.
|
# The full version, including alpha/beta/rc tags.
|
||||||
release = package_version('ocrmypdf')
|
release = package_version('ocrmypdf')
|
||||||
|
|||||||
+27
-10
@@ -18,8 +18,8 @@ work you're contemplating is already half-done in a development branch.
|
|||||||
Code style
|
Code style
|
||||||
==========
|
==========
|
||||||
|
|
||||||
We use PEP8, ``black`` for code formatting and ``isort`` for import sorting. The
|
We use PEP8, ``black`` for code formatting and ``ruff`` for everything else. The
|
||||||
settings for these programs are in ``pyproject.toml`` and ``setup.cfg``. Pull
|
settings for these programs are in ``pyproject.toml``. Pull
|
||||||
requests should follow the style guide. One difference we use from "black" style
|
requests should follow the style guide. One difference we use from "black" style
|
||||||
is that strings shown to the user are always in double quotes (``"``) and strings
|
is that strings shown to the user are always in double quotes (``"``) and strings
|
||||||
for internal uses are in single quotes (``'``).
|
for internal uses are in single quotes (``'``).
|
||||||
@@ -29,12 +29,17 @@ Tests
|
|||||||
|
|
||||||
New features should come with tests that confirm their correctness.
|
New features should come with tests that confirm their correctness.
|
||||||
|
|
||||||
New Python dependencies
|
New dependencies
|
||||||
=======================
|
================
|
||||||
|
|
||||||
If you are proposing a change that will require a new Python dependency, we
|
If you are proposing a change that will require a new dependency, we
|
||||||
prefer dependencies that are already packaged by Debian or Red Hat. This makes
|
prefer dependencies that are already packaged by Debian or Red Hat. This makes
|
||||||
life much easier for our downstream package maintainers.
|
life much easier for our downstream package maintainers. A package that is only
|
||||||
|
available on PyPI or GitHub, and not more widely packaged, may not be accepted.
|
||||||
|
|
||||||
|
We are unlikely to accept a dependency on CUDA or other GPU-based libraries,
|
||||||
|
because these are still difficult to package and install on many systems.
|
||||||
|
We recommend implementing these changes as plugins.
|
||||||
|
|
||||||
Python dependencies must also be license-compatible. GPLv3 or AGPLv3 are likely
|
Python dependencies must also be license-compatible. GPLv3 or AGPLv3 are likely
|
||||||
incompatible with the project's license, but LGPLv3 is compatible.
|
incompatible with the project's license, but LGPLv3 is compatible.
|
||||||
@@ -43,7 +48,19 @@ New non-Python dependencies
|
|||||||
===========================
|
===========================
|
||||||
|
|
||||||
OCRmyPDF uses several external programs (Tesseract, Ghostscript and others) for
|
OCRmyPDF uses several external programs (Tesseract, Ghostscript and others) for
|
||||||
its functionality. In general we prefer to avoid adding new external programs.
|
its functionality. In general we prefer to avoid adding new external programs,
|
||||||
|
and if we are to add external programs, we prefer those that are already
|
||||||
|
packaged by Debian or Red Hat.
|
||||||
|
|
||||||
|
Plugins
|
||||||
|
=======
|
||||||
|
|
||||||
|
Some new features may be a good fit for a plugin. Plugins are a way to add
|
||||||
|
features to OCRmyPDF without adding them to the core program. Plugins are
|
||||||
|
installed separately from OCRmyPDF. They are written in Python and can be
|
||||||
|
installed from PyPI. See the `plugin documentation <https://ocrmypdf.readthedocs.io/en/latest/plugins.html>`_.
|
||||||
|
|
||||||
|
We are happy to link users to your plugin from the documentation.
|
||||||
|
|
||||||
Style guide: Is it OCRmyPDF or ocrmypdf?
|
Style guide: Is it OCRmyPDF or ocrmypdf?
|
||||||
========================================
|
========================================
|
||||||
@@ -53,8 +70,8 @@ The program/project is OCRmyPDF and the name of the executable or library is ocr
|
|||||||
Copyright and license
|
Copyright and license
|
||||||
=====================
|
=====================
|
||||||
|
|
||||||
For contributions over 10 lines of code, please include your name to list of
|
For contributions over 10 lines of code, please add your name to list of
|
||||||
copyright holders for that file. The core program is licensed under MPL-2.0,
|
copyright holders for that file. The core program is licensed under MPL-2.0,
|
||||||
test files and documentation under CC-BY-SA 4.0, and miscellaneous files under
|
test files and documentation under CC-BY-SA 4.0, and miscellaneous files under
|
||||||
MIT. Please contribute code only that you wrote and you have the permission to
|
MIT, with a few minor exceptions. Please contribute only content that you own
|
||||||
contribute or license to us.
|
or have the right to contribute under these licenses.
|
||||||
|
|||||||
+28
-6
@@ -231,13 +231,20 @@ Don't actually OCR my PDF
|
|||||||
=========================
|
=========================
|
||||||
|
|
||||||
If you set ``--tesseract-timeout 0`` OCRmyPDF will apply its image
|
If you set ``--tesseract-timeout 0`` OCRmyPDF will apply its image
|
||||||
processing without performing OCR, if all you want to is to apply image
|
processing without performing OCR (by causing OCR to time out). This works
|
||||||
processing or PDF/A conversion.
|
if all you want to is to apply image processing or PDF/A conversion.
|
||||||
|
|
||||||
.. code-block:: bash
|
.. code-block:: bash
|
||||||
|
|
||||||
ocrmypdf --tesseract-timeout=0 --remove-background input.pdf output.pdf
|
ocrmypdf --tesseract-timeout=0 --remove-background input.pdf output.pdf
|
||||||
|
|
||||||
|
.. versionchanged:: v14.1.0
|
||||||
|
|
||||||
|
Prior to this version, ``--tesseract-timeout 0`` would prevent other
|
||||||
|
uses of Tesseract, such as deskewing, from working. This is no longer
|
||||||
|
the case. Use ``--tesseract-non-ocr-timeout`` to control the timeout
|
||||||
|
for non-OCR operations, if needed.
|
||||||
|
|
||||||
Optimize images without performing OCR
|
Optimize images without performing OCR
|
||||||
--------------------------------------
|
--------------------------------------
|
||||||
|
|
||||||
@@ -261,9 +268,10 @@ Hyphens denote a range of pages and commas separate page numbers. If you prefer
|
|||||||
to use spaces, quote all of the page numbers: ``--pages '2, 3, 5, 7'``.
|
to use spaces, quote all of the page numbers: ``--pages '2, 3, 5, 7'``.
|
||||||
|
|
||||||
OCRmyPDF will warn if your list of page numbers contains duplicates or
|
OCRmyPDF will warn if your list of page numbers contains duplicates or
|
||||||
overlap pages. OCRmyPDF does not currently account for document page numbers,
|
overlapping pages. OCRmyPDF does not currently account for document page numbers,
|
||||||
such as an introduction section of a book that uses Roman numerals. It simply
|
such as an introduction section of a book that uses Roman numerals. It simply
|
||||||
counts the number of virtual pieces of paper since the start.
|
counts the number of virtual pieces of paper since the start. If your list of
|
||||||
|
pages is out of numerical order, OCRmyPDF will sort it for you.
|
||||||
|
|
||||||
Regardless of the argument to ``--pages``, OCRmyPDF will optimize all pages/images
|
Regardless of the argument to ``--pages``, OCRmyPDF will optimize all pages/images
|
||||||
in the file and convert it to PDF/A, unless you disable those options. Both of these
|
in the file and convert it to PDF/A, unless you disable those options. Both of these
|
||||||
@@ -283,7 +291,7 @@ argument. (Normally, OCRmyPDF will exit with an error if asked to modify
|
|||||||
a file with OCR.)
|
a file with OCR.)
|
||||||
|
|
||||||
This may be helpful for users who want to take advantage of accuracy
|
This may be helpful for users who want to take advantage of accuracy
|
||||||
improvements in Tesseract 4.0 for files they previously OCRed with an
|
improvements in Tesseract for files they previously OCRed with an
|
||||||
earlier version of Tesseract and OCRmyPDF.
|
earlier version of Tesseract and OCRmyPDF.
|
||||||
|
|
||||||
.. code-block:: bash
|
.. code-block:: bash
|
||||||
@@ -360,7 +368,7 @@ The types of optimization available may expand over time. By default,
|
|||||||
OCRmyPDF compresses data streams inside PDFs, and will change
|
OCRmyPDF compresses data streams inside PDFs, and will change
|
||||||
inefficient compression modes to more modern versions. A program like
|
inefficient compression modes to more modern versions. A program like
|
||||||
``qpdf`` can be used to change encodings, e.g. to inspect the internals
|
``qpdf`` can be used to change encodings, e.g. to inspect the internals
|
||||||
fo a PDF.
|
for a PDF.
|
||||||
|
|
||||||
.. code-block:: bash
|
.. code-block:: bash
|
||||||
|
|
||||||
@@ -372,3 +380,17 @@ Some users may consider enabling lossy JBIG2. See: :ref:`jbig2-lossy`.
|
|||||||
|
|
||||||
Image processing and PDF/A conversion can also introduce lossy transformations
|
Image processing and PDF/A conversion can also introduce lossy transformations
|
||||||
to your PDF images, even when ``--optimize 1`` is in use.
|
to your PDF images, even when ``--optimize 1`` is in use.
|
||||||
|
|
||||||
|
|
||||||
|
Digitally signed PDFs
|
||||||
|
=====================
|
||||||
|
|
||||||
|
OCRmyPDF cannot preserve digital signatures in PDFs and also add to OCR to them.
|
||||||
|
By default, it will refuse to modify a signed PDF regardless of other settings. You can
|
||||||
|
override this behavior with ``--invalidate-digital-signatures``; as the name suggests,
|
||||||
|
any digital signatures will be invalidated.
|
||||||
|
|
||||||
|
OCRmyPDF cannot open documents that are encrypted with a digital certificate.
|
||||||
|
|
||||||
|
Versions of OCRmyPDF prior to 14.4.0 would invalidate existing digital signatures
|
||||||
|
without warning.
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
.. SPDX-FileCopyrightText: 2023 James R. Barlow
|
||||||
|
.. SPDX-License-Identifier: CC-BY-SA-4.0
|
||||||
|
|
||||||
|
============
|
||||||
|
Design notes
|
||||||
|
============
|
||||||
|
|
||||||
|
Why doesn't OCRmyPDF use PyTesseract?
|
||||||
|
=====================================
|
||||||
|
|
||||||
|
PyTesseract is a Python wrapper around the Tesseract OCR engine. When OCRmyPDF was
|
||||||
|
first written, PyTesseract used ABI bindings to call the Tesseract library. This
|
||||||
|
was not a good fit for OCRmyPDF because ABI bindings can be fragile.
|
||||||
|
|
||||||
|
PyTesseract has since evolved calling the Tesseract executable, abandoning the ABI
|
||||||
|
approach and using the CLI instead, just like OCRmyPDF does. If it were written from
|
||||||
|
scratch today, OCRmyPDF might use PyTesseract.
|
||||||
|
|
||||||
|
PyTesseract has more features don't particularly need PDF output, but less features
|
||||||
|
than OCRmyPDF's API for creating PDFs.
|
||||||
|
|
||||||
|
What is ``executor()``?
|
||||||
|
=======================
|
||||||
|
|
||||||
|
OCRmyPDF uses a custom concurrent executor which can support either threads or
|
||||||
|
processes with the same interface. This is useful because OCRmyPDF can use
|
||||||
|
either threads or processes to parallelize work, whichever is more appropriate
|
||||||
|
for the task at hand.
|
||||||
|
|
||||||
|
The interface is currently private and subject to change. In particular, if
|
||||||
|
experiments with asyncio and anyio are successful, the interface will change.
|
||||||
|
|
||||||
+61
-30
@@ -8,17 +8,16 @@
|
|||||||
OCRmyPDF Docker image
|
OCRmyPDF Docker image
|
||||||
=====================
|
=====================
|
||||||
|
|
||||||
OCRmyPDF is also available in a Docker image that packages recent
|
OCRmyPDF is also available in Docker images that packages recent
|
||||||
versions of all dependencies.
|
versions of all dependencies.
|
||||||
|
|
||||||
For users who already have Docker installed this may be an easy and
|
For users who already have Docker installed this may be an easy and
|
||||||
convenient option. However, it is less performant than a system
|
convenient option.
|
||||||
installation and may require Docker engine configuration.
|
|
||||||
|
|
||||||
OCRmyPDF needs a generous amount of RAM, CPU cores, temporary storage
|
On platforms other than Linux, Docker runs in a virtual machine, and so may
|
||||||
space, whether running in a Docker container or on its own. It may be
|
be less performant. You may also want to adjust the Docker virtual machine's
|
||||||
necessary to ensure the container is provisioned with additional
|
memory and CPU allocation. On Linux, the Docker image runs natively and
|
||||||
resources.
|
performance is comparable to a system installation.
|
||||||
|
|
||||||
.. _docker-install:
|
.. _docker-install:
|
||||||
|
|
||||||
@@ -35,28 +34,37 @@ execute the image:
|
|||||||
|
|
||||||
docker run hello-world
|
docker run hello-world
|
||||||
|
|
||||||
The recommended OCRmyPDF Docker image is currently named ``ocrmypdf``:
|
.. list-table:: Docker images
|
||||||
|
:width: 30 20 50
|
||||||
|
:header-rows: 1
|
||||||
|
|
||||||
|
* - Image
|
||||||
|
- Architecture
|
||||||
|
- Description
|
||||||
|
* - ``jbarlow83/ocrmypdf-alpine``
|
||||||
|
- x86_64 only
|
||||||
|
- Recommended image, based on Alpine Linux.
|
||||||
|
* - ``jbarlow83/ocrmypdf-ubuntu``
|
||||||
|
- x86_64 and arm64
|
||||||
|
- Alternate image, based on Ubuntu. When the Alpine image is considered
|
||||||
|
stable and available for arm64, this image will be deprecated.
|
||||||
|
* - ``jbarlow83/ocrmypdf``
|
||||||
|
- x86_64 and arm64
|
||||||
|
- Currently an alias for ocrmypdf-ubuntu. When the Alpine image is
|
||||||
|
considered stable and available for arm64, this name point to the
|
||||||
|
Alpine image. If you don't about the difference between Alpine and
|
||||||
|
Ubuntu, use this image.
|
||||||
|
|
||||||
|
To install:
|
||||||
|
|
||||||
.. code-block:: bash
|
.. code-block:: bash
|
||||||
|
|
||||||
docker pull jbarlow83/ocrmypdf
|
docker pull jbarlow83/ocrmypdf-alpine
|
||||||
|
|
||||||
|
The ``ocrmypdf`` image is also available, but is deprecated and will be removed
|
||||||
|
in the future.
|
||||||
|
|
||||||
OCRmyPDF will use all available CPU cores. By default, the VirtualBox
|
OCRmyPDF will use all available CPU cores. See the Docker documentation for
|
||||||
machine instance on Windows and macOS has only a single CPU core
|
|
||||||
enabled. Use the VirtualBox Manager to determine the name of your Docker
|
|
||||||
engine host, and then follow these optional steps to enable multiple
|
|
||||||
CPUs:
|
|
||||||
|
|
||||||
.. code-block:: bash
|
|
||||||
|
|
||||||
# Optional step for Mac OS X users
|
|
||||||
docker-machine stop "yourVM"
|
|
||||||
VBoxManage modifyvm "yourVM" --cpus 2 # or whatever number of core is desired
|
|
||||||
docker-machine start "yourVM"
|
|
||||||
eval $(docker-machine env "yourVM")
|
|
||||||
|
|
||||||
See the Docker documentation for
|
|
||||||
`adjusting memory and CPU on other platforms <https://docs.docker.com/config/containers/resource_constraints/>`__.
|
`adjusting memory and CPU on other platforms <https://docs.docker.com/config/containers/resource_constraints/>`__.
|
||||||
|
|
||||||
Using the Docker image on the command line
|
Using the Docker image on the command line
|
||||||
@@ -66,6 +74,8 @@ Using the Docker image on the command line
|
|||||||
container is ephemeral – it runs for one OCR job and terminates, just like a
|
container is ephemeral – it runs for one OCR job and terminates, just like a
|
||||||
command line program. We are using Docker to deliver an application (as opposed
|
command line program. We are using Docker to deliver an application (as opposed
|
||||||
to the more conventional case, where a Docker container runs as a server).
|
to the more conventional case, where a Docker container runs as a server).
|
||||||
|
For that reason we usually use the ``--rm`` argument to delete the container
|
||||||
|
when it exits.
|
||||||
|
|
||||||
To start a Docker container (instance of the image):
|
To start a Docker container (instance of the image):
|
||||||
|
|
||||||
@@ -116,7 +126,7 @@ Dockerfile based on the public one.
|
|||||||
# Example: add Italian
|
# Example: add Italian
|
||||||
RUN apt install tesseract-ocr-ita
|
RUN apt install tesseract-ocr-ita
|
||||||
|
|
||||||
To install language packs (training data) such as the
|
To install language packs (training data) such as the
|
||||||
`tessdata_best <https://github.com/tesseract-ocr/tessdata_best>`_ suite or
|
`tessdata_best <https://github.com/tesseract-ocr/tessdata_best>`_ suite or
|
||||||
custom data, you first need to determine the version of Tesseract data files, which
|
custom data, you first need to determine the version of Tesseract data files, which
|
||||||
may differ from the Tesseract program version. Use this command to determine the data
|
may differ from the Tesseract program version. Use this command to determine the data
|
||||||
@@ -132,17 +142,35 @@ You can then add new data with either a Dockerfile:
|
|||||||
|
|
||||||
.. code-block:: dockerfile
|
.. code-block:: dockerfile
|
||||||
|
|
||||||
FROM jbarlow83/ocrmypdf
|
FROM jbarlow83/ocrmypdf:{TAG}
|
||||||
|
|
||||||
# Example: add a tessdata_best file
|
# Example: add a tessdata_best file
|
||||||
COPY chi_tra_vert.traineddata /usr/share/tesseract-ocr/<data version>/tessdata/
|
COPY chi_tra_vert.traineddata /usr/share/tesseract-ocr/<data version>/tessdata/
|
||||||
|
|
||||||
|
When creating your own image, you should always pin a specific version of the
|
||||||
|
OCRmyPDF Docker image. This ensures that your image will not break when a new
|
||||||
|
version of OCRmyPDF is released.
|
||||||
|
|
||||||
Alternately, you can copy training data into a Docker container as follows:
|
Alternately, you can copy training data into a Docker container as follows:
|
||||||
|
|
||||||
.. code-block:: bash
|
.. code-block:: bash
|
||||||
|
|
||||||
docker cp mycustomtraining.traineddata name_of_container:/usr/share/tesseract-ocr/<tesseract version>/tessdata/
|
docker cp mycustomtraining.traineddata name_of_container:/usr/share/tesseract-ocr/<tesseract version>/tessdata/
|
||||||
|
|
||||||
|
Extending the Docker image
|
||||||
|
==========================
|
||||||
|
|
||||||
|
You can extend the Docker image with your own customizations, similar to the way
|
||||||
|
it is extended to add language packs.
|
||||||
|
|
||||||
|
Note that the Docker image is subject to change at any time. For example, the base
|
||||||
|
image may be updated to a newer version of Ubuntu or Debian. Such changes will be
|
||||||
|
noted in the release notes but might occur at minor versions releases, unless the
|
||||||
|
way a "casual" user of the Docker image is affected.
|
||||||
|
|
||||||
|
If you extend the Docker image, you should pin a specific version of the OCRmyPDF
|
||||||
|
Docker image.
|
||||||
|
|
||||||
Executing the test suite
|
Executing the test suite
|
||||||
========================
|
========================
|
||||||
|
|
||||||
@@ -150,16 +178,16 @@ The OCRmyPDF test suite is installed with image. To run it:
|
|||||||
|
|
||||||
.. code-block:: bash
|
.. code-block:: bash
|
||||||
|
|
||||||
docker run --entrypoint python3 jbarlow83/ocrmypdf -m pytest
|
docker run --rm --entrypoint python jbarlow83/ocrmypdf -m pytest
|
||||||
|
|
||||||
Accessing the shell
|
Accessing the shell
|
||||||
===================
|
===================
|
||||||
|
|
||||||
To use the bash shell in the Docker image:
|
To use the shell in the Docker image:
|
||||||
|
|
||||||
.. code-block:: bash
|
.. code-block:: bash
|
||||||
|
|
||||||
docker run -it --entrypoint bash jbarlow83/ocrmypdf
|
docker run -it --entrypoint sh jbarlow83/ocrmypdf
|
||||||
|
|
||||||
Using the OCRmyPDF web service wrapper
|
Using the OCRmyPDF web service wrapper
|
||||||
======================================
|
======================================
|
||||||
@@ -169,7 +197,10 @@ service. The webservice may be launched as follows:
|
|||||||
|
|
||||||
.. code-block:: bash
|
.. code-block:: bash
|
||||||
|
|
||||||
docker run --entrypoint python3 -p 5000:5000 jbarlow83/ocrmypdf webservice.py
|
docker run --entrypoint python -p 5000:5000 jbarlow83/ocrmypdf webservice.py
|
||||||
|
|
||||||
|
We omit the ``--rm`` parameter so that the container will not be
|
||||||
|
automatically deleted when it exits.
|
||||||
|
|
||||||
This will configure the machine to listen on port 5000. On Linux machines
|
This will configure the machine to listen on port 5000. On Linux machines
|
||||||
this is port 5000 of localhost. On macOS or Windows machines running
|
this is port 5000 of localhost. On macOS or Windows machines running
|
||||||
|
|||||||
+4
-2
@@ -12,7 +12,7 @@ files, allowing them to be searched.
|
|||||||
|
|
||||||
PDF is the best format for storing and exchanging scanned documents.
|
PDF is the best format for storing and exchanging scanned documents.
|
||||||
Unfortunately, PDFs can be difficult to modify. OCRmyPDF makes it easy to apply
|
Unfortunately, PDFs can be difficult to modify. OCRmyPDF makes it easy to apply
|
||||||
image processing and OCR to existing PDFs.
|
image processing and OCR (recognized, searchable text) to existing PDFs.
|
||||||
|
|
||||||
.. toctree::
|
.. toctree::
|
||||||
:maxdepth: 1
|
:maxdepth: 1
|
||||||
@@ -20,7 +20,6 @@ image processing and OCR to existing PDFs.
|
|||||||
introduction
|
introduction
|
||||||
release_notes
|
release_notes
|
||||||
installation
|
installation
|
||||||
optimizer
|
|
||||||
languages
|
languages
|
||||||
jbig2
|
jbig2
|
||||||
|
|
||||||
@@ -29,9 +28,11 @@ image processing and OCR to existing PDFs.
|
|||||||
:maxdepth: 2
|
:maxdepth: 2
|
||||||
|
|
||||||
cookbook
|
cookbook
|
||||||
|
optimizer
|
||||||
docker
|
docker
|
||||||
advanced
|
advanced
|
||||||
batch
|
batch
|
||||||
|
cloud
|
||||||
performance
|
performance
|
||||||
pdfsecurity
|
pdfsecurity
|
||||||
errors
|
errors
|
||||||
@@ -43,6 +44,7 @@ image processing and OCR to existing PDFs.
|
|||||||
api
|
api
|
||||||
plugins
|
plugins
|
||||||
apiref
|
apiref
|
||||||
|
design_notes
|
||||||
contributing
|
contributing
|
||||||
maintainers
|
maintainers
|
||||||
|
|
||||||
|
|||||||
+84
-130
@@ -21,7 +21,7 @@ These platforms have one-liner installs:
|
|||||||
+-------------------------------+-----------------------------------------+
|
+-------------------------------+-----------------------------------------+
|
||||||
| Windows Subsystem for Linux | ``apt install ocrmypdf`` |
|
| Windows Subsystem for Linux | ``apt install ocrmypdf`` |
|
||||||
+-------------------------------+-----------------------------------------+
|
+-------------------------------+-----------------------------------------+
|
||||||
| Fedora | ``dnf install ocrmypdf`` |
|
| Fedora | ``dnf install ocrmypdf tesseract-osd`` |
|
||||||
+-------------------------------+-----------------------------------------+
|
+-------------------------------+-----------------------------------------+
|
||||||
| macOS | ``brew install ocrmypdf`` |
|
| macOS | ``brew install ocrmypdf`` |
|
||||||
+-------------------------------+-----------------------------------------+
|
+-------------------------------+-----------------------------------------+
|
||||||
@@ -44,7 +44,7 @@ install, or install a more recent version than your platform provides, read on.
|
|||||||
Installing on Linux
|
Installing on Linux
|
||||||
===================
|
===================
|
||||||
|
|
||||||
Debian and Ubuntu 18.04 or newer
|
Debian and Ubuntu 20.04 or newer
|
||||||
--------------------------------
|
--------------------------------
|
||||||
|
|
||||||
.. |deb-11| image:: https://repology.org/badge/version-for-repo/debian_11/ocrmypdf.svg
|
.. |deb-11| image:: https://repology.org/badge/version-for-repo/debian_11/ocrmypdf.svg
|
||||||
@@ -56,9 +56,6 @@ Debian and Ubuntu 18.04 or newer
|
|||||||
.. |deb-unstable| image:: https://repology.org/badge/version-for-repo/debian_unstable/ocrmypdf.svg
|
.. |deb-unstable| image:: https://repology.org/badge/version-for-repo/debian_unstable/ocrmypdf.svg
|
||||||
:alt: Debian unstable
|
:alt: Debian unstable
|
||||||
|
|
||||||
.. |ubu-1804| image:: https://repology.org/badge/version-for-repo/ubuntu_18_04/ocrmypdf.svg
|
|
||||||
:alt: Ubuntu 18.04 LTS
|
|
||||||
|
|
||||||
.. |ubu-2004| image:: https://repology.org/badge/version-for-repo/ubuntu_20_04/ocrmypdf.svg
|
.. |ubu-2004| image:: https://repology.org/badge/version-for-repo/ubuntu_20_04/ocrmypdf.svg
|
||||||
:alt: Ubuntu 20.04 LTS
|
:alt: Ubuntu 20.04 LTS
|
||||||
|
|
||||||
@@ -72,15 +69,14 @@ Debian and Ubuntu 18.04 or newer
|
|||||||
+-----------------------------------------------+
|
+-----------------------------------------------+
|
||||||
| |deb-11| |deb-12| |deb-unstable| |
|
| |deb-11| |deb-12| |deb-unstable| |
|
||||||
+-----------------------------------------------+
|
+-----------------------------------------------+
|
||||||
| |ubu-1804| |ubu-2004| |ubu-2204| |
|
| |ubu-2004| |ubu-2204| |
|
||||||
+-----------------------------------------------+
|
+-----------------------------------------------+
|
||||||
|
|
||||||
Users of Debian 9 ("stretch") or later, or Ubuntu 18.04 or later, including users
|
Users of Debian or Ubuntu may simply
|
||||||
of Windows Subsystem for Linux, may simply
|
|
||||||
|
|
||||||
.. code-block:: bash
|
.. code-block:: bash
|
||||||
|
|
||||||
apt-get install ocrmypdf
|
apt install ocrmypdf
|
||||||
|
|
||||||
As indicated in the table above, Debian and Ubuntu releases may lag
|
As indicated in the table above, Debian and Ubuntu releases may lag
|
||||||
behind the latest version. If the version available for your platform is
|
behind the latest version. If the version available for your platform is
|
||||||
@@ -103,11 +99,11 @@ For full details on version availability for your platform, check the
|
|||||||
Fedora
|
Fedora
|
||||||
------
|
------
|
||||||
|
|
||||||
.. |fedora-35| image:: https://repology.org/badge/version-for-repo/fedora_35/ocrmypdf.svg
|
.. |fedora-37| image:: https://repology.org/badge/version-for-repo/fedora_37/ocrmypdf.svg
|
||||||
:alt: Fedora 35
|
:alt: Fedora 37
|
||||||
|
|
||||||
.. |fedora-36| image:: https://repology.org/badge/version-for-repo/fedora_36/ocrmypdf.svg
|
.. |fedora-38| image:: https://repology.org/badge/version-for-repo/fedora_38/ocrmypdf.svg
|
||||||
:alt: Fedora 36
|
:alt: Fedora 38
|
||||||
|
|
||||||
.. |fedora-rawhide| image:: https://repology.org/badge/version-for-repo/fedora_rawhide/ocrmypdf.svg
|
.. |fedora-rawhide| image:: https://repology.org/badge/version-for-repo/fedora_rawhide/ocrmypdf.svg
|
||||||
:alt: Fedore Rawhide
|
:alt: Fedore Rawhide
|
||||||
@@ -117,14 +113,14 @@ Fedora
|
|||||||
+-----------------------------------------------+
|
+-----------------------------------------------+
|
||||||
| |latest| |
|
| |latest| |
|
||||||
+-----------------------------------------------+
|
+-----------------------------------------------+
|
||||||
| |fedora-35| |fedora-36| |fedora-rawhide| |
|
| |fedora-37| |fedora-38| |fedora-rawhide| |
|
||||||
+-----------------------------------------------+
|
+-----------------------------------------------+
|
||||||
|
|
||||||
Users of Fedora 29 or later may simply
|
Users of Fedora may simply
|
||||||
|
|
||||||
.. code-block:: bash
|
.. code-block:: bash
|
||||||
|
|
||||||
dnf install ocrmypdf
|
dnf install ocrmypdf tesseract-osd
|
||||||
|
|
||||||
For full details on version availability, check the `Fedora Package
|
For full details on version availability, check the `Fedora Package
|
||||||
Tracker <https://apps.fedoraproject.org/packages/ocrmypdf>`__.
|
Tracker <https://apps.fedoraproject.org/packages/ocrmypdf>`__.
|
||||||
@@ -159,7 +155,7 @@ user, follow these steps:
|
|||||||
|
|
||||||
If you get the message ``WARNING: The script ocrmypdf is installed in
|
If you get the message ``WARNING: The script ocrmypdf is installed in
|
||||||
'/home/$USER/.local/bin' which is not on PATH.``, you may need to re-login
|
'/home/$USER/.local/bin' which is not on PATH.``, you may need to re-login
|
||||||
or open a new shell, or manually add this to your user's PATH.
|
or open a new shell, or manually adjust your PATH.
|
||||||
|
|
||||||
To add JBIG2 encoding, see :ref:`jbig2`.
|
To add JBIG2 encoding, see :ref:`jbig2`.
|
||||||
|
|
||||||
@@ -198,46 +194,6 @@ To install for the current user only:
|
|||||||
|
|
||||||
To add JBIG2 encoding, see :ref:`jbig2`.
|
To add JBIG2 encoding, see :ref:`jbig2`.
|
||||||
|
|
||||||
Ubuntu 18.04 LTS
|
|
||||||
----------------
|
|
||||||
|
|
||||||
Ubuntu 18.04 includes ocrmypdf 6.1.2 - you can install that with ``apt``, but
|
|
||||||
it is quite old now. To install a more recent version, uninstall the old version
|
|
||||||
of ocrmypdf, and install the following dependencies:
|
|
||||||
|
|
||||||
.. code-block:: bash
|
|
||||||
|
|
||||||
sudo apt-get -y remove ocrmypdf
|
|
||||||
sudo apt-get -y update
|
|
||||||
sudo apt-get -y install \
|
|
||||||
ghostscript \
|
|
||||||
icc-profiles-free \
|
|
||||||
libxml2 \
|
|
||||||
pngquant \
|
|
||||||
python3-distutils \
|
|
||||||
python3-pkg-resources \
|
|
||||||
python3-reportlab \
|
|
||||||
qpdf \
|
|
||||||
tesseract-ocr \
|
|
||||||
zlib1g \
|
|
||||||
unpaper
|
|
||||||
|
|
||||||
We will need a newer version of ``pip`` then was available for Ubuntu 18.04:
|
|
||||||
|
|
||||||
.. code-block:: bash
|
|
||||||
|
|
||||||
wget https://bootstrap.pypa.io/get-pip.py && python3 get-pip.py
|
|
||||||
|
|
||||||
Then install the most recent ocrmypdf for the local user and set the
|
|
||||||
user's ``PATH`` to check for the user's Python packages.
|
|
||||||
|
|
||||||
.. code-block:: bash
|
|
||||||
|
|
||||||
export PATH=$HOME/.local/bin:$PATH
|
|
||||||
python3 -m pip install --user ocrmypdf
|
|
||||||
|
|
||||||
To add JBIG2 encoding, see :ref:`jbig2`.
|
|
||||||
|
|
||||||
Arch Linux (AUR)
|
Arch Linux (AUR)
|
||||||
----------------
|
----------------
|
||||||
|
|
||||||
@@ -318,6 +274,21 @@ To install OCRmyPDF for Alpine Linux:
|
|||||||
|
|
||||||
apk add ocrmypdf
|
apk add ocrmypdf
|
||||||
|
|
||||||
|
Gentoo Linux
|
||||||
|
------------
|
||||||
|
|
||||||
|
.. image:: https://repology.org/badge/version-for-repo/gentoo_ovl_guru/ocrmypdf.svg
|
||||||
|
:alt: Gentoo Linux
|
||||||
|
:target: https://repology.org/metapackage/ocrmypdf
|
||||||
|
|
||||||
|
To install OCRmyPDF on Gentoo Linux, use the following commands:
|
||||||
|
|
||||||
|
.. code-block:: bash
|
||||||
|
|
||||||
|
eselect repository enable guru
|
||||||
|
emaint sync --repo guru
|
||||||
|
emerge --ask app-text/OCRmyPDF
|
||||||
|
|
||||||
Other Linux packages
|
Other Linux packages
|
||||||
--------------------
|
--------------------
|
||||||
|
|
||||||
@@ -336,7 +307,7 @@ Homebrew
|
|||||||
|
|
||||||
.. image:: https://img.shields.io/homebrew/v/ocrmypdf.svg
|
.. image:: https://img.shields.io/homebrew/v/ocrmypdf.svg
|
||||||
:alt: homebrew
|
:alt: homebrew
|
||||||
:target: http://brewformulas.org/Ocrmypdf
|
:target: https://formulae.brew.sh/formula/ocrmypdf
|
||||||
|
|
||||||
OCRmyPDF is now a standard `Homebrew <https://brew.sh>`__ formula. To
|
OCRmyPDF is now a standard `Homebrew <https://brew.sh>`__ formula. To
|
||||||
install on macOS:
|
install on macOS:
|
||||||
@@ -387,18 +358,12 @@ Update the homebrew pip:
|
|||||||
|
|
||||||
pip install --upgrade pip
|
pip install --upgrade pip
|
||||||
|
|
||||||
You can then install OCRmyPDF from PyPI, for the current user:
|
You can then install OCRmyPDF from PyPI for the current user:
|
||||||
|
|
||||||
.. code-block:: bash
|
.. code-block:: bash
|
||||||
|
|
||||||
pip install --user ocrmypdf
|
pip install --user ocrmypdf
|
||||||
|
|
||||||
or system-wide:
|
|
||||||
|
|
||||||
.. code-block:: bash
|
|
||||||
|
|
||||||
pip install ocrmypdf
|
|
||||||
|
|
||||||
The command line program should now be available:
|
The command line program should now be available:
|
||||||
|
|
||||||
.. code-block:: bash
|
.. code-block:: bash
|
||||||
@@ -417,31 +382,35 @@ Native Windows
|
|||||||
|
|
||||||
You must install the following for Windows:
|
You must install the following for Windows:
|
||||||
|
|
||||||
* Python 3.7 (64-bit) or later
|
* Python 64-bit
|
||||||
* Tesseract 4.0 or later
|
* Tesseract 64-bit
|
||||||
* Ghostscript 9.50 or later
|
* Ghostscript 64-bit
|
||||||
|
|
||||||
Using the `Chocolatey <https://chocolatey.org/>`_ package manager, install the
|
Using the `winget <https://docs.microsoft.com/en-us/windows/package-manager/winget/>`_
|
||||||
following when running in an Administrator command prompt:
|
package manager:
|
||||||
|
|
||||||
|
* ``winget install -e --id Python.Python.3.11``
|
||||||
|
* ``winget install -e --id UB-Mannheim.TesseractOCR``
|
||||||
|
|
||||||
|
You will need to install Ghostscript manually, `since it does not support automated
|
||||||
|
installs anymore <https://artifex.com/news/ghostscript-10.01.0-disabling-silent-install-option>`_.
|
||||||
|
|
||||||
|
* `Ghostscript download page <https://ghostscript.com/releases/gsdnld.html>`_.`
|
||||||
|
|
||||||
|
(Or alternately, using the `Chocolatey <https://chocolatey.org/>`_ package manager, install
|
||||||
|
the following when running in an Administrator command prompt):
|
||||||
|
|
||||||
* ``choco install python3``
|
* ``choco install python3``
|
||||||
* ``choco install --pre tesseract``
|
* ``choco install --pre tesseract``
|
||||||
* ``choco install ghostscript``
|
|
||||||
* ``choco install pngquant`` (optional)
|
* ``choco install pngquant`` (optional)
|
||||||
|
|
||||||
The commands above will install Python 3.x (latest version), Tesseract, Ghostscript
|
Either set of commands will install the required software. At the moment there is no
|
||||||
and pngquant. Chocolatey may also need to install the Windows Visual C++ Runtime
|
single command to install Windows.
|
||||||
DLLs or other Windows patches, and may require a reboot.
|
|
||||||
|
|
||||||
You may then use ``pip`` to install ocrmypdf. (This can performed by a user or
|
You may then use ``pip`` to install ocrmypdf. (This can performed by a user or
|
||||||
Administrator.):
|
Administrator.):
|
||||||
|
|
||||||
* ``pip install ocrmypdf``
|
* ``python3 -m pip install ocrmypdf``
|
||||||
|
|
||||||
Chocolatey automatically selects appropriate versions of these applications. If you
|
|
||||||
are installing them manually, please install 64-bit versions of all applications for
|
|
||||||
64-bit Windows, or 32-bit versions of all applications for 32-bit Windows. Mixing
|
|
||||||
the "bitness" of these programs will lead to errors.
|
|
||||||
|
|
||||||
OCRmyPDF will check the Windows Registry and standard locations in your Program Files
|
OCRmyPDF will check the Windows Registry and standard locations in your Program Files
|
||||||
for third party software it needs (specifically, Tesseract and Ghostscript). To
|
for third party software it needs (specifically, Tesseract and Ghostscript). To
|
||||||
@@ -453,9 +422,13 @@ to change the PATH.
|
|||||||
|
|
||||||
As of early 2021, users have reported problems with the Microsoft Store version of
|
As of early 2021, users have reported problems with the Microsoft Store version of
|
||||||
Python and OCRmyPDF. These issues affect many other third party Python packages.
|
Python and OCRmyPDF. These issues affect many other third party Python packages.
|
||||||
Please download Python from Python.org or Chocolatey instead, and do not use the
|
Please download Python from Python.org or a package manager instead of the
|
||||||
Microsoft Store version.
|
Microsoft Store version.
|
||||||
|
|
||||||
|
.. warning::
|
||||||
|
|
||||||
|
32-bit Windows is not supported.
|
||||||
|
|
||||||
Windows Subsystem for Linux
|
Windows Subsystem for Linux
|
||||||
---------------------------
|
---------------------------
|
||||||
|
|
||||||
@@ -481,7 +454,7 @@ Cygwin64
|
|||||||
|
|
||||||
First install the the following prerequisite Cygwin packages using ``setup-x86_64.exe``::
|
First install the the following prerequisite Cygwin packages using ``setup-x86_64.exe``::
|
||||||
|
|
||||||
python37 (or later)
|
python310 (or later)
|
||||||
python3?-devel
|
python3?-devel
|
||||||
python3?-pip
|
python3?-pip
|
||||||
python3?-lxml
|
python3?-lxml
|
||||||
@@ -490,7 +463,7 @@ First install the the following prerequisite Cygwin packages using ``setup-x86_6
|
|||||||
(where 3? means match the version of python3 you installed)
|
(where 3? means match the version of python3 you installed)
|
||||||
|
|
||||||
gcc-g++
|
gcc-g++
|
||||||
ghostscript (<=9.50 or >=9.52-2 see note below)
|
ghostscript
|
||||||
libexempi3
|
libexempi3
|
||||||
libexempi-devel
|
libexempi-devel
|
||||||
libffi6
|
libffi6
|
||||||
@@ -501,13 +474,6 @@ First install the the following prerequisite Cygwin packages using ``setup-x86_6
|
|||||||
tesseract-ocr
|
tesseract-ocr
|
||||||
tesseract-ocr-devel
|
tesseract-ocr-devel
|
||||||
|
|
||||||
.. note::
|
|
||||||
|
|
||||||
The Cygwin package for Ghostscript in versions 9.52 and
|
|
||||||
9.52-1 contained a bug that caused an exception to occur when
|
|
||||||
ocrmypdf invoked gs. Make sure you have either 9.50 (or earlier)
|
|
||||||
or 9.52-2 (or later).
|
|
||||||
|
|
||||||
Then open a Cygwin terminal (i.e. ``mintty``), run the following commands. Note
|
Then open a Cygwin terminal (i.e. ``mintty``), run the following commands. Note
|
||||||
that if you are using the version of ``pip`` that was installed with the Cygwin
|
that if you are using the version of ``pip`` that was installed with the Cygwin
|
||||||
Python package, the command name will be ``pip3``. If you have since updated
|
Python package, the command name will be ``pip3``. If you have since updated
|
||||||
@@ -559,21 +525,6 @@ the latest version. However, PyPI and ``pip`` cannot address the fact
|
|||||||
that ``ocrmypdf`` depends on certain non-Python system libraries and
|
that ``ocrmypdf`` depends on certain non-Python system libraries and
|
||||||
programs being installed.
|
programs being installed.
|
||||||
|
|
||||||
.. warning::
|
|
||||||
|
|
||||||
Debian and Ubuntu users: unfortunately, Debian and Ubuntu customize
|
|
||||||
Python in non-standard ways, and the nature of these customizations
|
|
||||||
varies from release to release. This can make for a frustrating
|
|
||||||
user experience. The instructions below work on almost all platforms that
|
|
||||||
have Python installed, except for Debian and Ubuntu, where you may need
|
|
||||||
to take additional steps. For best results on Debian and Ubuntu, use the
|
|
||||||
``apt`` packages; or if these are too old, run
|
|
||||||
``apt install python3-pip python3-venv``, create a virtual environment,
|
|
||||||
and install OCRmyPDF in that environment.
|
|
||||||
|
|
||||||
`See here for more inforation on Debian-Python issues
|
|
||||||
<https://gist.github.com/tiran/2dec9e03c6f901814f6d1e8dad09528e>`__.
|
|
||||||
|
|
||||||
For best results, first install `your platform's
|
For best results, first install `your platform's
|
||||||
version <https://repology.org/metapackage/ocrmypdf/versions>`__ of
|
version <https://repology.org/metapackage/ocrmypdf/versions>`__ of
|
||||||
``ocrmypdf``, using the instructions elsewhere in this document. Then
|
``ocrmypdf``, using the instructions elsewhere in this document. Then
|
||||||
@@ -592,21 +543,6 @@ try:
|
|||||||
You should then be able to run ``ocrmypdf --version`` and see that the
|
You should then be able to run ``ocrmypdf --version`` and see that the
|
||||||
latest version was located.
|
latest version was located.
|
||||||
|
|
||||||
Since ``pip install --user`` does not work correctly on some platforms,
|
|
||||||
notably Ubuntu 16.04 and older, and the Homebrew version of Python,
|
|
||||||
instead use this for a system wide installation:
|
|
||||||
|
|
||||||
.. code-block:: bash
|
|
||||||
|
|
||||||
pip install ocrmypdf
|
|
||||||
|
|
||||||
.. note::
|
|
||||||
|
|
||||||
AArch64 (ARM64) users: this process will be difficult because most
|
|
||||||
Python packages are not available as binary wheels for your platform.
|
|
||||||
You're probably better off using a platform install on Debian, Ubuntu,
|
|
||||||
or Fedora.
|
|
||||||
|
|
||||||
Requirements for pip and HEAD install
|
Requirements for pip and HEAD install
|
||||||
-------------------------------------
|
-------------------------------------
|
||||||
|
|
||||||
@@ -616,13 +552,16 @@ manager. ``pip`` cannot provide them.
|
|||||||
|
|
||||||
The following versions are required:
|
The following versions are required:
|
||||||
|
|
||||||
- Python 3.7 or newer
|
- Python 3.10 or newer
|
||||||
- Ghostscript 9.23 or newer
|
- Ghostscript 9.55 or newer
|
||||||
- Tesseract 4.0.0 or newer
|
- Tesseract 4.1.1 or newer
|
||||||
- jbig2enc 0.29 or newer
|
- jbig2enc 0.29 or newer
|
||||||
- pngquant 2.5 or newer
|
- pngquant 2.5 or newer
|
||||||
- unpaper 6.1
|
- unpaper 6.1
|
||||||
|
|
||||||
|
We recommend 64-bit versions of all software. (32-bit versions are not
|
||||||
|
supported, although on Linux, they may still work.)
|
||||||
|
|
||||||
jbig2enc, pngquant, and unpaper are optional. If missing certain
|
jbig2enc, pngquant, and unpaper are optional. If missing certain
|
||||||
features are disabled. OCRmyPDF will discover them as soon as they are
|
features are disabled. OCRmyPDF will discover them as soon as they are
|
||||||
available.
|
available.
|
||||||
@@ -649,7 +588,7 @@ unfortunately, the ``pip install`` command cannot satisfy all of them.
|
|||||||
Installing HEAD revision from sources
|
Installing HEAD revision from sources
|
||||||
=====================================
|
=====================================
|
||||||
|
|
||||||
If you have ``git`` and Python 3.7 or newer installed, you can install
|
If you have ``git`` and Python 3.10 or newer installed, you can install
|
||||||
from source. When the ``pip`` installer runs, it will alert you if
|
from source. When the ``pip`` installer runs, it will alert you if
|
||||||
dependencies are missing.
|
dependencies are missing.
|
||||||
|
|
||||||
@@ -678,9 +617,9 @@ system-wide:
|
|||||||
|
|
||||||
.. code-block:: bash
|
.. code-block:: bash
|
||||||
|
|
||||||
git clone -b master https://github.com/ocrmypdf/OCRmyPDF.git
|
git clone -b main https://github.com/ocrmypdf/OCRmyPDF.git
|
||||||
python3 -m venv
|
python3 -m venv .venv
|
||||||
source venv/bin/activate
|
source .venv/bin/activate
|
||||||
cd OCRmyPDF
|
cd OCRmyPDF
|
||||||
pip install .
|
pip install .
|
||||||
|
|
||||||
@@ -705,9 +644,9 @@ To install all of the development and test requirements:
|
|||||||
|
|
||||||
.. code-block:: bash
|
.. code-block:: bash
|
||||||
|
|
||||||
git clone -b master https://github.com/ocrmypdf/OCRmyPDF.git
|
git clone -b main https://github.com/ocrmypdf/OCRmyPDF.git
|
||||||
python -m venv
|
python -m .venv
|
||||||
source venv/bin/activate
|
source .venv/bin/activate
|
||||||
cd OCRmyPDF
|
cd OCRmyPDF
|
||||||
pip install -e .[test]
|
pip install -e .[test]
|
||||||
|
|
||||||
@@ -728,3 +667,18 @@ To manually install the ``bash`` completion, copy
|
|||||||
To manually install the ``fish`` completion, copy
|
To manually install the ``fish`` completion, copy
|
||||||
``misc/completion/ocrmypdf.fish`` to
|
``misc/completion/ocrmypdf.fish`` to
|
||||||
``~/.config/fish/completions/ocrmypdf.fish``.
|
``~/.config/fish/completions/ocrmypdf.fish``.
|
||||||
|
|
||||||
|
Note on 32-bit support
|
||||||
|
======================
|
||||||
|
|
||||||
|
Many Python libraries no longer 32-bit binary wheels for Linux. This
|
||||||
|
includes many of the libraries that OCRmyPDF depends on, such as
|
||||||
|
Pillow. The easiest way to express this to end users is to say we don't
|
||||||
|
support 32-bit Linux.
|
||||||
|
|
||||||
|
However, if your Linux distribution still supports 32-bit binaries, you
|
||||||
|
can still install and use OCRmyPDF. A warning message will appear.
|
||||||
|
In practice, OCRmyPDF may need more than 32-bit memory space to run when
|
||||||
|
large documents are processed, so there are practical limitations to what
|
||||||
|
users can accomplish with it. Still, for the common use case of an 32-bit
|
||||||
|
ARM NAS or Raspberry Pi processing small documents, it should work.
|
||||||
|
|||||||
+109
-127
@@ -6,23 +6,23 @@
|
|||||||
Introduction
|
Introduction
|
||||||
============
|
============
|
||||||
|
|
||||||
OCRmyPDF is an application and library that adds text "layers" to images
|
OCRmyPDF is a Python application and library that adds text "layers" to images in
|
||||||
in PDFs, making scanned image PDFs searchable. It uses OCR to guess what text
|
PDFs, making scanned image PDFs searchable. It uses OCR to guess the text
|
||||||
is contained in images. It is written in Python. OCRmyPDF supports plugins
|
contained in images. OCRmyPDF also supports plugins
|
||||||
that allow customization of its processing steps, and is very tolerant of
|
that enable customization of its processing steps, and it is highly tolerant
|
||||||
PDFs that contain scanned images and "born digital" content that needs no
|
of PDFs containing scanned images and "born digital" content that doesn't
|
||||||
text recognition.
|
require text recognition.
|
||||||
|
|
||||||
About OCR
|
About OCR
|
||||||
=========
|
=========
|
||||||
|
|
||||||
`Optical character
|
`Optical character
|
||||||
recognition <https://en.wikipedia.org/wiki/Optical_character_recognition>`__
|
recognition <https://en.wikipedia.org/wiki/Optical_character_recognition>`__
|
||||||
is technology that converts images of typed or handwritten text, such as
|
is a technology that converts images of typed or handwritten text, such as
|
||||||
in a scanned document, to computer text that can be selected, searched and copied.
|
in a scanned document, into computer text that can be selected, searched and copied.
|
||||||
|
|
||||||
OCRmyPDF uses
|
OCRmyPDF uses
|
||||||
`Tesseract <https://github.com/tesseract-ocr/tesseract>`__, the best
|
`Tesseract <https://github.com/tesseract-ocr/tesseract>`__, a widely
|
||||||
available open source OCR engine, to perform OCR.
|
available open source OCR engine, to perform OCR.
|
||||||
|
|
||||||
.. _raster-vector:
|
.. _raster-vector:
|
||||||
@@ -30,19 +30,19 @@ available open source OCR engine, to perform OCR.
|
|||||||
About PDFs
|
About PDFs
|
||||||
==========
|
==========
|
||||||
|
|
||||||
PDFs are page description files that attempts to preserve a layout
|
PDFs are page description files that attempt to preserve a layout
|
||||||
exactly. They contain `vector
|
exactly. They contain `vector
|
||||||
graphics <http://vector-conversions.com/vectorizing/raster_vs_vector.html>`__
|
graphics <http://vector-conversions.com/vectorizing/raster_vs_vector.html>`__
|
||||||
that can contain raster objects such as scanned images. Because PDFs can
|
that can contain raster objects, such as scanned images. Because PDFs can
|
||||||
contain multiple pages (unlike many image formats) and can contain fonts
|
contain multiple pages (unlike many image formats) and can contain fonts
|
||||||
and text, it is a good format for exchanging scanned documents.
|
and text, they are a suitable format for exchanging scanned documents.
|
||||||
|
|
||||||
|image|
|
|image|
|
||||||
|
|
||||||
A PDF page might contain multiple images, even if it only appears to
|
A PDF page may contain multiple images, even if it appears to have only
|
||||||
have one image. Some scanners or scanning software will segment pages
|
one image. Some scanners or scanning software may segment pages into
|
||||||
into monochromatic text and color regions for example, to improve the
|
monochromatic text and color regions, for example, to enhance the compression
|
||||||
compression ratio and appearance of the page.
|
ratio and appearance of the page.
|
||||||
|
|
||||||
Rasterizing a PDF is the process of generating corresponding raster images.
|
Rasterizing a PDF is the process of generating corresponding raster images.
|
||||||
OCR engines like Tesseract work with images, not scalable vector graphics
|
OCR engines like Tesseract work with images, not scalable vector graphics
|
||||||
@@ -54,148 +54,131 @@ About PDF/A
|
|||||||
`PDF/A <https://en.wikipedia.org/wiki/PDF/A>`__ is an ISO-standardized
|
`PDF/A <https://en.wikipedia.org/wiki/PDF/A>`__ is an ISO-standardized
|
||||||
subset of the full PDF specification that is designed for archiving (the
|
subset of the full PDF specification that is designed for archiving (the
|
||||||
'A' stands for Archive). PDF/A differs from PDF primarily by omitting
|
'A' stands for Archive). PDF/A differs from PDF primarily by omitting
|
||||||
features that would make it difficult to read the file in the future,
|
features that could complicate future file readability,
|
||||||
such as embedded Javascript, video, audio and references to external
|
such as embedded Javascript, video, audio and references to external
|
||||||
fonts. All fonts and resources needed to interpret the PDF must be
|
fonts. All fonts and resources needed to interpret the PDF must be
|
||||||
contained within it. Because PDF/A disables Javascript and other types
|
contained within it. Because PDF/A disables Javascript and other types
|
||||||
of embedded content, it is probably more secure.
|
of embedded content, it is likely more secure.
|
||||||
|
|
||||||
There are various conformance levels and versions, such as "PDF/A-2b".
|
There are various conformance levels and versions, such as "PDF/A-2b".
|
||||||
|
|
||||||
Generally speaking, the best format for scanned documents is PDF/A. Some
|
In general, the preferred format for scanned documents is PDF/A. Some
|
||||||
governments and jurisdictions, US Courts in particular, `mandate the use
|
governments and jurisdictions, US Courts in particular, `mandate the use
|
||||||
of PDF/A <https://pdfblog.com/2012/02/13/what-is-pdfa/>`__ for scanned
|
of PDF/A <https://pdfblog.com/2012/02/13/what-is-pdfa/>`__ for scanned
|
||||||
documents.
|
documents.
|
||||||
|
|
||||||
Since most people who scan documents are interested in reading them
|
Since most individuals scanning documents aim for long-term readability,
|
||||||
indefinitely into the future, OCRmyPDF generates PDF/A-2b by default.
|
OCRmyPDF defaults to generating PDF/A-2b.
|
||||||
|
|
||||||
PDF/A has a few drawbacks. Some PDF viewers include an alert that the
|
PDF/A does have a few drawbacks. Some PDF viewers display an alert
|
||||||
file is a PDF/A, which may confuse some users. It also tends to produce
|
indicating that the file is in PDF/A format, which may confuse some users.
|
||||||
larger files than PDF, because it embeds certain resources even if they
|
Additionally, it tends to result in larger files than standard PDFs because
|
||||||
are commonly available. PDF/A files can be digitally signed, but may not
|
it embeds certain resources, even if they are widely available. PDF/A
|
||||||
be encrypted, to ensure they can be read in the future. Fortunately,
|
files can be digitally signed but may not be encrypted to ensure future
|
||||||
converting from PDF/A to a regular PDF is trivial, and any PDF viewer
|
readability. Fortunately, converting from PDF/A to a regular PDF is
|
||||||
can view PDF/A.
|
straightforward, and any PDF viewer can handle PDF/A files.
|
||||||
|
|
||||||
What OCRmyPDF does
|
What OCRmyPDF does
|
||||||
==================
|
==================
|
||||||
|
|
||||||
OCRmyPDF analyzes each page of a PDF to determine the colorspace and
|
OCRmyPDF analyzes each page of a PDF to determine the required colorspace
|
||||||
resolution (DPI) needed to capture all of the information on that page
|
and resolution (DPI) for capturing all the information on that page without
|
||||||
without losing content. It uses
|
losing content. It uses
|
||||||
`Ghostscript <http://ghostscript.com/>`__ to rasterize the page, and
|
`Ghostscript <http://ghostscript.com/>`__ to rasterize each page and subsequently
|
||||||
then performs on OCR the rasterized image to create an OCR "layer".
|
performs OCR on the rasterized image to generate an OCR "layer." This layer
|
||||||
The layer is then grafted back onto the original PDF.
|
is then integrated back into the original PDF.
|
||||||
|
|
||||||
While one can use a program like Ghostscript or ImageMagick to get an
|
While it is possible to use a program like Ghostscript or ImageMagick to
|
||||||
image and put the image through Tesseract, that actually creates a new
|
obtain an image and then run that image through Tesseract OCR, this process
|
||||||
PDF and many details may be lost. OCRmyPDF can produce a minimally
|
actually generates a new PDF, potentially resulting in the loss of various
|
||||||
changed PDF as output.
|
details (such as the document's metadata). In contrast, OCRmyPDF can produce
|
||||||
|
a minimally altered PDF as the output.
|
||||||
|
|
||||||
OCRmyPDF also provides some image processing options, like deskew, which
|
OCRmyPDF also offers several image processing options, such as deskew, which
|
||||||
improves the appearance of files and quality of OCR. When these are used,
|
enhances the visual quality of files and the accuracy of OCR. When these
|
||||||
the OCR layer is grafted onto the processed image instead.
|
options are utilized, the OCR layer is integrated into the processed image.
|
||||||
|
|
||||||
By default, OCRmyPDF produces archival PDFs – PDF/A, which are a
|
By default, OCRmyPDF generates archival PDFs in the PDF/A format, which is
|
||||||
stricter subset of PDF features designed for long term archives. If
|
a more rigid subset of PDF features designed for long-term archives. If you
|
||||||
regular PDFs are desired, this can be disabled with
|
prefer regular PDFs, you can disable this feature using the
|
||||||
``--output-type pdf``.
|
``--output-type pdf`` option.
|
||||||
|
|
||||||
Why you shouldn't do this manually
|
Why you shouldn't do this manually
|
||||||
==================================
|
==================================
|
||||||
|
|
||||||
A PDF is similar to an HTML file, in that it contains document structure
|
A PDF is similar to an HTML file, in that it contains document structure
|
||||||
along with images. Sometimes a PDF does nothing more than present a full
|
along with images. While some PDFs may solely display a full-page image,
|
||||||
page image, but often there is additional content that would be lost.
|
they often contain additional content that would be forfeited if not preserved.
|
||||||
|
|
||||||
A manual process could work like either of these:
|
A manual process could take one of these approaches:
|
||||||
|
|
||||||
1. Rasterize each page as an image, OCR the images, and combine the
|
1. Rasterize each page as an image, perform OCR on the images, and then merge the
|
||||||
output into a PDF. This preserves the layout of each page, but
|
output into a PDF. This method preserves the layout of each page, but
|
||||||
resamples all images (possibly losing quality, increasing file size,
|
resamples all images potentially leading to quality loss, increased file size,
|
||||||
introducing compression artifacts, etc.).
|
and the introduction of compression artifacts, among other issues.
|
||||||
2. Extract each image, OCR, and combine the output into a PDF. This
|
2. Extract each image, OCR, and combine the output into a PDF. This approach
|
||||||
loses the context in which images are used in the PDF, meaning that
|
loses the context in which images are used in the PDF, potentially resulting
|
||||||
cropping, rotation and scaling of pages may be lost. Some scanned
|
in loss of information related to scaling and position of images. Some scanned
|
||||||
PDFs use multiple images segmented into black and white, grayscale
|
PDFs contain multiple images segmented into black and white, grayscale
|
||||||
and color regions, with stencil masks to prevent overlap, as this can
|
and color regions, with stencil masks to prevent overlap, as this can
|
||||||
enhance the appearance of a file while reducing file size. Clearly,
|
enhance the appearance of a file while reducing file size.
|
||||||
reassembling these images will be easy. This also loses and text or
|
Reassembling these images can be challenging, and risks losing vector art
|
||||||
vector art on any pages in a PDF with both scanned and pure digital
|
or text that is not part of an image.
|
||||||
content.
|
|
||||||
|
|
||||||
In the case of a PDF that is nothing other than a container of images
|
In cases where a PDF solely serves as a container for images without any
|
||||||
(no rotation, scaling, cropping, one image per page), the second
|
rotation, scaling, or cropping, the second approach can be lossless.
|
||||||
approach can be lossless.
|
|
||||||
|
|
||||||
OCRmyPDF uses several strategies depending on input options and the
|
OCRmyPDF uses various strategies depending on input options and the input PDF
|
||||||
input PDF itself, but generally speaking it rasterizes a page for OCR
|
itself. Generally, it rasterizes a page for OCR and then integrates the OCR
|
||||||
and then grafts the OCR back onto the original. As such it can handle
|
data back into the original PDF. This approach allows it to handle complex
|
||||||
complex PDFs and still preserve their contents as much as possible.
|
PDFs and preserve their content as much as possible.
|
||||||
|
|
||||||
OCRmyPDF also supports a many, many edge cases that have cropped over
|
Furthermore, OCRmyPDF supports a wide range of edge cases that have emerged
|
||||||
several years of development. We support PDF features like images inside
|
during several years of development. It accommodates PDF features like
|
||||||
of Form XObjects, and pages with UserUnit scaling. We support rare image
|
images within Form XObjects and pages with UserUnit scaling. It also
|
||||||
formats like non-monochrome 1-bit images. We warn about files you may
|
supports less common image formats like non-monochrome 1-bit images and
|
||||||
not to OCR. Thanks to pikepdf and QPDF, we auto-repair PDFs that are
|
provides warnings about files you may not want to OCR. Thanks to tools
|
||||||
damaged. (Not that you need to know what any of these are! You should be
|
like pikepdf and QPDF, it can auto-repair damaged PDFs. You don't need to
|
||||||
able to throw any PDF at it.)
|
understand the intricacies of these issues; you should be able to use
|
||||||
|
OCRmyPDF with any PDF file, and expect reasonable results.
|
||||||
|
|
||||||
Limitations
|
Limitations
|
||||||
===========
|
===========
|
||||||
|
|
||||||
OCRmyPDF is limited by the Tesseract OCR engine. As such it experiences
|
OCRmyPDF is subject to limitations imposed by the Tesseract OCR engine.
|
||||||
these limitations, as do any other programs that rely on Tesseract:
|
These limitations are inherent to any software relying on Tesseract:
|
||||||
|
|
||||||
- The OCR is not as accurate as commercial OCR solutions.
|
- The OCR accuracy may not match that of commercial OCR solutions.
|
||||||
- It is not capable of recognizing handwriting.
|
- It is incapable of recognizing handwriting.
|
||||||
- It may find gibberish and report this as OCR output.
|
- It may detect gibberish and report it as OCR output.
|
||||||
- If a document contains languages outside of those given in the
|
- Results may be subpar when a document contains languages not specified
|
||||||
``-l LANG`` arguments, results may be poor.
|
in the ``-l LANG`` argument.
|
||||||
- It is not always good at analyzing the natural reading order of
|
- Tesseract may struggle to analyze the natural reading order of documents.
|
||||||
documents. For example, it may fail to recognize that a document
|
For instance, it might fail to recognize two columns in a document and
|
||||||
contains two columns, and may try to join text across columns.
|
attempt to join text across columns.
|
||||||
- Poor quality scans may produce poor quality OCR. Garbage in, garbage
|
- Poor quality scans can result in subpar OCR quality. In other words, the
|
||||||
out.
|
quality of the OCR output depends on the quality of the input.
|
||||||
- It does not expose information about what font family text belongs
|
- Tesseract does not provide information about the font family to which text
|
||||||
to.
|
belongs.
|
||||||
|
- Tesseract does not divide text into paragraphs or headings. It only provides
|
||||||
OCRmyPDF is also limited by the PDF specification:
|
the text and its bounding box. As such, the generated PDF does not
|
||||||
|
contain any information about the document's structure.
|
||||||
- PDF encodes the position of text glyphs but does not encode document
|
|
||||||
structure. There is no markup that divides a document in sections,
|
|
||||||
paragraphs, sentences, or even words (since blank spaces are not
|
|
||||||
represented). As such all elements of document structure including
|
|
||||||
the spaces between words must be derived heuristically. Some PDF
|
|
||||||
viewers do a better job of this than others.
|
|
||||||
- Because some popular open source PDF viewers have a particularly hard
|
|
||||||
time with spaces between words, OCRmyPDF appends a space to each text
|
|
||||||
element as a workaround (when using ``--pdf-renderer hocr``). While
|
|
||||||
this mixes document structure with graphical information that ideally
|
|
||||||
should be left to the PDF viewer to interpret, it improves
|
|
||||||
compatibility with some viewers and does not cause problems for
|
|
||||||
better ones.
|
|
||||||
|
|
||||||
Ghostscript also imposes some limitations:
|
Ghostscript also imposes some limitations:
|
||||||
|
|
||||||
- PDFs containing JBIG2-encoded content will be converted to CCITT
|
- PDFs containing JPEG 2000-encoded content may be converted to JPEG
|
||||||
Group4 encoding, which has lower compression ratios, if Ghostscript
|
|
||||||
PDF/A is enabled.
|
|
||||||
- PDFs containing JPEG 2000-encoded content will be converted to JPEG
|
|
||||||
encoding, which may introduce compression artifacts, if Ghostscript
|
encoding, which may introduce compression artifacts, if Ghostscript
|
||||||
PDF/A is enabled.
|
PDF/A is enabled.
|
||||||
- Ghostscript may transcode grayscale and color images, either lossy to
|
- Ghostscript may transcode grayscale and color images, potentially
|
||||||
lossless or lossless to lossy, based on an internal algorithm. This
|
lossily, based on an internal algorithm. This
|
||||||
behavior can be suppressed by setting ``--pdfa-image-compression`` to
|
behavior can be suppressed by setting ``--pdfa-image-compression`` to
|
||||||
``jpeg`` or ``lossless`` to set all images to one type or the other.
|
``jpeg`` or ``lossless`` to set all images to one type or the other.
|
||||||
Ghostscript has no option to maintain the input image's format.
|
Ghostscript lacks an option to maintain the input image's format.
|
||||||
(Ghostscript 9.25+ can copy JPEG images without transcoding them;
|
(Modern Ghostscript can copy JPEG images without transcoding them.)
|
||||||
earlier versions will transcode.)
|
|
||||||
- Ghostscript's PDF/A conversion removes any XMP metadata that is not
|
- Ghostscript's PDF/A conversion removes any XMP metadata that is not
|
||||||
one of the standard XMP metadata namespaces for PDFs. In particular,
|
one of the standard XMP metadata namespaces for PDFs. In particular,
|
||||||
PRISM Metdata is removed.
|
PRISM Metadata is removed.
|
||||||
- Ghostscript's PDF/A conversion seems to remove or deactivate
|
- Ghostscript's PDF/A conversion may remove or deactivate
|
||||||
hyperlinks and other active content.
|
hyperlinks and other active content.
|
||||||
|
|
||||||
You can use ``--output-type pdf`` to disable PDF/A conversion and produce
|
You can use ``--output-type pdf`` to disable PDF/A conversion and produce
|
||||||
@@ -203,7 +186,7 @@ a standard, non-archival PDF.
|
|||||||
|
|
||||||
Regarding OCRmyPDF itself:
|
Regarding OCRmyPDF itself:
|
||||||
|
|
||||||
- PDFs that use transparency are not currently represented in the test
|
- PDFs using transparency are not currently represented in the test
|
||||||
suite
|
suite
|
||||||
|
|
||||||
Similar programs
|
Similar programs
|
||||||
@@ -211,11 +194,7 @@ Similar programs
|
|||||||
|
|
||||||
To the author's knowledge, OCRmyPDF is the most feature-rich and
|
To the author's knowledge, OCRmyPDF is the most feature-rich and
|
||||||
thoroughly tested command line OCR PDF conversion tool. If it does not
|
thoroughly tested command line OCR PDF conversion tool. If it does not
|
||||||
meet your needs, contributions and suggestions are welcome. If not,
|
meet your needs, contributions and suggestions are welcome.
|
||||||
consider one of these similar open source programs:
|
|
||||||
|
|
||||||
- pdf2pdfocr
|
|
||||||
- pdfsandwich
|
|
||||||
|
|
||||||
Ghostscript recently added three "pdfocr" output devices. They work by
|
Ghostscript recently added three "pdfocr" output devices. They work by
|
||||||
rasterizing all content and converting all pages to a single colour space.
|
rasterizing all content and converting all pages to a single colour space.
|
||||||
@@ -223,16 +202,19 @@ rasterizing all content and converting all pages to a single colour space.
|
|||||||
Web front-ends
|
Web front-ends
|
||||||
==============
|
==============
|
||||||
|
|
||||||
The Docker image ``ocrmypdf`` provides a web service front-end
|
The Docker image of OCRmyPDF provides a web service front-end
|
||||||
that allows files to submitted over HTTP and the results "downloaded".
|
that allows files to submitted over HTTP, and the results can be downloaded.
|
||||||
This is an HTTP server intended to simplify web services deployments; it
|
This is an HTTP server intended to demonstrate how OCRmyPDF can be
|
||||||
is not intended to be deployed on the public internet and no real
|
integrated into a web service. It is not intended to be deployed on the
|
||||||
security measures to speak of.
|
public internet and does not provide any security measures.
|
||||||
|
|
||||||
In addition, the following third-party integrations are available:
|
In addition, the following third-party integrations are available:
|
||||||
|
|
||||||
|
- `Paperless-ngx <https://docs.paperless-ngx.com/>`__ is a free software
|
||||||
|
document management system that uses OCRmyPDF to perform OCR on
|
||||||
|
uploaded documents.
|
||||||
- `Nextcloud OCR <https://github.com/janis91/ocr>`__ is a free software
|
- `Nextcloud OCR <https://github.com/janis91/ocr>`__ is a free software
|
||||||
plugin for the Nextcloud private cloud software
|
plugin for the Nextcloud private cloud software.
|
||||||
|
|
||||||
OCRmyPDF is not designed to be secure against malware-bearing PDFs (see
|
OCRmyPDF is not designed to be secure against malware-bearing PDFs (see
|
||||||
`Using OCRmyPDF online <ocr-service>`__). Users should ensure they
|
`Using OCRmyPDF online <ocr-service>`__). Users should ensure they
|
||||||
|
|||||||
+22
-9
@@ -14,17 +14,20 @@ expired as of 2017, but it is possible that unknown patents exist.
|
|||||||
|
|
||||||
JBIG2 encoding is recommended for OCRmyPDF and is used to losslessly
|
JBIG2 encoding is recommended for OCRmyPDF and is used to losslessly
|
||||||
create smaller PDFs. If JBIG2 encoding is not available, lower quality
|
create smaller PDFs. If JBIG2 encoding is not available, lower quality
|
||||||
encodings will be used.
|
CCITT encoding will be used for monochrome images.
|
||||||
|
|
||||||
JBIG2 decoding is not patented and is performed automatically by most
|
JBIG2 decoding is not patented and is performed automatically by most
|
||||||
PDF viewers. It is widely supported and has been part of the PDF
|
PDF viewers. It is widely supported and has been part of the PDF
|
||||||
specification since 2001.
|
specification since 2001.
|
||||||
|
|
||||||
On macOS, Homebrew packages jbig2enc and OCRmyPDF includes it by
|
JBIG encoding is automatically provided by these OCRmyPDF packages:
|
||||||
default. The Docker image for OCRmyPDF also builds its own JBIG2 encoder
|
- Docker image (both Ubuntu and Alpine)
|
||||||
from source.
|
- Snap package
|
||||||
|
- ArchLinux AUR package
|
||||||
|
- Alpine Linux package
|
||||||
|
- Homebrew on macOS
|
||||||
|
|
||||||
For all other Linux, you must build a JBIG2 encoder from source:
|
For all other platforms, you would need to build the JBIG2 encoder from source:
|
||||||
|
|
||||||
.. code-block:: bash
|
.. code-block:: bash
|
||||||
|
|
||||||
@@ -37,26 +40,36 @@ For all other Linux, you must build a JBIG2 encoder from source:
|
|||||||
.. _jbig2-lossy:
|
.. _jbig2-lossy:
|
||||||
|
|
||||||
Dependencies include libtoolize and libleptonica, which on Ubuntu systems
|
Dependencies include libtoolize and libleptonica, which on Ubuntu systems
|
||||||
are packaged as libtool and libleptonica-dev.
|
are packaged as libtool and libleptonica-dev. On Fedora (35) they are packaged
|
||||||
|
as libtool and leptonica-devel.
|
||||||
|
|
||||||
Lossy mode JBIG2
|
Lossy mode JBIG2
|
||||||
================
|
================
|
||||||
|
|
||||||
OCRmyPDF provides lossy mode JBIG2 as an advanced feature. Users should
|
OCRmyPDF provides lossy mode JBIG2 as an advanced and potentially dangerous
|
||||||
|
feature. Users should
|
||||||
`review the technical concerns with JBIG2 in lossy
|
`review the technical concerns with JBIG2 in lossy
|
||||||
mode <https://en.wikipedia.org/wiki/JBIG2#Disadvantages>`__
|
mode <https://en.wikipedia.org/wiki/JBIG2#Disadvantages>`__
|
||||||
and decide if this feature is acceptable for their use case.
|
and decide if this feature is acceptable for their use case. In general,
|
||||||
|
this mode should not be used for archival purposes, should not be used when
|
||||||
|
the original document is not available or will be destroyed, and should
|
||||||
|
not be used when numbers present in the document are important, because
|
||||||
|
there is a risk of 6/8 and 8/6 substitution errors.
|
||||||
|
|
||||||
JBIG2 lossy mode does achieve higher compression ratios than any other
|
JBIG2 lossy mode does achieve higher compression ratios than any other
|
||||||
monochrome (bitonal) compression technology; for large text documents
|
monochrome (bitonal) compression technology; for large text documents
|
||||||
the savings are considerable. JBIG2 lossless still gives great
|
the savings are considerable. JBIG2 lossless still gives great
|
||||||
compression ratios and is a major improvement over the older CCITT G4
|
compression ratios and is a major improvement over the older CCITT G4
|
||||||
standard. As explained above, there is some risk of substitution errors.
|
standard.
|
||||||
|
|
||||||
To turn on JBIG2 lossy mode, add the argument ``--jbig2-lossy``.
|
To turn on JBIG2 lossy mode, add the argument ``--jbig2-lossy``.
|
||||||
``--optimize {1,2,3}`` are necessary for the argument to take effect
|
``--optimize {1,2,3}`` are necessary for the argument to take effect
|
||||||
also required. Also, a JBIG2 encoder must be installed as described in
|
also required. Also, a JBIG2 encoder must be installed as described in
|
||||||
the previous section.
|
the previous section.
|
||||||
|
|
||||||
|
You can adjust the threshold for JBIG2 compression with the
|
||||||
|
``--jbig2-threshold``. The default is 0.85, meaning that if two symbols
|
||||||
|
are 85% similar, they will be compressed together.
|
||||||
|
|
||||||
*Due to an oversight, ocrmypdf v7.0 and v7.1 used lossy mode by
|
*Due to an oversight, ocrmypdf v7.0 and v7.1 used lossy mode by
|
||||||
default.*
|
default.*
|
||||||
|
|||||||
+39
-21
@@ -12,22 +12,32 @@ OCRmyPDF uses Tesseract for OCR, and relies on its language packs for all langua
|
|||||||
On most platforms, English is installed with Tesseract by default, but not always.
|
On most platforms, English is installed with Tesseract by default, but not always.
|
||||||
|
|
||||||
Tesseract supports `most
|
Tesseract supports `most
|
||||||
languages <https://github.com/tesseract-ocr/tesseract/blob/master/doc/tesseract.1.asc#languages>`__.
|
languages <https://github.com/tesseract-ocr/tesseract/blob/main/doc/tesseract.1.asc#languages>`__.
|
||||||
Languages are identified by standardized three-letter codes (called ISO 639-2 Alpha-3).
|
Languages are identified by standardized three-letter codes (called ISO 639-2 Alpha-3).
|
||||||
Tesseract's documentation also lists the three-letter code for your language.
|
Tesseract's documentation also lists the three-letter code for your language.
|
||||||
Some are anglicized, e.g. Spanish is ``spa`` rather than ``esp``, while others
|
Some are anglicized, e.g. Spanish is ``spa`` rather than ``esp``, while others
|
||||||
are not, e.g. German is ``deu`` and French is ``fra``.
|
are not, e.g. German is ``deu`` and French is ``fra``.
|
||||||
|
|
||||||
|
Language packs (strictly speaking, Tesseract "traineddata" files) generally correspond
|
||||||
|
to the language in question, but different language packs are used in certain
|
||||||
|
situations. For German, the "Fraktur" language pack can assist with reading older
|
||||||
|
materials in the Fraktur typeface family (``deu_frak``). Some communities have changed
|
||||||
|
their script from Cyrillic to Latin; the Cyrillic version of Uzbek is available
|
||||||
|
as ``uzb_cyrl`` and the Latin version is ``uzb``.
|
||||||
|
|
||||||
After you have installed a language pack, you can use it with ``ocrmypdf -l <language>``,
|
After you have installed a language pack, you can use it with ``ocrmypdf -l <language>``,
|
||||||
for example ``ocrmypdf -l spa``. For multilingual documents, you can specify
|
for example ``ocrmypdf -l spa``. For multilingual documents, you can specify
|
||||||
all languages to be expected, e.g. ``ocrmypdf -l eng+fra`` for English and French.
|
all languages to be expected, e.g. ``ocrmypdf -l eng+fra`` for English and French.
|
||||||
English is assumed by default unless other language(s) are specified.
|
English is assumed by default unless other language(s) are specified.
|
||||||
|
|
||||||
For Linux users, you can often find packages that provide language
|
For Linux users, you can often find packages that provide language
|
||||||
packs:
|
packs.
|
||||||
|
|
||||||
Debian and Ubuntu users
|
Platform install steps
|
||||||
=======================
|
======================
|
||||||
|
|
||||||
|
Debian and Ubuntu (apt)
|
||||||
|
-----------------------
|
||||||
|
|
||||||
.. code-block:: bash
|
.. code-block:: bash
|
||||||
|
|
||||||
@@ -42,8 +52,8 @@ to what languages it should search for. Multiple languages can be
|
|||||||
requested using either ``-l eng+fra`` (English and French) or
|
requested using either ``-l eng+fra`` (English and French) or
|
||||||
``-l eng -l fra``.
|
``-l eng -l fra``.
|
||||||
|
|
||||||
Fedora users
|
Fedora
|
||||||
============
|
------
|
||||||
|
|
||||||
.. code-block:: bash
|
.. code-block:: bash
|
||||||
|
|
||||||
@@ -58,8 +68,8 @@ to what languages it should search for. Multiple languages can be
|
|||||||
requested using either ``-l eng+fra`` (English and French) or
|
requested using either ``-l eng+fra`` (English and French) or
|
||||||
``-l eng -l fra``.
|
``-l eng -l fra``.
|
||||||
|
|
||||||
Gentoo users
|
Gentoo
|
||||||
============
|
------
|
||||||
|
|
||||||
On Gentoo the package ``app-text/tessdata_fast``, which ``app-text/tesseract`` depends on, handles Tesseract languages.
|
On Gentoo the package ``app-text/tessdata_fast``, which ``app-text/tesseract`` depends on, handles Tesseract languages.
|
||||||
It accepts USE flags to select what languages should be installed, these can be set in ``/etc/portage/package.use``.
|
It accepts USE flags to select what languages should be installed, these can be set in ``/etc/portage/package.use``.
|
||||||
@@ -70,13 +80,13 @@ This enables these languages for all packages (e.g. including aspell).
|
|||||||
|
|
||||||
# Display a list of all Tesseract language packs
|
# Display a list of all Tesseract language packs
|
||||||
equery uses app-text/tessdata_fast
|
equery uses app-text/tessdata_fast
|
||||||
|
|
||||||
# Add English and German language support for Tesseract only
|
# Add English and German language support for Tesseract only
|
||||||
echo 'app-text/tessdata_fast l10n_de l10n_en' >> /etc/portage/package.use
|
echo 'app-text/tessdata_fast l10n_de l10n_en' >> /etc/portage/package.use
|
||||||
|
|
||||||
# Add global English and German language support (the `l10n_` from equery has to be omited)
|
# Add global English and German language support (the `l10n_` from equery has to be omitted)
|
||||||
echo L10N="de en" >> /etc/portage/make.conf
|
echo L10N="de en" >> /etc/portage/make.conf
|
||||||
|
|
||||||
# update system to reflect changed USE flags
|
# update system to reflect changed USE flags
|
||||||
emerge --update --deep --newuse @world
|
emerge --update --deep --newuse @world
|
||||||
|
|
||||||
@@ -85,23 +95,31 @@ to what languages it should search for. Multiple languages can be
|
|||||||
requested using either ``-l eng+fra`` (English and French) or
|
requested using either ``-l eng+fra`` (English and French) or
|
||||||
``-l eng -l fra``.
|
``-l eng -l fra``.
|
||||||
|
|
||||||
macOS users
|
macOS
|
||||||
===========
|
-----
|
||||||
|
|
||||||
You can install additional language packs by
|
You can install additional language packs by
|
||||||
:ref:`installing Tesseract using Homebrew with all language packs <macos-all-languages>`.
|
:ref:`installing Tesseract using Homebrew with all language packs <macos-all-languages>`.
|
||||||
|
|
||||||
Docker users
|
Docker
|
||||||
============
|
------
|
||||||
|
|
||||||
Users of the OCRmyPDF Docker image should install language packs into a
|
Users of the OCRmyPDF Docker image should install language packs into a
|
||||||
derived Docker image as
|
derived Docker image as
|
||||||
:ref:`described in that section <docker-lang-packs>`.
|
:ref:`described in that section <docker-lang-packs>`.
|
||||||
|
|
||||||
Windows users
|
Windows
|
||||||
=============
|
-------
|
||||||
|
|
||||||
The Tesseract installer provided by Chocolatey currently includes only English language.
|
The Tesseract installer provided by Chocolatey currently includes only English language.
|
||||||
To install other languages, download the respective language pack (``.traineddata`` file)
|
To install other languages, download the respective language pack (``.traineddata`` file)
|
||||||
from https://github.com/tesseract-ocr/tessdata/ and place it in
|
from https://github.com/tesseract-ocr/tessdata/ and place it in
|
||||||
``C:\\Program Files\\Tesseract-OCR\\tessdata`` (or wherever Tesseract OCR is installed).
|
``C:\\Program Files\\Tesseract-OCR\\tessdata`` (or wherever Tesseract OCR is installed).
|
||||||
|
|
||||||
|
Custom language packs
|
||||||
|
=====================
|
||||||
|
|
||||||
|
If you have fine-tuned or trained Tesseract and generated custom trained data, you can
|
||||||
|
copy your ``customlang.traineddata`` file into your Tesseract "tessdata" folder, and
|
||||||
|
then use the ``-l customlang`` argument to tell OCRmyPDF to pass that language on to
|
||||||
|
Tesseract.
|
||||||
@@ -45,11 +45,6 @@ to indicate that your distribution modifies OCRmyPDF in some way.
|
|||||||
You can patch the ``__version__`` variable in ``src/ocrmypdf/_version.py`` if
|
You can patch the ``__version__`` variable in ``src/ocrmypdf/_version.py`` if
|
||||||
necessary.
|
necessary.
|
||||||
|
|
||||||
OCRmyPDF uses setuptools-scm-git-archive to ensure that tarballs downloaded from
|
|
||||||
GitHub contain version information. Unfortunately, these tarballs are not always
|
|
||||||
deterministic. See this
|
|
||||||
`issue <https://github.com/ocrmypdf/OCRmyPDF/issues/841#issuecomment-936562696>`_.
|
|
||||||
|
|
||||||
jbig2enc
|
jbig2enc
|
||||||
--------
|
--------
|
||||||
|
|
||||||
@@ -61,4 +56,12 @@ improve OCRmyPDF's compression.
|
|||||||
Command line completions
|
Command line completions
|
||||||
------------------------
|
------------------------
|
||||||
|
|
||||||
Please ensure that command line completions are installed.
|
Please ensure that command line completions are installed, as described in the
|
||||||
|
installation documentation.
|
||||||
|
|
||||||
|
32-bit Linux support
|
||||||
|
--------------------
|
||||||
|
|
||||||
|
If you maintain a Linux distribution that supports 32-bit x86 or ARM, OCRmyPDF
|
||||||
|
should continue to work as long as all of its dependencies continue to be
|
||||||
|
available in 32-bit form. Please note we do not test on 32-bit platforms.
|
||||||
+32
-11
@@ -13,21 +13,40 @@ tuned. Optimization occurs after OCR, and only if OCR succeeded. It does not
|
|||||||
perform other possible optimizations such as deduplicating resources,
|
perform other possible optimizations such as deduplicating resources,
|
||||||
consolidating fonts, simplifying vector drawings, or anything of that nature.
|
consolidating fonts, simplifying vector drawings, or anything of that nature.
|
||||||
|
|
||||||
Optimization ranges from ``-O0`` through ``-O3``, where ``0`` disables
|
.. list-table:: Title
|
||||||
optimization and ``3`` implements all options. ``1``, the default, performs only
|
:widths: 33 6 60
|
||||||
safe and lossless optimizations. (This is similar to GCC's optimization
|
:header-rows: 1
|
||||||
parameter.) The exact type of optimizations performed will vary over time.
|
|
||||||
|
|
||||||
PDF optimization requires third-party, optional tools for certain optimizations.
|
* - Optimization level
|
||||||
If these are not installed or cannot be found by OCRmyPDF, optimization will not
|
- Shorthand
|
||||||
be as good.
|
- Description
|
||||||
|
* - ``--optimize 0``
|
||||||
|
- ``-O0``
|
||||||
|
- Disable most optimizations.
|
||||||
|
* - ``--optimize 1`` (default)
|
||||||
|
- ``-O1``
|
||||||
|
- Safe and lossless optimizations.
|
||||||
|
* - ``--optimize 2``
|
||||||
|
- ``-O2``
|
||||||
|
- Safe and lossy optimizations.
|
||||||
|
* - ``--optimize 3``
|
||||||
|
- ``-O3``
|
||||||
|
- Aggressive lossy optimizations.
|
||||||
|
|
||||||
|
The exact type of optimizations performed will vary over time, and depend on
|
||||||
|
the availability of third-party tools.
|
||||||
|
|
||||||
|
Despite optimizations, OCRmyPDF might still increase the overall file size,
|
||||||
|
since it must embed information about the recognized text, and depending on the
|
||||||
|
settings chosen, may not be able to represent the output file as compactly as
|
||||||
|
the input file.
|
||||||
|
|
||||||
Optimizations that always occurs
|
Optimizations that always occurs
|
||||||
================================
|
================================
|
||||||
|
|
||||||
OCRmyPDF will automatically replace obsolete or inferior compression schemes
|
OCRmyPDF will automatically replace obsolete or inferior compression schemes
|
||||||
such as RLE or LZW with superior schemes such as Deflate and converting
|
such as RLE or LZW with superior schemes such as Deflate, and convert
|
||||||
monochrome images to CCITT G4. Since this is harmless it always occurs and there
|
monochrome images to CCITT G4. Since this is lossless, it always occurs and there
|
||||||
is no way to disable it. Other non-image compressed objects are compressed as
|
is no way to disable it. Other non-image compressed objects are compressed as
|
||||||
well.
|
well.
|
||||||
|
|
||||||
@@ -37,12 +56,14 @@ Fast web view
|
|||||||
OCRmyPDF automatically optimizes PDFs for "fast web view" in Adobe Acrobat's
|
OCRmyPDF automatically optimizes PDFs for "fast web view" in Adobe Acrobat's
|
||||||
parlance, or equivalently, linearizes PDFs so that the resources they reference
|
parlance, or equivalently, linearizes PDFs so that the resources they reference
|
||||||
are presented in the order a viewer needs them for sequential display. This
|
are presented in the order a viewer needs them for sequential display. This
|
||||||
reduces the latency of viewing a PDF both online and from local storage. This
|
reduces the latency of viewing a PDF both online and from local storage, in
|
||||||
actually slightly increases the file size.
|
exchange for a slight increase in file size.
|
||||||
|
|
||||||
To disable this optimization and all others, use ``ocrmypdf --optimize 0 ...``
|
To disable this optimization and all others, use ``ocrmypdf --optimize 0 ...``
|
||||||
or the shorthand ``-O0``.
|
or the shorthand ``-O0``.
|
||||||
|
|
||||||
|
Adobe Acrobat might not report the file as being "fast web view".
|
||||||
|
|
||||||
Lossless optimizations
|
Lossless optimizations
|
||||||
======================
|
======================
|
||||||
|
|
||||||
|
|||||||
+61
-102
@@ -29,13 +29,9 @@ attack vectors.
|
|||||||
In short, PDFs `may contain
|
In short, PDFs `may contain
|
||||||
viruses <https://security.stackexchange.com/questions/64052/can-a-pdf-file-contain-a-virus>`__.
|
viruses <https://security.stackexchange.com/questions/64052/can-a-pdf-file-contain-a-virus>`__.
|
||||||
|
|
||||||
This
|
If you do not trust a PDF or its source, do not open it or use OCRmyPDF
|
||||||
`article <https://theinvisiblethings.blogspot.ca/2013/02/converting-untrusted-pdfs-into-trusted.html>`__
|
on it. Consider using a Docker container or virtual machine to isolate
|
||||||
describes a high-paranoia method which allows potentially hostile PDFs
|
an untrusted PDF from your system.
|
||||||
to be viewed and rasterized safely in a disposable virtual machine. A
|
|
||||||
trusted PDF created in this manner is converted to images and loses all
|
|
||||||
information making it searchable and losing all compression. OCRmyPDF
|
|
||||||
could be used to restore searchability.
|
|
||||||
|
|
||||||
How OCRmyPDF processes PDFs
|
How OCRmyPDF processes PDFs
|
||||||
===========================
|
===========================
|
||||||
@@ -43,11 +39,11 @@ How OCRmyPDF processes PDFs
|
|||||||
OCRmyPDF must open and interpret your PDF in order to insert an OCR
|
OCRmyPDF must open and interpret your PDF in order to insert an OCR
|
||||||
layer. First, it runs all PDFs through
|
layer. First, it runs all PDFs through
|
||||||
`pikepdf <https://github.com/pikepdf/pikepdf>`__, a library based on
|
`pikepdf <https://github.com/pikepdf/pikepdf>`__, a library based on
|
||||||
`qpdf <https://github.com/qpdf/qpdf>`__, a program that repairs PDFs
|
`QPDF <https://github.com/qpdf/qpdf>`__, a program that repairs PDFs
|
||||||
with syntax errors. This is done because, in the author's experience, a
|
with syntax errors. This is done because, in the author's experience, a
|
||||||
significant number of PDFs in the wild, especially those created by
|
significant number of PDFs in the wild, especially those created by
|
||||||
scanners, are not well-formed files. qpdf makes it more likely that
|
scanners, are not well-formed files. QPDF makes it more likely that
|
||||||
OCRmyPDF will succeed, but offers no security guarantees. qpdf is also
|
OCRmyPDF will succeed, but offers no security guarantees. QPDF is also
|
||||||
used to split the PDF into single page PDFs.
|
used to split the PDF into single page PDFs.
|
||||||
|
|
||||||
Finally, OCRmyPDF rasterizes each page of the PDF using
|
Finally, OCRmyPDF rasterizes each page of the PDF using
|
||||||
@@ -58,109 +54,72 @@ into the existing PDF or it may essentially reconstruct ("re-fry") a
|
|||||||
visually identical PDF that may be quite different at the binary level.
|
visually identical PDF that may be quite different at the binary level.
|
||||||
That said, OCRmyPDF is not a tool designed for sanitizing PDFs.
|
That said, OCRmyPDF is not a tool designed for sanitizing PDFs.
|
||||||
|
|
||||||
.. _ocr-service:
|
Password protected PDFs
|
||||||
|
=======================
|
||||||
Using OCRmyPDF online or as a service
|
|
||||||
=====================================
|
|
||||||
|
|
||||||
OCRmyPDF is not designed for use as a public web service where a
|
|
||||||
malicious user could upload a chosen PDF. In particular, it is not
|
|
||||||
necessarily secure against PDF malware or PDFs that cause denial of
|
|
||||||
service. OCRmyPDF relies on Ghostscript, and therefore, if deployed
|
|
||||||
online one should be prepared to comply with Ghostscript's Affero GPL
|
|
||||||
license, and any other licenses.
|
|
||||||
|
|
||||||
Setting aside these concerns, a side effect of OCRmyPDF is that it may
|
|
||||||
incidentally sanitize PDFs containing certain types of malware. It
|
|
||||||
repairs the PDF with pikepdf/libqpdf, which could correct malformed PDF
|
|
||||||
structures that are part of an attack. When PDF/A output is selected
|
|
||||||
(the default), the input PDF is partially reconstructed by Ghostscript.
|
|
||||||
When ``--force-ocr`` is used, all pages are rasterized and reconverted
|
|
||||||
to PDF, which could remove malware in embedded images.
|
|
||||||
|
|
||||||
OCRmyPDF should be relatively safe to use in a trusted intranet, with
|
|
||||||
some considerations:
|
|
||||||
|
|
||||||
Limiting CPU usage
|
|
||||||
------------------
|
|
||||||
|
|
||||||
OCRmyPDF will attempt to use all available CPUs and storage, so
|
|
||||||
executing ``nice ocrmypdf`` or limiting the number of jobs with the
|
|
||||||
``-j`` argument may ensure the server remains available. Another option
|
|
||||||
would be to run OCRmyPDF jobs inside a Docker container, a virtual machine,
|
|
||||||
or a cloud instance, which can impose its own limits on CPU usage and be
|
|
||||||
terminated "from orbit" if it fails to complete.
|
|
||||||
|
|
||||||
Temporary storage requirements
|
|
||||||
------------------------------
|
|
||||||
|
|
||||||
OCRmyPDF will use a large amount of temporary storage for its work,
|
|
||||||
proportional to the total number of pixels needed to rasterize the PDF.
|
|
||||||
The raster image of a 8.5×11" color page at 300 DPI takes 25 MB
|
|
||||||
uncompressed; OCRmyPDF saves its intermediates as PNG, but that still
|
|
||||||
means it requires about 9 MB per intermediate based on average
|
|
||||||
compression ratios. Multiple intermediates per page are also required,
|
|
||||||
depending on the command line given. A rule of thumb would be to allow
|
|
||||||
100 MB of temporary storage per page in a file – meaning that a small
|
|
||||||
cloud servers or small VM partitions should be provisioned with plenty
|
|
||||||
of extra space, if say, a 500 page file might be sent.
|
|
||||||
|
|
||||||
To check temporary storage usage on actual files, run
|
|
||||||
``ocrmypdf -k ...`` which will preserve and print the path to temporary
|
|
||||||
storage when the job is done.
|
|
||||||
|
|
||||||
To change where temporary files are stored, change the ``TMPDIR``
|
|
||||||
environment variable for ocrmypdf's environment. (Python's
|
|
||||||
``tempfile.gettempdir()`` returns the root directory in which temporary
|
|
||||||
files will be stored.) For example, one could redirect ``TMPDIR`` to a
|
|
||||||
large RAM disk to avoid wear on HDD/SSD and potentially improve
|
|
||||||
performance. On Amazon Web Services, ``TMPDIR`` can be set to `empheral
|
|
||||||
storage <https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/InstanceStorage.html>`__.
|
|
||||||
|
|
||||||
Timeouts
|
|
||||||
--------
|
|
||||||
|
|
||||||
To prevent excessively long OCR jobs consider setting
|
|
||||||
``--tesseract-timeout`` and/or ``--skip-big`` arguments. ``--skip-big``
|
|
||||||
is particularly helpful if your PDFs include documents such as reports
|
|
||||||
on standard page sizes with large images attached - often large images
|
|
||||||
are not worth OCR'ing anyway.
|
|
||||||
|
|
||||||
Commercial alternatives
|
|
||||||
-----------------------
|
|
||||||
|
|
||||||
The author also provides professional services that include OCR and
|
|
||||||
building databases around PDFs, and is happy to provide consultation.
|
|
||||||
|
|
||||||
Abbyy Cloud OCR is viable commercial alternative with a web services
|
|
||||||
API. Amazon Textract, Google Cloud Vision, and Microsoft Azure
|
|
||||||
Computer Vision provide advanced OCR but have less PDF rendering capability.
|
|
||||||
|
|
||||||
Password protection, digital signatures and certification
|
|
||||||
=========================================================
|
|
||||||
|
|
||||||
Password protected PDFs usually have two passwords, and owner and user
|
Password protected PDFs usually have two passwords, and owner and user
|
||||||
password. When the user password is set to empty, PDF readers will open
|
password. When the user password is set to empty, PDF readers will open
|
||||||
the file automatically and marked it as "(SECURED)". While not as
|
the file automatically and mark it as "(SECURED)". Password security can
|
||||||
reliable as a digital signature, this indicates that whoever set the
|
also request certain restrictions on the PDF, but anyone can remove these
|
||||||
password approved of the file at that time. When the user password is
|
restrictions if they have either the owner *or* user password. Passwords
|
||||||
set, the document cannot be viewed without the password.
|
mainly present a barrier for casual users.
|
||||||
|
|
||||||
Either way, OCRmyPDF does not remove passwords from PDFs and exits with
|
OCRmyPDF cannot remove passwords from PDFs. If you want to remove a
|
||||||
an error on encountering them.
|
password from a PDF, you must use other software, such as ``qpdf``.
|
||||||
|
|
||||||
``qpdf`` can remove passwords. If the owner and user password are set, a
|
If the owner and user password are set, a
|
||||||
password is required for ``qpdf``. If only the owner password is set, then the
|
password is required for ``qpdf``. If only the owner password is set, then the
|
||||||
password can be stripped, even if one does not have the owner password.
|
password can be stripped, even if one does not have the owner password. To
|
||||||
|
remove the password from a using QPDF, use:
|
||||||
|
|
||||||
After OCR is applied, password protection is not permitted on PDF/A
|
.. code-block:: bash
|
||||||
documents but the file can be converted to regular PDF.
|
|
||||||
|
qpdf --decrypt --password='abc123' input.pdf no_password.pdf
|
||||||
|
|
||||||
|
Then you can run OCRmyPDF on the file.
|
||||||
|
|
||||||
|
In its default mode, OCRmyPDF generates PDF/A. Passwords may not be set on PDF/A
|
||||||
|
documents. If you want to set a password on the output PDF, you must
|
||||||
|
specify ``--output-type pdf``.
|
||||||
|
|
||||||
|
Signature images
|
||||||
|
================
|
||||||
|
|
||||||
Many programs exist which are capable of inserting an image of someone's
|
Many programs exist which are capable of inserting an image of someone's
|
||||||
signature. On its own, this offers no security guarantees. It is trivial
|
signature. On its own, this offers no security guarantees. It is trivial
|
||||||
to remove the signature image and apply it to other files. This practice
|
to remove the signature image and apply it to other files. This practice
|
||||||
offers no real security.
|
offers no real security.
|
||||||
|
|
||||||
|
Digital signatures
|
||||||
|
==================
|
||||||
|
|
||||||
Important documents can be digitally signed and certified to attest to
|
Important documents can be digitally signed and certified to attest to
|
||||||
their authorship. OCRmyPDF cannot do this. Open source tools such as
|
their authorship, approval or execution of a legal agreement. OCRmyPDF
|
||||||
pdfbox (Java) have this capability as does Adobe Acrobat.
|
will detect signed PDFs and will not modify them, unless the
|
||||||
|
``--invalidate-digital-signatures`` option is used, which will
|
||||||
|
invalidate any signatures. (The signature may still be present in the PDF
|
||||||
|
if opened, but PDF readers will not validate it.)
|
||||||
|
|
||||||
|
A digital signature adds a cryptographic hash of the document to the
|
||||||
|
document, so tamper protection is provided. That also precludes OCRmyPDF
|
||||||
|
from modifying the document and preserving the signature.
|
||||||
|
|
||||||
|
Digital signatures are not the same as a signature image. A digital
|
||||||
|
signature is a cryptographic hash of the document that is encrypted with
|
||||||
|
the author's private key. The signature is decrypted with the author's
|
||||||
|
public key. The public key is usually distributed by a certificate
|
||||||
|
authority. The signature is then verified by the PDF reader. If the
|
||||||
|
document is modified, the signature will be invalidated.
|
||||||
|
|
||||||
|
Certificate-encrypted PDFs
|
||||||
|
==========================
|
||||||
|
|
||||||
|
PDFs can be encrypted with a certificate. This is a more secure form of
|
||||||
|
encryption than a password. The certificate is usually issued by a
|
||||||
|
certificate authority. A certificate is used to encrypt the document using
|
||||||
|
the public key for the benefit of a specific recipient who possesses
|
||||||
|
the private key.
|
||||||
|
|
||||||
|
OCRmyPDF cannot open certificate-encrypted PDFs. If you have the
|
||||||
|
certificate, you can use other PDF software, such as Acrobat, to
|
||||||
|
decrypt the PDF.
|
||||||
@@ -17,7 +17,7 @@ If running OCRmyPDF quickly is your main goal, you can use settings such as:
|
|||||||
|
|
||||||
* ``--optimize 0`` to disable file size optimization
|
* ``--optimize 0`` to disable file size optimization
|
||||||
* ``--output-type pdf`` to disable PDF/A generation
|
* ``--output-type pdf`` to disable PDF/A generation
|
||||||
* ``--fast-web-view 0`` to disable fast web view optimization
|
* ``--fast-web-view 999999`` to disable fast web view optimization
|
||||||
* ``--skip-big`` to skip large images, if some pages have large images
|
* ``--skip-big`` to skip large images, if some pages have large images
|
||||||
|
|
||||||
You can also avoid:
|
You can also avoid:
|
||||||
|
|||||||
+11
-10
@@ -76,20 +76,16 @@ Setuptools plugins
|
|||||||
You can also create a plugin that OCRmyPDF will always automatically load if both are
|
You can also create a plugin that OCRmyPDF will always automatically load if both are
|
||||||
installed in the same virtual environment, using a setuptools entrypoint.
|
installed in the same virtual environment, using a setuptools entrypoint.
|
||||||
|
|
||||||
Your package's ``setup.py`` would need to contain the following, for a plugin
|
Your package's ``pyproject.toml`` would need to contain the following, for a plugin
|
||||||
named ``ocrmypdf-exampleplugin``:
|
named ``ocrmypdf-exampleplugin``:
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: toml
|
||||||
|
|
||||||
# sample ./setup.py file
|
[project]
|
||||||
from setuptools import setup
|
name = "ocrmypdf-exampleplugin"
|
||||||
|
|
||||||
setup(
|
[project.entry-points."ocrmypdf"]
|
||||||
name="ocrmypdf-exampleplugin",
|
exampleplugin = "exampleplugin.pluginmodule"
|
||||||
packages=["exampleplugin"],
|
|
||||||
# the following makes a plugin available to pytest
|
|
||||||
entry_points={"ocrmypdf": ["exampleplugin = exampleplugin.pluginmodule"]},
|
|
||||||
)
|
|
||||||
|
|
||||||
.. code-block:: ini
|
.. code-block:: ini
|
||||||
|
|
||||||
@@ -181,8 +177,13 @@ Custom command line arguments
|
|||||||
Execution and progress reporting
|
Execution and progress reporting
|
||||||
--------------------------------
|
--------------------------------
|
||||||
|
|
||||||
|
.. autoclass:: ocrmypdf.pluginspec.ProgressBar
|
||||||
|
:members:
|
||||||
|
:special-members: __init__, __enter__, __exit__
|
||||||
|
|
||||||
.. autoclass:: ocrmypdf.pluginspec.Executor
|
.. autoclass:: ocrmypdf.pluginspec.Executor
|
||||||
:members:
|
:members:
|
||||||
|
:special-members: __call__
|
||||||
|
|
||||||
.. autofunction:: ocrmypdf.pluginspec.get_logging_console
|
.. autofunction:: ocrmypdf.pluginspec.get_logging_console
|
||||||
|
|
||||||
|
|||||||
+288
-1
@@ -20,6 +20,8 @@ The most recent release of OCRmyPDF is |OCRmyPDF PyPI|. Any newer versions
|
|||||||
referred to in these notes may exist the main branch but have not been
|
referred to in these notes may exist the main branch but have not been
|
||||||
tagged yet.
|
tagged yet.
|
||||||
|
|
||||||
|
OCRmyPDF typically supports the three most recent Python versions.
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
|
|
||||||
Attention maintainers: these release notes may be updated with information
|
Attention maintainers: these release notes may be updated with information
|
||||||
@@ -28,6 +30,291 @@ tagged yet.
|
|||||||
|
|
||||||
.. |OCRmyPDF PyPI| image:: https://img.shields.io/pypi/v/ocrmypdf.svg
|
.. |OCRmyPDF PyPI| image:: https://img.shields.io/pypi/v/ocrmypdf.svg
|
||||||
|
|
||||||
|
|
||||||
|
v16.0.3
|
||||||
|
=======
|
||||||
|
|
||||||
|
- Changed minimum required Ghostscript to 9.54, to support users of RHEL 9 and its
|
||||||
|
derivatives, since that is the latest version available there.
|
||||||
|
- Removed warning message about CVE-2023-43115, on the assumption that most
|
||||||
|
distributions have backported the patch by now.
|
||||||
|
|
||||||
|
v16.0.2
|
||||||
|
=======
|
||||||
|
|
||||||
|
- Temporarily changed PDF text renderer back to sandwich by default to address
|
||||||
|
regressions in macOS Preview.
|
||||||
|
|
||||||
|
v16.0.1
|
||||||
|
=======
|
||||||
|
|
||||||
|
- Fixed text rendering issue with new hOCR text renderer - extraneous byte order
|
||||||
|
marks.
|
||||||
|
- Tightened dependencies.
|
||||||
|
|
||||||
|
v16.0.0
|
||||||
|
=======
|
||||||
|
|
||||||
|
- Added OCR text renderer, combined the best ideas of Tesseract's PDF
|
||||||
|
generator and the older hOCR transformer renderer. The result is a hopefully
|
||||||
|
permanent fix for wordssmushedtogetherwithoutspaces issues in extracted text,
|
||||||
|
better registration/position of text on skewed baselines :issue:`1009`,
|
||||||
|
fixes to character output when the German Fraktur script is used :issue:`1191`,
|
||||||
|
proper rendering of right to left languages (Arabic, Hebrew, Persian) :issue:`1157`.
|
||||||
|
Asian languages may still have excessive word breaks compared to expectations.
|
||||||
|
The new renderer is the default; the old sandwich renderer is still available
|
||||||
|
using ``--pdf-renderer sandwich``; the old hOCR renderer is no more.
|
||||||
|
- The ``ocrmypdf.hocrtransform`` API has changed substantially.
|
||||||
|
- Support for Python 3.9 has been dropped. Python 3.10+ is now required.
|
||||||
|
- pikepdf >= 8.8.0 is now required.
|
||||||
|
|
||||||
|
|
||||||
|
v15.4.4
|
||||||
|
=======
|
||||||
|
|
||||||
|
- Fixed documentation for installing Ghostscript on Windows. :issue:`1198`
|
||||||
|
- Added warning message about security issue in older versions of Ghostscript.
|
||||||
|
|
||||||
|
v15.4.3
|
||||||
|
=======
|
||||||
|
|
||||||
|
- Fixed deprecation warning in pikepdf older than 8.7.1; pikepdf >= 8.7.1 is
|
||||||
|
now required.
|
||||||
|
|
||||||
|
v15.4.2
|
||||||
|
=======
|
||||||
|
|
||||||
|
- We now raise an exception on a certain class of PDFs that likely need an
|
||||||
|
explicit color conversion strategy selected to display correctly
|
||||||
|
for PDF/A conversion.
|
||||||
|
- Fixed an error that occurred while trying to write a log message after the
|
||||||
|
debug log handler was removed.
|
||||||
|
|
||||||
|
v15.4.1
|
||||||
|
=======
|
||||||
|
|
||||||
|
- Fixed misc/watcher.py regressions: accept ``--ocr-json-settings`` as either
|
||||||
|
filename or JSON string, as previously; and argument count mismatch.
|
||||||
|
:issue:`1183,1185`
|
||||||
|
- We no longer attempt to set /ProcSet in the PDF output, since this is an
|
||||||
|
obsolete PDF feature.
|
||||||
|
- Documentation improvements.
|
||||||
|
|
||||||
|
v15.4.0
|
||||||
|
=======
|
||||||
|
|
||||||
|
- Added new experimental APIs to support offline editing of the final text.
|
||||||
|
Specifically, one can now generate hOCR files with OCRmyPDF, edit them with
|
||||||
|
some other tool, and then finalize the PDF. They are experimental and
|
||||||
|
subject to change, including details of how the working folder is used.
|
||||||
|
There is no command line interface.
|
||||||
|
- Code reorganization: executors, progress bars, initialization and setup.
|
||||||
|
- Fixed test coverage in cases where the coverage tool did not properly trace
|
||||||
|
into threads or subprocesses. This code was still being tested but appeared
|
||||||
|
as not covered.
|
||||||
|
- In the test suite, reduced use of subprocesses and other techniques that
|
||||||
|
interfere with coverage measurement.
|
||||||
|
- Improved error check for when we appear to be running inside a snap container
|
||||||
|
and files are not available.
|
||||||
|
- Plugin specification now properly defines progress bars as a protocol rather
|
||||||
|
than defining them as "tqdm-like".
|
||||||
|
- We now default to using "forkserver" process creation on POSIX platforms
|
||||||
|
rather than fork, since this is method is more robust and avoids some
|
||||||
|
issues when threads are present.
|
||||||
|
- Fixed an instance where the user's request to ``--no-use-threads`` was ignored.
|
||||||
|
- If a PDF does not have language metadata on its top level object, we add
|
||||||
|
the OCR language.
|
||||||
|
- Replace some cryptic test error messages with more helpful ones.
|
||||||
|
- Debug messages for how OCRmyPDF picks the colorspace for a page are now
|
||||||
|
more descriptive.
|
||||||
|
|
||||||
|
v15.3.1
|
||||||
|
=======
|
||||||
|
|
||||||
|
- Fixed an issue with logging settings for misc/watcher.py introduced in the
|
||||||
|
previous release. :issue:`1180`
|
||||||
|
- We now attempt to preserve the input's extended attributes when creating
|
||||||
|
the output file.
|
||||||
|
- For some reason, the macOS build now needs OpenSSL explicitly installed.
|
||||||
|
- Updated documentation on Docker performance concerns.
|
||||||
|
|
||||||
|
v15.3.0
|
||||||
|
=======
|
||||||
|
|
||||||
|
- Update misc/watcher.py to improve command line interface using Typer, and
|
||||||
|
support ``.env`` specification of environment variables. Improved error
|
||||||
|
messages. Thanks to @mflagg2814 for the PR that prompted this improvement.
|
||||||
|
- Improved error message when a file cannot be read because we are running in
|
||||||
|
a snap container.
|
||||||
|
|
||||||
|
v15.2.0
|
||||||
|
=======
|
||||||
|
|
||||||
|
- Added a Docker image based on Alpine Linux. This image is smaller than the
|
||||||
|
Ubuntu-based image and may be useful in some situations. Currently hosted at
|
||||||
|
jbarlow83/ocrmypdf-alpine. Currently not available in ARM flavor.
|
||||||
|
- The Ubuntu Docker is now aliased to jbarlow83/ocrmypdf-ubuntu.
|
||||||
|
- Updated Docker documentation.
|
||||||
|
|
||||||
|
v15.1.0
|
||||||
|
=======
|
||||||
|
|
||||||
|
- We now require Pillow 10.0.1, due a serious security vulnerability in all earlier
|
||||||
|
versions of that dependency. The vulnerability concerns WebP images and could
|
||||||
|
be triggered in OCRmyPDF when creating a PDF from a malicious WebP image.
|
||||||
|
- Added some keyword arguments to ``ocrmypdf.ocr`` that were previously accepted
|
||||||
|
but undocumented.
|
||||||
|
- Documentation updates and typing improvements.
|
||||||
|
|
||||||
|
v15.0.2
|
||||||
|
=======
|
||||||
|
|
||||||
|
- Added Python 3.12 to test matrix.
|
||||||
|
- Updated documentation for notes on Python 3.12, 32-bit support and some new
|
||||||
|
features in v15.
|
||||||
|
|
||||||
|
v15.0.1
|
||||||
|
=======
|
||||||
|
|
||||||
|
- Wheels Python tag changed to py39.
|
||||||
|
- Marked as a expected fail a test that fails on recent Ghostscript versions.
|
||||||
|
- Clarified documentation and release notes around the extent of 32-bit support.
|
||||||
|
- Updated installation documentation to changes in v15.
|
||||||
|
|
||||||
|
v15.0.0
|
||||||
|
=======
|
||||||
|
|
||||||
|
- Dropped support for Python 3.8.
|
||||||
|
- Dropped support some older dependencies, specifically ``coloredlogs`` and
|
||||||
|
``tqdm`` in favor of rich - see ``pyproject.toml`` for details.
|
||||||
|
Generally speaking, Ubuntu 22.04 is our new baseline system.
|
||||||
|
- Tightened version requirements for some dependencies.
|
||||||
|
- Dropped support for 32-bit Linux wheels. We strongly recommend a 64-bit operating
|
||||||
|
system, and 64-bit versions of Python, Tesseract and Ghostscript to use OCRmyPDF.
|
||||||
|
Many of our dependencies are dropping 32-bit builds (e.g. Pillow), and we are
|
||||||
|
following suit. (Maintainers may still build 32-bit versions from source.)
|
||||||
|
- Changed to trusted release for PyPI publishing.
|
||||||
|
- pikepdf memory mapping is enabled again for improved performance, now that an
|
||||||
|
issue with feature in pikepdf is fixed.
|
||||||
|
- ``ocrmypdf.helpers.calculate_downsample`` previously had two variants, one
|
||||||
|
that took a ``PIL.Image`` and one that took a ``tuple[int, int]``. The latter
|
||||||
|
was removed.
|
||||||
|
- The snap version of ocrmypdf is now based on Ubuntu core22.
|
||||||
|
- We now account for situations where a small portion of an image on a page is drawn
|
||||||
|
at high DPI (resolution). Previously, the entire page would be rasterized at the
|
||||||
|
highest resolution of any feature, which caused performance problems. Now,
|
||||||
|
the page is rasterized
|
||||||
|
at a resolution based on the average DPI of the page, weighted by the area that
|
||||||
|
each feature occupies. Typically, small areas of high resolution in PDFs are
|
||||||
|
errors or quirks from the repeated use of assets and high resolution is not
|
||||||
|
beneficial. :issue:`1010,1104,1004,1079,1010`
|
||||||
|
- Ghostscript color conversion strategy is now configurable using
|
||||||
|
``--color-conversion-strategy``. :issue:`1143`
|
||||||
|
- JBIG2 threshold for optimization is now configurable using
|
||||||
|
``--jbig2-threshold``. :issue:`1133`
|
||||||
|
|
||||||
|
v14.4.0
|
||||||
|
=======
|
||||||
|
|
||||||
|
- Digitally signed PDFs are now detected. If the PDF is signed, OCRmyPDF will
|
||||||
|
refuse to modify it. Previously, only encrypted PDFs were detected, not
|
||||||
|
those that were signed but not encrypted. :issue:`1040`
|
||||||
|
- In addition, ``--invalidate-digital-signatures`` can be used to override the
|
||||||
|
above behavior and modify the PDF anyway. :issue:`1040`
|
||||||
|
- tqdm progress bars replaced with "rich" progress bars. The rich library is
|
||||||
|
a new dependency. Certain APIs that used tqdm are now deprecated and will
|
||||||
|
be removed in the next major release.
|
||||||
|
- Improved integration with GitHub Releases. Thanks to @stumpylog.
|
||||||
|
|
||||||
|
v14.3.0
|
||||||
|
=======
|
||||||
|
|
||||||
|
- Renamed master branch to main.
|
||||||
|
- Improve PDF rasterization accuracy by using the ``-dPDFSTOPONERROR`` option
|
||||||
|
to Ghostscript. Use ``--continue-on-soft-render-error`` if you want to render
|
||||||
|
the PDF anyway. The plugin specification was adjusted to support this feature;
|
||||||
|
plugin authors may want to adapt PDF rasterizing and rendering
|
||||||
|
plugins. :issue:`1083`
|
||||||
|
- The calculated deskew angle is now recorded in the logged output. :issue:`1101`
|
||||||
|
- Metadata can now be unset by setting a metadata type such as ``--title`` to an
|
||||||
|
empty string. :issue:`1117,1059`
|
||||||
|
- Fixed random order of languages due to use of a set. This may have caused output
|
||||||
|
to vary when multiple languages were set for OCR. :issue:`1113`
|
||||||
|
- Clarified the optimization ratio reported in the log output.
|
||||||
|
- Documentation improvements.
|
||||||
|
|
||||||
|
v14.2.1
|
||||||
|
=======
|
||||||
|
|
||||||
|
- Fixed :issue:`977`, where images inside Form XObjects were always excluded
|
||||||
|
from image optimization.
|
||||||
|
|
||||||
|
v14.2.0
|
||||||
|
=======
|
||||||
|
|
||||||
|
- Added ``--tesseract-downsample-above`` to downsample larger images even when
|
||||||
|
they do not exceed Tesseract's internal limits. This can be used to speed
|
||||||
|
up OCR, possibly sacrificing accuracy.
|
||||||
|
- Fixed resampling AttributeError on older Pillow. :issue:`1096`
|
||||||
|
- Removed an error about using Ghostscript on PDFs with that have the /UserUnit
|
||||||
|
feature in use. Previously, Ghostscript would fail to process these PDFs,
|
||||||
|
but in all supported versions it is now supported, so the error is no longer
|
||||||
|
needed.
|
||||||
|
- Improved documentation around installing other language packs for Tesseract.
|
||||||
|
|
||||||
|
v14.1.0
|
||||||
|
=======
|
||||||
|
|
||||||
|
- Added ``--tesseract-non-ocr-timeout``. This allows using Tesseract's deskew
|
||||||
|
and other non-OCR features while disabling OCR using ``--tesseract-timeout 0``.
|
||||||
|
- Added ``--tesseract-downsample-large-images``. This downsamples larges images
|
||||||
|
that exceed the maximum image size Tesseract can handle. Large images may still
|
||||||
|
take a long time to process, but this allows them to be processed if that
|
||||||
|
is desired.
|
||||||
|
- Fixed :issue:`1082`, an issue with snap packaged building.
|
||||||
|
- Change linter to ruff, fix lint errors, update documentation.
|
||||||
|
|
||||||
|
v14.0.4
|
||||||
|
=======
|
||||||
|
|
||||||
|
- Fixed :issue:`1066, 1075`, an exception when processing certain malformed PDFs.
|
||||||
|
|
||||||
|
v14.0.3
|
||||||
|
=======
|
||||||
|
|
||||||
|
- Fixed :issue:`1068`, avoid deleting /dev/null when running as root.
|
||||||
|
- Other documentation fixes.
|
||||||
|
|
||||||
|
v14.0.2
|
||||||
|
=======
|
||||||
|
|
||||||
|
- Fixed :issue:`1052`, an exception on attempting to process certain nonconforming PDFs.
|
||||||
|
- Explicitly documented that Windows 32-bit is no longer supported.
|
||||||
|
- Fixed source installation instructions.
|
||||||
|
- Other documentation fixes.
|
||||||
|
|
||||||
|
v14.0.1
|
||||||
|
=======
|
||||||
|
|
||||||
|
- Fixed some version checks done with smart version comparison.
|
||||||
|
- Added missing jbig2dec to Docker image.
|
||||||
|
|
||||||
|
v14.0.0
|
||||||
|
=======
|
||||||
|
|
||||||
|
- Dropped support for Python 3.7.
|
||||||
|
- Dropped support generally speaking, all dependencies older than what Ubuntu 20.04
|
||||||
|
provides.
|
||||||
|
- Ghostscript 9.50 or newer is now required. Shims to support old versions were
|
||||||
|
removed.
|
||||||
|
- Tesseract 4.1.1 or newer is now required. Shims to support old versions were
|
||||||
|
removed.
|
||||||
|
- Docker image now uses Tesseract 5.
|
||||||
|
- Dropped setup.cfg configuration for pyproject.toml.
|
||||||
|
- Removed deprecation exception PdfMergeFailedError.
|
||||||
|
- A few more public domain test files were removed or replaced. We are aiming for
|
||||||
|
100% compliance with SPDX and generally towards simplifying copyright.
|
||||||
|
|
||||||
v13.7.0
|
v13.7.0
|
||||||
=======
|
=======
|
||||||
|
|
||||||
@@ -681,7 +968,7 @@ v10.3.2
|
|||||||
v10.3.1
|
v10.3.1
|
||||||
=======
|
=======
|
||||||
|
|
||||||
- Fixed a number of test suite failures with pdfminer.six older than veresion 20200402.
|
- Fixed a number of test suite failures with pdfminer.six older than version 20200402.
|
||||||
- Enabled support for pdfminer.six 20200720.
|
- Enabled support for pdfminer.six 20200720.
|
||||||
|
|
||||||
v10.3.0
|
v10.3.0
|
||||||
|
|||||||
+9
-2
@@ -2,11 +2,18 @@
|
|||||||
# SPDX-FileCopyrightText: 2016 findingorder <https://github.com/findingorder>
|
# SPDX-FileCopyrightText: 2016 findingorder <https://github.com/findingorder>
|
||||||
# SPDX-License-Identifier: MIT
|
# SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
"""Example of using ocrmypdf as a library in a script.
|
||||||
|
|
||||||
|
This script will recursively search a directory for PDF files and run OCR on
|
||||||
|
them. It will log the results. It runs OCR on every file, even if it already
|
||||||
|
has text. OCRmyPDF will detect files that already have text.
|
||||||
|
|
||||||
|
You should edit this script to meet your needs.
|
||||||
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
# This script must be edited to meet your needs.
|
|
||||||
import logging
|
import logging
|
||||||
import os
|
|
||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
|||||||
@@ -6,52 +6,56 @@ set -o errexit
|
|||||||
|
|
||||||
__ocrmypdf_arguments()
|
__ocrmypdf_arguments()
|
||||||
{
|
{
|
||||||
local arguments="--help (show help message)
|
local arguments="\
|
||||||
--language (language(s) of the file to be OCRed)
|
--help (show help message)
|
||||||
--image-dpi (assume this DPI if input image DPI is unknown)
|
--language (language(s) of the file to be OCRed)
|
||||||
--output-type (select PDF output options)
|
--image-dpi (assume this DPI if input image DPI is unknown)
|
||||||
--sidecar (write OCR to text file)
|
--output-type (select PDF output options)
|
||||||
--version (print program version and exit)
|
--sidecar (write OCR to text file)
|
||||||
--jobs (how many worker processes to use)
|
--version (print program version and exit)
|
||||||
--quiet (suppress INFO messages)
|
--jobs (how many worker processes to use)
|
||||||
--verbose (set verbosity level)
|
--quiet (suppress INFO messages)
|
||||||
--title (set metadata)
|
--verbose (set verbosity level)
|
||||||
--author (set metadata)
|
--title (set metadata)
|
||||||
--subject (set metadata)
|
--author (set metadata)
|
||||||
--keywords (set metadata)
|
--subject (set metadata)
|
||||||
--rotate-pages (rotate pages to correct orientation)
|
--keywords (set metadata)
|
||||||
--remove-background (attempt to remove background from pages)
|
--rotate-pages (rotate pages to correct orientation)
|
||||||
--deskew (fix small horizontal alignment skew)
|
--remove-background (attempt to remove background from pages)
|
||||||
--clean (clean document images before OCR)
|
--deskew (fix small horizontal alignment skew)
|
||||||
--clean-final (clean document images and keep result)
|
--clean (clean document images before OCR)
|
||||||
--unpaper-args (a quoted string of arguments to pass to unpaper)
|
--clean-final (clean document images and keep result)
|
||||||
--oversample (oversample images to this DPI)
|
--unpaper-args (a quoted string of arguments to pass to unpaper)
|
||||||
--remove-vectors (don\'t send vector objects to OCR)
|
--oversample (oversample images to this DPI)
|
||||||
--threshold (threshold images before OCR)
|
--remove-vectors (don\'t send vector objects to OCR)
|
||||||
--force-ocr (OCR documents that already have printable text)
|
--threshold (threshold images before OCR)
|
||||||
--skip-text (skip OCR on any pages that already contain text)
|
--force-ocr (OCR documents that already have printable text)
|
||||||
--redo-ocr (redo OCR on any pages that seem to have OCR already)
|
--skip-text (skip OCR on any pages that already contain text)
|
||||||
--skip-big (skip OCR on pages larger than this many MPixels)
|
--redo-ocr (redo OCR on any pages that seem to have OCR already)
|
||||||
--optimize (select optimization level)
|
--invalidate-digital-signatures (remove digital signatures from PDF)
|
||||||
--jpeg-quality (JPEG quality [0..100])
|
--skip-big (skip OCR on pages larger than this many MPixels)
|
||||||
--png-quality (PNG quality [0..100])
|
--optimize (select optimization level)
|
||||||
--jbig2-lossy (enable lossy JBIG2 (see docs))
|
--jpeg-quality (JPEG quality [0..100])
|
||||||
--pages (apply OCR to only the specified pages)
|
--png-quality (PNG quality [0..100])
|
||||||
--max-image-mpixels (image decompression bomb threshold)
|
--jbig2-lossy (enable lossy JBIG2 (see docs))
|
||||||
--pdf-renderer (select PDF renderer options)
|
--jbig2-threshold (set JBIG2 threshold (see docs))
|
||||||
--rotate-pages-threshold (page rotation confidence)
|
--pages (apply OCR to only the specified pages)
|
||||||
--pdfa-image-compression (set PDF/A image compression options)
|
--max-image-mpixels (image decompression bomb threshold)
|
||||||
--fast-web-view (if file size if above this amount in MB linearize PDF)
|
--pdf-renderer (select PDF renderer options)
|
||||||
--plugin (name of plugin to import)
|
--rotate-pages-threshold (page rotation confidence)
|
||||||
--keep-temporary-files (keep temporary files (debug)
|
--pdfa-image-compression (set PDF/A image compression options)
|
||||||
--tesseract-config (set custom tesseract config file)
|
--fast-web-view (if file size if above this amount in MB linearize PDF)
|
||||||
--tesseract-pagesegmode (set tesseract --psm)
|
--plugin (name of plugin to import)
|
||||||
--tesseract-oem (set tesseract --oem)
|
--keep-temporary-files (keep temporary files (debug)
|
||||||
--tesseract-thresholding (set tesseract image thresholding)
|
--tesseract-config (set custom tesseract config file)
|
||||||
--tesseract-timeout (maximum number of seconds to wait for OCR)
|
--tesseract-pagesegmode (set tesseract --psm)
|
||||||
--user-words (specify location of user words file)
|
--tesseract-oem (set tesseract --oem)
|
||||||
--user-patterns (specify location of user patterns file)
|
--tesseract-thresholding (set tesseract image thresholding)
|
||||||
--no-progress-bar (disable the progress bar)
|
--tesseract-timeout (maximum number of seconds to wait for OCR)
|
||||||
|
--user-words (specify location of user words file)
|
||||||
|
--user-patterns (specify location of user patterns file)
|
||||||
|
--no-progress-bar (disable the progress bar)
|
||||||
|
--color-conversion-strategy (select color conversion strategy)
|
||||||
"
|
"
|
||||||
|
|
||||||
COMPREPLY=( $( compgen -W "$arguments" -- "$cur") )
|
COMPREPLY=( $( compgen -W "$arguments" -- "$cur") )
|
||||||
@@ -191,6 +195,20 @@ sauvola (use Sauvola thresholding)"
|
|||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
|
__ocrmypdf_color-conversion-strategy()
|
||||||
|
{
|
||||||
|
local choices="LeaveColorUnchanged (default)
|
||||||
|
CMYK (convert to CMYK)
|
||||||
|
Gray (convert to grayscale)
|
||||||
|
RGB (convert to RGB)
|
||||||
|
UseDeviceIndependentColor (convert with device independent color)"
|
||||||
|
|
||||||
|
COMPREPLY=( $( compgen -W "$choices" -- "$cur") )
|
||||||
|
# Remove description if only one completion exists
|
||||||
|
if [[ ${#COMPREPLY[*]} -eq 1 ]]; then
|
||||||
|
COMPREPLY=( ${COMPREPLY[0]%% *} )
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
__ocrmypdf_check_previous()
|
__ocrmypdf_check_previous()
|
||||||
{
|
{
|
||||||
@@ -250,6 +268,10 @@ __ocrmypdf_check_previous()
|
|||||||
_filedir
|
_filedir
|
||||||
return 0
|
return 0
|
||||||
;;
|
;;
|
||||||
|
--color-conversion-strategy)
|
||||||
|
__ocrmypdf_color-conversion-strategy
|
||||||
|
return 0
|
||||||
|
;;
|
||||||
esac
|
esac
|
||||||
|
|
||||||
return 1
|
return 1
|
||||||
|
|||||||
@@ -14,8 +14,9 @@ complete -c ocrmypdf -s i -l clean-final -d "clean document images and keep resu
|
|||||||
complete -c ocrmypdf -l remove-vectors -d "don't send vector objects to OCR"
|
complete -c ocrmypdf -l remove-vectors -d "don't send vector objects to OCR"
|
||||||
|
|
||||||
complete -c ocrmypdf -s f -l force-ocr -d "OCR documents that already have printable text"
|
complete -c ocrmypdf -s f -l force-ocr -d "OCR documents that already have printable text"
|
||||||
complete -c ocrmypdf -s s -l skip-ocr -d "skip OCR on pages that text, otherwise try OCR"
|
complete -c ocrmypdf -s s -l skip-text -d "skip OCR on any pages that already contain text"
|
||||||
complete -c ocrmypdf -l redo-ocr -d "redo OCR on any pages that seem to have OCR already"
|
complete -c ocrmypdf -l redo-ocr -d "redo OCR on any pages that seem to have OCR already"
|
||||||
|
complete -c ocrmypdf -l invalidate-digital-signatures -d "invalidate digital signatures and allow OCR to proceed"
|
||||||
|
|
||||||
complete -c ocrmypdf -s k -l keep-temporary-files -d "keep temporary files (debug)"
|
complete -c ocrmypdf -s k -l keep-temporary-files -d "keep temporary files (debug)"
|
||||||
|
|
||||||
@@ -83,6 +84,7 @@ complete -c ocrmypdf -x -l skip-big -d "skip OCR on pages larger than this many
|
|||||||
complete -c ocrmypdf -x -l jpeg-quality -d "JPEG quality [0..100]"
|
complete -c ocrmypdf -x -l jpeg-quality -d "JPEG quality [0..100]"
|
||||||
complete -c ocrmypdf -x -l png-quality -d "PNG quality [0..100]"
|
complete -c ocrmypdf -x -l png-quality -d "PNG quality [0..100]"
|
||||||
complete -c ocrmypdf -x -l jbig2-lossy -d "enable lossy JBIG2 (see docs)"
|
complete -c ocrmypdf -x -l jbig2-lossy -d "enable lossy JBIG2 (see docs)"
|
||||||
|
complete -c ocrmypdf -x -l jbig2-threshold -d "JBIG2 compression threshold (see docs)"
|
||||||
complete -c ocrmypdf -x -l max-image-mpixels -d "image decompression bomb threshold"
|
complete -c ocrmypdf -x -l max-image-mpixels -d "image decompression bomb threshold"
|
||||||
complete -c ocrmypdf -x -l pages -d "apply OCR to only the specified pages"
|
complete -c ocrmypdf -x -l pages -d "apply OCR to only the specified pages"
|
||||||
complete -c ocrmypdf -x -l tesseract-config -d "set custom tesseract config file"
|
complete -c ocrmypdf -x -l tesseract-config -d "set custom tesseract config file"
|
||||||
@@ -128,4 +130,27 @@ complete -c ocrmypdf -r -l user-words -d "specify location of user words file"
|
|||||||
complete -c ocrmypdf -r -l user-patterns -d "specify location of user patterns file"
|
complete -c ocrmypdf -r -l user-patterns -d "specify location of user patterns file"
|
||||||
complete -c ocrmypdf -x -l fast-web-view -d "if file size if above this amount in MB, linearize PDF"
|
complete -c ocrmypdf -x -l fast-web-view -d "if file size if above this amount in MB, linearize PDF"
|
||||||
|
|
||||||
complete -c ocrmypdf -x -a "(__fish_complete_suffix .pdf; __fish_complete_suffix .PDF; __fish_complete_suffix .jpg; __fish_complete_suffix .png)"
|
function __fish_ocrmypdf_color_conversion_strategy
|
||||||
|
echo -e "LeaveColorUnchanged\t"(_ "do not convert color spaces (default)")
|
||||||
|
echo -e "CMYK\t"(_ "convert all color spaces to CMYK")
|
||||||
|
echo -e "Gray\t"(_ "convert all color spaces to grayscale")
|
||||||
|
echo -e "RGB\t"(_ "convert all color spaces to RGB")
|
||||||
|
echo -e "UseDeviceIndependentColor\t"(_ "convert all color spaces to ICC-based color spaces")
|
||||||
|
end
|
||||||
|
|
||||||
|
complete -c ocrmypdf -x -l color-conversion-strategy -a '(__fish_ocrmypdf_color_conversion_strategy)' -d "set color conversion strategy"
|
||||||
|
|
||||||
|
function __fish_ocrmypdf_input_file_given
|
||||||
|
set -l tokens (commandline -opc)
|
||||||
|
for token in $tokens
|
||||||
|
if string match -q -r '^-' -- $token
|
||||||
|
continue
|
||||||
|
end
|
||||||
|
if test -f "$token"
|
||||||
|
return 0
|
||||||
|
end
|
||||||
|
end
|
||||||
|
return 1
|
||||||
|
end
|
||||||
|
|
||||||
|
complete -c ocrmypdf -x -n 'not __fish_ocrmypdf_input_file_given' -a "(__fish_complete_suffix .pdf)" -d "input file"
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
||||||
|
# SPDX-License-Identifier: MIT
|
||||||
---
|
---
|
||||||
version: "3.3"
|
version: "3.3"
|
||||||
services:
|
services:
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
# SPDX-FileCopyrightText: 2022 James R Barlow: https://github.com/jbarlow83
|
# SPDX-FileCopyrightText: 2022 James R Barlow: https://github.com/jbarlow83
|
||||||
# SPDX-License-Identifier: MIT
|
# SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
"""
|
"""An example of an OCRmyPDF plugin.
|
||||||
An example of an OCRmyPDF plugin.
|
|
||||||
|
|
||||||
This plugin adds two new command line arguments
|
This plugin adds two new command line arguments
|
||||||
--grayscale-ocr: converts the image to grayscale before performing OCR on it
|
--grayscale-ocr: converts the image to grayscale before performing OCR on it
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
<!-- SPDX-License-Identifier: CC-BY-SA-4.0 -->
|
||||||
|
|
||||||
|
To regenerate
|
||||||
|
=============
|
||||||
|
|
||||||
|
Using asciinema and svg-term (`npm install -g svg-term-cli`).
|
||||||
|
|
||||||
|
Create `~/.config/asciinema/config` to disable prompt.
|
||||||
|
|
||||||
|
```
|
||||||
|
[record]
|
||||||
|
|
||||||
|
command = fish --init-command 'alias fish_prompt="echo \>\ "'
|
||||||
|
```
|
||||||
|
|
||||||
|
Run asciinema
|
||||||
|
|
||||||
|
```
|
||||||
|
asciinema rec new_input.cast
|
||||||
|
```
|
||||||
|
|
||||||
|
Re-record faster version with fewer pauses
|
||||||
|
|
||||||
|
```
|
||||||
|
asciinema rec demo.cast -c "asciinema play new_input.cast --speed 2 --idle-time-limit 0.5"
|
||||||
|
```
|
||||||
|
|
||||||
|
Convert to SVG
|
||||||
|
```
|
||||||
|
svg-term --in=misc/screencast/demo.cast --out=misc/screencast/demo.svg --window
|
||||||
|
```
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
{"version": 2, "width": 131, "height": 24, "timestamp": 1687247006, "env": {"SHELL": "/usr/bin/fish", "TERM": "xterm-256color"}}
|
||||||
|
[0.103649, "o", "\u001b[?2004h\u001b]7; \u0007"]
|
||||||
|
[0.104223, "o", "\u001b]0;fish \u0007\u001b[30m\u001b(B\u001b[m\r> \u001b[K\r\u001b[C\u001b[C"]
|
||||||
|
[0.604542, "o", "o\r\u001b[3C\b\u001b[38;2;255;0;0mo\r\u001b[3C\u001b[30m\u001b(B\u001b[m\u001b[38;2;85;85;85mcrmypdf multipage.pdf multipage_with_ocr.pdf\r\u001b[3C\u001b[30m\u001b(B\u001b[m"]
|
||||||
|
[0.679571, "o", "\u001b[38;2;255;0;0mc\u001b[38;2;85;85;85mrmypdf multipage.pdf multipage_with_ocr.pdf\r\u001b[4C\u001b[30m\u001b(B\u001b[m"]
|
||||||
|
[0.767271, "o", "\u001b[38;2;255;0;0mr\u001b[38;2;85;85;85mmypdf multipage.pdf multipage_with_ocr.pdf\r\u001b[5C\u001b[30m\u001b(B\u001b[m"]
|
||||||
|
[0.814505, "o", "\u001b[38;2;255;0;0mm\u001b[38;2;85;85;85mypdf multipage.pdf multipage_with_ocr.pdf\r\u001b[6C\u001b[30m\u001b(B\u001b[m"]
|
||||||
|
[0.938919, "o", "\u001b[38;2;255;0;0my\u001b[38;2;85;85;85mpdf multipage.pdf multipage_with_ocr.pdf\r\u001b[7C\u001b[30m\u001b(B\u001b[m"]
|
||||||
|
[0.967347, "o", "\u001b[38;2;255;0;0mp\u001b[38;2;85;85;85mdf multipage.pdf multipage_with_ocr.pdf\r\u001b[8C\u001b[30m\u001b(B\u001b[m"]
|
||||||
|
[1.009954, "o", "\u001b[38;2;255;0;0md\u001b[38;2;85;85;85mf multipage.pdf multipage_with_ocr.pdf\r\u001b[9C\u001b[30m\u001b(B\u001b[m"]
|
||||||
|
[1.034488, "o", "\u001b[38;2;255;0;0mf\u001b[38;2;85;85;85m multipage.pdf multipage_with_ocr.pdf\r\u001b[10C\u001b[30m\u001b(B\u001b[m\b\b\b\b\b\b\b\b\u001b[38;2;0;95;215mocrmypdf\u001b[38;2;85;85;85m multipage.pdf multipage_with_ocr.pdf\r\u001b[10C\u001b[30m\u001b(B\u001b[m"]
|
||||||
|
[1.069226, "o", "\u001b[38;2;0;95;215m \u001b[38;2;85;85;85mmultipage.pdf multipage_with_ocr.pdf\r\u001b[11C\u001b[30m\u001b(B\u001b[m\b \u001b[38;2;85;85;85mmultipage.pdf multipage_with_ocr.pdf\r\u001b[11C\u001b[30m\u001b(B\u001b[m"]
|
||||||
|
[1.569682, "o", "-\u001b[K\r\u001b[12C\u001b[38;2;85;85;85m-version\r\u001b[12C\u001b[30m\u001b(B\u001b[m\b\u001b[38;2;0;175;255m-\u001b[38;2;85;85;85m-version\r\u001b[12C\u001b[30m\u001b(B\u001b[m"]
|
||||||
|
[1.642096, "o", "\u001b[38;2;0;175;255m-\u001b[38;2;85;85;85mversion\r\u001b[13C\u001b[30m\u001b(B\u001b[m"]
|
||||||
|
[1.71793, "o", "\u001b[38;2;0;175;255ms\u001b[30m\u001b(B\u001b[m\u001b[K\r\u001b[14C"]
|
||||||
|
[1.771483, "o", "\u001b[38;2;0;175;255mk\r\u001b[15C\u001b[30m\u001b(B\u001b[m"]
|
||||||
|
[1.864664, "o", "\u001b[38;2;0;175;255mi\r\u001b[16C\u001b[30m\u001b(B\u001b[m"]
|
||||||
|
[1.876085, "o", "\u001b[38;2;0;175;255mp\r\u001b[17C\u001b[30m\u001b(B\u001b[m"]
|
||||||
|
[2.092979, "o", "\u001b[38;2;0;175;255m-\r\u001b[18C\u001b[30m\u001b(B\u001b[m"]
|
||||||
|
[2.138821, "o", "\u001b[38;2;0;175;255mt\r\u001b[19C\u001b[30m\u001b(B\u001b[m"]
|
||||||
|
[2.18017, "o", "\u001b[38;2;0;175;255me\r\u001b[20C\u001b[30m\u001b(B\u001b[m"]
|
||||||
|
[2.268222, "o", "\u001b[38;2;0;175;255mx\r\u001b[21C\u001b[30m\u001b(B\u001b[m"]
|
||||||
|
[2.277031, "o", "\u001b[38;2;0;175;255mt\r\u001b[22C\u001b[30m\u001b(B\u001b[m"]
|
||||||
|
[2.322469, "o", "\u001b[38;2;0;175;255m \r\u001b[23C\u001b[30m\u001b(B\u001b[m\b \r\u001b[23C"]
|
||||||
|
[2.824696, "o", "m\r\u001b[24C\b\u001b[38;2;0;175;255m\u001b[4mm\r\u001b[24C\u001b[30m\u001b(B\u001b[m\u001b[38;2;85;85;85masks.pdf \r\u001b[24C\u001b[30m\u001b(B\u001b[m"]
|
||||||
|
[2.923234, "o", "\u001b[38;2;0;175;255m\u001b[4mu\u001b[30m\u001b(B\u001b[m\u001b[K\r\u001b[25C\u001b[38;2;85;85;85mltipage.pdf \r\u001b[25C\u001b[30m\u001b(B\u001b[m"]
|
||||||
|
[2.960685, "o", "\u001b[38;2;0;175;255m\u001b[4ml\u001b[38;2;85;85;85m\u001b[24mtipage.pdf \r\u001b[26C\u001b[30m\u001b(B\u001b[m"]
|
||||||
|
[3.03365, "o", "\u001b[38;2;0;175;255m\u001b[4mt\u001b[38;2;85;85;85m\u001b[24mipage.pdf \r\u001b[27C\u001b[30m\u001b(B\u001b[m"]
|
||||||
|
[3.479338, "o", "\u001b[38;2;0;175;255m\u001b[4mipage.pdf \r\u001b[37C\u001b[30m\u001b(B\u001b[m\b \r\u001b[37C"]
|
||||||
|
[3.754818, "o", "m\r\u001b[38C\b\u001b[38;2;0;175;255m\u001b[4mm\r\u001b[38C\u001b[30m\u001b(B\u001b[m\u001b[38;2;85;85;85masks.pdf \r\u001b[38C\u001b[30m\u001b(B\u001b[m"]
|
||||||
|
[3.873318, "o", "\u001b[38;2;0;175;255m\u001b[4mu\u001b[30m\u001b(B\u001b[m\u001b[K\r\u001b[39C\u001b[38;2;85;85;85mltipage.pdf \r\u001b[39C\u001b[30m\u001b(B\u001b[m"]
|
||||||
|
[3.926829, "o", "\u001b[38;2;0;175;255m\u001b[4ml\u001b[38;2;85;85;85m\u001b[24mtipage.pdf \r\u001b[40C\u001b[30m\u001b(B\u001b[m"]
|
||||||
|
[4.272251, "o", "\u001b[38;2;0;175;255m\u001b[4mtipage.pdf \r\u001b[51C\u001b[30m\u001b(B\u001b[m\b \r\u001b[51C"]
|
||||||
|
[4.343464, "o", "\r\u001b[50C"]
|
||||||
|
[4.416286, "o", "\r\u001b[49C"]
|
||||||
|
[4.490574, "o", "\r\u001b[48C"]
|
||||||
|
[4.564115, "o", "\r\u001b[47C"]
|
||||||
|
[4.630398, "o", "\r\u001b[46C"]
|
||||||
|
[4.76825, "o", "\u001b[38;2;0;175;255m\u001b[4m_.pd\u001b[30m\u001b(B\u001b[mf \r\u001b[47C\u001b[10D\u001b[38;2;0;175;255mmultipage_.pdf\u001b[30m\u001b(B\u001b[m \r\u001b[47C"]
|
||||||
|
[5.012506, "o", "\u001b[38;2;0;175;255mo.pd\u001b[30m\u001b(B\u001b[mf \r\u001b[48C\u001b[3C\u001b[38;2;0;175;255mf\u001b[30m\u001b(B\u001b[m \r\u001b[48C"]
|
||||||
|
[5.053615, "o", "\u001b[38;2;0;175;255mc.pd\u001b[30m\u001b(B\u001b[mf \r\u001b[49C\u001b[3C\u001b[38;2;0;175;255mf\u001b[30m\u001b(B\u001b[m \r\u001b[49C"]
|
||||||
|
[5.103957, "o", "\u001b[38;2;0;175;255mr.pd\u001b[30m\u001b(B\u001b[mf \r\u001b[50C\u001b[3C\u001b[38;2;0;175;255mf\u001b[30m\u001b(B\u001b[m \r\u001b[50C"]
|
||||||
|
[5.226183, "o", "\r\u001b[55C"]
|
||||||
|
[5.728321, "o", "\r\n\u001b[30m\u001b(B\u001b[m\u001b[?2004l\u001b]0;ocrmypdf --skip-text multipage.pdf multipage_ocr.pdf /home/jb/src/ocrmypdf/tests/resources\u0007\u001b[30m\u001b(B\u001b[m\r"]
|
||||||
|
[5.801032, "o", "\rScanning contents: 0%| | 0/6 [00:00<?, ?page/s]"]
|
||||||
|
[5.802664, "o", "\rScanning contents: 100%|█████████████████████████████████████████████████████████████████████████| 6/6 [00:00<00:00, 1270.68page/s]\r\n"]
|
||||||
|
[5.802747, "o", "Start processing 6 pages concurrently\r\n"]
|
||||||
|
[5.803488, "o", "\rOCR: 0%| | 0.0/6.0 [00:00<?, ?page/s]"]
|
||||||
|
[5.804896, "o", "\r \r 4 skipping all processing on this page\r\n\rOCR: 0%| | 0.0/6.0 [00:00<?, ?page/s]"]
|
||||||
|
[5.896969, "o", "\rOCR: 25%|█████████████████████▎ | 1.5/6.0 [00:00<00:00, 8.12page/s]"]
|
||||||
|
[6.170021, "o", "\rOCR: 42%|███████████████████████████████████▍ | 2.5/6.0 [00:00<00:01, 3.05page/s]"]
|
||||||
|
[6.292338, "o", "\rOCR: 58%|█████████████████████████████████████████████████▌ | 3.5/6.0 [00:00<00:00, 3.39page/s]"]
|
||||||
|
[6.586017, "o", "\rOCR: 75%|███████████████████████████████████████████████████████████████▊ | 4.5/6.0 [00:01<00:00, 2.49page/s]"]
|
||||||
|
[7.087058, "o", "\rOCR: 92%|█████████████████████████████████████████████████████████████████████████████▉ | 5.5/6.0 [00:06<00:00, 1.98s/page]\rOCR: 100%|█████████████████████████████████████████████████████████████████████████████████████| 6.0/6.0 [00:06<00:00, 1.09s/page]\r\nPostprocessing...\r\n"]
|
||||||
|
[7.104927, "o", "\rPDF/A conversion: 0%| | 0/6 [00:00<?, ?page/s]"]
|
||||||
|
[7.607392, "o", "\rPDF/A conversion: 50%|██████████████████████████████████████ | 3/6 [00:01<00:01, 1.61page/s]"]
|
||||||
|
[7.653781, "o", "\rPDF/A conversion: 83%|███████████████████████████████████████████████████████████████▎ | 5/6 [00:01<00:00, 2.90page/s]"]
|
||||||
|
[7.774532, "o", "\rPDF/A conversion: 100%|████████████████████████████████████████████████████████████████████████████| 6/6 [00:02<00:00, 2.71page/s]\r\n"]
|
||||||
|
[7.778252, "o", "\u001b[33mSome input metadata could not be copied because it is not permitted in PDF/A. You may wish to examine the output PDF's XMP metadata.\u001b[0m\r\n"]
|
||||||
|
[8.280789, "o", "\rRecompressing JPEGs: 0image [00:00, ?image/s]\rRecompressing JPEGs: 0image [00:00, ?image/s]\r\n\rDeflating JPEGs: 0%| | 0/4 [00:00<?, ?image/s]\rDeflating JPEGs: 100%|███████████████████████████████████████████████████████████████████████████| 4/4 [00:00<00:00, 238.28image/s]\r\n"]
|
||||||
|
[8.28149, "o", "\rJBIG2: 0item [00:00, ?item/s]\rJBIG2: 0item [00:00, ?item/s]\r\n"]
|
||||||
|
[8.289998, "o", "Image optimization ratio: 1.01 savings: 1.3%\r\nTotal file size ratio: 1.02 savings: 1.6%\r\n"]
|
||||||
|
[8.291209, "o", "Output file is a PDF/A-2B (as expected)\r\n"]
|
||||||
|
[8.361316, "o", "\u001b[2m⏎\u001b(B\u001b[m \r⏎ \r\u001b[K\u001b[?2004h\u001b]0;fish /home/jb/src/ocrmypdf/tests/resources\u0007\u001b[30m\u001b(B\u001b[m> \u001b[K\r\u001b[C\u001b[C"]
|
||||||
|
[8.862206, "o", "\r\n\u001b[30m\u001b(B\u001b[m\u001b[30m\u001b(B\u001b[m\u001b[?2004l"]
|
||||||
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 29 KiB |
+3
-4
@@ -2,6 +2,8 @@
|
|||||||
# SPDX-FileCopyrightText: 2017 Enantiomerie
|
# SPDX-FileCopyrightText: 2017 Enantiomerie
|
||||||
# SPDX-License-Identifier: MIT
|
# SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
"""Example OCRmyPDF for Synology NAS."""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
# This script must be edited to meet your needs.
|
# This script must be edited to meet your needs.
|
||||||
@@ -25,10 +27,7 @@ logging.basicConfig(
|
|||||||
filemode='w',
|
filemode='w',
|
||||||
)
|
)
|
||||||
|
|
||||||
if len(sys.argv) > 1:
|
start_dir = sys.argv[1] if len(sys.argv) > 1 else '.'
|
||||||
start_dir = sys.argv[1]
|
|
||||||
else:
|
|
||||||
start_dir = '.'
|
|
||||||
|
|
||||||
for dir_name, _subdirs, file_list in os.walk(start_dir):
|
for dir_name, _subdirs, file_list in os.walk(start_dir):
|
||||||
logging.info(dir_name)
|
logging.info(dir_name)
|
||||||
|
|||||||
+240
-73
@@ -3,165 +3,332 @@
|
|||||||
# SPDX-FileCopyrightText: 2020 James R Barlow <https://github.com/jbarlow83>
|
# SPDX-FileCopyrightText: 2020 James R Barlow <https://github.com/jbarlow83>
|
||||||
# SPDX-License-Identifier: MIT
|
# SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
from __future__ import annotations
|
"""Watch a directory for new PDFs and OCR them."""
|
||||||
|
|
||||||
|
# Do not enable annotations!
|
||||||
|
# https://github.com/tiangolo/typer/discussions/598
|
||||||
|
# from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import os
|
|
||||||
import shutil
|
import shutil
|
||||||
import sys
|
import sys
|
||||||
import time
|
import time
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
from enum import Enum
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from typing import Annotated, Any
|
||||||
|
|
||||||
import pikepdf
|
import pikepdf
|
||||||
|
import typer
|
||||||
|
from dotenv import load_dotenv
|
||||||
from watchdog.events import PatternMatchingEventHandler
|
from watchdog.events import PatternMatchingEventHandler
|
||||||
from watchdog.observers import Observer
|
from watchdog.observers import Observer
|
||||||
from watchdog.observers.polling import PollingObserver
|
from watchdog.observers.polling import PollingObserver
|
||||||
|
|
||||||
import ocrmypdf
|
import ocrmypdf
|
||||||
|
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
|
|
||||||
# pylint: disable=logging-format-interpolation
|
# pylint: disable=logging-format-interpolation
|
||||||
|
app = typer.Typer(name="ocrmypdf-watcher")
|
||||||
|
|
||||||
def getenv_bool(name: str, default: str = 'False'):
|
|
||||||
return os.getenv(name, default).lower() in ('true', 'yes', 'y', '1')
|
|
||||||
|
|
||||||
|
|
||||||
INPUT_DIRECTORY = os.getenv('OCR_INPUT_DIRECTORY', '/input')
|
|
||||||
OUTPUT_DIRECTORY = os.getenv('OCR_OUTPUT_DIRECTORY', '/output')
|
|
||||||
ARCHIVE_DIRECTORY = os.getenv('OCR_ARCHIVE_DIRECTORY', '/processed')
|
|
||||||
OUTPUT_DIRECTORY_YEAR_MONTH = getenv_bool('OCR_OUTPUT_DIRECTORY_YEAR_MONTH')
|
|
||||||
ON_SUCCESS_DELETE = getenv_bool('OCR_ON_SUCCESS_DELETE')
|
|
||||||
ON_SUCCESS_ARCHIVE = getenv_bool('OCR_ON_SUCCESS_ARCHIVE')
|
|
||||||
DESKEW = getenv_bool('OCR_DESKEW')
|
|
||||||
OCR_JSON_SETTINGS = json.loads(os.getenv('OCR_JSON_SETTINGS', '{}'))
|
|
||||||
POLL_NEW_FILE_SECONDS = int(os.getenv('OCR_POLL_NEW_FILE_SECONDS', '1'))
|
|
||||||
USE_POLLING = getenv_bool('OCR_USE_POLLING')
|
|
||||||
LOGLEVEL = os.getenv('OCR_LOGLEVEL', 'INFO')
|
|
||||||
PATTERNS = ['*.pdf', '*.PDF']
|
|
||||||
|
|
||||||
log = logging.getLogger('ocrmypdf-watcher')
|
log = logging.getLogger('ocrmypdf-watcher')
|
||||||
|
|
||||||
|
|
||||||
def get_output_dir(root, basename):
|
class LoggingLevelEnum(str, Enum):
|
||||||
if OUTPUT_DIRECTORY_YEAR_MONTH:
|
"""Enum for logging levels."""
|
||||||
|
|
||||||
|
DEBUG = "DEBUG"
|
||||||
|
INFO = "INFO"
|
||||||
|
WARNING = "WARNING"
|
||||||
|
ERROR = "ERROR"
|
||||||
|
CRITICAL = "CRITICAL"
|
||||||
|
|
||||||
|
|
||||||
|
def get_output_dir(root: Path, basename: str, output_dir_year_month: bool) -> Path:
|
||||||
|
if output_dir_year_month:
|
||||||
today = datetime.today()
|
today = datetime.today()
|
||||||
output_directory_year_month = (
|
output_directory_year_month = root / str(today.year) / f'{today.month:02d}'
|
||||||
Path(root) / str(today.year) / f'{today.month:02d}'
|
|
||||||
)
|
|
||||||
if not output_directory_year_month.exists():
|
if not output_directory_year_month.exists():
|
||||||
output_directory_year_month.mkdir(parents=True, exist_ok=True)
|
output_directory_year_month.mkdir(parents=True, exist_ok=True)
|
||||||
output_path = Path(output_directory_year_month) / basename
|
output_path = Path(output_directory_year_month) / basename
|
||||||
else:
|
else:
|
||||||
output_path = Path(OUTPUT_DIRECTORY) / basename
|
output_path = root / basename
|
||||||
return output_path
|
return output_path
|
||||||
|
|
||||||
|
|
||||||
def wait_for_file_ready(file_path):
|
def wait_for_file_ready(
|
||||||
|
file_path: Path, poll_new_file_seconds: int, retries_loading_file: int
|
||||||
|
):
|
||||||
# This loop waits to make sure that the file is completely loaded on
|
# This loop waits to make sure that the file is completely loaded on
|
||||||
# disk before attempting to read. Docker sometimes will publish the
|
# disk before attempting to read. Docker sometimes will publish the
|
||||||
# watchdog event before the file is actually fully on disk, causing
|
# watchdog event before the file is actually fully on disk, causing
|
||||||
# pikepdf to fail.
|
# pikepdf to fail.
|
||||||
|
|
||||||
retries = 5
|
tries = retries_loading_file + 1
|
||||||
while retries:
|
while tries:
|
||||||
try:
|
try:
|
||||||
pdf = pikepdf.open(file_path)
|
with pikepdf.Pdf.open(file_path) as pdf:
|
||||||
except (FileNotFoundError, pikepdf.PdfError) as e:
|
log.debug(f"{file_path} ready with {pdf.pages} pages")
|
||||||
|
return True
|
||||||
|
except (FileNotFoundError, OSError) as e:
|
||||||
log.info(f"File {file_path} is not ready yet")
|
log.info(f"File {file_path} is not ready yet")
|
||||||
log.debug("Exception was", exc_info=e)
|
log.debug("Exception was", exc_info=e)
|
||||||
time.sleep(POLL_NEW_FILE_SECONDS)
|
time.sleep(poll_new_file_seconds)
|
||||||
retries -= 1
|
tries -= 1
|
||||||
else:
|
except pikepdf.PdfError as e:
|
||||||
pdf.close()
|
log.info(f"File {file_path} is not full written yet")
|
||||||
return True
|
log.debug("Exception was", exc_info=e)
|
||||||
|
time.sleep(poll_new_file_seconds)
|
||||||
|
tries -= 1
|
||||||
|
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def execute_ocrmypdf(file_path):
|
def execute_ocrmypdf(
|
||||||
file_path = Path(file_path)
|
*,
|
||||||
output_path = get_output_dir(OUTPUT_DIRECTORY, file_path.name)
|
file_path: Path,
|
||||||
|
archive_dir: Path,
|
||||||
|
output_dir: Path,
|
||||||
|
ocrmypdf_kwargs: dict[str, Any],
|
||||||
|
on_success_delete: bool,
|
||||||
|
on_success_archive: bool,
|
||||||
|
poll_new_file_seconds: int,
|
||||||
|
retries_loading_file: int,
|
||||||
|
output_dir_year_month: bool,
|
||||||
|
):
|
||||||
|
output_path = get_output_dir(output_dir, file_path.name, output_dir_year_month)
|
||||||
|
|
||||||
log.info("-" * 20)
|
log.info("-" * 20)
|
||||||
log.info(f'New file: {file_path}. Waiting until fully loaded...')
|
log.info(f'New file: {file_path}. Waiting until fully written...')
|
||||||
if not wait_for_file_ready(file_path):
|
if not wait_for_file_ready(file_path, poll_new_file_seconds, retries_loading_file):
|
||||||
log.info(f"Gave up waiting for {file_path} to become ready")
|
log.info(f"Gave up waiting for {file_path} to become ready")
|
||||||
return
|
return
|
||||||
log.info(f'Attempting to OCRmyPDF to: {output_path}')
|
log.info(f'Attempting to OCRmyPDF to: {output_path}')
|
||||||
|
|
||||||
|
log.debug(
|
||||||
|
f'OCRmyPDF input_file={file_path} output_file={output_path} '
|
||||||
|
f'kwargs: {ocrmypdf_kwargs}'
|
||||||
|
)
|
||||||
exit_code = ocrmypdf.ocr(
|
exit_code = ocrmypdf.ocr(
|
||||||
input_file=file_path,
|
input_file=file_path,
|
||||||
output_file=output_path,
|
output_file=output_path,
|
||||||
deskew=DESKEW,
|
**ocrmypdf_kwargs,
|
||||||
**OCR_JSON_SETTINGS,
|
|
||||||
)
|
)
|
||||||
if exit_code == 0:
|
if exit_code == 0:
|
||||||
if ON_SUCCESS_DELETE:
|
if on_success_delete:
|
||||||
log.info(f'OCR is done. Deleting: {file_path}')
|
log.info(f'OCR is done. Deleting: {file_path}')
|
||||||
file_path.unlink()
|
file_path.unlink()
|
||||||
elif ON_SUCCESS_ARCHIVE:
|
elif on_success_archive:
|
||||||
log.info(f'OCR is done. Archiving {file_path.name} to {ARCHIVE_DIRECTORY}')
|
log.info(f'OCR is done. Archiving {file_path.name} to {archive_dir}')
|
||||||
shutil.move(file_path, f'{ARCHIVE_DIRECTORY}/{file_path.name}')
|
shutil.move(file_path, f'{archive_dir}/{file_path.name}')
|
||||||
|
else:
|
||||||
|
log.info('OCR is done')
|
||||||
else:
|
else:
|
||||||
log.info('OCR is done')
|
log.info('OCR is done')
|
||||||
|
|
||||||
|
|
||||||
class HandleObserverEvent(PatternMatchingEventHandler):
|
class HandleObserverEvent(PatternMatchingEventHandler):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
patterns=None,
|
||||||
|
ignore_patterns=None,
|
||||||
|
ignore_directories=False,
|
||||||
|
case_sensitive=False,
|
||||||
|
settings={},
|
||||||
|
):
|
||||||
|
super().__init__(
|
||||||
|
patterns=patterns,
|
||||||
|
ignore_patterns=ignore_patterns,
|
||||||
|
ignore_directories=ignore_directories,
|
||||||
|
case_sensitive=case_sensitive,
|
||||||
|
)
|
||||||
|
self._settings = settings
|
||||||
|
|
||||||
def on_any_event(self, event):
|
def on_any_event(self, event):
|
||||||
if event.event_type in ['created']:
|
if event.event_type in ['created']:
|
||||||
execute_ocrmypdf(event.src_path)
|
execute_ocrmypdf(file_path=Path(event.src_path), **self._settings)
|
||||||
|
|
||||||
|
|
||||||
def main():
|
@app.command()
|
||||||
|
def main(
|
||||||
|
input_dir: Annotated[
|
||||||
|
Path,
|
||||||
|
typer.Argument(
|
||||||
|
envvar='OCR_INPUT_DIRECTORY',
|
||||||
|
exists=True,
|
||||||
|
file_okay=False,
|
||||||
|
dir_okay=True,
|
||||||
|
readable=True,
|
||||||
|
resolve_path=True,
|
||||||
|
),
|
||||||
|
] = '/input',
|
||||||
|
output_dir: Annotated[
|
||||||
|
Path,
|
||||||
|
typer.Argument(
|
||||||
|
envvar='OCR_OUTPUT_DIRECTORY',
|
||||||
|
exists=True,
|
||||||
|
file_okay=False,
|
||||||
|
dir_okay=True,
|
||||||
|
writable=True,
|
||||||
|
resolve_path=True,
|
||||||
|
),
|
||||||
|
] = '/output',
|
||||||
|
archive_dir: Annotated[
|
||||||
|
Path,
|
||||||
|
typer.Argument(
|
||||||
|
envvar='OCR_ARCHIVE_DIRECTORY',
|
||||||
|
exists=True,
|
||||||
|
file_okay=False,
|
||||||
|
dir_okay=True,
|
||||||
|
writable=True,
|
||||||
|
resolve_path=True,
|
||||||
|
),
|
||||||
|
] = '/processed',
|
||||||
|
output_dir_year_month: Annotated[
|
||||||
|
bool,
|
||||||
|
typer.Option(
|
||||||
|
envvar='OCR_OUTPUT_DIRECTORY_YEAR_MONTH',
|
||||||
|
help='Create a subdirectory in the output directory for each year and month',
|
||||||
|
),
|
||||||
|
] = False,
|
||||||
|
on_success_delete: Annotated[
|
||||||
|
bool,
|
||||||
|
typer.Option(
|
||||||
|
envvar='OCR_ON_SUCCESS_DELETE',
|
||||||
|
help='Delete the input file after successful OCR',
|
||||||
|
),
|
||||||
|
] = False,
|
||||||
|
on_success_archive: Annotated[
|
||||||
|
bool,
|
||||||
|
typer.Option(
|
||||||
|
envvar='OCR_ON_SUCCESS_ARCHIVE',
|
||||||
|
help='Archive the input file after successful OCR',
|
||||||
|
),
|
||||||
|
] = False,
|
||||||
|
deskew: Annotated[
|
||||||
|
bool,
|
||||||
|
typer.Option(
|
||||||
|
envvar='OCR_DESKEW',
|
||||||
|
help='Deskew the input file before OCR',
|
||||||
|
),
|
||||||
|
] = False,
|
||||||
|
ocr_json_settings: Annotated[
|
||||||
|
str,
|
||||||
|
typer.Option(
|
||||||
|
envvar='OCR_JSON_SETTINGS',
|
||||||
|
help='JSON settings to pass to OCRmyPDF (JSON string or file path)',
|
||||||
|
),
|
||||||
|
] = None,
|
||||||
|
poll_new_file_seconds: Annotated[
|
||||||
|
int,
|
||||||
|
typer.Option(
|
||||||
|
envvar='OCR_POLL_NEW_FILE_SECONDS',
|
||||||
|
help='Seconds to wait before polling a new file',
|
||||||
|
min=0,
|
||||||
|
),
|
||||||
|
] = 1,
|
||||||
|
use_polling: Annotated[
|
||||||
|
bool,
|
||||||
|
typer.Option(
|
||||||
|
envvar='OCR_USE_POLLING',
|
||||||
|
help='Use polling instead of filesystem events',
|
||||||
|
),
|
||||||
|
] = False,
|
||||||
|
retries_loading_file: Annotated[
|
||||||
|
int,
|
||||||
|
typer.Option(
|
||||||
|
envvar='OCR_RETRIES_LOADING_FILE',
|
||||||
|
help='Number of times to retry loading a file before giving up',
|
||||||
|
min=0,
|
||||||
|
),
|
||||||
|
] = 5,
|
||||||
|
loglevel: Annotated[
|
||||||
|
LoggingLevelEnum,
|
||||||
|
typer.Option(
|
||||||
|
envvar='OCR_LOGLEVEL',
|
||||||
|
help='Logging level',
|
||||||
|
),
|
||||||
|
] = LoggingLevelEnum.INFO,
|
||||||
|
patterns: Annotated[
|
||||||
|
str,
|
||||||
|
typer.Option(
|
||||||
|
envvar='OCR_PATTERNS',
|
||||||
|
help='File patterns to watch',
|
||||||
|
),
|
||||||
|
] = '*.pdf,*.PDF',
|
||||||
|
):
|
||||||
ocrmypdf.configure_logging(
|
ocrmypdf.configure_logging(
|
||||||
verbosity=(
|
verbosity=(
|
||||||
ocrmypdf.Verbosity.default
|
ocrmypdf.Verbosity.default
|
||||||
if LOGLEVEL != 'DEBUG'
|
if loglevel != LoggingLevelEnum.DEBUG
|
||||||
else ocrmypdf.Verbosity.debug
|
else ocrmypdf.Verbosity.debug
|
||||||
),
|
),
|
||||||
manage_root_logger=True,
|
manage_root_logger=True,
|
||||||
)
|
)
|
||||||
log.setLevel(LOGLEVEL)
|
log.setLevel(loglevel.value)
|
||||||
log.info(
|
log.info(
|
||||||
f"Starting OCRmyPDF watcher with config:\n"
|
f"Starting OCRmyPDF watcher with config:\n"
|
||||||
f"Input Directory: {INPUT_DIRECTORY}\n"
|
f"Input Directory: {input_dir}\n"
|
||||||
f"Output Directory: {OUTPUT_DIRECTORY}\n"
|
f"Output Directory: {output_dir}\n"
|
||||||
f"Output Directory Year & Month: {OUTPUT_DIRECTORY_YEAR_MONTH}\n"
|
f"Output Directory Year & Month: {output_dir_year_month}\n"
|
||||||
f"Archive Directory: {ARCHIVE_DIRECTORY}"
|
f"Archive Directory: {archive_dir}"
|
||||||
)
|
)
|
||||||
log.debug(
|
log.debug(
|
||||||
f"INPUT_DIRECTORY: {INPUT_DIRECTORY}\n"
|
f"INPUT_DIRECTORY: {input_dir}\n"
|
||||||
f"OUTPUT_DIRECTORY: {OUTPUT_DIRECTORY}\n"
|
f"OUTPUT_DIRECTORY: {output_dir}\n"
|
||||||
f"OUTPUT_DIRECTORY_YEAR_MONTH: {OUTPUT_DIRECTORY_YEAR_MONTH}\n"
|
f"OUTPUT_DIRECTORY_YEAR_MONTH: {output_dir_year_month}\n"
|
||||||
f"ARCHIVE_DIRECTORY: {ARCHIVE_DIRECTORY}\n"
|
f"ARCHIVE_DIRECTORY: {archive_dir}\n"
|
||||||
f"ON_SUCCESS_DELETE: {ON_SUCCESS_DELETE}\n"
|
f"ON_SUCCESS_DELETE: {on_success_delete}\n"
|
||||||
f"ON_SUCCESS_ARCHIVE: {ON_SUCCESS_ARCHIVE}\n"
|
f"ON_SUCCESS_ARCHIVE: {on_success_archive}\n"
|
||||||
f"DESKEW: {DESKEW}\n"
|
f"DESKEW: {deskew}\n"
|
||||||
f"ARGS: {OCR_JSON_SETTINGS}\n"
|
f"ARGS: {ocr_json_settings}\n"
|
||||||
f"POLL_NEW_FILE_SECONDS: {POLL_NEW_FILE_SECONDS}\n"
|
f"POLL_NEW_FILE_SECONDS: {poll_new_file_seconds}\n"
|
||||||
f"USE_POLLING: {USE_POLLING}\n"
|
f"RETRIES_LOADING_FILE: {retries_loading_file}\n"
|
||||||
f"LOGLEVEL: {LOGLEVEL}"
|
f"USE_POLLING: {use_polling}\n"
|
||||||
|
f"LOGLEVEL: {loglevel.value}"
|
||||||
)
|
)
|
||||||
|
|
||||||
if 'input_file' in OCR_JSON_SETTINGS or 'output_file' in OCR_JSON_SETTINGS:
|
if ocr_json_settings and Path(ocr_json_settings).exists():
|
||||||
log.error('OCR_JSON_SETTINGS should not specify input file or output file')
|
json_settings = json.loads(Path(ocr_json_settings).read_text())
|
||||||
|
else:
|
||||||
|
json_settings = json.loads(ocr_json_settings or '{}')
|
||||||
|
|
||||||
|
if 'input_file' in json_settings or 'output_file' in json_settings:
|
||||||
|
log.error(
|
||||||
|
'OCR_JSON_SETTINGS (--ocr-json-settings) may not specify input/output file'
|
||||||
|
)
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
handler = HandleObserverEvent(patterns=PATTERNS)
|
handler = HandleObserverEvent(
|
||||||
if USE_POLLING:
|
patterns=patterns.split(','),
|
||||||
|
settings={
|
||||||
|
'archive_dir': archive_dir,
|
||||||
|
'output_dir': output_dir,
|
||||||
|
'ocrmypdf_kwargs': json_settings | {'deskew': deskew},
|
||||||
|
'on_success_delete': on_success_delete,
|
||||||
|
'on_success_archive': on_success_archive,
|
||||||
|
'poll_new_file_seconds': poll_new_file_seconds,
|
||||||
|
'retries_loading_file': retries_loading_file,
|
||||||
|
'output_dir_year_month': output_dir_year_month,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
if use_polling:
|
||||||
observer = PollingObserver()
|
observer = PollingObserver()
|
||||||
else:
|
else:
|
||||||
observer = Observer()
|
observer = Observer()
|
||||||
observer.schedule(handler, INPUT_DIRECTORY, recursive=True)
|
observer.schedule(handler, input_dir, recursive=True)
|
||||||
observer.start()
|
observer.start()
|
||||||
|
typer.echo(f"Watching {input_dir} for new PDFs. Press Ctrl+C to exit.")
|
||||||
try:
|
try:
|
||||||
while True:
|
while True:
|
||||||
time.sleep(1)
|
time.sleep(30)
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
observer.stop()
|
observer.stop()
|
||||||
observer.join()
|
observer.join()
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
app()
|
||||||
|
|||||||
+3
-3
@@ -2,7 +2,7 @@
|
|||||||
# SPDX-FileCopyrightText: 2019 James R. Barlow
|
# SPDX-FileCopyrightText: 2019 James R. Barlow
|
||||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
"""This is a simple web service/HTTP wrapper for OCRmyPDF
|
"""This is a simple web service/HTTP wrapper for OCRmyPDF.
|
||||||
|
|
||||||
This may be more convenient than the command line tool for some Docker users.
|
This may be more convenient than the command line tool for some Docker users.
|
||||||
Note that OCRmyPDF uses Ghostscript, which is licensed under AGPLv3+. While
|
Note that OCRmyPDF uses Ghostscript, which is licensed under AGPLv3+. While
|
||||||
@@ -15,7 +15,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import os
|
import os
|
||||||
import shlex
|
import shlex
|
||||||
from subprocess import PIPE, run
|
from subprocess import run
|
||||||
from tempfile import TemporaryDirectory
|
from tempfile import TemporaryDirectory
|
||||||
|
|
||||||
from flask import Flask, Response, request, send_from_directory
|
from flask import Flask, Response, request, send_from_directory
|
||||||
@@ -48,7 +48,7 @@ def do_ocrmypdf(file):
|
|||||||
return Response("--sidecar not supported", 501, mimetype='text/plain')
|
return Response("--sidecar not supported", 501, mimetype='text/plain')
|
||||||
|
|
||||||
ocrmypdf_args = ["ocrmypdf", *cmd_args, up_file, down_file]
|
ocrmypdf_args = ["ocrmypdf", *cmd_args, up_file, down_file]
|
||||||
proc = run(ocrmypdf_args, capture_output=True, encoding="utf-8")
|
proc = run(ocrmypdf_args, capture_output=True, encoding="utf-8", check=False)
|
||||||
if proc.returncode != 0:
|
if proc.returncode != 0:
|
||||||
stderr = proc.stderr
|
stderr = proc.stderr
|
||||||
return Response(stderr, 400, mimetype='text/plain')
|
return Response(stderr, 400, mimetype='text/plain')
|
||||||
|
|||||||
+102
-34
@@ -1,16 +1,86 @@
|
|||||||
|
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
||||||
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
[build-system]
|
[build-system]
|
||||||
requires = [
|
requires = ["setuptools >= 61", "setuptools_scm[toml] >= 7.0.5", "wheel"]
|
||||||
"setuptools >= 52",
|
|
||||||
"setuptools_scm[toml] >= 7.0.5",
|
|
||||||
"wheel"
|
|
||||||
]
|
|
||||||
build-backend = "setuptools.build_meta"
|
build-backend = "setuptools.build_meta"
|
||||||
|
|
||||||
|
[project]
|
||||||
|
name = "ocrmypdf"
|
||||||
|
dynamic = ["version"]
|
||||||
|
description = "OCRmyPDF adds an OCR text layer to scanned PDF files, allowing them to be searched"
|
||||||
|
readme = "README.md"
|
||||||
|
license = { text = "MPL-2.0" }
|
||||||
|
requires-python = ">=3.10"
|
||||||
|
dependencies = [
|
||||||
|
"Pillow>=10.0.1",
|
||||||
|
"deprecation>=2.1.0",
|
||||||
|
"img2pdf>=0.5",
|
||||||
|
"packaging>=20",
|
||||||
|
"pdfminer.six>=20220319",
|
||||||
|
"pikepdf>=8.10.1",
|
||||||
|
"pluggy>=1",
|
||||||
|
"rich>=13",
|
||||||
|
]
|
||||||
|
authors = [{ name = "James R. Barlow", email = "james@purplerock.ca" }]
|
||||||
|
classifiers = [
|
||||||
|
"Development Status :: 5 - Production/Stable",
|
||||||
|
"Environment :: Console",
|
||||||
|
"Intended Audience :: End Users/Desktop",
|
||||||
|
"Intended Audience :: Science/Research",
|
||||||
|
"Intended Audience :: System Administrators",
|
||||||
|
"License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)",
|
||||||
|
"Operating System :: MacOS",
|
||||||
|
"Operating System :: Microsoft :: Windows",
|
||||||
|
"Operating System :: POSIX",
|
||||||
|
"Operating System :: POSIX :: BSD",
|
||||||
|
"Operating System :: POSIX :: Linux",
|
||||||
|
"Programming Language :: Python :: 3",
|
||||||
|
"Topic :: Scientific/Engineering :: Image Recognition",
|
||||||
|
"Topic :: Text Processing :: Indexing",
|
||||||
|
"Topic :: Text Processing :: Linguistic",
|
||||||
|
]
|
||||||
|
keywords = ["PDF", "OCR", "optical character recognition", "PDF/A", "scanning"]
|
||||||
|
|
||||||
|
[project.urls]
|
||||||
|
Documentation = "https://ocrmypdf.readthedocs.io/"
|
||||||
|
Source = "https://github.com/ocrmypdf/OCRmyPDF"
|
||||||
|
Tracker = "https://github.com/ocrmypdf/OCRmyPDF/issues"
|
||||||
|
|
||||||
|
[project.optional-dependencies]
|
||||||
|
docs = ["sphinx", "sphinx-issues", "sphinx-rtd-theme"]
|
||||||
|
extended_test = ["PyMuPDF>=1.19.1"]
|
||||||
|
test = [
|
||||||
|
"coverage[toml]>=6.2",
|
||||||
|
"hypothesis>=6.36.0",
|
||||||
|
"pytest>=6.2.5",
|
||||||
|
"pytest-cov>=3.0.0",
|
||||||
|
"pytest-xdist>=2.5.0",
|
||||||
|
"python-xmp-toolkit==2.0.1", # also requires apt-get install libexempi3
|
||||||
|
"reportlab>=3.6.8",
|
||||||
|
"types-Pillow",
|
||||||
|
"types-humanfriendly",
|
||||||
|
]
|
||||||
|
watcher = ["watchdog>=1.0.2", "typer[all]", "python-dotenv"]
|
||||||
|
webservice = ["Flask>=2.0.1"]
|
||||||
|
|
||||||
|
[project.scripts]
|
||||||
|
ocrmypdf = "ocrmypdf.__main__:run"
|
||||||
|
|
||||||
|
[tool.setuptools.package-data]
|
||||||
|
ocrmypdf = ["data/sRGB.icc", "py.typed"]
|
||||||
|
|
||||||
|
[tool.setuptools.packages.find]
|
||||||
|
where = ["src"]
|
||||||
|
namespaces = false
|
||||||
|
|
||||||
[tool.setuptools_scm]
|
[tool.setuptools_scm]
|
||||||
|
|
||||||
|
[tool.distutils.bdist_wheel]
|
||||||
|
python-tag = "py310"
|
||||||
|
|
||||||
[tool.black]
|
[tool.black]
|
||||||
line-length = 88
|
line-length = 88
|
||||||
target-version = ["py37", "py38"]
|
target-version = ["py310", "py311", "py312"]
|
||||||
skip-string-normalization = true
|
skip-string-normalization = true
|
||||||
include = '\.pyi?$'
|
include = '\.pyi?$'
|
||||||
exclude = '''
|
exclude = '''
|
||||||
@@ -34,7 +104,8 @@ exclude = '''
|
|||||||
[tool.coverage.run]
|
[tool.coverage.run]
|
||||||
branch = true
|
branch = true
|
||||||
parallel = true
|
parallel = true
|
||||||
concurrency = ["multiprocessing"]
|
concurrency = ["multiprocessing", "thread"]
|
||||||
|
sigterm = true
|
||||||
|
|
||||||
[tool.coverage.paths]
|
[tool.coverage.paths]
|
||||||
source = ["src/ocrmypdf"]
|
source = ["src/ocrmypdf"]
|
||||||
@@ -51,28 +122,7 @@ exclude_lines = [
|
|||||||
"if 0:",
|
"if 0:",
|
||||||
"if False:",
|
"if False:",
|
||||||
"if __name__ == .__main__.:",
|
"if __name__ == .__main__.:",
|
||||||
"if TYPE_CHECKING:"
|
"if TYPE_CHECKING:",
|
||||||
]
|
|
||||||
|
|
||||||
[tool.isort]
|
|
||||||
profile = "black"
|
|
||||||
known_first_party = "ocrmypdf"
|
|
||||||
known_third_party = [
|
|
||||||
"PIL",
|
|
||||||
"flask",
|
|
||||||
"img2pdf",
|
|
||||||
"ocrmypdf",
|
|
||||||
"pdfminer",
|
|
||||||
"pikepdf",
|
|
||||||
"pkg_resources",
|
|
||||||
"pluggy",
|
|
||||||
"pytest",
|
|
||||||
"reportlab",
|
|
||||||
"setuptools",
|
|
||||||
"sphinx_rtd_theme",
|
|
||||||
"tqdm",
|
|
||||||
"watchdog",
|
|
||||||
"werkzeug"
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[tool.pytest.ini_options]
|
[tool.pytest.ini_options]
|
||||||
@@ -95,11 +145,29 @@ module = [
|
|||||||
'reportlab.*',
|
'reportlab.*',
|
||||||
'fitz',
|
'fitz',
|
||||||
'libxmp.utils',
|
'libxmp.utils',
|
||||||
'importlib_metadata'
|
|
||||||
]
|
]
|
||||||
ignore_missing_imports = true
|
ignore_missing_imports = true
|
||||||
|
|
||||||
[tool.pylint.basic]
|
[tool.ruff]
|
||||||
good-names = ["i", "j", "k", "ex", "Run", "_", "e", "p", "im", "w", "h", "m", "x", "y", "a", "b", "fp", "n", "f", "s", "v", "q", "dx", "dy"]
|
select = [
|
||||||
logging-format-style = "old"
|
"D", # pydocstyle
|
||||||
disable = ["raw-checker-failed", "bad-inline-option", "locally-disabled", "file-ignored", "suppressed-message", "useless-suppression", "deprecated-pragma", "use-symbolic-message-instead", "logging-fstring-interpolation", "missing-function-docstring", "too-few-public-methods"]
|
"E", # pycodestyle
|
||||||
|
"W", # pycodestyle
|
||||||
|
"F", # pyflakes
|
||||||
|
"I001", # isort
|
||||||
|
"UP", # pyupgrade
|
||||||
|
]
|
||||||
|
target-version = "py310"
|
||||||
|
|
||||||
|
[tool.ruff.isort]
|
||||||
|
known-first-party = ["ocrmypdf"]
|
||||||
|
required-imports = ["from __future__ import annotations"]
|
||||||
|
|
||||||
|
[tool.ruff.pydocstyle]
|
||||||
|
convention = "google"
|
||||||
|
|
||||||
|
[tool.ruff.per-file-ignores]
|
||||||
|
"docs/conf.py" = ["D100", "D101", "D105"]
|
||||||
|
"tests/*.py" = ["D100", "D101", "D102", "D103", "D105"]
|
||||||
|
"misc/*.py" = ["D103", "D101", "D102"]
|
||||||
|
"src/ocrmypdf/builtin_plugins/*.py" = ["D103", "D102", "D105"]
|
||||||
|
|||||||
@@ -1,116 +0,0 @@
|
|||||||
[metadata]
|
|
||||||
name = ocrmypdf
|
|
||||||
description = OCRmyPDF adds an OCR text layer to scanned PDF files, allowing them to be searched
|
|
||||||
long_description = file: README.md
|
|
||||||
long_description_content_type = text/markdown
|
|
||||||
url = https://github.com/ocrmypdf/OCRmyPDF
|
|
||||||
author = James R. Barlow
|
|
||||||
author_email = james@purplerock.ca
|
|
||||||
license = MPL-2.0
|
|
||||||
license_file = LICENSE
|
|
||||||
license_files =
|
|
||||||
LICENSE
|
|
||||||
classifiers =
|
|
||||||
Development Status :: 5 - Production/Stable
|
|
||||||
Environment :: Console
|
|
||||||
Intended Audience :: End Users/Desktop
|
|
||||||
Intended Audience :: Science/Research
|
|
||||||
Intended Audience :: System Administrators
|
|
||||||
License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)
|
|
||||||
Operating System :: MacOS :: MacOS X
|
|
||||||
Operating System :: Microsoft :: Windows :: Windows 10
|
|
||||||
Operating System :: POSIX
|
|
||||||
Operating System :: POSIX :: BSD
|
|
||||||
Operating System :: POSIX :: Linux
|
|
||||||
Programming Language :: Python :: 3
|
|
||||||
Programming Language :: Python :: 3 :: Only
|
|
||||||
Programming Language :: Python :: 3.7
|
|
||||||
Programming Language :: Python :: 3.8
|
|
||||||
Programming Language :: Python :: 3.9
|
|
||||||
Programming Language :: Python :: 3.10
|
|
||||||
Topic :: Scientific/Engineering :: Image Recognition
|
|
||||||
Topic :: Text Processing :: Indexing
|
|
||||||
Topic :: Text Processing :: Linguistic
|
|
||||||
keywords =
|
|
||||||
PDF
|
|
||||||
OCR
|
|
||||||
optical character recognition
|
|
||||||
PDF/A
|
|
||||||
scanning
|
|
||||||
project_urls =
|
|
||||||
Documentation = https://ocrmypdf.readthedocs.io/
|
|
||||||
Source = https://github.com/ocrmypdf/OCRmyPDF
|
|
||||||
Tracker = https://github.com/ocrmypdf/OCRmyPDF/issues
|
|
||||||
|
|
||||||
[options]
|
|
||||||
packages = find:
|
|
||||||
install_requires =
|
|
||||||
Pillow>=8.2.0
|
|
||||||
coloredlogs>=14.0 # strictly optional
|
|
||||||
img2pdf>=0.3.0 # pure Python
|
|
||||||
packaging>=20
|
|
||||||
pdfminer.six!=20200720,>=20191110
|
|
||||||
pikepdf!=5.0.0,>=4.0.0
|
|
||||||
pluggy>=0.13.0
|
|
||||||
reportlab>=3.5.66
|
|
||||||
tqdm>=4
|
|
||||||
importlib-metadata>=4;python_version<'3.8' # until Python 3.8
|
|
||||||
importlib-resources>=5;python_version<'3.9' # until Python 3.9
|
|
||||||
typing-extensions>=4;python_version<'3.10'
|
|
||||||
python_requires = >=3.7
|
|
||||||
include_package_data = True
|
|
||||||
package_dir =
|
|
||||||
=src
|
|
||||||
platforms = any
|
|
||||||
setup_requires =
|
|
||||||
setuptools-scm
|
|
||||||
setuptools-scm-git-archive
|
|
||||||
zip_safe = False
|
|
||||||
|
|
||||||
[options.packages.find]
|
|
||||||
where = src
|
|
||||||
|
|
||||||
[options.entry_points]
|
|
||||||
console_scripts =
|
|
||||||
ocrmypdf = ocrmypdf.__main__:run
|
|
||||||
|
|
||||||
[options.extras_require]
|
|
||||||
docs =
|
|
||||||
sphinx
|
|
||||||
sphinx-issues
|
|
||||||
sphinx-rtd-theme
|
|
||||||
extended_test =
|
|
||||||
PyMuPDF==1.19.1
|
|
||||||
test =
|
|
||||||
coverage[toml]>=5
|
|
||||||
pytest>=6.0.0
|
|
||||||
pytest-cov>=2.11.1
|
|
||||||
pytest-xdist>=2.2.0
|
|
||||||
python-xmp-toolkit==2.0.1 # also requires apt-get install libexempi3
|
|
||||||
types-Pillow
|
|
||||||
types-humanfriendly
|
|
||||||
watcher =
|
|
||||||
watchdog>=1.0.2
|
|
||||||
webservice =
|
|
||||||
Flask>=1
|
|
||||||
|
|
||||||
[options.package_data]
|
|
||||||
ocrmypdf =
|
|
||||||
data/sRGB.icc
|
|
||||||
py.typed
|
|
||||||
|
|
||||||
[bdist_wheel]
|
|
||||||
python-tag = py37
|
|
||||||
|
|
||||||
[aliases]
|
|
||||||
test = pytest
|
|
||||||
|
|
||||||
[check-manifest]
|
|
||||||
ignore =
|
|
||||||
.github
|
|
||||||
|
|
||||||
[flake8]
|
|
||||||
ignore = D203,F401,W503,E501,E203,F841
|
|
||||||
exclude = .git,__pycache__,docs/conf.py,build,dist,.venv,.venvpp,.eggs,tmp,src/ocrmypdf/lib/
|
|
||||||
max-complexity = 10
|
|
||||||
max-line-length = 100
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
|
||||||
# SPDX-License-Identifier: MPL-2.0
|
|
||||||
|
|
||||||
"""setup.py to support older setuptools and pip."""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from setuptools import setup
|
|
||||||
|
|
||||||
setup()
|
|
||||||
+27
-5
@@ -1,8 +1,13 @@
|
|||||||
|
# SPDX-FileCopyrightText: 2022 Alexander Langanke
|
||||||
|
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
||||||
|
# SPDX-FileCopyrightText: 2023 林博仁(Buo-ren, Lin) <Buo.Ren.Lin@gmail.com>
|
||||||
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
|
|
||||||
name: ocrmypdf
|
name: ocrmypdf
|
||||||
title: OCRmyPDF
|
title: OCRmyPDF
|
||||||
base: core20
|
base: core22
|
||||||
version: git
|
version: git
|
||||||
summary: OCRmyPDF adds optical character recognition (OCR) to PDFs
|
summary: OCRmyPDF adds a searchable text layer to scanned PDF files
|
||||||
description: OCRmyPDF packaged for snap
|
description: OCRmyPDF packaged for snap
|
||||||
grade: stable
|
grade: stable
|
||||||
confinement: strict
|
confinement: strict
|
||||||
@@ -13,8 +18,8 @@ architectures: [amd64]
|
|||||||
|
|
||||||
environment:
|
environment:
|
||||||
TESSDATA_PREFIX: $SNAP/usr/share/tesseract-ocr/4.00/tessdata
|
TESSDATA_PREFIX: $SNAP/usr/share/tesseract-ocr/4.00/tessdata
|
||||||
GS_LIB: $SNAP/usr/share/ghostscript/9.50/Resource/Init
|
GS_LIB: $SNAP/usr/share/ghostscript/9.55/Resource/Init
|
||||||
GS_FONTPATH: $SNAP/usr/share/ghostscript/9.50/Resource/Font
|
GS_FONTPATH: $SNAP/usr/share/ghostscript/9.55/Resource/Font
|
||||||
LD_LIBRARY_PATH: $SNAP/usr/lib/x86_64-linux-gnu
|
LD_LIBRARY_PATH: $SNAP/usr/lib/x86_64-linux-gnu
|
||||||
|
|
||||||
apps:
|
apps:
|
||||||
@@ -41,9 +46,19 @@ parts:
|
|||||||
stage-packages:
|
stage-packages:
|
||||||
- lib32stdc++6
|
- lib32stdc++6
|
||||||
|
|
||||||
|
jbig2enc:
|
||||||
|
plugin: autotools
|
||||||
|
source: https://github.com/agl/jbig2enc.git
|
||||||
|
source-tag: "0.29"
|
||||||
|
build-packages:
|
||||||
|
- libleptonica-dev
|
||||||
|
|
||||||
ocrmypdf:
|
ocrmypdf:
|
||||||
plugin: python
|
plugin: python
|
||||||
source: https://github.com/ocrmypdf/OCRmyPDF.git
|
source: .
|
||||||
|
|
||||||
|
build-packages:
|
||||||
|
- python3-pip
|
||||||
|
|
||||||
stage-packages:
|
stage-packages:
|
||||||
- ghostscript
|
- ghostscript
|
||||||
@@ -66,7 +81,14 @@ parts:
|
|||||||
- setuptools
|
- setuptools
|
||||||
- tqdm
|
- tqdm
|
||||||
- pipe
|
- pipe
|
||||||
|
- wheel
|
||||||
|
|
||||||
override-build: |
|
override-build: |
|
||||||
|
pip3 install --user dephell[full]
|
||||||
|
$HOME/.local/bin/dephell deps convert \
|
||||||
|
--from-path pyproject.toml \
|
||||||
|
--from-format pyproject \
|
||||||
|
--to-path setup.py \
|
||||||
|
--to-format setuppy
|
||||||
snapcraftctl build
|
snapcraftctl build
|
||||||
ln -sf ../usr/lib/libsnapcraft-preload.so $SNAPCRAFT_PART_INSTALL/lib/libsnapcraft-preload.so
|
ln -sf ../usr/lib/libsnapcraft-preload.so $SNAPCRAFT_PART_INSTALL/lib/libsnapcraft-preload.so
|
||||||
|
|||||||
@@ -1,3 +1,6 @@
|
|||||||
|
<!-- SPDX-FileCopyrightText: 2022 James R. Barlow -->
|
||||||
|
<!-- SPDX-License-Identifier: CC-BY-SA-4.0 -->
|
||||||
|
|
||||||
# Release checklist
|
# Release checklist
|
||||||
|
|
||||||
## Patch release
|
## Patch release
|
||||||
@@ -14,11 +17,11 @@
|
|||||||
|
|
||||||
- Check README.md
|
- Check README.md
|
||||||
|
|
||||||
- Check setup.py
|
- Check pyproject.toml
|
||||||
|
|
||||||
- Are classifiers up to date?
|
- Are classifiers up to date?
|
||||||
- Is `python_requires` correct?
|
- Is `python_requires` correct?
|
||||||
- Python 3.6 is EOL on December 2021-12. Could drop support then.
|
- Is it to drop support for older Pythons?
|
||||||
- Can we tighten any `install_requires` dependencies?
|
- Can we tighten any `install_requires` dependencies?
|
||||||
|
|
||||||
- Search for old version shims we can remove
|
- Search for old version shims we can remove
|
||||||
|
|||||||
@@ -10,8 +10,15 @@ from pluggy import HookimplMarker as _HookimplMarker
|
|||||||
from ocrmypdf import helpers, hocrtransform, pdfa, pdfinfo
|
from ocrmypdf import helpers, hocrtransform, pdfa, pdfinfo
|
||||||
from ocrmypdf._concurrent import Executor
|
from ocrmypdf._concurrent import Executor
|
||||||
from ocrmypdf._jobcontext import PageContext, PdfContext
|
from ocrmypdf._jobcontext import PageContext, PdfContext
|
||||||
|
from ocrmypdf._pipelines._common import (
|
||||||
|
configure_debug_logging,
|
||||||
|
)
|
||||||
from ocrmypdf._version import PROGRAM_NAME, __version__
|
from ocrmypdf._version import PROGRAM_NAME, __version__
|
||||||
from ocrmypdf.api import Verbosity, configure_logging, ocr
|
from ocrmypdf.api import (
|
||||||
|
Verbosity,
|
||||||
|
configure_logging,
|
||||||
|
ocr,
|
||||||
|
)
|
||||||
from ocrmypdf.exceptions import (
|
from ocrmypdf.exceptions import (
|
||||||
BadArgsError,
|
BadArgsError,
|
||||||
DpiError,
|
DpiError,
|
||||||
@@ -21,7 +28,6 @@ from ocrmypdf.exceptions import (
|
|||||||
InputFileError,
|
InputFileError,
|
||||||
MissingDependencyError,
|
MissingDependencyError,
|
||||||
OutputFileAccessError,
|
OutputFileAccessError,
|
||||||
PdfMergeFailedError,
|
|
||||||
PriorOcrFoundError,
|
PriorOcrFoundError,
|
||||||
SubprocessOutputError,
|
SubprocessOutputError,
|
||||||
TesseractConfigError,
|
TesseractConfigError,
|
||||||
@@ -30,3 +36,35 @@ from ocrmypdf.exceptions import (
|
|||||||
from ocrmypdf.pluginspec import OcrEngine, OrientationConfidence
|
from ocrmypdf.pluginspec import OcrEngine, OrientationConfidence
|
||||||
|
|
||||||
hookimpl = _HookimplMarker('ocrmypdf')
|
hookimpl = _HookimplMarker('ocrmypdf')
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
'__version__',
|
||||||
|
'BadArgsError',
|
||||||
|
'configure_debug_logging',
|
||||||
|
'configure_logging',
|
||||||
|
'DpiError',
|
||||||
|
'EncryptedPdfError',
|
||||||
|
'Executor',
|
||||||
|
'ExitCode',
|
||||||
|
'ExitCodeException',
|
||||||
|
'helpers',
|
||||||
|
'hocrtransform',
|
||||||
|
'hookimpl',
|
||||||
|
'InputFileError',
|
||||||
|
'MissingDependencyError',
|
||||||
|
'ocr',
|
||||||
|
'OcrEngine',
|
||||||
|
'OrientationConfidence',
|
||||||
|
'OutputFileAccessError',
|
||||||
|
'PageContext',
|
||||||
|
'pdfa',
|
||||||
|
'PdfContext',
|
||||||
|
'pdfinfo',
|
||||||
|
'PriorOcrFoundError',
|
||||||
|
'PROGRAM_NAME',
|
||||||
|
'SubprocessOutputError',
|
||||||
|
'TesseractConfigError',
|
||||||
|
'UnsupportedImageFormatError',
|
||||||
|
'Verbosity',
|
||||||
|
]
|
||||||
|
|||||||
@@ -7,15 +7,15 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
import multiprocessing
|
||||||
import os
|
import os
|
||||||
import signal
|
import signal
|
||||||
import sys
|
import sys
|
||||||
from contextlib import suppress
|
from contextlib import suppress
|
||||||
from multiprocessing import set_start_method
|
|
||||||
|
|
||||||
from ocrmypdf import __version__
|
from ocrmypdf import __version__
|
||||||
|
from ocrmypdf._pipelines.ocr import run_pipeline_cli
|
||||||
from ocrmypdf._plugin_manager import get_parser_options_plugins
|
from ocrmypdf._plugin_manager import get_parser_options_plugins
|
||||||
from ocrmypdf._sync import run_pipeline
|
|
||||||
from ocrmypdf._validation import check_options
|
from ocrmypdf._validation import check_options
|
||||||
from ocrmypdf.api import Verbosity, configure_logging
|
from ocrmypdf.api import Verbosity, configure_logging
|
||||||
from ocrmypdf.exceptions import (
|
from ocrmypdf.exceptions import (
|
||||||
@@ -29,10 +29,16 @@ log = logging.getLogger('ocrmypdf')
|
|||||||
|
|
||||||
|
|
||||||
def sigbus(*args):
|
def sigbus(*args):
|
||||||
|
"""Handle SIGBUS signals.
|
||||||
|
|
||||||
|
pikepdf, depending on configuration, may use mmap so SIGBUS is a
|
||||||
|
possibility.
|
||||||
|
"""
|
||||||
raise InputFileError("Lost access to the input file")
|
raise InputFileError("Lost access to the input file")
|
||||||
|
|
||||||
|
|
||||||
def run(args=None):
|
def run(args=None):
|
||||||
|
"""Run the ocrmypdf command line interface."""
|
||||||
_parser, options, plugin_manager = get_parser_options_plugins(args=args)
|
_parser, options, plugin_manager = get_parser_options_plugins(args=args)
|
||||||
|
|
||||||
with suppress(AttributeError, PermissionError):
|
with suppress(AttributeError, PermissionError):
|
||||||
@@ -66,11 +72,12 @@ def run(args=None):
|
|||||||
with suppress(AttributeError, OSError):
|
with suppress(AttributeError, OSError):
|
||||||
signal.signal(signal.SIGBUS, sigbus)
|
signal.signal(signal.SIGBUS, sigbus)
|
||||||
|
|
||||||
result = run_pipeline(options=options, plugin_manager=plugin_manager)
|
result = run_pipeline_cli(options=options, plugin_manager=plugin_manager)
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
if sys.platform == 'darwin' and sys.version_info < (3, 8):
|
multiprocessing.freeze_support()
|
||||||
set_start_method('spawn') # see python bpo-33725
|
if os.name == 'posix':
|
||||||
|
multiprocessing.set_start_method('forkserver')
|
||||||
sys.exit(run())
|
sys.exit(run())
|
||||||
|
|||||||
+19
-28
@@ -7,27 +7,20 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import threading
|
import threading
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
from typing import Callable, Iterable
|
from collections.abc import Iterable
|
||||||
|
from typing import Any, Callable, TypeVar
|
||||||
|
|
||||||
|
from ocrmypdf._progressbar import NullProgressBar, ProgressBar
|
||||||
|
|
||||||
|
T = TypeVar('T')
|
||||||
|
|
||||||
|
|
||||||
def _task_noop(*_args, **_kwargs):
|
def _task_noop(*_args, **_kwargs):
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|
||||||
class NullProgressBar:
|
def _task_finished_noop(_result: Any, pbar: ProgressBar):
|
||||||
"""Progress bar API that takes no actions."""
|
pbar.update()
|
||||||
|
|
||||||
def __init__(self, **kwargs):
|
|
||||||
pass
|
|
||||||
|
|
||||||
def __enter__(self):
|
|
||||||
return self
|
|
||||||
|
|
||||||
def __exit__(self, exc_type, exc_value, traceback):
|
|
||||||
return False
|
|
||||||
|
|
||||||
def update(self, _arg=None):
|
|
||||||
return
|
|
||||||
|
|
||||||
|
|
||||||
class Executor(ABC):
|
class Executor(ABC):
|
||||||
@@ -45,14 +38,13 @@ class Executor(ABC):
|
|||||||
*,
|
*,
|
||||||
use_threads: bool,
|
use_threads: bool,
|
||||||
max_workers: int,
|
max_workers: int,
|
||||||
tqdm_kwargs: dict,
|
progress_kwargs: dict,
|
||||||
worker_initializer: Callable | None = None,
|
worker_initializer: Callable | None = None,
|
||||||
task: Callable | None = None,
|
task: Callable[..., T] | None = None,
|
||||||
task_arguments: Iterable | None = None,
|
task_arguments: Iterable | None = None,
|
||||||
task_finished: Callable | None = None,
|
task_finished: Callable[[T, ProgressBar], None] | None = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""
|
"""Set up parallel execution and progress reporting.
|
||||||
Set up parallel execution and progress reporting.
|
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
use_threads: If ``False``, the workload is the sort that will benefit from
|
use_threads: If ``False``, the workload is the sort that will benefit from
|
||||||
@@ -60,7 +52,7 @@ class Executor(ABC):
|
|||||||
heavily, and parallelizing it with threads is not expected to be
|
heavily, and parallelizing it with threads is not expected to be
|
||||||
performant).
|
performant).
|
||||||
max_workers: The maximum number of workers that should be run.
|
max_workers: The maximum number of workers that should be run.
|
||||||
tdqm_kwargs: Arguments to set up the progress bar.
|
progress_kwargs: Arguments to set up the progress bar.
|
||||||
worker_initializer: Called when a worker is initialized, in the worker's
|
worker_initializer: Called when a worker is initialized, in the worker's
|
||||||
execution context. If the child workers are processes, it must be
|
execution context. If the child workers are processes, it must be
|
||||||
possible to marshall/pickle the worker initializer.
|
possible to marshall/pickle the worker initializer.
|
||||||
@@ -73,13 +65,12 @@ class Executor(ABC):
|
|||||||
task. This runs in the parent's context, but the parameters must be
|
task. This runs in the parent's context, but the parameters must be
|
||||||
marshallable to the worker.
|
marshallable to the worker.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if not task_arguments:
|
if not task_arguments:
|
||||||
return # Nothing to do!
|
return # Nothing to do!
|
||||||
if not worker_initializer:
|
if not worker_initializer:
|
||||||
worker_initializer = _task_noop
|
worker_initializer = _task_noop
|
||||||
if not task_finished:
|
if not task_finished:
|
||||||
task_finished = _task_noop
|
task_finished = _task_finished_noop
|
||||||
if not task:
|
if not task:
|
||||||
task = _task_noop
|
task = _task_noop
|
||||||
|
|
||||||
@@ -87,7 +78,7 @@ class Executor(ABC):
|
|||||||
self._execute(
|
self._execute(
|
||||||
use_threads=use_threads,
|
use_threads=use_threads,
|
||||||
max_workers=max_workers,
|
max_workers=max_workers,
|
||||||
tqdm_kwargs=tqdm_kwargs,
|
progress_kwargs=progress_kwargs,
|
||||||
worker_initializer=worker_initializer,
|
worker_initializer=worker_initializer,
|
||||||
task=task,
|
task=task,
|
||||||
task_arguments=task_arguments,
|
task_arguments=task_arguments,
|
||||||
@@ -100,7 +91,7 @@ class Executor(ABC):
|
|||||||
*,
|
*,
|
||||||
use_threads: bool,
|
use_threads: bool,
|
||||||
max_workers: int,
|
max_workers: int,
|
||||||
tqdm_kwargs: dict,
|
progress_kwargs: dict,
|
||||||
worker_initializer: Callable,
|
worker_initializer: Callable,
|
||||||
task: Callable,
|
task: Callable,
|
||||||
task_arguments: Iterable,
|
task_arguments: Iterable,
|
||||||
@@ -126,13 +117,13 @@ class SerialExecutor(Executor):
|
|||||||
*,
|
*,
|
||||||
use_threads: bool,
|
use_threads: bool,
|
||||||
max_workers: int,
|
max_workers: int,
|
||||||
tqdm_kwargs: dict,
|
progress_kwargs: dict,
|
||||||
worker_initializer: Callable,
|
worker_initializer: Callable,
|
||||||
task: Callable,
|
task: Callable,
|
||||||
task_arguments: Iterable,
|
task_arguments: Iterable,
|
||||||
task_finished: Callable,
|
task_finished: Callable,
|
||||||
): # pylint: disable=unused-argument
|
): # pylint: disable=unused-argument
|
||||||
with self.pbar_class(**tqdm_kwargs) as pbar:
|
with self.pbar_class(**progress_kwargs) as pbar:
|
||||||
for args in task_arguments:
|
for args in task_arguments:
|
||||||
result = task(args)
|
result = task(*args)
|
||||||
task_finished(result, pbar)
|
task_finished(result, pbar)
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
||||||
# SPDX-License-Identifier: MPL-2.0
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
|
|
||||||
"""Manage third party executables"""
|
"""Manage third party executables."""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|||||||
@@ -1,65 +1,75 @@
|
|||||||
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
||||||
# SPDX-License-Identifier: MPL-2.0
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
|
|
||||||
"""Interface to Ghostscript executable"""
|
"""Interface to Ghostscript executable."""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import sys
|
from collections import deque
|
||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
from os import fspath
|
from os import fspath
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from subprocess import PIPE, CalledProcessError
|
from subprocess import PIPE, CalledProcessError
|
||||||
|
|
||||||
|
from packaging.version import Version
|
||||||
from PIL import Image, UnidentifiedImageError
|
from PIL import Image, UnidentifiedImageError
|
||||||
|
|
||||||
from ocrmypdf.exceptions import SubprocessOutputError
|
from ocrmypdf.exceptions import ColorConversionNeededError, SubprocessOutputError
|
||||||
from ocrmypdf.helpers import Resolution
|
from ocrmypdf.helpers import Resolution
|
||||||
from ocrmypdf.subprocess import get_version, run, run_polling_stderr
|
from ocrmypdf.subprocess import get_version, run, run_polling_stderr
|
||||||
|
|
||||||
# Remove this workaround when we require Pillow >= 10
|
COLOR_CONVERSION_STRATEGIES = frozenset(
|
||||||
try:
|
[
|
||||||
Transpose = Image.Transpose # type: ignore
|
'CMYK',
|
||||||
except AttributeError:
|
'Gray',
|
||||||
# Pillow 9 shim
|
'LeaveColorUnchanged',
|
||||||
Transpose = Image # type: ignore
|
'RGB',
|
||||||
|
'UseDeviceIndependentColor',
|
||||||
|
]
|
||||||
|
)
|
||||||
|
# Ghostscript executable - gswin32c is not supported
|
||||||
|
GS = 'gswin64c' if os.name == 'nt' else 'gs'
|
||||||
|
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
# Most reliable what to get the bitness of Python interpreter, according to Python docs
|
|
||||||
_IS_64BIT = sys.maxsize > 2**32
|
|
||||||
|
|
||||||
_GSWIN = None
|
class DuplicateFilter(logging.Filter):
|
||||||
if os.name == 'nt':
|
"""Filter out duplicate log messages.
|
||||||
if _IS_64BIT:
|
|
||||||
_GSWIN = 'gswin64c'
|
|
||||||
else:
|
|
||||||
_GSWIN = 'gswin32c'
|
|
||||||
|
|
||||||
GS = _GSWIN if _GSWIN else 'gs'
|
A context window of default 5 messages is used to determine if a message is a
|
||||||
del _GSWIN
|
duplicate. This is because some Ghostscript messages are word wrapped.
|
||||||
|
|
||||||
|
|
||||||
def version():
|
|
||||||
return get_version(GS)
|
|
||||||
|
|
||||||
|
|
||||||
def jpeg_passthrough_available() -> bool:
|
|
||||||
"""Returns True if the installed version of Ghostscript supports JPEG passthru
|
|
||||||
|
|
||||||
Prior to 9.23, Ghostscript decoded and re-encoded JPEGs internally. In 9.23
|
|
||||||
it gained the ability to keep JPEGs unmodified. However, the 9.23
|
|
||||||
implementation was buggy and would deletes the last two bytes of images in
|
|
||||||
some cases, as reported here.
|
|
||||||
https://bugs.ghostscript.com/show_bug.cgi?id=699216
|
|
||||||
|
|
||||||
The issue was fixed for 9.24, hence that is the first version we consider
|
|
||||||
the feature available. (Ghostscript 9.24 has its own problems is blacklisted.)
|
|
||||||
"""
|
"""
|
||||||
return version() >= '9.24'
|
|
||||||
|
def __init__(self, logger: logging.Logger, context_window=5):
|
||||||
|
self.window: deque[str] = deque([], maxlen=context_window)
|
||||||
|
self.logger = logger
|
||||||
|
self.levelno = logging.DEBUG
|
||||||
|
self.count = 0
|
||||||
|
|
||||||
|
def filter(self, record):
|
||||||
|
if record.msg in self.window:
|
||||||
|
self.count += 1
|
||||||
|
self.levelno = record.levelno
|
||||||
|
return False
|
||||||
|
else:
|
||||||
|
if self.count >= 1:
|
||||||
|
rep_msg = f"(suppressed {self.count} repeated lines)"
|
||||||
|
self.count = 0 # Avoid infinite recursion
|
||||||
|
self.logger.log(self.levelno, rep_msg)
|
||||||
|
self.window.clear()
|
||||||
|
self.window.append(record.msg)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
log.addFilter(DuplicateFilter(log))
|
||||||
|
|
||||||
|
|
||||||
|
def version() -> Version:
|
||||||
|
return Version(get_version(GS))
|
||||||
|
|
||||||
|
|
||||||
def _gs_error_reported(stream) -> bool:
|
def _gs_error_reported(stream) -> bool:
|
||||||
@@ -67,6 +77,20 @@ def _gs_error_reported(stream) -> bool:
|
|||||||
return bool(match)
|
return bool(match)
|
||||||
|
|
||||||
|
|
||||||
|
def _gs_devicen_reported(stream) -> bool:
|
||||||
|
"""Did Ghostscript warn about a DeviceN with inappropriate alternate?
|
||||||
|
|
||||||
|
If so, we need the user to select a color conversion, or the resulting PDF will
|
||||||
|
not present correctly in some PDF viewers.
|
||||||
|
"""
|
||||||
|
match = re.search(
|
||||||
|
r'DeviceN.*inappropriate alternate',
|
||||||
|
stream,
|
||||||
|
flags=re.IGNORECASE | re.MULTILINE,
|
||||||
|
)
|
||||||
|
return bool(match)
|
||||||
|
|
||||||
|
|
||||||
def rasterize_pdf(
|
def rasterize_pdf(
|
||||||
input_file: os.PathLike,
|
input_file: os.PathLike,
|
||||||
output_file: os.PathLike,
|
output_file: os.PathLike,
|
||||||
@@ -77,6 +101,7 @@ def rasterize_pdf(
|
|||||||
page_dpi: Resolution | None = None,
|
page_dpi: Resolution | None = None,
|
||||||
rotation: int | None = None,
|
rotation: int | None = None,
|
||||||
filter_vector: bool = False,
|
filter_vector: bool = False,
|
||||||
|
stop_on_error: bool = False,
|
||||||
):
|
):
|
||||||
"""Rasterize one page of a PDF at resolution raster_dpi in canvas units."""
|
"""Rasterize one page of a PDF at resolution raster_dpi in canvas units."""
|
||||||
raster_dpi = raster_dpi.round(6)
|
raster_dpi = raster_dpi.round(6)
|
||||||
@@ -97,6 +122,7 @@ def rasterize_pdf(
|
|||||||
f'-r{raster_dpi.x:f}x{raster_dpi.y:f}',
|
f'-r{raster_dpi.x:f}x{raster_dpi.y:f}',
|
||||||
]
|
]
|
||||||
+ (['-dFILTERVECTOR'] if filter_vector else [])
|
+ (['-dFILTERVECTOR'] if filter_vector else [])
|
||||||
|
+ (['-dPDFSTOPONERROR'] if stop_on_error else [])
|
||||||
+ [
|
+ [
|
||||||
'-o',
|
'-o',
|
||||||
'-',
|
'-',
|
||||||
@@ -124,11 +150,11 @@ def rasterize_pdf(
|
|||||||
# rotation is a clockwise angle and Image.ROTATE_* is
|
# rotation is a clockwise angle and Image.ROTATE_* is
|
||||||
# counterclockwise so this cancels out the rotation
|
# counterclockwise so this cancels out the rotation
|
||||||
if rotation == 90:
|
if rotation == 90:
|
||||||
im = im.transpose(Transpose.ROTATE_90)
|
im = im.transpose(Image.Transpose.ROTATE_90)
|
||||||
elif rotation == 180:
|
elif rotation == 180:
|
||||||
im = im.transpose(Transpose.ROTATE_180)
|
im = im.transpose(Image.Transpose.ROTATE_180)
|
||||||
elif rotation == 270:
|
elif rotation == 270:
|
||||||
im = im.transpose(Transpose.ROTATE_270)
|
im = im.transpose(Image.Transpose.ROTATE_270)
|
||||||
if rotation % 180 == 90:
|
if rotation % 180 == 90:
|
||||||
page_dpi = page_dpi.flip_axis()
|
page_dpi = page_dpi.flip_axis()
|
||||||
im.save(fspath(output_file), dpi=page_dpi)
|
im.save(fspath(output_file), dpi=page_dpi)
|
||||||
@@ -172,9 +198,11 @@ def generate_pdfa(
|
|||||||
output_file: os.PathLike,
|
output_file: os.PathLike,
|
||||||
*,
|
*,
|
||||||
compression: str,
|
compression: str,
|
||||||
|
color_conversion_strategy: str,
|
||||||
pdf_version: str = '1.5',
|
pdf_version: str = '1.5',
|
||||||
pdfa_part: str = '2',
|
pdfa_part: str = '2',
|
||||||
progressbar_class=None,
|
progressbar_class=None,
|
||||||
|
stop_on_error: bool = False,
|
||||||
):
|
):
|
||||||
# Ghostscript's compression is all or nothing. We can either force all images
|
# Ghostscript's compression is all or nothing. We can either force all images
|
||||||
# to JPEG, force all to Flate/PNG, or let it decide how to encode the images.
|
# to JPEG, force all to Flate/PNG, or let it decide how to encode the images.
|
||||||
@@ -200,23 +228,16 @@ def generate_pdfa(
|
|||||||
"-dAutoFilterGrayImages=true",
|
"-dAutoFilterGrayImages=true",
|
||||||
]
|
]
|
||||||
|
|
||||||
strategy = 'LeaveColorUnchanged'
|
|
||||||
# Older versions of Ghostscript expect a leading slash in
|
|
||||||
# sColorConversionStrategy, newer ones should not have it. See Ghostscript
|
|
||||||
# git commit fe1c025d.
|
|
||||||
gs_version = version()
|
gs_version = version()
|
||||||
strategy = ('/' + strategy) if gs_version < '9.19' else strategy
|
if gs_version == Version('9.56.0'):
|
||||||
|
# 9.56.0 breaks our OCR, should be fixed in 9.56.1
|
||||||
if gs_version == '9.23':
|
# https://bugs.ghostscript.com/show_bug.cgi?id=705187
|
||||||
# 9.23: added JPEG passthrough as a new feature, but with a bug that
|
|
||||||
# incorrectly formats some images. Fixed as of 9.24. So we disable this
|
|
||||||
# feature for 9.23.
|
|
||||||
# https://bugs.ghostscript.com/show_bug.cgi?id=699216
|
|
||||||
compression_args.append('-dPassThroughJPEGImages=false')
|
|
||||||
elif gs_version == '9.56.0':
|
|
||||||
# 9.56.0 breaks our OCR...?
|
|
||||||
compression_args.append('-dNEWPDF=false')
|
compression_args.append('-dNEWPDF=false')
|
||||||
|
|
||||||
|
if os.name == 'nt':
|
||||||
|
# Windows has lots of fatal "permission denied" errors
|
||||||
|
stop_on_error = False
|
||||||
|
|
||||||
# nb no need to specify ProcessColorModel when ColorConversionStrategy
|
# nb no need to specify ProcessColorModel when ColorConversionStrategy
|
||||||
# is set; see:
|
# is set; see:
|
||||||
# https://bugs.ghostscript.com/show_bug.cgi?id=699392
|
# https://bugs.ghostscript.com/show_bug.cgi?id=699392
|
||||||
@@ -226,15 +247,16 @@ def generate_pdfa(
|
|||||||
"-dBATCH",
|
"-dBATCH",
|
||||||
"-dNOPAUSE",
|
"-dNOPAUSE",
|
||||||
"-dSAFER",
|
"-dSAFER",
|
||||||
"-dCompatibilityLevel=" + str(pdf_version),
|
f"-dCompatibilityLevel={str(pdf_version)}",
|
||||||
"-sDEVICE=pdfwrite",
|
"-sDEVICE=pdfwrite",
|
||||||
"-dAutoRotatePages=/None",
|
"-dAutoRotatePages=/None",
|
||||||
"-sColorConversionStrategy=" + strategy,
|
f"-sColorConversionStrategy={color_conversion_strategy}",
|
||||||
]
|
]
|
||||||
|
+ (['-dPDFSTOPONERROR'] if stop_on_error else [])
|
||||||
+ compression_args
|
+ compression_args
|
||||||
+ [
|
+ [
|
||||||
"-dJPEGQ=95",
|
"-dJPEGQ=95",
|
||||||
"-dPDFA=" + pdfa_part,
|
f"-dPDFA={pdfa_part}",
|
||||||
"-dPDFACompatibilityPolicy=1",
|
"-dPDFACompatibilityPolicy=1",
|
||||||
"-o",
|
"-o",
|
||||||
"-",
|
"-",
|
||||||
@@ -242,7 +264,6 @@ def generate_pdfa(
|
|||||||
]
|
]
|
||||||
)
|
)
|
||||||
args_gs.extend(fspath(s) for s in pdf_pages) # Stringify Path objs
|
args_gs.extend(fspath(s) for s in pdf_pages) # Stringify Path objs
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with Path(output_file).open('wb') as output:
|
with Path(output_file).open('wb') as output:
|
||||||
p = run_polling_stderr(
|
p = run_polling_stderr(
|
||||||
@@ -265,14 +286,11 @@ def generate_pdfa(
|
|||||||
# If there is an error we log the whole stderr, except for filtering
|
# If there is an error we log the whole stderr, except for filtering
|
||||||
# duplicates.
|
# duplicates.
|
||||||
if _gs_error_reported(stderr):
|
if _gs_error_reported(stderr):
|
||||||
last_part = None
|
# Ghostscript outputs the pattern **** Error: .... frequently.
|
||||||
repcount = 0
|
# Occasionally the error message is spammed many times. We filter
|
||||||
|
# out duplicates of this message using the filter above. We use
|
||||||
|
# the **** pattern to split the stderr into parts.
|
||||||
for part in stderr.split('****'):
|
for part in stderr.split('****'):
|
||||||
if part != last_part:
|
log.error(part)
|
||||||
if repcount > 1:
|
if _gs_devicen_reported(stderr):
|
||||||
log.error(f"(previous error message repeated {repcount} times)")
|
raise ColorConversionNeededError()
|
||||||
repcount = 0
|
|
||||||
log.error(part)
|
|
||||||
else:
|
|
||||||
repcount += 1
|
|
||||||
last_part = part
|
|
||||||
|
|||||||
@@ -1,18 +1,20 @@
|
|||||||
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
||||||
# SPDX-License-Identifier: MPL-2.0
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
|
|
||||||
"""Interface to jbig2 executable"""
|
"""Interface to jbig2 executable."""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from subprocess import PIPE
|
from subprocess import PIPE
|
||||||
|
|
||||||
|
from packaging.version import Version
|
||||||
|
|
||||||
from ocrmypdf.exceptions import MissingDependencyError
|
from ocrmypdf.exceptions import MissingDependencyError
|
||||||
from ocrmypdf.subprocess import get_version, run
|
from ocrmypdf.subprocess import get_version, run
|
||||||
|
|
||||||
|
|
||||||
def version():
|
def version() -> Version:
|
||||||
return get_version('jbig2', regex=r'jbig2enc (\d+(\.\d+)*).*')
|
return Version(get_version('jbig2', regex=r'jbig2enc (\d+(\.\d+)*).*'))
|
||||||
|
|
||||||
|
|
||||||
def available():
|
def available():
|
||||||
@@ -23,15 +25,17 @@ def available():
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
def convert_group(*, cwd, infiles, out_prefix):
|
def convert_group(cwd, infiles, out_prefix, threshold):
|
||||||
args = [
|
args = [
|
||||||
'jbig2',
|
'jbig2',
|
||||||
'-b',
|
'-b',
|
||||||
out_prefix,
|
out_prefix,
|
||||||
'-s', # symbol mode (lossy)
|
'--symbol-mode', # symbol mode (lossy)
|
||||||
|
'-t',
|
||||||
|
str(threshold), # threshold
|
||||||
# '-r', # refinement mode (lossless symbol mode, currently disabled in
|
# '-r', # refinement mode (lossless symbol mode, currently disabled in
|
||||||
# jbig2)
|
# jbig2)
|
||||||
'-p',
|
'--pdf',
|
||||||
]
|
]
|
||||||
args.extend(infiles)
|
args.extend(infiles)
|
||||||
proc = run(args, cwd=cwd, stdout=PIPE, stderr=PIPE)
|
proc = run(args, cwd=cwd, stdout=PIPE, stderr=PIPE)
|
||||||
@@ -39,17 +43,9 @@ def convert_group(*, cwd, infiles, out_prefix):
|
|||||||
return proc
|
return proc
|
||||||
|
|
||||||
|
|
||||||
def convert_group_mp(args):
|
def convert_single(cwd, infile, outfile, threshold):
|
||||||
return convert_group(cwd=args[0], infiles=args[1], out_prefix=args[2])
|
args = ['jbig2', '--pdf', '-t', str(threshold), infile]
|
||||||
|
|
||||||
|
|
||||||
def convert_single(*, cwd, infile, outfile):
|
|
||||||
args = ['jbig2', '-p', infile]
|
|
||||||
with open(outfile, 'wb') as fstdout:
|
with open(outfile, 'wb') as fstdout:
|
||||||
proc = run(args, cwd=cwd, stdout=fstdout, stderr=PIPE)
|
proc = run(args, cwd=cwd, stdout=fstdout, stderr=PIPE)
|
||||||
proc.check_returncode()
|
proc.check_returncode()
|
||||||
return proc
|
return proc
|
||||||
|
|
||||||
|
|
||||||
def convert_single_mp(args):
|
|
||||||
return convert_single(cwd=args[0], infile=args[1], outfile=args[2])
|
|
||||||
|
|||||||
@@ -1,23 +1,21 @@
|
|||||||
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
||||||
# SPDX-License-Identifier: MPL-2.0
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
|
|
||||||
"""Interface to pngquant executable"""
|
"""Interface to pngquant executable."""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from contextlib import contextmanager
|
|
||||||
from io import BytesIO
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from subprocess import PIPE
|
from subprocess import PIPE
|
||||||
|
|
||||||
from PIL import Image
|
from packaging.version import Version
|
||||||
|
|
||||||
from ocrmypdf.exceptions import MissingDependencyError
|
from ocrmypdf.exceptions import MissingDependencyError
|
||||||
from ocrmypdf.subprocess import get_version, run
|
from ocrmypdf.subprocess import get_version, run
|
||||||
|
|
||||||
|
|
||||||
def version():
|
def version() -> Version:
|
||||||
return get_version('pngquant', regex=r'(\d+(\.\d+)*).*')
|
return Version(get_version('pngquant', regex=r'(\d+(\.\d+)*).*'))
|
||||||
|
|
||||||
|
|
||||||
def available():
|
def available():
|
||||||
@@ -28,21 +26,16 @@ def available():
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
@contextmanager
|
|
||||||
def input_as_png(input_file: Path):
|
|
||||||
if not input_file.name.endswith('.png'):
|
|
||||||
with Image.open(input_file) as im:
|
|
||||||
bio = BytesIO()
|
|
||||||
im.save(bio, format='png')
|
|
||||||
bio.seek(0)
|
|
||||||
yield bio
|
|
||||||
else:
|
|
||||||
with open(input_file, 'rb') as f:
|
|
||||||
yield f
|
|
||||||
|
|
||||||
|
|
||||||
def quantize(input_file: Path, output_file: Path, quality_min: int, quality_max: int):
|
def quantize(input_file: Path, output_file: Path, quality_min: int, quality_max: int):
|
||||||
with input_as_png(input_file) as input_stream:
|
"""Quantize a PNG image using pngquant.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
input_file: Input PNG image
|
||||||
|
output_file: Output PNG image
|
||||||
|
quality_min: Minimum quality to use
|
||||||
|
quality_max: Maximum quality to use
|
||||||
|
"""
|
||||||
|
with open(input_file, 'rb') as input_stream:
|
||||||
args = [
|
args = [
|
||||||
'pngquant',
|
'pngquant',
|
||||||
'--force',
|
'--force',
|
||||||
@@ -57,7 +50,3 @@ def quantize(input_file: Path, output_file: Path, quality_min: int, quality_max:
|
|||||||
if result.returncode == 0:
|
if result.returncode == 0:
|
||||||
# input_file could be the same as output_file, so we defer the write
|
# input_file could be the same as output_file, so we defer the write
|
||||||
output_file.write_bytes(result.stdout)
|
output_file.write_bytes(result.stdout)
|
||||||
|
|
||||||
|
|
||||||
def quantize_mp(args):
|
|
||||||
return quantize(*args)
|
|
||||||
|
|||||||
@@ -1,19 +1,19 @@
|
|||||||
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
||||||
# SPDX-License-Identifier: MPL-2.0
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
|
|
||||||
"""Interface to Tesseract executable"""
|
"""Interface to Tesseract executable."""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
import re
|
import re
|
||||||
|
from contextlib import suppress
|
||||||
from math import pi
|
from math import pi
|
||||||
from os import fspath
|
from os import fspath
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from subprocess import PIPE, STDOUT, CalledProcessError, TimeoutExpired
|
from subprocess import PIPE, STDOUT, CalledProcessError, TimeoutExpired
|
||||||
|
|
||||||
from packaging.version import Version
|
from packaging.version import Version
|
||||||
from PIL import Image
|
|
||||||
|
|
||||||
from ocrmypdf.exceptions import (
|
from ocrmypdf.exceptions import (
|
||||||
MissingDependencyError,
|
MissingDependencyError,
|
||||||
@@ -26,23 +26,6 @@ from ocrmypdf.subprocess import get_version, run
|
|||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
HOCR_TEMPLATE = """<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
|
|
||||||
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
|
||||||
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
|
|
||||||
<head>
|
|
||||||
<title></title>
|
|
||||||
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
|
|
||||||
<meta name='ocr-system' content='tesseract 4.0.0' />
|
|
||||||
<meta name='ocr-capabilities' content='ocr_page ocr_carea ocr_par ocr_line ocrx_word ocrp_wconf'/>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<div class='ocr_page' id='page_1' title='image "_blank.png"; bbox 0 0 {0} {1}; ppageno 0'>
|
|
||||||
</div>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
"""
|
|
||||||
|
|
||||||
TESSERACT_THRESHOLDING_METHODS: dict[str, int] = {
|
TESSERACT_THRESHOLDING_METHODS: dict[str, int] = {
|
||||||
'auto': 0,
|
'auto': 0,
|
||||||
'otsu': 0,
|
'otsu': 0,
|
||||||
@@ -52,7 +35,7 @@ TESSERACT_THRESHOLDING_METHODS: dict[str, int] = {
|
|||||||
|
|
||||||
|
|
||||||
class TesseractLoggerAdapter(logging.LoggerAdapter):
|
class TesseractLoggerAdapter(logging.LoggerAdapter):
|
||||||
"Prepend [tesseract] to messages emitted from tesseract"
|
"""Prepend [tesseract] to messages emitted from tesseract."""
|
||||||
|
|
||||||
def process(self, msg, kwargs):
|
def process(self, msg, kwargs):
|
||||||
kwargs['extra'] = self.extra
|
kwargs['extra'] = self.extra
|
||||||
@@ -104,28 +87,20 @@ TESSERACT_VERSION_PATTERN = r"""
|
|||||||
|
|
||||||
|
|
||||||
class TesseractVersion(Version):
|
class TesseractVersion(Version):
|
||||||
"Modify standard packaging.Version regex to support Tesseract idiosyncracies."
|
"""Modify standard packaging.Version regex to support Tesseract idiosyncrasies."""
|
||||||
|
|
||||||
_regex = re.compile(
|
_regex = re.compile(
|
||||||
r"^\s*" + TESSERACT_VERSION_PATTERN + r"\s*$", re.VERBOSE | re.IGNORECASE
|
r"^\s*" + TESSERACT_VERSION_PATTERN + r"\s*$", re.VERBOSE | re.IGNORECASE
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def version() -> str:
|
def version() -> Version:
|
||||||
return get_version('tesseract', regex=r'tesseract\s(.+)')
|
return TesseractVersion(get_version('tesseract', regex=r'tesseract\s(.+)'))
|
||||||
|
|
||||||
|
|
||||||
def has_user_words() -> bool:
|
|
||||||
"""Does Tesseract have --user-words capability?
|
|
||||||
|
|
||||||
Not available in 4.0, but available in 4.1. Also available in 3.x, but
|
|
||||||
we no longer support 3.x.
|
|
||||||
"""
|
|
||||||
return version() >= '4.1'
|
|
||||||
|
|
||||||
|
|
||||||
def has_thresholding() -> bool:
|
def has_thresholding() -> bool:
|
||||||
"""Does Tesseract have -c thresholding method capability?"""
|
"""Does Tesseract have -c thresholding method capability?"""
|
||||||
return version() >= '5.0'
|
return version() >= Version('5.0')
|
||||||
|
|
||||||
|
|
||||||
def get_languages() -> set[str]:
|
def get_languages() -> set[str]:
|
||||||
@@ -239,12 +214,13 @@ def get_deskew(
|
|||||||
parsed = _parse_tesseract_output(p.stdout)
|
parsed = _parse_tesseract_output(p.stdout)
|
||||||
deskew_radians = float(parsed.get('Deskew angle', 0))
|
deskew_radians = float(parsed.get('Deskew angle', 0))
|
||||||
deskew_degrees = 180 / pi * deskew_radians
|
deskew_degrees = 180 / pi * deskew_radians
|
||||||
|
log.debug(f"Deskew angle: {deskew_degrees:.3f}")
|
||||||
return deskew_degrees
|
return deskew_degrees
|
||||||
|
|
||||||
|
|
||||||
def tesseract_log_output(stream: bytes) -> None:
|
def tesseract_log_output(stream: bytes) -> None:
|
||||||
tlog = TesseractLoggerAdapter(
|
tlog = TesseractLoggerAdapter(
|
||||||
log, extra=log.extra if hasattr(log, 'extra') else None
|
log, extra=log.extra if hasattr(log, 'extra') else None # type: ignore
|
||||||
)
|
)
|
||||||
|
|
||||||
if not stream:
|
if not stream:
|
||||||
@@ -289,12 +265,11 @@ def page_timedout(timeout: float) -> None:
|
|||||||
|
|
||||||
|
|
||||||
def _generate_null_hocr(output_hocr: Path, output_text: Path, image: Path) -> None:
|
def _generate_null_hocr(output_hocr: Path, output_text: Path, image: Path) -> None:
|
||||||
"""Produce a .hocr file that reports no text detected on a page that is
|
"""Produce an empty .hocr file.
|
||||||
the same size as the input image."""
|
|
||||||
with Image.open(image) as im:
|
|
||||||
w, h = im.size
|
|
||||||
|
|
||||||
output_hocr.write_text(HOCR_TEMPLATE.format(w, h), encoding='utf-8')
|
Ensures page is the same size as the input image.
|
||||||
|
"""
|
||||||
|
output_hocr.write_text('', encoding='utf-8')
|
||||||
output_text.write_text('[skipped page]', encoding='utf-8')
|
output_text.write_text('[skipped page]', encoding='utf-8')
|
||||||
|
|
||||||
|
|
||||||
@@ -353,7 +328,7 @@ def generate_hocr(
|
|||||||
tesseract_log_output(stdout)
|
tesseract_log_output(stdout)
|
||||||
# The sidecar text file will get the suffix .txt; rename it to
|
# The sidecar text file will get the suffix .txt; rename it to
|
||||||
# whatever caller wants it named
|
# whatever caller wants it named
|
||||||
if prefix.with_suffix('.txt').exists():
|
with suppress(FileNotFoundError):
|
||||||
prefix.with_suffix('.txt').replace(output_text)
|
prefix.with_suffix('.txt').replace(output_text)
|
||||||
|
|
||||||
|
|
||||||
@@ -409,7 +384,7 @@ def generate_pdf(
|
|||||||
try:
|
try:
|
||||||
p = run(args_tesseract, stdout=PIPE, stderr=STDOUT, timeout=timeout, check=True)
|
p = run(args_tesseract, stdout=PIPE, stderr=STDOUT, timeout=timeout, check=True)
|
||||||
stdout = p.stdout
|
stdout = p.stdout
|
||||||
if prefix.with_suffix('.txt').exists():
|
with suppress(FileNotFoundError):
|
||||||
prefix.with_suffix('.txt').replace(output_text)
|
prefix.with_suffix('.txt').replace(output_text)
|
||||||
except TimeoutExpired:
|
except TimeoutExpired:
|
||||||
page_timedout(timeout)
|
page_timedout(timeout)
|
||||||
|
|||||||
@@ -1,46 +1,30 @@
|
|||||||
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
||||||
# SPDX-License-Identifier: MPL-2.0
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
|
|
||||||
from __future__ import annotations
|
"""Interface to unpaper executable."""
|
||||||
|
|
||||||
# unpaper documentation:
|
from __future__ import annotations
|
||||||
# https://github.com/Flameeyes/unpaper/blob/master/doc/basic-concepts.md
|
|
||||||
"""Interface to unpaper executable"""
|
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
import shlex
|
import shlex
|
||||||
import sys
|
import sys
|
||||||
|
from collections.abc import Iterator
|
||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from subprocess import PIPE, STDOUT
|
from subprocess import PIPE, STDOUT
|
||||||
from typing import Iterator, Union
|
from tempfile import TemporaryDirectory
|
||||||
|
from typing import Union
|
||||||
|
|
||||||
|
from packaging.version import Version
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
|
|
||||||
from ocrmypdf.exceptions import MissingDependencyError, SubprocessOutputError
|
from ocrmypdf.exceptions import MissingDependencyError, SubprocessOutputError
|
||||||
from ocrmypdf.subprocess import get_version, run
|
from ocrmypdf.subprocess import get_version, run
|
||||||
|
|
||||||
if sys.version_info >= (3, 10):
|
# unpaper documentation:
|
||||||
from tempfile import TemporaryDirectory
|
# https://github.com/Flameeyes/unpaper/blob/main/doc/basic-concepts.md
|
||||||
else:
|
|
||||||
from tempfile import TemporaryDirectory as _TemporaryDirectory
|
|
||||||
|
|
||||||
class TemporaryDirectory(_TemporaryDirectory):
|
|
||||||
"""Shim to consume ignore_cleanup_errors kwarg on Python 3.9 and older.
|
|
||||||
|
|
||||||
The argument is consumed without action. If users are getting errors related
|
|
||||||
to temporary file cleanup, they should upgrade to Python 3.10 which properly
|
|
||||||
cleans up temporary directories on Windows.
|
|
||||||
|
|
||||||
See: https://github.com/python/cpython/pull/24793
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, ignore_cleanup_errors=False, **kwargs):
|
|
||||||
super().__init__(**kwargs)
|
|
||||||
|
|
||||||
del _TemporaryDirectory
|
|
||||||
|
|
||||||
|
|
||||||
UNPAPER_IMAGE_PIXEL_LIMIT = 256 * 1024 * 1024
|
UNPAPER_IMAGE_PIXEL_LIMIT = 256 * 1024 * 1024
|
||||||
@@ -65,34 +49,8 @@ class UnpaperImageTooLargeError(Exception):
|
|||||||
super().__init__(self.message)
|
super().__init__(self.message)
|
||||||
|
|
||||||
|
|
||||||
def version() -> str:
|
def version() -> Version:
|
||||||
return get_version('unpaper')
|
return Version(get_version('unpaper'))
|
||||||
|
|
||||||
|
|
||||||
SUPPORTED_MODES = {'1', 'L', 'RGB'}
|
|
||||||
|
|
||||||
|
|
||||||
def _convert_image(im: Image.Image) -> tuple[Image.Image, bool]:
|
|
||||||
im_modified = False
|
|
||||||
|
|
||||||
if im.mode not in SUPPORTED_MODES:
|
|
||||||
log.info("Converting image to other colorspace")
|
|
||||||
try:
|
|
||||||
if im.mode == 'P' and len(im.getcolors()) == 2:
|
|
||||||
im = im.convert(mode='1')
|
|
||||||
else:
|
|
||||||
im = im.convert(mode='RGB')
|
|
||||||
except OSError as e:
|
|
||||||
raise MissingDependencyError(
|
|
||||||
"Could not convert image with type " + im.mode
|
|
||||||
) from e
|
|
||||||
else:
|
|
||||||
im_modified = True
|
|
||||||
if im.mode not in SUPPORTED_MODES:
|
|
||||||
raise MissingDependencyError(
|
|
||||||
"Failed to convert image to a supported format."
|
|
||||||
) from None
|
|
||||||
return im, im_modified
|
|
||||||
|
|
||||||
|
|
||||||
@contextmanager
|
@contextmanager
|
||||||
@@ -100,21 +58,15 @@ def _setup_unpaper_io(input_file: Path) -> Iterator[tuple[Path, Path, Path]]:
|
|||||||
with Image.open(input_file) as im:
|
with Image.open(input_file) as im:
|
||||||
if im.width * im.height >= UNPAPER_IMAGE_PIXEL_LIMIT:
|
if im.width * im.height >= UNPAPER_IMAGE_PIXEL_LIMIT:
|
||||||
raise UnpaperImageTooLargeError(w=im.width, h=im.height)
|
raise UnpaperImageTooLargeError(w=im.width, h=im.height)
|
||||||
im, im_modified = _convert_image(im)
|
|
||||||
|
|
||||||
with TemporaryDirectory(ignore_cleanup_errors=True) as tmpdir:
|
with TemporaryDirectory(ignore_cleanup_errors=True) as tmpdir:
|
||||||
tmppath = Path(tmpdir)
|
tmppath = Path(tmpdir)
|
||||||
if im_modified or input_file.suffix != '.png':
|
# No changes, PNG input, just use the file we already have
|
||||||
input_png = tmppath / 'input.png'
|
input_png = input_file
|
||||||
im.save(input_png, format='PNG')
|
# unpaper can write .png too, but it seems to write them slowly
|
||||||
else:
|
# adds a few seconds to test suite - so just use pnm
|
||||||
# No changes, PNG input, just use the file we already have
|
output_pnm = tmppath / 'output.pnm'
|
||||||
input_png = input_file
|
yield input_png, output_pnm, tmppath
|
||||||
|
|
||||||
# unpaper can write .png too, but it seems to write them slowly
|
|
||||||
# adds a few seconds to test suite - so just use pnm
|
|
||||||
output_pnm = tmppath / 'output.pnm'
|
|
||||||
yield input_png, output_pnm, tmppath
|
|
||||||
|
|
||||||
|
|
||||||
def run_unpaper(
|
def run_unpaper(
|
||||||
|
|||||||
+63
-53
@@ -7,49 +7,57 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import logging
|
import logging
|
||||||
from contextlib import suppress
|
from contextlib import suppress
|
||||||
|
from enum import Enum
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from pikepdf import (
|
from pikepdf import (
|
||||||
Dictionary,
|
Dictionary,
|
||||||
|
Matrix,
|
||||||
Name,
|
Name,
|
||||||
Object,
|
|
||||||
Operator,
|
Operator,
|
||||||
|
Page,
|
||||||
Pdf,
|
Pdf,
|
||||||
PdfError,
|
PdfError,
|
||||||
PdfMatrix,
|
|
||||||
Stream,
|
Stream,
|
||||||
parse_content_stream,
|
parse_content_stream,
|
||||||
unparse_content_stream,
|
unparse_content_stream,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
from ocrmypdf._jobcontext import PdfContext
|
||||||
|
|
||||||
|
|
||||||
|
class RenderMode(Enum):
|
||||||
|
ON_TOP = 0
|
||||||
|
UNDERNEATH = 1
|
||||||
|
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
MAX_REPLACE_PAGES = 100
|
MAX_REPLACE_PAGES = 100
|
||||||
|
|
||||||
|
|
||||||
def _ensure_dictionary(obj, name):
|
def _ensure_dictionary(obj: Dictionary | Stream, name: Name):
|
||||||
if name not in obj:
|
if name not in obj:
|
||||||
obj[name] = Dictionary({})
|
obj[name] = Dictionary({})
|
||||||
return obj[name]
|
return obj[name]
|
||||||
|
|
||||||
|
|
||||||
def _update_resources(*, obj, font, font_key, procset):
|
def _update_resources(
|
||||||
|
*,
|
||||||
|
obj: Dictionary | Stream,
|
||||||
|
font: Dictionary | None,
|
||||||
|
font_key: Name | None,
|
||||||
|
):
|
||||||
"""Update this obj's fonts with a reference to the Glyphless font.
|
"""Update this obj's fonts with a reference to the Glyphless font.
|
||||||
|
|
||||||
obj can be a page or Form XObject.
|
obj can be a page or Form XObject.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
resources = _ensure_dictionary(obj, Name.Resources)
|
resources = _ensure_dictionary(obj, Name.Resources)
|
||||||
fonts = _ensure_dictionary(resources, Name.Font)
|
fonts = _ensure_dictionary(resources, Name.Font)
|
||||||
if font_key is not None and font_key not in fonts:
|
if font_key is not None and font_key not in fonts:
|
||||||
fonts[font_key] = font
|
fonts[font_key] = font
|
||||||
|
|
||||||
# Reassign /ProcSet to one that just lists everything - ProcSet is
|
|
||||||
# obsolete and doesn't matter but recommended for old viewer support
|
|
||||||
if procset:
|
|
||||||
resources['/ProcSet'] = procset
|
|
||||||
|
|
||||||
|
def strip_invisible_text(pdf: Pdf, page: Page):
|
||||||
def strip_invisible_text(pdf, page):
|
|
||||||
stream = []
|
stream = []
|
||||||
in_text_obj = False
|
in_text_obj = False
|
||||||
render_mode = 0
|
render_mode = 0
|
||||||
@@ -80,22 +88,20 @@ def strip_invisible_text(pdf, page):
|
|||||||
class OcrGrafter:
|
class OcrGrafter:
|
||||||
"""Manages grafting text-only PDFs onto regular PDFs."""
|
"""Manages grafting text-only PDFs onto regular PDFs."""
|
||||||
|
|
||||||
def __init__(self, context):
|
def __init__(self, context: PdfContext):
|
||||||
self.context = context
|
self.context = context
|
||||||
self.path_base = context.origin
|
self.path_base = context.origin
|
||||||
|
|
||||||
self.pdf_base = Pdf.open(self.path_base)
|
self.pdf_base = Pdf.open(self.path_base)
|
||||||
self.font, self.font_key = None, None
|
self.font: Dictionary | None = None
|
||||||
|
self.font_key: Name | None = None
|
||||||
|
|
||||||
self.pdfinfo = context.pdfinfo
|
self.pdfinfo = context.pdfinfo
|
||||||
self.output_file = context.get_path('graft_layers.pdf')
|
self.output_file = context.get_path('graft_layers.pdf')
|
||||||
|
|
||||||
self.procset = self.pdf_base.make_indirect(
|
|
||||||
Object.parse(b'[ /PDF /Text /ImageB /ImageC /ImageI ]')
|
|
||||||
)
|
|
||||||
|
|
||||||
self.emplacements = 1
|
self.emplacements = 1
|
||||||
self.interim_count = 0
|
self.interim_count = 0
|
||||||
|
self.render_mode = RenderMode.UNDERNEATH
|
||||||
|
|
||||||
def graft_page(
|
def graft_page(
|
||||||
self,
|
self,
|
||||||
@@ -120,7 +126,9 @@ class OcrGrafter:
|
|||||||
foreign_image_page = pdf_image.pages[0]
|
foreign_image_page = pdf_image.pages[0]
|
||||||
self.pdf_base.pages.append(foreign_image_page)
|
self.pdf_base.pages.append(foreign_image_page)
|
||||||
local_image_page = self.pdf_base.pages[-1]
|
local_image_page = self.pdf_base.pages[-1]
|
||||||
self.pdf_base.pages[pageno].emplace(local_image_page)
|
self.pdf_base.pages[pageno].emplace(
|
||||||
|
local_image_page, retain=(Name.Parent,)
|
||||||
|
)
|
||||||
del self.pdf_base.pages[-1]
|
del self.pdf_base.pages[-1]
|
||||||
emplaced_page = True
|
emplaced_page = True
|
||||||
|
|
||||||
@@ -131,10 +139,13 @@ class OcrGrafter:
|
|||||||
text_misaligned = (text_rotation - content_rotation) % 360
|
text_misaligned = (text_rotation - content_rotation) % 360
|
||||||
log.debug(
|
log.debug(
|
||||||
f"Text rotation: (text, autorotate, content) -> text misalignment = "
|
f"Text rotation: (text, autorotate, content) -> text misalignment = "
|
||||||
f"({text_rotation}, {autorotate_correction}, {content_rotation}) -> {text_misaligned}"
|
f"({text_rotation}, {autorotate_correction}, {content_rotation}) -> "
|
||||||
|
f"{text_misaligned}"
|
||||||
)
|
)
|
||||||
|
|
||||||
if textpdf and self.font:
|
if textpdf and self.font:
|
||||||
|
if self.font_key is None:
|
||||||
|
raise ValueError("Font key is not set")
|
||||||
# Graft the text layer onto this page, whether new or old, possibly
|
# Graft the text layer onto this page, whether new or old, possibly
|
||||||
# rotating the text layer by the amount is misaligned.
|
# rotating the text layer by the amount is misaligned.
|
||||||
strip_old = self.context.options.redo_ocr
|
strip_old = self.context.options.redo_ocr
|
||||||
@@ -144,7 +155,6 @@ class OcrGrafter:
|
|||||||
font=self.font,
|
font=self.font,
|
||||||
font_key=self.font_key,
|
font_key=self.font_key,
|
||||||
text_rotation=text_misaligned,
|
text_rotation=text_misaligned,
|
||||||
procset=self.procset,
|
|
||||||
strip_old_text=strip_old,
|
strip_old_text=strip_old,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -159,18 +169,15 @@ class OcrGrafter:
|
|||||||
if self.emplacements % MAX_REPLACE_PAGES == 0:
|
if self.emplacements % MAX_REPLACE_PAGES == 0:
|
||||||
self.save_and_reload()
|
self.save_and_reload()
|
||||||
|
|
||||||
def save_and_reload(self):
|
def save_and_reload(self) -> None:
|
||||||
"""Save and reload the Pdf.
|
"""Save and reload the Pdf.
|
||||||
|
|
||||||
This will keep a lid on our memory usage for very large files. Attach
|
This will keep a lid on our memory usage for very large files. Attach
|
||||||
the font to page 1 even if page 1 doesn't use it, so we have a way to get it
|
the font to page 1 even if page 1 doesn't use it, so we have a way to get it
|
||||||
back.
|
back.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
page0 = self.pdf_base.pages[0]
|
page0 = self.pdf_base.pages[0]
|
||||||
_update_resources(
|
_update_resources(obj=page0.obj, font=self.font, font_key=self.font_key)
|
||||||
obj=page0, font=self.font, font_key=self.font_key, procset=self.procset
|
|
||||||
)
|
|
||||||
|
|
||||||
# We cannot read and write the same file, that will corrupt it
|
# We cannot read and write the same file, that will corrupt it
|
||||||
# but we don't to keep more copies than we need to. Delete intermediates.
|
# but we don't to keep more copies than we need to. Delete intermediates.
|
||||||
@@ -189,7 +196,6 @@ class OcrGrafter:
|
|||||||
self.pdf_base.close()
|
self.pdf_base.close()
|
||||||
|
|
||||||
self.pdf_base = Pdf.open(next_file)
|
self.pdf_base = Pdf.open(next_file)
|
||||||
self.procset = self.pdf_base.pages[0].Resources.ProcSet
|
|
||||||
self.font, self.font_key = None, None # Ensure we reacquire this information
|
self.font, self.font_key = None, None # Ensure we reacquire this information
|
||||||
self.interim_count += 1
|
self.interim_count += 1
|
||||||
|
|
||||||
@@ -198,25 +204,32 @@ class OcrGrafter:
|
|||||||
self.pdf_base.close()
|
self.pdf_base.close()
|
||||||
return self.output_file
|
return self.output_file
|
||||||
|
|
||||||
def _find_font(self, text):
|
def _find_font(self, text: Path) -> tuple[Dictionary | None, Name | None]:
|
||||||
"""Copy a font from the filename text into pdf_base"""
|
"""Copy a font from the filename text into pdf_base."""
|
||||||
|
|
||||||
font, font_key = None, None
|
font, font_key = None, None
|
||||||
possible_font_names = ('/f-0-0', '/F1')
|
possible_font_names = ('/f-0-0', '/F1')
|
||||||
try:
|
try:
|
||||||
with Pdf.open(text) as pdf_text:
|
with Pdf.open(text) as pdf_text:
|
||||||
try:
|
try:
|
||||||
pdf_text_fonts = pdf_text.pages[0].Resources.get('/Font', {})
|
pdf_text_fonts = pdf_text.pages[0].Resources.get(
|
||||||
|
Name.Font, Dictionary()
|
||||||
|
)
|
||||||
except (AttributeError, IndexError, KeyError):
|
except (AttributeError, IndexError, KeyError):
|
||||||
return None, None
|
return None, None
|
||||||
|
if not isinstance(pdf_text_fonts, Dictionary):
|
||||||
|
log.warning("Page fonts are not stored in a dictionary")
|
||||||
|
return None, None
|
||||||
pdf_text_font = None
|
pdf_text_font = None
|
||||||
for f in possible_font_names:
|
for f in possible_font_names:
|
||||||
pdf_text_font = pdf_text_fonts.get(f, None)
|
pdf_text_font = pdf_text_fonts.get(f, None)
|
||||||
if pdf_text_font is not None:
|
if pdf_text_font is not None:
|
||||||
font_key = f
|
font_key = Name(f)
|
||||||
break
|
break
|
||||||
if pdf_text_font:
|
if pdf_text_font:
|
||||||
font = self.pdf_base.copy_foreign(pdf_text_font)
|
font = self.pdf_base.copy_foreign(pdf_text_font)
|
||||||
|
if not isinstance(font, Dictionary):
|
||||||
|
log.warning("Font is not a dictionary")
|
||||||
|
font, font_key = None, None
|
||||||
return font, font_key
|
return font, font_key
|
||||||
except (FileNotFoundError, PdfError):
|
except (FileNotFoundError, PdfError):
|
||||||
# PdfError occurs if a 0-length file is written e.g. due to OCR timeout
|
# PdfError occurs if a 0-length file is written e.g. due to OCR timeout
|
||||||
@@ -227,14 +240,12 @@ class OcrGrafter:
|
|||||||
*,
|
*,
|
||||||
page_num: int,
|
page_num: int,
|
||||||
textpdf: Path,
|
textpdf: Path,
|
||||||
font: Object,
|
font: Dictionary,
|
||||||
font_key: Object,
|
font_key: Name,
|
||||||
procset: Object,
|
|
||||||
text_rotation: int,
|
text_rotation: int,
|
||||||
strip_old_text: bool,
|
strip_old_text: bool,
|
||||||
):
|
):
|
||||||
"""Insert the text layer from text page 0 on to pdf_base at page_num"""
|
"""Insert the text layer from text page 0 on to pdf_base at page_num."""
|
||||||
|
|
||||||
# pylint: disable=invalid-name
|
# pylint: disable=invalid-name
|
||||||
|
|
||||||
log.debug("Grafting")
|
log.debug("Grafting")
|
||||||
@@ -251,19 +262,19 @@ class OcrGrafter:
|
|||||||
# content may have a rotation applied. Wrap the text stream with a rotation
|
# content may have a rotation applied. Wrap the text stream with a rotation
|
||||||
# so it will be oriented the same way as the rest of the page content.
|
# so it will be oriented the same way as the rest of the page content.
|
||||||
# (Previous versions OCRmyPDF rotated the content layer to match the text.)
|
# (Previous versions OCRmyPDF rotated the content layer to match the text.)
|
||||||
mediabox = [float(pdf_text.pages[0].MediaBox[v]) for v in range(4)]
|
mediabox = pdf_text.pages[0].mediabox
|
||||||
wt, ht = mediabox[2] - mediabox[0], mediabox[3] - mediabox[1]
|
wt, ht = mediabox[2] - mediabox[0], mediabox[3] - mediabox[1]
|
||||||
|
|
||||||
mediabox = [float(base_page.MediaBox[v]) for v in range(4)]
|
mediabox = base_page.mediabox
|
||||||
wp, hp = mediabox[2] - mediabox[0], mediabox[3] - mediabox[1]
|
wp, hp = mediabox[2] - mediabox[0], mediabox[3] - mediabox[1]
|
||||||
|
|
||||||
translate = PdfMatrix().translated(-wt / 2, -ht / 2)
|
translate = Matrix().translated(-wt / 2, -ht / 2)
|
||||||
untranslate = PdfMatrix().translated(wp / 2, hp / 2)
|
untranslate = Matrix().translated(wp / 2, hp / 2)
|
||||||
corner = PdfMatrix().translated(mediabox[0], mediabox[1])
|
corner = Matrix().translated(mediabox[0], mediabox[1])
|
||||||
# -rotation because the input is a clockwise angle and this formula
|
# -rotation because the input is a clockwise angle and this formula
|
||||||
# uses CCW
|
# uses CCW
|
||||||
text_rotation = -text_rotation % 360
|
text_rotation = -text_rotation % 360
|
||||||
rotate = PdfMatrix().rotated(text_rotation)
|
rotate = Matrix().rotated(text_rotation)
|
||||||
|
|
||||||
# Because of rounding of DPI, we might get a text layer that is not
|
# Because of rounding of DPI, we might get a text layer that is not
|
||||||
# identically sized to the target page. Scale to adjust. Normally this
|
# identically sized to the target page. Scale to adjust. Normally this
|
||||||
@@ -274,14 +285,15 @@ class OcrGrafter:
|
|||||||
scale_y = hp / ht
|
scale_y = hp / ht
|
||||||
|
|
||||||
# log.debug('%r', scale_x, scale_y)
|
# log.debug('%r', scale_x, scale_y)
|
||||||
scale = PdfMatrix().scaled(scale_x, scale_y)
|
scale = Matrix().scaled(scale_x, scale_y)
|
||||||
|
|
||||||
# Translate the text so it is centered at (0, 0), rotate it there, adjust
|
# Translate the text so it is centered at (0, 0), rotate it there, adjust
|
||||||
# for a size different between initial and text PDF, then untranslate, and
|
# for a size different between initial and text PDF, then untranslate, and
|
||||||
# finally move the lower left corner to match the mediabox
|
# finally move the lower left corner to match the mediabox. All transforms
|
||||||
ctm = translate @ rotate @ scale @ untranslate @ corner
|
# must be premultiplied so they are applied in reverse order here.
|
||||||
|
ctm = corner @ untranslate @ scale @ rotate @ translate
|
||||||
|
|
||||||
base_resources = _ensure_dictionary(base_page, Name.Resources)
|
base_resources = _ensure_dictionary(base_page.obj, Name.Resources)
|
||||||
base_xobjs = _ensure_dictionary(base_resources, Name.XObject)
|
base_xobjs = _ensure_dictionary(base_resources, Name.XObject)
|
||||||
text_xobj_name = Name.random(prefix="OCR-")
|
text_xobj_name = Name.random(prefix="OCR-")
|
||||||
xobj = self.pdf_base.make_stream(pdf_text_contents)
|
xobj = self.pdf_base.make_stream(pdf_text_contents)
|
||||||
@@ -290,9 +302,7 @@ class OcrGrafter:
|
|||||||
xobj.Subtype = Name.Form
|
xobj.Subtype = Name.Form
|
||||||
xobj.FormType = 1
|
xobj.FormType = 1
|
||||||
xobj.BBox = mediabox
|
xobj.BBox = mediabox
|
||||||
_update_resources(
|
_update_resources(obj=xobj, font=font, font_key=font_key)
|
||||||
obj=xobj, font=font, font_key=font_key, procset=[Name.PDF]
|
|
||||||
)
|
|
||||||
|
|
||||||
pdf_draw_xobj = (
|
pdf_draw_xobj = (
|
||||||
(b'q %s cm\n' % ctm.encode()) + (b'%s Do\n' % text_xobj_name) + b'\nQ\n'
|
(b'q %s cm\n' % ctm.encode()) + (b'%s Do\n' % text_xobj_name) + b'\nQ\n'
|
||||||
@@ -302,8 +312,8 @@ class OcrGrafter:
|
|||||||
if strip_old_text:
|
if strip_old_text:
|
||||||
strip_invisible_text(self.pdf_base, base_page)
|
strip_invisible_text(self.pdf_base, base_page)
|
||||||
|
|
||||||
base_page.contents_add(new_text_layer, prepend=True)
|
base_page.contents_add(
|
||||||
|
new_text_layer, prepend=self.render_mode == RenderMode.ON_TOP
|
||||||
_update_resources(
|
|
||||||
obj=base_page, font=font, font_key=font_key, procset=procset
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
_update_resources(obj=base_page.obj, font=font, font_key=font_key)
|
||||||
|
|||||||
@@ -6,12 +6,10 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import os
|
import os
|
||||||
import shutil
|
|
||||||
import sys
|
|
||||||
from argparse import Namespace
|
from argparse import Namespace
|
||||||
|
from collections.abc import Iterator
|
||||||
from copy import copy
|
from copy import copy
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Iterator
|
|
||||||
|
|
||||||
from pluggy import PluginManager
|
from pluggy import PluginManager
|
||||||
|
|
||||||
@@ -55,11 +53,17 @@ class PdfContext:
|
|||||||
for n in range(npages):
|
for n in range(npages):
|
||||||
yield PageContext(self, n)
|
yield PageContext(self, n)
|
||||||
|
|
||||||
|
def get_page_context_args(self) -> Iterator[tuple[PageContext]]:
|
||||||
|
"""Get all ``PageContext`` for this PDF packaged in tuple for args-splatting."""
|
||||||
|
npages = len(self.pdfinfo)
|
||||||
|
for n in range(npages):
|
||||||
|
yield (PageContext(self, n),)
|
||||||
|
|
||||||
|
|
||||||
class PageContext:
|
class PageContext:
|
||||||
"""Holds our context for a page.
|
"""Holds our context for a page.
|
||||||
|
|
||||||
Must be pickable, so stores only intrinsic/simple data elements or those
|
Must be pickle-able, so stores only intrinsic/simple data elements or those
|
||||||
capable of their serializing themselves via ``__getstate__``.
|
capable of their serializing themselves via ``__getstate__``.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -94,10 +98,3 @@ class PageContext:
|
|||||||
if not isinstance(state['options'].output_file, (str, bytes, os.PathLike)):
|
if not isinstance(state['options'].output_file, (str, bytes, os.PathLike)):
|
||||||
state['options'].output_file = 'stream'
|
state['options'].output_file = 'stream'
|
||||||
return state
|
return state
|
||||||
|
|
||||||
|
|
||||||
def cleanup_working_files(work_folder: Path, options: Namespace):
|
|
||||||
if options.keep_temporary_files:
|
|
||||||
print(f"Temporary working files retained at:\n{work_folder}", file=sys.stderr)
|
|
||||||
else:
|
|
||||||
shutil.rmtree(work_folder, ignore_errors=True)
|
|
||||||
|
|||||||
@@ -6,9 +6,9 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
from contextlib import suppress
|
|
||||||
|
|
||||||
from tqdm import tqdm
|
from rich.console import Console
|
||||||
|
from rich.logging import RichHandler
|
||||||
|
|
||||||
|
|
||||||
class PageNumberFilter(logging.Filter):
|
class PageNumberFilter(logging.Filter):
|
||||||
@@ -23,21 +23,8 @@ class PageNumberFilter(logging.Filter):
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
class TqdmConsole:
|
class RichLoggingHandler(RichHandler):
|
||||||
"""Wrapper to log messages in a way that is compatible with tqdm progress bar
|
def __init__(self, console: Console, **kwargs):
|
||||||
|
super().__init__(
|
||||||
This routes log messages through tqdm so that it can print them above the
|
console=console, show_level=False, show_time=False, markup=True, **kwargs
|
||||||
progress bar, and then refresh the progress bar, rather than overwriting
|
)
|
||||||
it which looks messy.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, file):
|
|
||||||
self.file = file
|
|
||||||
|
|
||||||
def write(self, msg):
|
|
||||||
# When no progress bar is active, tqdm.write() routes to print()
|
|
||||||
tqdm.write(msg.rstrip(), end='\n', file=self.file)
|
|
||||||
|
|
||||||
def flush(self):
|
|
||||||
with suppress(AttributeError):
|
|
||||||
self.file.flush()
|
|
||||||
|
|||||||
@@ -0,0 +1,184 @@
|
|||||||
|
# SPDX-FileCopyrightText: 2023 James R. Barlow
|
||||||
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
|
|
||||||
|
"""OCRmyPDF page processing pipeline functions."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from pikepdf import Dictionary, Name, Pdf
|
||||||
|
from pikepdf import __version__ as PIKEPDF_VERSION
|
||||||
|
from pikepdf.models.metadata import PdfMetadata, encode_pdf_date
|
||||||
|
|
||||||
|
from ocrmypdf._jobcontext import PdfContext
|
||||||
|
from ocrmypdf._version import PROGRAM_NAME
|
||||||
|
from ocrmypdf._version import __version__ as OCRMYPF_VERSION
|
||||||
|
from ocrmypdf.languages import iso_639_2_from_3
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def get_docinfo(base_pdf: Pdf, context: PdfContext) -> dict[str, str]:
|
||||||
|
"""Read the document info and store it in a dictionary."""
|
||||||
|
options = context.options
|
||||||
|
|
||||||
|
def from_document_info(key):
|
||||||
|
try:
|
||||||
|
s = base_pdf.docinfo[key]
|
||||||
|
return str(s)
|
||||||
|
except (KeyError, TypeError):
|
||||||
|
return ''
|
||||||
|
|
||||||
|
pdfmark = {
|
||||||
|
k: from_document_info(k)
|
||||||
|
for k in ('/Title', '/Author', '/Keywords', '/Subject', '/CreationDate')
|
||||||
|
}
|
||||||
|
if options.title:
|
||||||
|
pdfmark['/Title'] = options.title
|
||||||
|
if options.author:
|
||||||
|
pdfmark['/Author'] = options.author
|
||||||
|
if options.keywords:
|
||||||
|
pdfmark['/Keywords'] = options.keywords
|
||||||
|
if options.subject:
|
||||||
|
pdfmark['/Subject'] = options.subject
|
||||||
|
|
||||||
|
creator_tag = context.plugin_manager.hook.get_ocr_engine().creator_tag(options)
|
||||||
|
|
||||||
|
pdfmark['/Creator'] = f'{PROGRAM_NAME} {OCRMYPF_VERSION} / {creator_tag}'
|
||||||
|
pdfmark['/Producer'] = f'pikepdf {PIKEPDF_VERSION}'
|
||||||
|
pdfmark['/ModDate'] = encode_pdf_date(datetime.now(timezone.utc))
|
||||||
|
return pdfmark
|
||||||
|
|
||||||
|
|
||||||
|
def report_on_metadata(options, missing):
|
||||||
|
if not missing:
|
||||||
|
return
|
||||||
|
if options.output_type.startswith('pdfa'):
|
||||||
|
log.warning(
|
||||||
|
"Some input metadata could not be copied because it is not "
|
||||||
|
"permitted in PDF/A. You may wish to examine the output "
|
||||||
|
"PDF's XMP metadata."
|
||||||
|
)
|
||||||
|
log.debug("The following metadata fields were not copied: %r", missing)
|
||||||
|
else:
|
||||||
|
log.error(
|
||||||
|
"Some input metadata could not be copied."
|
||||||
|
"You may wish to examine the output PDF's XMP metadata."
|
||||||
|
)
|
||||||
|
log.info("The following metadata fields were not copied: %r", missing)
|
||||||
|
|
||||||
|
|
||||||
|
def repair_docinfo_nuls(pdf):
|
||||||
|
"""If the DocumentInfo block contains NUL characters, remove them.
|
||||||
|
|
||||||
|
If the DocumentInfo block is malformed, log an error and continue.
|
||||||
|
"""
|
||||||
|
modified = False
|
||||||
|
try:
|
||||||
|
if not isinstance(pdf.docinfo, Dictionary):
|
||||||
|
raise TypeError("DocumentInfo is not a dictionary")
|
||||||
|
for k, v in pdf.docinfo.items():
|
||||||
|
if isinstance(v, str) and b'\x00' in bytes(v):
|
||||||
|
pdf.docinfo[k] = bytes(v).replace(b'\x00', b'')
|
||||||
|
modified = True
|
||||||
|
except TypeError:
|
||||||
|
# TypeError can also be raised if dictionary items are unexpected types
|
||||||
|
log.error("File contains a malformed DocumentInfo block - continuing anyway.")
|
||||||
|
return modified
|
||||||
|
|
||||||
|
|
||||||
|
def should_linearize(working_file: Path, context: PdfContext) -> bool:
|
||||||
|
"""Determine whether the PDF should be linearized.
|
||||||
|
|
||||||
|
For smaller files, linearization is not worth the effort.
|
||||||
|
"""
|
||||||
|
filesize = os.stat(working_file).st_size
|
||||||
|
if filesize > (context.options.fast_web_view * 1_000_000):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _fix_metadata(meta_original: PdfMetadata, meta_pdf: PdfMetadata):
|
||||||
|
# If xmp:CreateDate is missing, set it to the modify date to
|
||||||
|
# ensure consistency with Ghostscript.
|
||||||
|
if 'xmp:CreateDate' not in meta_pdf:
|
||||||
|
meta_pdf['xmp:CreateDate'] = meta_pdf.get('xmp:ModifyDate', '')
|
||||||
|
if meta_pdf.get('dc:title') == 'Untitled':
|
||||||
|
# Ghostscript likes to set title to Untitled if omitted from input.
|
||||||
|
# Reverse this, because PDF/A TechNote 0003:Metadata in PDF/A-1
|
||||||
|
# and the XMP Spec do not make this recommendation.
|
||||||
|
if 'dc:title' not in meta_original:
|
||||||
|
del meta_pdf['dc:title']
|
||||||
|
|
||||||
|
|
||||||
|
def _unset_empty_metadata(meta: PdfMetadata, options):
|
||||||
|
"""Unset metadata fields that were explicitly set to empty strings.
|
||||||
|
|
||||||
|
If the user explicitly specified an empty string for any of the
|
||||||
|
following, they should be unset and not reported as missing in
|
||||||
|
the output pdf. Note that some metadata fields use differing names
|
||||||
|
between PDF/A and PDF.
|
||||||
|
"""
|
||||||
|
if options.title == '' and 'dc:title' in meta:
|
||||||
|
del meta['dc:title'] # PDF/A and PDF
|
||||||
|
if options.author == '':
|
||||||
|
if 'dc:creator' in meta:
|
||||||
|
del meta['dc:creator'] # PDF/A (Not xmp:CreatorTool)
|
||||||
|
if 'pdf:Author' in meta:
|
||||||
|
del meta['pdf:Author'] # PDF
|
||||||
|
if options.subject == '':
|
||||||
|
if 'dc:description' in meta:
|
||||||
|
del meta['dc:description'] # PDF/A
|
||||||
|
if 'dc:subject' in meta:
|
||||||
|
del meta['dc:subject'] # PDF
|
||||||
|
if options.keywords == '' and 'pdf:Keywords' in meta:
|
||||||
|
del meta['pdf:Keywords'] # PDF/A and PDF
|
||||||
|
|
||||||
|
|
||||||
|
def _set_language(pdf: Pdf, languages: list[str]):
|
||||||
|
"""Set the language of the PDF."""
|
||||||
|
if Name.Lang in pdf.Root or not languages:
|
||||||
|
return # Already set or can't change
|
||||||
|
primary_language_iso639_3 = languages[0]
|
||||||
|
if not primary_language_iso639_3:
|
||||||
|
return
|
||||||
|
iso639_2 = iso_639_2_from_3(primary_language_iso639_3)
|
||||||
|
if not iso639_2:
|
||||||
|
return
|
||||||
|
pdf.Root.Lang = iso639_2
|
||||||
|
|
||||||
|
|
||||||
|
def metadata_fixup(
|
||||||
|
working_file: Path, context: PdfContext, pdf_save_settings: dict[str, Any]
|
||||||
|
) -> Path:
|
||||||
|
"""Fix certain metadata fields after Ghostscript PDF/A conversion.
|
||||||
|
|
||||||
|
Also report on metadata in the input file that was not retained during
|
||||||
|
PDF/A conversion.
|
||||||
|
"""
|
||||||
|
output_file = context.get_path('metafix.pdf')
|
||||||
|
options = context.options
|
||||||
|
|
||||||
|
with Pdf.open(context.origin) as original, Pdf.open(working_file) as pdf:
|
||||||
|
docinfo = get_docinfo(original, context)
|
||||||
|
with original.open_metadata(
|
||||||
|
set_pikepdf_as_editor=False, update_docinfo=False, strict=False
|
||||||
|
) as meta_original, pdf.open_metadata() as meta_pdf:
|
||||||
|
meta_pdf.load_from_docinfo(
|
||||||
|
docinfo, delete_missing=False, raise_failure=False
|
||||||
|
)
|
||||||
|
_fix_metadata(meta_original, meta_pdf)
|
||||||
|
_unset_empty_metadata(meta_original, options)
|
||||||
|
_unset_empty_metadata(meta_pdf, options)
|
||||||
|
meta_missing = set(meta_original.keys()) - set(meta_pdf.keys())
|
||||||
|
report_on_metadata(options, meta_missing)
|
||||||
|
|
||||||
|
_set_language(pdf, options.languages)
|
||||||
|
pdf.save(output_file, **pdf_save_settings)
|
||||||
|
|
||||||
|
return output_file
|
||||||
+331
-246
@@ -1,4 +1,5 @@
|
|||||||
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
# SPDX-FileCopyrightText: 2018-2022 James R. Barlow
|
||||||
|
# SPDX-FileCopyrightText: 2019 Martin Wind
|
||||||
# SPDX-License-Identifier: MPL-2.0
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
|
|
||||||
"""OCRmyPDF page processing pipeline functions."""
|
"""OCRmyPDF page processing pipeline functions."""
|
||||||
@@ -9,47 +10,56 @@ import logging
|
|||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import sys
|
import sys
|
||||||
|
from collections.abc import Iterable, Iterator, Sequence
|
||||||
from contextlib import suppress
|
from contextlib import suppress
|
||||||
from datetime import datetime, timezone
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from shutil import copyfileobj
|
from shutil import copyfileobj, copystat
|
||||||
from typing import Iterable
|
from typing import Any, BinaryIO, TypeVar, cast
|
||||||
|
|
||||||
import img2pdf
|
import img2pdf
|
||||||
import pikepdf
|
import pikepdf
|
||||||
from pikepdf.models.metadata import encode_pdf_date
|
|
||||||
from PIL import Image, ImageColor, ImageDraw
|
from PIL import Image, ImageColor, ImageDraw
|
||||||
|
|
||||||
from ocrmypdf._concurrent import Executor
|
from ocrmypdf._concurrent import Executor
|
||||||
from ocrmypdf._exec import unpaper
|
from ocrmypdf._exec import unpaper
|
||||||
from ocrmypdf._jobcontext import PageContext, PdfContext
|
from ocrmypdf._jobcontext import PageContext, PdfContext
|
||||||
from ocrmypdf._version import PROGRAM_NAME
|
from ocrmypdf._metadata import repair_docinfo_nuls
|
||||||
from ocrmypdf._version import __version__ as VERSION
|
|
||||||
from ocrmypdf.exceptions import (
|
from ocrmypdf.exceptions import (
|
||||||
|
DigitalSignatureError,
|
||||||
DpiError,
|
DpiError,
|
||||||
EncryptedPdfError,
|
EncryptedPdfError,
|
||||||
InputFileError,
|
InputFileError,
|
||||||
PriorOcrFoundError,
|
PriorOcrFoundError,
|
||||||
|
TaggedPDFError,
|
||||||
UnsupportedImageFormatError,
|
UnsupportedImageFormatError,
|
||||||
)
|
)
|
||||||
from ocrmypdf.helpers import IMG2PDF_KWARGS, Resolution, safe_symlink
|
from ocrmypdf.helpers import IMG2PDF_KWARGS, Resolution, safe_symlink
|
||||||
from ocrmypdf.hocrtransform import HocrTransform
|
from ocrmypdf.hocrtransform import HocrTransform
|
||||||
from ocrmypdf.pdfa import generate_pdfa_ps
|
from ocrmypdf.pdfa import generate_pdfa_ps
|
||||||
from ocrmypdf.pdfinfo import Colorspace, Encoding, PdfInfo
|
from ocrmypdf.pdfinfo import Colorspace, Encoding, PageInfo, PdfInfo
|
||||||
|
from ocrmypdf.pluginspec import OrientationConfidence
|
||||||
# Remove this workaround when we require Pillow >= 10
|
|
||||||
try:
|
|
||||||
BICUBIC = Image.Resampling.BICUBIC # type: ignore
|
|
||||||
except AttributeError: # pragma: no cover
|
|
||||||
# Pillow 9 shim
|
|
||||||
BICUBIC = Image.BICUBIC # type: ignore
|
|
||||||
|
|
||||||
|
T = TypeVar("T")
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
VECTOR_PAGE_DPI = 400
|
VECTOR_PAGE_DPI = 400
|
||||||
|
|
||||||
|
|
||||||
def triage_image_file(input_file, output_file, options):
|
def triage_image_file(input_file: Path, output_file: Path, options) -> None:
|
||||||
|
"""Triage the input image file.
|
||||||
|
|
||||||
|
If the input file is an image, check its resolution and convert it to PDF.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
input_file: The path to the input file.
|
||||||
|
output_file: The path to the output file.
|
||||||
|
options: An object containing the options passed to the OCRmyPDF command.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
UnsupportedImageFormatError: If the input file is not a supported image format.
|
||||||
|
DpiError: If the input image has no resolution (DPI) in its metadata or if the
|
||||||
|
resolution is not credible.
|
||||||
|
"""
|
||||||
log.info("Input file is not a PDF, checking if it is an image...")
|
log.info("Input file is not a PDF, checking if it is an image...")
|
||||||
try:
|
try:
|
||||||
im = Image.open(input_file)
|
im = Image.open(input_file)
|
||||||
@@ -64,34 +74,32 @@ def triage_image_file(input_file, output_file, options):
|
|||||||
if im.info['dpi'] <= (96, 96) and not options.image_dpi:
|
if im.info['dpi'] <= (96, 96) and not options.image_dpi:
|
||||||
log.info("Image size: (%d, %d)", *im.size)
|
log.info("Image size: (%d, %d)", *im.size)
|
||||||
log.info("Image resolution: (%d, %d)", *im.info['dpi'])
|
log.info("Image resolution: (%d, %d)", *im.info['dpi'])
|
||||||
log.error(
|
raise DpiError(
|
||||||
"Input file is an image, but the resolution (DPI) is "
|
"Input file is an image, but the resolution (DPI) is "
|
||||||
"not credible. Estimate the resolution at which the "
|
"not credible. Estimate the resolution at which the "
|
||||||
"image was scanned and specify it using --image-dpi."
|
"image was scanned and specify it using --image-dpi."
|
||||||
)
|
)
|
||||||
raise DpiError()
|
|
||||||
elif not options.image_dpi:
|
elif not options.image_dpi:
|
||||||
log.info("Image size: (%d, %d)", *im.size)
|
log.info("Image size: (%d, %d)", *im.size)
|
||||||
log.error(
|
raise DpiError(
|
||||||
"Input file is an image, but has no resolution (DPI) "
|
"Input file is an image, but has no resolution (DPI) "
|
||||||
"in its metadata. Estimate the resolution at which "
|
"in its metadata. Estimate the resolution at which "
|
||||||
"image was scanned and specify it using --image-dpi."
|
"image was scanned and specify it using --image-dpi."
|
||||||
)
|
)
|
||||||
raise DpiError()
|
|
||||||
|
|
||||||
if im.mode in ('RGBA', 'LA'):
|
if im.mode in ('RGBA', 'LA'):
|
||||||
log.error(
|
raise UnsupportedImageFormatError(
|
||||||
"The input image has an alpha channel. Remove the alpha "
|
"The input image has an alpha channel. Remove the alpha "
|
||||||
"channel first."
|
"channel first."
|
||||||
)
|
)
|
||||||
raise UnsupportedImageFormatError()
|
|
||||||
|
|
||||||
if 'iccprofile' not in im.info:
|
if 'iccprofile' not in im.info:
|
||||||
if im.mode == 'RGB':
|
if im.mode == 'RGB':
|
||||||
log.info("Input image has no ICC profile, assuming sRGB")
|
log.info("Input image has no ICC profile, assuming sRGB")
|
||||||
elif im.mode == 'CMYK':
|
elif im.mode == 'CMYK':
|
||||||
log.error("Input CMYK image has no ICC profile, not usable")
|
raise UnsupportedImageFormatError(
|
||||||
raise UnsupportedImageFormatError()
|
"Input CMYK image has no ICC profile, not usable"
|
||||||
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
log.info("Image seems valid. Try converting to PDF...")
|
log.info("Image seems valid. Try converting to PDF...")
|
||||||
@@ -109,27 +117,28 @@ def triage_image_file(input_file, output_file, options):
|
|||||||
)
|
)
|
||||||
log.info("Successfully converted to PDF, processing...")
|
log.info("Successfully converted to PDF, processing...")
|
||||||
except img2pdf.ImageOpenError as e:
|
except img2pdf.ImageOpenError as e:
|
||||||
log.error(e)
|
|
||||||
raise UnsupportedImageFormatError() from e
|
raise UnsupportedImageFormatError() from e
|
||||||
|
|
||||||
|
|
||||||
def _pdf_guess_version(input_file, search_window=1024):
|
def _pdf_guess_version(input_file: Path, search_window=1024) -> str:
|
||||||
"""Try to find version signature at start of file.
|
"""Try to find version signature at start of file.
|
||||||
|
|
||||||
Not robust enough to deal with appended files.
|
Not robust enough to deal with appended files.
|
||||||
|
|
||||||
Returns empty string if not found, indicating file is probably not PDF.
|
Returns empty string if not found, indicating file is probably not PDF.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
with open(input_file, 'rb') as f:
|
with open(input_file, 'rb') as f:
|
||||||
signature = f.read(search_window)
|
signature = f.read(search_window)
|
||||||
m = re.search(br'%PDF-(\d\.\d)', signature)
|
m = re.search(br'%PDF-(\d\.\d)', signature)
|
||||||
if m:
|
if m:
|
||||||
return m.group(1)
|
return m.group(1).decode('ascii')
|
||||||
return ''
|
return ''
|
||||||
|
|
||||||
|
|
||||||
def triage(original_filename, input_file, output_file, options):
|
def triage(
|
||||||
|
original_filename: str, input_file: Path, output_file: Path, options
|
||||||
|
) -> Path:
|
||||||
|
"""Triage the input file. We can handle PDFs and images."""
|
||||||
try:
|
try:
|
||||||
if _pdf_guess_version(input_file):
|
if _pdf_guess_version(input_file):
|
||||||
if options.image_dpi:
|
if options.image_dpi:
|
||||||
@@ -153,17 +162,20 @@ def get_pdfinfo(
|
|||||||
input_file,
|
input_file,
|
||||||
*,
|
*,
|
||||||
executor: Executor,
|
executor: Executor,
|
||||||
detailed_analysis=False,
|
detailed_analysis: bool = False,
|
||||||
progbar=False,
|
progbar: bool = False,
|
||||||
max_workers=None,
|
max_workers: int | None = None,
|
||||||
|
use_threads: bool = True,
|
||||||
check_pages=None,
|
check_pages=None,
|
||||||
) -> PdfInfo:
|
) -> PdfInfo:
|
||||||
|
"""Get the PDF info."""
|
||||||
try:
|
try:
|
||||||
return PdfInfo(
|
return PdfInfo(
|
||||||
input_file,
|
input_file,
|
||||||
detailed_analysis=detailed_analysis,
|
detailed_analysis=detailed_analysis,
|
||||||
progbar=progbar,
|
progbar=progbar,
|
||||||
max_workers=max_workers,
|
max_workers=max_workers,
|
||||||
|
use_threads=use_threads,
|
||||||
check_pages=check_pages,
|
check_pages=check_pages,
|
||||||
executor=executor,
|
executor=executor,
|
||||||
)
|
)
|
||||||
@@ -173,32 +185,27 @@ def get_pdfinfo(
|
|||||||
raise InputFileError() from e
|
raise InputFileError() from e
|
||||||
|
|
||||||
|
|
||||||
def validate_pdfinfo_options(context: PdfContext):
|
def validate_pdfinfo_options(context: PdfContext) -> None:
|
||||||
|
"""Validate the PDF info options."""
|
||||||
pdfinfo = context.pdfinfo
|
pdfinfo = context.pdfinfo
|
||||||
options = context.options
|
options = context.options
|
||||||
|
|
||||||
if pdfinfo.needs_rendering:
|
if pdfinfo.needs_rendering:
|
||||||
log.error(
|
raise InputFileError(
|
||||||
"This PDF contains dynamic XFA forms created by Adobe LiveCycle "
|
"This PDF contains dynamic XFA forms created by Adobe LiveCycle "
|
||||||
"Designer and can only be read by Adobe Acrobat or Adobe Reader."
|
"Designer and can only be read by Adobe Acrobat or Adobe Reader."
|
||||||
)
|
)
|
||||||
raise InputFileError()
|
if pdfinfo.has_signature:
|
||||||
if pdfinfo.has_userunit and options.output_type.startswith('pdfa'):
|
if options.invalidate_digital_signatures:
|
||||||
log.error(
|
log.warning("All digital signatures will be invalidated")
|
||||||
"This input file uses a PDF feature that is not supported "
|
else:
|
||||||
"by Ghostscript, so you cannot use --output-type=pdfa for this "
|
raise DigitalSignatureError()
|
||||||
"file. (Specifically, it uses the PDF-1.6 /UserUnit feature to "
|
|
||||||
"support very large or small page sizes, and Ghostscript cannot "
|
|
||||||
"output these files.) Use --output-type=pdf instead."
|
|
||||||
)
|
|
||||||
raise InputFileError()
|
|
||||||
if pdfinfo.has_acroform:
|
if pdfinfo.has_acroform:
|
||||||
if options.redo_ocr:
|
if options.redo_ocr:
|
||||||
log.error(
|
raise InputFileError(
|
||||||
"This PDF has a user fillable form. --redo-ocr is not "
|
"This PDF has a user fillable form. --redo-ocr is not "
|
||||||
"currently possible on such files."
|
"currently possible on such files."
|
||||||
)
|
)
|
||||||
raise InputFileError()
|
|
||||||
else:
|
else:
|
||||||
log.warning(
|
log.warning(
|
||||||
"This PDF has a fillable form. "
|
"This PDF has a fillable form. "
|
||||||
@@ -211,32 +218,37 @@ def validate_pdfinfo_options(context: PdfContext):
|
|||||||
"form and all filled form fields. The output PDF will be "
|
"form and all filled form fields. The output PDF will be "
|
||||||
"'flattened' and will no longer be fillable."
|
"'flattened' and will no longer be fillable."
|
||||||
)
|
)
|
||||||
|
if pdfinfo.is_tagged:
|
||||||
|
if options.force_ocr or options.skip_text or options.redo_ocr:
|
||||||
|
log.warning(
|
||||||
|
"This PDF is marked as a Tagged PDF. This often indicates "
|
||||||
|
"that the PDF was generated from an office document and does "
|
||||||
|
"not need OCR. PDF pages processed by OCRmyPDF may not be "
|
||||||
|
"tagged correctly."
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
raise TaggedPDFError()
|
||||||
context.plugin_manager.hook.validate(pdfinfo=pdfinfo, options=options)
|
context.plugin_manager.hook.validate(pdfinfo=pdfinfo, options=options)
|
||||||
|
|
||||||
|
|
||||||
def _vector_page_dpi(pageinfo):
|
def _vector_page_dpi(pageinfo: PageInfo) -> int:
|
||||||
return VECTOR_PAGE_DPI if pageinfo.has_vector or pageinfo.has_text else 0.0
|
"""Get a DPI to use for vector pages, if the page has vector content."""
|
||||||
|
return VECTOR_PAGE_DPI if pageinfo.has_vector or pageinfo.has_text else 0
|
||||||
|
|
||||||
|
|
||||||
def get_page_dpi(pageinfo, options):
|
def get_page_square_dpi(
|
||||||
"Get the DPI when nonsquare DPI is tolerable"
|
page_context: PageContext, image_dpi: Resolution | None = None
|
||||||
xres = max(
|
) -> Resolution:
|
||||||
pageinfo.dpi.x or VECTOR_PAGE_DPI,
|
"""Get the DPI when we require xres == yres, scaled to physical units.
|
||||||
options.oversample or 0.0,
|
|
||||||
_vector_page_dpi(pageinfo),
|
|
||||||
)
|
|
||||||
yres = max(
|
|
||||||
pageinfo.dpi.y or VECTOR_PAGE_DPI,
|
|
||||||
options.oversample or 0,
|
|
||||||
_vector_page_dpi(pageinfo),
|
|
||||||
)
|
|
||||||
return Resolution(float(xres), float(yres))
|
|
||||||
|
|
||||||
|
Page DPI includes UserUnit scaling.
|
||||||
def get_page_square_dpi(pageinfo, options) -> Resolution:
|
"""
|
||||||
"Get the DPI when we require xres == yres, scaled to physical units"
|
pageinfo = page_context.pageinfo
|
||||||
xres = pageinfo.dpi.x or 0.0
|
options = page_context.options
|
||||||
yres = pageinfo.dpi.y or 0.0
|
if not image_dpi:
|
||||||
|
image_dpi = pageinfo.dpi
|
||||||
|
xres = image_dpi.x or 0.0
|
||||||
|
yres = image_dpi.y or 0.0
|
||||||
userunit = float(pageinfo.userunit) or 1.0
|
userunit = float(pageinfo.userunit) or 1.0
|
||||||
units = float(
|
units = float(
|
||||||
max(
|
max(
|
||||||
@@ -249,12 +261,23 @@ def get_page_square_dpi(pageinfo, options) -> Resolution:
|
|||||||
return Resolution(units, units)
|
return Resolution(units, units)
|
||||||
|
|
||||||
|
|
||||||
def get_canvas_square_dpi(pageinfo, options) -> Resolution:
|
def get_canvas_square_dpi(
|
||||||
"""Get the DPI when we require xres == yres, in Postscript units"""
|
page_context: PageContext, image_dpi: Resolution | None = None
|
||||||
|
) -> Resolution:
|
||||||
|
"""Get the DPI when we require xres == yres, in Postscript units.
|
||||||
|
|
||||||
|
Canvas DPI is independent of PDF UserUnit scaling, which is
|
||||||
|
used to describe situations where the PDF user space is not 1:1 with
|
||||||
|
the physical units of the page.
|
||||||
|
"""
|
||||||
|
pageinfo = page_context.pageinfo
|
||||||
|
options = page_context.options
|
||||||
|
if not image_dpi:
|
||||||
|
image_dpi = pageinfo.dpi
|
||||||
units = float(
|
units = float(
|
||||||
max(
|
max(
|
||||||
(pageinfo.dpi.x) or VECTOR_PAGE_DPI,
|
image_dpi.x or VECTOR_PAGE_DPI,
|
||||||
(pageinfo.dpi.y) or VECTOR_PAGE_DPI,
|
image_dpi.y or VECTOR_PAGE_DPI,
|
||||||
_vector_page_dpi(pageinfo),
|
_vector_page_dpi(pageinfo),
|
||||||
options.oversample or 0.0,
|
options.oversample or 0.0,
|
||||||
)
|
)
|
||||||
@@ -262,7 +285,8 @@ def get_canvas_square_dpi(pageinfo, options) -> Resolution:
|
|||||||
return Resolution(units, units)
|
return Resolution(units, units)
|
||||||
|
|
||||||
|
|
||||||
def is_ocr_required(page_context: PageContext):
|
def is_ocr_required(page_context: PageContext) -> bool:
|
||||||
|
"""Check if the page needs to be OCR'd."""
|
||||||
pageinfo = page_context.pageinfo
|
pageinfo = page_context.pageinfo
|
||||||
options = page_context.options
|
options = page_context.options
|
||||||
|
|
||||||
@@ -312,8 +336,8 @@ def is_ocr_required(page_context: PageContext):
|
|||||||
log.warning(
|
log.warning(
|
||||||
"page has no images - "
|
"page has no images - "
|
||||||
"all vector content will be "
|
"all vector content will be "
|
||||||
f"rasterized at {VECTOR_PAGE_DPI} DPI, losing some resolution and likely "
|
f"rasterized at {VECTOR_PAGE_DPI} DPI, losing some resolution and "
|
||||||
"increasing file size. Use --oversample to adjust the "
|
"likely increasing file size. Use --oversample to adjust the "
|
||||||
"DPI."
|
"DPI."
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
@@ -337,10 +361,13 @@ def is_ocr_required(page_context: PageContext):
|
|||||||
return ocr_required
|
return ocr_required
|
||||||
|
|
||||||
|
|
||||||
def rasterize_preview(input_file: Path, page_context: PageContext):
|
def rasterize_preview(input_file: Path, page_context: PageContext) -> Path:
|
||||||
|
"""Generate a lower quality preview image."""
|
||||||
output_file = page_context.get_path('rasterize_preview.jpg')
|
output_file = page_context.get_path('rasterize_preview.jpg')
|
||||||
canvas_dpi = get_canvas_square_dpi(page_context.pageinfo, page_context.options)
|
canvas_dpi = Resolution(300.0, 300.0).take_min(
|
||||||
page_dpi = get_page_square_dpi(page_context.pageinfo, page_context.options)
|
[get_canvas_square_dpi(page_context)]
|
||||||
|
)
|
||||||
|
page_dpi = Resolution(300.0, 300.0).take_min([get_page_square_dpi(page_context)])
|
||||||
page_context.plugin_manager.hook.rasterize_pdf_page(
|
page_context.plugin_manager.hook.rasterize_pdf_page(
|
||||||
input_file=input_file,
|
input_file=input_file,
|
||||||
output_file=output_file,
|
output_file=output_file,
|
||||||
@@ -350,14 +377,15 @@ def rasterize_preview(input_file: Path, page_context: PageContext):
|
|||||||
page_dpi=page_dpi,
|
page_dpi=page_dpi,
|
||||||
rotation=0,
|
rotation=0,
|
||||||
filter_vector=False,
|
filter_vector=False,
|
||||||
|
stop_on_soft_error=not page_context.options.continue_on_soft_render_error,
|
||||||
)
|
)
|
||||||
return output_file
|
return output_file
|
||||||
|
|
||||||
|
|
||||||
def describe_rotation(page_context: PageContext, orient_conf, correction: int):
|
def describe_rotation(
|
||||||
"""
|
page_context: PageContext, orient_conf: OrientationConfidence, correction: int
|
||||||
Describe the page rotation we are going to perform.
|
) -> str:
|
||||||
"""
|
"""Describe the page rotation we are going to perform (or not perform)."""
|
||||||
direction = {0: '⇧', 90: '⇨', 180: '⇩', 270: '⇦'}
|
direction = {0: '⇧', 90: '⇨', 180: '⇩', 270: '⇦'}
|
||||||
turns = {0: ' ', 90: '⬏', 180: '↻', 270: '⬑'}
|
turns = {0: ' ', 90: '⬏', 180: '↻', 270: '⬑'}
|
||||||
|
|
||||||
@@ -383,8 +411,8 @@ def describe_rotation(page_context: PageContext, orient_conf, correction: int):
|
|||||||
return f"{facing}, confidence {orient_conf.confidence:.2f} - {action}"
|
return f"{facing}, confidence {orient_conf.confidence:.2f} - {action}"
|
||||||
|
|
||||||
|
|
||||||
def get_orientation_correction(preview: Path, page_context: PageContext):
|
def get_orientation_correction(preview: Path, page_context: PageContext) -> int:
|
||||||
"""Work out orientation correct for each page.
|
"""Work out orientation correction for each page.
|
||||||
|
|
||||||
We ask Ghostscript to draw a preview page, which will rasterize with the
|
We ask Ghostscript to draw a preview page, which will rasterize with the
|
||||||
current /Rotate applied, and then ask OCR which way the page is
|
current /Rotate applied, and then ask OCR which way the page is
|
||||||
@@ -398,7 +426,6 @@ def get_orientation_correction(preview: Path, page_context: PageContext):
|
|||||||
which points it (hopefully) upright. _graft.py takes care of the orienting
|
which points it (hopefully) upright. _graft.py takes care of the orienting
|
||||||
the image and text layers.
|
the image and text layers.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
orient_conf = page_context.plugin_manager.hook.get_ocr_engine().get_orientation(
|
orient_conf = page_context.plugin_manager.hook.get_ocr_engine().get_orientation(
|
||||||
preview, page_context.options
|
preview, page_context.options
|
||||||
)
|
)
|
||||||
@@ -414,13 +441,59 @@ def get_orientation_correction(preview: Path, page_context: PageContext):
|
|||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def calculate_image_dpi(page_context: PageContext) -> Resolution:
|
||||||
|
"""Calculate the DPI for the page image."""
|
||||||
|
pageinfo = page_context.pageinfo
|
||||||
|
dpi_profile = pageinfo.page_dpi_profile()
|
||||||
|
if dpi_profile and dpi_profile.average_to_max_dpi_ratio < 0.8:
|
||||||
|
image_dpi = Resolution(dpi_profile.weighted_dpi, dpi_profile.weighted_dpi)
|
||||||
|
else:
|
||||||
|
image_dpi = pageinfo.dpi
|
||||||
|
return image_dpi
|
||||||
|
|
||||||
|
|
||||||
|
def calculate_raster_dpi(page_context: PageContext):
|
||||||
|
"""Calculate the DPI for rasterization."""
|
||||||
|
# Produce the page image with square resolution or else deskew and OCR
|
||||||
|
# will not work properly.
|
||||||
|
image_dpi = calculate_image_dpi(page_context)
|
||||||
|
dpi_profile = page_context.pageinfo.page_dpi_profile()
|
||||||
|
canvas_dpi = get_canvas_square_dpi(page_context, image_dpi)
|
||||||
|
page_dpi = get_page_square_dpi(page_context, image_dpi)
|
||||||
|
if dpi_profile and dpi_profile.average_to_max_dpi_ratio < 0.8:
|
||||||
|
log.warning(
|
||||||
|
"Weight average image DPI is %0.1f, max DPI is %0.1f. "
|
||||||
|
"The discrepancy may indicate a high detail region on this page, "
|
||||||
|
"but could also indicate a problem with the input PDF file. "
|
||||||
|
"Page image will be rendered at %0.1f DPI.",
|
||||||
|
dpi_profile.weighted_dpi,
|
||||||
|
dpi_profile.max_dpi,
|
||||||
|
canvas_dpi.to_scalar(),
|
||||||
|
)
|
||||||
|
return canvas_dpi, page_dpi
|
||||||
|
|
||||||
|
|
||||||
def rasterize(
|
def rasterize(
|
||||||
input_file: Path,
|
input_file: Path,
|
||||||
page_context: PageContext,
|
page_context: PageContext,
|
||||||
correction: int = 0,
|
correction: int = 0,
|
||||||
output_tag: str = '',
|
output_tag: str = '',
|
||||||
remove_vectors=None,
|
remove_vectors: bool | None = None,
|
||||||
):
|
) -> Path:
|
||||||
|
"""Rasterize a PDF page to a PNG image.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
input_file: The input PDF file path.
|
||||||
|
page_context: The page context object.
|
||||||
|
correction: The orientation correction angle. Defaults to 0.
|
||||||
|
output_tag: The output tag. Defaults to ''.
|
||||||
|
remove_vectors: Whether to remove vectors. Defaults to None, which means
|
||||||
|
the value from the page context options will be used. If the value
|
||||||
|
is True or False, it will override the page context options.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Path: The output PNG file path.
|
||||||
|
"""
|
||||||
colorspaces = ['pngmono', 'pnggray', 'png256', 'png16m']
|
colorspaces = ['pngmono', 'pnggray', 'png256', 'png16m']
|
||||||
device_idx = 0
|
device_idx = 0
|
||||||
|
|
||||||
@@ -445,16 +518,14 @@ def rasterize(
|
|||||||
device_idx = at_least('png16m')
|
device_idx = at_least('png16m')
|
||||||
|
|
||||||
if pageinfo.has_vector:
|
if pageinfo.has_vector:
|
||||||
|
log.debug("Page has vector content, using png16m")
|
||||||
device_idx = at_least('png16m')
|
device_idx = at_least('png16m')
|
||||||
|
|
||||||
device = colorspaces[device_idx]
|
device = colorspaces[device_idx]
|
||||||
|
|
||||||
log.debug(f"Rasterize with {device}, rotation {correction}")
|
log.debug(f"Rasterize with {device}, rotation {correction}")
|
||||||
|
|
||||||
# Produce the page image with square resolution or else deskew and OCR
|
canvas_dpi, page_dpi = calculate_raster_dpi(page_context)
|
||||||
# will not work properly.
|
|
||||||
canvas_dpi = get_canvas_square_dpi(pageinfo, page_context.options)
|
|
||||||
page_dpi = get_page_square_dpi(pageinfo, page_context.options)
|
|
||||||
|
|
||||||
page_context.plugin_manager.hook.rasterize_pdf_page(
|
page_context.plugin_manager.hook.rasterize_pdf_page(
|
||||||
input_file=input_file,
|
input_file=input_file,
|
||||||
@@ -465,24 +536,34 @@ def rasterize(
|
|||||||
pageno=pageinfo.pageno + 1,
|
pageno=pageinfo.pageno + 1,
|
||||||
rotation=correction,
|
rotation=correction,
|
||||||
filter_vector=remove_vectors,
|
filter_vector=remove_vectors,
|
||||||
|
stop_on_soft_error=not page_context.options.continue_on_soft_render_error,
|
||||||
)
|
)
|
||||||
return output_file
|
return output_file
|
||||||
|
|
||||||
|
|
||||||
def preprocess_remove_background(input_file: Path, page_context: PageContext):
|
def preprocess_remove_background(input_file: Path, page_context: PageContext) -> Path:
|
||||||
|
"""Remove the background from the input image (temporarily disabled)."""
|
||||||
if any(image.bpc > 1 for image in page_context.pageinfo.images):
|
if any(image.bpc > 1 for image in page_context.pageinfo.images):
|
||||||
raise NotImplementedError("--remove-background is temporarily not implemented")
|
raise NotImplementedError("--remove-background is temporarily not implemented")
|
||||||
# output_file = page_context.get_path('pp_rm_bg.png')
|
# output_file = page_context.get_path('pp_rm_bg.png')
|
||||||
# leptonica.remove_background(input_file, output_file)
|
# leptonica.remove_background(input_file, output_file)
|
||||||
# return output_file
|
# return output_file
|
||||||
else:
|
log.info("background removal skipped on mono page")
|
||||||
log.info("background removal skipped on mono page")
|
return input_file
|
||||||
return input_file
|
|
||||||
|
|
||||||
|
|
||||||
def preprocess_deskew(input_file: Path, page_context: PageContext):
|
def preprocess_deskew(input_file: Path, page_context: PageContext) -> Path:
|
||||||
|
"""Deskews the input image using the OCR engine and saves the output to a file.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
input_file: The input image file to deskew.
|
||||||
|
page_context: The context of the page being processed.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Path: The path to the deskewed image file.
|
||||||
|
"""
|
||||||
output_file = page_context.get_path('pp_deskew.png')
|
output_file = page_context.get_path('pp_deskew.png')
|
||||||
dpi = get_page_square_dpi(page_context.pageinfo, page_context.options)
|
dpi = get_page_square_dpi(page_context, calculate_image_dpi(page_context))
|
||||||
|
|
||||||
ocr_engine = page_context.plugin_manager.hook.get_ocr_engine()
|
ocr_engine = page_context.plugin_manager.hook.get_ocr_engine()
|
||||||
deskew_angle_degrees = ocr_engine.get_deskew(input_file, page_context.options)
|
deskew_angle_degrees = ocr_engine.get_deskew(input_file, page_context.options)
|
||||||
@@ -492,7 +573,7 @@ def preprocess_deskew(input_file: Path, page_context: PageContext):
|
|||||||
# resampling if image is mode '1' or 'P'
|
# resampling if image is mode '1' or 'P'
|
||||||
deskewed = im.rotate(
|
deskewed = im.rotate(
|
||||||
deskew_angle_degrees,
|
deskew_angle_degrees,
|
||||||
resample=BICUBIC,
|
resample=Image.Resampling.BICUBIC,
|
||||||
fillcolor=ImageColor.getcolor('white', mode=im.mode), # type: ignore
|
fillcolor=ImageColor.getcolor('white', mode=im.mode), # type: ignore
|
||||||
)
|
)
|
||||||
deskewed.save(output_file, dpi=dpi)
|
deskewed.save(output_file, dpi=dpi)
|
||||||
@@ -500,22 +581,24 @@ def preprocess_deskew(input_file: Path, page_context: PageContext):
|
|||||||
return output_file
|
return output_file
|
||||||
|
|
||||||
|
|
||||||
def preprocess_clean(input_file: Path, page_context: PageContext):
|
def preprocess_clean(input_file: Path, page_context: PageContext) -> Path:
|
||||||
|
"""Clean the input image using unpaper."""
|
||||||
output_file = page_context.get_path('pp_clean.png')
|
output_file = page_context.get_path('pp_clean.png')
|
||||||
dpi = get_page_square_dpi(page_context.pageinfo, page_context.options)
|
dpi = get_page_square_dpi(page_context, calculate_image_dpi(page_context))
|
||||||
return unpaper.clean(
|
return unpaper.clean(
|
||||||
input_file,
|
input_file,
|
||||||
output_file,
|
output_file,
|
||||||
dpi=dpi.x,
|
dpi=dpi.to_scalar(),
|
||||||
unpaper_args=page_context.options.unpaper_args,
|
unpaper_args=page_context.options.unpaper_args,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def create_ocr_image(image: Path, page_context: PageContext):
|
def create_ocr_image(image: Path, page_context: PageContext) -> Path:
|
||||||
"""Create the image we send for OCR. May not be the same as the display
|
"""Create the image we send for OCR.
|
||||||
image depending on preprocessing. This image will never be shown to the
|
|
||||||
user."""
|
|
||||||
|
|
||||||
|
Might not be the same as the display image depending on preprocessing.
|
||||||
|
This image will never be shown to the user.
|
||||||
|
"""
|
||||||
output_file = page_context.get_path('ocr.png')
|
output_file = page_context.get_path('ocr.png')
|
||||||
options = page_context.options
|
options = page_context.options
|
||||||
with Image.open(image) as im:
|
with Image.open(image) as im:
|
||||||
@@ -559,7 +642,8 @@ def create_ocr_image(image: Path, page_context: PageContext):
|
|||||||
return output_file
|
return output_file
|
||||||
|
|
||||||
|
|
||||||
def ocr_engine_hocr(input_file: Path, page_context: PageContext):
|
def ocr_engine_hocr(input_file: Path, page_context: PageContext) -> tuple[Path, Path]:
|
||||||
|
"""Run the OCR engine and generate hOCR output."""
|
||||||
hocr_out = page_context.get_path('ocr_hocr.hocr')
|
hocr_out = page_context.get_path('ocr_hocr.hocr')
|
||||||
hocr_text_out = page_context.get_path('ocr_hocr.txt')
|
hocr_text_out = page_context.get_path('ocr_hocr.txt')
|
||||||
options = page_context.options
|
options = page_context.options
|
||||||
@@ -571,15 +655,30 @@ def ocr_engine_hocr(input_file: Path, page_context: PageContext):
|
|||||||
output_text=hocr_text_out,
|
output_text=hocr_text_out,
|
||||||
options=options,
|
options=options,
|
||||||
)
|
)
|
||||||
return (hocr_out, hocr_text_out)
|
return hocr_out, hocr_text_out
|
||||||
|
|
||||||
|
|
||||||
def should_visible_page_image_use_jpg(pageinfo):
|
def should_visible_page_image_use_jpg(pageinfo: PageInfo) -> bool:
|
||||||
# If all images were JPEGs originally, produce a JPEG as output
|
"""Determines whether the visible page image should be saved as a JPEG.
|
||||||
return pageinfo.images and all(im.enc == Encoding.jpeg for im in pageinfo.images)
|
|
||||||
|
If all images were JPEGs originally, permit a JPEG as output.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
pageinfo: The PageInfo object containing information about the page.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
A boolean indicating whether the visible page image should be saved as a JPEG.
|
||||||
|
"""
|
||||||
|
return bool(pageinfo.images) and all(
|
||||||
|
im.enc == Encoding.jpeg for im in pageinfo.images
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def create_visible_page_jpg(image: Path, page_context: PageContext) -> Path:
|
def create_visible_page_jpg(image: Path, page_context: PageContext) -> Path:
|
||||||
|
"""Create a visible page image in JPEG format.
|
||||||
|
|
||||||
|
This is intended to be used when all images on the page were originally JPEGs.
|
||||||
|
"""
|
||||||
output_file = page_context.get_path('visible.jpg')
|
output_file = page_context.get_path('visible.jpg')
|
||||||
with Image.open(image) as im:
|
with Image.open(image) as im:
|
||||||
# At this point the image should be a .png, but deskew, unpaper
|
# At this point the image should be a .png, but deskew, unpaper
|
||||||
@@ -591,7 +690,7 @@ def create_visible_page_jpg(image: Path, page_context: PageContext) -> Path:
|
|||||||
dpi = Resolution(*im.info['dpi'])
|
dpi = Resolution(*im.info['dpi'])
|
||||||
else:
|
else:
|
||||||
# Fallback to page-implied DPI
|
# Fallback to page-implied DPI
|
||||||
dpi = get_page_square_dpi(page_context.pageinfo, page_context.options)
|
dpi = get_page_square_dpi(page_context, calculate_image_dpi(page_context))
|
||||||
|
|
||||||
# Pillow requires integer DPI
|
# Pillow requires integer DPI
|
||||||
im.save(output_file, format='JPEG', dpi=dpi.to_int())
|
im.save(output_file, format='JPEG', dpi=dpi.to_int())
|
||||||
@@ -599,8 +698,9 @@ def create_visible_page_jpg(image: Path, page_context: PageContext) -> Path:
|
|||||||
|
|
||||||
|
|
||||||
def create_pdf_page_from_image(
|
def create_pdf_page_from_image(
|
||||||
image: Path, page_context: PageContext, orientation_correction
|
image: Path, page_context: PageContext, orientation_correction: int
|
||||||
):
|
) -> Path:
|
||||||
|
"""Create a PDF page from a page image."""
|
||||||
# We rasterize a square DPI version of each page because most image
|
# We rasterize a square DPI version of each page because most image
|
||||||
# processing tools don't support rectangular DPI. Use the square DPI as it
|
# processing tools don't support rectangular DPI. Use the square DPI as it
|
||||||
# accurately describes the image. It would be possible to resample the image
|
# accurately describes the image. It would be possible to resample the image
|
||||||
@@ -628,28 +728,36 @@ def create_pdf_page_from_image(
|
|||||||
output_file = page_context.plugin_manager.hook.filter_pdf_page(
|
output_file = page_context.plugin_manager.hook.filter_pdf_page(
|
||||||
page=page_context, image_filename=image, output_pdf=output_file
|
page=page_context, image_filename=image, output_pdf=output_file
|
||||||
)
|
)
|
||||||
|
|
||||||
return output_file
|
return output_file
|
||||||
|
|
||||||
|
|
||||||
def render_hocr_page(hocr: Path, page_context: PageContext):
|
def render_hocr_page(hocr: Path, page_context: PageContext) -> Path:
|
||||||
|
"""Render the hOCR page to a PDF."""
|
||||||
options = page_context.options
|
options = page_context.options
|
||||||
output_file = page_context.get_path('ocr_hocr.pdf')
|
output_file = page_context.get_path('ocr_hocr.pdf')
|
||||||
dpi = get_page_square_dpi(page_context.pageinfo, options)
|
if hocr.stat().st_size == 0:
|
||||||
|
# If hOCR file is empty (skipped page marker), create an empty PDF file
|
||||||
|
output_file.touch()
|
||||||
|
return output_file
|
||||||
|
|
||||||
|
dpi = get_page_square_dpi(page_context, calculate_image_dpi(page_context))
|
||||||
debug_mode = options.pdf_renderer == 'hocrdebug'
|
debug_mode = options.pdf_renderer == 'hocrdebug'
|
||||||
|
|
||||||
hocrtransform = HocrTransform(hocr_filename=hocr, dpi=dpi.x) # square
|
HocrTransform(
|
||||||
hocrtransform.to_pdf(
|
hocr_filename=hocr,
|
||||||
|
dpi=dpi.to_scalar(), # square
|
||||||
|
debug=debug_mode,
|
||||||
|
).to_pdf(
|
||||||
out_filename=output_file,
|
out_filename=output_file,
|
||||||
image_filename=None,
|
image_filename=None,
|
||||||
show_bounding_boxes=False if not debug_mode else True,
|
|
||||||
invisible_text=True if not debug_mode else False,
|
|
||||||
interword_spaces=True,
|
|
||||||
)
|
)
|
||||||
return output_file
|
return output_file
|
||||||
|
|
||||||
|
|
||||||
def ocr_engine_textonly_pdf(input_image: Path, page_context: PageContext):
|
def ocr_engine_textonly_pdf(
|
||||||
|
input_image: Path, page_context: PageContext
|
||||||
|
) -> tuple[Path, Path]:
|
||||||
|
"""Run the OCR engine and generate a text-only PDF (will look blank)."""
|
||||||
output_pdf = page_context.get_path('ocr_tess.pdf')
|
output_pdf = page_context.get_path('ocr_tess.pdf')
|
||||||
output_text = page_context.get_path('ocr_tess.txt')
|
output_text = page_context.get_path('ocr_tess.txt')
|
||||||
options = page_context.options
|
options = page_context.options
|
||||||
@@ -664,44 +772,29 @@ def ocr_engine_textonly_pdf(input_image: Path, page_context: PageContext):
|
|||||||
return (output_pdf, output_text)
|
return (output_pdf, output_text)
|
||||||
|
|
||||||
|
|
||||||
def get_docinfo(base_pdf: pikepdf.Pdf, context: PdfContext) -> dict[str, str]:
|
def generate_postscript_stub(context: PdfContext) -> Path:
|
||||||
options = context.options
|
"""Generates a PostScript file stub for the given PDF context.
|
||||||
|
|
||||||
def from_document_info(key):
|
Args:
|
||||||
try:
|
context: The PDF context to generate the PostScript file stub for.
|
||||||
s = base_pdf.docinfo[key]
|
|
||||||
return str(s)
|
|
||||||
except (KeyError, TypeError):
|
|
||||||
return ''
|
|
||||||
|
|
||||||
pdfmark = {
|
Returns:
|
||||||
k: from_document_info(k)
|
Path: The path to the generated PostScript file stub.
|
||||||
for k in ('/Title', '/Author', '/Keywords', '/Subject', '/CreationDate')
|
"""
|
||||||
}
|
|
||||||
if options.title:
|
|
||||||
pdfmark['/Title'] = options.title
|
|
||||||
if options.author:
|
|
||||||
pdfmark['/Author'] = options.author
|
|
||||||
if options.keywords:
|
|
||||||
pdfmark['/Keywords'] = options.keywords
|
|
||||||
if options.subject:
|
|
||||||
pdfmark['/Subject'] = options.subject
|
|
||||||
|
|
||||||
creator_tag = context.plugin_manager.hook.get_ocr_engine().creator_tag(options)
|
|
||||||
|
|
||||||
pdfmark['/Creator'] = f'{PROGRAM_NAME} {VERSION} / {creator_tag}'
|
|
||||||
pdfmark['/Producer'] = f'pikepdf {pikepdf.__version__}'
|
|
||||||
pdfmark['/ModDate'] = encode_pdf_date(datetime.now(timezone.utc))
|
|
||||||
return pdfmark
|
|
||||||
|
|
||||||
|
|
||||||
def generate_postscript_stub(context: PdfContext):
|
|
||||||
output_file = context.get_path('pdfa.ps')
|
output_file = context.get_path('pdfa.ps')
|
||||||
generate_pdfa_ps(output_file)
|
generate_pdfa_ps(output_file)
|
||||||
return output_file
|
return output_file
|
||||||
|
|
||||||
|
|
||||||
def convert_to_pdfa(input_pdf: Path, input_ps_stub: Path, context: PdfContext):
|
def convert_to_pdfa(input_pdf: Path, input_ps_stub: Path, context: PdfContext) -> Path:
|
||||||
|
"""Converts the given PDF to PDF/A.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
input_pdf: The input PDF file path (presumably not PDF/A).
|
||||||
|
input_ps_stub: The input PostScript file path, containing instructions
|
||||||
|
for the PDF/A generator to use.
|
||||||
|
context: The PDF context.
|
||||||
|
"""
|
||||||
options = context.options
|
options = context.options
|
||||||
input_pdfinfo = context.pdfinfo
|
input_pdfinfo = context.pdfinfo
|
||||||
fix_docinfo_file = context.get_path('fix_docinfo.pdf')
|
fix_docinfo_file = context.get_path('fix_docinfo.pdf')
|
||||||
@@ -712,21 +805,8 @@ def convert_to_pdfa(input_pdf: Path, input_ps_stub: Path, context: PdfContext):
|
|||||||
# NULs in DocumentInfo seem to be common since older Acrobats included them.
|
# NULs in DocumentInfo seem to be common since older Acrobats included them.
|
||||||
# pikepdf can deal with this, but we make the world a better place by
|
# pikepdf can deal with this, but we make the world a better place by
|
||||||
# stamping them out as soon as possible.
|
# stamping them out as soon as possible.
|
||||||
modified = False
|
|
||||||
with pikepdf.open(input_pdf) as pdf_file:
|
with pikepdf.open(input_pdf) as pdf_file:
|
||||||
try:
|
if repair_docinfo_nuls(pdf_file):
|
||||||
len(pdf_file.docinfo)
|
|
||||||
except TypeError:
|
|
||||||
log.error(
|
|
||||||
"File contains a malformed DocumentInfo block - continuing anyway"
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
if pdf_file.docinfo:
|
|
||||||
for k, v in pdf_file.docinfo.items():
|
|
||||||
if b'\x00' in bytes(v):
|
|
||||||
pdf_file.docinfo[k] = bytes(v).replace(b'\x00', b'')
|
|
||||||
modified = True
|
|
||||||
if modified:
|
|
||||||
pdf_file.save(fix_docinfo_file)
|
pdf_file.save(fix_docinfo_file)
|
||||||
else:
|
else:
|
||||||
safe_symlink(input_pdf, fix_docinfo_file)
|
safe_symlink(input_pdf, fix_docinfo_file)
|
||||||
@@ -736,26 +816,36 @@ def convert_to_pdfa(input_pdf: Path, input_ps_stub: Path, context: PdfContext):
|
|||||||
pdf_pages=[fix_docinfo_file],
|
pdf_pages=[fix_docinfo_file],
|
||||||
pdfmark=input_ps_stub,
|
pdfmark=input_ps_stub,
|
||||||
output_file=output_file,
|
output_file=output_file,
|
||||||
compression=options.pdfa_image_compression,
|
context=context,
|
||||||
pdfa_part=options.output_type[-1], # is pdfa-1, pdfa-2, or pdfa-3
|
pdfa_part=options.output_type[-1], # is pdfa-1, pdfa-2, or pdfa-3
|
||||||
progressbar_class=(
|
progressbar_class=(
|
||||||
context.plugin_manager.hook.get_progressbar_class()
|
context.plugin_manager.hook.get_progressbar_class()
|
||||||
if options.progress_bar
|
if options.progress_bar
|
||||||
else None
|
else None
|
||||||
),
|
),
|
||||||
|
stop_on_soft_error=not options.continue_on_soft_render_error,
|
||||||
)
|
)
|
||||||
|
|
||||||
return output_file
|
return output_file
|
||||||
|
|
||||||
|
|
||||||
def should_linearize(working_file: Path, context: PdfContext):
|
def should_linearize(working_file: Path, context: PdfContext) -> bool:
|
||||||
|
"""Determine whether the PDF should be linearized.
|
||||||
|
|
||||||
|
For smaller files, linearization is not worth the effort.
|
||||||
|
"""
|
||||||
filesize = os.stat(working_file).st_size
|
filesize = os.stat(working_file).st_size
|
||||||
if filesize > (context.options.fast_web_view * 1_000_000):
|
if filesize > (context.options.fast_web_view * 1_000_000):
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def get_pdf_save_settings(output_type: str):
|
def get_pdf_save_settings(output_type: str) -> dict[str, Any]:
|
||||||
|
"""Get pikepdf.Pdf.save settings for the given output type.
|
||||||
|
|
||||||
|
Essentially, don't use features that are incompatible with a given
|
||||||
|
PDF/A specification.
|
||||||
|
"""
|
||||||
if output_type == 'pdfa-1':
|
if output_type == 'pdfa-1':
|
||||||
# Trigger recompression to ensure object streams are removed, because
|
# Trigger recompression to ensure object streams are removed, because
|
||||||
# Acrobat complains about them in PDF/A-1b validation.
|
# Acrobat complains about them in PDF/A-1b validation.
|
||||||
@@ -773,63 +863,33 @@ def get_pdf_save_settings(output_type: str):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def metadata_fixup(working_file: Path, context: PdfContext):
|
def _file_size_ratio(
|
||||||
output_file = context.get_path('metafix.pdf')
|
input_file: Path, output_file: Path
|
||||||
options = context.options
|
) -> tuple[float | None, float | None]:
|
||||||
|
"""Calculate ratio of input to output file sizes and percentage savings.
|
||||||
|
|
||||||
def report_on_metadata(missing):
|
Args:
|
||||||
if not missing:
|
input_file (Path): The path to the input file.
|
||||||
return
|
output_file (Path): The path to the output file.
|
||||||
if options.output_type.startswith('pdfa'):
|
|
||||||
log.warning(
|
|
||||||
"Some input metadata could not be copied because it is not "
|
|
||||||
"permitted in PDF/A. You may wish to examine the output "
|
|
||||||
"PDF's XMP metadata."
|
|
||||||
)
|
|
||||||
log.debug("The following metadata fields were not copied: %r", missing)
|
|
||||||
else:
|
|
||||||
log.error(
|
|
||||||
"Some input metadata could not be copied."
|
|
||||||
"You may wish to examine the output PDF's XMP metadata."
|
|
||||||
)
|
|
||||||
log.info("The following metadata fields were not copied: %r", missing)
|
|
||||||
|
|
||||||
with pikepdf.open(context.origin) as original, pikepdf.open(working_file) as pdf:
|
Returns:
|
||||||
docinfo = get_docinfo(original, context)
|
tuple[float | None, float | None]: A tuple containing the file size
|
||||||
with pdf.open_metadata() as meta:
|
ratio and the percentage savings achieved by the output file size
|
||||||
meta.load_from_docinfo(docinfo, delete_missing=False, raise_failure=False)
|
compared to the input file size.
|
||||||
# If xmp:CreateDate is missing, set it to the modify date to
|
"""
|
||||||
# match Ghostscript, for consistency
|
input_size = input_file.stat().st_size
|
||||||
if 'xmp:CreateDate' not in meta:
|
output_size = output_file.stat().st_size
|
||||||
meta['xmp:CreateDate'] = meta.get('xmp:ModifyDate', '')
|
if output_size == 0:
|
||||||
|
return None, None
|
||||||
with original.open_metadata(
|
ratio = input_size / output_size
|
||||||
set_pikepdf_as_editor=False, update_docinfo=False, strict=False
|
savings = 1 - output_size / input_size
|
||||||
) as meta_original:
|
return ratio, savings
|
||||||
if meta.get('dc:title') == 'Untitled':
|
|
||||||
# Ghostscript likes to set title to Untitled if omitted from input.
|
|
||||||
# Reverse this, because PDF/A TechNote 0003:Metadata in PDF/A-1
|
|
||||||
# and the XMP Spec do not make this recommendation.
|
|
||||||
if 'dc:title' not in meta_original:
|
|
||||||
del meta['dc:title']
|
|
||||||
missing = set(meta_original.keys()) - set(meta.keys())
|
|
||||||
report_on_metadata(missing)
|
|
||||||
|
|
||||||
optimizing = context.plugin_manager.hook.is_optimization_enabled(
|
|
||||||
context=context
|
|
||||||
)
|
|
||||||
pdf.save(
|
|
||||||
output_file,
|
|
||||||
**get_pdf_save_settings(options.output_type),
|
|
||||||
linearize=( # Don't linearize if optimize() will be linearizing too
|
|
||||||
not optimizing and should_linearize(working_file, context)
|
|
||||||
),
|
|
||||||
)
|
|
||||||
|
|
||||||
return output_file
|
|
||||||
|
|
||||||
|
|
||||||
def optimize_pdf(input_file: Path, context: PdfContext, executor: Executor):
|
def optimize_pdf(
|
||||||
|
input_file: Path, context: PdfContext, executor: Executor
|
||||||
|
) -> tuple[Path, Sequence[str]]:
|
||||||
|
"""Optimize the given PDF file."""
|
||||||
output_file = context.get_path('optimize.pdf')
|
output_file = context.get_path('optimize.pdf')
|
||||||
output_pdf, messages = context.plugin_manager.hook.optimize_pdf(
|
output_pdf, messages = context.plugin_manager.hook.optimize_pdf(
|
||||||
input_pdf=input_file,
|
input_pdf=input_file,
|
||||||
@@ -839,17 +899,29 @@ def optimize_pdf(input_file: Path, context: PdfContext, executor: Executor):
|
|||||||
linearize=should_linearize(input_file, context),
|
linearize=should_linearize(input_file, context),
|
||||||
)
|
)
|
||||||
|
|
||||||
input_size = input_file.stat().st_size
|
ratio, savings = _file_size_ratio(input_file, output_file)
|
||||||
output_size = output_file.stat().st_size
|
if ratio:
|
||||||
if output_size > 0:
|
log.info(f"Image optimization ratio: {ratio:.2f} savings: {(savings):.1%}")
|
||||||
ratio = input_size / output_size
|
ratio, savings = _file_size_ratio(context.origin, output_file)
|
||||||
savings = 1 - output_size / input_size
|
if ratio:
|
||||||
log.info(f"Optimize ratio: {ratio:.2f} savings: {(savings):.1%}")
|
log.info(f"Total file size ratio: {ratio:.2f} savings: {(savings):.1%}")
|
||||||
|
|
||||||
return output_pdf, messages
|
return output_pdf, messages
|
||||||
|
|
||||||
|
|
||||||
def enumerate_compress_ranges(iterable):
|
def enumerate_compress_ranges(
|
||||||
|
iterable: Iterable[T],
|
||||||
|
) -> Iterator[tuple[tuple[int, int], T | None]]:
|
||||||
|
"""Enumerate the ranges of non-empty elements in an iterable.
|
||||||
|
|
||||||
|
Compresses consecutive ranges of length 1 into single elements.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
iterable: An iterable of elements to enumerate.
|
||||||
|
|
||||||
|
Yields:
|
||||||
|
A tuple containing a range of indices and the corresponding element.
|
||||||
|
If the element is None, the range represents a skipped range of indices.
|
||||||
|
"""
|
||||||
skipped_from, index = None, None
|
skipped_from, index = None, None
|
||||||
for index, txt_file in enumerate(iterable):
|
for index, txt_file in enumerate(iterable):
|
||||||
index += 1
|
index += 1
|
||||||
@@ -865,22 +937,23 @@ def enumerate_compress_ranges(iterable):
|
|||||||
yield (skipped_from, index), None
|
yield (skipped_from, index), None
|
||||||
|
|
||||||
|
|
||||||
def merge_sidecars(txt_files: Iterable[Path | None], context: PdfContext):
|
def merge_sidecars(txt_files: Iterable[Path | None], context: PdfContext) -> Path:
|
||||||
|
"""Merge the page sidecar files into a single file.
|
||||||
|
|
||||||
|
Sidecar files are created by the OCR engine and contain the text for each
|
||||||
|
page in the PDF. This function merges the sidecar files into a single file
|
||||||
|
and returns the path to the merged file.
|
||||||
|
"""
|
||||||
output_file = context.get_path('sidecar.txt')
|
output_file = context.get_path('sidecar.txt')
|
||||||
with open(output_file, 'w', encoding="utf-8") as stream:
|
with open(output_file, 'w', encoding="utf-8") as stream:
|
||||||
for (from_, to_), txt_file in enumerate_compress_ranges(txt_files):
|
for (from_, to_), txt_file in enumerate_compress_ranges(txt_files):
|
||||||
if from_ != 1:
|
if from_ != 1:
|
||||||
stream.write('\f') # Form feed between pages
|
stream.write('\f') # Form feed between pages for all pages after first
|
||||||
if txt_file:
|
if txt_file:
|
||||||
with open(txt_file, encoding="utf-8") as in_:
|
txt = txt_file.read_text(encoding="utf-8")
|
||||||
txt = in_.read()
|
# Some versions of Tesseract add a form feed at the end and
|
||||||
# Some OCR engines (e.g. Tesseract v4 alpha) add form feeds
|
# others don't. Remove it if it exists, since we add one manually.
|
||||||
# between pages, and some do not. For consistency, we ignore
|
stream.write(txt.removesuffix('\f'))
|
||||||
# any added by the OCR engine and them on our own.
|
|
||||||
if txt.endswith('\f'):
|
|
||||||
stream.write(txt[:-1])
|
|
||||||
else:
|
|
||||||
stream.write(txt)
|
|
||||||
else:
|
else:
|
||||||
if from_ != to_:
|
if from_ != to_:
|
||||||
pages = f'{from_}-{to_}'
|
pages = f'{from_}-{to_}'
|
||||||
@@ -890,20 +963,32 @@ def merge_sidecars(txt_files: Iterable[Path | None], context: PdfContext):
|
|||||||
return output_file
|
return output_file
|
||||||
|
|
||||||
|
|
||||||
def copy_final(input_file, output_file, _context: PdfContext):
|
def copy_final(
|
||||||
|
input_file: Path, output_file: str | Path | BinaryIO, original_file: Path | None
|
||||||
|
) -> None:
|
||||||
|
"""Copy the final temporary file to the output destination.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
input_file (Path): The intermediate input file to copy.
|
||||||
|
output_file (str | Path | BinaryIO): The output file to copy to.
|
||||||
|
original_file: The original file to copy attributes from.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
None
|
||||||
|
"""
|
||||||
log.debug('%s -> %s', input_file, output_file)
|
log.debug('%s -> %s', input_file, output_file)
|
||||||
with open(input_file, 'rb') as input_stream:
|
with input_file.open('rb') as input_stream:
|
||||||
if output_file == '-':
|
if output_file == '-':
|
||||||
copyfileobj(input_stream, sys.stdout.buffer)
|
copyfileobj(input_stream, sys.stdout.buffer) # type: ignore[misc]
|
||||||
sys.stdout.flush()
|
sys.stdout.flush()
|
||||||
elif hasattr(output_file, 'writable'):
|
elif hasattr(output_file, 'writable'):
|
||||||
output_stream = output_file
|
output_stream = cast(BinaryIO, output_file)
|
||||||
copyfileobj(input_stream, output_stream)
|
copyfileobj(input_stream, output_stream) # type: ignore[misc]
|
||||||
with suppress(AttributeError):
|
with suppress(AttributeError):
|
||||||
output_stream.flush()
|
output_stream.flush()
|
||||||
else:
|
else:
|
||||||
# At this point we overwrite the output_file specified by the user
|
# At this point we overwrite the output_file specified by the user
|
||||||
# use copyfileobj because then we use open() to create the file and
|
# use copyfileobj because then we use open() to create the file and
|
||||||
# get the appropriate umask, ownership, etc.
|
# get the appropriate umask, ownership, etc.
|
||||||
with open(output_file, 'wb') as output_stream:
|
with open(output_file, 'w+b') as output_stream:
|
||||||
copyfileobj(input_stream, output_stream)
|
copyfileobj(input_stream, output_stream)
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# SPDX-FileCopyrightText: 2023 James R. Barlow
|
||||||
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
|
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
@@ -1,64 +1,53 @@
|
|||||||
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
# SPDX-FileCopyrightText: 2023 James R. Barlow
|
||||||
# SPDX-License-Identifier: MPL-2.0
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
|
|
||||||
"""Implements the concurrent and page synchronous parts of the pipeline."""
|
|
||||||
|
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
|
import json
|
||||||
import logging
|
import logging
|
||||||
import logging.handlers
|
import logging.handlers
|
||||||
import os
|
import os
|
||||||
|
import shutil
|
||||||
import sys
|
import sys
|
||||||
import threading
|
import threading
|
||||||
|
from collections.abc import Sequence
|
||||||
from concurrent.futures.process import BrokenProcessPool
|
from concurrent.futures.process import BrokenProcessPool
|
||||||
from concurrent.futures.thread import BrokenThreadPool
|
from concurrent.futures.thread import BrokenThreadPool
|
||||||
from functools import partial
|
from contextlib import contextmanager
|
||||||
|
from dataclasses import dataclass
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from tempfile import mkdtemp
|
from typing import Callable, NamedTuple, cast
|
||||||
from typing import NamedTuple, Sequence, cast
|
|
||||||
|
|
||||||
import PIL
|
import PIL
|
||||||
|
|
||||||
from ocrmypdf._concurrent import Executor, setup_executor
|
from ocrmypdf._concurrent import Executor, setup_executor
|
||||||
from ocrmypdf._graft import OcrGrafter
|
from ocrmypdf._jobcontext import PageContext, PdfContext
|
||||||
from ocrmypdf._jobcontext import PageContext, PdfContext, cleanup_working_files
|
|
||||||
from ocrmypdf._logging import PageNumberFilter
|
from ocrmypdf._logging import PageNumberFilter
|
||||||
|
from ocrmypdf._metadata import metadata_fixup
|
||||||
from ocrmypdf._pipeline import (
|
from ocrmypdf._pipeline import (
|
||||||
convert_to_pdfa,
|
convert_to_pdfa,
|
||||||
copy_final,
|
|
||||||
create_ocr_image,
|
create_ocr_image,
|
||||||
create_pdf_page_from_image,
|
create_pdf_page_from_image,
|
||||||
create_visible_page_jpg,
|
create_visible_page_jpg,
|
||||||
generate_postscript_stub,
|
generate_postscript_stub,
|
||||||
get_orientation_correction,
|
get_orientation_correction,
|
||||||
get_pdfinfo,
|
get_pdf_save_settings,
|
||||||
is_ocr_required,
|
|
||||||
merge_sidecars,
|
|
||||||
metadata_fixup,
|
|
||||||
ocr_engine_hocr,
|
|
||||||
ocr_engine_textonly_pdf,
|
|
||||||
optimize_pdf,
|
optimize_pdf,
|
||||||
preprocess_clean,
|
preprocess_clean,
|
||||||
preprocess_deskew,
|
preprocess_deskew,
|
||||||
preprocess_remove_background,
|
preprocess_remove_background,
|
||||||
rasterize,
|
rasterize,
|
||||||
rasterize_preview,
|
rasterize_preview,
|
||||||
render_hocr_page,
|
should_linearize,
|
||||||
should_visible_page_image_use_jpg,
|
should_visible_page_image_use_jpg,
|
||||||
triage,
|
|
||||||
validate_pdfinfo_options,
|
|
||||||
)
|
)
|
||||||
from ocrmypdf._plugin_manager import OcrmypdfPluginManager, get_plugin_manager
|
from ocrmypdf._plugin_manager import OcrmypdfPluginManager
|
||||||
from ocrmypdf._validation import (
|
from ocrmypdf._validation import (
|
||||||
check_requested_output_file,
|
|
||||||
create_input_file,
|
|
||||||
report_output_file_size,
|
report_output_file_size,
|
||||||
)
|
)
|
||||||
from ocrmypdf.exceptions import ExitCode, ExitCodeException
|
from ocrmypdf.exceptions import ExitCode, ExitCodeException
|
||||||
from ocrmypdf.helpers import (
|
from ocrmypdf.helpers import (
|
||||||
NeverRaise,
|
|
||||||
available_cpu_count,
|
available_cpu_count,
|
||||||
check_pdf,
|
check_pdf,
|
||||||
pikepdf_enable_mmap,
|
pikepdf_enable_mmap,
|
||||||
@@ -67,33 +56,248 @@ from ocrmypdf.helpers import (
|
|||||||
from ocrmypdf.pdfa import file_claims_pdfa
|
from ocrmypdf.pdfa import file_claims_pdfa
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
|
tls = threading.local()
|
||||||
|
tls.pageno = None
|
||||||
|
|
||||||
|
|
||||||
|
def _set_logging_tls(tls):
|
||||||
|
"""Inject current page number (when available) into log records."""
|
||||||
|
old_factory = logging.getLogRecordFactory()
|
||||||
|
|
||||||
|
def wrapper(*args, **kwargs):
|
||||||
|
record = old_factory(*args, **kwargs)
|
||||||
|
if hasattr(tls, 'pageno'):
|
||||||
|
record.pageno = tls.pageno
|
||||||
|
return record
|
||||||
|
|
||||||
|
logging.setLogRecordFactory(wrapper)
|
||||||
|
|
||||||
|
|
||||||
|
_set_logging_tls(tls)
|
||||||
|
|
||||||
|
|
||||||
|
def set_thread_pageno(pageno: int | None):
|
||||||
|
"""Set page number (1-based) that the current thread is processing."""
|
||||||
|
tls.pageno = pageno
|
||||||
|
|
||||||
|
|
||||||
class PageResult(NamedTuple):
|
class PageResult(NamedTuple):
|
||||||
"""Result when a page is finished processing."""
|
"""Result when a page is finished processing."""
|
||||||
|
|
||||||
pageno: int
|
pageno: int
|
||||||
pdf_page_from_image: Path | None
|
"""Page number, 0-based."""
|
||||||
ocr: Path | None
|
|
||||||
text: Path | None
|
pdf_page_from_image: Path | None = None
|
||||||
orientation_correction: int
|
"""Single page PDF from image."""
|
||||||
|
|
||||||
|
ocr: Path | None = None
|
||||||
|
"""Single page OCR PDF."""
|
||||||
|
|
||||||
|
text: Path | None = None
|
||||||
|
"""Single page text file."""
|
||||||
|
|
||||||
|
orientation_correction: int = 0
|
||||||
|
"""Orientation correction in degrees."""
|
||||||
|
|
||||||
|
|
||||||
tls = threading.local()
|
@dataclass
|
||||||
tls.pageno = None
|
class HOCRResult:
|
||||||
|
"""Result when hOCR is finished processing."""
|
||||||
|
|
||||||
|
pageno: int
|
||||||
|
"""Page number, 0-based."""
|
||||||
|
|
||||||
|
pdf_page_from_image: Path | None = None
|
||||||
|
"""Single page PDF from image."""
|
||||||
|
|
||||||
|
hocr: Path | None = None
|
||||||
|
"""Single page hOCR file."""
|
||||||
|
|
||||||
|
textpdf: Path | None = None
|
||||||
|
"""hOCR file after conversion to PDF."""
|
||||||
|
|
||||||
|
orientation_correction: int = 0
|
||||||
|
"""Orientation correction in degrees."""
|
||||||
|
|
||||||
|
def __getstate__(self):
|
||||||
|
"""Return state values to be pickled."""
|
||||||
|
return {
|
||||||
|
k: (
|
||||||
|
('Path://' + str(v))
|
||||||
|
if k in ('pdf_page_from_image', 'hocr', 'textpdf') and v is not None
|
||||||
|
else v
|
||||||
|
)
|
||||||
|
for k, v in self.__dict__.items()
|
||||||
|
}
|
||||||
|
|
||||||
|
def __setstate__(self, state):
|
||||||
|
"""Restore state from the unpickled state values."""
|
||||||
|
self.__dict__.update(
|
||||||
|
{
|
||||||
|
k: (
|
||||||
|
Path(v.removeprefix('Path://'))
|
||||||
|
if k in ('pdf_page_from_image', 'hocr', 'textpdf') and v is not None
|
||||||
|
else v
|
||||||
|
)
|
||||||
|
for k, v in state.items()
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_json(cls, json_str: str) -> HOCRResult:
|
||||||
|
"""Create an instance from a dict."""
|
||||||
|
return cls(**json.loads(json_str))
|
||||||
|
|
||||||
|
def to_json(self) -> str:
|
||||||
|
"""Serialize to a JSON string."""
|
||||||
|
return json.dumps(self.__getstate__())
|
||||||
|
|
||||||
|
|
||||||
old_factory = logging.getLogRecordFactory()
|
def configure_debug_logging(
|
||||||
|
log_filename: Path, prefix: str = ''
|
||||||
|
) -> tuple[logging.FileHandler, Callable[[], None]]:
|
||||||
|
"""Create a debug log file at a specified location.
|
||||||
|
|
||||||
|
Returns the log handler, and a function to remove the handler.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
log_filename: Where to the put the log file.
|
||||||
|
prefix: The logging domain prefix that should be sent to the log.
|
||||||
|
"""
|
||||||
|
log_file_handler = logging.FileHandler(log_filename, delay=True)
|
||||||
|
log_file_handler.setLevel(logging.DEBUG)
|
||||||
|
formatter = logging.Formatter(
|
||||||
|
'[%(asctime)s] - %(name)s - %(levelname)7s -%(pageno)s %(message)s'
|
||||||
|
)
|
||||||
|
log_file_handler.setFormatter(formatter)
|
||||||
|
log_file_handler.addFilter(PageNumberFilter())
|
||||||
|
logging.getLogger(prefix).addHandler(log_file_handler)
|
||||||
|
|
||||||
|
def remover():
|
||||||
|
try:
|
||||||
|
logging.getLogger(prefix).removeHandler(log_file_handler)
|
||||||
|
log_file_handler.close()
|
||||||
|
except OSError as e:
|
||||||
|
print(e, file=sys.stderr)
|
||||||
|
|
||||||
|
return log_file_handler, remover
|
||||||
|
|
||||||
|
|
||||||
def record_factory(*args, **kwargs):
|
def worker_init(max_pixels: int) -> None:
|
||||||
record = old_factory(*args, **kwargs)
|
"""Initialize a worker thread or process."""
|
||||||
if hasattr(tls, 'pageno'):
|
# In Windows, child process will not inherit our change to this value in
|
||||||
record.pageno = tls.pageno
|
# the parent process, so ensure workers get it set. Not needed when running
|
||||||
return record
|
# threaded, but harmless to set again.
|
||||||
|
PIL.Image.MAX_IMAGE_PIXELS = max_pixels
|
||||||
|
pikepdf_enable_mmap()
|
||||||
|
|
||||||
|
|
||||||
logging.setLogRecordFactory(record_factory)
|
@contextmanager
|
||||||
|
def manage_debug_log_handler(
|
||||||
|
*,
|
||||||
|
options: argparse.Namespace,
|
||||||
|
work_folder: Path,
|
||||||
|
):
|
||||||
|
remover = None
|
||||||
|
if (options.keep_temporary_files or options.verbose >= 1) and not os.environ.get(
|
||||||
|
'PYTEST_CURRENT_TEST', ''
|
||||||
|
):
|
||||||
|
# Debug log for command line interface only with verbose output
|
||||||
|
# See https://github.com/pytest-dev/pytest/issues/5502 for why we skip this
|
||||||
|
# when pytest is running
|
||||||
|
_debug_log_handler, remover = configure_debug_logging(
|
||||||
|
work_folder / "debug.log", prefix=""
|
||||||
|
) # pragma: no cover
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
if remover:
|
||||||
|
remover()
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def manage_work_folder(*, work_folder: Path, retain: bool, print_location: bool):
|
||||||
|
try:
|
||||||
|
yield work_folder
|
||||||
|
finally:
|
||||||
|
if retain:
|
||||||
|
if print_location:
|
||||||
|
print(
|
||||||
|
f"Temporary working files retained at:\n{work_folder}",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
shutil.rmtree(work_folder, ignore_errors=True)
|
||||||
|
|
||||||
|
|
||||||
|
def cli_exception_handler(
|
||||||
|
fn: Callable[[argparse.Namespace, OcrmypdfPluginManager], ExitCode],
|
||||||
|
options: argparse.Namespace,
|
||||||
|
plugin_manager: OcrmypdfPluginManager,
|
||||||
|
) -> ExitCode:
|
||||||
|
"""Convert exceptions into command line error messages and exit codes.
|
||||||
|
|
||||||
|
When known exceptions are raised, the exception message is printed to stderr
|
||||||
|
and the program exits with a non-zero exit code. When unknown exceptions are
|
||||||
|
raised, the exception traceback is printed to stderr and the program exits
|
||||||
|
with a non-zero exit code.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
# We cannot use a generator and yield here, as would be the usual pattern
|
||||||
|
# for exception handling context managers, because we need to return an exit
|
||||||
|
# code.
|
||||||
|
return fn(options, plugin_manager)
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
if options.verbose >= 1:
|
||||||
|
log.exception("KeyboardInterrupt")
|
||||||
|
else:
|
||||||
|
log.error("KeyboardInterrupt")
|
||||||
|
return ExitCode.ctrl_c
|
||||||
|
except ExitCodeException as e:
|
||||||
|
e = cast(ExitCodeException, e)
|
||||||
|
if options.verbose >= 1:
|
||||||
|
log.exception("ExitCodeException")
|
||||||
|
elif str(e):
|
||||||
|
log.error("%s: %s", type(e).__name__, str(e))
|
||||||
|
else:
|
||||||
|
log.error(type(e).__name__)
|
||||||
|
return e.exit_code
|
||||||
|
except PIL.Image.DecompressionBombError:
|
||||||
|
log.exception(
|
||||||
|
"A decompression bomb error was encountered while executing the "
|
||||||
|
"pipeline. Use the argument --max-image-mpixels to raise the maximum "
|
||||||
|
"image pixel limit."
|
||||||
|
)
|
||||||
|
return ExitCode.other_error
|
||||||
|
except (
|
||||||
|
BrokenProcessPool,
|
||||||
|
BrokenThreadPool,
|
||||||
|
):
|
||||||
|
log.exception(
|
||||||
|
"A worker process was terminated unexpectedly. This is known to occur if "
|
||||||
|
"processing your file takes all available swap space and RAM. It may "
|
||||||
|
"help to try again with a smaller number of jobs, using the --jobs "
|
||||||
|
"argument."
|
||||||
|
)
|
||||||
|
return ExitCode.child_process_error
|
||||||
|
except Exception: # pylint: disable=broad-except
|
||||||
|
log.exception("An exception occurred while executing the pipeline")
|
||||||
|
return ExitCode.other_error
|
||||||
|
|
||||||
|
|
||||||
|
def setup_pipeline(
|
||||||
|
options: argparse.Namespace,
|
||||||
|
plugin_manager: OcrmypdfPluginManager,
|
||||||
|
) -> Executor:
|
||||||
|
# Any changes to options will not take effect for options that are already
|
||||||
|
# bound to function parameters in the pipeline. (For example
|
||||||
|
# options.input_file, options.pdf_renderer are already bound.)
|
||||||
|
if not options.jobs:
|
||||||
|
options.jobs = available_cpu_count()
|
||||||
|
|
||||||
|
pikepdf_enable_mmap()
|
||||||
|
executor = setup_executor(plugin_manager)
|
||||||
|
return executor
|
||||||
|
|
||||||
|
|
||||||
def preprocess(
|
def preprocess(
|
||||||
@@ -103,6 +307,7 @@ def preprocess(
|
|||||||
deskew: bool,
|
deskew: bool,
|
||||||
clean: bool,
|
clean: bool,
|
||||||
) -> Path:
|
) -> Path:
|
||||||
|
"""Preprocess an image."""
|
||||||
if remove_background:
|
if remove_background:
|
||||||
image = preprocess_remove_background(image, page_context)
|
image = preprocess_remove_background(image, page_context)
|
||||||
if deskew:
|
if deskew:
|
||||||
@@ -115,6 +320,7 @@ def preprocess(
|
|||||||
def make_intermediate_images(
|
def make_intermediate_images(
|
||||||
page_context: PageContext, orientation_correction: int
|
page_context: PageContext, orientation_correction: int
|
||||||
) -> tuple[Path, Path | None]:
|
) -> tuple[Path, Path | None]:
|
||||||
|
"""Create intermediate and preprocessed images for OCR."""
|
||||||
options = page_context.options
|
options = page_context.options
|
||||||
|
|
||||||
ocr_image = preprocess_out = None
|
ocr_image = preprocess_out = None
|
||||||
@@ -171,19 +377,9 @@ def make_intermediate_images(
|
|||||||
return ocr_image, preprocess_out
|
return ocr_image, preprocess_out
|
||||||
|
|
||||||
|
|
||||||
def exec_page_sync(page_context: PageContext) -> PageResult:
|
def process_page(page_context: PageContext) -> tuple[Path, Path | None, int]:
|
||||||
|
"""Process page to create OCR image, visible page image and orientation."""
|
||||||
options = page_context.options
|
options = page_context.options
|
||||||
tls.pageno = page_context.pageno + 1
|
|
||||||
|
|
||||||
if not is_ocr_required(page_context):
|
|
||||||
return PageResult(
|
|
||||||
pageno=page_context.pageno,
|
|
||||||
pdf_page_from_image=None,
|
|
||||||
ocr=None,
|
|
||||||
text=None,
|
|
||||||
orientation_correction=0,
|
|
||||||
)
|
|
||||||
|
|
||||||
orientation_correction = 0
|
orientation_correction = 0
|
||||||
if options.rotate_pages:
|
if options.rotate_pages:
|
||||||
# Rasterize
|
# Rasterize
|
||||||
@@ -206,262 +402,53 @@ def exec_page_sync(page_context: PageContext) -> PageResult:
|
|||||||
filtered_image = page_context.plugin_manager.hook.filter_page_image(
|
filtered_image = page_context.plugin_manager.hook.filter_page_image(
|
||||||
page=page_context, image_filename=visible_image_out
|
page=page_context, image_filename=visible_image_out
|
||||||
)
|
)
|
||||||
if filtered_image:
|
if filtered_image is not None: # None if no hook is present
|
||||||
visible_image_out = filtered_image
|
visible_image_out = filtered_image
|
||||||
pdf_page_from_image_out = create_pdf_page_from_image(
|
pdf_page_from_image_out = create_pdf_page_from_image(
|
||||||
visible_image_out, page_context, orientation_correction
|
visible_image_out, page_context, orientation_correction
|
||||||
)
|
)
|
||||||
|
return ocr_image_out, pdf_page_from_image_out, orientation_correction
|
||||||
if options.pdf_renderer.startswith('hocr'):
|
|
||||||
(hocr_out, text_out) = ocr_engine_hocr(ocr_image_out, page_context)
|
|
||||||
ocr_out = render_hocr_page(hocr_out, page_context)
|
|
||||||
elif options.pdf_renderer == 'sandwich':
|
|
||||||
(ocr_out, text_out) = ocr_engine_textonly_pdf(ocr_image_out, page_context)
|
|
||||||
else:
|
|
||||||
raise NotImplementedError(f"pdf_renderer {options.pdf_renderer}")
|
|
||||||
|
|
||||||
return PageResult(
|
|
||||||
pageno=page_context.pageno,
|
|
||||||
pdf_page_from_image=pdf_page_from_image_out,
|
|
||||||
ocr=ocr_out,
|
|
||||||
text=text_out,
|
|
||||||
orientation_correction=orientation_correction,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def post_process(
|
def postprocess(
|
||||||
pdf_file: Path, context: PdfContext, executor: Executor
|
pdf_file: Path, context: PdfContext, executor: Executor
|
||||||
) -> tuple[Path, Sequence[str]]:
|
) -> tuple[Path, Sequence[str]]:
|
||||||
|
"""Postprocess the PDF file."""
|
||||||
pdf_out = pdf_file
|
pdf_out = pdf_file
|
||||||
if context.options.output_type.startswith('pdfa'):
|
if context.options.output_type.startswith('pdfa'):
|
||||||
ps_stub_out = generate_postscript_stub(context)
|
ps_stub_out = generate_postscript_stub(context)
|
||||||
pdf_out = convert_to_pdfa(pdf_out, ps_stub_out, context)
|
pdf_out = convert_to_pdfa(pdf_out, ps_stub_out, context)
|
||||||
|
|
||||||
pdf_out = metadata_fixup(pdf_out, context)
|
optimizing = context.plugin_manager.hook.is_optimization_enabled(context=context)
|
||||||
|
save_settings = get_pdf_save_settings(context.options.output_type)
|
||||||
|
save_settings['linearize'] = not optimizing and should_linearize(pdf_out, context)
|
||||||
|
|
||||||
|
pdf_out = metadata_fixup(pdf_out, context, pdf_save_settings=save_settings)
|
||||||
return optimize_pdf(pdf_out, context, executor)
|
return optimize_pdf(pdf_out, context, executor)
|
||||||
|
|
||||||
|
|
||||||
def worker_init(max_pixels: int) -> None:
|
def report_output_pdf(options, start_input_file, optimize_messages) -> ExitCode:
|
||||||
# In Windows, child process will not inherit our change to this value in
|
if options.output_file == '-':
|
||||||
# the parent process, so ensure workers get it set. Not needed when running
|
log.info("Output sent to stdout")
|
||||||
# threaded, but harmless to set again.
|
elif hasattr(options.output_file, 'writable') and options.output_file.writable():
|
||||||
PIL.Image.MAX_IMAGE_PIXELS = max_pixels
|
log.info("Output written to stream")
|
||||||
pikepdf_enable_mmap()
|
elif samefile(options.output_file, Path(os.devnull)):
|
||||||
|
pass # Say nothing when sending to dev null
|
||||||
|
else:
|
||||||
def exec_concurrent(context: PdfContext, executor: Executor) -> Sequence[str]:
|
if options.output_type.startswith('pdfa'):
|
||||||
"""Execute the pipeline concurrently"""
|
pdfa_info = file_claims_pdfa(options.output_file)
|
||||||
|
if pdfa_info['pass']:
|
||||||
# Run exec_page_sync on every page context
|
log.info("Output file is a %s (as expected)", pdfa_info['conformance'])
|
||||||
options = context.options
|
else:
|
||||||
max_workers = min(len(context.pdfinfo), options.jobs)
|
log.warning(
|
||||||
if max_workers > 1:
|
"Output file is okay but is not PDF/A (seems to be %s)",
|
||||||
log.info("Start processing %d pages concurrently", max_workers)
|
pdfa_info['conformance'],
|
||||||
|
)
|
||||||
sidecars: list[Path | None] = [None] * len(context.pdfinfo)
|
return ExitCode.pdfa_conversion_failed
|
||||||
ocrgraft = OcrGrafter(context)
|
if not check_pdf(options.output_file):
|
||||||
|
log.warning('Output file: The generated PDF is INVALID')
|
||||||
def update_page(result: PageResult, pbar):
|
return ExitCode.invalid_output_pdf
|
||||||
try:
|
report_output_file_size(
|
||||||
tls.pageno = result.pageno + 1
|
options, start_input_file, options.output_file, optimize_messages
|
||||||
sidecars[result.pageno] = result.text
|
|
||||||
pbar.update()
|
|
||||||
ocrgraft.graft_page(
|
|
||||||
pageno=result.pageno,
|
|
||||||
image=result.pdf_page_from_image,
|
|
||||||
textpdf=result.ocr,
|
|
||||||
autorotate_correction=result.orientation_correction,
|
|
||||||
)
|
|
||||||
pbar.update()
|
|
||||||
finally:
|
|
||||||
tls.pageno = None
|
|
||||||
|
|
||||||
executor(
|
|
||||||
use_threads=options.use_threads,
|
|
||||||
max_workers=max_workers,
|
|
||||||
tqdm_kwargs=dict(
|
|
||||||
total=(2 * len(context.pdfinfo)),
|
|
||||||
desc='OCR' if options.tesseract_timeout > 0 else 'Image processing',
|
|
||||||
unit='page',
|
|
||||||
unit_scale=0.5,
|
|
||||||
disable=not options.progress_bar,
|
|
||||||
),
|
|
||||||
worker_initializer=partial(worker_init, PIL.Image.MAX_IMAGE_PIXELS),
|
|
||||||
task=exec_page_sync,
|
|
||||||
task_arguments=context.get_page_contexts(),
|
|
||||||
task_finished=update_page,
|
|
||||||
)
|
|
||||||
|
|
||||||
# Output sidecar text
|
|
||||||
if options.sidecar:
|
|
||||||
text = merge_sidecars(sidecars, context)
|
|
||||||
# Copy text file to destination
|
|
||||||
copy_final(text, options.sidecar, context)
|
|
||||||
|
|
||||||
# Merge layers to one single pdf
|
|
||||||
pdf = ocrgraft.finalize()
|
|
||||||
|
|
||||||
messages: Sequence[str] = []
|
|
||||||
if options.output_type != 'none':
|
|
||||||
# PDF/A and metadata
|
|
||||||
log.info("Postprocessing...")
|
|
||||||
pdf, messages = post_process(pdf, context, executor)
|
|
||||||
|
|
||||||
# Copy PDF file to destination
|
|
||||||
copy_final(pdf, options.output_file, context)
|
|
||||||
return messages
|
|
||||||
|
|
||||||
|
|
||||||
def configure_debug_logging(
|
|
||||||
log_filename: Path, prefix: str = ''
|
|
||||||
) -> logging.FileHandler:
|
|
||||||
"""
|
|
||||||
Create a debug log file at a specified location.
|
|
||||||
|
|
||||||
Arguments:
|
|
||||||
log_filename: Where to the put the log file.
|
|
||||||
prefix: The logging domain prefix that should be sent to the log.
|
|
||||||
"""
|
|
||||||
log_file_handler = logging.FileHandler(log_filename, delay=True)
|
|
||||||
log_file_handler.setLevel(logging.DEBUG)
|
|
||||||
formatter = logging.Formatter(
|
|
||||||
'[%(asctime)s] - %(name)s - %(levelname)7s -%(pageno)s %(message)s'
|
|
||||||
)
|
|
||||||
log_file_handler.setFormatter(formatter)
|
|
||||||
log_file_handler.addFilter(PageNumberFilter())
|
|
||||||
logging.getLogger(prefix).addHandler(log_file_handler)
|
|
||||||
return log_file_handler
|
|
||||||
|
|
||||||
|
|
||||||
def run_pipeline(
|
|
||||||
options: argparse.Namespace,
|
|
||||||
*,
|
|
||||||
plugin_manager: OcrmypdfPluginManager | None,
|
|
||||||
api: bool = False,
|
|
||||||
) -> ExitCode:
|
|
||||||
# Any changes to options will not take effect for options that are already
|
|
||||||
# bound to function parameters in the pipeline. (For example
|
|
||||||
# options.input_file, options.pdf_renderer are already bound.)
|
|
||||||
if not options.jobs:
|
|
||||||
options.jobs = available_cpu_count()
|
|
||||||
if not plugin_manager:
|
|
||||||
plugin_manager = get_plugin_manager(options.plugins)
|
|
||||||
|
|
||||||
work_folder = Path(mkdtemp(prefix="ocrmypdf.io."))
|
|
||||||
debug_log_handler = None
|
|
||||||
if (
|
|
||||||
(options.keep_temporary_files or options.verbose >= 1)
|
|
||||||
and not os.environ.get('PYTEST_CURRENT_TEST', '')
|
|
||||||
and not api
|
|
||||||
):
|
|
||||||
# Debug log for command line interface only with verbose output
|
|
||||||
# See https://github.com/pytest-dev/pytest/issues/5502 for why we skip this
|
|
||||||
# when pytest is running
|
|
||||||
debug_log_handler = configure_debug_logging(
|
|
||||||
Path(work_folder) / "debug.log"
|
|
||||||
) # pragma: no cover
|
|
||||||
|
|
||||||
pikepdf_enable_mmap()
|
|
||||||
|
|
||||||
executor = setup_executor(plugin_manager)
|
|
||||||
try:
|
|
||||||
check_requested_output_file(options)
|
|
||||||
start_input_file, original_filename = create_input_file(options, work_folder)
|
|
||||||
|
|
||||||
# Triage image or pdf
|
|
||||||
origin_pdf = triage(
|
|
||||||
original_filename, start_input_file, work_folder / 'origin.pdf', options
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# Gather pdfinfo and create context
|
|
||||||
pdfinfo = get_pdfinfo(
|
|
||||||
origin_pdf,
|
|
||||||
executor=executor,
|
|
||||||
detailed_analysis=options.redo_ocr,
|
|
||||||
progbar=options.progress_bar,
|
|
||||||
max_workers=options.jobs if not options.use_threads else 1, # To help debug
|
|
||||||
check_pages=options.pages,
|
|
||||||
)
|
|
||||||
|
|
||||||
context = PdfContext(options, work_folder, origin_pdf, pdfinfo, plugin_manager)
|
|
||||||
|
|
||||||
# Validate options are okay for this pdf
|
|
||||||
validate_pdfinfo_options(context)
|
|
||||||
|
|
||||||
# Execute the pipeline
|
|
||||||
optimize_messages = exec_concurrent(context, executor)
|
|
||||||
|
|
||||||
if options.output_file == '-':
|
|
||||||
log.info("Output sent to stdout")
|
|
||||||
elif (
|
|
||||||
hasattr(options.output_file, 'writable') and options.output_file.writable()
|
|
||||||
):
|
|
||||||
log.info("Output written to stream")
|
|
||||||
elif samefile(options.output_file, Path(os.devnull)):
|
|
||||||
pass # Say nothing when sending to dev null
|
|
||||||
else:
|
|
||||||
if options.output_type.startswith('pdfa'):
|
|
||||||
pdfa_info = file_claims_pdfa(options.output_file)
|
|
||||||
if pdfa_info['pass']:
|
|
||||||
log.info(
|
|
||||||
"Output file is a %s (as expected)", pdfa_info['conformance']
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
log.warning(
|
|
||||||
"Output file is okay but is not PDF/A (seems to be %s)",
|
|
||||||
pdfa_info['conformance'],
|
|
||||||
)
|
|
||||||
return ExitCode.pdfa_conversion_failed
|
|
||||||
if not check_pdf(options.output_file):
|
|
||||||
log.warning('Output file: The generated PDF is INVALID')
|
|
||||||
return ExitCode.invalid_output_pdf
|
|
||||||
report_output_file_size(
|
|
||||||
options, start_input_file, options.output_file, optimize_messages
|
|
||||||
)
|
|
||||||
|
|
||||||
except (KeyboardInterrupt if not api else NeverRaise):
|
|
||||||
if options.verbose >= 1:
|
|
||||||
log.exception("KeyboardInterrupt")
|
|
||||||
else:
|
|
||||||
log.error("KeyboardInterrupt")
|
|
||||||
return ExitCode.ctrl_c
|
|
||||||
except (ExitCodeException if not api else NeverRaise) as e:
|
|
||||||
e = cast(ExitCodeException, e)
|
|
||||||
if options.verbose >= 1:
|
|
||||||
log.exception("ExitCodeException")
|
|
||||||
elif str(e):
|
|
||||||
log.error("%s: %s", type(e).__name__, str(e))
|
|
||||||
else:
|
|
||||||
log.error(type(e).__name__)
|
|
||||||
return e.exit_code
|
|
||||||
except (PIL.Image.DecompressionBombError if not api else NeverRaise):
|
|
||||||
log.exception(
|
|
||||||
"A decompression bomb error was encountered while executing the "
|
|
||||||
"pipeline. Use the argument --max-image-mpixels to raise the maximum "
|
|
||||||
"image pixel limit."
|
|
||||||
)
|
|
||||||
return ExitCode.other_error
|
|
||||||
except (
|
|
||||||
BrokenProcessPool if not api else NeverRaise,
|
|
||||||
BrokenThreadPool if not api else NeverRaise,
|
|
||||||
):
|
|
||||||
log.exception(
|
|
||||||
"A worker process was terminated unexpectedly. This is known to occur if "
|
|
||||||
"processing your file takes all available swap space and RAM. It may "
|
|
||||||
"help to try again with a smaller number of jobs, using the --jobs "
|
|
||||||
"argument."
|
|
||||||
)
|
|
||||||
return ExitCode.child_process_error
|
|
||||||
except (Exception if not api else NeverRaise): # pylint: disable=broad-except
|
|
||||||
log.exception("An exception occurred while executing the pipeline")
|
|
||||||
return ExitCode.other_error
|
|
||||||
finally:
|
|
||||||
if debug_log_handler:
|
|
||||||
try:
|
|
||||||
debug_log_handler.close()
|
|
||||||
log.removeHandler(debug_log_handler)
|
|
||||||
except OSError as e:
|
|
||||||
print(e, file=sys.stderr)
|
|
||||||
cleanup_working_files(work_folder, options)
|
|
||||||
|
|
||||||
return ExitCode.ok
|
return ExitCode.ok
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
# SPDX-FileCopyrightText: 2019-2023 James R. Barlow
|
||||||
|
# SPDX-FileCopyrightText: 2019 Martin Wind
|
||||||
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
|
|
||||||
|
"""Implements the concurrent and page synchronous parts of the pipeline."""
|
||||||
|
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import logging
|
||||||
|
import logging.handlers
|
||||||
|
from collections.abc import Sequence
|
||||||
|
from functools import partial
|
||||||
|
|
||||||
|
import PIL
|
||||||
|
|
||||||
|
from ocrmypdf._concurrent import Executor
|
||||||
|
from ocrmypdf._graft import OcrGrafter
|
||||||
|
from ocrmypdf._jobcontext import PageContext, PdfContext
|
||||||
|
from ocrmypdf._pipeline import (
|
||||||
|
copy_final,
|
||||||
|
get_pdfinfo,
|
||||||
|
render_hocr_page,
|
||||||
|
)
|
||||||
|
from ocrmypdf._pipelines._common import (
|
||||||
|
HOCRResult,
|
||||||
|
manage_work_folder,
|
||||||
|
postprocess,
|
||||||
|
report_output_pdf,
|
||||||
|
set_thread_pageno,
|
||||||
|
setup_pipeline,
|
||||||
|
worker_init,
|
||||||
|
)
|
||||||
|
from ocrmypdf._plugin_manager import OcrmypdfPluginManager
|
||||||
|
from ocrmypdf._progressbar import ProgressBar
|
||||||
|
from ocrmypdf.exceptions import ExitCode
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _exec_hocrtransform_sync(page_context: PageContext) -> HOCRResult:
|
||||||
|
"""Process each page."""
|
||||||
|
hocr_json = page_context.get_path('hocr.json')
|
||||||
|
if not hocr_json.exists():
|
||||||
|
# No hOCR file, so no OCR was performed on this page.
|
||||||
|
return HOCRResult(pageno=page_context.pageno)
|
||||||
|
hocr_result = HOCRResult.from_json(hocr_json.read_text())
|
||||||
|
hocr_result.textpdf = render_hocr_page(
|
||||||
|
page_context.get_path('ocr_hocr.hocr'), page_context
|
||||||
|
)
|
||||||
|
return hocr_result
|
||||||
|
|
||||||
|
|
||||||
|
def exec_hocr_to_ocr_pdf(context: PdfContext, executor: Executor) -> Sequence[str]:
|
||||||
|
"""Convert hOCR files to OCR PDF."""
|
||||||
|
# Run exec_page_sync on every page
|
||||||
|
options = context.options
|
||||||
|
max_workers = min(len(context.pdfinfo), options.jobs)
|
||||||
|
if max_workers > 1:
|
||||||
|
log.info("Continue processing %d pages concurrently", max_workers)
|
||||||
|
|
||||||
|
ocrgraft = OcrGrafter(context)
|
||||||
|
|
||||||
|
def graft_page(result: HOCRResult, pbar: ProgressBar):
|
||||||
|
"""Graft text only PDF on to main PDF's page."""
|
||||||
|
try:
|
||||||
|
set_thread_pageno(result.pageno + 1)
|
||||||
|
pbar.update()
|
||||||
|
ocrgraft.graft_page(
|
||||||
|
pageno=result.pageno,
|
||||||
|
image=result.pdf_page_from_image,
|
||||||
|
textpdf=result.textpdf,
|
||||||
|
autorotate_correction=result.orientation_correction,
|
||||||
|
)
|
||||||
|
pbar.update()
|
||||||
|
finally:
|
||||||
|
set_thread_pageno(None)
|
||||||
|
|
||||||
|
executor(
|
||||||
|
use_threads=options.use_threads,
|
||||||
|
max_workers=max_workers,
|
||||||
|
progress_kwargs=dict(
|
||||||
|
total=(2 * len(context.pdfinfo)),
|
||||||
|
desc='Grafting hOCR to PDF',
|
||||||
|
unit='page',
|
||||||
|
unit_scale=0.5,
|
||||||
|
disable=not options.progress_bar,
|
||||||
|
),
|
||||||
|
worker_initializer=partial(worker_init, PIL.Image.MAX_IMAGE_PIXELS),
|
||||||
|
task=_exec_hocrtransform_sync,
|
||||||
|
task_arguments=context.get_page_context_args(),
|
||||||
|
task_finished=graft_page,
|
||||||
|
)
|
||||||
|
|
||||||
|
pdf = ocrgraft.finalize()
|
||||||
|
messages: Sequence[str] = []
|
||||||
|
if options.output_type != 'none':
|
||||||
|
# PDF/A and metadata
|
||||||
|
log.info("Postprocessing...")
|
||||||
|
pdf, messages = postprocess(pdf, context, executor)
|
||||||
|
|
||||||
|
# Copy PDF file to destination (we don't know the input PDF file name)
|
||||||
|
copy_final(pdf, options.output_file, None)
|
||||||
|
return messages
|
||||||
|
|
||||||
|
|
||||||
|
def run_hocr_to_ocr_pdf_pipeline(
|
||||||
|
options: argparse.Namespace,
|
||||||
|
*,
|
||||||
|
plugin_manager: OcrmypdfPluginManager,
|
||||||
|
) -> ExitCode:
|
||||||
|
"""Run pipeline to convert hOCR to final output PDF."""
|
||||||
|
with manage_work_folder(
|
||||||
|
work_folder=options.work_folder, retain=True, print_location=False
|
||||||
|
) as work_folder:
|
||||||
|
executor = setup_pipeline(options, plugin_manager)
|
||||||
|
origin_pdf = work_folder / 'origin.pdf'
|
||||||
|
|
||||||
|
# Gather pdfinfo and create context
|
||||||
|
pdfinfo = get_pdfinfo(
|
||||||
|
origin_pdf,
|
||||||
|
executor=executor,
|
||||||
|
detailed_analysis=options.redo_ocr,
|
||||||
|
progbar=options.progress_bar,
|
||||||
|
max_workers=options.jobs,
|
||||||
|
use_threads=options.use_threads,
|
||||||
|
check_pages=options.pages,
|
||||||
|
)
|
||||||
|
context = PdfContext(options, work_folder, origin_pdf, pdfinfo, plugin_manager)
|
||||||
|
plugin_manager.hook.check_options(options=options)
|
||||||
|
optimize_messages = exec_hocr_to_ocr_pdf(context, executor)
|
||||||
|
|
||||||
|
return report_output_pdf(options, origin_pdf, optimize_messages)
|
||||||
@@ -0,0 +1,225 @@
|
|||||||
|
# SPDX-FileCopyrightText: 2019-2023 James R. Barlow
|
||||||
|
# SPDX-FileCopyrightText: 2019 Martin Wind
|
||||||
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
|
|
||||||
|
"""Implements the concurrent and page synchronous parts of the pipeline."""
|
||||||
|
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import logging
|
||||||
|
import logging.handlers
|
||||||
|
from collections.abc import Sequence
|
||||||
|
from functools import partial
|
||||||
|
from pathlib import Path
|
||||||
|
from tempfile import mkdtemp
|
||||||
|
|
||||||
|
import PIL
|
||||||
|
|
||||||
|
from ocrmypdf._concurrent import Executor
|
||||||
|
from ocrmypdf._graft import OcrGrafter
|
||||||
|
from ocrmypdf._jobcontext import PageContext, PdfContext
|
||||||
|
from ocrmypdf._pipeline import (
|
||||||
|
copy_final,
|
||||||
|
get_pdfinfo,
|
||||||
|
is_ocr_required,
|
||||||
|
merge_sidecars,
|
||||||
|
ocr_engine_hocr,
|
||||||
|
ocr_engine_textonly_pdf,
|
||||||
|
render_hocr_page,
|
||||||
|
triage,
|
||||||
|
validate_pdfinfo_options,
|
||||||
|
)
|
||||||
|
from ocrmypdf._pipelines._common import (
|
||||||
|
PageResult,
|
||||||
|
cli_exception_handler,
|
||||||
|
manage_debug_log_handler,
|
||||||
|
manage_work_folder,
|
||||||
|
postprocess,
|
||||||
|
process_page,
|
||||||
|
report_output_pdf,
|
||||||
|
set_thread_pageno,
|
||||||
|
setup_pipeline,
|
||||||
|
worker_init,
|
||||||
|
)
|
||||||
|
from ocrmypdf._plugin_manager import OcrmypdfPluginManager
|
||||||
|
from ocrmypdf._progressbar import ProgressBar
|
||||||
|
from ocrmypdf._validation import (
|
||||||
|
check_requested_output_file,
|
||||||
|
create_input_file,
|
||||||
|
)
|
||||||
|
from ocrmypdf.exceptions import ExitCode
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _image_to_ocr_text(
|
||||||
|
page_context: PageContext, ocr_image_out: Path
|
||||||
|
) -> tuple[Path, Path]:
|
||||||
|
"""Run OCR engine on image to create OCR PDF and text file."""
|
||||||
|
options = page_context.options
|
||||||
|
if options.pdf_renderer.startswith('hocr'):
|
||||||
|
hocr_out, text_out = ocr_engine_hocr(ocr_image_out, page_context)
|
||||||
|
ocr_out = render_hocr_page(hocr_out, page_context)
|
||||||
|
elif options.pdf_renderer == 'sandwich':
|
||||||
|
ocr_out, text_out = ocr_engine_textonly_pdf(ocr_image_out, page_context)
|
||||||
|
else:
|
||||||
|
raise NotImplementedError(f"pdf_renderer {options.pdf_renderer}")
|
||||||
|
return ocr_out, text_out
|
||||||
|
|
||||||
|
|
||||||
|
def _exec_page_sync(page_context: PageContext) -> PageResult:
|
||||||
|
"""Execute a pipeline for a single page synchronously."""
|
||||||
|
set_thread_pageno(page_context.pageno + 1)
|
||||||
|
|
||||||
|
if not is_ocr_required(page_context):
|
||||||
|
return PageResult(pageno=page_context.pageno)
|
||||||
|
|
||||||
|
ocr_image_out, pdf_page_from_image_out, orientation_correction = process_page(
|
||||||
|
page_context
|
||||||
|
)
|
||||||
|
ocr_out, text_out = _image_to_ocr_text(page_context, ocr_image_out)
|
||||||
|
|
||||||
|
return PageResult(
|
||||||
|
pageno=page_context.pageno,
|
||||||
|
pdf_page_from_image=pdf_page_from_image_out,
|
||||||
|
ocr=ocr_out,
|
||||||
|
text=text_out,
|
||||||
|
orientation_correction=orientation_correction,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def exec_concurrent(context: PdfContext, executor: Executor) -> Sequence[str]:
|
||||||
|
"""Execute the OCR pipeline concurrently."""
|
||||||
|
options = context.options
|
||||||
|
max_workers = min(len(context.pdfinfo), options.jobs)
|
||||||
|
if max_workers > 1:
|
||||||
|
log.info("Start processing %d pages concurrently", max_workers)
|
||||||
|
|
||||||
|
sidecars: list[Path | None] = [None] * len(context.pdfinfo)
|
||||||
|
ocrgraft = OcrGrafter(context)
|
||||||
|
|
||||||
|
def update_page(result: PageResult, pbar: ProgressBar):
|
||||||
|
"""After OCR is complete for a page, update the PDF."""
|
||||||
|
try:
|
||||||
|
set_thread_pageno(result.pageno + 1)
|
||||||
|
sidecars[result.pageno] = result.text
|
||||||
|
pbar.update()
|
||||||
|
ocrgraft.graft_page(
|
||||||
|
pageno=result.pageno,
|
||||||
|
image=result.pdf_page_from_image,
|
||||||
|
textpdf=result.ocr,
|
||||||
|
autorotate_correction=result.orientation_correction,
|
||||||
|
)
|
||||||
|
pbar.update()
|
||||||
|
finally:
|
||||||
|
set_thread_pageno(None)
|
||||||
|
|
||||||
|
executor(
|
||||||
|
use_threads=options.use_threads,
|
||||||
|
max_workers=max_workers,
|
||||||
|
progress_kwargs=dict(
|
||||||
|
total=(2 * len(context.pdfinfo)),
|
||||||
|
desc='OCR' if options.tesseract_timeout > 0 else 'Image processing',
|
||||||
|
unit='page',
|
||||||
|
unit_scale=0.5,
|
||||||
|
disable=not options.progress_bar,
|
||||||
|
),
|
||||||
|
worker_initializer=partial(worker_init, PIL.Image.MAX_IMAGE_PIXELS),
|
||||||
|
task=_exec_page_sync,
|
||||||
|
task_arguments=context.get_page_context_args(),
|
||||||
|
task_finished=update_page,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Output sidecar text
|
||||||
|
if options.sidecar:
|
||||||
|
text = merge_sidecars(sidecars, context)
|
||||||
|
# Copy text file to destination
|
||||||
|
copy_final(text, options.sidecar, options.input_file)
|
||||||
|
|
||||||
|
# Merge layers to one single pdf
|
||||||
|
pdf = ocrgraft.finalize()
|
||||||
|
|
||||||
|
messages: Sequence[str] = []
|
||||||
|
if options.output_type != 'none':
|
||||||
|
# PDF/A and metadata
|
||||||
|
log.info("Postprocessing...")
|
||||||
|
pdf, messages = postprocess(pdf, context, executor)
|
||||||
|
|
||||||
|
# Copy PDF file to destination
|
||||||
|
copy_final(pdf, options.output_file, options.input_file)
|
||||||
|
return messages
|
||||||
|
|
||||||
|
|
||||||
|
def _run_pipeline(
|
||||||
|
options: argparse.Namespace,
|
||||||
|
plugin_manager: OcrmypdfPluginManager,
|
||||||
|
) -> ExitCode:
|
||||||
|
with manage_work_folder(
|
||||||
|
work_folder=Path(mkdtemp(prefix="ocrmypdf.io.")),
|
||||||
|
retain=options.keep_temporary_files,
|
||||||
|
print_location=options.keep_temporary_files,
|
||||||
|
) as work_folder, manage_debug_log_handler(
|
||||||
|
options=options, work_folder=work_folder
|
||||||
|
):
|
||||||
|
executor = setup_pipeline(options, plugin_manager)
|
||||||
|
check_requested_output_file(options)
|
||||||
|
start_input_file, original_filename = create_input_file(options, work_folder)
|
||||||
|
|
||||||
|
# Triage image or pdf
|
||||||
|
origin_pdf = triage(
|
||||||
|
original_filename, start_input_file, work_folder / 'origin.pdf', options
|
||||||
|
)
|
||||||
|
|
||||||
|
# Gather pdfinfo and create context
|
||||||
|
pdfinfo = get_pdfinfo(
|
||||||
|
origin_pdf,
|
||||||
|
executor=executor,
|
||||||
|
detailed_analysis=options.redo_ocr,
|
||||||
|
progbar=options.progress_bar,
|
||||||
|
max_workers=options.jobs,
|
||||||
|
use_threads=options.use_threads,
|
||||||
|
check_pages=options.pages,
|
||||||
|
)
|
||||||
|
|
||||||
|
context = PdfContext(options, work_folder, origin_pdf, pdfinfo, plugin_manager)
|
||||||
|
|
||||||
|
# Validate options are okay for this pdf
|
||||||
|
validate_pdfinfo_options(context)
|
||||||
|
|
||||||
|
# Execute the pipeline
|
||||||
|
optimize_messages = exec_concurrent(context, executor)
|
||||||
|
|
||||||
|
exitcode = report_output_pdf(options, start_input_file, optimize_messages)
|
||||||
|
return exitcode
|
||||||
|
|
||||||
|
|
||||||
|
def run_pipeline_cli(
|
||||||
|
options: argparse.Namespace,
|
||||||
|
*,
|
||||||
|
plugin_manager: OcrmypdfPluginManager,
|
||||||
|
) -> ExitCode:
|
||||||
|
"""Run the OCR pipeline with command line exception handling.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
options: The parsed command line options.
|
||||||
|
plugin_manager: The plugin manager to use. If not provided, one will be
|
||||||
|
created.
|
||||||
|
"""
|
||||||
|
return cli_exception_handler(_run_pipeline, options, plugin_manager)
|
||||||
|
|
||||||
|
|
||||||
|
def run_pipeline(
|
||||||
|
options: argparse.Namespace,
|
||||||
|
*,
|
||||||
|
plugin_manager: OcrmypdfPluginManager,
|
||||||
|
) -> ExitCode:
|
||||||
|
"""Run the OCR pipeline without command line exception handling.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
options: The parsed command line options.
|
||||||
|
plugin_manager: The plugin manager to use. If not provided, one will be
|
||||||
|
created.
|
||||||
|
"""
|
||||||
|
return _run_pipeline(options, plugin_manager)
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
# SPDX-FileCopyrightText: 2019-2023 James R. Barlow
|
||||||
|
# SPDX-FileCopyrightText: 2019 Martin Wind
|
||||||
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
|
|
||||||
|
"""Implements the concurrent and page synchronous parts of the pipeline."""
|
||||||
|
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import logging
|
||||||
|
import logging.handlers
|
||||||
|
import shutil
|
||||||
|
from functools import partial
|
||||||
|
|
||||||
|
import PIL
|
||||||
|
|
||||||
|
from ocrmypdf._concurrent import Executor
|
||||||
|
from ocrmypdf._jobcontext import PageContext, PdfContext
|
||||||
|
from ocrmypdf._pipeline import (
|
||||||
|
get_pdfinfo,
|
||||||
|
is_ocr_required,
|
||||||
|
ocr_engine_hocr,
|
||||||
|
validate_pdfinfo_options,
|
||||||
|
)
|
||||||
|
from ocrmypdf._pipelines._common import (
|
||||||
|
HOCRResult,
|
||||||
|
manage_work_folder,
|
||||||
|
process_page,
|
||||||
|
set_thread_pageno,
|
||||||
|
setup_pipeline,
|
||||||
|
worker_init,
|
||||||
|
)
|
||||||
|
from ocrmypdf._plugin_manager import OcrmypdfPluginManager
|
||||||
|
from ocrmypdf._validation import (
|
||||||
|
set_lossless_reconstruction,
|
||||||
|
)
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _exec_page_hocr_sync(page_context: PageContext) -> HOCRResult:
|
||||||
|
"""Execute a pipeline for a single page hOCR."""
|
||||||
|
set_thread_pageno(page_context.pageno + 1)
|
||||||
|
|
||||||
|
if not is_ocr_required(page_context):
|
||||||
|
return HOCRResult(pageno=page_context.pageno)
|
||||||
|
|
||||||
|
ocr_image_out, pdf_page_from_image_out, orientation_correction = process_page(
|
||||||
|
page_context
|
||||||
|
)
|
||||||
|
hocr_out, _ = ocr_engine_hocr(ocr_image_out, page_context)
|
||||||
|
|
||||||
|
result = HOCRResult(
|
||||||
|
pageno=page_context.pageno,
|
||||||
|
pdf_page_from_image=pdf_page_from_image_out,
|
||||||
|
hocr=hocr_out,
|
||||||
|
orientation_correction=orientation_correction,
|
||||||
|
)
|
||||||
|
page_context.get_path('hocr.json').write_text(result.to_json())
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def exec_pdf_to_hocr(context: PdfContext, executor: Executor) -> None:
|
||||||
|
"""Execute the OCR pipeline concurrently and output hOCR."""
|
||||||
|
# Run exec_page_sync on every page
|
||||||
|
options = context.options
|
||||||
|
max_workers = min(len(context.pdfinfo), options.jobs)
|
||||||
|
if max_workers > 1:
|
||||||
|
log.info("Start processing %d pages concurrently", max_workers)
|
||||||
|
|
||||||
|
executor(
|
||||||
|
use_threads=options.use_threads,
|
||||||
|
max_workers=max_workers,
|
||||||
|
progress_kwargs=dict(
|
||||||
|
total=(2 * len(context.pdfinfo)),
|
||||||
|
desc='hOCR',
|
||||||
|
unit='page',
|
||||||
|
unit_scale=0.5,
|
||||||
|
disable=not options.progress_bar,
|
||||||
|
),
|
||||||
|
worker_initializer=partial(worker_init, PIL.Image.MAX_IMAGE_PIXELS),
|
||||||
|
task=_exec_page_hocr_sync,
|
||||||
|
task_arguments=context.get_page_context_args(),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def run_hocr_pipeline(
|
||||||
|
options: argparse.Namespace,
|
||||||
|
*,
|
||||||
|
plugin_manager: OcrmypdfPluginManager,
|
||||||
|
) -> None:
|
||||||
|
"""Run pipeline to output hOCR."""
|
||||||
|
with manage_work_folder(
|
||||||
|
work_folder=options.output_folder, retain=True, print_location=False
|
||||||
|
) as work_folder:
|
||||||
|
executor = setup_pipeline(options, plugin_manager)
|
||||||
|
shutil.copy2(options.input_file, work_folder / 'origin.pdf')
|
||||||
|
|
||||||
|
# Gather pdfinfo and create context
|
||||||
|
pdfinfo = get_pdfinfo(
|
||||||
|
options.input_file,
|
||||||
|
executor=executor,
|
||||||
|
detailed_analysis=options.redo_ocr,
|
||||||
|
progbar=options.progress_bar,
|
||||||
|
max_workers=options.jobs,
|
||||||
|
use_threads=options.use_threads,
|
||||||
|
check_pages=options.pages,
|
||||||
|
)
|
||||||
|
context = PdfContext(
|
||||||
|
options, work_folder, options.input_file, pdfinfo, plugin_manager
|
||||||
|
)
|
||||||
|
# Validate options are okay for this pdf
|
||||||
|
set_lossless_reconstruction(options)
|
||||||
|
validate_pdfinfo_options(context)
|
||||||
|
exec_pdf_to_hocr(context, executor)
|
||||||
@@ -10,8 +10,8 @@ import importlib
|
|||||||
import importlib.util
|
import importlib.util
|
||||||
import pkgutil
|
import pkgutil
|
||||||
import sys
|
import sys
|
||||||
|
from collections.abc import Sequence
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Sequence
|
|
||||||
|
|
||||||
import pluggy
|
import pluggy
|
||||||
|
|
||||||
@@ -33,7 +33,7 @@ class OcrmypdfPluginManager(pluggy.PluginManager):
|
|||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
*args,
|
*args,
|
||||||
plugins: list[str | Path],
|
plugins: Sequence[str | Path],
|
||||||
builtins: bool = True,
|
builtins: bool = True,
|
||||||
**kwargs,
|
**kwargs,
|
||||||
):
|
):
|
||||||
@@ -100,10 +100,12 @@ class OcrmypdfPluginManager(pluggy.PluginManager):
|
|||||||
self.register(module)
|
self.register(module)
|
||||||
|
|
||||||
|
|
||||||
def get_plugin_manager(plugins: list[str | Path], builtins=True):
|
def get_plugin_manager(
|
||||||
|
plugins: Sequence[str | Path] | None = None, builtins=True
|
||||||
|
) -> OcrmypdfPluginManager:
|
||||||
return OcrmypdfPluginManager(
|
return OcrmypdfPluginManager(
|
||||||
project_name='ocrmypdf',
|
project_name='ocrmypdf',
|
||||||
plugins=plugins,
|
plugins=plugins if plugins is not None else [],
|
||||||
builtins=builtins,
|
builtins=builtins,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,142 @@
|
|||||||
|
# SPDX-FileCopyrightText: 2023 James R. Barlow
|
||||||
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
|
|
||||||
|
"""Defines progress bar API."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Protocol
|
||||||
|
|
||||||
|
from rich.console import Console
|
||||||
|
from rich.progress import (
|
||||||
|
BarColumn,
|
||||||
|
MofNCompleteColumn,
|
||||||
|
Progress,
|
||||||
|
TaskProgressColumn,
|
||||||
|
TextColumn,
|
||||||
|
TimeRemainingColumn,
|
||||||
|
)
|
||||||
|
from rich.table import Column
|
||||||
|
|
||||||
|
|
||||||
|
class ProgressBar(Protocol):
|
||||||
|
"""The protocol that OCRmyPDF expects progress bar classes to be compatible with.
|
||||||
|
|
||||||
|
In practice this could be used for any time of monitoring, not just a progress bar.
|
||||||
|
|
||||||
|
Calling the class should return a new progress bar object, which is activated
|
||||||
|
with ``__enter__`` and terminated with ``__exit__``. An update method is called
|
||||||
|
whenever the progress bar is updated. Progress bar objects will not be reused;
|
||||||
|
a new one will be created for each group of tasks.
|
||||||
|
|
||||||
|
The progress bar is held in the main process/thread and not updated by child
|
||||||
|
process/threads. When a child notifies the parent of completed work, the
|
||||||
|
parent updates the progress bar.
|
||||||
|
|
||||||
|
Progress bars should never write to ``sys.stdout``, or they will corrupt the
|
||||||
|
output if OCRmyPDF writes a PDF to standard output.
|
||||||
|
|
||||||
|
The type of events that OCRmyPDF reports to a progress bar may change in
|
||||||
|
minor releases.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
total: int | float | None,
|
||||||
|
desc: str | None,
|
||||||
|
unit: str | None,
|
||||||
|
disable: bool = False,
|
||||||
|
**kwargs,
|
||||||
|
):
|
||||||
|
"""Initialize a progress bar.
|
||||||
|
|
||||||
|
*total* indicates the total number of work units. If None, the total
|
||||||
|
number of work units is unknown. If *disable* is True, the progress bar
|
||||||
|
should be disabled. *unit* is a description of the work unit.
|
||||||
|
*desc* is a description of the overall task to be performed.
|
||||||
|
|
||||||
|
Unrecognized keyword arguments must be ignored, as the list of keyword
|
||||||
|
arguments may grow with time.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __enter__(self):
|
||||||
|
"""Enter a progress bar context."""
|
||||||
|
|
||||||
|
def __exit__(self, *args):
|
||||||
|
"""Exit a progress bar context."""
|
||||||
|
|
||||||
|
def update(self, n=1):
|
||||||
|
"""Update the progress bar by an increment.
|
||||||
|
|
||||||
|
For use within a progress bar context.
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class NullProgressBar:
|
||||||
|
"""Progress bar API that takes no actions."""
|
||||||
|
|
||||||
|
def __init__(self, **kwargs):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def __enter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, exc_type, exc_value, traceback):
|
||||||
|
return False
|
||||||
|
|
||||||
|
def update(self, _arg=None):
|
||||||
|
return
|
||||||
|
|
||||||
|
|
||||||
|
class RichProgressBar:
|
||||||
|
"""Display progress bar using rich."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
console: Console,
|
||||||
|
desc: str,
|
||||||
|
total: float | None = None,
|
||||||
|
unit: str | None = None,
|
||||||
|
unit_scale: float | None = 1.0,
|
||||||
|
disable: bool = False,
|
||||||
|
**kwargs,
|
||||||
|
):
|
||||||
|
self.progress = Progress(
|
||||||
|
TextColumn(
|
||||||
|
"[progress.description]{task.description}",
|
||||||
|
table_column=Column(min_width=20),
|
||||||
|
),
|
||||||
|
BarColumn(),
|
||||||
|
TaskProgressColumn(),
|
||||||
|
MofNCompleteColumn(),
|
||||||
|
TimeRemainingColumn(),
|
||||||
|
console=console,
|
||||||
|
auto_refresh=True,
|
||||||
|
redirect_stderr=True,
|
||||||
|
redirect_stdout=False,
|
||||||
|
disable=disable,
|
||||||
|
**kwargs,
|
||||||
|
)
|
||||||
|
self.unit_scale = unit_scale
|
||||||
|
self.progress_bar = self.progress.add_task(
|
||||||
|
desc,
|
||||||
|
total=total * self.unit_scale
|
||||||
|
if total is not None and self.unit_scale is not None
|
||||||
|
else None,
|
||||||
|
unit=unit,
|
||||||
|
)
|
||||||
|
|
||||||
|
def __enter__(self):
|
||||||
|
self.progress.start()
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, exc_type, exc_value, traceback):
|
||||||
|
self.progress.refresh()
|
||||||
|
self.progress.stop()
|
||||||
|
return False
|
||||||
|
|
||||||
|
def update(self, value=None):
|
||||||
|
advance = self.unit_scale if value is None else value
|
||||||
|
self.progress.update(self.progress_bar, advance=advance)
|
||||||
+55
-41
@@ -12,9 +12,9 @@ import os
|
|||||||
import sys
|
import sys
|
||||||
import unicodedata
|
import unicodedata
|
||||||
from argparse import Namespace
|
from argparse import Namespace
|
||||||
|
from collections.abc import Sequence
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from shutil import copyfileobj
|
from shutil import copyfileobj
|
||||||
from typing import Sequence
|
|
||||||
|
|
||||||
import pikepdf
|
import pikepdf
|
||||||
import PIL
|
import PIL
|
||||||
@@ -28,7 +28,6 @@ from ocrmypdf.exceptions import (
|
|||||||
OutputFileAccessError,
|
OutputFileAccessError,
|
||||||
)
|
)
|
||||||
from ocrmypdf.helpers import is_file_writable, monotonic, safe_symlink
|
from ocrmypdf.helpers import is_file_writable, monotonic, safe_symlink
|
||||||
from ocrmypdf.hocrtransform import HOCR_OK_LANGS
|
|
||||||
from ocrmypdf.subprocess import check_external_program
|
from ocrmypdf.subprocess import check_external_program
|
||||||
|
|
||||||
# -------------
|
# -------------
|
||||||
@@ -43,43 +42,46 @@ log = logging.getLogger(__name__)
|
|||||||
|
|
||||||
|
|
||||||
def check_platform() -> None:
|
def check_platform() -> None:
|
||||||
if os.name == 'nt' and sys.maxsize <= 2**32: # pragma: no cover
|
if sys.maxsize <= 2**32: # pragma: no cover
|
||||||
# 32-bit interpreter on Windows
|
log.warning(
|
||||||
log.error(
|
"You are running OCRmyPDF in a 32-bit (x86) Python interpreter. "
|
||||||
"You are running OCRmyPDF in a 32-bit (x86) Python interpreter."
|
"This is not supported. 32-bit does not have enough address space "
|
||||||
|
"to process large files. "
|
||||||
"Please use a 64-bit (x86-64) version of Python."
|
"Please use a 64-bit (x86-64) version of Python."
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def check_options_languages(options: Namespace, ocr_engine_languages: set[str]) -> None:
|
def check_options_languages(
|
||||||
|
options: Namespace, ocr_engine_languages: list[str]
|
||||||
|
) -> None:
|
||||||
if not options.languages:
|
if not options.languages:
|
||||||
options.languages = {DEFAULT_LANGUAGE}
|
options.languages = [DEFAULT_LANGUAGE]
|
||||||
system_lang = locale.getlocale()[0]
|
system_lang = locale.getlocale()[0]
|
||||||
if system_lang and not system_lang.startswith('en'):
|
if system_lang and not system_lang.startswith('en'):
|
||||||
log.debug("No language specified; assuming --language %s", DEFAULT_LANGUAGE)
|
log.debug("No language specified; assuming --language %s", DEFAULT_LANGUAGE)
|
||||||
if not ocr_engine_languages:
|
if not ocr_engine_languages:
|
||||||
return
|
return
|
||||||
missing_languages = options.languages - ocr_engine_languages
|
missing_languages = set(options.languages) - set(ocr_engine_languages)
|
||||||
if missing_languages:
|
if missing_languages:
|
||||||
|
lang_text = '\n'.join(lang for lang in missing_languages)
|
||||||
msg = (
|
msg = (
|
||||||
"OCR engine does not have language data for the following "
|
"OCR engine does not have language data for the following "
|
||||||
"requested languages: \n"
|
"requested languages: \n"
|
||||||
|
f"{lang_text}\n"
|
||||||
|
"Please install the appropriate language data for your OCR engine.\n"
|
||||||
|
"\n"
|
||||||
|
"See the online documentation for instructions:\n"
|
||||||
|
" https://ocrmypdf.readthedocs.io/en/latest/languages.html\n"
|
||||||
|
"\n"
|
||||||
|
"Note: most languages are identified by a 3-letter ISO 639-2 Code.\n"
|
||||||
|
"For example, English is 'eng', German is 'deu', and Spanish is 'spa'.\n"
|
||||||
|
"Simplified Chinese is 'chi_sim' and Traditional Chinese is 'chi_tra'."
|
||||||
|
"\n"
|
||||||
)
|
)
|
||||||
msg += '\n'.join(lang for lang in missing_languages)
|
|
||||||
msg += '\nNote: most languages are identified by a 3-digit ISO 639-2 Code'
|
|
||||||
raise MissingDependencyError(msg)
|
raise MissingDependencyError(msg)
|
||||||
|
|
||||||
|
|
||||||
def check_options_output(options: Namespace) -> None:
|
def check_options_output(options: Namespace) -> None:
|
||||||
is_latin = options.languages.issubset(HOCR_OK_LANGS)
|
|
||||||
|
|
||||||
if options.pdf_renderer.startswith('hocr') and not is_latin:
|
|
||||||
log.warning(
|
|
||||||
"The 'hocr' PDF renderer is known to cause problems with one "
|
|
||||||
"or more of the languages in your document. Use "
|
|
||||||
"`--pdf-renderer auto` (the default) to avoid this issue."
|
|
||||||
)
|
|
||||||
|
|
||||||
if options.output_type == 'none' and options.output_file not in (os.devnull, '-'):
|
if options.output_type == 'none' and options.output_file not in (os.devnull, '-'):
|
||||||
raise BadArgsError(
|
raise BadArgsError(
|
||||||
"Since you specified `--output-type none`, the output file "
|
"Since you specified `--output-type none`, the output file "
|
||||||
@@ -87,6 +89,8 @@ def check_options_output(options: Namespace) -> None:
|
|||||||
f"`-` to suppress this message."
|
f"`-` to suppress this message."
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def set_lossless_reconstruction(options: Namespace) -> None:
|
||||||
lossless_reconstruction = False
|
lossless_reconstruction = False
|
||||||
if not any(
|
if not any(
|
||||||
(
|
(
|
||||||
@@ -109,12 +113,10 @@ def check_options_output(options: Namespace) -> None:
|
|||||||
def check_options_sidecar(options: Namespace) -> None:
|
def check_options_sidecar(options: Namespace) -> None:
|
||||||
if options.sidecar == '\0':
|
if options.sidecar == '\0':
|
||||||
if options.output_file == '-':
|
if options.output_file == '-':
|
||||||
raise BadArgsError(
|
raise BadArgsError("--sidecar filename needed when output file is stdout.")
|
||||||
"--sidecar filename must be specified when output file is stdout."
|
|
||||||
)
|
|
||||||
elif options.output_file == os.devnull:
|
elif options.output_file == os.devnull:
|
||||||
raise BadArgsError(
|
raise BadArgsError(
|
||||||
"--sidecar filename must be specified when output file is /dev/null or NUL."
|
"--sidecar filename needed when output file is /dev/null or NUL."
|
||||||
)
|
)
|
||||||
options.sidecar = options.output_file + '.txt'
|
options.sidecar = options.output_file + '.txt'
|
||||||
if options.sidecar == options.input_file or options.sidecar == options.output_file:
|
if options.sidecar == options.input_file or options.sidecar == options.output_file:
|
||||||
@@ -134,7 +136,7 @@ def check_options_preprocessing(options: Namespace) -> None:
|
|||||||
package='unpaper',
|
package='unpaper',
|
||||||
version_checker=unpaper.version,
|
version_checker=unpaper.version,
|
||||||
need_version='6.1',
|
need_version='6.1',
|
||||||
required_for=['--clean, --clean-final'],
|
required_for="--clean, --clean-final", # Problem arguments
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
if options.unpaper_args:
|
if options.unpaper_args:
|
||||||
@@ -195,16 +197,6 @@ def check_options_ocr_behavior(options: Namespace) -> None:
|
|||||||
options.pages = _pages_from_ranges(options.pages)
|
options.pages = _pages_from_ranges(options.pages)
|
||||||
|
|
||||||
|
|
||||||
def check_options_advanced(options: Namespace) -> None:
|
|
||||||
if options.pdfa_image_compression != 'auto' and not options.output_type.startswith(
|
|
||||||
'pdfa'
|
|
||||||
):
|
|
||||||
log.warning(
|
|
||||||
"--pdfa-image-compression argument only applies when "
|
|
||||||
"--output-type is one of 'pdfa', 'pdfa-1', or 'pdfa-2'"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def check_options_metadata(options: Namespace) -> None:
|
def check_options_metadata(options: Namespace) -> None:
|
||||||
docinfo = [options.title, options.author, options.keywords, options.subject]
|
docinfo = [options.title, options.author, options.keywords, options.subject]
|
||||||
for s in (m for m in docinfo if m):
|
for s in (m for m in docinfo if m):
|
||||||
@@ -221,17 +213,17 @@ def check_options_metadata(options: Namespace) -> None:
|
|||||||
def check_options_pillow(options: Namespace) -> None:
|
def check_options_pillow(options: Namespace) -> None:
|
||||||
PIL.Image.MAX_IMAGE_PIXELS = int(options.max_image_mpixels * 1_000_000)
|
PIL.Image.MAX_IMAGE_PIXELS = int(options.max_image_mpixels * 1_000_000)
|
||||||
if PIL.Image.MAX_IMAGE_PIXELS == 0:
|
if PIL.Image.MAX_IMAGE_PIXELS == 0:
|
||||||
PIL.Image.MAX_IMAGE_PIXELS = None
|
PIL.Image.MAX_IMAGE_PIXELS = None # type: ignore
|
||||||
|
|
||||||
|
|
||||||
def _check_plugin_invariant_options(options: Namespace) -> None:
|
def _check_plugin_invariant_options(options: Namespace) -> None:
|
||||||
check_platform()
|
check_platform()
|
||||||
check_options_metadata(options)
|
check_options_metadata(options)
|
||||||
check_options_output(options)
|
check_options_output(options)
|
||||||
|
set_lossless_reconstruction(options)
|
||||||
check_options_sidecar(options)
|
check_options_sidecar(options)
|
||||||
check_options_preprocessing(options)
|
check_options_preprocessing(options)
|
||||||
check_options_ocr_behavior(options)
|
check_options_ocr_behavior(options)
|
||||||
check_options_advanced(options)
|
|
||||||
check_options_pillow(options)
|
check_options_pillow(options)
|
||||||
|
|
||||||
|
|
||||||
@@ -246,6 +238,18 @@ def check_options(options: Namespace, plugin_manager: PluginManager) -> None:
|
|||||||
_check_plugin_options(options, plugin_manager)
|
_check_plugin_options(options, plugin_manager)
|
||||||
|
|
||||||
|
|
||||||
|
def _in_docker():
|
||||||
|
return Path('/.dockerenv').exists()
|
||||||
|
|
||||||
|
|
||||||
|
def _in_snap():
|
||||||
|
try:
|
||||||
|
cgroup_text = Path('/proc/self/cgroup').read_text()
|
||||||
|
return 'snap.ocrmypdf' in cgroup_text
|
||||||
|
except FileNotFoundError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
def create_input_file(options: Namespace, work_folder: Path) -> tuple[Path, str]:
|
def create_input_file(options: Namespace, work_folder: Path) -> tuple[Path, str]:
|
||||||
if options.input_file == '-':
|
if options.input_file == '-':
|
||||||
# stdin
|
# stdin
|
||||||
@@ -269,14 +273,24 @@ def create_input_file(options: Namespace, work_folder: Path) -> tuple[Path, str]
|
|||||||
return target, os.fspath(options.input_file)
|
return target, os.fspath(options.input_file)
|
||||||
except FileNotFoundError as e:
|
except FileNotFoundError as e:
|
||||||
msg = f"File not found - {options.input_file}"
|
msg = f"File not found - {options.input_file}"
|
||||||
if Path('/.dockerenv').exists(): # pragma: no cover
|
if _in_docker(): # pragma: no cover
|
||||||
msg += (
|
msg += (
|
||||||
"\nDocker cannot your working directory unless you "
|
"\nDocker cannot access your working directory unless you "
|
||||||
"explicitly share it with the Docker container and set up"
|
"explicitly share it with the Docker container and set up"
|
||||||
"permissions correctly.\n"
|
"permissions correctly.\n"
|
||||||
"You may find it easier to use stdin/stdout:"
|
"You may find it easier to use stdin/stdout:"
|
||||||
"\n"
|
"\n"
|
||||||
"\tdocker run -i --rm jbarlow83/ocrmypdf - - <input.pdf >output.pdf\n"
|
"\tdocker run -i --rm jbarlow83/ocrmypdf - - <input.pdf >output.pdf"
|
||||||
|
"\n"
|
||||||
|
)
|
||||||
|
elif _in_snap(): # pragma: no cover
|
||||||
|
msg += (
|
||||||
|
"\nSnap applications cannot access files outside of "
|
||||||
|
"your home directory unless you explicitly allow it. "
|
||||||
|
"You may find it easier to use stdin/stdout:"
|
||||||
|
"\n"
|
||||||
|
"\tsnap run ocrmypdf - - <input.pdf >output.pdf"
|
||||||
|
"\n"
|
||||||
)
|
)
|
||||||
raise InputFileError(msg) from e
|
raise InputFileError(msg) from e
|
||||||
|
|
||||||
@@ -333,7 +347,7 @@ def report_output_file_size(
|
|||||||
for arg in image_preproc:
|
for arg in image_preproc:
|
||||||
if getattr(options, arg, False):
|
if getattr(options, arg, False):
|
||||||
reasons.append(
|
reasons.append(
|
||||||
f"The argument --{arg.replace('_', '-')} was issued, causing transcoding."
|
f"--{arg.replace('_', '-')} was issued, causing transcoding."
|
||||||
)
|
)
|
||||||
|
|
||||||
reasons.extend(optimize_messages)
|
reasons.extend(optimize_messages)
|
||||||
|
|||||||
@@ -8,10 +8,7 @@ OCRmyPDF uses setuptools_scm to derive version from git tags.
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
try:
|
from importlib.metadata import version as _package_version
|
||||||
from importlib.metadata import version as _package_version
|
|
||||||
except ImportError:
|
|
||||||
from importlib_metadata import version as _package_version # type: ignore
|
|
||||||
|
|
||||||
PROGRAM_NAME = 'ocrmypdf'
|
PROGRAM_NAME = 'ocrmypdf'
|
||||||
|
|
||||||
|
|||||||
+284
-86
@@ -9,31 +9,31 @@ import logging
|
|||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
import threading
|
import threading
|
||||||
|
from argparse import Namespace
|
||||||
|
from collections.abc import Iterable, Sequence
|
||||||
from enum import IntEnum
|
from enum import IntEnum
|
||||||
from io import IOBase
|
from io import IOBase
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import AnyStr, BinaryIO, Iterable, Union
|
from typing import AnyStr, BinaryIO, Union
|
||||||
from warnings import warn
|
from warnings import warn
|
||||||
|
|
||||||
from ocrmypdf._logging import PageNumberFilter, TqdmConsole
|
import pluggy
|
||||||
|
|
||||||
|
from ocrmypdf._logging import PageNumberFilter
|
||||||
|
from ocrmypdf._pipelines.hocr_to_ocr_pdf import run_hocr_to_ocr_pdf_pipeline
|
||||||
|
from ocrmypdf._pipelines.ocr import run_pipeline, run_pipeline_cli
|
||||||
|
from ocrmypdf._pipelines.pdf_to_hocr import run_hocr_pipeline
|
||||||
from ocrmypdf._plugin_manager import get_plugin_manager
|
from ocrmypdf._plugin_manager import get_plugin_manager
|
||||||
from ocrmypdf._sync import run_pipeline
|
|
||||||
from ocrmypdf._validation import check_options
|
from ocrmypdf._validation import check_options
|
||||||
from ocrmypdf.cli import ArgumentParser, get_parser
|
from ocrmypdf.cli import ArgumentParser, get_parser
|
||||||
from ocrmypdf.helpers import is_iterable_notstr
|
from ocrmypdf.helpers import is_iterable_notstr
|
||||||
|
|
||||||
try:
|
|
||||||
import coloredlogs
|
|
||||||
except ModuleNotFoundError:
|
|
||||||
coloredlogs = None # pylint: disable=invalid-name
|
|
||||||
|
|
||||||
if coloredlogs:
|
|
||||||
from humanfriendly.terminal import enable_ansi_support
|
|
||||||
|
|
||||||
|
|
||||||
StrPath = Union[Path, AnyStr]
|
StrPath = Union[Path, AnyStr]
|
||||||
PathOrIO = Union[BinaryIO, StrPath]
|
PathOrIO = Union[BinaryIO, StrPath]
|
||||||
|
|
||||||
|
# Installing plugins affects the global state of the Python interpreter,
|
||||||
|
# so we need to use a lock to prevent multiple threads from installing
|
||||||
|
# plugins at the same time.
|
||||||
_api_lock = threading.Lock()
|
_api_lock = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
@@ -52,7 +52,7 @@ def configure_logging(
|
|||||||
*,
|
*,
|
||||||
progress_bar_friendly: bool = True,
|
progress_bar_friendly: bool = True,
|
||||||
manage_root_logger: bool = False,
|
manage_root_logger: bool = False,
|
||||||
plugin_manager=None,
|
plugin_manager: pluggy.PluginManager | None = None,
|
||||||
):
|
):
|
||||||
"""Set up logging.
|
"""Set up logging.
|
||||||
|
|
||||||
@@ -92,7 +92,6 @@ def configure_logging(
|
|||||||
Returns:
|
Returns:
|
||||||
The toplevel logger for ocrmypdf (or the root logger, if we are managing it).
|
The toplevel logger for ocrmypdf (or the root logger, if we are managing it).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
prefix = '' if manage_root_logger else 'ocrmypdf'
|
prefix = '' if manage_root_logger else 'ocrmypdf'
|
||||||
|
|
||||||
log = logging.getLogger(prefix)
|
log = logging.getLogger(prefix)
|
||||||
@@ -119,14 +118,7 @@ def configure_logging(
|
|||||||
else:
|
else:
|
||||||
fmt = '%(pageno)s%(message)s'
|
fmt = '%(pageno)s%(message)s'
|
||||||
|
|
||||||
use_colors = progress_bar_friendly
|
|
||||||
formatter = None
|
formatter = None
|
||||||
if coloredlogs and use_colors:
|
|
||||||
use_colors = enable_ansi_support()
|
|
||||||
if use_colors:
|
|
||||||
use_colors = coloredlogs.terminal_supports_colors()
|
|
||||||
if use_colors:
|
|
||||||
formatter = coloredlogs.ColoredFormatter(fmt=fmt)
|
|
||||||
|
|
||||||
if not formatter:
|
if not formatter:
|
||||||
formatter = logging.Formatter(fmt=fmt)
|
formatter = logging.Formatter(fmt=fmt)
|
||||||
@@ -146,20 +138,19 @@ def configure_logging(
|
|||||||
return log
|
return log
|
||||||
|
|
||||||
|
|
||||||
def create_options(
|
def _kwargs_to_cmdline(
|
||||||
*, input_file: PathOrIO, output_file: PathOrIO, parser: ArgumentParser, **kwargs
|
*, defer_kwargs: set[str], **kwargs
|
||||||
):
|
) -> tuple[list[str], dict[str, AnyStr]]:
|
||||||
|
"""Convert kwargs to command line arguments."""
|
||||||
cmdline = []
|
cmdline = []
|
||||||
deferred = []
|
deferred = {}
|
||||||
|
|
||||||
for arg, val in kwargs.items():
|
for arg, val in kwargs.items():
|
||||||
if val is None:
|
if val is None:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# These arguments with special handling for which we bypass
|
# Skip arguments that are handled elsewhere
|
||||||
# argparse
|
if arg in defer_kwargs:
|
||||||
if arg in {'progress_bar', 'plugins'}:
|
deferred[arg] = val
|
||||||
deferred.append((arg, val))
|
|
||||||
continue
|
continue
|
||||||
|
|
||||||
cmd_style_arg = arg.replace('_', '-')
|
cmd_style_arg = arg.replace('_', '-')
|
||||||
@@ -186,7 +177,30 @@ def create_options(
|
|||||||
cmdline.append(str(val))
|
cmdline.append(str(val))
|
||||||
else:
|
else:
|
||||||
raise TypeError(f"{arg}: {val} ({type(val)})")
|
raise TypeError(f"{arg}: {val} ({type(val)})")
|
||||||
|
return cmdline, deferred
|
||||||
|
|
||||||
|
|
||||||
|
def create_options(
|
||||||
|
*, input_file: PathOrIO, output_file: PathOrIO, parser: ArgumentParser, **kwargs
|
||||||
|
) -> Namespace:
|
||||||
|
"""Construct an options object from the input/output files and keyword arguments.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
input_file: Input file path or file object.
|
||||||
|
output_file: Output file path or file object.
|
||||||
|
parser: ArgumentParser object.
|
||||||
|
**kwargs: Keyword arguments.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
argparse.Namespace: A Namespace object containing the parsed arguments.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
TypeError: If the type of a keyword argument is not supported.
|
||||||
|
"""
|
||||||
|
cmdline, deferred = _kwargs_to_cmdline(
|
||||||
|
defer_kwargs={'progress_bar', 'plugins', 'parser', 'input_file', 'output_file'},
|
||||||
|
**kwargs,
|
||||||
|
)
|
||||||
if isinstance(input_file, (BinaryIO, IOBase)):
|
if isinstance(input_file, (BinaryIO, IOBase)):
|
||||||
cmdline.append('stream://input_file')
|
cmdline.append('stream://input_file')
|
||||||
else:
|
else:
|
||||||
@@ -198,7 +212,7 @@ def create_options(
|
|||||||
|
|
||||||
parser.enable_api_mode()
|
parser.enable_api_mode()
|
||||||
options = parser.parse_args(cmdline)
|
options = parser.parse_args(cmdline)
|
||||||
for keyword, val in deferred:
|
for keyword, val in deferred.items():
|
||||||
setattr(options, keyword, val)
|
setattr(options, keyword, val)
|
||||||
|
|
||||||
if options.input_file == 'stream://input_file':
|
if options.input_file == 'stream://input_file':
|
||||||
@@ -209,59 +223,78 @@ def create_options(
|
|||||||
return options
|
return options
|
||||||
|
|
||||||
|
|
||||||
def ocr( # pylint: disable=unused-argument
|
def ocr( # noqa: D417
|
||||||
input_file: PathOrIO,
|
input_file: PathOrIO,
|
||||||
output_file: PathOrIO,
|
output_file: PathOrIO,
|
||||||
*,
|
*,
|
||||||
language: Iterable[str] = None,
|
language: Iterable[str] | None = None,
|
||||||
image_dpi: int = None,
|
image_dpi: int | None = None,
|
||||||
output_type=None,
|
output_type: str | None = None,
|
||||||
sidecar: StrPath | None = None,
|
sidecar: StrPath | None = None,
|
||||||
jobs: int = None,
|
jobs: int | None = None,
|
||||||
use_threads: bool = None,
|
use_threads: bool | None = None,
|
||||||
title: str = None,
|
title: str | None = None,
|
||||||
author: str = None,
|
author: str | None = None,
|
||||||
subject: str = None,
|
subject: str | None = None,
|
||||||
keywords: str = None,
|
keywords: str | None = None,
|
||||||
rotate_pages: bool = None,
|
rotate_pages: bool | None = None,
|
||||||
remove_background: bool = None,
|
remove_background: bool | None = None,
|
||||||
deskew: bool = None,
|
deskew: bool | None = None,
|
||||||
clean: bool = None,
|
clean: bool | None = None,
|
||||||
clean_final: bool = None,
|
clean_final: bool | None = None,
|
||||||
unpaper_args: str = None,
|
unpaper_args: str | None = None,
|
||||||
oversample: int = None,
|
oversample: int | None = None,
|
||||||
remove_vectors: bool = None,
|
remove_vectors: bool | None = None,
|
||||||
force_ocr: bool = None,
|
force_ocr: bool | None = None,
|
||||||
skip_text: bool = None,
|
skip_text: bool | None = None,
|
||||||
redo_ocr: bool = None,
|
redo_ocr: bool | None = None,
|
||||||
skip_big: float = None,
|
skip_big: float | None = None,
|
||||||
optimize: int = None,
|
optimize: int | None = None,
|
||||||
jpg_quality: int = None,
|
jpg_quality: int | None = None,
|
||||||
png_quality: int = None,
|
png_quality: int | None = None,
|
||||||
jbig2_lossy: bool = None,
|
jbig2_lossy: bool | None = None,
|
||||||
jbig2_page_group_size: int = None,
|
jbig2_page_group_size: int | None = None,
|
||||||
pages: str = None,
|
jbig2_threshold: float | None = None,
|
||||||
max_image_mpixels: float = None,
|
pages: str | None = None,
|
||||||
tesseract_config: Iterable[str] = None,
|
max_image_mpixels: float | None = None,
|
||||||
tesseract_pagesegmode: int = None,
|
tesseract_config: Iterable[str] | None = None,
|
||||||
tesseract_oem: int = None,
|
tesseract_pagesegmode: int | None = None,
|
||||||
tesseract_thresholding: int = None,
|
tesseract_oem: int | None = None,
|
||||||
pdf_renderer=None,
|
tesseract_thresholding: int | None = None,
|
||||||
tesseract_timeout: float = None,
|
pdf_renderer: str | None = None,
|
||||||
rotate_pages_threshold: float = None,
|
tesseract_timeout: float | None = None,
|
||||||
pdfa_image_compression=None,
|
tesseract_non_ocr_timeout: float | None = None,
|
||||||
user_words: os.PathLike = None,
|
tesseract_downsample_above: int | None = None,
|
||||||
user_patterns: os.PathLike = None,
|
tesseract_downsample_large_images: bool | None = None,
|
||||||
fast_web_view: float = None,
|
rotate_pages_threshold: float | None = None,
|
||||||
plugins: Iterable[StrPath] = None,
|
pdfa_image_compression: str | None = None,
|
||||||
|
color_conversion_strategy: str | None = None,
|
||||||
|
user_words: os.PathLike | None = None,
|
||||||
|
user_patterns: os.PathLike | None = None,
|
||||||
|
fast_web_view: float | None = None,
|
||||||
|
continue_on_soft_render_error: bool | None = None,
|
||||||
|
invalidate_digital_signatures: bool | None = None,
|
||||||
|
plugins: Iterable[StrPath] | None = None,
|
||||||
plugin_manager=None,
|
plugin_manager=None,
|
||||||
keep_temporary_files: bool = None,
|
keep_temporary_files: bool | None = None,
|
||||||
progress_bar: bool = None,
|
progress_bar: bool | None = None,
|
||||||
**kwargs,
|
**kwargs,
|
||||||
):
|
):
|
||||||
"""Run OCRmyPDF on one PDF or image.
|
"""Run OCRmyPDF on one PDF or image.
|
||||||
|
|
||||||
For most arguments, see documentation for the equivalent command line parameter.
|
For most arguments, see documentation for the equivalent command line parameter.
|
||||||
|
|
||||||
|
This API takes a threading lock, because OCRmyPDF uses global state in particular
|
||||||
|
for the plugin system. The jobs parameter will be used to create a pool of
|
||||||
|
worker threads or processes at different times, subject to change. A Python
|
||||||
|
process can only run one OCRmyPDF task at a time.
|
||||||
|
|
||||||
|
To run parallelize instances OCRmyPDF, use separate Python processes to scale
|
||||||
|
horizontally. Generally speaking you should set jobs=sqrt(cpu_count) and run
|
||||||
|
sqrt(cpu_count) processes as a starting point. If you have files with a high page
|
||||||
|
count, run fewer processes and more jobs per process. If you have a lot of short
|
||||||
|
files, run more processes and fewer jobs per process.
|
||||||
|
|
||||||
A few specific arguments are discussed here:
|
A few specific arguments are discussed here:
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
@@ -283,9 +316,8 @@ def ocr( # pylint: disable=unused-argument
|
|||||||
When a stream is used as output, whether via a writable object or
|
When a stream is used as output, whether via a writable object or
|
||||||
``"-"``, some final validation steps are not performed (we do not read
|
``"-"``, some final validation steps are not performed (we do not read
|
||||||
back the stream after it is written).
|
back the stream after it is written).
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
ocrmypdf.PdfMergeFailedError: If the input PDF is malformed, preventing merging
|
|
||||||
with the OCR layer.
|
|
||||||
ocrmypdf.MissingDependencyError: If a required dependency program is missing or
|
ocrmypdf.MissingDependencyError: If a required dependency program is missing or
|
||||||
was not found on PATH.
|
was not found on PATH.
|
||||||
ocrmypdf.UnsupportedImageFormatError: If the input file type was an image that
|
ocrmypdf.UnsupportedImageFormatError: If the input file type was an image that
|
||||||
@@ -317,17 +349,15 @@ def ocr( # pylint: disable=unused-argument
|
|||||||
plugins = list(plugins)
|
plugins = list(plugins)
|
||||||
|
|
||||||
# No new variable names should be assigned until these two steps are run
|
# No new variable names should be assigned until these two steps are run
|
||||||
create_options_kwargs = {k: v for k, v in locals().items() if k != 'kwargs'}
|
create_options_kwargs = {
|
||||||
|
k: v
|
||||||
|
for k, v in locals().items()
|
||||||
|
if k not in {'input_file', 'output_file', 'kwargs'}
|
||||||
|
}
|
||||||
create_options_kwargs.update(kwargs)
|
create_options_kwargs.update(kwargs)
|
||||||
|
|
||||||
parser = get_parser()
|
parser = get_parser()
|
||||||
create_options_kwargs['parser'] = parser
|
|
||||||
|
|
||||||
with _api_lock:
|
with _api_lock:
|
||||||
# We can't allow multiple ocrmypdf.ocr() threads to run in parallel, because
|
|
||||||
# they might install different plugins, and generally speaking we have areas
|
|
||||||
# of code that use global state.
|
|
||||||
|
|
||||||
if not plugin_manager:
|
if not plugin_manager:
|
||||||
plugin_manager = get_plugin_manager(plugins)
|
plugin_manager = get_plugin_manager(plugins)
|
||||||
plugin_manager.hook.add_options(parser=parser) # pylint: disable=no-member
|
plugin_manager.hook.add_options(parser=parser) # pylint: disable=no-member
|
||||||
@@ -335,14 +365,181 @@ def ocr( # pylint: disable=unused-argument
|
|||||||
if 'verbose' in kwargs:
|
if 'verbose' in kwargs:
|
||||||
warn("ocrmypdf.ocr(verbose=) is ignored. Use ocrmypdf.configure_logging().")
|
warn("ocrmypdf.ocr(verbose=) is ignored. Use ocrmypdf.configure_logging().")
|
||||||
|
|
||||||
options = create_options(**create_options_kwargs)
|
options = create_options(
|
||||||
|
input_file=input_file,
|
||||||
|
output_file=output_file,
|
||||||
|
parser=parser,
|
||||||
|
**create_options_kwargs,
|
||||||
|
)
|
||||||
check_options(options, plugin_manager)
|
check_options(options, plugin_manager)
|
||||||
return run_pipeline(options=options, plugin_manager=plugin_manager, api=True)
|
return run_pipeline(options=options, plugin_manager=plugin_manager)
|
||||||
|
|
||||||
|
|
||||||
|
def _pdf_to_hocr( # noqa: D417
|
||||||
|
input_pdf: Path,
|
||||||
|
output_folder: Path,
|
||||||
|
*,
|
||||||
|
language: Iterable[str] | None = None,
|
||||||
|
image_dpi: int | None = None,
|
||||||
|
jobs: int | None = None,
|
||||||
|
use_threads: bool | None = None,
|
||||||
|
title: str | None = None,
|
||||||
|
author: str | None = None,
|
||||||
|
subject: str | None = None,
|
||||||
|
keywords: str | None = None,
|
||||||
|
rotate_pages: bool | None = None,
|
||||||
|
remove_background: bool | None = None,
|
||||||
|
deskew: bool | None = None,
|
||||||
|
clean: bool | None = None,
|
||||||
|
clean_final: bool | None = None,
|
||||||
|
unpaper_args: str | None = None,
|
||||||
|
oversample: int | None = None,
|
||||||
|
remove_vectors: bool | None = None,
|
||||||
|
force_ocr: bool | None = None,
|
||||||
|
skip_text: bool | None = None,
|
||||||
|
redo_ocr: bool | None = None,
|
||||||
|
skip_big: float | None = None,
|
||||||
|
pages: str | None = None,
|
||||||
|
max_image_mpixels: float | None = None,
|
||||||
|
tesseract_config: Iterable[str] | None = None,
|
||||||
|
tesseract_pagesegmode: int | None = None,
|
||||||
|
tesseract_oem: int | None = None,
|
||||||
|
tesseract_thresholding: int | None = None,
|
||||||
|
tesseract_timeout: float | None = None,
|
||||||
|
tesseract_non_ocr_timeout: float | None = None,
|
||||||
|
tesseract_downsample_above: int | None = None,
|
||||||
|
tesseract_downsample_large_images: bool | None = None,
|
||||||
|
rotate_pages_threshold: float | None = None,
|
||||||
|
user_words: os.PathLike | None = None,
|
||||||
|
user_patterns: os.PathLike | None = None,
|
||||||
|
continue_on_soft_render_error: bool | None = None,
|
||||||
|
invalidate_digital_signatures: bool | None = None,
|
||||||
|
plugin_manager=None,
|
||||||
|
plugins: Sequence[StrPath] | None = None,
|
||||||
|
keep_temporary_files: bool | None = None,
|
||||||
|
**kwargs,
|
||||||
|
):
|
||||||
|
"""Partially run OCRmyPDF and produces an output folder containing hOCR files.
|
||||||
|
|
||||||
|
Given a PDF file, this function will run OCRmyPDF up to the point where
|
||||||
|
the PDF is rasterized to images, OCRed, and the hOCR files are produced,
|
||||||
|
all of which are saved to the output folder. This is useful for applications
|
||||||
|
that want to provide an interface for users to edit the text before
|
||||||
|
rendering the final PDF.
|
||||||
|
|
||||||
|
Use :func:`hocr_to_ocr_pdf` to produce the final PDF.
|
||||||
|
|
||||||
|
For arguments not explicitly documented here, see documentation for the
|
||||||
|
equivalent command line parameter.
|
||||||
|
|
||||||
|
This API is **experimental** and subject to change.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
input_pdf: Input PDF file path.
|
||||||
|
output_folder: Output folder path.
|
||||||
|
**kwargs: Keyword arguments.
|
||||||
|
"""
|
||||||
|
# No new variable names should be assigned until these two steps are run
|
||||||
|
create_options_kwargs = {
|
||||||
|
k: v
|
||||||
|
for k, v in locals().items()
|
||||||
|
if k not in {'input_pdf', 'output_folder', 'kwargs'}
|
||||||
|
}
|
||||||
|
create_options_kwargs.update(kwargs)
|
||||||
|
|
||||||
|
parser = get_parser()
|
||||||
|
|
||||||
|
with _api_lock:
|
||||||
|
if not plugin_manager:
|
||||||
|
plugin_manager = get_plugin_manager(plugins)
|
||||||
|
plugin_manager.hook.add_options(parser=parser) # pylint: disable=no-member
|
||||||
|
|
||||||
|
cmdline, deferred = _kwargs_to_cmdline(
|
||||||
|
defer_kwargs={'input_pdf', 'output_folder', 'plugins'},
|
||||||
|
**create_options_kwargs,
|
||||||
|
)
|
||||||
|
cmdline.append(str(input_pdf))
|
||||||
|
cmdline.append(str(output_folder))
|
||||||
|
parser.enable_api_mode()
|
||||||
|
options = parser.parse_args(cmdline)
|
||||||
|
for keyword, val in deferred.items():
|
||||||
|
setattr(options, keyword, val)
|
||||||
|
delattr(options, 'output_file')
|
||||||
|
setattr(options, 'output_folder', output_folder)
|
||||||
|
|
||||||
|
return run_hocr_pipeline(options=options, plugin_manager=plugin_manager)
|
||||||
|
|
||||||
|
|
||||||
|
def _hocr_to_ocr_pdf( # noqa: D417
|
||||||
|
work_folder: Path,
|
||||||
|
output_file: Path,
|
||||||
|
*,
|
||||||
|
jobs: int | None = None,
|
||||||
|
use_threads: bool | None = None,
|
||||||
|
optimize: int | None = None,
|
||||||
|
jpg_quality: int | None = None,
|
||||||
|
png_quality: int | None = None,
|
||||||
|
jbig2_lossy: bool | None = None,
|
||||||
|
jbig2_page_group_size: int | None = None,
|
||||||
|
jbig2_threshold: float | None = None,
|
||||||
|
pdfa_image_compression: str | None = None,
|
||||||
|
color_conversion_strategy: str | None = None,
|
||||||
|
fast_web_view: float | None = None,
|
||||||
|
plugin_manager=None,
|
||||||
|
plugins: Sequence[StrPath] | None = None,
|
||||||
|
**kwargs,
|
||||||
|
):
|
||||||
|
"""Run OCRmyPDF on a work folder and produce an output PDF.
|
||||||
|
|
||||||
|
After running :func:`pdf_to_hocr`, this function will run OCRmyPDF on the work
|
||||||
|
folder to produce an output PDF. This function consolidates any changes made
|
||||||
|
to the hOCR files in the work folder and produces a final PDF.
|
||||||
|
|
||||||
|
For arguments not explicitly documented here, see documentation for the
|
||||||
|
equivalent command line parameter.
|
||||||
|
|
||||||
|
This API is **experimental** and subject to change.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
work_folder: Work folder path, as generated by :func:`pdf_to_hocr`.
|
||||||
|
output_file: Output PDF file path.
|
||||||
|
**kwargs: Keyword arguments.
|
||||||
|
"""
|
||||||
|
# No new variable names should be assigned until these two steps are run
|
||||||
|
create_options_kwargs = {
|
||||||
|
k: v
|
||||||
|
for k, v in locals().items()
|
||||||
|
if k not in {'work_folder', 'output_pdf', 'kwargs'}
|
||||||
|
}
|
||||||
|
create_options_kwargs.update(kwargs)
|
||||||
|
|
||||||
|
parser = get_parser()
|
||||||
|
|
||||||
|
with _api_lock:
|
||||||
|
if not plugin_manager:
|
||||||
|
plugin_manager = get_plugin_manager(plugins)
|
||||||
|
plugin_manager.hook.add_options(parser=parser) # pylint: disable=no-member
|
||||||
|
|
||||||
|
cmdline, deferred = _kwargs_to_cmdline(
|
||||||
|
defer_kwargs={'work_folder', 'output_file', 'plugins'},
|
||||||
|
**create_options_kwargs,
|
||||||
|
)
|
||||||
|
cmdline.append(str(work_folder))
|
||||||
|
cmdline.append(str(output_file))
|
||||||
|
parser.enable_api_mode()
|
||||||
|
options = parser.parse_args(cmdline)
|
||||||
|
for keyword, val in deferred.items():
|
||||||
|
setattr(options, keyword, val)
|
||||||
|
delattr(options, 'input_file')
|
||||||
|
setattr(options, 'work_folder', work_folder)
|
||||||
|
|
||||||
|
return run_hocr_to_ocr_pdf_pipeline(
|
||||||
|
options=options, plugin_manager=plugin_manager
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
'PageNumberFilter',
|
'PageNumberFilter',
|
||||||
'TqdmConsole',
|
|
||||||
'Verbosity',
|
'Verbosity',
|
||||||
'check_options',
|
'check_options',
|
||||||
'configure_logging',
|
'configure_logging',
|
||||||
@@ -351,4 +548,5 @@ __all__ = [
|
|||||||
'get_plugin_manager',
|
'get_plugin_manager',
|
||||||
'ocr',
|
'ocr',
|
||||||
'run_pipeline',
|
'run_pipeline',
|
||||||
|
'run_pipeline_cli',
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
||||||
# SPDX-License-Identifier: MPL-2.0
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
|
|
||||||
from __future__ import annotations
|
"""Plugins in this package are automatically loaded by ocrmypdf."""
|
||||||
|
|
||||||
# This file exists only mark builtin_plugins as a package.
|
from __future__ import annotations
|
||||||
# The plugin manager will not load it, so anything defined here may not be
|
|
||||||
# processed as a module.
|
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
||||||
# SPDX-License-Identifier: MPL-2.0
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
"""OCRmyPDF's multiprocessing/multithreading abstraction layer."""
|
"""OCRmyPDF's multiprocessing/multithreading abstraction layer."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
import logging.handlers
|
import logging.handlers
|
||||||
import multiprocessing
|
import multiprocessing
|
||||||
@@ -12,25 +12,27 @@ import queue
|
|||||||
import signal
|
import signal
|
||||||
import sys
|
import sys
|
||||||
import threading
|
import threading
|
||||||
|
from collections.abc import Iterable
|
||||||
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, as_completed
|
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, as_completed
|
||||||
from contextlib import suppress
|
from contextlib import suppress
|
||||||
from typing import Callable, Iterable, Type, Union
|
from typing import Callable, Union
|
||||||
|
|
||||||
from tqdm import tqdm
|
from rich.console import Console as RichConsole
|
||||||
|
|
||||||
from ocrmypdf import Executor, hookimpl
|
from ocrmypdf import Executor, hookimpl
|
||||||
from ocrmypdf._logging import TqdmConsole
|
from ocrmypdf._logging import RichLoggingHandler
|
||||||
|
from ocrmypdf._progressbar import RichProgressBar
|
||||||
from ocrmypdf.exceptions import InputFileError
|
from ocrmypdf.exceptions import InputFileError
|
||||||
from ocrmypdf.helpers import remove_all_log_handlers
|
from ocrmypdf.helpers import remove_all_log_handlers
|
||||||
|
|
||||||
FuturesExecutorClass = Union[Type[ThreadPoolExecutor], Type[ProcessPoolExecutor]]
|
FuturesExecutorClass = Union[type[ThreadPoolExecutor], type[ProcessPoolExecutor]]
|
||||||
Queue = Union[multiprocessing.Queue, queue.Queue]
|
Queue = Union[multiprocessing.Queue, queue.Queue]
|
||||||
UserInit = Callable[[], None]
|
UserInit = Callable[[], None]
|
||||||
WorkerInit = Callable[[Queue, UserInit, int], None]
|
WorkerInit = Callable[[Queue, UserInit, int], None]
|
||||||
|
|
||||||
|
|
||||||
def log_listener(q: Queue):
|
def log_listener(q: Queue):
|
||||||
"""Listen to the worker processes and forward the messages to logging
|
"""Listen to the worker processes and forward the messages to logging.
|
||||||
|
|
||||||
For simplicity this is a thread rather than a process. Only one process
|
For simplicity this is a thread rather than a process. Only one process
|
||||||
should actually write to sys.stderr or whatever we're using, so if this is
|
should actually write to sys.stderr or whatever we're using, so if this is
|
||||||
@@ -39,7 +41,6 @@ def log_listener(q: Queue):
|
|||||||
See:
|
See:
|
||||||
https://docs.python.org/3/howto/logging-cookbook.html#logging-to-a-single-file-from-multiple-processes
|
https://docs.python.org/3/howto/logging-cookbook.html#logging-to-a-single-file-from-multiple-processes
|
||||||
"""
|
"""
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
record = q.get()
|
record = q.get()
|
||||||
@@ -55,12 +56,12 @@ def log_listener(q: Queue):
|
|||||||
|
|
||||||
|
|
||||||
def process_sigbus(*args):
|
def process_sigbus(*args):
|
||||||
|
"""Handle SIGBUS signal at the worker level."""
|
||||||
raise InputFileError("A worker process lost access to an input file")
|
raise InputFileError("A worker process lost access to an input file")
|
||||||
|
|
||||||
|
|
||||||
def process_init(q: Queue, user_init: UserInit, loglevel) -> None:
|
def process_init(q: Queue, user_init: UserInit, loglevel) -> None:
|
||||||
"""Initialize a process pool worker"""
|
"""Initialize a process pool worker."""
|
||||||
|
|
||||||
# Ignore SIGINT (our parent process will kill us gracefully)
|
# Ignore SIGINT (our parent process will kill us gracefully)
|
||||||
signal.signal(signal.SIGINT, signal.SIG_IGN)
|
signal.signal(signal.SIGINT, signal.SIG_IGN)
|
||||||
|
|
||||||
@@ -69,7 +70,7 @@ def process_init(q: Queue, user_init: UserInit, loglevel) -> None:
|
|||||||
# Windows and Cygwin do not have pthread_sigmask or SIGBUS
|
# Windows and Cygwin do not have pthread_sigmask or SIGBUS
|
||||||
signal.signal(signal.SIGBUS, process_sigbus)
|
signal.signal(signal.SIGBUS, process_sigbus)
|
||||||
|
|
||||||
# Remove any log handlers that belong to the parent process
|
# Remove any log handlers inherited from the parent process
|
||||||
root = logging.getLogger()
|
root = logging.getLogger()
|
||||||
remove_all_log_handlers(root)
|
remove_all_log_handlers(root)
|
||||||
|
|
||||||
@@ -82,6 +83,7 @@ def process_init(q: Queue, user_init: UserInit, loglevel) -> None:
|
|||||||
|
|
||||||
|
|
||||||
def thread_init(q: Queue, user_init: UserInit, loglevel) -> None:
|
def thread_init(q: Queue, user_init: UserInit, loglevel) -> None:
|
||||||
|
"""Begin a thread pool worker."""
|
||||||
del q # unused but required argument
|
del q # unused but required argument
|
||||||
del loglevel # unused but required argument
|
del loglevel # unused but required argument
|
||||||
# As a thread, block SIGBUS so the main thread deals with it...
|
# As a thread, block SIGBUS so the main thread deals with it...
|
||||||
@@ -95,21 +97,12 @@ def thread_init(q: Queue, user_init: UserInit, loglevel) -> None:
|
|||||||
class StandardExecutor(Executor):
|
class StandardExecutor(Executor):
|
||||||
"""Standard OCRmyPDF concurrent task executor."""
|
"""Standard OCRmyPDF concurrent task executor."""
|
||||||
|
|
||||||
def _cancel_futures_kwargs(self):
|
|
||||||
"""Shim older Pythons that do not have Executor.shutdown(...cancel_futures=).
|
|
||||||
|
|
||||||
Remove this code when support for Python 3.8 is dropped.
|
|
||||||
"""
|
|
||||||
if sys.version_info[:2] < (3, 9):
|
|
||||||
return {}
|
|
||||||
return dict(cancel_futures=True)
|
|
||||||
|
|
||||||
def _execute(
|
def _execute(
|
||||||
self,
|
self,
|
||||||
*,
|
*,
|
||||||
use_threads: bool,
|
use_threads: bool,
|
||||||
max_workers: int,
|
max_workers: int,
|
||||||
tqdm_kwargs: dict,
|
progress_kwargs: dict,
|
||||||
worker_initializer: Callable,
|
worker_initializer: Callable,
|
||||||
task: Callable,
|
task: Callable,
|
||||||
task_arguments: Iterable,
|
task_arguments: Iterable,
|
||||||
@@ -127,22 +120,27 @@ class StandardExecutor(Executor):
|
|||||||
# Regardless of whether we use_threads for worker processes, the log_listener
|
# Regardless of whether we use_threads for worker processes, the log_listener
|
||||||
# must be a thread. Make sure we create the listener after the worker pool,
|
# must be a thread. Make sure we create the listener after the worker pool,
|
||||||
# so that it does not get forked into the workers.
|
# so that it does not get forked into the workers.
|
||||||
|
# If use_threads is False, we are currently guilty of creating a thread before
|
||||||
|
# forking on Linux, which is not recommended. However, we take a big
|
||||||
|
# performance hit in pdfinfo if we can't fork. Long term solution is to
|
||||||
|
# replace most of this with an asyncio implementation, and probably to
|
||||||
|
# migrate some of pdfinfo into C++ or Rust.
|
||||||
listener = threading.Thread(target=log_listener, args=(log_queue,))
|
listener = threading.Thread(target=log_listener, args=(log_queue,))
|
||||||
listener.start()
|
listener.start()
|
||||||
|
|
||||||
with self.pbar_class(**tqdm_kwargs) as pbar, executor_class(
|
with self.pbar_class(**progress_kwargs) as pbar, executor_class(
|
||||||
max_workers=max_workers,
|
max_workers=max_workers,
|
||||||
initializer=initializer,
|
initializer=initializer,
|
||||||
initargs=(log_queue, worker_initializer, logging.getLogger("").level),
|
initargs=(log_queue, worker_initializer, logging.getLogger("").level),
|
||||||
) as executor:
|
) as executor:
|
||||||
futures = [executor.submit(task, args) for args in task_arguments]
|
futures = [executor.submit(task, *args) for args in task_arguments]
|
||||||
try:
|
try:
|
||||||
for future in as_completed(futures):
|
for future in as_completed(futures):
|
||||||
result = future.result()
|
result = future.result()
|
||||||
task_finished(result, pbar)
|
task_finished(result, pbar)
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
# Terminate pool so we exit instantly
|
# Terminate pool so we exit instantly
|
||||||
executor.shutdown(wait=False, **self._cancel_futures_kwargs())
|
executor.shutdown(wait=False, cancel_futures=True)
|
||||||
raise
|
raise
|
||||||
except Exception:
|
except Exception:
|
||||||
if not os.environ.get("PYTEST_CURRENT_TEST", ""):
|
if not os.environ.get("PYTEST_CURRENT_TEST", ""):
|
||||||
@@ -151,7 +149,7 @@ class StandardExecutor(Executor):
|
|||||||
# results will be discard. But if the condition above is True,
|
# results will be discard. But if the condition above is True,
|
||||||
# then we are running in pytest, and we want everything to exit
|
# then we are running in pytest, and we want everything to exit
|
||||||
# as cleanly as possible so that we get good error messages.
|
# as cleanly as possible so that we get good error messages.
|
||||||
executor.shutdown(wait=False, **self._cancel_futures_kwargs())
|
executor.shutdown(wait=False, cancel_futures=True)
|
||||||
raise
|
raise
|
||||||
finally:
|
finally:
|
||||||
# Terminate log listener
|
# Terminate log listener
|
||||||
@@ -164,14 +162,24 @@ class StandardExecutor(Executor):
|
|||||||
|
|
||||||
@hookimpl
|
@hookimpl
|
||||||
def get_executor(progressbar_class):
|
def get_executor(progressbar_class):
|
||||||
|
"""Return the default executor."""
|
||||||
return StandardExecutor(pbar_class=progressbar_class)
|
return StandardExecutor(pbar_class=progressbar_class)
|
||||||
|
|
||||||
|
|
||||||
|
RICH_CONSOLE = RichConsole(stderr=True)
|
||||||
|
|
||||||
|
|
||||||
@hookimpl
|
@hookimpl
|
||||||
def get_progressbar_class():
|
def get_progressbar_class():
|
||||||
return tqdm
|
"""Return the default progress bar class."""
|
||||||
|
|
||||||
|
def partial_RichProgressBar(*args, **kwargs):
|
||||||
|
return RichProgressBar(*args, **kwargs, console=RICH_CONSOLE)
|
||||||
|
|
||||||
|
return partial_RichProgressBar
|
||||||
|
|
||||||
|
|
||||||
@hookimpl
|
@hookimpl
|
||||||
def get_logging_console():
|
def get_logging_console():
|
||||||
return logging.StreamHandler(stream=TqdmConsole(sys.stderr))
|
"""Return the default logging console handler."""
|
||||||
|
return RichLoggingHandler(console=RICH_CONSOLE)
|
||||||
|
|||||||
@@ -6,50 +6,75 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
|
from packaging.version import Version
|
||||||
|
|
||||||
from ocrmypdf import hookimpl
|
from ocrmypdf import hookimpl
|
||||||
from ocrmypdf._exec import ghostscript
|
from ocrmypdf._exec import ghostscript
|
||||||
from ocrmypdf._validation import HOCR_OK_LANGS
|
|
||||||
from ocrmypdf.exceptions import MissingDependencyError
|
from ocrmypdf.exceptions import MissingDependencyError
|
||||||
from ocrmypdf.subprocess import check_external_program
|
from ocrmypdf.subprocess import check_external_program
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# Currently all blacklisted versions are lower than 9.55, so none need to
|
||||||
|
# be added here. If a future version is blacklisted, add it here.
|
||||||
|
BLACKLISTED_GS_VERSIONS: frozenset[str] = frozenset()
|
||||||
|
|
||||||
|
|
||||||
|
@hookimpl
|
||||||
|
def add_options(parser):
|
||||||
|
gs = parser.add_argument_group("Ghostscript", "Advanced control of Ghostscript")
|
||||||
|
gs.add_argument(
|
||||||
|
'--color-conversion-strategy',
|
||||||
|
action='store',
|
||||||
|
type=str,
|
||||||
|
metavar='STRATEGY',
|
||||||
|
choices=ghostscript.COLOR_CONVERSION_STRATEGIES,
|
||||||
|
default='LeaveColorUnchanged',
|
||||||
|
help="Set Ghostscript color conversion strategy",
|
||||||
|
)
|
||||||
|
gs.add_argument(
|
||||||
|
'--pdfa-image-compression',
|
||||||
|
choices=['auto', 'jpeg', 'lossless'],
|
||||||
|
default='auto',
|
||||||
|
help="Specify how to compress images in the output PDF/A. 'auto' lets "
|
||||||
|
"OCRmyPDF decide. 'jpeg' changes all grayscale and color images to "
|
||||||
|
"JPEG compression. 'lossless' uses PNG-style lossless compression "
|
||||||
|
"for all images. Monochrome images are always compressed using a "
|
||||||
|
"lossless codec. Compression settings "
|
||||||
|
"are applied to all pages, including those for which OCR was "
|
||||||
|
"skipped. Not supported for --output-type=pdf ; that setting "
|
||||||
|
"preserves the original compression of all images.",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@hookimpl
|
@hookimpl
|
||||||
def check_options(options):
|
def check_options(options):
|
||||||
|
"""Check that the options are valid for this plugin."""
|
||||||
check_external_program(
|
check_external_program(
|
||||||
program='gs',
|
program='gs',
|
||||||
package='ghostscript',
|
package='ghostscript',
|
||||||
version_checker=ghostscript.version,
|
version_checker=ghostscript.version,
|
||||||
need_version='9.15', # limited by Travis CI / Ubuntu 14.04 backports
|
need_version='9.54', # RHEL 9's version; Ubuntu 22.04 has 9.55
|
||||||
)
|
)
|
||||||
gs_version = ghostscript.version()
|
gs_version = ghostscript.version()
|
||||||
if gs_version in ('9.24', '9.51'):
|
if gs_version in BLACKLISTED_GS_VERSIONS:
|
||||||
raise MissingDependencyError(
|
raise MissingDependencyError(
|
||||||
f"Ghostscript {gs_version} contains serious regressions and is not "
|
f"Ghostscript {gs_version} contains serious regressions and is not "
|
||||||
"supported. Please upgrade to a newer version, or downgrade to the "
|
"supported. Please upgrade to a newer version."
|
||||||
"previous version."
|
|
||||||
)
|
|
||||||
|
|
||||||
# We have these constraints to check for.
|
|
||||||
# 1. Ghostscript < 9.20 mangles multibyte Unicode
|
|
||||||
# 2. hocr doesn't work on non-Latin languages (so don't select it)
|
|
||||||
is_latin = options.languages.issubset(HOCR_OK_LANGS)
|
|
||||||
if gs_version < '9.20' and options.output_type != 'pdf' and not is_latin:
|
|
||||||
# https://bugs.ghostscript.com/show_bug.cgi?id=696874
|
|
||||||
# Ghostscript < 9.20 fails to encode multibyte characters properly
|
|
||||||
log.warning(
|
|
||||||
f"The installed version of Ghostscript ({gs_version}) does not work "
|
|
||||||
"correctly with the OCR languages you specified. Use --output-type pdf or "
|
|
||||||
"upgrade to Ghostscript 9.20 or later to avoid this issue."
|
|
||||||
)
|
)
|
||||||
|
|
||||||
if options.output_type == 'pdfa':
|
if options.output_type == 'pdfa':
|
||||||
options.output_type = 'pdfa-2'
|
options.output_type = 'pdfa-2'
|
||||||
|
if options.color_conversion_strategy not in ghostscript.COLOR_CONVERSION_STRATEGIES:
|
||||||
if options.output_type == 'pdfa-3' and ghostscript.version() < '9.19':
|
raise ValueError(
|
||||||
raise MissingDependencyError(
|
f"Invalid color conversion strategy: {options.color_conversion_strategy}"
|
||||||
"--output-type pdfa-3 requires Ghostscript 9.19 or later"
|
)
|
||||||
|
if options.pdfa_image_compression != 'auto' and not options.output_type.startswith(
|
||||||
|
'pdfa'
|
||||||
|
):
|
||||||
|
log.warning(
|
||||||
|
"--pdfa-image-compression argument only applies when "
|
||||||
|
"--output-type is one of 'pdfa', 'pdfa-1', or 'pdfa-2'"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -63,7 +88,9 @@ def rasterize_pdf_page(
|
|||||||
page_dpi,
|
page_dpi,
|
||||||
rotation,
|
rotation,
|
||||||
filter_vector,
|
filter_vector,
|
||||||
|
stop_on_soft_error,
|
||||||
):
|
):
|
||||||
|
"""Rasterize a single page of a PDF file using Ghostscript."""
|
||||||
ghostscript.rasterize_pdf(
|
ghostscript.rasterize_pdf(
|
||||||
input_file,
|
input_file,
|
||||||
output_file,
|
output_file,
|
||||||
@@ -73,6 +100,7 @@ def rasterize_pdf_page(
|
|||||||
page_dpi=page_dpi,
|
page_dpi=page_dpi,
|
||||||
rotation=rotation,
|
rotation=rotation,
|
||||||
filter_vector=filter_vector,
|
filter_vector=filter_vector,
|
||||||
|
stop_on_error=stop_on_soft_error,
|
||||||
)
|
)
|
||||||
return output_file
|
return output_file
|
||||||
|
|
||||||
@@ -82,17 +110,21 @@ def generate_pdfa(
|
|||||||
pdf_pages,
|
pdf_pages,
|
||||||
pdfmark,
|
pdfmark,
|
||||||
output_file,
|
output_file,
|
||||||
compression,
|
context,
|
||||||
pdf_version,
|
pdf_version,
|
||||||
pdfa_part,
|
pdfa_part,
|
||||||
progressbar_class,
|
progressbar_class,
|
||||||
|
stop_on_soft_error,
|
||||||
):
|
):
|
||||||
|
"""Generate a PDF/A from the list of PDF pages and PDF/A metadata."""
|
||||||
ghostscript.generate_pdfa(
|
ghostscript.generate_pdfa(
|
||||||
pdf_pages=[*pdf_pages, pdfmark],
|
pdf_pages=[*pdf_pages, pdfmark],
|
||||||
output_file=output_file,
|
output_file=output_file,
|
||||||
compression=compression,
|
compression=context.options.pdfa_image_compression,
|
||||||
|
color_conversion_strategy=context.options.color_conversion_strategy,
|
||||||
pdf_version=pdf_version,
|
pdf_version=pdf_version,
|
||||||
pdfa_part=pdfa_part,
|
pdfa_part=pdfa_part,
|
||||||
progressbar_class=progressbar_class,
|
progressbar_class=progressbar_class,
|
||||||
|
stop_on_error=stop_on_soft_error,
|
||||||
)
|
)
|
||||||
return output_file
|
return output_file
|
||||||
|
|||||||
@@ -6,8 +6,8 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
import logging
|
import logging
|
||||||
|
from collections.abc import Sequence
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Sequence
|
|
||||||
|
|
||||||
from ocrmypdf import Executor, PdfContext, hookimpl
|
from ocrmypdf import Executor, PdfContext, hookimpl
|
||||||
from ocrmypdf._exec import jbig2enc, pngquant
|
from ocrmypdf._exec import jbig2enc, pngquant
|
||||||
@@ -86,6 +86,16 @@ def add_options(parser):
|
|||||||
# Adjust number of pages to consider at once for JBIG2 compression
|
# Adjust number of pages to consider at once for JBIG2 compression
|
||||||
help=argparse.SUPPRESS,
|
help=argparse.SUPPRESS,
|
||||||
)
|
)
|
||||||
|
optimizing.add_argument(
|
||||||
|
'--jbig2-threshold',
|
||||||
|
type=numeric(float, 0.4, 0.9),
|
||||||
|
default=0.85,
|
||||||
|
metavar='T',
|
||||||
|
help=(
|
||||||
|
"Adjust JBIG2 symbol code classification threshold "
|
||||||
|
"(default 0.85), range 0.4 to 0.9."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@hookimpl
|
@hookimpl
|
||||||
@@ -95,7 +105,7 @@ def check_options(options):
|
|||||||
program='pngquant',
|
program='pngquant',
|
||||||
package='pngquant',
|
package='pngquant',
|
||||||
version_checker=pngquant.version,
|
version_checker=pngquant.version,
|
||||||
need_version='2.0.1',
|
need_version='2.12.2',
|
||||||
required_for='--optimize {2,3}',
|
required_for='--optimize {2,3}',
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -8,10 +8,14 @@ from __future__ import annotations
|
|||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
|
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
from ocrmypdf import hookimpl
|
from ocrmypdf import hookimpl
|
||||||
from ocrmypdf._exec import tesseract
|
from ocrmypdf._exec import tesseract
|
||||||
|
from ocrmypdf._jobcontext import PageContext
|
||||||
from ocrmypdf.cli import numeric, str_to_int
|
from ocrmypdf.cli import numeric, str_to_int
|
||||||
from ocrmypdf.helpers import clamp
|
from ocrmypdf.helpers import clamp
|
||||||
|
from ocrmypdf.imageops import calculate_downsample, downsample_image
|
||||||
from ocrmypdf.pluginspec import OcrEngine
|
from ocrmypdf.pluginspec import OcrEngine
|
||||||
from ocrmypdf.subprocess import check_external_program
|
from ocrmypdf.subprocess import check_external_program
|
||||||
|
|
||||||
@@ -26,7 +30,7 @@ def add_options(parser):
|
|||||||
action='append',
|
action='append',
|
||||||
metavar='CFG',
|
metavar='CFG',
|
||||||
default=[],
|
default=[],
|
||||||
help="Additional Tesseract configuration files -- see documentation",
|
help="Additional Tesseract configuration files -- see documentation.",
|
||||||
)
|
)
|
||||||
tess.add_argument(
|
tess.add_argument(
|
||||||
'--tesseract-pagesegmode',
|
'--tesseract-pagesegmode',
|
||||||
@@ -34,7 +38,7 @@ def add_options(parser):
|
|||||||
type=int,
|
type=int,
|
||||||
metavar='PSM',
|
metavar='PSM',
|
||||||
choices=range(0, 14),
|
choices=range(0, 14),
|
||||||
help="Set Tesseract page segmentation mode (see tesseract --help)",
|
help="Set Tesseract page segmentation mode (see tesseract --help).",
|
||||||
)
|
)
|
||||||
tess.add_argument(
|
tess.add_argument(
|
||||||
'--tesseract-oem',
|
'--tesseract-oem',
|
||||||
@@ -43,7 +47,7 @@ def add_options(parser):
|
|||||||
metavar='MODE',
|
metavar='MODE',
|
||||||
choices=range(0, 4),
|
choices=range(0, 4),
|
||||||
help=(
|
help=(
|
||||||
"Set Tesseract 4.0+ OCR engine mode: "
|
"Set Tesseract 4+ OCR engine mode: "
|
||||||
"0 - original Tesseract only; "
|
"0 - original Tesseract only; "
|
||||||
"1 - neural nets LSTM only; "
|
"1 - neural nets LSTM only; "
|
||||||
"2 - Tesseract + LSTM; "
|
"2 - Tesseract + LSTM; "
|
||||||
@@ -58,7 +62,7 @@ def add_options(parser):
|
|||||||
metavar='METHOD',
|
metavar='METHOD',
|
||||||
help=(
|
help=(
|
||||||
"Set Tesseract 5.0+ input image thresholding mode. This may improve OCR "
|
"Set Tesseract 5.0+ input image thresholding mode. This may improve OCR "
|
||||||
"results on low quality images or those that contain high constrast color. "
|
"results on low quality images or those that contain high contrast color. "
|
||||||
"legacy-otsu is the Tesseract default; adaptive-otsu is an improved Otsu "
|
"legacy-otsu is the Tesseract default; adaptive-otsu is an improved Otsu "
|
||||||
"algorithm with improved sort for background color changes; sauvola is "
|
"algorithm with improved sort for background color changes; sauvola is "
|
||||||
"based on local standard deviation."
|
"based on local standard deviation."
|
||||||
@@ -69,8 +73,51 @@ def add_options(parser):
|
|||||||
default=180.0,
|
default=180.0,
|
||||||
type=numeric(float, 0),
|
type=numeric(float, 0),
|
||||||
metavar='SECONDS',
|
metavar='SECONDS',
|
||||||
help='Give up on OCR after the timeout, but copy the preprocessed page '
|
help=(
|
||||||
'into the final output',
|
"Give up on OCR after the timeout, but copy the preprocessed page "
|
||||||
|
"into the final output. This timeout is only used when using Tesseract "
|
||||||
|
"for OCR. When Tesseract is used for other operations such as "
|
||||||
|
"deskewing and orientation, the timeout is controlled by "
|
||||||
|
"--tesseract-non-ocr-timeout."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
tess.add_argument(
|
||||||
|
'--tesseract-non-ocr-timeout',
|
||||||
|
default=180.0,
|
||||||
|
type=numeric(float, 0),
|
||||||
|
metavar='SECONDS',
|
||||||
|
help=(
|
||||||
|
"Give up on non-OCR operations such as deskewing and orientation "
|
||||||
|
"after timeout. This is a separate timeout from --tesseract-timeout "
|
||||||
|
"because these operations are not as expensive as OCR."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
tess.add_argument(
|
||||||
|
'--tesseract-downsample-large-images',
|
||||||
|
action='store_true',
|
||||||
|
help=(
|
||||||
|
"Downsample large images before OCR. Tesseract has an upper limit on the "
|
||||||
|
"size images it will support. If this argument is given, OCRmyPDF will "
|
||||||
|
"downsample large images to fit Tesseract. This may reduce OCR quality, "
|
||||||
|
"on large images the most desirable text is usually larger. If this "
|
||||||
|
"parameter is not supplied, Tesseract will error out and produce no OCR "
|
||||||
|
"on the page in question. This argument should be used with a high value "
|
||||||
|
"of --tesseract-timeout to ensure Tesseract has enough to time."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
tess.add_argument(
|
||||||
|
'--tesseract-downsample-above',
|
||||||
|
action='store',
|
||||||
|
type=numeric(int, 100, 32767),
|
||||||
|
default=32767,
|
||||||
|
help=(
|
||||||
|
"Downsample images larger than this size pixel size in either dimension "
|
||||||
|
"before OCR. --tesseract-downsample-large-images downsamples only when "
|
||||||
|
"an image exceeds Tesseract's internal limits. This argument causes "
|
||||||
|
"downsampling to occur when an image exceeds the given size. This may "
|
||||||
|
"reduce OCR quality, but on large images the most desirable text is "
|
||||||
|
"usually larger."
|
||||||
|
),
|
||||||
)
|
)
|
||||||
tess.add_argument(
|
tess.add_argument(
|
||||||
'--user-words',
|
'--user-words',
|
||||||
@@ -93,7 +140,7 @@ def check_options(options):
|
|||||||
program='tesseract',
|
program='tesseract',
|
||||||
package={'linux': 'tesseract-ocr'},
|
package={'linux': 'tesseract-ocr'},
|
||||||
version_checker=tesseract.version,
|
version_checker=tesseract.version,
|
||||||
need_version='4.0.0-beta.1', # using backport for Travis CI
|
need_version='4.1.1', # Ubuntu 22.04 version (also 20.04)
|
||||||
version_parser=tesseract.TesseractVersion,
|
version_parser=tesseract.TesseractVersion,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -101,11 +148,6 @@ def check_options(options):
|
|||||||
if options.pdf_renderer == 'auto':
|
if options.pdf_renderer == 'auto':
|
||||||
options.pdf_renderer = 'sandwich'
|
options.pdf_renderer = 'sandwich'
|
||||||
|
|
||||||
if not tesseract.has_user_words() and (options.user_words or options.user_patterns):
|
|
||||||
log.warning(
|
|
||||||
"Tesseract 4.0 (which you have installed) ignores --user-words and "
|
|
||||||
"--user-patterns, so these arguments have no effect."
|
|
||||||
)
|
|
||||||
if not tesseract.has_thresholding() and options.tesseract_thresholding != 0:
|
if not tesseract.has_thresholding() and options.tesseract_thresholding != 0:
|
||||||
log.warning(
|
log.warning(
|
||||||
"The installed version of Tesseract does not support changes to its "
|
"The installed version of Tesseract does not support changes to its "
|
||||||
@@ -136,17 +178,45 @@ def validate(pdfinfo, options):
|
|||||||
tess_threads = int(os.environ['OMP_THREAD_LIMIT'])
|
tess_threads = int(os.environ['OMP_THREAD_LIMIT'])
|
||||||
log.debug("Using Tesseract OpenMP thread limit %d", tess_threads)
|
log.debug("Using Tesseract OpenMP thread limit %d", tess_threads)
|
||||||
|
|
||||||
|
if (
|
||||||
|
options.tesseract_downsample_above != 32767
|
||||||
|
and not options.tesseract_downsample_large_images
|
||||||
|
):
|
||||||
|
log.warning(
|
||||||
|
"The --tesseract-downsample-above argument will have no effect unless "
|
||||||
|
"--tesseract-downsample-large-images is also given."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@hookimpl
|
||||||
|
def filter_ocr_image(page: PageContext, image: Image.Image) -> Image.Image:
|
||||||
|
"""Filter the image before OCR.
|
||||||
|
|
||||||
|
Tesseract cannot handle images with more than 32767 pixels in either axis,
|
||||||
|
or more than 2**31 bytes. This function resizes the image to fit within
|
||||||
|
those limits.
|
||||||
|
"""
|
||||||
|
threshold = min(page.options.tesseract_downsample_above, 32767)
|
||||||
|
|
||||||
|
options = page.options
|
||||||
|
if options.tesseract_downsample_large_images:
|
||||||
|
size = calculate_downsample(
|
||||||
|
image, max_size=(threshold, threshold), max_bytes=(2**31) - 1
|
||||||
|
)
|
||||||
|
image = downsample_image(image, size)
|
||||||
|
return image
|
||||||
|
|
||||||
|
|
||||||
class TesseractOcrEngine(OcrEngine):
|
class TesseractOcrEngine(OcrEngine):
|
||||||
"""Implements OCR with Tesseract."""
|
"""Implements OCR with Tesseract."""
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def version():
|
def version():
|
||||||
return tesseract.version()
|
return str(tesseract.version())
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def creator_tag(options):
|
def creator_tag(options):
|
||||||
tag = '-PDF' if options.pdf_renderer == 'sandwich' else ''
|
tag = '-PDF' if options.pdf_renderer == 'sandwich' else 'hOCR'
|
||||||
return f"Tesseract OCR{tag} {TesseractOcrEngine.version()}"
|
return f"Tesseract OCR{tag} {TesseractOcrEngine.version()}"
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
@@ -161,7 +231,7 @@ class TesseractOcrEngine(OcrEngine):
|
|||||||
return tesseract.get_orientation(
|
return tesseract.get_orientation(
|
||||||
input_file,
|
input_file,
|
||||||
engine_mode=options.tesseract_oem,
|
engine_mode=options.tesseract_oem,
|
||||||
timeout=options.tesseract_timeout,
|
timeout=options.tesseract_non_ocr_timeout,
|
||||||
)
|
)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@@ -170,7 +240,7 @@ class TesseractOcrEngine(OcrEngine):
|
|||||||
input_file,
|
input_file,
|
||||||
languages=options.languages,
|
languages=options.languages,
|
||||||
engine_mode=options.tesseract_oem,
|
engine_mode=options.tesseract_oem,
|
||||||
timeout=options.tesseract_timeout,
|
timeout=options.tesseract_non_ocr_timeout,
|
||||||
)
|
)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
|||||||
+42
-22
@@ -6,7 +6,8 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
from typing import Any, Callable, Mapping, TypeVar
|
from collections.abc import Mapping
|
||||||
|
from typing import Any, Callable, TypeVar
|
||||||
|
|
||||||
from ocrmypdf._version import PROGRAM_NAME as _PROGRAM_NAME
|
from ocrmypdf._version import PROGRAM_NAME as _PROGRAM_NAME
|
||||||
from ocrmypdf._version import __version__ as _VERSION
|
from ocrmypdf._version import __version__ as _VERSION
|
||||||
@@ -15,7 +16,11 @@ T = TypeVar('T', int, float)
|
|||||||
|
|
||||||
|
|
||||||
def numeric(basetype: Callable[[Any], T], min_: T | None = None, max_: T | None = None):
|
def numeric(basetype: Callable[[Any], T], min_: T | None = None, max_: T | None = None):
|
||||||
"""Validator for numeric params"""
|
"""Validator for numeric command line parameters.
|
||||||
|
|
||||||
|
Stipulates that the value must be of type basetype (typically int or float), and
|
||||||
|
optionally, within the range [min_, max_].
|
||||||
|
"""
|
||||||
min_ = basetype(min_) if min_ is not None else None
|
min_ = basetype(min_) if min_ is not None else None
|
||||||
max_ = basetype(max_) if max_ is not None else None
|
max_ = basetype(max_) if max_ is not None else None
|
||||||
|
|
||||||
@@ -46,7 +51,7 @@ def str_to_int(mapping: Mapping[str, int]):
|
|||||||
|
|
||||||
|
|
||||||
class ArgumentParser(argparse.ArgumentParser):
|
class ArgumentParser(argparse.ArgumentParser):
|
||||||
"""Override parser's default behavior of calling sys.exit()
|
"""Override parser's default behavior of calling sys.exit().
|
||||||
|
|
||||||
https://stackoverflow.com/questions/5943249/python-argparse-and-controlling-overriding-the-exit-status-code
|
https://stackoverflow.com/questions/5943249/python-argparse-and-controlling-overriding-the-exit-status-code
|
||||||
|
|
||||||
@@ -57,13 +62,21 @@ class ArgumentParser(argparse.ArgumentParser):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
|
"""Initialize the parser."""
|
||||||
super().__init__(*args, **kwargs)
|
super().__init__(*args, **kwargs)
|
||||||
self._api_mode = False
|
self._api_mode = False
|
||||||
|
|
||||||
def enable_api_mode(self):
|
def enable_api_mode(self):
|
||||||
|
"""Enable API mode.
|
||||||
|
|
||||||
|
When set, the parser will not call sys.exit() on error. OCRmyPDF was originally
|
||||||
|
a command line program, but now it has an API. The API works by synthesizing
|
||||||
|
command line arguments.
|
||||||
|
"""
|
||||||
self._api_mode = True
|
self._api_mode = True
|
||||||
|
|
||||||
def error(self, message):
|
def error(self, message):
|
||||||
|
"""Override the default argparse error behavior."""
|
||||||
if not self._api_mode:
|
if not self._api_mode:
|
||||||
super().error(message)
|
super().error(message)
|
||||||
return
|
return
|
||||||
@@ -74,19 +87,22 @@ class LanguageSetAction(argparse.Action):
|
|||||||
"""Manages a list of languages."""
|
"""Manages a list of languages."""
|
||||||
|
|
||||||
def __init__(self, option_strings, dest, default=None, **kwargs):
|
def __init__(self, option_strings, dest, default=None, **kwargs):
|
||||||
|
"""Initialize the action."""
|
||||||
if default is None:
|
if default is None:
|
||||||
default = set()
|
default = list()
|
||||||
super().__init__(option_strings, dest, default=default, **kwargs)
|
super().__init__(option_strings, dest, default=default, **kwargs)
|
||||||
|
|
||||||
def __call__(self, parser, namespace, values, option_string=None):
|
def __call__(self, parser, namespace, values, option_string=None):
|
||||||
|
"""Add a language to the set."""
|
||||||
dest = getattr(namespace, self.dest)
|
dest = getattr(namespace, self.dest)
|
||||||
if '+' in values:
|
if '+' in values:
|
||||||
dest.update(lang for lang in values.split('+'))
|
[dest.append(lang) for lang in values.split('+')]
|
||||||
else:
|
else:
|
||||||
dest.add(values)
|
dest.append(values)
|
||||||
|
|
||||||
|
|
||||||
def get_parser():
|
def get_parser():
|
||||||
|
"""Get the main CLI parser."""
|
||||||
parser = ArgumentParser(
|
parser = ArgumentParser(
|
||||||
prog=_PROGRAM_NAME,
|
prog=_PROGRAM_NAME,
|
||||||
allow_abbrev=True,
|
allow_abbrev=True,
|
||||||
@@ -166,7 +182,9 @@ Online documentation is located at:
|
|||||||
'--image-dpi',
|
'--image-dpi',
|
||||||
metavar='DPI',
|
metavar='DPI',
|
||||||
type=int,
|
type=int,
|
||||||
help="For input image instead of PDF, use this DPI instead of file's.",
|
help="When the input file is an image, not a PDF, use this DPI instead "
|
||||||
|
"of the DPI claimed by the input file. If the input does not claim a "
|
||||||
|
"sensible DPI, this option will be required.",
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
'--output-type',
|
'--output-type',
|
||||||
@@ -175,8 +193,8 @@ Online documentation is located at:
|
|||||||
help="Choose output type. 'pdfa' creates a PDF/A-2b compliant file for "
|
help="Choose output type. 'pdfa' creates a PDF/A-2b compliant file for "
|
||||||
"long term archiving (default, recommended) but may not suitable "
|
"long term archiving (default, recommended) but may not suitable "
|
||||||
"for users who want their file altered as little as possible. 'pdfa' "
|
"for users who want their file altered as little as possible. 'pdfa' "
|
||||||
"also has problems with full Unicode text. 'pdf' attempts to "
|
"also has problems with full Unicode text. 'pdf' minimizes changes "
|
||||||
"preserve file contents as much as possible. 'pdf-a1' creates a "
|
"to the input file. 'pdf-a1' creates a "
|
||||||
"PDF/A1-b file. 'pdf-a2' is equivalent to 'pdfa'. 'pdf-a3' creates a "
|
"PDF/A1-b file. 'pdf-a2' is equivalent to 'pdfa'. 'pdf-a3' creates a "
|
||||||
"PDF/A3-b file. 'none' will produce no output, which may be helpful if "
|
"PDF/A3-b file. 'none' will produce no output, which may be helpful if "
|
||||||
"only the --sidecar is desired.",
|
"only the --sidecar is desired.",
|
||||||
@@ -348,6 +366,13 @@ Online documentation is located at:
|
|||||||
help="Skip OCR on pages larger than the specified amount of megapixels, "
|
help="Skip OCR on pages larger than the specified amount of megapixels, "
|
||||||
"but include skipped pages in final output",
|
"but include skipped pages in final output",
|
||||||
)
|
)
|
||||||
|
ocrsettings.add_argument(
|
||||||
|
'--invalidate-digital-signatures',
|
||||||
|
action='store_true',
|
||||||
|
help="Normally, OCRmyPDF will refuse to OCR a PDF that has a digital "
|
||||||
|
"signature. This option allows OCR to proceed, but the digital signature "
|
||||||
|
"will be invalidated.",
|
||||||
|
)
|
||||||
|
|
||||||
advanced = parser.add_argument_group(
|
advanced = parser.add_argument_group(
|
||||||
"Advanced", "Advanced options to control OCRmyPDF"
|
"Advanced", "Advanced options to control OCRmyPDF"
|
||||||
@@ -384,19 +409,6 @@ Online documentation is located at:
|
|||||||
help="Only rotate pages when confidence is above this value (arbitrary "
|
help="Only rotate pages when confidence is above this value (arbitrary "
|
||||||
"units reported by tesseract)",
|
"units reported by tesseract)",
|
||||||
)
|
)
|
||||||
advanced.add_argument(
|
|
||||||
'--pdfa-image-compression',
|
|
||||||
choices=['auto', 'jpeg', 'lossless'],
|
|
||||||
default='auto',
|
|
||||||
help="Specify how to compress images in the output PDF/A. 'auto' lets "
|
|
||||||
"OCRmyPDF decide. 'jpeg' changes all grayscale and color images to "
|
|
||||||
"JPEG compression. 'lossless' uses PNG-style lossless compression "
|
|
||||||
"for all images. Monochrome images are always compressed using a "
|
|
||||||
"lossless codec. Compression settings "
|
|
||||||
"are applied to all pages, including those for which OCR was "
|
|
||||||
"skipped. Not supported for --output-type=pdf ; that setting "
|
|
||||||
"preserves the original compression of all images.",
|
|
||||||
)
|
|
||||||
advanced.add_argument(
|
advanced.add_argument(
|
||||||
'--fast-web-view',
|
'--fast-web-view',
|
||||||
type=numeric(float, 0),
|
type=numeric(float, 0),
|
||||||
@@ -409,6 +421,14 @@ Online documentation is located at:
|
|||||||
"which do not benefit. If the threshold is 0 it will be apply to all files. "
|
"which do not benefit. If the threshold is 0 it will be apply to all files. "
|
||||||
"Set the threshold very high to disable.",
|
"Set the threshold very high to disable.",
|
||||||
)
|
)
|
||||||
|
advanced.add_argument(
|
||||||
|
'--continue-on-soft-render-error',
|
||||||
|
action='store_true',
|
||||||
|
help="Continue processing pages after a recoverable PDF rendering error. "
|
||||||
|
"A recoverable error is one that does not prevent the page from being "
|
||||||
|
"rendered, but may result in visual differences compared to the input "
|
||||||
|
"file. Missing fonts are a typical source of these errors.",
|
||||||
|
)
|
||||||
advanced.add_argument(
|
advanced.add_argument(
|
||||||
'--plugin',
|
'--plugin',
|
||||||
dest='plugins',
|
dest='plugins',
|
||||||
|
|||||||
Binary file not shown.
+40
-22
@@ -35,6 +35,7 @@ class ExitCodeException(Exception):
|
|||||||
message = ""
|
message = ""
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
|
"""Return a string representation of the exception."""
|
||||||
super_msg = super().__str__() # Don't do str(super())
|
super_msg = super().__str__() # Don't do str(super())
|
||||||
if self.message:
|
if self.message:
|
||||||
return self.message.format(super_msg)
|
return self.message.format(super_msg)
|
||||||
@@ -47,26 +48,6 @@ class BadArgsError(ExitCodeException):
|
|||||||
exit_code = ExitCode.bad_args
|
exit_code = ExitCode.bad_args
|
||||||
|
|
||||||
|
|
||||||
class PdfMergeFailedError(ExitCodeException): # deprecated
|
|
||||||
"""An intermediate PDF can't be merged.
|
|
||||||
|
|
||||||
No longer in use.
|
|
||||||
"""
|
|
||||||
|
|
||||||
exit_code = ExitCode.input_file
|
|
||||||
message = dedent(
|
|
||||||
'''\
|
|
||||||
Failed to merge PDF image layer with OCR layer
|
|
||||||
|
|
||||||
Usually this happens because the input PDF file is malformed and
|
|
||||||
ocrmypdf cannot correct the problem on its own.
|
|
||||||
|
|
||||||
Try using
|
|
||||||
ocrmypdf --pdf-renderer sandwich [..other args..]
|
|
||||||
'''
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class MissingDependencyError(ExitCodeException):
|
class MissingDependencyError(ExitCodeException):
|
||||||
"""A third-party dependency is missing."""
|
"""A third-party dependency is missing."""
|
||||||
|
|
||||||
@@ -114,7 +95,7 @@ class EncryptedPdfError(ExitCodeException):
|
|||||||
|
|
||||||
exit_code = ExitCode.encrypted_pdf
|
exit_code = ExitCode.encrypted_pdf
|
||||||
message = dedent(
|
message = dedent(
|
||||||
'''\
|
"""\
|
||||||
Input PDF is encrypted. The encryption must be removed to
|
Input PDF is encrypted. The encryption must be removed to
|
||||||
perform OCR.
|
perform OCR.
|
||||||
|
|
||||||
@@ -123,7 +104,7 @@ class EncryptedPdfError(ExitCodeException):
|
|||||||
|
|
||||||
You can remove the encryption using
|
You can remove the encryption using
|
||||||
qpdf --decrypt [--password=[password]] infilename
|
qpdf --decrypt [--password=[password]] infilename
|
||||||
'''
|
"""
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -132,3 +113,40 @@ class TesseractConfigError(ExitCodeException):
|
|||||||
|
|
||||||
exit_code = ExitCode.invalid_config
|
exit_code = ExitCode.invalid_config
|
||||||
message = "Error occurred while parsing a Tesseract configuration file"
|
message = "Error occurred while parsing a Tesseract configuration file"
|
||||||
|
|
||||||
|
|
||||||
|
class DigitalSignatureError(InputFileError):
|
||||||
|
"""PDF has a digital signature."""
|
||||||
|
|
||||||
|
message = dedent(
|
||||||
|
"""\
|
||||||
|
Input PDF has a digital signature. OCR would alter the document,
|
||||||
|
invalidating the signature.
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class TaggedPDFError(InputFileError):
|
||||||
|
"""PDF is tagged."""
|
||||||
|
|
||||||
|
message = dedent(
|
||||||
|
"""\
|
||||||
|
This PDF is marked as a Tagged PDF. This often indicates
|
||||||
|
that the PDF was generated from an office document and does
|
||||||
|
not need OCR. Use --force-ocr, --skip-text or --redo-ocr to
|
||||||
|
override this error.
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ColorConversionNeededError(BadArgsError):
|
||||||
|
"""PDF needs color conversion."""
|
||||||
|
|
||||||
|
message = dedent(
|
||||||
|
"""\
|
||||||
|
The input PDF has an unusual color space. Use
|
||||||
|
--color-conversion-strategy to convert to a common color space
|
||||||
|
such as RGB, or use --output-type pdf to skip PDF/A conversion
|
||||||
|
and retain the original color space.
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
|||||||
@@ -1,3 +1,9 @@
|
|||||||
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
||||||
#
|
#
|
||||||
# SPDX-License-Identifier: MPL-2.0
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
|
|
||||||
|
"""Extra plugins. These are not automatically inserted when ocrmypdf is run.
|
||||||
|
|
||||||
|
You can use these plugins by specifying them on the command line, e.g.:
|
||||||
|
ocrmypdf --plugin ocrmypdf.extra_plugins.semfree ...
|
||||||
|
"""
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ worker communicates only with the main process.
|
|||||||
|
|
||||||
This is not without drawbacks. If the tasks are not "even" in size, which cannot
|
This is not without drawbacks. If the tasks are not "even" in size, which cannot
|
||||||
be guaranteed, some workers may end up with too much work while others are idle.
|
be guaranteed, some workers may end up with too much work while others are idle.
|
||||||
It is less efficient than the standard implementation, so not th edefault.
|
It is less efficient than the standard implementation, so not the default.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -20,12 +20,13 @@ from __future__ import annotations
|
|||||||
import logging
|
import logging
|
||||||
import logging.handlers
|
import logging.handlers
|
||||||
import signal
|
import signal
|
||||||
|
from collections.abc import Iterable, Iterator
|
||||||
from contextlib import suppress
|
from contextlib import suppress
|
||||||
from enum import Enum, auto
|
from enum import Enum, auto
|
||||||
from itertools import islice, repeat, takewhile, zip_longest
|
from itertools import islice, repeat, takewhile, zip_longest
|
||||||
from multiprocessing import Pipe, Process
|
from multiprocessing import Pipe, Process
|
||||||
from multiprocessing.connection import Connection, wait
|
from multiprocessing.connection import Connection, wait
|
||||||
from typing import Callable, Iterable, Iterator
|
from typing import Callable
|
||||||
|
|
||||||
from ocrmypdf import Executor, hookimpl
|
from ocrmypdf import Executor, hookimpl
|
||||||
from ocrmypdf._concurrent import NullProgressBar
|
from ocrmypdf._concurrent import NullProgressBar
|
||||||
@@ -54,6 +55,7 @@ def split_every(n: int, iterable: Iterable) -> Iterator:
|
|||||||
|
|
||||||
|
|
||||||
def process_sigbus(*args):
|
def process_sigbus(*args):
|
||||||
|
"""Handle SIGBUS signal at the worker level."""
|
||||||
raise InputFileError("A worker process lost access to an input file")
|
raise InputFileError("A worker process lost access to an input file")
|
||||||
|
|
||||||
|
|
||||||
@@ -61,20 +63,21 @@ class ConnectionLogHandler(logging.handlers.QueueHandler):
|
|||||||
"""Handler used by child processes to forward log messages to parent."""
|
"""Handler used by child processes to forward log messages to parent."""
|
||||||
|
|
||||||
def __init__(self, conn: Connection) -> None:
|
def __init__(self, conn: Connection) -> None:
|
||||||
|
"""Initialize the handler."""
|
||||||
# sets the parent's queue to None - parent only touches queue
|
# sets the parent's queue to None - parent only touches queue
|
||||||
# in enqueue() which we override
|
# in enqueue() which we override
|
||||||
super().__init__(None) # type: ignore
|
super().__init__(None) # type: ignore
|
||||||
self.conn = conn
|
self.conn = conn
|
||||||
|
|
||||||
def enqueue(self, record):
|
def enqueue(self, record):
|
||||||
|
"""Enqueue a log message."""
|
||||||
self.conn.send(('log', record))
|
self.conn.send(('log', record))
|
||||||
|
|
||||||
|
|
||||||
def process_loop(
|
def process_loop(
|
||||||
conn: Connection, user_init: Callable[[], None], loglevel, task, task_args
|
conn: Connection, user_init: Callable[[], None], loglevel, task, task_args
|
||||||
):
|
):
|
||||||
"""Initialize a process pool worker"""
|
"""Initialize a process pool worker."""
|
||||||
|
|
||||||
# Install SIGBUS handler (so our parent process can abort somewhat gracefully)
|
# Install SIGBUS handler (so our parent process can abort somewhat gracefully)
|
||||||
with suppress(AttributeError): # Windows and Cygwin do not have SIGBUS
|
with suppress(AttributeError): # Windows and Cygwin do not have SIGBUS
|
||||||
# Windows and Cygwin do not have pthread_sigmask or SIGBUS
|
# Windows and Cygwin do not have pthread_sigmask or SIGBUS
|
||||||
@@ -91,7 +94,7 @@ def process_loop(
|
|||||||
|
|
||||||
for args in task_args:
|
for args in task_args:
|
||||||
try:
|
try:
|
||||||
result = task(args)
|
result = task(*args)
|
||||||
except Exception as e: # pylint: disable=broad-except
|
except Exception as e: # pylint: disable=broad-except
|
||||||
conn.send((MessageType.exception, e))
|
conn.send((MessageType.exception, e))
|
||||||
break
|
break
|
||||||
@@ -111,16 +114,16 @@ class LambdaExecutor(Executor):
|
|||||||
*,
|
*,
|
||||||
use_threads: bool,
|
use_threads: bool,
|
||||||
max_workers: int,
|
max_workers: int,
|
||||||
tqdm_kwargs: dict,
|
progress_kwargs: dict,
|
||||||
worker_initializer: Callable,
|
worker_initializer: Callable,
|
||||||
task: Callable,
|
task: Callable,
|
||||||
task_arguments: Iterable,
|
task_arguments: Iterable,
|
||||||
task_finished: Callable,
|
task_finished: Callable,
|
||||||
):
|
):
|
||||||
if use_threads and max_workers == 1:
|
if use_threads and max_workers == 1:
|
||||||
with self.pbar_class(**tqdm_kwargs) as pbar:
|
with self.pbar_class(**progress_kwargs) as pbar:
|
||||||
for args in task_arguments:
|
for args in task_arguments:
|
||||||
result = task(args)
|
result = task(*args)
|
||||||
task_finished(result, pbar)
|
task_finished(result, pbar)
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -154,7 +157,7 @@ class LambdaExecutor(Executor):
|
|||||||
for process in processes:
|
for process in processes:
|
||||||
process.start()
|
process.start()
|
||||||
|
|
||||||
with self.pbar_class(**tqdm_kwargs) as pbar:
|
with self.pbar_class(**progress_kwargs) as pbar:
|
||||||
while connections:
|
while connections:
|
||||||
for result in wait(connections):
|
for result in wait(connections):
|
||||||
if not isinstance(result, Connection):
|
if not isinstance(result, Connection):
|
||||||
@@ -166,8 +169,7 @@ class LambdaExecutor(Executor):
|
|||||||
continue
|
continue
|
||||||
|
|
||||||
if msg_type == MessageType.result:
|
if msg_type == MessageType.result:
|
||||||
if task_finished:
|
task_finished(msg, pbar)
|
||||||
task_finished(msg, pbar)
|
|
||||||
elif msg_type == 'log':
|
elif msg_type == 'log':
|
||||||
record = msg
|
record = msg
|
||||||
logger = logging.getLogger(record.name)
|
logger = logging.getLogger(record.name)
|
||||||
@@ -185,14 +187,20 @@ class LambdaExecutor(Executor):
|
|||||||
|
|
||||||
@hookimpl
|
@hookimpl
|
||||||
def get_executor(progressbar_class):
|
def get_executor(progressbar_class):
|
||||||
|
"""Return a LambdaExecutor instance."""
|
||||||
return LambdaExecutor(pbar_class=progressbar_class)
|
return LambdaExecutor(pbar_class=progressbar_class)
|
||||||
|
|
||||||
|
|
||||||
@hookimpl
|
@hookimpl
|
||||||
def get_logging_console():
|
def get_logging_console():
|
||||||
|
"""Return a logging.StreamHandler instance."""
|
||||||
return logging.StreamHandler()
|
return logging.StreamHandler()
|
||||||
|
|
||||||
|
|
||||||
@hookimpl
|
@hookimpl
|
||||||
def get_progressbar_class():
|
def get_progressbar_class():
|
||||||
|
"""Return a NullProgressBar instance.
|
||||||
|
|
||||||
|
This executor cannot use a progress bar.
|
||||||
|
"""
|
||||||
return NullProgressBar
|
return NullProgressBar
|
||||||
|
|||||||
+104
-64
@@ -10,48 +10,58 @@ import multiprocessing
|
|||||||
import os
|
import os
|
||||||
import shutil
|
import shutil
|
||||||
import warnings
|
import warnings
|
||||||
from collections import namedtuple
|
from collections.abc import Iterable, Sequence
|
||||||
from collections.abc import Iterable
|
|
||||||
from contextlib import suppress
|
from contextlib import suppress
|
||||||
from functools import wraps
|
from decimal import Decimal
|
||||||
from io import StringIO
|
from io import StringIO
|
||||||
from math import isclose, isfinite
|
from math import isclose, isfinite
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Sequence
|
from statistics import harmonic_mean
|
||||||
|
from typing import (
|
||||||
|
Any,
|
||||||
|
Callable,
|
||||||
|
Generic,
|
||||||
|
TypeVar,
|
||||||
|
)
|
||||||
|
|
||||||
import img2pdf
|
import img2pdf
|
||||||
import pikepdf
|
import pikepdf
|
||||||
from packaging.version import Version
|
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
if Version(img2pdf.__version__) < Version('0.4.0'):
|
IMG2PDF_KWARGS = dict(engine=img2pdf.Engine.pikepdf, rotation=img2pdf.Rotation.ifvalid)
|
||||||
IMG2PDF_KWARGS = dict(without_pdfw=True)
|
|
||||||
elif Version(img2pdf.__version__) < Version('0.4.3'):
|
|
||||||
IMG2PDF_KWARGS = dict(engine=img2pdf.Engine.pikepdf)
|
|
||||||
else:
|
|
||||||
IMG2PDF_KWARGS = dict(
|
|
||||||
engine=img2pdf.Engine.pikepdf, rotation=img2pdf.Rotation.ifvalid
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class Resolution(namedtuple('Resolution', ('x', 'y'))):
|
T = TypeVar('T', float, int, Decimal)
|
||||||
|
|
||||||
|
|
||||||
|
class Resolution(Generic[T]):
|
||||||
"""The number of pixels per inch in each 2D direction.
|
"""The number of pixels per inch in each 2D direction.
|
||||||
|
|
||||||
Resolution objects are considered "equal" for == purposes if they are
|
Resolution objects are considered "equal" for == purposes if they are
|
||||||
equal to a reasonable tolerance.
|
equal to a reasonable tolerance.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
__slots__ = ()
|
x: T
|
||||||
|
y: T
|
||||||
|
|
||||||
|
__slots__ = ('x', 'y')
|
||||||
|
|
||||||
|
def __init__(self, x: T, y: T):
|
||||||
|
"""Construct a Resolution object."""
|
||||||
|
self.x = x
|
||||||
|
self.y = y
|
||||||
|
|
||||||
# rel_tol after converting from dpi to pixels per meter and saving
|
# rel_tol after converting from dpi to pixels per meter and saving
|
||||||
# as integer with rounding, as many file formats
|
# as integer with rounding, as many file formats
|
||||||
CONVERSION_ERROR = 0.002
|
CONVERSION_ERROR = 0.002
|
||||||
|
|
||||||
def round(self, ndigits: int):
|
def round(self, ndigits: int) -> Resolution:
|
||||||
|
"""Round to ndigits after the decimal point."""
|
||||||
return Resolution(round(self.x, ndigits), round(self.y, ndigits))
|
return Resolution(round(self.x, ndigits), round(self.y, ndigits))
|
||||||
|
|
||||||
def to_int(self):
|
def to_int(self) -> Resolution[int]:
|
||||||
|
"""Round to nearest integer."""
|
||||||
return Resolution(int(round(self.x)), int(round(self.y)))
|
return Resolution(int(round(self.x)), int(round(self.y)))
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
@@ -60,31 +70,65 @@ class Resolution(namedtuple('Resolution', ('x', 'y'))):
|
|||||||
|
|
||||||
@property
|
@property
|
||||||
def is_square(self) -> bool:
|
def is_square(self) -> bool:
|
||||||
|
"""True if the resolution is square (x == y)."""
|
||||||
return self._isclose(self.x, self.y)
|
return self._isclose(self.x, self.y)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def is_finite(self) -> bool:
|
def is_finite(self) -> bool:
|
||||||
|
"""True if both x and y are finite numbers."""
|
||||||
return isfinite(self.x) and isfinite(self.y)
|
return isfinite(self.x) and isfinite(self.y)
|
||||||
|
|
||||||
def take_max(self, vals, yvals=None):
|
def to_scalar(self) -> float:
|
||||||
if yvals is not None:
|
"""Return the harmonic mean of x and y as a 1D approximation.
|
||||||
return Resolution(max(self.x, *vals), max(self.y, *yvals))
|
|
||||||
max_x, max_y = self.x, self.y
|
|
||||||
for x, y in vals:
|
|
||||||
max_x = max(x, max_x)
|
|
||||||
max_y = max(y, max_y)
|
|
||||||
return Resolution(max_x, max_y)
|
|
||||||
|
|
||||||
def flip_axis(self):
|
In most cases, Resolution is 2D, but typically it is "square" (x == y) and
|
||||||
|
can be approximated as a single number. When not square, the harmonic mean
|
||||||
|
is used to approximate the 2D resolution as a single number.
|
||||||
|
"""
|
||||||
|
return harmonic_mean([float(self.x), float(self.y)])
|
||||||
|
|
||||||
|
def _take_minmax(
|
||||||
|
self, vals: Iterable[Any], yvals: Iterable[Any] | None, cmp: Callable
|
||||||
|
) -> Resolution:
|
||||||
|
"""Return a new Resolution object with the maximum resolution of inputs."""
|
||||||
|
if yvals is not None:
|
||||||
|
return Resolution(cmp(self.x, *vals), cmp(self.y, *yvals))
|
||||||
|
cmp_x, cmp_y = self.x, self.y
|
||||||
|
for x, y in vals:
|
||||||
|
cmp_x = cmp(x, cmp_x)
|
||||||
|
cmp_y = cmp(y, cmp_y)
|
||||||
|
return Resolution(cmp_x, cmp_y)
|
||||||
|
|
||||||
|
def take_max(
|
||||||
|
self, vals: Iterable[Any], yvals: Iterable[Any] | None = None
|
||||||
|
) -> Resolution:
|
||||||
|
"""Return a new Resolution object with the maximum resolution of inputs."""
|
||||||
|
return self._take_minmax(vals, yvals, max)
|
||||||
|
|
||||||
|
def take_min(
|
||||||
|
self, vals: Iterable[Any], yvals: Iterable[Any] | None = None
|
||||||
|
) -> Resolution:
|
||||||
|
"""Return a new Resolution object with the minimum resolution of inputs."""
|
||||||
|
return self._take_minmax(vals, yvals, min)
|
||||||
|
|
||||||
|
def flip_axis(self) -> Resolution[T]:
|
||||||
|
"""Return a new Resolution object with x and y swapped."""
|
||||||
return Resolution(self.y, self.x)
|
return Resolution(self.y, self.x)
|
||||||
|
|
||||||
|
def __getitem__(self, idx: int | slice) -> T:
|
||||||
|
"""Support [0] and [1] indexing."""
|
||||||
|
return (self.x, self.y)[idx]
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return f"{self.x:f}x{self.y:f}"
|
"""Return a string representation of the resolution."""
|
||||||
|
return f"{self.x:f}×{self.y:f}"
|
||||||
|
|
||||||
def __repr__(self): # pragma: no cover
|
def __repr__(self): # pragma: no cover
|
||||||
return f"Resolution({self.x}x{self.y} dpi)"
|
"""Return a repr() of the resolution."""
|
||||||
|
return f"Resolution({self.x!r}, {self.y!r})"
|
||||||
|
|
||||||
def __eq__(self, other):
|
def __eq__(self, other):
|
||||||
|
"""Return True if the resolution is equal to another resolution."""
|
||||||
if isinstance(other, tuple) and len(other) == 2:
|
if isinstance(other, tuple) and len(other) == 2:
|
||||||
other = Resolution(*other)
|
other = Resolution(*other)
|
||||||
if not isinstance(other, Resolution):
|
if not isinstance(other, Resolution):
|
||||||
@@ -93,10 +137,10 @@ class Resolution(namedtuple('Resolution', ('x', 'y'))):
|
|||||||
|
|
||||||
|
|
||||||
class NeverRaise(Exception):
|
class NeverRaise(Exception):
|
||||||
"""An exception that is never raised"""
|
"""An exception that is never raised."""
|
||||||
|
|
||||||
|
|
||||||
def safe_symlink(input_file: os.PathLike, soft_link_name: os.PathLike):
|
def safe_symlink(input_file: os.PathLike, soft_link_name: os.PathLike) -> None:
|
||||||
"""Create a symbolic link at ``soft_link_name``, which references ``input_file``.
|
"""Create a symbolic link at ``soft_link_name``, which references ``input_file``.
|
||||||
|
|
||||||
Think of this as copying ``input_file`` to ``soft_link_name`` with less overhead.
|
Think of this as copying ``input_file`` to ``soft_link_name`` with less overhead.
|
||||||
@@ -111,7 +155,7 @@ def safe_symlink(input_file: os.PathLike, soft_link_name: os.PathLike):
|
|||||||
# Guard against soft linking to oneself
|
# Guard against soft linking to oneself
|
||||||
if input_file == soft_link_name:
|
if input_file == soft_link_name:
|
||||||
log.warning(
|
log.warning(
|
||||||
"No symbolic link created. You are using the original data directory "
|
"No symbolic link created. You are using the original data directory "
|
||||||
"as the working directory."
|
"as the working directory."
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
@@ -137,7 +181,11 @@ def safe_symlink(input_file: os.PathLike, soft_link_name: os.PathLike):
|
|||||||
os.symlink(os.path.abspath(input_file), soft_link_name)
|
os.symlink(os.path.abspath(input_file), soft_link_name)
|
||||||
|
|
||||||
|
|
||||||
def samefile(file1: os.PathLike, file2: os.PathLike):
|
def samefile(file1: os.PathLike, file2: os.PathLike) -> bool:
|
||||||
|
"""Return True if two files are the same file.
|
||||||
|
|
||||||
|
Attempts to account for different relative paths to the same file.
|
||||||
|
"""
|
||||||
if os.name == 'nt':
|
if os.name == 'nt':
|
||||||
return file1 == file2
|
return file1 == file2
|
||||||
else:
|
else:
|
||||||
@@ -155,7 +203,7 @@ def monotonic(seq: Sequence) -> bool:
|
|||||||
|
|
||||||
|
|
||||||
def page_number(input_file: os.PathLike) -> int:
|
def page_number(input_file: os.PathLike) -> int:
|
||||||
"""Get one-based page number implied by filename (000002.pdf -> 2)"""
|
"""Get one-based page number implied by filename (000002.pdf -> 2)."""
|
||||||
return int(os.path.basename(os.fspath(input_file))[0:6])
|
return int(os.path.basename(os.fspath(input_file))[0:6])
|
||||||
|
|
||||||
|
|
||||||
@@ -184,7 +232,7 @@ def is_file_writable(test_file: os.PathLike) -> bool:
|
|||||||
p = p.resolve(strict=False)
|
p = p.resolve(strict=False)
|
||||||
|
|
||||||
# p.is_file() throws an exception in some cases
|
# p.is_file() throws an exception in some cases
|
||||||
if p.exists() and p.is_file():
|
if p.exists() and (p.is_file() or p.samefile(os.devnull)):
|
||||||
return os.access(
|
return os.access(
|
||||||
os.fspath(p),
|
os.fspath(p),
|
||||||
os.W_OK,
|
os.W_OK,
|
||||||
@@ -252,43 +300,35 @@ def check_pdf(input_file: Path) -> bool:
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def clamp(n, smallest, largest): # mypy doesn't understand types for this
|
def clamp(n: T, smallest: T, largest: T) -> T:
|
||||||
"""Clamps the value of ``n`` to between ``smallest`` and ``largest``."""
|
"""Clamps the value of ``n`` to between ``smallest`` and ``largest``."""
|
||||||
return max(smallest, min(n, largest))
|
return max(smallest, min(n, largest))
|
||||||
|
|
||||||
|
|
||||||
def remove_all_log_handlers(logger):
|
def remove_all_log_handlers(logger: logging.Logger) -> None:
|
||||||
"Remove all log handlers, usually used in a child process."
|
"""Remove all log handlers, usually used in a child process.
|
||||||
|
|
||||||
|
The child process inherits the log handlers from the parent process when
|
||||||
|
a fork occurs. Typically we want to remove all log handlers in the child
|
||||||
|
process so that the child process can set up a single queue handler to
|
||||||
|
forward log messages to the parent process.
|
||||||
|
"""
|
||||||
for handler in logger.handlers[:]:
|
for handler in logger.handlers[:]:
|
||||||
logger.removeHandler(handler)
|
logger.removeHandler(handler)
|
||||||
handler.close() # To ensure handlers with opened resources are released
|
handler.close() # To ensure handlers with opened resources are released
|
||||||
|
|
||||||
|
|
||||||
def pikepdf_enable_mmap():
|
def pikepdf_enable_mmap() -> None:
|
||||||
# try:
|
"""Enable pikepdf memory mapping."""
|
||||||
# if pikepdf._qpdf.set_access_default_mmap(True):
|
try:
|
||||||
# log.debug("pikepdf mmap enabled")
|
pikepdf._core.set_access_default_mmap(True)
|
||||||
# except AttributeError:
|
log.debug(
|
||||||
# log.debug("pikepdf mmap not available")
|
"pikepdf mmap "
|
||||||
# We found a race condition probably related to pybind issue #2252 that can
|
+ (
|
||||||
# cause a crash. For now, disable pikepdf mmap to be on the safe side.
|
'enabled'
|
||||||
# Fix is not in pybind11 2.6.0
|
if pikepdf._core.get_access_default_mmap() # type: ignore[attr-defined]
|
||||||
# log.debug("pikepdf mmap disabled")
|
else 'disabled'
|
||||||
return
|
)
|
||||||
|
|
||||||
|
|
||||||
def deprecated(func):
|
|
||||||
"""Warn that function is deprecated."""
|
|
||||||
|
|
||||||
@wraps(func)
|
|
||||||
def new_func(*args, **kwargs):
|
|
||||||
warnings.simplefilter('always', DeprecationWarning) # turn off filter
|
|
||||||
warnings.warn(
|
|
||||||
f"Call to deprecated function {func.__name__}.",
|
|
||||||
category=DeprecationWarning,
|
|
||||||
stacklevel=2,
|
|
||||||
)
|
)
|
||||||
warnings.simplefilter('default', DeprecationWarning) # reset filter
|
except AttributeError:
|
||||||
return func(*args, **kwargs)
|
log.debug("pikepdf mmap not available")
|
||||||
|
|
||||||
return new_func
|
|
||||||
|
|||||||
@@ -1,481 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# SPDX-FileCopyrightText: 2010 Jonathan Brinley
|
|
||||||
# SPDX-FileCopyrightText: 2013-2014 Julien Pfefferkorn
|
|
||||||
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
|
||||||
# SPDX-License-Identifier: MIT
|
|
||||||
|
|
||||||
"""Transform .hocr and page image to text PDF."""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import argparse
|
|
||||||
import os
|
|
||||||
import re
|
|
||||||
import warnings
|
|
||||||
from math import atan, cos, sin
|
|
||||||
from pathlib import Path
|
|
||||||
from typing import Any, NamedTuple, Optional, Tuple, Union
|
|
||||||
from xml.etree import ElementTree
|
|
||||||
|
|
||||||
with warnings.catch_warnings():
|
|
||||||
warnings.filterwarnings(
|
|
||||||
'ignore', category=DeprecationWarning, message=r".*load_module.*"
|
|
||||||
)
|
|
||||||
from reportlab.lib.colors import black, cyan, magenta, red
|
|
||||||
from reportlab.lib.units import inch
|
|
||||||
from reportlab.pdfgen.canvas import Canvas
|
|
||||||
|
|
||||||
# According to Wikipedia these languages are supported in the ISO-8859-1 character
|
|
||||||
# set, meaning reportlab can generate them and they are compatible with hocr,
|
|
||||||
# assuming Tesseract has the necessary languages installed. Note that there may
|
|
||||||
# not be language packs for them.
|
|
||||||
HOCR_OK_LANGS = frozenset(
|
|
||||||
[
|
|
||||||
# Languages fully covered by Latin-1:
|
|
||||||
'afr', # Afrikaans
|
|
||||||
'alb', # Albanian
|
|
||||||
'ast', # Leonese
|
|
||||||
'baq', # Basque
|
|
||||||
'bre', # Breton
|
|
||||||
'cos', # Corsican
|
|
||||||
'eng', # English
|
|
||||||
'eus', # Basque
|
|
||||||
'fao', # Faoese
|
|
||||||
'gla', # Scottish Gaelic
|
|
||||||
'glg', # Galician
|
|
||||||
'glv', # Manx
|
|
||||||
'ice', # Icelandic
|
|
||||||
'ind', # Indonesian
|
|
||||||
'isl', # Icelandic
|
|
||||||
'ita', # Italian
|
|
||||||
'ltz', # Luxembourgish
|
|
||||||
'mal', # Malay Rumi
|
|
||||||
'mga', # Irish
|
|
||||||
'nor', # Norwegian
|
|
||||||
'oci', # Occitan
|
|
||||||
'por', # Portugeuse
|
|
||||||
'roh', # Romansh
|
|
||||||
'sco', # Scots
|
|
||||||
'sma', # Sami
|
|
||||||
'spa', # Spanish
|
|
||||||
'sqi', # Albanian
|
|
||||||
'swa', # Swahili
|
|
||||||
'swe', # Swedish
|
|
||||||
'tgl', # Tagalog
|
|
||||||
'wln', # Walloon
|
|
||||||
# Languages supported by Latin-1 except for a few rare characters that OCR
|
|
||||||
# is probably not trained to recognize anyway:
|
|
||||||
'cat', # Catalan
|
|
||||||
'cym', # Welsh
|
|
||||||
'dan', # Danish
|
|
||||||
'deu', # German
|
|
||||||
'dut', # Dutch
|
|
||||||
'est', # Estonian
|
|
||||||
'fin', # Finnish
|
|
||||||
'fra', # French
|
|
||||||
'hun', # Hungarian
|
|
||||||
'kur', # Kurdish
|
|
||||||
'nld', # Dutch
|
|
||||||
'wel', # Welsh
|
|
||||||
]
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
Element = ElementTree.Element
|
|
||||||
|
|
||||||
|
|
||||||
class Rect(NamedTuple):
|
|
||||||
"""A rectangle for managing PDF coordinates."""
|
|
||||||
|
|
||||||
x1: Any
|
|
||||||
y1: Any
|
|
||||||
x2: Any
|
|
||||||
y2: Any
|
|
||||||
|
|
||||||
|
|
||||||
class HocrTransformError(Exception):
|
|
||||||
"""Error while applying hOCR transform."""
|
|
||||||
|
|
||||||
|
|
||||||
class HocrTransform:
|
|
||||||
|
|
||||||
"""
|
|
||||||
A class for converting documents from the hOCR format.
|
|
||||||
For details of the hOCR format, see:
|
|
||||||
http://kba.cloud/hocr-spec/
|
|
||||||
"""
|
|
||||||
|
|
||||||
box_pattern = re.compile(r'bbox((\s+\d+){4})')
|
|
||||||
baseline_pattern = re.compile(
|
|
||||||
r'''
|
|
||||||
baseline \s+
|
|
||||||
([\-\+]?\d*\.?\d*) \s+ # +/- decimal float
|
|
||||||
([\-\+]?\d+) # +/- int''',
|
|
||||||
re.VERBOSE,
|
|
||||||
)
|
|
||||||
ligatures = str.maketrans(
|
|
||||||
{'ff': 'ff', 'ffi': 'ffi', 'ffl': 'ffl', 'fi': 'fi', 'fl': 'fl'}
|
|
||||||
)
|
|
||||||
|
|
||||||
def __init__(self, *, hocr_filename: str | Path, dpi: float):
|
|
||||||
self.dpi = dpi
|
|
||||||
self.hocr = ElementTree.parse(os.fspath(hocr_filename))
|
|
||||||
|
|
||||||
# if the hOCR file has a namespace, ElementTree requires its use to
|
|
||||||
# find elements
|
|
||||||
matches = re.match(r'({.*})html', self.hocr.getroot().tag)
|
|
||||||
self.xmlns = ''
|
|
||||||
if matches:
|
|
||||||
self.xmlns = matches.group(1)
|
|
||||||
|
|
||||||
# get dimension in pt (not pixel!!!!) of the OCRed image
|
|
||||||
self.width, self.height = None, None
|
|
||||||
for div in self.hocr.findall(self._child_xpath('div', 'ocr_page')):
|
|
||||||
coords = self.element_coordinates(div)
|
|
||||||
pt_coords = self.pt_from_pixel(coords)
|
|
||||||
self.width = pt_coords.x2 - pt_coords.x1
|
|
||||||
self.height = pt_coords.y2 - pt_coords.y1
|
|
||||||
# there shouldn't be more than one, and if there is, we don't want
|
|
||||||
# it
|
|
||||||
break
|
|
||||||
if self.width is None or self.height is None:
|
|
||||||
raise HocrTransformError("hocr file is missing page dimensions")
|
|
||||||
|
|
||||||
def __str__(self): # pragma: no cover
|
|
||||||
"""
|
|
||||||
Return the textual content of the HTML body
|
|
||||||
"""
|
|
||||||
if self.hocr is None:
|
|
||||||
return ''
|
|
||||||
body = self.hocr.find(self._child_xpath('body'))
|
|
||||||
if body:
|
|
||||||
return self._get_element_text(body)
|
|
||||||
else:
|
|
||||||
return ''
|
|
||||||
|
|
||||||
def _get_element_text(self, element: Element):
|
|
||||||
"""
|
|
||||||
Return the textual content of the element and its children
|
|
||||||
"""
|
|
||||||
text = ''
|
|
||||||
if element.text is not None:
|
|
||||||
text += element.text
|
|
||||||
for child in element:
|
|
||||||
text += self._get_element_text(child)
|
|
||||||
if element.tail is not None:
|
|
||||||
text += element.tail
|
|
||||||
return text
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def element_coordinates(cls, element: Element) -> Rect:
|
|
||||||
"""
|
|
||||||
Returns a tuple containing the coordinates of the bounding box around
|
|
||||||
an element
|
|
||||||
"""
|
|
||||||
out = Rect._make(0 for _ in range(4))
|
|
||||||
if 'title' in element.attrib:
|
|
||||||
matches = cls.box_pattern.search(element.attrib['title'])
|
|
||||||
if matches:
|
|
||||||
coords = matches.group(1).split()
|
|
||||||
out = Rect._make(int(coords[n]) for n in range(4))
|
|
||||||
return out
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def baseline(cls, element: Element) -> tuple[float, float]:
|
|
||||||
"""
|
|
||||||
Returns a tuple containing the baseline slope and intercept.
|
|
||||||
"""
|
|
||||||
if 'title' in element.attrib:
|
|
||||||
matches = cls.baseline_pattern.search(element.attrib['title'])
|
|
||||||
if matches:
|
|
||||||
return float(matches.group(1)), int(matches.group(2))
|
|
||||||
return (0.0, 0.0)
|
|
||||||
|
|
||||||
def pt_from_pixel(self, pxl) -> Rect:
|
|
||||||
"""
|
|
||||||
Returns the quantity in PDF units (pt) given quantity in pixels
|
|
||||||
"""
|
|
||||||
return Rect._make((c / self.dpi * inch) for c in pxl)
|
|
||||||
|
|
||||||
def _child_xpath(self, html_tag: str, html_class: str | None = None) -> str:
|
|
||||||
xpath = f".//{self.xmlns}{html_tag}"
|
|
||||||
if html_class:
|
|
||||||
xpath += f"[@class='{html_class}']"
|
|
||||||
return xpath
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def replace_unsupported_chars(cls, s: str) -> str:
|
|
||||||
"""
|
|
||||||
Given an input string, returns the corresponding string that:
|
|
||||||
* is available in the Helvetica facetype
|
|
||||||
* does not contain any ligature (to allow easy search in the PDF file)
|
|
||||||
"""
|
|
||||||
return s.translate(cls.ligatures)
|
|
||||||
|
|
||||||
def topdown_position(self, element):
|
|
||||||
pxl_line_coords = self.element_coordinates(element)
|
|
||||||
line_box = self.pt_from_pixel(pxl_line_coords)
|
|
||||||
# Coordinates here are still in the hocr coordinate system, so 0 on the y axis
|
|
||||||
# is the top of the page and increasing values of y will move towards the
|
|
||||||
# bottom of the page.
|
|
||||||
return line_box.y2
|
|
||||||
|
|
||||||
def to_pdf(
|
|
||||||
self,
|
|
||||||
*,
|
|
||||||
out_filename: Path,
|
|
||||||
image_filename: Path | None = None,
|
|
||||||
show_bounding_boxes: bool = False,
|
|
||||||
fontname: str = "Helvetica",
|
|
||||||
invisible_text: bool = False,
|
|
||||||
interword_spaces: bool = False,
|
|
||||||
) -> None:
|
|
||||||
"""
|
|
||||||
Creates a PDF file with an image superimposed on top of the text.
|
|
||||||
Text is positioned according to the bounding box of the lines in
|
|
||||||
the hOCR file.
|
|
||||||
The image need not be identical to the image used to create the hOCR
|
|
||||||
file.
|
|
||||||
It can have a lower resolution, different color mode, etc.
|
|
||||||
|
|
||||||
Arguments:
|
|
||||||
out_filename: Path of PDF to write.
|
|
||||||
image_filename: Image to use for this file. If omitted, the OCR text
|
|
||||||
is shown.
|
|
||||||
show_bounding_boxes: Show bounding boxes around various text regions,
|
|
||||||
for debugging.
|
|
||||||
fontname: Name of font to use.
|
|
||||||
invisible_text: If True, text is rendered invisible so that is
|
|
||||||
selectable but never drawn. If False, text is visible and may
|
|
||||||
be seen if the image is skipped or deleted in Acrobat.
|
|
||||||
interword_spaces: If True, insert spaces between words rather than
|
|
||||||
drawing each word without spaces. Generally this improves text
|
|
||||||
extraction.
|
|
||||||
"""
|
|
||||||
# create the PDF file
|
|
||||||
# page size in points (1/72 in.)
|
|
||||||
pdf = Canvas(
|
|
||||||
os.fspath(out_filename),
|
|
||||||
pagesize=(self.width, self.height),
|
|
||||||
pageCompression=1,
|
|
||||||
)
|
|
||||||
|
|
||||||
# draw bounding box for each paragraph
|
|
||||||
# light blue for bounding box of paragraph
|
|
||||||
pdf.setStrokeColor(cyan)
|
|
||||||
# light blue for bounding box of paragraph
|
|
||||||
pdf.setFillColor(cyan)
|
|
||||||
pdf.setLineWidth(0) # no line for bounding box
|
|
||||||
for elem in self.hocr.iterfind(self._child_xpath('p', 'ocr_par')):
|
|
||||||
elemtxt = self._get_element_text(elem).rstrip()
|
|
||||||
if len(elemtxt) == 0:
|
|
||||||
continue
|
|
||||||
|
|
||||||
pxl_coords = self.element_coordinates(elem)
|
|
||||||
pt = self.pt_from_pixel(pxl_coords) # pylint: disable=invalid-name
|
|
||||||
|
|
||||||
# draw the bbox border
|
|
||||||
if show_bounding_boxes: # pragma: no cover
|
|
||||||
pdf.rect(
|
|
||||||
pt.x1, self.height - pt.y2, pt.x2 - pt.x1, pt.y2 - pt.y1, fill=1
|
|
||||||
)
|
|
||||||
|
|
||||||
found_lines = False
|
|
||||||
for line in (
|
|
||||||
element
|
|
||||||
for element in self.hocr.iterfind(self._child_xpath('span'))
|
|
||||||
if 'class' in element.attrib
|
|
||||||
and element.attrib['class'] in {'ocr_header', 'ocr_line', 'ocr_textfloat'}
|
|
||||||
):
|
|
||||||
found_lines = True
|
|
||||||
self._do_line(
|
|
||||||
pdf,
|
|
||||||
line,
|
|
||||||
"ocrx_word",
|
|
||||||
fontname,
|
|
||||||
invisible_text,
|
|
||||||
interword_spaces,
|
|
||||||
show_bounding_boxes,
|
|
||||||
)
|
|
||||||
|
|
||||||
if not found_lines:
|
|
||||||
# Tesseract did not report any lines (just words)
|
|
||||||
root = self.hocr.find(self._child_xpath('div', 'ocr_page'))
|
|
||||||
self._do_line(
|
|
||||||
pdf,
|
|
||||||
root,
|
|
||||||
"ocrx_word",
|
|
||||||
fontname,
|
|
||||||
invisible_text,
|
|
||||||
interword_spaces,
|
|
||||||
show_bounding_boxes,
|
|
||||||
)
|
|
||||||
# put the image on the page, scaled to fill the page
|
|
||||||
if image_filename is not None:
|
|
||||||
pdf.drawImage(
|
|
||||||
os.fspath(image_filename), 0, 0, width=self.width, height=self.height
|
|
||||||
)
|
|
||||||
|
|
||||||
# finish up the page and save it
|
|
||||||
pdf.showPage()
|
|
||||||
pdf.save()
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def polyval(cls, poly, x): # pragma: no cover
|
|
||||||
return x * poly[0] + poly[1]
|
|
||||||
|
|
||||||
def _do_line(
|
|
||||||
self,
|
|
||||||
pdf: Canvas,
|
|
||||||
line: Element | None,
|
|
||||||
elemclass: str,
|
|
||||||
fontname: str,
|
|
||||||
invisible_text: bool,
|
|
||||||
interword_spaces: bool,
|
|
||||||
show_bounding_boxes: bool,
|
|
||||||
):
|
|
||||||
if line is None:
|
|
||||||
return
|
|
||||||
pxl_line_coords = self.element_coordinates(line)
|
|
||||||
line_box = self.pt_from_pixel(pxl_line_coords)
|
|
||||||
line_height = line_box.y2 - line_box.y1
|
|
||||||
|
|
||||||
slope, pxl_intercept = self.baseline(line)
|
|
||||||
if abs(slope) < 0.005:
|
|
||||||
slope = 0.0
|
|
||||||
angle = atan(slope)
|
|
||||||
cos_a, sin_a = cos(angle), sin(angle)
|
|
||||||
|
|
||||||
text = pdf.beginText()
|
|
||||||
intercept = pxl_intercept / self.dpi * inch
|
|
||||||
|
|
||||||
# Don't allow the font to break out of the bounding box. Division by
|
|
||||||
# cos_a accounts for extra clearance between the glyph's vertical axis
|
|
||||||
# on a sloped baseline and the edge of the bounding box.
|
|
||||||
fontsize = (line_height - abs(intercept)) / cos_a
|
|
||||||
text.setFont(fontname, fontsize)
|
|
||||||
if invisible_text:
|
|
||||||
text.setTextRenderMode(3) # Invisible (indicates OCR text)
|
|
||||||
|
|
||||||
# Intercept is normally negative, so this places it above the bottom
|
|
||||||
# of the line box
|
|
||||||
baseline_y2 = self.height - (line_box.y2 + intercept)
|
|
||||||
|
|
||||||
if show_bounding_boxes: # pragma: no cover
|
|
||||||
# draw the baseline in magenta, dashed
|
|
||||||
pdf.setDash()
|
|
||||||
pdf.setStrokeColor(magenta)
|
|
||||||
pdf.setLineWidth(0.5)
|
|
||||||
# negate slope because it is defined as a rise/run in pixel
|
|
||||||
# coordinates and page coordinates have the y axis flipped
|
|
||||||
pdf.line(
|
|
||||||
line_box.x1,
|
|
||||||
baseline_y2,
|
|
||||||
line_box.x2,
|
|
||||||
self.polyval((-slope, baseline_y2), line_box.x2 - line_box.x1),
|
|
||||||
)
|
|
||||||
# light green for bounding box of word/line
|
|
||||||
pdf.setDash(6, 3)
|
|
||||||
pdf.setStrokeColor(red)
|
|
||||||
|
|
||||||
text.setTextTransform(cos_a, -sin_a, sin_a, cos_a, line_box.x1, baseline_y2)
|
|
||||||
pdf.setFillColor(black) # text in black
|
|
||||||
|
|
||||||
elements = line.findall(self._child_xpath('span', elemclass))
|
|
||||||
for elem in elements:
|
|
||||||
elemtxt = self._get_element_text(elem).strip()
|
|
||||||
elemtxt = self.replace_unsupported_chars(elemtxt)
|
|
||||||
if elemtxt == '':
|
|
||||||
continue
|
|
||||||
|
|
||||||
pxl_coords = self.element_coordinates(elem)
|
|
||||||
box = self.pt_from_pixel(pxl_coords)
|
|
||||||
if interword_spaces:
|
|
||||||
# if `--interword-spaces` is true, append a space
|
|
||||||
# to the end of each text element to allow simpler PDF viewers
|
|
||||||
# such as PDF.js to better recognize words in search and copy
|
|
||||||
# and paste. Do not remove space from last word in line, even
|
|
||||||
# though it would look better, because it will interfere with
|
|
||||||
# naive text extraction. \n does not work either.
|
|
||||||
elemtxt += ' '
|
|
||||||
box = Rect._make(
|
|
||||||
(
|
|
||||||
box.x1,
|
|
||||||
line_box.y1,
|
|
||||||
box.x2 + pdf.stringWidth(' ', fontname, line_height),
|
|
||||||
line_box.y2,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
box_width = box.x2 - box.x1
|
|
||||||
font_width = pdf.stringWidth(elemtxt, fontname, fontsize)
|
|
||||||
|
|
||||||
# draw the bbox border
|
|
||||||
if show_bounding_boxes: # pragma: no cover
|
|
||||||
pdf.rect(
|
|
||||||
box.x1, self.height - line_box.y2, box_width, line_height, fill=0
|
|
||||||
)
|
|
||||||
|
|
||||||
# Adjust relative position of cursor
|
|
||||||
# This is equivalent to:
|
|
||||||
# text.setTextOrigin(pt.x1, self.height - line_box.y2)
|
|
||||||
# but the former generates a full text reposition matrix (Tm) in the
|
|
||||||
# content stream while this issues a "offset" (Td) command.
|
|
||||||
# .moveCursor() is relative to start of the text line, where the
|
|
||||||
# "text line" means whatever reportlab defines it as. Do not use
|
|
||||||
# use .getCursor(), since moveCursor() rather unintuitively plans
|
|
||||||
# its moves relative to .getStartOfLine().
|
|
||||||
# For skewed lines, in the text transform we set up a rotated
|
|
||||||
# coordinate system, so we don't have to account for the
|
|
||||||
# incremental offset. Surprisingly most PDF viewers can handle this.
|
|
||||||
cursor = text.getStartOfLine()
|
|
||||||
dx = box.x1 - cursor[0]
|
|
||||||
dy = baseline_y2 - cursor[1]
|
|
||||||
text.moveCursor(dx, dy)
|
|
||||||
|
|
||||||
# If reportlab tells us this word is 0 units wide, our best seems
|
|
||||||
# to be to suppress this text
|
|
||||||
if font_width > 0:
|
|
||||||
text.setHorizScale(100 * box_width / font_width)
|
|
||||||
text.textOut(elemtxt)
|
|
||||||
pdf.drawText(text)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
parser = argparse.ArgumentParser(description='Convert hocr file to PDF')
|
|
||||||
parser.add_argument(
|
|
||||||
'-b',
|
|
||||||
'--boundingboxes',
|
|
||||||
action="store_true",
|
|
||||||
default=False,
|
|
||||||
help='Show bounding boxes borders',
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
'-r',
|
|
||||||
'--resolution',
|
|
||||||
type=int,
|
|
||||||
default=300,
|
|
||||||
help='Resolution of the image that was OCRed',
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
'-i',
|
|
||||||
'--image',
|
|
||||||
default=None,
|
|
||||||
help='Path to the image to be placed above the text',
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
'--interword-spaces',
|
|
||||||
action='store_true',
|
|
||||||
default=False,
|
|
||||||
help='Add spaces between words',
|
|
||||||
)
|
|
||||||
parser.add_argument('hocrfile', help='Path to the hocr file to be parsed')
|
|
||||||
parser.add_argument('outputfile', help='Path to the PDF file to be generated')
|
|
||||||
args = parser.parse_args()
|
|
||||||
|
|
||||||
hocr = HocrTransform(hocr_filename=args.hocrfile, dpi=args.resolution)
|
|
||||||
hocr.to_pdf(
|
|
||||||
out_filename=args.outputfile,
|
|
||||||
image_filename=args.image,
|
|
||||||
show_bounding_boxes=args.boundingboxes,
|
|
||||||
interword_spaces=args.interword_spaces,
|
|
||||||
)
|
|
||||||
Executable
+18
@@ -0,0 +1,18 @@
|
|||||||
|
# SPDX-FileCopyrightText: 2023 James R. Barlow
|
||||||
|
# SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
"""Transform .hocr and page image to text PDF."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from ocrmypdf.hocrtransform._hocr import (
|
||||||
|
DebugRenderOptions,
|
||||||
|
HocrTransform,
|
||||||
|
HocrTransformError,
|
||||||
|
)
|
||||||
|
|
||||||
|
__all__ = (
|
||||||
|
'HocrTransform',
|
||||||
|
'HocrTransformError',
|
||||||
|
'DebugRenderOptions',
|
||||||
|
)
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
# SPDX-FileCopyrightText: 2023 James R. Barlow
|
||||||
|
# SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
"""Simple CLI for testing HOCR."""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
|
||||||
|
from ocrmypdf.hocrtransform import HocrTransform
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
parser = argparse.ArgumentParser(description='Convert hocr file to PDF')
|
||||||
|
parser.add_argument(
|
||||||
|
'-b',
|
||||||
|
'--boundingboxes',
|
||||||
|
action="store_true",
|
||||||
|
default=False,
|
||||||
|
help='Show bounding boxes borders',
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
'-r',
|
||||||
|
'--resolution',
|
||||||
|
type=int,
|
||||||
|
default=300,
|
||||||
|
help='Resolution of the image that was OCRed',
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
'-i',
|
||||||
|
'--image',
|
||||||
|
default=None,
|
||||||
|
help='Path to the image to be placed above the text',
|
||||||
|
)
|
||||||
|
parser.add_argument('hocrfile', help='Path to the hocr file to be parsed')
|
||||||
|
parser.add_argument('outputfile', help='Path to the PDF file to be generated')
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
hocr = HocrTransform(hocr_filename=args.hocrfile, dpi=args.resolution)
|
||||||
|
hocr.to_pdf(
|
||||||
|
out_filename=args.outputfile,
|
||||||
|
image_filename=args.image,
|
||||||
|
)
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
# SPDX-FileCopyrightText: 2023 James R. Barlow
|
||||||
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import unicodedata
|
||||||
|
import zlib
|
||||||
|
from importlib.resources import files as package_files
|
||||||
|
|
||||||
|
from pikepdf import (
|
||||||
|
Dictionary,
|
||||||
|
Name,
|
||||||
|
Pdf,
|
||||||
|
)
|
||||||
|
from pikepdf.canvas import Font
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class GlyphlessFont(Font):
|
||||||
|
CID_TO_GID_DATA = zlib.compress(b"\x00\x01" * 65536)
|
||||||
|
GLYPHLESS_FONT_NAME = 'pdf.ttf'
|
||||||
|
GLYPHLESS_FONT = (package_files('ocrmypdf.data') / GLYPHLESS_FONT_NAME).read_bytes()
|
||||||
|
CHAR_ASPECT = 2
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def text_width(self, text: str, fontsize: float) -> int:
|
||||||
|
"""Estimate the width of a text string when rendered with the given font."""
|
||||||
|
# NFKC: split ligatures, combine diacritics
|
||||||
|
return len(unicodedata.normalize("NFKC", text)) * (fontsize / self.CHAR_ASPECT)
|
||||||
|
|
||||||
|
def register(self, pdf: Pdf):
|
||||||
|
"""Register the glyphless font.
|
||||||
|
|
||||||
|
Create several data structures in the Pdf to describe the font. While it create
|
||||||
|
the data, a reference should be set in at least one page's /Resources dictionary
|
||||||
|
to retain the font in the output PDF and ensure it is usable on that page.
|
||||||
|
"""
|
||||||
|
PLACEHOLDER = Name.Placeholder
|
||||||
|
|
||||||
|
basefont = pdf.make_indirect(
|
||||||
|
Dictionary(
|
||||||
|
BaseFont=Name.GlyphLessFont,
|
||||||
|
DescendantFonts=[PLACEHOLDER],
|
||||||
|
Encoding=Name("/Identity-H"),
|
||||||
|
Subtype=Name.Type0,
|
||||||
|
ToUnicode=PLACEHOLDER,
|
||||||
|
Type=Name.Font,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
cid_font_type2 = pdf.make_indirect(
|
||||||
|
Dictionary(
|
||||||
|
BaseFont=Name.GlyphLessFont,
|
||||||
|
CIDToGIDMap=PLACEHOLDER,
|
||||||
|
CIDSystemInfo=Dictionary(
|
||||||
|
Ordering="Identity",
|
||||||
|
Registry="Adobe",
|
||||||
|
Supplement=0,
|
||||||
|
),
|
||||||
|
FontDescriptor=PLACEHOLDER,
|
||||||
|
Subtype=Name.CIDFontType2,
|
||||||
|
Type=Name.Font,
|
||||||
|
DW=1000 // self.CHAR_ASPECT,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
basefont.DescendantFonts = [cid_font_type2]
|
||||||
|
cid_font_type2.CIDToGIDMap = pdf.make_stream(
|
||||||
|
self.CID_TO_GID_DATA, Filter=Name.FlateDecode
|
||||||
|
)
|
||||||
|
basefont.ToUnicode = pdf.make_stream(
|
||||||
|
b"/CIDInit /ProcSet findresource begin\n"
|
||||||
|
b"12 dict begin\n"
|
||||||
|
b"begincmap\n"
|
||||||
|
b"/CIDSystemInfo\n"
|
||||||
|
b"<<\n"
|
||||||
|
b" /Registry (Adobe)\n"
|
||||||
|
b" /Ordering (UCS)\n"
|
||||||
|
b" /Supplement 0\n"
|
||||||
|
b">> def\n"
|
||||||
|
b"/CMapName /Adobe-Identify-UCS def\n"
|
||||||
|
b"/CMapType 2 def\n"
|
||||||
|
b"1 begincodespacerange\n"
|
||||||
|
b"<0000> <FFFF>\n"
|
||||||
|
b"endcodespacerange\n"
|
||||||
|
b"1 beginbfrange\n"
|
||||||
|
b"<0000> <FFFF> <0000>\n"
|
||||||
|
b"endbfrange\n"
|
||||||
|
b"endcmap\n"
|
||||||
|
b"CMapName currentdict /CMap defineresource pop\n"
|
||||||
|
b"end\n"
|
||||||
|
b"end\n"
|
||||||
|
)
|
||||||
|
font_descriptor = pdf.make_indirect(
|
||||||
|
Dictionary(
|
||||||
|
Ascent=1000,
|
||||||
|
CapHeight=1000,
|
||||||
|
Descent=-1,
|
||||||
|
Flags=5, # Fixed pitch and symbolic
|
||||||
|
FontBBox=[0, 0, 1000 // self.CHAR_ASPECT, 1000],
|
||||||
|
FontFile2=PLACEHOLDER,
|
||||||
|
FontName=Name.GlyphLessFont,
|
||||||
|
ItalicAngle=0,
|
||||||
|
StemV=80,
|
||||||
|
Type=Name.FontDescriptor,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
font_descriptor.FontFile2 = pdf.make_stream(self.GLYPHLESS_FONT)
|
||||||
|
cid_font_type2.FontDescriptor = font_descriptor
|
||||||
|
return basefont
|
||||||
@@ -0,0 +1,473 @@
|
|||||||
|
# SPDX-FileCopyrightText: 2010 Jonathan Brinley
|
||||||
|
# SPDX-FileCopyrightText: 2013-2014 Julien Pfefferkorn
|
||||||
|
# SPDX-FileCopyrightText: 2023 James R. Barlow
|
||||||
|
# SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
"""hOCR transform implementation."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import unicodedata
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from itertools import pairwise
|
||||||
|
from math import atan, cos, pi
|
||||||
|
from pathlib import Path
|
||||||
|
from xml.etree import ElementTree
|
||||||
|
|
||||||
|
from pikepdf import Matrix, Name, Rectangle
|
||||||
|
from pikepdf.canvas import (
|
||||||
|
BLACK,
|
||||||
|
BLUE,
|
||||||
|
CYAN,
|
||||||
|
DARKGREEN,
|
||||||
|
GREEN,
|
||||||
|
MAGENTA,
|
||||||
|
RED,
|
||||||
|
Canvas,
|
||||||
|
Font,
|
||||||
|
Text,
|
||||||
|
TextDirection,
|
||||||
|
)
|
||||||
|
|
||||||
|
from ocrmypdf.hocrtransform._font import GlyphlessFont
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
INCH = 72.0
|
||||||
|
|
||||||
|
Element = ElementTree.Element
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class DebugRenderOptions:
|
||||||
|
"""A class for managing rendering options."""
|
||||||
|
|
||||||
|
render_paragraph_bbox: bool
|
||||||
|
render_baseline: bool
|
||||||
|
render_triangle: bool
|
||||||
|
render_line_bbox: bool
|
||||||
|
render_word_bbox: bool
|
||||||
|
render_space_bbox: bool
|
||||||
|
|
||||||
|
|
||||||
|
class HocrTransformError(Exception):
|
||||||
|
"""Error while applying hOCR transform."""
|
||||||
|
|
||||||
|
|
||||||
|
class HocrTransform:
|
||||||
|
"""A class for converting documents from the hOCR format.
|
||||||
|
|
||||||
|
For details of the hOCR format, see:
|
||||||
|
http://kba.cloud/hocr-spec/.
|
||||||
|
"""
|
||||||
|
|
||||||
|
box_pattern = re.compile(r'bbox (\d+) (\d+) (\d+) (\d+)')
|
||||||
|
baseline_pattern = re.compile(
|
||||||
|
r'''
|
||||||
|
baseline \s+
|
||||||
|
([\-\+]?\d*\.?\d*) \s+ # +/- decimal float
|
||||||
|
([\-\+]?\d+) # +/- int''',
|
||||||
|
re.VERBOSE,
|
||||||
|
)
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
hocr_filename: str | Path,
|
||||||
|
dpi: float,
|
||||||
|
debug: bool = False,
|
||||||
|
fontname: Name = Name("/f-0-0"),
|
||||||
|
font: Font = GlyphlessFont(),
|
||||||
|
):
|
||||||
|
"""Initialize the HocrTransform object."""
|
||||||
|
self.dpi = dpi
|
||||||
|
self.hocr = ElementTree.parse(os.fspath(hocr_filename))
|
||||||
|
self._fontname = fontname
|
||||||
|
self._font = font
|
||||||
|
|
||||||
|
# if the hOCR file has a namespace, ElementTree requires its use to
|
||||||
|
# find elements
|
||||||
|
matches = re.match(r'({.*})html', self.hocr.getroot().tag)
|
||||||
|
self.xmlns = ''
|
||||||
|
if matches:
|
||||||
|
self.xmlns = matches.group(1)
|
||||||
|
|
||||||
|
for div in self.hocr.findall(self._child_xpath('div', 'ocr_page')):
|
||||||
|
coords = self.element_coordinates(div)
|
||||||
|
if not coords:
|
||||||
|
raise HocrTransformError("hocr file is missing page dimensions")
|
||||||
|
self.width = (coords.urx - coords.llx) / (self.dpi / INCH)
|
||||||
|
self.height = (coords.ury - coords.lly) / (self.dpi / INCH)
|
||||||
|
# Stop after first div that has page coordinates
|
||||||
|
break
|
||||||
|
self.render_options = DebugRenderOptions(
|
||||||
|
render_baseline=debug,
|
||||||
|
render_triangle=debug,
|
||||||
|
render_line_bbox=False,
|
||||||
|
render_word_bbox=debug,
|
||||||
|
render_paragraph_bbox=False,
|
||||||
|
render_space_bbox=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
def _get_element_text(self, element: Element):
|
||||||
|
"""Return the textual content of the element and its children."""
|
||||||
|
text = ''
|
||||||
|
if element.text is not None:
|
||||||
|
text += element.text
|
||||||
|
for child in element:
|
||||||
|
text += self._get_element_text(child)
|
||||||
|
if element.tail is not None:
|
||||||
|
text += element.tail
|
||||||
|
return text
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def element_coordinates(cls, element: Element) -> Rectangle | None:
|
||||||
|
"""Get coordinates of the bounding box around an element."""
|
||||||
|
matches = cls.box_pattern.search(element.attrib.get('title', ''))
|
||||||
|
if not matches:
|
||||||
|
return None
|
||||||
|
return Rectangle(
|
||||||
|
float(matches.group(1)), # llx = left
|
||||||
|
float(matches.group(2)), # lly = top
|
||||||
|
float(matches.group(3)), # urx = right
|
||||||
|
float(matches.group(4)), # ury = bottom
|
||||||
|
)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def baseline(cls, element: Element) -> tuple[float, float]:
|
||||||
|
"""Get baseline's slope and intercept."""
|
||||||
|
matches = cls.baseline_pattern.search(element.attrib.get('title', ''))
|
||||||
|
if not matches:
|
||||||
|
return (0.0, 0.0)
|
||||||
|
return float(matches.group(1)), int(matches.group(2))
|
||||||
|
|
||||||
|
def _child_xpath(self, html_tag: str, html_class: str | None = None) -> str:
|
||||||
|
xpath = f".//{self.xmlns}{html_tag}"
|
||||||
|
if html_class:
|
||||||
|
xpath += f"[@class='{html_class}']"
|
||||||
|
return xpath
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def normalize_text(cls, s: str) -> str:
|
||||||
|
"""Normalize the given text using the NFKC normalization form."""
|
||||||
|
return unicodedata.normalize("NFKC", s)
|
||||||
|
|
||||||
|
def to_pdf(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
out_filename: Path,
|
||||||
|
image_filename: Path | None = None,
|
||||||
|
invisible_text: bool = True,
|
||||||
|
) -> None:
|
||||||
|
"""Creates a PDF file with an image superimposed on top of the text.
|
||||||
|
|
||||||
|
Text is positioned according to the bounding box of the lines in
|
||||||
|
the hOCR file.
|
||||||
|
The image need not be identical to the image used to create the hOCR
|
||||||
|
file.
|
||||||
|
It can have a lower resolution, different color mode, etc.
|
||||||
|
|
||||||
|
Arguments:
|
||||||
|
out_filename: Path of PDF to write.
|
||||||
|
image_filename: Image to use for this file. If omitted, the OCR text
|
||||||
|
is shown.
|
||||||
|
invisible_text: If True, text is rendered invisible so that is
|
||||||
|
selectable but never drawn. If False, text is visible and may
|
||||||
|
be seen if the image is skipped or deleted in Acrobat.
|
||||||
|
"""
|
||||||
|
# create the PDF file
|
||||||
|
# page size in points (1/72 in.)
|
||||||
|
canvas = Canvas(page_size=(self.width, self.height))
|
||||||
|
canvas.add_font(self._fontname, self._font)
|
||||||
|
page_matrix = (
|
||||||
|
Matrix()
|
||||||
|
.translated(0, self.height)
|
||||||
|
.scaled(1, -1)
|
||||||
|
.scaled(INCH / self.dpi, INCH / self.dpi)
|
||||||
|
)
|
||||||
|
log.debug(page_matrix)
|
||||||
|
with canvas.do.save_state(cm=page_matrix):
|
||||||
|
self._debug_draw_paragraph_boxes(canvas)
|
||||||
|
found_lines = False
|
||||||
|
for par in self.hocr.iterfind(self._child_xpath('p', 'ocr_par')):
|
||||||
|
for line in (
|
||||||
|
element
|
||||||
|
for element in par.iterfind(self._child_xpath('span'))
|
||||||
|
if 'class' in element.attrib
|
||||||
|
and element.attrib['class']
|
||||||
|
in {'ocr_header', 'ocr_line', 'ocr_textfloat'}
|
||||||
|
):
|
||||||
|
found_lines = True
|
||||||
|
direction = self._get_text_direction(par)
|
||||||
|
inject_word_breaks = self._get_inject_word_breaks(par)
|
||||||
|
self._do_line(
|
||||||
|
canvas,
|
||||||
|
line,
|
||||||
|
"ocrx_word",
|
||||||
|
invisible_text,
|
||||||
|
direction,
|
||||||
|
inject_word_breaks,
|
||||||
|
)
|
||||||
|
|
||||||
|
if not found_lines:
|
||||||
|
# Tesseract did not report any lines (just words)
|
||||||
|
root = self.hocr.find(self._child_xpath('div', 'ocr_page'))
|
||||||
|
self._do_line(
|
||||||
|
canvas,
|
||||||
|
root,
|
||||||
|
"ocrx_word",
|
||||||
|
invisible_text,
|
||||||
|
TextDirection.LTR,
|
||||||
|
True,
|
||||||
|
)
|
||||||
|
# put the image on the page, scaled to fill the page
|
||||||
|
if image_filename is not None:
|
||||||
|
canvas.do.draw_image(
|
||||||
|
image_filename, 0, 0, width=self.width, height=self.height
|
||||||
|
)
|
||||||
|
|
||||||
|
# finish up the page and save it
|
||||||
|
canvas.to_pdf().save(out_filename)
|
||||||
|
|
||||||
|
def _get_text_direction(self, par):
|
||||||
|
"""Get the text direction of the paragraph.
|
||||||
|
|
||||||
|
Arabic, Hebrew, Persian, are right-to-left languages.
|
||||||
|
"""
|
||||||
|
return (
|
||||||
|
TextDirection.RTL
|
||||||
|
if par.attrib.get('dir', 'ltr') == 'rtl'
|
||||||
|
else TextDirection.LTR
|
||||||
|
)
|
||||||
|
|
||||||
|
def _get_inject_word_breaks(self, par):
|
||||||
|
"""Determine whether word breaks should be injected.
|
||||||
|
|
||||||
|
In Chinese, Japanese, and Korean, word breaks are not injected, because
|
||||||
|
words are usually one or two characters and separators are usually explicit.
|
||||||
|
In all other languages, we inject word breaks to help word segmentation.
|
||||||
|
"""
|
||||||
|
lang = par.attrib.get('lang', '')
|
||||||
|
log.debug(lang)
|
||||||
|
if lang in {'chi_sim', 'chi_tra', 'jpn', 'kor'}:
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def polyval(cls, poly, x): # pragma: no cover
|
||||||
|
"""Calculate the value of a polynomial at a point."""
|
||||||
|
return x * poly[0] + poly[1]
|
||||||
|
|
||||||
|
def _do_line(
|
||||||
|
self,
|
||||||
|
canvas: Canvas,
|
||||||
|
line: Element | None,
|
||||||
|
elemclass: str,
|
||||||
|
invisible_text: bool,
|
||||||
|
text_direction: TextDirection,
|
||||||
|
inject_word_breaks: bool,
|
||||||
|
):
|
||||||
|
"""Render the text for a given line.
|
||||||
|
|
||||||
|
The canvas's coordinate system must be configured so that hOCR pixel
|
||||||
|
coordinates are mapped to PDF coordinates.
|
||||||
|
"""
|
||||||
|
if line is None:
|
||||||
|
return
|
||||||
|
line_box = self.element_coordinates(line)
|
||||||
|
if not line_box:
|
||||||
|
return
|
||||||
|
assert line_box.ury > line_box.lly # lly is top, ury is bottom
|
||||||
|
|
||||||
|
self._debug_draw_line_bbox(canvas, line_box)
|
||||||
|
|
||||||
|
# Baseline is a polynomial (usually straight line) that describes the
|
||||||
|
# text baseline relative to the bottom left corner of the line bounding
|
||||||
|
# box.
|
||||||
|
bottom_left_corner = line_box.llx, line_box.ury
|
||||||
|
slope, intercept = self.baseline(line)
|
||||||
|
if abs(slope) < 0.005:
|
||||||
|
slope = 0.0
|
||||||
|
angle = atan(slope)
|
||||||
|
|
||||||
|
# Setup a new coordinate system on the line box's intercept and rotated by
|
||||||
|
# its slope.
|
||||||
|
line_matrix = (
|
||||||
|
Matrix()
|
||||||
|
.translated(*bottom_left_corner)
|
||||||
|
.translated(0, intercept)
|
||||||
|
.rotated(angle / pi * 180)
|
||||||
|
)
|
||||||
|
log.debug(line_matrix)
|
||||||
|
with canvas.do.save_state(cm=line_matrix):
|
||||||
|
text = Text(direction=text_direction)
|
||||||
|
|
||||||
|
# Don't allow the font to break out of the bounding box. Division by
|
||||||
|
# cos_a accounts for extra clearance between the glyph's vertical axis
|
||||||
|
# on a sloped baseline and the edge of the bounding box.
|
||||||
|
line_box_height = abs(line_box.height) / cos(angle)
|
||||||
|
fontsize = line_box_height + intercept
|
||||||
|
text.font(self._fontname, fontsize)
|
||||||
|
if invisible_text or True:
|
||||||
|
text.render_mode(3) # Invisible (indicates OCR text)
|
||||||
|
|
||||||
|
self._debug_draw_baseline(
|
||||||
|
canvas, line_matrix.inverse().transform(line_box), 0
|
||||||
|
)
|
||||||
|
|
||||||
|
canvas.do.fill_color(BLACK) # text in black
|
||||||
|
elements = line.findall(self._child_xpath('span', elemclass))
|
||||||
|
for elem, next_elem in pairwise(elements + [None]):
|
||||||
|
self._do_line_word(
|
||||||
|
canvas,
|
||||||
|
line_matrix,
|
||||||
|
text,
|
||||||
|
fontsize,
|
||||||
|
elem,
|
||||||
|
next_elem,
|
||||||
|
text_direction,
|
||||||
|
inject_word_breaks,
|
||||||
|
)
|
||||||
|
canvas.do.draw_text(text)
|
||||||
|
|
||||||
|
def _do_line_word(
|
||||||
|
self,
|
||||||
|
canvas: Canvas,
|
||||||
|
line_matrix: Matrix,
|
||||||
|
text: Text,
|
||||||
|
fontsize: float,
|
||||||
|
elem: Element,
|
||||||
|
next_elem: Element | None,
|
||||||
|
text_direction: TextDirection,
|
||||||
|
inject_word_breaks: bool,
|
||||||
|
):
|
||||||
|
"""Render the text for a single word."""
|
||||||
|
if elem is None:
|
||||||
|
return
|
||||||
|
elemtxt = self.normalize_text(self._get_element_text(elem).strip())
|
||||||
|
if elemtxt == '':
|
||||||
|
return
|
||||||
|
|
||||||
|
hocr_box = self.element_coordinates(elem)
|
||||||
|
if hocr_box is None:
|
||||||
|
return
|
||||||
|
box = line_matrix.inverse().transform(hocr_box)
|
||||||
|
font_width = self._font.text_width(elemtxt, fontsize)
|
||||||
|
|
||||||
|
# Debug sketches
|
||||||
|
self._debug_draw_word_triangle(canvas, box)
|
||||||
|
self._debug_draw_word_bbox(canvas, box)
|
||||||
|
|
||||||
|
# If this word is 0 units wide, our best bet seems to be to suppress this text
|
||||||
|
if font_width > 0:
|
||||||
|
text.text_transform(Matrix(1, 0, 0, 1, box.llx, 0))
|
||||||
|
text.horiz_scale(100 * box.width / font_width)
|
||||||
|
text.show(elemtxt.encode('utf-16be'))
|
||||||
|
|
||||||
|
# Get coordinates of the next word (if there is one)
|
||||||
|
hocr_next_box = (
|
||||||
|
self.element_coordinates(next_elem) if next_elem is not None else None
|
||||||
|
)
|
||||||
|
if hocr_next_box is None:
|
||||||
|
return
|
||||||
|
# Render a space this word and the next word. The explicit space helps
|
||||||
|
# PDF viewers identify the word break, and horizontally scaling it to
|
||||||
|
# occupy the space the between the words helps the PDF viewer
|
||||||
|
# avoid combiningthewordstogether.
|
||||||
|
if not inject_word_breaks:
|
||||||
|
return
|
||||||
|
next_box = line_matrix.inverse().transform(hocr_next_box)
|
||||||
|
if text_direction == TextDirection.LTR:
|
||||||
|
space_box = Rectangle(box.urx, box.lly, next_box.llx, next_box.ury)
|
||||||
|
elif text_direction == TextDirection.RTL:
|
||||||
|
space_box = Rectangle(next_box.urx, box.lly, box.llx, next_box.ury)
|
||||||
|
self._debug_draw_space_bbox(canvas, space_box)
|
||||||
|
text.text_transform(Matrix(1, 0, 0, 1, space_box.llx, 0))
|
||||||
|
space_width = self._font.text_width(' ', fontsize)
|
||||||
|
if space_width > 0:
|
||||||
|
text.horiz_scale(100 * space_box.width / space_width)
|
||||||
|
text.show(' '.encode('utf-16be'))
|
||||||
|
|
||||||
|
def _debug_draw_paragraph_boxes(self, canvas: Canvas, color=CYAN):
|
||||||
|
"""Draw boxes around paragraphs in the document."""
|
||||||
|
if not self.render_options.render_paragraph_bbox: # pragma: no cover
|
||||||
|
return
|
||||||
|
with canvas.do.save_state():
|
||||||
|
# draw box around paragraph
|
||||||
|
canvas.do.stroke_color(color).line_width(0.1)
|
||||||
|
for elem in self.hocr.iterfind(self._child_xpath('p', 'ocr_par')):
|
||||||
|
elemtxt = self._get_element_text(elem).strip()
|
||||||
|
if len(elemtxt) == 0:
|
||||||
|
continue
|
||||||
|
ocr_par = self.element_coordinates(elem)
|
||||||
|
if ocr_par is None:
|
||||||
|
continue
|
||||||
|
canvas.do.rect(
|
||||||
|
ocr_par.llx, ocr_par.lly, ocr_par.width, ocr_par.height, fill=0
|
||||||
|
)
|
||||||
|
|
||||||
|
def _debug_draw_line_bbox(self, canvas: Canvas, line_box: Rectangle, color=BLUE):
|
||||||
|
"""Render the bounding box of a text line."""
|
||||||
|
if not self.render_options.render_line_bbox: # pragma: no cover
|
||||||
|
return
|
||||||
|
with canvas.do.save_state():
|
||||||
|
canvas.do.stroke_color(color).line_width(0.15).rect(
|
||||||
|
line_box.llx, line_box.lly, line_box.width, line_box.height, fill=0
|
||||||
|
)
|
||||||
|
|
||||||
|
def _debug_draw_word_triangle(
|
||||||
|
self, canvas: Canvas, box: Rectangle, color=RED, line_width=0.1
|
||||||
|
):
|
||||||
|
"""Render a triangle that conveys word height and drawing direction."""
|
||||||
|
if not self.render_options.render_triangle: # pragma: no cover
|
||||||
|
return
|
||||||
|
with canvas.do.save_state():
|
||||||
|
canvas.do.stroke_color(color).line_width(line_width).line(
|
||||||
|
box.llx, box.lly, box.urx, box.lly
|
||||||
|
).line(box.urx, box.lly, box.llx, box.ury).line(
|
||||||
|
box.llx, box.lly, box.llx, box.ury
|
||||||
|
)
|
||||||
|
|
||||||
|
def _debug_draw_word_bbox(
|
||||||
|
self, canvas: Canvas, box: Rectangle, color=GREEN, line_width=0.1
|
||||||
|
):
|
||||||
|
"""Render a box depicting the word."""
|
||||||
|
if not self.render_options.render_word_bbox: # pragma: no cover
|
||||||
|
return
|
||||||
|
with canvas.do.save_state():
|
||||||
|
canvas.do.stroke_color(color).line_width(line_width).rect(
|
||||||
|
box.llx, box.lly, box.width, box.height, fill=0
|
||||||
|
)
|
||||||
|
|
||||||
|
def _debug_draw_space_bbox(
|
||||||
|
self, canvas: Canvas, box: Rectangle, color=DARKGREEN, line_width=0.1
|
||||||
|
):
|
||||||
|
"""Render a box depicting the space between two words."""
|
||||||
|
if not self.render_options.render_space_bbox: # pragma: no cover
|
||||||
|
return
|
||||||
|
with canvas.do.save_state():
|
||||||
|
canvas.do.fill_color(color).line_width(line_width).rect(
|
||||||
|
box.llx, box.lly, box.width, box.height, fill=1
|
||||||
|
)
|
||||||
|
|
||||||
|
def _debug_draw_baseline(
|
||||||
|
self,
|
||||||
|
canvas: Canvas,
|
||||||
|
line_box: Rectangle,
|
||||||
|
baseline_lly,
|
||||||
|
color=MAGENTA,
|
||||||
|
line_width=0.25,
|
||||||
|
):
|
||||||
|
"""Render the text baseline."""
|
||||||
|
if not self.render_options.render_baseline:
|
||||||
|
return
|
||||||
|
with canvas.do.save_state():
|
||||||
|
canvas.do.stroke_color(color).line_width(line_width).line(
|
||||||
|
line_box.llx,
|
||||||
|
baseline_lly,
|
||||||
|
line_box.urx,
|
||||||
|
baseline_lly,
|
||||||
|
)
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
# SPDX-FileCopyrightText: 2023 James R. Barlow
|
||||||
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
|
|
||||||
|
"""OCR-related image manipulation."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from math import floor, sqrt
|
||||||
|
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def bytes_per_pixel(mode: str) -> int:
|
||||||
|
"""Return the number of padded bytes per pixel for a given PIL image mode.
|
||||||
|
|
||||||
|
In RGB mode we assume 4 bytes per pixel, which is the case for most
|
||||||
|
consumers.
|
||||||
|
"""
|
||||||
|
if mode in ('1', 'L', 'P'):
|
||||||
|
return 1
|
||||||
|
if mode in ('LA', 'PA', 'La') or mode.startswith('I;16'):
|
||||||
|
return 2
|
||||||
|
return 4
|
||||||
|
|
||||||
|
|
||||||
|
def _calculate_downsample(
|
||||||
|
image_size: tuple[int, int],
|
||||||
|
bytes_per_pixel: int,
|
||||||
|
*,
|
||||||
|
max_size: tuple[int, int] | None = None,
|
||||||
|
max_pixels: int | None = None,
|
||||||
|
max_bytes: int | None = None,
|
||||||
|
) -> tuple[int, int]:
|
||||||
|
"""Calculate image size required to downsample an image to fit limits.
|
||||||
|
|
||||||
|
If no limit is exceeded, the input image's size is returned.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
image_size: Dimensions of image.
|
||||||
|
bytes_per_pixel: Number of bytes per pixel.
|
||||||
|
max_size: The maximum width and height of the image.
|
||||||
|
max_pixels: The maximum number of pixels in the image. Some image consumers
|
||||||
|
limit the total number of pixels as some value other than width*height.
|
||||||
|
max_bytes: The maximum number of bytes in the image. RGB is counted as 4
|
||||||
|
bytes; all other modes are counted as 1 byte.
|
||||||
|
"""
|
||||||
|
size = image_size
|
||||||
|
|
||||||
|
if max_size is not None:
|
||||||
|
overage = max_size[0] / size[0], max_size[1] / size[1]
|
||||||
|
size_factor = min(overage)
|
||||||
|
if size_factor < 1.0:
|
||||||
|
log.debug("Resizing image to fit image dimensions limit")
|
||||||
|
size = floor(size[0] * size_factor), floor(size[1] * size_factor)
|
||||||
|
if size[0] == 0:
|
||||||
|
size = 1, min(size[1], max_size[1])
|
||||||
|
elif size[1] == 0:
|
||||||
|
size = min(size[0], max_size[0]), 1
|
||||||
|
|
||||||
|
if max_pixels is not None:
|
||||||
|
if size[0] * size[1] > max_pixels:
|
||||||
|
log.debug("Resizing image to fit image pixel limit")
|
||||||
|
pixels_factor = sqrt(max_pixels / (size[0] * size[1]))
|
||||||
|
size = floor(size[0] * pixels_factor), floor(size[1] * pixels_factor)
|
||||||
|
|
||||||
|
if max_bytes is not None:
|
||||||
|
bpp = bytes_per_pixel
|
||||||
|
# stride = bytes per line
|
||||||
|
stride = size[0] * bpp
|
||||||
|
height = size[1]
|
||||||
|
if stride * height > max_bytes:
|
||||||
|
log.debug("Resizing image to fit image byte size limit")
|
||||||
|
bytes_factor = sqrt(max_bytes / (stride * height))
|
||||||
|
scaled_stride = floor(stride * bytes_factor)
|
||||||
|
scaled_height = floor(height * bytes_factor)
|
||||||
|
if scaled_stride == 0:
|
||||||
|
scaled_stride = bpp
|
||||||
|
scaled_height = min(max_bytes // bpp, scaled_height)
|
||||||
|
if scaled_height == 0:
|
||||||
|
scaled_height = 1
|
||||||
|
scaled_stride = min(max_bytes // scaled_height, scaled_stride)
|
||||||
|
size = floor(scaled_stride / bpp), scaled_height
|
||||||
|
|
||||||
|
return size
|
||||||
|
|
||||||
|
|
||||||
|
def calculate_downsample(
|
||||||
|
image: Image.Image,
|
||||||
|
*,
|
||||||
|
max_size: tuple[int, int] | None = None,
|
||||||
|
max_pixels: int | None = None,
|
||||||
|
max_bytes: int | None = None,
|
||||||
|
) -> tuple[int, int]:
|
||||||
|
"""Calculate image size required to downsample an image to fit limits.
|
||||||
|
|
||||||
|
If no limit is exceeded, the input image's size is returned.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
image: The image to downsample.
|
||||||
|
max_size: The maximum width and height of the image.
|
||||||
|
max_pixels: The maximum number of pixels in the image. Some image consumers
|
||||||
|
limit the total number of pixels as some value other than width*height.
|
||||||
|
max_bytes: The maximum number of bytes in the image. RGB is counted as 4
|
||||||
|
bytes; all other modes are counted as 1 byte.
|
||||||
|
"""
|
||||||
|
return _calculate_downsample(
|
||||||
|
image.size,
|
||||||
|
bytes_per_pixel(image.mode),
|
||||||
|
max_size=max_size,
|
||||||
|
max_pixels=max_pixels,
|
||||||
|
max_bytes=max_bytes,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downsample_image(
|
||||||
|
image: Image.Image,
|
||||||
|
new_size: tuple[int, int],
|
||||||
|
*,
|
||||||
|
resample_mode: Image.Resampling = Image.Resampling.BICUBIC,
|
||||||
|
reducing_gap: int = 3,
|
||||||
|
) -> Image.Image:
|
||||||
|
"""Downsample an image to fit within the given limits.
|
||||||
|
|
||||||
|
The DPI is adjusted to match the new size, which is how we can ensure the
|
||||||
|
OCR is positioned correctly.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
image: The image to downsample
|
||||||
|
new_size: The new size of the image.
|
||||||
|
resample_mode: The resampling mode to use when downsampling.
|
||||||
|
reducing_gap: The reducing gap to use when downsampling (for larger
|
||||||
|
reductions).
|
||||||
|
"""
|
||||||
|
if new_size == image.size:
|
||||||
|
return image
|
||||||
|
|
||||||
|
original_size = image.size
|
||||||
|
original_dpi = image.info['dpi']
|
||||||
|
image = image.resize(
|
||||||
|
new_size,
|
||||||
|
resample=resample_mode,
|
||||||
|
reducing_gap=reducing_gap,
|
||||||
|
)
|
||||||
|
image.info['dpi'] = (
|
||||||
|
round(original_dpi[0] * new_size[0] / original_size[0]),
|
||||||
|
round(original_dpi[1] * new_size[1] / original_size[1]),
|
||||||
|
)
|
||||||
|
log.debug(f"Rescaled image to {image.size} pixels and {image.info['dpi']} dpi")
|
||||||
|
return image
|
||||||
@@ -0,0 +1,849 @@
|
|||||||
|
# SPDX-FileCopyrightText: 2023 James R. Barlow
|
||||||
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
|
|
||||||
|
"""Language codes and names from ISO 639.
|
||||||
|
|
||||||
|
Derived from
|
||||||
|
https://www.loc.gov/standards/iso639-2/ascii_8bits.html
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
from typing import NamedTuple
|
||||||
|
|
||||||
|
|
||||||
|
class ISOCodeData(NamedTuple):
|
||||||
|
"""Data for a single ISO 639 code."""
|
||||||
|
alt: str
|
||||||
|
alpha_2: str
|
||||||
|
english: str
|
||||||
|
french: str
|
||||||
|
|
||||||
|
|
||||||
|
ISO_639_3 = {
|
||||||
|
'aar': ISOCodeData('', 'aa', 'Afar', 'afar'),
|
||||||
|
'abk': ISOCodeData('', 'ab', 'Abkhazian', 'abkhaze'),
|
||||||
|
'ace': ISOCodeData('', '', 'Achinese', 'aceh'),
|
||||||
|
'ach': ISOCodeData('', '', 'Acoli', 'acoli'),
|
||||||
|
'ada': ISOCodeData('', '', 'Adangme', 'adangme'),
|
||||||
|
'ady': ISOCodeData('', '', 'Adyghe; Adygei', 'adyghé'),
|
||||||
|
'afa': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Afro-Asiatic languages',
|
||||||
|
'afro-asiatiques, langues',
|
||||||
|
),
|
||||||
|
'afh': ISOCodeData('', '', 'Afrihili', 'afrihili'),
|
||||||
|
'afr': ISOCodeData('', 'af', 'Afrikaans', 'afrikaans'),
|
||||||
|
'ain': ISOCodeData('', '', 'Ainu', 'aïnou'),
|
||||||
|
'aka': ISOCodeData('', 'ak', 'Akan', 'akan'),
|
||||||
|
'akk': ISOCodeData('', '', 'Akkadian', 'akkadien'),
|
||||||
|
'alb': ISOCodeData('sqi', 'sq', 'Albanian', 'albanais'),
|
||||||
|
'ale': ISOCodeData('', '', 'Aleut', 'aléoute'),
|
||||||
|
'alg': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Algonquian languages',
|
||||||
|
'algonquines, langues',
|
||||||
|
),
|
||||||
|
'alt': ISOCodeData('', '', 'Southern Altai', 'altai du Sud'),
|
||||||
|
'amh': ISOCodeData('', 'am', 'Amharic', 'amharique'),
|
||||||
|
'ang': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'English, Old (ca.450-1100)',
|
||||||
|
'anglo-saxon (ca.450-1100)',
|
||||||
|
),
|
||||||
|
'anp': ISOCodeData('', '', 'Angika', 'angika'),
|
||||||
|
'apa': ISOCodeData('', '', 'Apache languages', 'apaches, langues'),
|
||||||
|
'ara': ISOCodeData('', 'ar', 'Arabic', 'arabe'),
|
||||||
|
'arc': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Official Aramaic (700-300 BCE); Imperial Aramaic (700-300 BCE)',
|
||||||
|
"araméen d'empire (700-300 BCE)",
|
||||||
|
),
|
||||||
|
'arg': ISOCodeData('', 'an', 'Aragonese', 'aragonais'),
|
||||||
|
'arm': ISOCodeData('hye', 'hy', 'Armenian', 'arménien'),
|
||||||
|
'arn': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Mapudungun; Mapuche',
|
||||||
|
'mapudungun; mapuche; mapuce',
|
||||||
|
),
|
||||||
|
'arp': ISOCodeData('', '', 'Arapaho', 'arapaho'),
|
||||||
|
'art': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Artificial languages',
|
||||||
|
'artificielles, langues',
|
||||||
|
),
|
||||||
|
'arw': ISOCodeData('', '', 'Arawak', 'arawak'),
|
||||||
|
'asm': ISOCodeData('', 'as', 'Assamese', 'assamais'),
|
||||||
|
'ast': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Asturian; Bable; Leonese; Asturleonese',
|
||||||
|
'asturien; bable; léonais; asturoléonais',
|
||||||
|
),
|
||||||
|
'ath': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Athapascan languages',
|
||||||
|
'athapascanes, langues',
|
||||||
|
),
|
||||||
|
'aus': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Australian languages',
|
||||||
|
'australiennes, langues',
|
||||||
|
),
|
||||||
|
'ava': ISOCodeData('', 'av', 'Avaric', 'avar'),
|
||||||
|
'ave': ISOCodeData('', 'ae', 'Avestan', 'avestique'),
|
||||||
|
'awa': ISOCodeData('', '', 'Awadhi', 'awadhi'),
|
||||||
|
'aym': ISOCodeData('', 'ay', 'Aymara', 'aymara'),
|
||||||
|
'aze': ISOCodeData('', 'az', 'Azerbaijani', 'azéri'),
|
||||||
|
'bad': ISOCodeData('', '', 'Banda languages', 'banda, langues'),
|
||||||
|
'bai': ISOCodeData('', '', 'Bamileke languages', 'bamiléké, langues'),
|
||||||
|
'bak': ISOCodeData('', 'ba', 'Bashkir', 'bachkir'),
|
||||||
|
'bal': ISOCodeData('', '', 'Baluchi', 'baloutchi'),
|
||||||
|
'bam': ISOCodeData('', 'bm', 'Bambara', 'bambara'),
|
||||||
|
'ban': ISOCodeData('', '', 'Balinese', 'balinais'),
|
||||||
|
'baq': ISOCodeData('eus', 'eu', 'Basque', 'basque'),
|
||||||
|
'bas': ISOCodeData('', '', 'Basa', 'basa'),
|
||||||
|
'bat': ISOCodeData('', '', 'Baltic languages', 'baltes, langues'),
|
||||||
|
'bej': ISOCodeData('', '', 'Beja; Bedawiyet', 'bedja'),
|
||||||
|
'bel': ISOCodeData('', 'be', 'Belarusian', 'biélorusse'),
|
||||||
|
'bem': ISOCodeData('', '', 'Bemba', 'bemba'),
|
||||||
|
'ben': ISOCodeData('', 'bn', 'Bengali', 'bengali'),
|
||||||
|
'ber': ISOCodeData('', '', 'Berber languages', 'berbères, langues'),
|
||||||
|
'bho': ISOCodeData('', '', 'Bhojpuri', 'bhojpuri'),
|
||||||
|
'bih': ISOCodeData('', 'bh', 'Bihari languages', 'langues biharis'),
|
||||||
|
'bik': ISOCodeData('', '', 'Bikol', 'bikol'),
|
||||||
|
'bin': ISOCodeData('', '', 'Bini; Edo', 'bini; edo'),
|
||||||
|
'bis': ISOCodeData('', 'bi', 'Bislama', 'bichlamar'),
|
||||||
|
'bla': ISOCodeData('', '', 'Siksika', 'blackfoot'),
|
||||||
|
'bnt': ISOCodeData('', '', 'Bantu languages', 'bantou, langues'),
|
||||||
|
'bos': ISOCodeData('', 'bs', 'Bosnian', 'bosniaque'),
|
||||||
|
'bra': ISOCodeData('', '', 'Braj', 'braj'),
|
||||||
|
'bre': ISOCodeData('', 'br', 'Breton', 'breton'),
|
||||||
|
'btk': ISOCodeData('', '', 'Batak languages', 'batak, langues'),
|
||||||
|
'bua': ISOCodeData('', '', 'Buriat', 'bouriate'),
|
||||||
|
'bug': ISOCodeData('', '', 'Buginese', 'bugi'),
|
||||||
|
'bul': ISOCodeData('', 'bg', 'Bulgarian', 'bulgare'),
|
||||||
|
'bur': ISOCodeData('mya', 'my', 'Burmese', 'birman'),
|
||||||
|
'byn': ISOCodeData('', '', 'Blin; Bilin', 'blin; bilen'),
|
||||||
|
'cad': ISOCodeData('', '', 'Caddo', 'caddo'),
|
||||||
|
'cai': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Central American Indian languages',
|
||||||
|
"amérindiennes de L'Amérique centrale, langues",
|
||||||
|
),
|
||||||
|
'car': ISOCodeData('', '', 'Galibi Carib', 'karib; galibi; carib'),
|
||||||
|
'cat': ISOCodeData('', 'ca', 'Catalan; Valencian', 'catalan; valencien'),
|
||||||
|
'cau': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Caucasian languages',
|
||||||
|
'caucasiennes, langues',
|
||||||
|
),
|
||||||
|
'ceb': ISOCodeData('', '', 'Cebuano', 'cebuano'),
|
||||||
|
'cel': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Celtic languages',
|
||||||
|
'celtiques, langues; celtes, langues',
|
||||||
|
),
|
||||||
|
'cha': ISOCodeData('', 'ch', 'Chamorro', 'chamorro'),
|
||||||
|
'chb': ISOCodeData('', '', 'Chibcha', 'chibcha'),
|
||||||
|
'che': ISOCodeData('', 'ce', 'Chechen', 'tchétchène'),
|
||||||
|
'chg': ISOCodeData('', '', 'Chagatai', 'djaghataï'),
|
||||||
|
'chi': ISOCodeData('zho', 'zh', 'Chinese', 'chinois'),
|
||||||
|
'chk': ISOCodeData('', '', 'Chuukese', 'chuuk'),
|
||||||
|
'chm': ISOCodeData('', '', 'Mari', 'mari'),
|
||||||
|
'chn': ISOCodeData('', '', 'Chinook jargon', 'chinook, jargon'),
|
||||||
|
'cho': ISOCodeData('', '', 'Choctaw', 'choctaw'),
|
||||||
|
'chp': ISOCodeData('', '', 'Chipewyan; Dene Suline', 'chipewyan'),
|
||||||
|
'chr': ISOCodeData('', '', 'Cherokee', 'cherokee'),
|
||||||
|
'chu': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'cu',
|
||||||
|
('Church Slavic; Old Slavonic; Church Slavonic;'
|
||||||
|
' Old Bulgarian; Old Church Slavonic'),
|
||||||
|
"slavon d'église; vieux slave; slavon liturgique; vieux bulgare",
|
||||||
|
),
|
||||||
|
'chv': ISOCodeData('', 'cv', 'Chuvash', 'tchouvache'),
|
||||||
|
'chy': ISOCodeData('', '', 'Cheyenne', 'cheyenne'),
|
||||||
|
'cmc': ISOCodeData('', '', 'Chamic languages', 'chames, langues'),
|
||||||
|
'cnr': ISOCodeData('', '', 'Montenegrin', 'monténégrin'),
|
||||||
|
'cop': ISOCodeData('', '', 'Coptic', 'copte'),
|
||||||
|
'cor': ISOCodeData('', 'kw', 'Cornish', 'cornique'),
|
||||||
|
'cos': ISOCodeData('', 'co', 'Corsican', 'corse'),
|
||||||
|
'cpe': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Creoles and pidgins, English based',
|
||||||
|
"créoles et pidgins basés sur l'anglais",
|
||||||
|
),
|
||||||
|
'cpf': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Creoles and pidgins, French-based',
|
||||||
|
'créoles et pidgins basés sur le français',
|
||||||
|
),
|
||||||
|
'cpp': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Creoles and pidgins, Portuguese-based',
|
||||||
|
'créoles et pidgins basés sur le portugais',
|
||||||
|
),
|
||||||
|
'cre': ISOCodeData('', 'cr', 'Cree', 'cree'),
|
||||||
|
'crh': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Crimean Tatar; Crimean Turkish',
|
||||||
|
'tatar de Crimé',
|
||||||
|
),
|
||||||
|
'crp': ISOCodeData('', '', 'Creoles and pidgins', 'créoles et pidgins'),
|
||||||
|
'csb': ISOCodeData('', '', 'Kashubian', 'kachoube'),
|
||||||
|
'cus': ISOCodeData('', '', 'Cushitic languages', 'couchitiques, langues'),
|
||||||
|
'cze': ISOCodeData('ces', 'cs', 'Czech', 'tchèque'),
|
||||||
|
'dak': ISOCodeData('', '', 'Dakota', 'dakota'),
|
||||||
|
'dan': ISOCodeData('', 'da', 'Danish', 'danois'),
|
||||||
|
'dar': ISOCodeData('', '', 'Dargwa', 'dargwa'),
|
||||||
|
'day': ISOCodeData('', '', 'Land Dayak languages', 'dayak, langues'),
|
||||||
|
'del': ISOCodeData('', '', 'Delaware', 'delaware'),
|
||||||
|
'den': ISOCodeData('', '', 'Slave (Athapascan)', 'esclave (athapascan)'),
|
||||||
|
'dgr': ISOCodeData('', '', 'Dogrib', 'dogrib'),
|
||||||
|
'din': ISOCodeData('', '', 'Dinka', 'dinka'),
|
||||||
|
'div': ISOCodeData('', 'dv', 'Divehi; Dhivehi; Maldivian', 'maldivien'),
|
||||||
|
'doi': ISOCodeData('', '', 'Dogri', 'dogri'),
|
||||||
|
'dra': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Dravidian languages',
|
||||||
|
'dravidiennes, langues',
|
||||||
|
),
|
||||||
|
'dsb': ISOCodeData('', '', 'Lower Sorbian', 'bas-sorabe'),
|
||||||
|
'dua': ISOCodeData('', '', 'Duala', 'douala'),
|
||||||
|
'dum': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Dutch, Middle (ca.1050-1350)',
|
||||||
|
'néerlandais moyen (ca. 1050-1350)',
|
||||||
|
),
|
||||||
|
'dut': ISOCodeData('nld', 'nl', 'Dutch; Flemish', 'néerlandais; flamand'),
|
||||||
|
'dyu': ISOCodeData('', '', 'Dyula', 'dioula'),
|
||||||
|
'dzo': ISOCodeData('', 'dz', 'Dzongkha', 'dzongkha'),
|
||||||
|
'efi': ISOCodeData('', '', 'Efik', 'efik'),
|
||||||
|
'egy': ISOCodeData('', '', 'Egyptian (Ancient)', 'égyptien'),
|
||||||
|
'eka': ISOCodeData('', '', 'Ekajuk', 'ekajuk'),
|
||||||
|
'elx': ISOCodeData('', '', 'Elamite', 'élamite'),
|
||||||
|
'eng': ISOCodeData('', 'en', 'English', 'anglais'),
|
||||||
|
'enm': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'English, Middle (1100-1500)',
|
||||||
|
'anglais moyen (1100-1500)',
|
||||||
|
),
|
||||||
|
'epo': ISOCodeData('', 'eo', 'Esperanto', 'espéranto'),
|
||||||
|
'est': ISOCodeData('', 'et', 'Estonian', 'estonien'),
|
||||||
|
'ewe': ISOCodeData('', 'ee', 'Ewe', 'éwé'),
|
||||||
|
'ewo': ISOCodeData('', '', 'Ewondo', 'éwondo'),
|
||||||
|
'fan': ISOCodeData('', '', 'Fang', 'fang'),
|
||||||
|
'fao': ISOCodeData('', 'fo', 'Faroese', 'féroïen'),
|
||||||
|
'fat': ISOCodeData('', '', 'Fanti', 'fanti'),
|
||||||
|
'fij': ISOCodeData('', 'fj', 'Fijian', 'fidjien'),
|
||||||
|
'fil': ISOCodeData('', '', 'Filipino; Pilipino', 'filipino; pilipino'),
|
||||||
|
'fin': ISOCodeData('', 'fi', 'Finnish', 'finnois'),
|
||||||
|
'fiu': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Finno-Ugrian languages',
|
||||||
|
'finno-ougriennes, langues',
|
||||||
|
),
|
||||||
|
'fon': ISOCodeData('', '', 'Fon', 'fon'),
|
||||||
|
'fre': ISOCodeData('fra', 'fr', 'French', 'français'),
|
||||||
|
'frm': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'French, Middle (ca.1400-1600)',
|
||||||
|
'français moyen (1400-1600)',
|
||||||
|
),
|
||||||
|
'fro': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'French, Old (842-ca.1400)',
|
||||||
|
'français ancien (842-ca.1400)',
|
||||||
|
),
|
||||||
|
'frr': ISOCodeData('', '', 'Northern Frisian', 'frison septentrional'),
|
||||||
|
'frs': ISOCodeData('', '', 'Eastern Frisian', 'frison oriental'),
|
||||||
|
'fry': ISOCodeData('', 'fy', 'Western Frisian', 'frison occidental'),
|
||||||
|
'ful': ISOCodeData('', 'ff', 'Fulah', 'peul'),
|
||||||
|
'fur': ISOCodeData('', '', 'Friulian', 'frioulan'),
|
||||||
|
'gaa': ISOCodeData('', '', 'Ga', 'ga'),
|
||||||
|
'gay': ISOCodeData('', '', 'Gayo', 'gayo'),
|
||||||
|
'gba': ISOCodeData('', '', 'Gbaya', 'gbaya'),
|
||||||
|
'gem': ISOCodeData('', '', 'Germanic languages', 'germaniques, langues'),
|
||||||
|
'geo': ISOCodeData('kat', 'ka', 'Georgian', 'géorgien'),
|
||||||
|
'ger': ISOCodeData('deu', 'de', 'German', 'allemand'),
|
||||||
|
'gez': ISOCodeData('', '', 'Geez', 'guèze'),
|
||||||
|
'gil': ISOCodeData('', '', 'Gilbertese', 'kiribati'),
|
||||||
|
'gla': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'gd',
|
||||||
|
'Gaelic; Scottish Gaelic',
|
||||||
|
'gaélique; gaélique écossais',
|
||||||
|
),
|
||||||
|
'gle': ISOCodeData('', 'ga', 'Irish', 'irlandais'),
|
||||||
|
'glg': ISOCodeData('', 'gl', 'Galician', 'galicien'),
|
||||||
|
'glv': ISOCodeData('', 'gv', 'Manx', 'manx; mannois'),
|
||||||
|
'gmh': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'German, Middle High (ca.1050-1500)',
|
||||||
|
'allemand, moyen haut (ca. 1050-1500)',
|
||||||
|
),
|
||||||
|
'goh': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'German, Old High (ca.750-1050)',
|
||||||
|
'allemand, vieux haut (ca. 750-1050)',
|
||||||
|
),
|
||||||
|
'gon': ISOCodeData('', '', 'Gondi', 'gond'),
|
||||||
|
'gor': ISOCodeData('', '', 'Gorontalo', 'gorontalo'),
|
||||||
|
'got': ISOCodeData('', '', 'Gothic', 'gothique'),
|
||||||
|
'grb': ISOCodeData('', '', 'Grebo', 'grebo'),
|
||||||
|
'grc': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Greek, Ancient (to 1453)',
|
||||||
|
"grec ancien (jusqu'à 1453)",
|
||||||
|
),
|
||||||
|
'gre': ISOCodeData(
|
||||||
|
'ell',
|
||||||
|
'el',
|
||||||
|
'Greek, Modern (1453-)',
|
||||||
|
'grec moderne (après 1453)',
|
||||||
|
),
|
||||||
|
'grn': ISOCodeData('', 'gn', 'Guarani', 'guarani'),
|
||||||
|
'gsw': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Swiss German; Alemannic; Alsatian',
|
||||||
|
'suisse alémanique; alémanique; alsacien',
|
||||||
|
),
|
||||||
|
'guj': ISOCodeData('', 'gu', 'Gujarati', 'goudjrati'),
|
||||||
|
'gwi': ISOCodeData('', '', "Gwich'in", "gwich'in"),
|
||||||
|
'hai': ISOCodeData('', '', 'Haida', 'haida'),
|
||||||
|
'hat': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'ht',
|
||||||
|
'Haitian; Haitian Creole',
|
||||||
|
'haïtien; créole haïtien',
|
||||||
|
),
|
||||||
|
'hau': ISOCodeData('', 'ha', 'Hausa', 'haoussa'),
|
||||||
|
'haw': ISOCodeData('', '', 'Hawaiian', 'hawaïen'),
|
||||||
|
'heb': ISOCodeData('', 'he', 'Hebrew', 'hébreu'),
|
||||||
|
'her': ISOCodeData('', 'hz', 'Herero', 'herero'),
|
||||||
|
'hil': ISOCodeData('', '', 'Hiligaynon', 'hiligaynon'),
|
||||||
|
'him': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Himachali languages; Western Pahari languages',
|
||||||
|
'langues himachalis; langues paharis occidentales',
|
||||||
|
),
|
||||||
|
'hin': ISOCodeData('', 'hi', 'Hindi', 'hindi'),
|
||||||
|
'hit': ISOCodeData('', '', 'Hittite', 'hittite'),
|
||||||
|
'hmn': ISOCodeData('', '', 'Hmong; Mong', 'hmong'),
|
||||||
|
'hmo': ISOCodeData('', 'ho', 'Hiri Motu', 'hiri motu'),
|
||||||
|
'hrv': ISOCodeData('', 'hr', 'Croatian', 'croate'),
|
||||||
|
'hsb': ISOCodeData('', '', 'Upper Sorbian', 'haut-sorabe'),
|
||||||
|
'hun': ISOCodeData('', 'hu', 'Hungarian', 'hongrois'),
|
||||||
|
'hup': ISOCodeData('', '', 'Hupa', 'hupa'),
|
||||||
|
'iba': ISOCodeData('', '', 'Iban', 'iban'),
|
||||||
|
'ibo': ISOCodeData('', 'ig', 'Igbo', 'igbo'),
|
||||||
|
'ice': ISOCodeData('isl', 'is', 'Icelandic', 'islandais'),
|
||||||
|
'ido': ISOCodeData('', 'io', 'Ido', 'ido'),
|
||||||
|
'iii': ISOCodeData('', 'ii', 'Sichuan Yi; Nuosu', 'yi de Sichuan'),
|
||||||
|
'ijo': ISOCodeData('', '', 'Ijo languages', 'ijo, langues'),
|
||||||
|
'iku': ISOCodeData('', 'iu', 'Inuktitut', 'inuktitut'),
|
||||||
|
'ile': ISOCodeData('', 'ie', 'Interlingue; Occidental', 'interlingue'),
|
||||||
|
'ilo': ISOCodeData('', '', 'Iloko', 'ilocano'),
|
||||||
|
'ina': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'ia',
|
||||||
|
'Interlingua (International Auxiliary Language Association)',
|
||||||
|
'interlingua (langue auxiliaire internationale)',
|
||||||
|
),
|
||||||
|
'inc': ISOCodeData('', '', 'Indic languages', 'indo-aryennes, langues'),
|
||||||
|
'ind': ISOCodeData('', 'id', 'Indonesian', 'indonésien'),
|
||||||
|
'ine': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Indo-European languages',
|
||||||
|
'indo-européennes, langues',
|
||||||
|
),
|
||||||
|
'inh': ISOCodeData('', '', 'Ingush', 'ingouche'),
|
||||||
|
'ipk': ISOCodeData('', 'ik', 'Inupiaq', 'inupiaq'),
|
||||||
|
'ira': ISOCodeData('', '', 'Iranian languages', 'iraniennes, langues'),
|
||||||
|
'iro': ISOCodeData('', '', 'Iroquoian languages', 'iroquoises, langues'),
|
||||||
|
'ita': ISOCodeData('', 'it', 'Italian', 'italien'),
|
||||||
|
'jav': ISOCodeData('', 'jv', 'Javanese', 'javanais'),
|
||||||
|
'jbo': ISOCodeData('', '', 'Lojban', 'lojban'),
|
||||||
|
'jpn': ISOCodeData('', 'ja', 'Japanese', 'japonais'),
|
||||||
|
'jpr': ISOCodeData('', '', 'Judeo-Persian', 'judéo-persan'),
|
||||||
|
'jrb': ISOCodeData('', '', 'Judeo-Arabic', 'judéo-arabe'),
|
||||||
|
'kaa': ISOCodeData('', '', 'Kara-Kalpak', 'karakalpak'),
|
||||||
|
'kab': ISOCodeData('', '', 'Kabyle', 'kabyle'),
|
||||||
|
'kac': ISOCodeData('', '', 'Kachin; Jingpho', 'kachin; jingpho'),
|
||||||
|
'kal': ISOCodeData('', 'kl', 'Kalaallisut; Greenlandic', 'groenlandais'),
|
||||||
|
'kam': ISOCodeData('', '', 'Kamba', 'kamba'),
|
||||||
|
'kan': ISOCodeData('', 'kn', 'Kannada', 'kannada'),
|
||||||
|
'kar': ISOCodeData('', '', 'Karen languages', 'karen, langues'),
|
||||||
|
'kas': ISOCodeData('', 'ks', 'Kashmiri', 'kashmiri'),
|
||||||
|
'kau': ISOCodeData('', 'kr', 'Kanuri', 'kanouri'),
|
||||||
|
'kaw': ISOCodeData('', '', 'Kawi', 'kawi'),
|
||||||
|
'kaz': ISOCodeData('', 'kk', 'Kazakh', 'kazakh'),
|
||||||
|
'kbd': ISOCodeData('', '', 'Kabardian', 'kabardien'),
|
||||||
|
'kha': ISOCodeData('', '', 'Khasi', 'khasi'),
|
||||||
|
'khi': ISOCodeData('', '', 'Khoisan languages', 'khoïsan, langues'),
|
||||||
|
'khm': ISOCodeData('', 'km', 'Central Khmer', 'khmer central'),
|
||||||
|
'kho': ISOCodeData('', '', 'Khotanese; Sakan', 'khotanais; sakan'),
|
||||||
|
'kik': ISOCodeData('', 'ki', 'Kikuyu; Gikuyu', 'kikuyu'),
|
||||||
|
'kin': ISOCodeData('', 'rw', 'Kinyarwanda', 'rwanda'),
|
||||||
|
'kir': ISOCodeData('', 'ky', 'Kirghiz; Kyrgyz', 'kirghiz'),
|
||||||
|
'kmb': ISOCodeData('', '', 'Kimbundu', 'kimbundu'),
|
||||||
|
'kok': ISOCodeData('', '', 'Konkani', 'konkani'),
|
||||||
|
'kom': ISOCodeData('', 'kv', 'Komi', 'kom'),
|
||||||
|
'kon': ISOCodeData('', 'kg', 'Kongo', 'kongo'),
|
||||||
|
'kor': ISOCodeData('', 'ko', 'Korean', 'coréen'),
|
||||||
|
'kos': ISOCodeData('', '', 'Kosraean', 'kosrae'),
|
||||||
|
'kpe': ISOCodeData('', '', 'Kpelle', 'kpellé'),
|
||||||
|
'krc': ISOCodeData('', '', 'Karachay-Balkar', 'karatchai balkar'),
|
||||||
|
'krl': ISOCodeData('', '', 'Karelian', 'carélien'),
|
||||||
|
'kro': ISOCodeData('', '', 'Kru languages', 'krou, langues'),
|
||||||
|
'kru': ISOCodeData('', '', 'Kurukh', 'kurukh'),
|
||||||
|
'kua': ISOCodeData('', 'kj', 'Kuanyama; Kwanyama', 'kuanyama; kwanyama'),
|
||||||
|
'kum': ISOCodeData('', '', 'Kumyk', 'koumyk'),
|
||||||
|
'kur': ISOCodeData('', 'ku', 'Kurdish', 'kurde'),
|
||||||
|
'kut': ISOCodeData('', '', 'Kutenai', 'kutenai'),
|
||||||
|
'lad': ISOCodeData('', '', 'Ladino', 'judéo-espagnol'),
|
||||||
|
'lah': ISOCodeData('', '', 'Lahnda', 'lahnda'),
|
||||||
|
'lam': ISOCodeData('', '', 'Lamba', 'lamba'),
|
||||||
|
'lao': ISOCodeData('', 'lo', 'Lao', 'lao'),
|
||||||
|
'lat': ISOCodeData('', 'la', 'Latin', 'latin'),
|
||||||
|
'lav': ISOCodeData('', 'lv', 'Latvian', 'letton'),
|
||||||
|
'lez': ISOCodeData('', '', 'Lezghian', 'lezghien'),
|
||||||
|
'lim': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'li',
|
||||||
|
'Limburgan; Limburger; Limburgish',
|
||||||
|
'limbourgeois',
|
||||||
|
),
|
||||||
|
'lin': ISOCodeData('', 'ln', 'Lingala', 'lingala'),
|
||||||
|
'lit': ISOCodeData('', 'lt', 'Lithuanian', 'lituanien'),
|
||||||
|
'lol': ISOCodeData('', '', 'Mongo', 'mongo'),
|
||||||
|
'loz': ISOCodeData('', '', 'Lozi', 'lozi'),
|
||||||
|
'ltz': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'lb',
|
||||||
|
'Luxembourgish; Letzeburgesch',
|
||||||
|
'luxembourgeois',
|
||||||
|
),
|
||||||
|
'lua': ISOCodeData('', '', 'Luba-Lulua', 'luba-lulua'),
|
||||||
|
'lub': ISOCodeData('', 'lu', 'Luba-Katanga', 'luba-katanga'),
|
||||||
|
'lug': ISOCodeData('', 'lg', 'Ganda', 'ganda'),
|
||||||
|
'lui': ISOCodeData('', '', 'Luiseno', 'luiseno'),
|
||||||
|
'lun': ISOCodeData('', '', 'Lunda', 'lunda'),
|
||||||
|
'luo': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Luo (Kenya and Tanzania)',
|
||||||
|
'luo (Kenya et Tanzanie)',
|
||||||
|
),
|
||||||
|
'lus': ISOCodeData('', '', 'Lushai', 'lushai'),
|
||||||
|
'mac': ISOCodeData('mkd', 'mk', 'Macedonian', 'macédonien'),
|
||||||
|
'mad': ISOCodeData('', '', 'Madurese', 'madourais'),
|
||||||
|
'mag': ISOCodeData('', '', 'Magahi', 'magahi'),
|
||||||
|
'mah': ISOCodeData('', 'mh', 'Marshallese', 'marshall'),
|
||||||
|
'mai': ISOCodeData('', '', 'Maithili', 'maithili'),
|
||||||
|
'mak': ISOCodeData('', '', 'Makasar', 'makassar'),
|
||||||
|
'mal': ISOCodeData('', 'ml', 'Malayalam', 'malayalam'),
|
||||||
|
'man': ISOCodeData('', '', 'Mandingo', 'mandingue'),
|
||||||
|
'mao': ISOCodeData('mri', 'mi', 'Maori', 'maori'),
|
||||||
|
'map': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Austronesian languages',
|
||||||
|
'austronésiennes, langues',
|
||||||
|
),
|
||||||
|
'mar': ISOCodeData('', 'mr', 'Marathi', 'marathe'),
|
||||||
|
'mas': ISOCodeData('', '', 'Masai', 'massaï'),
|
||||||
|
'may': ISOCodeData('msa', 'ms', 'Malay', 'malais'),
|
||||||
|
'mdf': ISOCodeData('', '', 'Moksha', 'moksa'),
|
||||||
|
'mdr': ISOCodeData('', '', 'Mandar', 'mandar'),
|
||||||
|
'men': ISOCodeData('', '', 'Mende', 'mendé'),
|
||||||
|
'mga': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Irish, Middle (900-1200)',
|
||||||
|
'irlandais moyen (900-1200)',
|
||||||
|
),
|
||||||
|
'mic': ISOCodeData('', '', "Mi'kmaq; Micmac", "mi'kmaq; micmac"),
|
||||||
|
'min': ISOCodeData('', '', 'Minangkabau', 'minangkabau'),
|
||||||
|
'mis': ISOCodeData('', '', 'Uncoded languages', 'langues non codées'),
|
||||||
|
'mkh': ISOCodeData('', '', 'Mon-Khmer languages', 'môn-khmer, langues'),
|
||||||
|
'mlg': ISOCodeData('', 'mg', 'Malagasy', 'malgache'),
|
||||||
|
'mlt': ISOCodeData('', 'mt', 'Maltese', 'maltais'),
|
||||||
|
'mnc': ISOCodeData('', '', 'Manchu', 'mandchou'),
|
||||||
|
'mni': ISOCodeData('', '', 'Manipuri', 'manipuri'),
|
||||||
|
'mno': ISOCodeData('', '', 'Manobo languages', 'manobo, langues'),
|
||||||
|
'moh': ISOCodeData('', '', 'Mohawk', 'mohawk'),
|
||||||
|
'mon': ISOCodeData('', 'mn', 'Mongolian', 'mongol'),
|
||||||
|
'mos': ISOCodeData('', '', 'Mossi', 'moré'),
|
||||||
|
'mul': ISOCodeData('', '', 'Multiple languages', 'multilingue'),
|
||||||
|
'mun': ISOCodeData('', '', 'Munda languages', 'mounda, langues'),
|
||||||
|
'mus': ISOCodeData('', '', 'Creek', 'muskogee'),
|
||||||
|
'mwl': ISOCodeData('', '', 'Mirandese', 'mirandais'),
|
||||||
|
'mwr': ISOCodeData('', '', 'Marwari', 'marvari'),
|
||||||
|
'myn': ISOCodeData('', '', 'Mayan languages', 'maya, langues'),
|
||||||
|
'myv': ISOCodeData('', '', 'Erzya', 'erza'),
|
||||||
|
'nah': ISOCodeData('', '', 'Nahuatl languages', 'nahuatl, langues'),
|
||||||
|
'nai': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'North American Indian languages',
|
||||||
|
'nord-amérindiennes, langues',
|
||||||
|
),
|
||||||
|
'nap': ISOCodeData('', '', 'Neapolitan', 'napolitain'),
|
||||||
|
'nau': ISOCodeData('', 'na', 'Nauru', 'nauruan'),
|
||||||
|
'nav': ISOCodeData('', 'nv', 'Navajo; Navaho', 'navaho'),
|
||||||
|
'nbl': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'nr',
|
||||||
|
'Ndebele, South; South Ndebele',
|
||||||
|
'ndébélé du Sud',
|
||||||
|
),
|
||||||
|
'nde': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'nd',
|
||||||
|
'Ndebele, North; North Ndebele',
|
||||||
|
'ndébélé du Nord',
|
||||||
|
),
|
||||||
|
'ndo': ISOCodeData('', 'ng', 'Ndonga', 'ndonga'),
|
||||||
|
'nds': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Low German; Low Saxon; German, Low; Saxon, Low',
|
||||||
|
'bas allemand; bas saxon; allemand, bas; saxon, bas',
|
||||||
|
),
|
||||||
|
'nep': ISOCodeData('', 'ne', 'Nepali', 'népalais'),
|
||||||
|
'new': ISOCodeData('', '', 'Nepal Bhasa; Newari', 'nepal bhasa; newari'),
|
||||||
|
'nia': ISOCodeData('', '', 'Nias', 'nias'),
|
||||||
|
'nic': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Niger-Kordofanian languages',
|
||||||
|
'nigéro-kordofaniennes, langues',
|
||||||
|
),
|
||||||
|
'niu': ISOCodeData('', '', 'Niuean', 'niué'),
|
||||||
|
'nno': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'nn',
|
||||||
|
'Norwegian Nynorsk; Nynorsk, Norwegian',
|
||||||
|
'norvégien nynorsk; nynorsk, norvégien',
|
||||||
|
),
|
||||||
|
'nob': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'nb',
|
||||||
|
'Bokmål, Norwegian; Norwegian Bokmål',
|
||||||
|
'norvégien bokmål',
|
||||||
|
),
|
||||||
|
'nog': ISOCodeData('', '', 'Nogai', 'nogaï; nogay'),
|
||||||
|
'non': ISOCodeData('', '', 'Norse, Old', 'norrois, vieux'),
|
||||||
|
'nor': ISOCodeData('', 'no', 'Norwegian', 'norvégien'),
|
||||||
|
'nqo': ISOCodeData('', '', "N'Ko", "n'ko"),
|
||||||
|
'nso': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Pedi; Sepedi; Northern Sotho',
|
||||||
|
'pedi; sepedi; sotho du Nord',
|
||||||
|
),
|
||||||
|
'nub': ISOCodeData('', '', 'Nubian languages', 'nubiennes, langues'),
|
||||||
|
'nwc': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Classical Newari; Old Newari; Classical Nepal Bhasa',
|
||||||
|
'newari classique',
|
||||||
|
),
|
||||||
|
'nya': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'ny',
|
||||||
|
'Chichewa; Chewa; Nyanja',
|
||||||
|
'chichewa; chewa; nyanja',
|
||||||
|
),
|
||||||
|
'nym': ISOCodeData('', '', 'Nyamwezi', 'nyamwezi'),
|
||||||
|
'nyn': ISOCodeData('', '', 'Nyankole', 'nyankolé'),
|
||||||
|
'nyo': ISOCodeData('', '', 'Nyoro', 'nyoro'),
|
||||||
|
'nzi': ISOCodeData('', '', 'Nzima', 'nzema'),
|
||||||
|
'oci': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'oc',
|
||||||
|
'Occitan (post 1500)',
|
||||||
|
'occitan (après 1500)',
|
||||||
|
),
|
||||||
|
'oji': ISOCodeData('', 'oj', 'Ojibwa', 'ojibwa'),
|
||||||
|
'ori': ISOCodeData('', 'or', 'Oriya', 'oriya'),
|
||||||
|
'orm': ISOCodeData('', 'om', 'Oromo', 'galla'),
|
||||||
|
'osa': ISOCodeData('', '', 'Osage', 'osage'),
|
||||||
|
'oss': ISOCodeData('', 'os', 'Ossetian; Ossetic', 'ossète'),
|
||||||
|
'ota': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Turkish, Ottoman (1500-1928)',
|
||||||
|
'turc ottoman (1500-1928)',
|
||||||
|
),
|
||||||
|
'oto': ISOCodeData('', '', 'Otomian languages', 'otomi, langues'),
|
||||||
|
'paa': ISOCodeData('', '', 'Papuan languages', 'papoues, langues'),
|
||||||
|
'pag': ISOCodeData('', '', 'Pangasinan', 'pangasinan'),
|
||||||
|
'pal': ISOCodeData('', '', 'Pahlavi', 'pahlavi'),
|
||||||
|
'pam': ISOCodeData('', '', 'Pampanga; Kapampangan', 'pampangan'),
|
||||||
|
'pan': ISOCodeData('', 'pa', 'Panjabi; Punjabi', 'pendjabi'),
|
||||||
|
'pap': ISOCodeData('', '', 'Papiamento', 'papiamento'),
|
||||||
|
'pau': ISOCodeData('', '', 'Palauan', 'palau'),
|
||||||
|
'peo': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Persian, Old (ca.600-400 B.C.)',
|
||||||
|
'perse, vieux (ca. 600-400 av. J.-C.)',
|
||||||
|
),
|
||||||
|
'per': ISOCodeData('fas', 'fa', 'Persian', 'persan'),
|
||||||
|
'phi': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Philippine languages',
|
||||||
|
'philippines, langues',
|
||||||
|
),
|
||||||
|
'phn': ISOCodeData('', '', 'Phoenician', 'phénicien'),
|
||||||
|
'pli': ISOCodeData('', 'pi', 'Pali', 'pali'),
|
||||||
|
'pol': ISOCodeData('', 'pl', 'Polish', 'polonais'),
|
||||||
|
'pon': ISOCodeData('', '', 'Pohnpeian', 'pohnpei'),
|
||||||
|
'por': ISOCodeData('', 'pt', 'Portuguese', 'portugais'),
|
||||||
|
'pra': ISOCodeData('', '', 'Prakrit languages', 'prâkrit, langues'),
|
||||||
|
'pro': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Provençal, Old (to 1500); Occitan, Old (to 1500)',
|
||||||
|
"provençal ancien (jusqu'à 1500); occitan ancien (jusqu'à 1500)",
|
||||||
|
),
|
||||||
|
'pus': ISOCodeData('', 'ps', 'Pushto; Pashto', 'pachto'),
|
||||||
|
'qaa': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Reserved for local use',
|
||||||
|
"réservée à l'usage local",
|
||||||
|
),
|
||||||
|
'que': ISOCodeData('', 'qu', 'Quechua', 'quechua'),
|
||||||
|
'raj': ISOCodeData('', '', 'Rajasthani', 'rajasthani'),
|
||||||
|
'rap': ISOCodeData('', '', 'Rapanui', 'rapanui'),
|
||||||
|
'rar': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Rarotongan; Cook Islands Maori',
|
||||||
|
'rarotonga; maori des îles Cook',
|
||||||
|
),
|
||||||
|
'roa': ISOCodeData('', '', 'Romance languages', 'romanes, langues'),
|
||||||
|
'roh': ISOCodeData('', 'rm', 'Romansh', 'romanche'),
|
||||||
|
'rom': ISOCodeData('', '', 'Romany', 'tsigane'),
|
||||||
|
'rum': ISOCodeData(
|
||||||
|
'ron',
|
||||||
|
'ro',
|
||||||
|
'Romanian; Moldavian; Moldovan',
|
||||||
|
'roumain; moldave',
|
||||||
|
),
|
||||||
|
'run': ISOCodeData('', 'rn', 'Rundi', 'rundi'),
|
||||||
|
'rup': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Aromanian; Arumanian; Macedo-Romanian',
|
||||||
|
'aroumain; macédo-roumain',
|
||||||
|
),
|
||||||
|
'rus': ISOCodeData('', 'ru', 'Russian', 'russe'),
|
||||||
|
'sad': ISOCodeData('', '', 'Sandawe', 'sandawe'),
|
||||||
|
'sag': ISOCodeData('', 'sg', 'Sango', 'sango'),
|
||||||
|
'sah': ISOCodeData('', '', 'Yakut', 'iakoute'),
|
||||||
|
'sai': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'South American Indian languages',
|
||||||
|
'sud-amérindiennes, langues',
|
||||||
|
),
|
||||||
|
'sal': ISOCodeData('', '', 'Salishan languages', 'salishennes, langues'),
|
||||||
|
'sam': ISOCodeData('', '', 'Samaritan Aramaic', 'samaritain'),
|
||||||
|
'san': ISOCodeData('', 'sa', 'Sanskrit', 'sanskrit'),
|
||||||
|
'sas': ISOCodeData('', '', 'Sasak', 'sasak'),
|
||||||
|
'sat': ISOCodeData('', '', 'Santali', 'santal'),
|
||||||
|
'scn': ISOCodeData('', '', 'Sicilian', 'sicilien'),
|
||||||
|
'sco': ISOCodeData('', '', 'Scots', 'écossais'),
|
||||||
|
'sel': ISOCodeData('', '', 'Selkup', 'selkoupe'),
|
||||||
|
'sem': ISOCodeData('', '', 'Semitic languages', 'sémitiques, langues'),
|
||||||
|
'sga': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Irish, Old (to 900)',
|
||||||
|
"irlandais ancien (jusqu'à 900)",
|
||||||
|
),
|
||||||
|
'sgn': ISOCodeData('', '', 'Sign Languages', 'langues des signes'),
|
||||||
|
'shn': ISOCodeData('', '', 'Shan', 'chan'),
|
||||||
|
'sid': ISOCodeData('', '', 'Sidamo', 'sidamo'),
|
||||||
|
'sin': ISOCodeData('', 'si', 'Sinhala; Sinhalese', 'singhalais'),
|
||||||
|
'sio': ISOCodeData('', '', 'Siouan languages', 'sioux, langues'),
|
||||||
|
'sit': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Sino-Tibetan languages',
|
||||||
|
'sino-tibétaines, langues',
|
||||||
|
),
|
||||||
|
'sla': ISOCodeData('', '', 'Slavic languages', 'slaves, langues'),
|
||||||
|
'slo': ISOCodeData('slk', 'sk', 'Slovak', 'slovaque'),
|
||||||
|
'slv': ISOCodeData('', 'sl', 'Slovenian', 'slovène'),
|
||||||
|
'sma': ISOCodeData('', '', 'Southern Sami', 'sami du Sud'),
|
||||||
|
'sme': ISOCodeData('', 'se', 'Northern Sami', 'sami du Nord'),
|
||||||
|
'smi': ISOCodeData('', '', 'Sami languages', 'sames, langues'),
|
||||||
|
'smj': ISOCodeData('', '', 'Lule Sami', 'sami de Lule'),
|
||||||
|
'smn': ISOCodeData('', '', 'Inari Sami', "sami d'Inari"),
|
||||||
|
'smo': ISOCodeData('', 'sm', 'Samoan', 'samoan'),
|
||||||
|
'sms': ISOCodeData('', '', 'Skolt Sami', 'sami skolt'),
|
||||||
|
'sna': ISOCodeData('', 'sn', 'Shona', 'shona'),
|
||||||
|
'snd': ISOCodeData('', 'sd', 'Sindhi', 'sindhi'),
|
||||||
|
'snk': ISOCodeData('', '', 'Soninke', 'soninké'),
|
||||||
|
'sog': ISOCodeData('', '', 'Sogdian', 'sogdien'),
|
||||||
|
'som': ISOCodeData('', 'so', 'Somali', 'somali'),
|
||||||
|
'son': ISOCodeData('', '', 'Songhai languages', 'songhai, langues'),
|
||||||
|
'sot': ISOCodeData('', 'st', 'Sotho, Southern', 'sotho du Sud'),
|
||||||
|
'spa': ISOCodeData('', 'es', 'Spanish; Castilian', 'espagnol; castillan'),
|
||||||
|
'srd': ISOCodeData('', 'sc', 'Sardinian', 'sarde'),
|
||||||
|
'srn': ISOCodeData('', '', 'Sranan Tongo', 'sranan tongo'),
|
||||||
|
'srp': ISOCodeData('', 'sr', 'Serbian', 'serbe'),
|
||||||
|
'srr': ISOCodeData('', '', 'Serer', 'sérère'),
|
||||||
|
'ssa': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Nilo-Saharan languages',
|
||||||
|
'nilo-sahariennes, langues',
|
||||||
|
),
|
||||||
|
'ssw': ISOCodeData('', 'ss', 'Swati', 'swati'),
|
||||||
|
'suk': ISOCodeData('', '', 'Sukuma', 'sukuma'),
|
||||||
|
'sun': ISOCodeData('', 'su', 'Sundanese', 'soundanais'),
|
||||||
|
'sus': ISOCodeData('', '', 'Susu', 'soussou'),
|
||||||
|
'sux': ISOCodeData('', '', 'Sumerian', 'sumérien'),
|
||||||
|
'swa': ISOCodeData('', 'sw', 'Swahili', 'swahili'),
|
||||||
|
'swe': ISOCodeData('', 'sv', 'Swedish', 'suédois'),
|
||||||
|
'syc': ISOCodeData('', '', 'Classical Syriac', 'syriaque classique'),
|
||||||
|
'syr': ISOCodeData('', '', 'Syriac', 'syriaque'),
|
||||||
|
'tah': ISOCodeData('', 'ty', 'Tahitian', 'tahitien'),
|
||||||
|
'tai': ISOCodeData('', '', 'Tai languages', 'tai, langues'),
|
||||||
|
'tam': ISOCodeData('', 'ta', 'Tamil', 'tamoul'),
|
||||||
|
'tat': ISOCodeData('', 'tt', 'Tatar', 'tatar'),
|
||||||
|
'tel': ISOCodeData('', 'te', 'Telugu', 'télougou'),
|
||||||
|
'tem': ISOCodeData('', '', 'Timne', 'temne'),
|
||||||
|
'ter': ISOCodeData('', '', 'Tereno', 'tereno'),
|
||||||
|
'tet': ISOCodeData('', '', 'Tetum', 'tetum'),
|
||||||
|
'tgk': ISOCodeData('', 'tg', 'Tajik', 'tadjik'),
|
||||||
|
'tgl': ISOCodeData('', 'tl', 'Tagalog', 'tagalog'),
|
||||||
|
'tha': ISOCodeData('', 'th', 'Thai', 'thaï'),
|
||||||
|
'tib': ISOCodeData('bod', 'bo', 'Tibetan', 'tibétain'),
|
||||||
|
'tig': ISOCodeData('', '', 'Tigre', 'tigré'),
|
||||||
|
'tir': ISOCodeData('', 'ti', 'Tigrinya', 'tigrigna'),
|
||||||
|
'tiv': ISOCodeData('', '', 'Tiv', 'tiv'),
|
||||||
|
'tkl': ISOCodeData('', '', 'Tokelau', 'tokelau'),
|
||||||
|
'tlh': ISOCodeData('', '', 'Klingon; tlhIngan-Hol', 'klingon'),
|
||||||
|
'tli': ISOCodeData('', '', 'Tlingit', 'tlingit'),
|
||||||
|
'tmh': ISOCodeData('', '', 'Tamashek', 'tamacheq'),
|
||||||
|
'tog': ISOCodeData('', '', 'Tonga (Nyasa)', 'tonga (Nyasa)'),
|
||||||
|
'ton': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'to',
|
||||||
|
'Tonga (Tonga Islands)',
|
||||||
|
'tongan (Îles Tonga)',
|
||||||
|
),
|
||||||
|
'tpi': ISOCodeData('', '', 'Tok Pisin', 'tok pisin'),
|
||||||
|
'tsi': ISOCodeData('', '', 'Tsimshian', 'tsimshian'),
|
||||||
|
'tsn': ISOCodeData('', 'tn', 'Tswana', 'tswana'),
|
||||||
|
'tso': ISOCodeData('', 'ts', 'Tsonga', 'tsonga'),
|
||||||
|
'tuk': ISOCodeData('', 'tk', 'Turkmen', 'turkmène'),
|
||||||
|
'tum': ISOCodeData('', '', 'Tumbuka', 'tumbuka'),
|
||||||
|
'tup': ISOCodeData('', '', 'Tupi languages', 'tupi, langues'),
|
||||||
|
'tur': ISOCodeData('', 'tr', 'Turkish', 'turc'),
|
||||||
|
'tut': ISOCodeData('', '', 'Altaic languages', 'altaïques, langues'),
|
||||||
|
'tvl': ISOCodeData('', '', 'Tuvalu', 'tuvalu'),
|
||||||
|
'twi': ISOCodeData('', 'tw', 'Twi', 'twi'),
|
||||||
|
'tyv': ISOCodeData('', '', 'Tuvinian', 'touva'),
|
||||||
|
'udm': ISOCodeData('', '', 'Udmurt', 'oudmourte'),
|
||||||
|
'uga': ISOCodeData('', '', 'Ugaritic', 'ougaritique'),
|
||||||
|
'uig': ISOCodeData('', 'ug', 'Uighur; Uyghur', 'ouïgour'),
|
||||||
|
'ukr': ISOCodeData('', 'uk', 'Ukrainian', 'ukrainien'),
|
||||||
|
'umb': ISOCodeData('', '', 'Umbundu', 'umbundu'),
|
||||||
|
'und': ISOCodeData('', '', 'Undetermined', 'indéterminée'),
|
||||||
|
'urd': ISOCodeData('', 'ur', 'Urdu', 'ourdou'),
|
||||||
|
'uzb': ISOCodeData('', 'uz', 'Uzbek', 'ouszbek'),
|
||||||
|
'vai': ISOCodeData('', '', 'Vai', 'vaï'),
|
||||||
|
'ven': ISOCodeData('', 've', 'Venda', 'venda'),
|
||||||
|
'vie': ISOCodeData('', 'vi', 'Vietnamese', 'vietnamien'),
|
||||||
|
'vol': ISOCodeData('', 'vo', 'Volapük', 'volapük'),
|
||||||
|
'vot': ISOCodeData('', '', 'Votic', 'vote'),
|
||||||
|
'wak': ISOCodeData('', '', 'Wakashan languages', 'wakashanes, langues'),
|
||||||
|
'wal': ISOCodeData('', '', 'Wolaitta; Wolaytta', 'wolaitta; wolaytta'),
|
||||||
|
'war': ISOCodeData('', '', 'Waray', 'waray'),
|
||||||
|
'was': ISOCodeData('', '', 'Washo', 'washo'),
|
||||||
|
'wel': ISOCodeData('cym', 'cy', 'Welsh', 'gallois'),
|
||||||
|
'wen': ISOCodeData('', '', 'Sorbian languages', 'sorabes, langues'),
|
||||||
|
'wln': ISOCodeData('', 'wa', 'Walloon', 'wallon'),
|
||||||
|
'wol': ISOCodeData('', 'wo', 'Wolof', 'wolof'),
|
||||||
|
'xal': ISOCodeData('', '', 'Kalmyk; Oirat', 'kalmouk; oïrat'),
|
||||||
|
'xho': ISOCodeData('', 'xh', 'Xhosa', 'xhosa'),
|
||||||
|
'yao': ISOCodeData('', '', 'Yao', 'yao'),
|
||||||
|
'yap': ISOCodeData('', '', 'Yapese', 'yapois'),
|
||||||
|
'yid': ISOCodeData('', 'yi', 'Yiddish', 'yiddish'),
|
||||||
|
'yor': ISOCodeData('', 'yo', 'Yoruba', 'yoruba'),
|
||||||
|
'ypk': ISOCodeData('', '', 'Yupik languages', 'yupik, langues'),
|
||||||
|
'zap': ISOCodeData('', '', 'Zapotec', 'zapotèque'),
|
||||||
|
'zbl': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Blissymbols; Blissymbolics; Bliss',
|
||||||
|
'symboles Bliss; Bliss',
|
||||||
|
),
|
||||||
|
'zen': ISOCodeData('', '', 'Zenaga', 'zenaga'),
|
||||||
|
'zgh': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Standard Moroccan Tamazight',
|
||||||
|
'amazighe standard marocain',
|
||||||
|
),
|
||||||
|
'zha': ISOCodeData('', 'za', 'Zhuang; Chuang', 'zhuang; chuang'),
|
||||||
|
'znd': ISOCodeData('', '', 'Zande languages', 'zandé, langues'),
|
||||||
|
'zul': ISOCodeData('', 'zu', 'Zulu', 'zoulou'),
|
||||||
|
'zun': ISOCodeData('', '', 'Zuni', 'zuni'),
|
||||||
|
'zxx': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'No linguistic content; Not applicable',
|
||||||
|
'pas de contenu linguistique; non applicable',
|
||||||
|
),
|
||||||
|
'zza': ISOCodeData(
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'Zaza; Dimili; Dimli; Kirdki; Kirmanjki; Zazaki',
|
||||||
|
'zaza; dimili; dimli; kirdki; kirmanjki; zazaki',
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def iso_639_2_from_3(iso3: str) -> str:
|
||||||
|
"""Convert ISO 639-3 code to ISO 639-2 code."""
|
||||||
|
if iso3 in ISO_639_3:
|
||||||
|
return ISO_639_3[iso3].alpha_2
|
||||||
|
else:
|
||||||
|
return ""
|
||||||
+150
-95
@@ -11,9 +11,11 @@ import sys
|
|||||||
import tempfile
|
import tempfile
|
||||||
import threading
|
import threading
|
||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
|
from collections.abc import Iterator, MutableSet, Sequence
|
||||||
from os import fspath
|
from os import fspath
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Callable, Iterator, MutableSet, NamedTuple, NewType, Sequence
|
from typing import Any, Callable, NamedTuple, NewType
|
||||||
|
from warnings import warn
|
||||||
from zlib import compress
|
from zlib import compress
|
||||||
|
|
||||||
import img2pdf
|
import img2pdf
|
||||||
@@ -33,6 +35,7 @@ from PIL import Image
|
|||||||
from ocrmypdf._concurrent import Executor, SerialExecutor
|
from ocrmypdf._concurrent import Executor, SerialExecutor
|
||||||
from ocrmypdf._exec import jbig2enc, pngquant
|
from ocrmypdf._exec import jbig2enc, pngquant
|
||||||
from ocrmypdf._jobcontext import PdfContext
|
from ocrmypdf._jobcontext import PdfContext
|
||||||
|
from ocrmypdf._progressbar import ProgressBar
|
||||||
from ocrmypdf.exceptions import OutputFileAccessError
|
from ocrmypdf.exceptions import OutputFileAccessError
|
||||||
from ocrmypdf.helpers import IMG2PDF_KWARGS, safe_symlink
|
from ocrmypdf.helpers import IMG2PDF_KWARGS, safe_symlink
|
||||||
|
|
||||||
@@ -53,23 +56,24 @@ class XrefExt(NamedTuple):
|
|||||||
|
|
||||||
|
|
||||||
def img_name(root: Path, xref: Xref, ext: str) -> Path:
|
def img_name(root: Path, xref: Xref, ext: str) -> Path:
|
||||||
|
"""Return the name of an image file for a given xref and extension."""
|
||||||
return root / f'{xref:08d}{ext}'
|
return root / f'{xref:08d}{ext}'
|
||||||
|
|
||||||
|
|
||||||
def png_name(root: Path, xref: Xref) -> Path:
|
def png_name(root: Path, xref: Xref) -> Path:
|
||||||
|
"""Return the name of a PNG file for a given xref."""
|
||||||
return img_name(root, xref, '.png')
|
return img_name(root, xref, '.png')
|
||||||
|
|
||||||
|
|
||||||
def jpg_name(root: Path, xref: Xref) -> Path:
|
def jpg_name(root: Path, xref: Xref) -> Path:
|
||||||
|
"""Return the name of a JPEG file for a given xref."""
|
||||||
return img_name(root, xref, '.jpg')
|
return img_name(root, xref, '.jpg')
|
||||||
|
|
||||||
|
|
||||||
def extract_image_filter(
|
def extract_image_filter(
|
||||||
pike: Pdf, root: Path, image: Stream, xref: Xref
|
image: Stream, xref: Xref
|
||||||
) -> tuple[PdfImage, tuple[Name, Object]] | None:
|
) -> tuple[PdfImage, tuple[Name, Object]] | None:
|
||||||
del pike # unused args
|
"""Determine if an image is extractable."""
|
||||||
del root
|
|
||||||
|
|
||||||
if image.Subtype != Name.Image:
|
if image.Subtype != Name.Image:
|
||||||
return None
|
return None
|
||||||
if image.Length < 100:
|
if image.Length < 100:
|
||||||
@@ -122,11 +126,12 @@ def extract_image_filter(
|
|||||||
|
|
||||||
|
|
||||||
def extract_image_jbig2(
|
def extract_image_jbig2(
|
||||||
*, pike: Pdf, root: Path, image: Stream, xref: Xref, options
|
*, pdf: Pdf, root: Path, image: Stream, xref: Xref, options
|
||||||
) -> XrefExt | None:
|
) -> XrefExt | None:
|
||||||
|
"""Extract an image, saving it as a JBIG2 file."""
|
||||||
del options # unused arg
|
del options # unused arg
|
||||||
|
|
||||||
result = extract_image_filter(pike, root, image, xref)
|
result = extract_image_filter(image, xref)
|
||||||
if result is None:
|
if result is None:
|
||||||
return None
|
return None
|
||||||
pim, filtdp = result
|
pim, filtdp = result
|
||||||
@@ -163,9 +168,10 @@ def extract_image_jbig2(
|
|||||||
|
|
||||||
|
|
||||||
def extract_image_generic(
|
def extract_image_generic(
|
||||||
*, pike: Pdf, root: Path, image: Stream, xref: Xref, options
|
*, pdf: Pdf, root: Path, image: Stream, xref: Xref, options
|
||||||
) -> XrefExt | None:
|
) -> XrefExt | None:
|
||||||
result = extract_image_filter(pike, root, image, xref)
|
"""Generic image extraction."""
|
||||||
|
result = extract_image_filter(image, xref)
|
||||||
if result is None:
|
if result is None:
|
||||||
return None
|
return None
|
||||||
pim, filtdp = result
|
pim, filtdp = result
|
||||||
@@ -224,13 +230,72 @@ def extract_image_generic(
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _find_image_xrefs_container(
|
||||||
|
pdf: Pdf,
|
||||||
|
container: Object,
|
||||||
|
pageno: int,
|
||||||
|
include_xrefs: MutableSet[Xref],
|
||||||
|
exclude_xrefs: MutableSet[Xref],
|
||||||
|
pageno_for_xref: dict[Xref, int],
|
||||||
|
depth: int = 0,
|
||||||
|
):
|
||||||
|
"""Find all image XRefs or Form XObject and add to the include/exclude sets."""
|
||||||
|
if depth > 10:
|
||||||
|
log.warning("Recursion depth exceeded in _find_image_xrefs_page")
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
xobjs = container.Resources.XObject
|
||||||
|
except AttributeError:
|
||||||
|
return
|
||||||
|
for _imname, image in dict(xobjs).items():
|
||||||
|
if image.objgen[1] != 0:
|
||||||
|
continue # Ignore images in an incremental PDF
|
||||||
|
if Name.Subtype in image and image.Subtype == Name.Form:
|
||||||
|
# Recurse into Form XObjects
|
||||||
|
log.debug(f"Recursing into Form XObject {_imname} in page {pageno}")
|
||||||
|
_find_image_xrefs_container(
|
||||||
|
pdf,
|
||||||
|
image,
|
||||||
|
pageno,
|
||||||
|
include_xrefs,
|
||||||
|
exclude_xrefs,
|
||||||
|
pageno_for_xref,
|
||||||
|
depth + 1,
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
xref = Xref(image.objgen[0])
|
||||||
|
if Name.SMask in image:
|
||||||
|
# Ignore soft masks
|
||||||
|
smask_xref = Xref(image.SMask.objgen[0])
|
||||||
|
exclude_xrefs.add(smask_xref)
|
||||||
|
log.debug(f"xref {smask_xref}: skipping image because it is an SMask")
|
||||||
|
include_xrefs.add(xref)
|
||||||
|
log.debug(f"xref {xref}: treating as an optimization candidate")
|
||||||
|
if xref not in pageno_for_xref:
|
||||||
|
pageno_for_xref[xref] = pageno
|
||||||
|
|
||||||
|
|
||||||
|
def _find_image_xrefs(pdf: Pdf):
|
||||||
|
include_xrefs: MutableSet[Xref] = set()
|
||||||
|
exclude_xrefs: MutableSet[Xref] = set()
|
||||||
|
pageno_for_xref: dict[Xref, int] = {}
|
||||||
|
|
||||||
|
for pageno, page in enumerate(pdf.pages):
|
||||||
|
_find_image_xrefs_container(
|
||||||
|
pdf, page.obj, pageno, include_xrefs, exclude_xrefs, pageno_for_xref
|
||||||
|
)
|
||||||
|
|
||||||
|
working_xrefs = include_xrefs - exclude_xrefs
|
||||||
|
return working_xrefs, pageno_for_xref
|
||||||
|
|
||||||
|
|
||||||
def extract_images(
|
def extract_images(
|
||||||
pike: Pdf,
|
pdf: Pdf,
|
||||||
root: Path,
|
root: Path,
|
||||||
options,
|
options,
|
||||||
extract_fn: Callable[..., XrefExt | None],
|
extract_fn: Callable[..., XrefExt | None],
|
||||||
) -> Iterator[tuple[int, XrefExt]]:
|
) -> Iterator[tuple[int, XrefExt]]:
|
||||||
"""Extract image using extract_fn
|
"""Extract image using extract_fn.
|
||||||
|
|
||||||
Enumerate images on each page, lookup their xref/ID number in the PDF.
|
Enumerate images on each page, lookup their xref/ID number in the PDF.
|
||||||
Exclude images that are soft masks (i.e. alpha transparency related).
|
Exclude images that are soft masks (i.e. alpha transparency related).
|
||||||
@@ -244,36 +309,13 @@ def extract_images(
|
|||||||
it does a tuple should be returned: (xref, ext) where .ext is the file
|
it does a tuple should be returned: (xref, ext) where .ext is the file
|
||||||
extension. extract_fn must also extract the file it finds interesting.
|
extension. extract_fn must also extract the file it finds interesting.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
include_xrefs: MutableSet[Xref] = set()
|
|
||||||
exclude_xrefs: MutableSet[Xref] = set()
|
|
||||||
pageno_for_xref = {}
|
|
||||||
errors = 0
|
errors = 0
|
||||||
for pageno, page in enumerate(pike.pages):
|
working_xrefs, pageno_for_xref = _find_image_xrefs(pdf)
|
||||||
try:
|
|
||||||
xobjs = page.Resources.XObject
|
|
||||||
except AttributeError:
|
|
||||||
continue
|
|
||||||
for _imname, image in dict(xobjs).items():
|
|
||||||
if image.objgen[1] != 0:
|
|
||||||
continue # Ignore images in an incremental PDF
|
|
||||||
xref = Xref(image.objgen[0])
|
|
||||||
if Name.SMask in image:
|
|
||||||
# Ignore soft masks
|
|
||||||
smask_xref = Xref(image.SMask.objgen[0])
|
|
||||||
exclude_xrefs.add(smask_xref)
|
|
||||||
log.debug(f"xref {smask_xref}: skipping image because it is an SMask")
|
|
||||||
include_xrefs.add(xref)
|
|
||||||
log.debug(f"xref {xref}: treating as an optimization candidate")
|
|
||||||
if xref not in pageno_for_xref:
|
|
||||||
pageno_for_xref[xref] = pageno
|
|
||||||
|
|
||||||
working_xrefs = include_xrefs - exclude_xrefs
|
|
||||||
for xref in working_xrefs:
|
for xref in working_xrefs:
|
||||||
image = pike.get_object((xref, 0))
|
image = pdf.get_object((xref, 0))
|
||||||
try:
|
try:
|
||||||
result = extract_fn(
|
result = extract_fn(
|
||||||
pike=pike, root=root, image=image, xref=xref, options=options
|
pdf=pdf, root=root, image=image, xref=xref, options=options
|
||||||
)
|
)
|
||||||
except Exception: # pylint: disable=broad-except
|
except Exception: # pylint: disable=broad-except
|
||||||
log.exception(
|
log.exception(
|
||||||
@@ -287,13 +329,12 @@ def extract_images(
|
|||||||
|
|
||||||
|
|
||||||
def extract_images_generic(
|
def extract_images_generic(
|
||||||
pike: Pdf, root: Path, options
|
pdf: Pdf, root: Path, options
|
||||||
) -> tuple[list[Xref], list[Xref]]:
|
) -> tuple[list[Xref], list[Xref]]:
|
||||||
"""Extract any >=2bpp image we think we can improve"""
|
"""Extract any >=2bpp image we think we can improve."""
|
||||||
|
|
||||||
jpegs = []
|
jpegs = []
|
||||||
pngs = []
|
pngs = []
|
||||||
for _, xref_ext in extract_images(pike, root, options, extract_image_generic):
|
for _, xref_ext in extract_images(pdf, root, options, extract_image_generic):
|
||||||
log.debug('%s', xref_ext)
|
log.debug('%s', xref_ext)
|
||||||
if xref_ext.ext == '.png':
|
if xref_ext.ext == '.png':
|
||||||
pngs.append(xref_ext.xref)
|
pngs.append(xref_ext.xref)
|
||||||
@@ -303,11 +344,10 @@ def extract_images_generic(
|
|||||||
return jpegs, pngs
|
return jpegs, pngs
|
||||||
|
|
||||||
|
|
||||||
def extract_images_jbig2(pike: Pdf, root: Path, options) -> dict[int, list[XrefExt]]:
|
def extract_images_jbig2(pdf: Pdf, root: Path, options) -> dict[int, list[XrefExt]]:
|
||||||
"""Extract any bitonal image that we think we can improve as JBIG2"""
|
"""Extract any bitonal image that we think we can improve as JBIG2."""
|
||||||
|
|
||||||
jbig2_groups = defaultdict(list)
|
jbig2_groups = defaultdict(list)
|
||||||
for pageno, xref_ext in extract_images(pike, root, options, extract_image_jbig2):
|
for pageno, xref_ext in extract_images(pdf, root, options, extract_image_jbig2):
|
||||||
group = pageno // options.jbig2_page_group_size
|
group = pageno // options.jbig2_page_group_size
|
||||||
jbig2_groups[group].append(xref_ext)
|
jbig2_groups[group].append(xref_ext)
|
||||||
|
|
||||||
@@ -318,7 +358,7 @@ def extract_images_jbig2(pike: Pdf, root: Path, options) -> dict[int, list[XrefE
|
|||||||
def _produce_jbig2_images(
|
def _produce_jbig2_images(
|
||||||
jbig2_groups: dict[int, list[XrefExt]], root: Path, options, executor: Executor
|
jbig2_groups: dict[int, list[XrefExt]], root: Path, options, executor: Executor
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Produce JBIG2 images from their groups"""
|
"""Produce JBIG2 images from their groups."""
|
||||||
|
|
||||||
def jbig2_group_args(root: Path, groups: dict[int, list[XrefExt]]):
|
def jbig2_group_args(root: Path, groups: dict[int, list[XrefExt]]):
|
||||||
for group, xref_exts in groups.items():
|
for group, xref_exts in groups.items():
|
||||||
@@ -327,9 +367,10 @@ def _produce_jbig2_images(
|
|||||||
fspath(root), # =cwd
|
fspath(root), # =cwd
|
||||||
(img_name(root, xref, ext) for xref, ext in xref_exts), # =infiles
|
(img_name(root, xref, ext) for xref, ext in xref_exts), # =infiles
|
||||||
prefix, # =out_prefix
|
prefix, # =out_prefix
|
||||||
|
options.jbig2_threshold,
|
||||||
)
|
)
|
||||||
|
|
||||||
def jbig2_single_args(root, groups: dict[int, list[XrefExt]]):
|
def jbig2_single_args(root: Path, groups: dict[int, list[XrefExt]]):
|
||||||
for group, xref_exts in groups.items():
|
for group, xref_exts in groups.items():
|
||||||
prefix = f'group{group:08d}'
|
prefix = f'group{group:08d}'
|
||||||
# Second loop is to ensure multiple images per page are unpacked
|
# Second loop is to ensure multiple images per page are unpacked
|
||||||
@@ -339,19 +380,20 @@ def _produce_jbig2_images(
|
|||||||
fspath(root),
|
fspath(root),
|
||||||
img_name(root, xref, ext),
|
img_name(root, xref, ext),
|
||||||
root / f'{prefix}.{n:04d}',
|
root / f'{prefix}.{n:04d}',
|
||||||
|
options.jbig2_threshold,
|
||||||
)
|
)
|
||||||
|
|
||||||
if options.jbig2_page_group_size > 1:
|
if options.jbig2_page_group_size > 1:
|
||||||
jbig2_args = jbig2_group_args
|
jbig2_args = jbig2_group_args
|
||||||
jbig2_convert = jbig2enc.convert_group_mp
|
jbig2_convert = jbig2enc.convert_group
|
||||||
else:
|
else:
|
||||||
jbig2_args = jbig2_single_args
|
jbig2_args = jbig2_single_args
|
||||||
jbig2_convert = jbig2enc.convert_single_mp
|
jbig2_convert = jbig2enc.convert_single
|
||||||
|
|
||||||
executor(
|
executor(
|
||||||
use_threads=True,
|
use_threads=True,
|
||||||
max_workers=options.jobs,
|
max_workers=options.jobs,
|
||||||
tqdm_kwargs=dict(
|
progress_kwargs=dict(
|
||||||
total=len(jbig2_groups),
|
total=len(jbig2_groups),
|
||||||
desc="JBIG2",
|
desc="JBIG2",
|
||||||
unit='item',
|
unit='item',
|
||||||
@@ -363,7 +405,7 @@ def _produce_jbig2_images(
|
|||||||
|
|
||||||
|
|
||||||
def convert_to_jbig2(
|
def convert_to_jbig2(
|
||||||
pike: Pdf,
|
pdf: Pdf,
|
||||||
jbig2_groups: dict[int, list[XrefExt]],
|
jbig2_groups: dict[int, list[XrefExt]],
|
||||||
root: Path,
|
root: Path,
|
||||||
options,
|
options,
|
||||||
@@ -390,7 +432,7 @@ def convert_to_jbig2(
|
|||||||
jbig2_symfile = root / (prefix + '.sym')
|
jbig2_symfile = root / (prefix + '.sym')
|
||||||
if jbig2_symfile.exists():
|
if jbig2_symfile.exists():
|
||||||
jbig2_globals_data = jbig2_symfile.read_bytes()
|
jbig2_globals_data = jbig2_symfile.read_bytes()
|
||||||
jbig2_globals = Stream(pike, jbig2_globals_data)
|
jbig2_globals = Stream(pdf, jbig2_globals_data)
|
||||||
jbig2_globals_dict = Dictionary(JBIG2Globals=jbig2_globals)
|
jbig2_globals_dict = Dictionary(JBIG2Globals=jbig2_globals)
|
||||||
elif options.jbig2_page_group_size == 1:
|
elif options.jbig2_page_group_size == 1:
|
||||||
jbig2_globals_dict = None
|
jbig2_globals_dict = None
|
||||||
@@ -401,15 +443,15 @@ def convert_to_jbig2(
|
|||||||
xref, _ = xref_ext
|
xref, _ = xref_ext
|
||||||
jbig2_im_file = root / (prefix + f'.{n:04d}')
|
jbig2_im_file = root / (prefix + f'.{n:04d}')
|
||||||
jbig2_im_data = jbig2_im_file.read_bytes()
|
jbig2_im_data = jbig2_im_file.read_bytes()
|
||||||
im_obj = pike.get_object(xref, 0)
|
im_obj = pdf.get_object(xref, 0)
|
||||||
im_obj.write(
|
im_obj.write(
|
||||||
jbig2_im_data, filter=Name.JBIG2Decode, decode_parms=jbig2_globals_dict
|
jbig2_im_data, filter=Name.JBIG2Decode, decode_parms=jbig2_globals_dict
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def _optimize_jpeg(args: tuple[Xref, Path, Path, int]) -> tuple[Xref, Path | None]:
|
def _optimize_jpeg(
|
||||||
xref, in_jpg, opt_jpg, jpeg_quality = args
|
xref: Xref, in_jpg: Path, opt_jpg: Path, jpeg_quality: int
|
||||||
|
) -> tuple[Xref, Path | None]:
|
||||||
with Image.open(in_jpg) as im:
|
with Image.open(in_jpg) as im:
|
||||||
im.save(opt_jpg, optimize=True, quality=jpeg_quality)
|
im.save(opt_jpg, optimize=True, quality=jpeg_quality)
|
||||||
|
|
||||||
@@ -421,26 +463,28 @@ def _optimize_jpeg(args: tuple[Xref, Path, Path, int]) -> tuple[Xref, Path | Non
|
|||||||
|
|
||||||
|
|
||||||
def transcode_jpegs(
|
def transcode_jpegs(
|
||||||
pike: Pdf, jpegs: Sequence[Xref], root: Path, options, executor: Executor
|
pdf: Pdf, jpegs: Sequence[Xref], root: Path, options, executor: Executor
|
||||||
) -> None:
|
) -> None:
|
||||||
|
"""Optimize JPEGs according to optimization settings."""
|
||||||
|
|
||||||
def jpeg_args() -> Iterator[tuple[Xref, Path, Path, int]]:
|
def jpeg_args() -> Iterator[tuple[Xref, Path, Path, int]]:
|
||||||
for xref in jpegs:
|
for xref in jpegs:
|
||||||
in_jpg = jpg_name(root, xref)
|
in_jpg = jpg_name(root, xref)
|
||||||
opt_jpg = in_jpg.with_suffix('.opt.jpg')
|
opt_jpg = in_jpg.with_suffix('.opt.jpg')
|
||||||
yield xref, in_jpg, opt_jpg, options.jpeg_quality
|
yield xref, in_jpg, opt_jpg, options.jpeg_quality
|
||||||
|
|
||||||
def finish_jpeg(result: tuple[Xref, Path | None], pbar):
|
def finish_jpeg(result: tuple[Xref, Path | None], pbar: ProgressBar):
|
||||||
xref, opt_jpg = result
|
xref, opt_jpg = result
|
||||||
if opt_jpg:
|
if opt_jpg:
|
||||||
compdata = opt_jpg.read_bytes() # JPEG can inserted into PDF as is
|
compdata = opt_jpg.read_bytes() # JPEG can inserted into PDF as is
|
||||||
im_obj = pike.get_object(xref, 0)
|
im_obj = pdf.get_object(xref, 0)
|
||||||
im_obj.write(compdata, filter=Name.DCTDecode)
|
im_obj.write(compdata, filter=Name.DCTDecode)
|
||||||
pbar.update()
|
pbar.update()
|
||||||
|
|
||||||
executor(
|
executor(
|
||||||
use_threads=True, # Processes are significantly slower at this task
|
use_threads=True, # Processes are significantly slower at this task
|
||||||
max_workers=options.jobs,
|
max_workers=options.jobs,
|
||||||
tqdm_kwargs=dict(
|
progress_kwargs=dict(
|
||||||
desc="Recompressing JPEGs",
|
desc="Recompressing JPEGs",
|
||||||
total=len(jpegs),
|
total=len(jpegs),
|
||||||
unit='image',
|
unit='image',
|
||||||
@@ -453,9 +497,9 @@ def transcode_jpegs(
|
|||||||
|
|
||||||
|
|
||||||
def _find_deflatable_jpeg(
|
def _find_deflatable_jpeg(
|
||||||
*, pike: Pdf, root: Path, image: Stream, xref: Xref, options
|
*, pdf: Pdf, root: Path, image: Stream, xref: Xref, options
|
||||||
) -> XrefExt | None:
|
) -> XrefExt | None:
|
||||||
result = extract_image_filter(pike, root, image, xref)
|
result = extract_image_filter(image, xref)
|
||||||
if result is None:
|
if result is None:
|
||||||
return None
|
return None
|
||||||
_pim, filtdp = result
|
_pim, filtdp = result
|
||||||
@@ -466,10 +510,11 @@ def _find_deflatable_jpeg(
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def _deflate_jpeg(args: tuple[Pdf, threading.Lock, Xref, int]) -> tuple[Xref, bytes]:
|
def _deflate_jpeg(
|
||||||
pike, lock, xref, complevel = args
|
pdf: Pdf, lock: threading.Lock, xref: Xref, complevel: int
|
||||||
|
) -> tuple[Xref, bytes]:
|
||||||
with lock:
|
with lock:
|
||||||
xobj = pike.get_object(xref, 0)
|
xobj = pdf.get_object(xref, 0)
|
||||||
try:
|
try:
|
||||||
data = xobj.read_raw_bytes()
|
data = xobj.read_raw_bytes()
|
||||||
except PdfError:
|
except PdfError:
|
||||||
@@ -480,9 +525,15 @@ def _deflate_jpeg(args: tuple[Pdf, threading.Lock, Xref, int]) -> tuple[Xref, by
|
|||||||
return xref, compdata
|
return xref, compdata
|
||||||
|
|
||||||
|
|
||||||
def deflate_jpegs(pike: Pdf, root: Path, options, executor: Executor) -> None:
|
def deflate_jpegs(pdf: Pdf, root: Path, options, executor: Executor) -> None:
|
||||||
|
"""Apply FlateDecode to JPEGs.
|
||||||
|
|
||||||
|
This is a lossless compression method that is supported by all PDF viewers,
|
||||||
|
and generally results in a smaller file size compared to straight DCTDecode
|
||||||
|
images.
|
||||||
|
"""
|
||||||
jpegs = []
|
jpegs = []
|
||||||
for _pageno, xref_ext in extract_images(pike, root, options, _find_deflatable_jpeg):
|
for _pageno, xref_ext in extract_images(pdf, root, options, _find_deflatable_jpeg):
|
||||||
xref = xref_ext.xref
|
xref = xref_ext.xref
|
||||||
log.debug(f'xref {xref}: marking this JPEG as deflatable')
|
log.debug(f'xref {xref}: marking this JPEG as deflatable')
|
||||||
jpegs.append(xref)
|
jpegs.append(xref)
|
||||||
@@ -494,20 +545,20 @@ def deflate_jpegs(pike: Pdf, root: Path, options, executor: Executor) -> None:
|
|||||||
|
|
||||||
def deflate_args() -> Iterator:
|
def deflate_args() -> Iterator:
|
||||||
for xref in jpegs:
|
for xref in jpegs:
|
||||||
yield pike, lock, xref, complevel
|
yield pdf, lock, xref, complevel
|
||||||
|
|
||||||
def finish(result, pbar):
|
def finish(result: tuple[Xref, bytes], pbar: ProgressBar):
|
||||||
xref, compdata = result
|
xref, compdata = result
|
||||||
if len(compdata) > 0:
|
if len(compdata) > 0:
|
||||||
with lock:
|
with lock:
|
||||||
xobj = pike.get_object(xref, 0)
|
xobj = pdf.get_object(xref, 0)
|
||||||
xobj.write(compdata, filter=[Name.FlateDecode, Name.DCTDecode])
|
xobj.write(compdata, filter=[Name.FlateDecode, Name.DCTDecode])
|
||||||
pbar.update()
|
pbar.update()
|
||||||
|
|
||||||
executor(
|
executor(
|
||||||
use_threads=True, # We're sharing the pdf directly, must use threads
|
use_threads=True, # We're sharing the pdf directly, must use threads
|
||||||
max_workers=options.jobs,
|
max_workers=options.jobs,
|
||||||
tqdm_kwargs=dict(
|
progress_kwargs=dict(
|
||||||
desc="Deflating JPEGs",
|
desc="Deflating JPEGs",
|
||||||
total=len(jpegs),
|
total=len(jpegs),
|
||||||
unit='image',
|
unit='image',
|
||||||
@@ -519,16 +570,16 @@ def deflate_jpegs(pike: Pdf, root: Path, options, executor: Executor) -> None:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def _transcode_png(pike: Pdf, filename: Path, xref: Xref) -> bool:
|
def _transcode_png(pdf: Pdf, filename: Path, xref: Xref) -> bool:
|
||||||
output = filename.with_suffix('.png.pdf')
|
output = filename.with_suffix('.png.pdf')
|
||||||
with output.open('wb') as f:
|
with output.open('wb') as f:
|
||||||
img2pdf.convert(fspath(filename), outputstream=f, **IMG2PDF_KWARGS)
|
img2pdf.convert(fspath(filename), outputstream=f, **IMG2PDF_KWARGS)
|
||||||
|
|
||||||
with Pdf.open(output) as pdf_image:
|
with Pdf.open(output) as pdf_image:
|
||||||
foreign_image = next(iter(pdf_image.pages[0].images.values()))
|
foreign_image = next(iter(pdf_image.pages[0].images.values()))
|
||||||
local_image = pike.copy_foreign(foreign_image)
|
local_image = pdf.copy_foreign(foreign_image)
|
||||||
|
|
||||||
im_obj = pike.get_object(xref, 0)
|
im_obj = pdf.get_object(xref, 0)
|
||||||
im_obj.write(
|
im_obj.write(
|
||||||
local_image.read_raw_bytes(),
|
local_image.read_raw_bytes(),
|
||||||
filter=local_image.Filter,
|
filter=local_image.Filter,
|
||||||
@@ -561,13 +612,14 @@ def _transcode_png(pike: Pdf, filename: Path, xref: Xref) -> bool:
|
|||||||
|
|
||||||
|
|
||||||
def transcode_pngs(
|
def transcode_pngs(
|
||||||
pike: Pdf,
|
pdf: Pdf,
|
||||||
images: Sequence[Xref],
|
images: Sequence[Xref],
|
||||||
image_name_fn: Callable[[Path, Xref], Path],
|
image_name_fn: Callable[[Path, Xref], Path],
|
||||||
root: Path,
|
root: Path,
|
||||||
options,
|
options,
|
||||||
executor,
|
executor: Executor,
|
||||||
) -> None:
|
) -> None:
|
||||||
|
"""Apply lossy transcoding to PNGs."""
|
||||||
modified: MutableSet[Xref] = set()
|
modified: MutableSet[Xref] = set()
|
||||||
if options.optimize >= 2:
|
if options.optimize >= 2:
|
||||||
png_quality = (
|
png_quality = (
|
||||||
@@ -589,19 +641,19 @@ def transcode_pngs(
|
|||||||
executor(
|
executor(
|
||||||
use_threads=True,
|
use_threads=True,
|
||||||
max_workers=options.jobs,
|
max_workers=options.jobs,
|
||||||
tqdm_kwargs=dict(
|
progress_kwargs=dict(
|
||||||
desc="PNGs",
|
desc="PNGs",
|
||||||
total=len(images),
|
total=len(images),
|
||||||
unit='image',
|
unit='image',
|
||||||
disable=not options.progress_bar,
|
disable=not options.progress_bar,
|
||||||
),
|
),
|
||||||
task=pngquant.quantize_mp,
|
task=pngquant.quantize,
|
||||||
task_arguments=pngquant_args(),
|
task_arguments=pngquant_args(),
|
||||||
)
|
)
|
||||||
|
|
||||||
for xref in modified:
|
for xref in modified:
|
||||||
filename = png_name(root, xref)
|
filename = png_name(root, xref)
|
||||||
_transcode_png(pike, filename, xref)
|
_transcode_png(pdf, filename, xref)
|
||||||
|
|
||||||
|
|
||||||
DEFAULT_EXECUTOR = SerialExecutor()
|
DEFAULT_EXECUTOR = SerialExecutor()
|
||||||
@@ -610,10 +662,11 @@ DEFAULT_EXECUTOR = SerialExecutor()
|
|||||||
def optimize(
|
def optimize(
|
||||||
input_file: Path,
|
input_file: Path,
|
||||||
output_file: Path,
|
output_file: Path,
|
||||||
context,
|
context: PdfContext,
|
||||||
save_settings,
|
save_settings: dict[str, Any],
|
||||||
executor: Executor = DEFAULT_EXECUTOR,
|
executor: Executor = DEFAULT_EXECUTOR,
|
||||||
) -> Path:
|
) -> Path:
|
||||||
|
"""Optimize images in a PDF file."""
|
||||||
options = context.options
|
options = context.options
|
||||||
if options.optimize == 0:
|
if options.optimize == 0:
|
||||||
safe_symlink(input_file, output_file)
|
safe_symlink(input_file, output_file)
|
||||||
@@ -626,24 +679,24 @@ def optimize(
|
|||||||
if options.jbig2_page_group_size == 0:
|
if options.jbig2_page_group_size == 0:
|
||||||
options.jbig2_page_group_size = 10 if options.jbig2_lossy else 1
|
options.jbig2_page_group_size = 10 if options.jbig2_lossy else 1
|
||||||
|
|
||||||
with Pdf.open(input_file) as pike:
|
with Pdf.open(input_file) as pdf:
|
||||||
root = output_file.parent / 'images'
|
root = output_file.parent / 'images'
|
||||||
root.mkdir(exist_ok=True)
|
root.mkdir(exist_ok=True)
|
||||||
|
|
||||||
jpegs, pngs = extract_images_generic(pike, root, options)
|
jpegs, pngs = extract_images_generic(pdf, root, options)
|
||||||
transcode_jpegs(pike, jpegs, root, options, executor)
|
transcode_jpegs(pdf, jpegs, root, options, executor)
|
||||||
deflate_jpegs(pike, root, options, executor)
|
deflate_jpegs(pdf, root, options, executor)
|
||||||
# if options.optimize >= 2:
|
# if options.optimize >= 2:
|
||||||
# Try pngifying the jpegs
|
# Try pngifying the jpegs
|
||||||
# transcode_pngs(pike, jpegs, jpg_name, root, options)
|
# transcode_pngs(pdf, jpegs, jpg_name, root, options)
|
||||||
transcode_pngs(pike, pngs, png_name, root, options, executor)
|
transcode_pngs(pdf, pngs, png_name, root, options, executor)
|
||||||
|
|
||||||
jbig2_groups = extract_images_jbig2(pike, root, options)
|
jbig2_groups = extract_images_jbig2(pdf, root, options)
|
||||||
convert_to_jbig2(pike, jbig2_groups, root, options, executor)
|
convert_to_jbig2(pdf, jbig2_groups, root, options, executor)
|
||||||
|
|
||||||
target_file = output_file.with_suffix('.opt.pdf')
|
target_file = output_file.with_suffix('.opt.pdf')
|
||||||
pike.remove_unreferenced_resources()
|
pdf.remove_unreferenced_resources()
|
||||||
pike.save(target_file, **save_settings)
|
pdf.save(target_file, **save_settings)
|
||||||
|
|
||||||
input_size = input_file.stat().st_size
|
input_size = input_file.stat().st_size
|
||||||
output_size = target_file.stat().st_size
|
output_size = target_file.stat().st_size
|
||||||
@@ -660,9 +713,9 @@ def optimize(
|
|||||||
"optimizations will not be used"
|
"optimizations will not be used"
|
||||||
)
|
)
|
||||||
# We still need to save the file
|
# We still need to save the file
|
||||||
with Pdf.open(input_file) as pike:
|
with Pdf.open(input_file) as pdf:
|
||||||
pike.remove_unreferenced_resources()
|
pdf.remove_unreferenced_resources()
|
||||||
pike.save(output_file, **save_settings)
|
pdf.save(output_file, **save_settings)
|
||||||
else:
|
else:
|
||||||
safe_symlink(target_file, output_file)
|
safe_symlink(target_file, output_file)
|
||||||
|
|
||||||
@@ -670,11 +723,12 @@ def optimize(
|
|||||||
|
|
||||||
|
|
||||||
def main(infile, outfile, level, jobs=1):
|
def main(infile, outfile, level, jobs=1):
|
||||||
|
"""Entry point for direct optimization of a file."""
|
||||||
from shutil import copy # pylint: disable=import-outside-toplevel
|
from shutil import copy # pylint: disable=import-outside-toplevel
|
||||||
from tempfile import TemporaryDirectory # pylint: disable=import-outside-toplevel
|
from tempfile import TemporaryDirectory # pylint: disable=import-outside-toplevel
|
||||||
|
|
||||||
class OptimizeOptions:
|
class OptimizeOptions:
|
||||||
"""Emulate ocrmypdf's options"""
|
"""Emulate ocrmypdf's options."""
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self, input_file, jobs, optimize_, jpeg_quality, png_quality, jb2lossy
|
self, input_file, jobs, optimize_, jpeg_quality, png_quality, jb2lossy
|
||||||
@@ -686,6 +740,7 @@ def main(infile, outfile, level, jobs=1):
|
|||||||
self.png_quality = png_quality
|
self.png_quality = png_quality
|
||||||
self.jbig2_page_group_size = 0
|
self.jbig2_page_group_size = 0
|
||||||
self.jbig2_lossy = jb2lossy
|
self.jbig2_lossy = jb2lossy
|
||||||
|
self.jbig2_threshold = 0.85
|
||||||
self.quiet = True
|
self.quiet = True
|
||||||
self.progress_bar = False
|
self.progress_bar = False
|
||||||
|
|
||||||
|
|||||||
+7
-14
@@ -1,20 +1,14 @@
|
|||||||
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
# SPDX-FileCopyrightText: 2022 James R. Barlow
|
||||||
# SPDX-License-Identifier: MPL-2.0
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
|
|
||||||
"""
|
"""Utilities for PDF/A production and confirmation with Ghostspcript."""
|
||||||
Utilities for PDF/A production and confirmation with Ghostspcript.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import base64
|
import base64
|
||||||
|
from collections.abc import Iterator
|
||||||
|
from importlib.resources import files as package_files
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Iterator
|
|
||||||
|
|
||||||
try:
|
|
||||||
from importlib.resources import files as package_files
|
|
||||||
except ImportError:
|
|
||||||
from importlib_resources import files as package_files # type: ignore
|
|
||||||
|
|
||||||
import pikepdf
|
import pikepdf
|
||||||
|
|
||||||
@@ -25,8 +19,8 @@ def _postscript_objdef(
|
|||||||
alias: str,
|
alias: str,
|
||||||
dictionary: dict[str, str],
|
dictionary: dict[str, str],
|
||||||
*,
|
*,
|
||||||
stream_name: str = None,
|
stream_name: str | None = None,
|
||||||
stream_data: bytes = None,
|
stream_data: bytes | None = None,
|
||||||
) -> Iterator[str]:
|
) -> Iterator[str]:
|
||||||
assert (stream_name is None) == (stream_data is None)
|
assert (stream_name is None) == (stream_data is None)
|
||||||
|
|
||||||
@@ -75,7 +69,7 @@ def _make_postscript(icc_name: str, icc_data: bytes, colors: int) -> Iterator[st
|
|||||||
|
|
||||||
|
|
||||||
def generate_pdfa_ps(target_filename: Path, icc: str = 'sRGB'):
|
def generate_pdfa_ps(target_filename: Path, icc: str = 'sRGB'):
|
||||||
"""Create a Postscript PDFMARK file for Ghostscript PDF/A conversion
|
"""Create a Postscript PDFMARK file for Ghostscript PDF/A conversion.
|
||||||
|
|
||||||
pdfmark is an extension to the Postscript language that describes some PDF
|
pdfmark is an extension to the Postscript language that describes some PDF
|
||||||
features like bookmarks and annotations. It was originally specified Adobe
|
features like bookmarks and annotations. It was originally specified Adobe
|
||||||
@@ -84,7 +78,7 @@ def generate_pdfa_ps(target_filename: Path, icc: str = 'sRGB'):
|
|||||||
Ghostscript uses pdfmark for PDF to PDF/A conversion as well. To use Ghostscript
|
Ghostscript uses pdfmark for PDF to PDF/A conversion as well. To use Ghostscript
|
||||||
to create a PDF/A, we need to create a pdfmark file with the necessary metadata.
|
to create a PDF/A, we need to create a pdfmark file with the necessary metadata.
|
||||||
|
|
||||||
This function takes care of the many version-specific bugs and pecularities in
|
This function takes care of the many version-specific bugs and peculiarities in
|
||||||
Ghostscript's handling of pdfmark.
|
Ghostscript's handling of pdfmark.
|
||||||
|
|
||||||
The only information we put in specifies that we want the file to be a
|
The only information we put in specifies that we want the file to be a
|
||||||
@@ -118,7 +112,6 @@ def file_claims_pdfa(filename: Path):
|
|||||||
This only checks if the XMP metadata contains a PDF/A marker. It does not
|
This only checks if the XMP metadata contains a PDF/A marker. It does not
|
||||||
do full PDF/A validation.
|
do full PDF/A validation.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
with pikepdf.open(filename) as pdf:
|
with pikepdf.open(filename) as pdf:
|
||||||
pdfmeta = pdf.open_metadata()
|
pdfmeta = pdf.open_metadata()
|
||||||
if not pdfmeta.pdfa_status:
|
if not pdfmeta.pdfa_status:
|
||||||
|
|||||||
@@ -6,4 +6,6 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from ocrmypdf.pdfinfo.info import Colorspace, Encoding, PdfInfo
|
from ocrmypdf.pdfinfo.info import Colorspace, Encoding, PageInfo, PdfInfo
|
||||||
|
|
||||||
|
__all__ = ["Colorspace", "Encoding", "PageInfo", "PdfInfo"]
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user