Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
173ce2f215 | ||
|
|
9b641055e1 | ||
|
|
4fa28d7e74 | ||
|
|
bed74501fc | ||
|
|
e821ca46d5 | ||
|
|
a29e4952fb | ||
|
|
4cc0dc6b4a | ||
|
|
7263702de9 | ||
|
|
0287d91874 | ||
|
|
436af55050 | ||
|
|
d6128e6937 | ||
|
|
642437e804 | ||
|
|
4ce802fdb2 | ||
|
|
a672422b0b | ||
|
|
addc2cbad0 | ||
|
|
5f45f77b4e | ||
|
|
93f9bffb37 | ||
|
|
44149ad319 | ||
|
|
d80d963cea | ||
|
|
4da33b8050 | ||
|
|
5cbbff8472 | ||
|
|
fa6e47c277 | ||
|
|
4ea9cffebd | ||
|
|
ae68edefc5 | ||
|
|
1558e068f1 | ||
|
|
d2a9c413f8 | ||
|
|
a510b21b20 | ||
|
|
e33ba07aa4 | ||
|
|
373f27832b | ||
|
|
b20a6e4c5d | ||
|
|
49734d5456 | ||
|
|
26a415c5dd | ||
|
|
60be64a5f1 | ||
|
|
190294634c |
@@ -1,6 +1,6 @@
|
|||||||
repos:
|
repos:
|
||||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||||
rev: v2.4.0
|
rev: v3.1.0
|
||||||
hooks:
|
hooks:
|
||||||
- id: check-case-conflict
|
- id: check-case-conflict
|
||||||
- id: check-merge-conflict
|
- id: check-merge-conflict
|
||||||
@@ -8,16 +8,16 @@ repos:
|
|||||||
- id: check-yaml
|
- id: check-yaml
|
||||||
- id: debug-statements
|
- id: debug-statements
|
||||||
- repo: https://github.com/asottile/seed-isort-config
|
- repo: https://github.com/asottile/seed-isort-config
|
||||||
rev: v1.9.3
|
rev: v2.2.0
|
||||||
hooks:
|
hooks:
|
||||||
- id: seed-isort-config
|
- id: seed-isort-config
|
||||||
- repo: https://github.com/pre-commit/mirrors-isort
|
- repo: https://github.com/pre-commit/mirrors-isort
|
||||||
rev: v4.3.21 # pick the isort version you'd like to use from https://github.com/pre-commit/mirrors-isort/releases
|
rev: v5.0.5 # pick the isort version you'd like to use from https://github.com/pre-commit/mirrors-isort/releases
|
||||||
hooks:
|
hooks:
|
||||||
- id: isort
|
- id: isort
|
||||||
- repo: https://github.com/psf/black
|
- repo: https://github.com/psf/black
|
||||||
rev: stable
|
rev: 19.10b0
|
||||||
hooks:
|
hooks:
|
||||||
- id: black
|
- id: black
|
||||||
language_version: python3.7
|
language_version: python3.8
|
||||||
exclude: ^src/ocrmypdf/lib/_leptonica.py
|
exclude: ^src/ocrmypdf/lib/_leptonica.py
|
||||||
|
|||||||
+10
-4
@@ -152,9 +152,9 @@ stages:
|
|||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
Python37:
|
Python37:
|
||||||
python.version: "3.7"
|
python.version: ""
|
||||||
# Python38:
|
Python38:
|
||||||
# python.version: "3.8"
|
python.version: "python@3.8"
|
||||||
steps:
|
steps:
|
||||||
# https://github.com/actions/virtual-environments/issues/664
|
# https://github.com/actions/virtual-environments/issues/664
|
||||||
# - task: UsePythonVersion@0
|
# - task: UsePythonVersion@0
|
||||||
@@ -163,6 +163,13 @@ stages:
|
|||||||
- bash: |
|
- bash: |
|
||||||
brew update
|
brew update
|
||||||
brew unlink python@2
|
brew unlink python@2
|
||||||
|
if [ "$(python.version)" != "" ]; then
|
||||||
|
brew upgrade $(python.version)
|
||||||
|
else
|
||||||
|
echo "Using Python `python3 --version`"
|
||||||
|
fi
|
||||||
|
displayName: "Update brew and Python"
|
||||||
|
- bash: |
|
||||||
brew install \
|
brew install \
|
||||||
exempi \
|
exempi \
|
||||||
ghostscript \
|
ghostscript \
|
||||||
@@ -170,7 +177,6 @@ stages:
|
|||||||
leptonica \
|
leptonica \
|
||||||
openjpeg \
|
openjpeg \
|
||||||
pngquant \
|
pngquant \
|
||||||
python \
|
|
||||||
tesseract \
|
tesseract \
|
||||||
unpaper
|
unpaper
|
||||||
displayName: "Install system packages"
|
displayName: "Install system packages"
|
||||||
|
|||||||
Vendored
+692
-4
@@ -2,7 +2,6 @@ Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
|
|||||||
Upstream-Name: OCRmyPDF
|
Upstream-Name: OCRmyPDF
|
||||||
Upstream-Contact: James R. Barlow <barlow.jim@gmail.com>
|
Upstream-Contact: James R. Barlow <barlow.jim@gmail.com>
|
||||||
Source: https://github.com/jbarlow83/OCRmyPDF
|
Source: https://github.com/jbarlow83/OCRmyPDF
|
||||||
Files-Excluded: tests/resources/milk.pdf
|
|
||||||
|
|
||||||
Files: *
|
Files: *
|
||||||
Copyright:
|
Copyright:
|
||||||
@@ -10,10 +9,24 @@ Copyright:
|
|||||||
(C) 2013-2016, 2015-2017 2016, 2017, 2017-2018, 2018 James R. Barlow
|
(C) 2013-2016, 2015-2017 2016, 2017, 2017-2018, 2018 James R. Barlow
|
||||||
License: GPL-3+
|
License: GPL-3+
|
||||||
|
|
||||||
|
Files: misc/watcher.py
|
||||||
|
Copyright:
|
||||||
|
(C) 2019 Ian Alexander: https://github.com/ianalexander
|
||||||
|
(C) 2020 James R. Barlow
|
||||||
|
License: GPL-3+
|
||||||
|
|
||||||
|
Files: misc/webservice.py
|
||||||
|
Copyright: (C) 2019 James R. Barlow
|
||||||
|
License: AGPL-3+
|
||||||
|
|
||||||
Files: docs tests/resources/*
|
Files: docs tests/resources/*
|
||||||
Copyright: (C) 2013-2018 James R. Barlow
|
Copyright: (C) 2013-2018 James R. Barlow
|
||||||
License: CC-BY-SA-4.0
|
License: CC-BY-SA-4.0
|
||||||
|
|
||||||
|
Files: docs/images/bitmap_vs_svg.svg
|
||||||
|
Copyright: (C) 2006 Yug
|
||||||
|
License: CC-BY-SA-2.5
|
||||||
|
|
||||||
Files: src/ocrmypdf/hocrtransform.py
|
Files: src/ocrmypdf/hocrtransform.py
|
||||||
Copyright: (C) 2010 Jonathan Brinley <jonathanbrinley@gmail.com>
|
Copyright: (C) 2010 Jonathan Brinley <jonathanbrinley@gmail.com>
|
||||||
(C) 2013-14 Julien Pfefferkorn
|
(C) 2013-14 Julien Pfefferkorn
|
||||||
@@ -30,7 +43,7 @@ Copyright: (C) 2014 Armin Ronacher
|
|||||||
(C) 2017 James R. Barlow
|
(C) 2017 James R. Barlow
|
||||||
License: BSD-3-clause
|
License: BSD-3-clause
|
||||||
|
|
||||||
Files: tests/spoof/*
|
Files: tests/plugins/*
|
||||||
Copyright: (C) 2016, 2017, 2016-2018 James R. Barlow
|
Copyright: (C) 2016, 2017, 2016-2018 James R. Barlow
|
||||||
License: Expat
|
License: Expat
|
||||||
|
|
||||||
@@ -79,15 +92,20 @@ Copyright: held by the contributors to the Wikipedia article "Optical character
|
|||||||
(epson.pdf generated from Wikipedia article as of 2016-09-14)
|
(epson.pdf generated from Wikipedia article as of 2016-09-14)
|
||||||
License: CC-BY-SA-3.0
|
License: CC-BY-SA-3.0
|
||||||
|
|
||||||
Files: tests/resources/typewriter.png tests/resources/2400dpi.pdf tests/resources/3small.pdf
|
Files: tests/resources/typewriter.png tests/resources/2400dpi.pdf
|
||||||
Copyright: (C) 2005 Ellywa
|
Copyright: (C) 2005 Ellywa
|
||||||
License: GFDL-1.2+ or CC-BY-SA-1.0 or CC-BY-SA-2.0 or CC-BY-SA-2.5 or CC-BY-SA-3.0
|
License: GFDL-1.2+ 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
|
Files: tests/resources/overlay.pdf
|
||||||
Copyright: (C) 2017 Max Anderson
|
Copyright: (C) 2017 Max Anderson
|
||||||
License: Expat
|
License: Expat
|
||||||
|
|
||||||
Files: tests/resources/baiona*.png tests/resources/3small.pdf
|
Files:
|
||||||
|
tests/resources/baiona*.png
|
||||||
|
tests/resources/baiona*.jpg
|
||||||
|
tests/resources/link.pdf
|
||||||
Copyright: (C) 2014 Euskaldunaa
|
Copyright: (C) 2014 Euskaldunaa
|
||||||
License: CC-BY-SA-4.0
|
License: CC-BY-SA-4.0
|
||||||
|
|
||||||
@@ -95,6 +113,13 @@ Files: tests/resources/vector.pdf
|
|||||||
Copyright: (C) 2018 Catscratch
|
Copyright: (C) 2018 Catscratch
|
||||||
License: Expat
|
License: Expat
|
||||||
|
|
||||||
|
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 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
|
||||||
|
|
||||||
Files: src/ocrmypdf/data/sRGB.icc
|
Files: src/ocrmypdf/data/sRGB.icc
|
||||||
Copyright: Kai-Uwe Behrmann <www.behrmann.name>
|
Copyright: Kai-Uwe Behrmann <www.behrmann.name>
|
||||||
Marti Maria <www.littlecms.com>
|
Marti Maria <www.littlecms.com>
|
||||||
@@ -124,6 +149,669 @@ License: GPL-3+
|
|||||||
On Debian systems, the complete text of the GNU General
|
On Debian systems, the complete text of the GNU General
|
||||||
Public License version 3 can be found in "/usr/share/common-licenses/GPL-3".
|
Public License version 3 can be found in "/usr/share/common-licenses/GPL-3".
|
||||||
|
|
||||||
|
License: AGPL-3+
|
||||||
|
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 19 November 2007
|
||||||
|
.
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
.
|
||||||
|
Preamble
|
||||||
|
.
|
||||||
|
The GNU Affero General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works, specifically designed to ensure
|
||||||
|
cooperation with the community in the case of network server software.
|
||||||
|
.
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
our General Public Licenses are intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users.
|
||||||
|
.
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
.
|
||||||
|
Developers that use our General Public Licenses protect your rights
|
||||||
|
with two steps: (1) assert copyright on the software, and (2) offer
|
||||||
|
you this License which gives you legal permission to copy, distribute
|
||||||
|
and/or modify the software.
|
||||||
|
.
|
||||||
|
A secondary benefit of defending all users' freedom is that
|
||||||
|
improvements made in alternate versions of the program, if they
|
||||||
|
receive widespread use, become available for other developers to
|
||||||
|
incorporate. Many developers of free software are heartened and
|
||||||
|
encouraged by the resulting cooperation. However, in the case of
|
||||||
|
software used on network servers, this result may fail to come about.
|
||||||
|
The GNU General Public License permits making a modified version and
|
||||||
|
letting the public access it on a server without ever releasing its
|
||||||
|
source code to the public.
|
||||||
|
.
|
||||||
|
The GNU Affero General Public License is designed specifically to
|
||||||
|
ensure that, in such cases, the modified source code becomes available
|
||||||
|
to the community. It requires the operator of a network server to
|
||||||
|
provide the source code of the modified version running there to the
|
||||||
|
users of that server. Therefore, public use of a modified version, on
|
||||||
|
a publicly accessible server, gives the public access to the source
|
||||||
|
code of the modified version.
|
||||||
|
.
|
||||||
|
An older license, called the Affero General Public License and
|
||||||
|
published by Affero, was designed to accomplish similar goals. This is
|
||||||
|
a different license, not a version of the Affero GPL, but Affero has
|
||||||
|
released a new version of the Affero GPL which permits relicensing under
|
||||||
|
this license.
|
||||||
|
.
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
.
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
.
|
||||||
|
0. Definitions.
|
||||||
|
.
|
||||||
|
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||||
|
.
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
.
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
.
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
.
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
.
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
.
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
.
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
.
|
||||||
|
1. Source Code.
|
||||||
|
.
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
.
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
.
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
.
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
.
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
.
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
.
|
||||||
|
2. Basic Permissions.
|
||||||
|
.
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
.
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
.
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
.
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
.
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
.
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
.
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
.
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
.
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
.
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
.
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
.
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
.
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
.
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
.
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
.
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
.
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
.
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
.
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
.
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
.
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
.
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
.
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
.
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
.
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
.
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
.
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
.
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
.
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
.
|
||||||
|
7. Additional Terms.
|
||||||
|
.
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
.
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
.
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
.
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
.
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
.
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
.
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
.
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
.
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
.
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
.
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
.
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
.
|
||||||
|
8. Termination.
|
||||||
|
.
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
.
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
.
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
.
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
.
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
.
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
.
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
.
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
.
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
.
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
.
|
||||||
|
11. Patents.
|
||||||
|
.
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
.
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
.
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
.
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
.
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
.
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
.
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
.
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
.
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
.
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
.
|
||||||
|
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||||
|
.
|
||||||
|
Notwithstanding any other provision of this License, if you modify the
|
||||||
|
Program, your modified version must prominently offer all users
|
||||||
|
interacting with it remotely through a computer network (if your version
|
||||||
|
supports such interaction) an opportunity to receive the Corresponding
|
||||||
|
Source of your version by providing access to the Corresponding Source
|
||||||
|
from a network server at no charge, through some standard or customary
|
||||||
|
means of facilitating copying of software. This Corresponding Source
|
||||||
|
shall include the Corresponding Source for any work covered by version 3
|
||||||
|
of the GNU General Public License that is incorporated pursuant to the
|
||||||
|
following paragraph.
|
||||||
|
.
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the work with which it is combined will remain governed by version
|
||||||
|
3 of the GNU General Public License.
|
||||||
|
.
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
.
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU Affero General Public License from time to time. Such new versions
|
||||||
|
will be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
.
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU Affero General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU Affero General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
.
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU Affero General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
.
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
.
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
.
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
.
|
||||||
|
16. Limitation of Liability.
|
||||||
|
.
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
.
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
.
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
.
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
.
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
.
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
.
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
.
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
.
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU Affero General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
.
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU Affero General Public License for more details.
|
||||||
|
.
|
||||||
|
You should have received a copy of the GNU Affero General Public License
|
||||||
|
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
.
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
.
|
||||||
|
If your software can interact with users remotely through a computer
|
||||||
|
network, you should also make sure that it provides a way for users to
|
||||||
|
get its source. For example, if your program is a web application, its
|
||||||
|
interface could display a "Source" link that leads users to an archive
|
||||||
|
of the code. There are many ways you could offer source, and different
|
||||||
|
solutions will be better for different programs; see section 13 for the
|
||||||
|
specific requirements.
|
||||||
|
.
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||||
|
<http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
License: Expat
|
License: Expat
|
||||||
Permission is hereby granted, free of charge, to any person obtaining
|
Permission is hereby granted, free of charge, to any person obtaining
|
||||||
a copy of this software and associated documentation files (the
|
a copy of this software and associated documentation files (the
|
||||||
|
|||||||
@@ -51,6 +51,10 @@ Forking a child process to call ``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 does not.
|
OCRmyPDF does not.
|
||||||
|
|
||||||
|
Programs that call ``ocrmypdf.ocr()`` should also install a SIGBUS signal
|
||||||
|
handler (except on Windows), to raise an exception if access to a memory
|
||||||
|
mapped file fails. OCRmyPDF may use memory mapping.
|
||||||
|
|
||||||
.. warning::
|
.. warning::
|
||||||
|
|
||||||
On Windows, the script that calls ``ocrmypdf.ocr()`` must be protected
|
On Windows, the script that calls ``ocrmypdf.ocr()`` must be protected
|
||||||
|
|||||||
+1
-1
@@ -127,7 +127,7 @@ Users may need to customize the script to meet their requirements.
|
|||||||
"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_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``"
|
"OCR_JSON_SETTINGS", "A JSON string specifying any other arguments for ``ocrmypdf.ocr``, e.g. ``'OCR_JSON_SETTINGS={"rotate_pages": true}'``.
|
||||||
"OCR_POLL_NEW_FILE_SECONDS", "Polling interval"
|
"OCR_POLL_NEW_FILE_SECONDS", "Polling interval"
|
||||||
"OCR_LOGLEVEL", "Level of log messages to report"
|
"OCR_LOGLEVEL", "Level of log messages to report"
|
||||||
|
|
||||||
|
|||||||
@@ -665,6 +665,13 @@ instead use this for a system wide installation:
|
|||||||
|
|
||||||
pip3 install ocrmypdf
|
pip3 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
|
||||||
-------------------------------------
|
-------------------------------------
|
||||||
|
|
||||||
|
|||||||
+63
-16
@@ -2,6 +2,11 @@
|
|||||||
Plugins
|
Plugins
|
||||||
=======
|
=======
|
||||||
|
|
||||||
|
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL
|
||||||
|
NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and
|
||||||
|
"OPTIONAL" in this document are to be interpreted as described in
|
||||||
|
RFC 2119.
|
||||||
|
|
||||||
You can use plugins to customize the behavior of OCRmyPDF at certain points of
|
You can use plugins to customize the behavior of OCRmyPDF at certain points of
|
||||||
interest.
|
interest.
|
||||||
|
|
||||||
@@ -11,39 +16,34 @@ Currently, it is possible to:
|
|||||||
- override the decision for whether or not to perform OCR on a particular file
|
- override the decision for whether or not to perform OCR on a particular file
|
||||||
- modify the image is about to be sent for OCR
|
- modify the image is about to be sent for OCR
|
||||||
- modify the page image before it is converted to PDF
|
- modify the page image before it is converted to PDF
|
||||||
|
- replace the Tesseract OCR with another OCR engine that has similar behavior
|
||||||
|
- replace Ghostscript with another PDF to image converter (rasterizer) or
|
||||||
|
PDF/A generator
|
||||||
|
|
||||||
OCRmyPDF plugins are based on the Python ``pluggy`` package and conform to its
|
OCRmyPDF plugins are based on the Python ``pluggy`` package and conform to its
|
||||||
conventions. Note that: plugins installed with as setuptools entrypoints are
|
conventions. Note that: plugins installed with as setuptools entrypoints are
|
||||||
not checked currently, because OCRmyPDF assumes you may not want to enable
|
not checked currently, because OCRmyPDF assumes you may not want to enable
|
||||||
plugins for all files. Also, plugins must be functions, not classes.
|
plugins for all files.
|
||||||
|
|
||||||
How plugins are imported
|
|
||||||
========================
|
|
||||||
|
|
||||||
Plugins are imported on demand, by the OCRmyPDF worker process that needs to use
|
|
||||||
them. As such, plugins cannot share state with other plugins, cannot rely on
|
|
||||||
their module's or the interpreter's global state, and should expect asynchronous
|
|
||||||
copies of themselves to be running. Plugins can write intermediate files to the
|
|
||||||
folder specified in ``options.work_folder``.
|
|
||||||
|
|
||||||
Plugins should work whether executed in threads or processes.
|
|
||||||
|
|
||||||
Script plugins
|
Script plugins
|
||||||
==============
|
==============
|
||||||
|
|
||||||
Script plugins may be called from the command line, by specifying the name of a file.
|
Script plugins may be called from the command line, by specifying the name of a file.
|
||||||
|
Script plugins may be convenient for informal or "one-off" plugins, when a certain
|
||||||
|
batch of files needs a special processing step for example.
|
||||||
|
|
||||||
.. code-block:: bash
|
.. code-block:: bash
|
||||||
|
|
||||||
ocrmypdf --plugin example_plugin.py input.pdf output.pdf
|
ocrmypdf --plugin ocrmypdf_example_plugin.py input.pdf output.pdf
|
||||||
|
|
||||||
Multiple plugins may be called by issuing the ``--plugin`` argument multiple times.
|
Multiple plugins may be installed by issuing the ``--plugin`` argument multiple times.
|
||||||
|
|
||||||
Packaged plugins
|
Packaged plugins
|
||||||
================
|
================
|
||||||
|
|
||||||
Installed plugins may be installed into the same virtual environment as OCRmyPDF
|
Installed plugins may be installed into the same virtual environment as OCRmyPDF
|
||||||
is installed into. They may be invoked using Python standard module naming.
|
is installed into. They may be invoked using Python standard module naming.
|
||||||
|
If you are intending to distribute a plugin, please package it.
|
||||||
|
|
||||||
.. code-block:: bash
|
.. code-block:: bash
|
||||||
|
|
||||||
@@ -59,10 +59,45 @@ as packaged plugins, and these modules should begin with the name ``ocrmypdf_``
|
|||||||
similar to ``pytest`` packages such as ``pytest-cov`` (the package) and
|
similar to ``pytest`` packages such as ``pytest-cov`` (the package) and
|
||||||
``pytest_cov`` (the module).
|
``pytest_cov`` (the module).
|
||||||
|
|
||||||
|
.. note::
|
||||||
|
|
||||||
|
We strongly recommend plugin authors name their plugins with the prefix
|
||||||
|
``ocrmypdf-`` (for the package name on PyPI) and ``ocrmypdf_`` (for the
|
||||||
|
module), just like pytest plugins.
|
||||||
|
|
||||||
|
Plugin requirements
|
||||||
|
===================
|
||||||
|
|
||||||
|
OCRmyPDF generally uses multiple worker processes. When a new worker is started,
|
||||||
|
Python will import all plugins again, including all plugins that were imported earlier.
|
||||||
|
This means that the global state of a plugin in one worker will not be shared with
|
||||||
|
other workers. As such, plugin hook implementations should be stateless, relying
|
||||||
|
only on their inputs. Hook implementations may use their input parameters to
|
||||||
|
to obtain a reference to shared state prepared by another hook implementation.
|
||||||
|
Plugins must expect that other instances of the plugin will be running
|
||||||
|
simultaneously.
|
||||||
|
|
||||||
|
The ``context`` object that is passed to many hooks can be used to share information
|
||||||
|
about a file being worked on. Plugins must write private, plugin-specific data to
|
||||||
|
a subfolder named ``{options.work_folder}/ocrmypdf-plugin-name``. Plugins MAY
|
||||||
|
read and write files in ``options.work_folder``, but should be aware that their
|
||||||
|
semantics are subject to change.
|
||||||
|
|
||||||
|
OCRmyPDF will delete ``options.work_folder`` when it has finished OCRing
|
||||||
|
a file, unless invoked with ``--keep-temporary-files``.
|
||||||
|
|
||||||
|
The documentation for some plugin hooks contain a detailed description of the
|
||||||
|
execution context in which they will be called.
|
||||||
|
|
||||||
|
Plugins should be prepared to work whether executed in worker threads or worker
|
||||||
|
processes. Generally, OCRmyPDF uses processes, but has a semi-hidden threaded
|
||||||
|
argument that simplifies debugging.
|
||||||
|
|
||||||
|
|
||||||
Plugin hooks
|
Plugin hooks
|
||||||
============
|
============
|
||||||
|
|
||||||
A plugin may provide the following hooks. Hooks should be decorated with
|
A plugin may provide the following hooks. Hooks must be decorated with
|
||||||
``ocrmypdf.hookimpl``, for example:
|
``ocrmypdf.hookimpl``, for example:
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
@@ -73,9 +108,21 @@ A plugin may provide the following hooks. Hooks should be decorated with
|
|||||||
def add_options(parser):
|
def add_options(parser):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
The following is a complete list of hooks that may be installed and when
|
The following is a complete list of hooks that are available, and when
|
||||||
they are called.
|
they are called.
|
||||||
|
|
||||||
|
.. _firstresult:
|
||||||
|
|
||||||
|
**Note on firstresult hooks**
|
||||||
|
|
||||||
|
If multiple plugins install implementations for this hook, they will be called in
|
||||||
|
the reverse of the order in which they are installed (i.e., last plugin wins).
|
||||||
|
When each hook implementation is called in order, the first implementation that
|
||||||
|
returns a value other than ``None`` will "win" and prevent execution of all other
|
||||||
|
hooks. As such, you cannot "chain" a series of plugin filters together in this
|
||||||
|
way. Instead, a single hook implementation should be responsible for any such
|
||||||
|
chaining operations.
|
||||||
|
|
||||||
Custom command line arguments
|
Custom command line arguments
|
||||||
-----------------------------
|
-----------------------------
|
||||||
|
|
||||||
|
|||||||
@@ -16,6 +16,40 @@ Note that it is licensed under GPLv3, so scripts that
|
|||||||
``import ocrmypdf`` and are released publicly should probably also be
|
``import ocrmypdf`` and are released publicly should probably also be
|
||||||
licensed under GPLv3.
|
licensed under GPLv3.
|
||||||
|
|
||||||
|
v10.3.3
|
||||||
|
=======
|
||||||
|
|
||||||
|
- Fixed a "KeyError: 'dpi'" error message when using ``--threshold`` on an image.
|
||||||
|
(#607)
|
||||||
|
|
||||||
|
v10.3.2
|
||||||
|
=======
|
||||||
|
|
||||||
|
- Fixed a case where we reported "no reason" for a file size increase, when we
|
||||||
|
could determine the reason.
|
||||||
|
- Enabled support for pdfminer.six 20200726.
|
||||||
|
|
||||||
|
v10.3.1
|
||||||
|
=======
|
||||||
|
|
||||||
|
- Fixed a number of test suite failures with pdfminer.six older than veresion 20200420.
|
||||||
|
- Enabled support for pdfminer.six 20200720.
|
||||||
|
|
||||||
|
v10.3.0
|
||||||
|
=======
|
||||||
|
|
||||||
|
- Fixed an issue where we would consider images that were already JBIG2-encoded
|
||||||
|
for optimization, potentially producing a less optimized image than the original.
|
||||||
|
We do not believe this issue would ever cause an image to loss fidelity.
|
||||||
|
- Where available, pikepdf memory mapping is now used. This improves performance.
|
||||||
|
- When Leptonica 1.79+ is installed, use its new error handling API to avoid
|
||||||
|
a "messy" redirection of stderr which was necessary to capture its error
|
||||||
|
messages.
|
||||||
|
- For older versions of Leptonica, added a new thread level lock. This fixes a
|
||||||
|
possible race condition in handling error conditions in Leptonica (although
|
||||||
|
there is no evidence it ever caused issues in practice).
|
||||||
|
- Documentation improvements and more type hinting.
|
||||||
|
|
||||||
v10.2.1
|
v10.2.1
|
||||||
=======
|
=======
|
||||||
|
|
||||||
|
|||||||
@@ -83,7 +83,7 @@ setup(
|
|||||||
'cffi >= 1.9.1', # must be a setup and install requirement
|
'cffi >= 1.9.1', # must be a setup and install requirement
|
||||||
'coloredlogs >= 14.0', # strictly optional
|
'coloredlogs >= 14.0', # strictly optional
|
||||||
'img2pdf >= 0.3.0, < 0.4', # pure Python, so track HEAD closely
|
'img2pdf >= 0.3.0, < 0.4', # pure Python, so track HEAD closely
|
||||||
'pdfminer.six >= 20191110, <= 20200517',
|
'pdfminer.six >= 20191110, <= 20200726',
|
||||||
'pikepdf >= 1.14.0, < 2',
|
'pikepdf >= 1.14.0, < 2',
|
||||||
'Pillow >= 7.0.0',
|
'Pillow >= 7.0.0',
|
||||||
'pluggy >= 0.13.0',
|
'pluggy >= 0.13.0',
|
||||||
|
|||||||
@@ -18,6 +18,7 @@
|
|||||||
|
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
|
import signal
|
||||||
import sys
|
import sys
|
||||||
from multiprocessing import set_start_method
|
from multiprocessing import set_start_method
|
||||||
|
|
||||||
@@ -26,11 +27,20 @@ from ocrmypdf._plugin_manager import get_parser_options_plugins
|
|||||||
from ocrmypdf._sync import run_pipeline
|
from ocrmypdf._sync import run_pipeline
|
||||||
from ocrmypdf._validation import check_closed_streams, check_options
|
from ocrmypdf._validation import check_closed_streams, check_options
|
||||||
from ocrmypdf.api import Verbosity, configure_logging
|
from ocrmypdf.api import Verbosity, configure_logging
|
||||||
from ocrmypdf.exceptions import BadArgsError, ExitCode, MissingDependencyError
|
from ocrmypdf.exceptions import (
|
||||||
|
BadArgsError,
|
||||||
|
ExitCode,
|
||||||
|
InputFileError,
|
||||||
|
MissingDependencyError,
|
||||||
|
)
|
||||||
|
|
||||||
log = logging.getLogger('ocrmypdf')
|
log = logging.getLogger('ocrmypdf')
|
||||||
|
|
||||||
|
|
||||||
|
def sigbus(*args):
|
||||||
|
raise InputFileError("Lost access to the input file")
|
||||||
|
|
||||||
|
|
||||||
def run(args=None):
|
def run(args=None):
|
||||||
_parser, options, plugin_manager = get_parser_options_plugins(args=args)
|
_parser, options, plugin_manager = get_parser_options_plugins(args=args)
|
||||||
|
|
||||||
@@ -62,6 +72,9 @@ def run(args=None):
|
|||||||
log.error(e)
|
log.error(e)
|
||||||
return ExitCode.missing_dependency
|
return ExitCode.missing_dependency
|
||||||
|
|
||||||
|
if hasattr(signal, 'SIGBUS'):
|
||||||
|
signal.signal(signal.SIGBUS, sigbus)
|
||||||
|
|
||||||
result = run_pipeline(options=options, plugin_manager=plugin_manager)
|
result = run_pipeline(options=options, plugin_manager=plugin_manager)
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|||||||
@@ -28,6 +28,8 @@ from typing import Callable, Iterable, Optional
|
|||||||
|
|
||||||
from tqdm import tqdm
|
from tqdm import tqdm
|
||||||
|
|
||||||
|
from ocrmypdf.exceptions import InputFileError
|
||||||
|
|
||||||
|
|
||||||
def log_listener(queue):
|
def log_listener(queue):
|
||||||
"""Listen to the worker processes and forward the messages to logging
|
"""Listen to the worker processes and forward the messages to logging
|
||||||
@@ -53,12 +55,20 @@ def log_listener(queue):
|
|||||||
traceback.print_exc(file=sys.stderr)
|
traceback.print_exc(file=sys.stderr)
|
||||||
|
|
||||||
|
|
||||||
|
def process_sigbus(*args):
|
||||||
|
raise InputFileError("A worker process lost access to an input file")
|
||||||
|
|
||||||
|
|
||||||
def process_init(queue, user_init):
|
def process_init(queue, user_init):
|
||||||
"""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)
|
||||||
|
|
||||||
|
# Install SIGBUS handler (so our parent process can abort somewhat gracefully)
|
||||||
|
if hasattr(signal, 'SIGBUS'):
|
||||||
|
signal.signal(signal.SIGBUS, process_sigbus)
|
||||||
|
|
||||||
# Reconfigure the root logger for this process to send all messages to a queue
|
# Reconfigure the root logger for this process to send all messages to a queue
|
||||||
h = logging.handlers.QueueHandler(queue)
|
h = logging.handlers.QueueHandler(queue)
|
||||||
root = logging.getLogger()
|
root = logging.getLogger()
|
||||||
@@ -70,6 +80,9 @@ def process_init(queue, user_init):
|
|||||||
|
|
||||||
|
|
||||||
def thread_init(_queue, user_init):
|
def thread_init(_queue, user_init):
|
||||||
|
# As a thread, block SIGBUS so the main thread deals with it...
|
||||||
|
if hasattr(signal, 'SIGBUS'):
|
||||||
|
signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGBUS})
|
||||||
if user_init:
|
if user_init:
|
||||||
user_init()
|
user_init()
|
||||||
|
|
||||||
|
|||||||
@@ -17,6 +17,7 @@
|
|||||||
|
|
||||||
"""Interface to pngquant executable"""
|
"""Interface to pngquant executable"""
|
||||||
|
|
||||||
|
from os import fspath
|
||||||
from tempfile import NamedTemporaryFile
|
from tempfile import NamedTemporaryFile
|
||||||
|
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
@@ -38,6 +39,8 @@ def available():
|
|||||||
|
|
||||||
|
|
||||||
def quantize(input_file, output_file, quality_min, quality_max):
|
def quantize(input_file, output_file, quality_min, quality_max):
|
||||||
|
input_file = fspath(input_file)
|
||||||
|
output_file = fspath(output_file)
|
||||||
if input_file.endswith('.jpg'):
|
if input_file.endswith('.jpg'):
|
||||||
with Image.open(input_file) as im, NamedTemporaryFile(suffix='.png') as tmp:
|
with Image.open(input_file) as im, NamedTemporaryFile(suffix='.png') as tmp:
|
||||||
im.save(tmp)
|
im.save(tmp)
|
||||||
|
|||||||
@@ -530,7 +530,9 @@ def create_ocr_image(image: Path, page_context: PageContext):
|
|||||||
if options.threshold:
|
if options.threshold:
|
||||||
pix = leptonica.Pix.frompil(im)
|
pix = leptonica.Pix.frompil(im)
|
||||||
pix = pix.masked_threshold_on_background_norm()
|
pix = pix.masked_threshold_on_background_norm()
|
||||||
im = pix.topil()
|
im_pix = pix.topil()
|
||||||
|
im_pix.info['dpi'] = im.info['dpi']
|
||||||
|
im = im_pix
|
||||||
|
|
||||||
del draw
|
del draw
|
||||||
|
|
||||||
|
|||||||
+12
-1
@@ -25,11 +25,13 @@ from pathlib import Path
|
|||||||
from tempfile import mkdtemp
|
from tempfile import mkdtemp
|
||||||
from typing import List, NamedTuple, Optional, Tuple
|
from typing import List, NamedTuple, Optional, Tuple
|
||||||
|
|
||||||
|
import pikepdf
|
||||||
import PIL
|
import PIL
|
||||||
|
|
||||||
from ocrmypdf._concurrent import exec_progress_pool
|
from ocrmypdf._concurrent import exec_progress_pool
|
||||||
from ocrmypdf._graft import OcrGrafter
|
from ocrmypdf._graft import OcrGrafter
|
||||||
from ocrmypdf._jobcontext import PageContext, PdfContext, cleanup_working_files
|
from ocrmypdf._jobcontext import PageContext, PdfContext, cleanup_working_files
|
||||||
|
from ocrmypdf._logging import PageNumberFilter
|
||||||
from ocrmypdf._pipeline import (
|
from ocrmypdf._pipeline import (
|
||||||
convert_to_pdfa,
|
convert_to_pdfa,
|
||||||
copy_final,
|
copy_final,
|
||||||
@@ -62,7 +64,12 @@ from ocrmypdf._validation import (
|
|||||||
report_output_file_size,
|
report_output_file_size,
|
||||||
)
|
)
|
||||||
from ocrmypdf.exceptions import ExitCode, ExitCodeException
|
from ocrmypdf.exceptions import ExitCode, ExitCodeException
|
||||||
from ocrmypdf.helpers import available_cpu_count, check_pdf, samefile
|
from ocrmypdf.helpers import (
|
||||||
|
available_cpu_count,
|
||||||
|
check_pdf,
|
||||||
|
pikepdf_enable_mmap,
|
||||||
|
samefile,
|
||||||
|
)
|
||||||
from ocrmypdf.pdfa import file_claims_pdfa
|
from ocrmypdf.pdfa import file_claims_pdfa
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
@@ -240,6 +247,7 @@ def worker_init(max_pixels: int):
|
|||||||
# the parent process, so ensure workers get it set. Not needed when running
|
# the parent process, so ensure workers get it set. Not needed when running
|
||||||
# threaded, but harmless to set again.
|
# threaded, but harmless to set again.
|
||||||
PIL.Image.MAX_IMAGE_PIXELS = max_pixels
|
PIL.Image.MAX_IMAGE_PIXELS = max_pixels
|
||||||
|
pikepdf_enable_mmap()
|
||||||
|
|
||||||
|
|
||||||
def exec_concurrent(context: PdfContext):
|
def exec_concurrent(context: PdfContext):
|
||||||
@@ -309,6 +317,7 @@ def configure_debug_logging(log_filename, prefix=''):
|
|||||||
'[%(asctime)s] - %(name)s - %(levelname)7s -%(pageno)s %(message)s'
|
'[%(asctime)s] - %(name)s - %(levelname)7s -%(pageno)s %(message)s'
|
||||||
)
|
)
|
||||||
log_file_handler.setFormatter(formatter)
|
log_file_handler.setFormatter(formatter)
|
||||||
|
log_file_handler.addFilter(PageNumberFilter())
|
||||||
logging.getLogger(prefix).addHandler(log_file_handler)
|
logging.getLogger(prefix).addHandler(log_file_handler)
|
||||||
return log_file_handler
|
return log_file_handler
|
||||||
|
|
||||||
@@ -329,6 +338,8 @@ def run_pipeline(options, *, plugin_manager, api=False):
|
|||||||
):
|
):
|
||||||
debug_log_handler = configure_debug_logging(Path(work_folder) / "debug.log")
|
debug_log_handler = configure_debug_logging(Path(work_folder) / "debug.log")
|
||||||
|
|
||||||
|
pikepdf_enable_mmap()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
check_requested_output_file(options)
|
check_requested_output_file(options)
|
||||||
start_input_file, original_filename = create_input_file(options, work_folder)
|
start_input_file, original_filename = create_input_file(options, work_folder)
|
||||||
|
|||||||
@@ -416,6 +416,10 @@ def report_output_file_size(options, input_file, output_file):
|
|||||||
f"The optional dependency '{name}' was not found, so some image "
|
f"The optional dependency '{name}' was not found, so some image "
|
||||||
f"optimizations could not be attempted."
|
f"optimizations could not be attempted."
|
||||||
)
|
)
|
||||||
|
if options.output_type.startswith('pdfa'):
|
||||||
|
reasons.append("PDF/A conversion was enabled. (Try `--output-type pdf`.)")
|
||||||
|
if options.plugins:
|
||||||
|
reasons.append("Plugins were used.")
|
||||||
|
|
||||||
if reasons:
|
if reasons:
|
||||||
explanation = "Possible reasons for this include:\n" + '\n'.join(reasons) + "\n"
|
explanation = "Possible reasons for this include:\n" + '\n'.join(reasons) + "\n"
|
||||||
|
|||||||
+11
-8
@@ -83,8 +83,8 @@ image, and then creates a PDF from the OCR information.
|
|||||||
""",
|
""",
|
||||||
epilog="""\
|
epilog="""\
|
||||||
OCRmyPDF attempts to keep the output file at about the same size. If a file
|
OCRmyPDF attempts to keep the output file at about the same size. If a file
|
||||||
contains losslessly compressed images, and output file will be losslessly
|
contains losslessly compressed images, and images in the output file will be
|
||||||
compressed as well.
|
losslessly compressed as well.
|
||||||
|
|
||||||
PDF is a page description file that attempts to preserve a layout exactly.
|
PDF is a page description file that attempts to preserve a layout exactly.
|
||||||
A PDF can contain vector objects (such as text or lines) and raster objects
|
A PDF can contain vector objects (such as text or lines) and raster objects
|
||||||
@@ -103,9 +103,8 @@ all objects on the page and produce an image-only PDF as output.
|
|||||||
|
|
||||||
If you are concerned about long-term archiving of PDFs, use the default option
|
If you are concerned about long-term archiving of PDFs, use the default option
|
||||||
--output-type pdfa which converts the PDF to a standardized PDF/A-2b. This
|
--output-type pdfa which converts the PDF to a standardized PDF/A-2b. This
|
||||||
converts images to sRGB colorspace, removes some features from the PDF such
|
removes some features from the PDF such as Javascript or forms. If you want to
|
||||||
as Javascript or forms. If you want to minimize the number of changes made to
|
minimize the number of changes made to your PDF, use --output-type pdf.
|
||||||
your PDF, use --output-type pdf.
|
|
||||||
|
|
||||||
If OCRmyPDF is given an image file as input, it will attempt to convert the
|
If OCRmyPDF is given an image file as input, it will attempt to convert the
|
||||||
image to a PDF before processing. For more control over the conversion of
|
image to a PDF before processing. For more control over the conversion of
|
||||||
@@ -113,8 +112,7 @@ images to PDF, use the Python package img2pdf or other image to PDF software.
|
|||||||
|
|
||||||
For example, this command uses img2pdf to convert all .png files beginning
|
For example, this command uses img2pdf to convert all .png files beginning
|
||||||
with the 'page' prefix to a PDF, fitting each image on A4-sized paper, and
|
with the 'page' prefix to a PDF, fitting each image on A4-sized paper, and
|
||||||
sending the result to OCRmyPDF through a pipe. img2pdf is a dependency of
|
sending the result to OCRmyPDF through a pipe.
|
||||||
ocrmypdf so it is already installed.
|
|
||||||
|
|
||||||
img2pdf --pagesize A4 page*.png | ocrmypdf - myfile.pdf
|
img2pdf --pagesize A4 page*.png | ocrmypdf - myfile.pdf
|
||||||
|
|
||||||
@@ -462,7 +460,12 @@ Online documentation is located at:
|
|||||||
dest='plugins',
|
dest='plugins',
|
||||||
action='append',
|
action='append',
|
||||||
default=[],
|
default=[],
|
||||||
help="Name of plugin to import.",
|
help="Name of plugin to import. Argument may be issued multiple times to "
|
||||||
|
"import multiple plugins. Plugins may be specified as module names in "
|
||||||
|
"Python syntax, provided they are installed in the same Python (virtual) "
|
||||||
|
"environment as ocrmypdf; or you may give the path to the Python file that "
|
||||||
|
"contains the plugin. Plugins must conform to the specification in the "
|
||||||
|
"OCRmyPDF documentation.",
|
||||||
)
|
)
|
||||||
|
|
||||||
debugging = parser.add_argument_group(
|
debugging = parser.add_argument_group(
|
||||||
|
|||||||
@@ -222,6 +222,14 @@ def clamp(n: T, smallest: T, largest: T) -> T:
|
|||||||
return max(smallest, min(n, largest))
|
return max(smallest, min(n, largest))
|
||||||
|
|
||||||
|
|
||||||
|
def pikepdf_enable_mmap():
|
||||||
|
try:
|
||||||
|
if pikepdf._qpdf.set_access_default_mmap(True):
|
||||||
|
log.debug("pikepdf mmap enabled")
|
||||||
|
except AttributeError:
|
||||||
|
log.debug("pikepdf mmap not available")
|
||||||
|
|
||||||
|
|
||||||
def deprecated(func):
|
def deprecated(func):
|
||||||
"""Warn that function is deprecated"""
|
"""Warn that function is deprecated"""
|
||||||
|
|
||||||
|
|||||||
@@ -24,7 +24,9 @@ import argparse
|
|||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
import threading
|
||||||
import warnings
|
import warnings
|
||||||
|
from collections import deque
|
||||||
from collections.abc import Sequence
|
from collections.abc import Sequence
|
||||||
from contextlib import suppress
|
from contextlib import suppress
|
||||||
from ctypes.util import find_library
|
from ctypes.util import find_library
|
||||||
@@ -75,7 +77,7 @@ except ffi.error as e:
|
|||||||
) from e
|
) from e
|
||||||
|
|
||||||
|
|
||||||
class _LeptonicaErrorTrap:
|
class _LeptonicaErrorTrap_Redirect:
|
||||||
"""
|
"""
|
||||||
Context manager to trap errors reported by Leptonica.
|
Context manager to trap errors reported by Leptonica.
|
||||||
|
|
||||||
@@ -90,19 +92,21 @@ class _LeptonicaErrorTrap:
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
leptonica_lock = threading.Lock()
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.tmpfile = None
|
self.tmpfile = None
|
||||||
self.copy_of_stderr = -1
|
self.copy_of_stderr = -1
|
||||||
self.no_stderr = False
|
self.no_stderr = False
|
||||||
|
|
||||||
def __enter__(self):
|
def __enter__(self):
|
||||||
|
|
||||||
self.tmpfile = TemporaryFile()
|
self.tmpfile = TemporaryFile()
|
||||||
|
|
||||||
# Save the old stderr, and redirect stderr to temporary file
|
# Save the old stderr, and redirect stderr to temporary file
|
||||||
with suppress(AttributeError):
|
self.leptonica_lock.acquire()
|
||||||
sys.stderr.flush()
|
|
||||||
try:
|
try:
|
||||||
|
with suppress(AttributeError):
|
||||||
|
sys.stderr.flush()
|
||||||
self.copy_of_stderr = os.dup(sys.stderr.fileno())
|
self.copy_of_stderr = os.dup(sys.stderr.fileno())
|
||||||
os.dup2(self.tmpfile.fileno(), sys.stderr.fileno(), inheritable=False)
|
os.dup2(self.tmpfile.fileno(), sys.stderr.fileno(), inheritable=False)
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
@@ -114,7 +118,10 @@ class _LeptonicaErrorTrap:
|
|||||||
os.dup2(self.tmpfile.fileno(), 2, inheritable=False)
|
os.dup2(self.tmpfile.fileno(), 2, inheritable=False)
|
||||||
except UnsupportedOperation:
|
except UnsupportedOperation:
|
||||||
self.copy_of_stderr = None
|
self.copy_of_stderr = None
|
||||||
return
|
except Exception:
|
||||||
|
self.leptonica_lock.release()
|
||||||
|
raise
|
||||||
|
return self
|
||||||
|
|
||||||
def __exit__(self, exc_type, exc_value, traceback):
|
def __exit__(self, exc_type, exc_value, traceback):
|
||||||
# Restore old stderr
|
# Restore old stderr
|
||||||
@@ -131,6 +138,8 @@ class _LeptonicaErrorTrap:
|
|||||||
self.tmpfile.seek(0) # Cursor will be at end, so move back to beginning
|
self.tmpfile.seek(0) # Cursor will be at end, so move back to beginning
|
||||||
leptonica_output = self.tmpfile.read().decode(errors='replace')
|
leptonica_output = self.tmpfile.read().decode(errors='replace')
|
||||||
self.tmpfile.close()
|
self.tmpfile.close()
|
||||||
|
self.leptonica_lock.release()
|
||||||
|
|
||||||
# If there are Python errors, record them
|
# If there are Python errors, record them
|
||||||
if exc_type:
|
if exc_type:
|
||||||
logger.warning(leptonica_output)
|
logger.warning(leptonica_output)
|
||||||
@@ -148,6 +157,62 @@ class _LeptonicaErrorTrap:
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
tls = threading.local()
|
||||||
|
tls.trap = None
|
||||||
|
|
||||||
|
|
||||||
|
@ffi.callback("void(char *)")
|
||||||
|
def _stderr_handler(cstr):
|
||||||
|
msg = ffi.string(cstr).decode(errors='replace')
|
||||||
|
if msg.startswith("Error"):
|
||||||
|
logger.error(msg)
|
||||||
|
elif msg.startswith("Warning"):
|
||||||
|
logger.warning(msg)
|
||||||
|
else:
|
||||||
|
logger.debug(msg)
|
||||||
|
if tls.trap is not None:
|
||||||
|
tls.trap.append(msg)
|
||||||
|
return
|
||||||
|
|
||||||
|
|
||||||
|
class _LeptonicaErrorTrap_Queue:
|
||||||
|
def __init__(self):
|
||||||
|
self.queue = deque()
|
||||||
|
|
||||||
|
def __enter__(self):
|
||||||
|
self.queue.clear()
|
||||||
|
tls.trap = self.queue
|
||||||
|
|
||||||
|
def __exit__(self, exc_type, exc_value, traceback):
|
||||||
|
tls.trap = None
|
||||||
|
output = ''.join(self.queue)
|
||||||
|
self.queue.clear()
|
||||||
|
|
||||||
|
# If there are Python errors, record them
|
||||||
|
if exc_type:
|
||||||
|
logger.warning(output)
|
||||||
|
|
||||||
|
if 'Error' in output:
|
||||||
|
if 'image file not found' in output:
|
||||||
|
raise FileNotFoundError()
|
||||||
|
if 'pixWrite: stream not opened' in output:
|
||||||
|
raise LeptonicaIOError()
|
||||||
|
if 'index not valid' in output:
|
||||||
|
raise IndexError()
|
||||||
|
raise LeptonicaError(output)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
try:
|
||||||
|
lept.leptSetStderrHandler(_stderr_handler)
|
||||||
|
except ffi.error:
|
||||||
|
# Pre-1.79 Leptonica does not have leptSetStderrHandler
|
||||||
|
_LeptonicaErrorTrap = _LeptonicaErrorTrap_Redirect
|
||||||
|
else:
|
||||||
|
# 1.79 have this new symbol
|
||||||
|
_LeptonicaErrorTrap = _LeptonicaErrorTrap_Queue
|
||||||
|
|
||||||
|
|
||||||
class LeptonicaError(Exception):
|
class LeptonicaError(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@@ -856,6 +921,8 @@ def get_leptonica_version():
|
|||||||
Caveat: Leptonica expects the caller to free this memory. We don't,
|
Caveat: Leptonica expects the caller to free this memory. We don't,
|
||||||
since that would involve binding to libc to access libc.free(),
|
since that would involve binding to libc to access libc.free(),
|
||||||
a pointless effort to reclaim 100 bytes of memory.
|
a pointless effort to reclaim 100 bytes of memory.
|
||||||
|
|
||||||
|
Reminder that this returns "leptonica-1.xx" or "leptonica-1.yy.0".
|
||||||
"""
|
"""
|
||||||
return ffi.string(lept.getLeptonicaVersion()).decode()
|
return ffi.string(lept.getLeptonicaVersion()).decode()
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@@ -509,6 +509,8 @@ void selDestroy ( SEL **psel );
|
|||||||
l_int32
|
l_int32
|
||||||
setMsgSeverity(l_int32 newsev);
|
setMsgSeverity(l_int32 newsev);
|
||||||
|
|
||||||
|
void
|
||||||
|
leptSetStderrHandler(void (*handler)(const char *));
|
||||||
"""
|
"""
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
+95
-52
@@ -22,9 +22,23 @@ from collections import defaultdict
|
|||||||
from functools import partial
|
from functools import partial
|
||||||
from os import fspath
|
from os import fspath
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from typing import (
|
||||||
|
Any,
|
||||||
|
Callable,
|
||||||
|
Dict,
|
||||||
|
Iterator,
|
||||||
|
List,
|
||||||
|
MutableSet,
|
||||||
|
NamedTuple,
|
||||||
|
NewType,
|
||||||
|
Optional,
|
||||||
|
Sequence,
|
||||||
|
Tuple,
|
||||||
|
Union,
|
||||||
|
)
|
||||||
|
|
||||||
import pikepdf
|
import pikepdf
|
||||||
from pikepdf import Dictionary, Name
|
from pikepdf import Dictionary, Name, Object, Pdf, PdfImage
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
from tqdm import tqdm
|
from tqdm import tqdm
|
||||||
|
|
||||||
@@ -41,30 +55,40 @@ DEFAULT_JPEG_QUALITY = 75
|
|||||||
DEFAULT_PNG_QUALITY = 70
|
DEFAULT_PNG_QUALITY = 70
|
||||||
|
|
||||||
|
|
||||||
def img_name(root, xref, ext):
|
Xref = NewType('Xref', int)
|
||||||
return fspath(root / f'{xref:08d}{ext}')
|
|
||||||
|
|
||||||
|
|
||||||
def png_name(root, xref):
|
class XrefExt(NamedTuple):
|
||||||
|
xref: Xref
|
||||||
|
ext: str
|
||||||
|
|
||||||
|
|
||||||
|
def img_name(root: Path, xref: Xref, ext: str) -> Path:
|
||||||
|
return root / f'{xref:08d}{ext}'
|
||||||
|
|
||||||
|
|
||||||
|
def png_name(root: Path, xref: Xref) -> Path:
|
||||||
return img_name(root, xref, '.png')
|
return img_name(root, xref, '.png')
|
||||||
|
|
||||||
|
|
||||||
def jpg_name(root, xref):
|
def jpg_name(root: Path, xref: Xref) -> Path:
|
||||||
return img_name(root, xref, '.jpg')
|
return img_name(root, xref, '.jpg')
|
||||||
|
|
||||||
|
|
||||||
def tif_name(root, xref):
|
def tif_name(root: Path, xref: Xref) -> Path:
|
||||||
return img_name(root, xref, '.tif')
|
return img_name(root, xref, '.tif')
|
||||||
|
|
||||||
|
|
||||||
def extract_image_filter(pike, root, image, xref):
|
def extract_image_filter(
|
||||||
|
pike: Pdf, root: Path, image: Object, xref: Xref
|
||||||
|
) -> Optional[Tuple[PdfImage, Tuple[Name, Object]]]:
|
||||||
if image.Subtype != Name.Image:
|
if image.Subtype != Name.Image:
|
||||||
return None
|
return None
|
||||||
if image.Length < 100:
|
if image.Length < 100:
|
||||||
log.debug("Skipping small image, xref %s", xref)
|
log.debug("Skipping small image, xref %s", xref)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
pim = pikepdf.PdfImage(image)
|
pim = PdfImage(image)
|
||||||
|
|
||||||
if len(pim.filter_decodeparms) > 1:
|
if len(pim.filter_decodeparms) > 1:
|
||||||
log.debug("Skipping multiply filtered, xref %s", xref)
|
log.debug("Skipping multiply filtered, xref %s", xref)
|
||||||
@@ -83,7 +107,9 @@ def extract_image_filter(pike, root, image, xref):
|
|||||||
return pim, filtdp
|
return pim, filtdp
|
||||||
|
|
||||||
|
|
||||||
def extract_image_jbig2(*, pike, root, image, xref, options):
|
def extract_image_jbig2(
|
||||||
|
*, pike: pikepdf.Pdf, root: Path, image: Object, xref: Xref, options
|
||||||
|
) -> Optional[XrefExt]:
|
||||||
result = extract_image_filter(pike, root, image, xref)
|
result = extract_image_filter(pike, root, image, xref)
|
||||||
if result is None:
|
if result is None:
|
||||||
return None
|
return None
|
||||||
@@ -91,21 +117,23 @@ def extract_image_jbig2(*, pike, root, image, xref, options):
|
|||||||
|
|
||||||
if (
|
if (
|
||||||
pim.bits_per_component == 1
|
pim.bits_per_component == 1
|
||||||
and filtdp != Name.JBIG2Decode
|
and filtdp[0] != Name.JBIG2Decode
|
||||||
and jbig2enc.available()
|
and jbig2enc.available()
|
||||||
):
|
):
|
||||||
try:
|
try:
|
||||||
imgname = Path(root / f'{xref:08d}')
|
imgname = root / f'{xref:08d}'
|
||||||
with imgname.open('wb') as f:
|
with imgname.open('wb') as f:
|
||||||
ext = pim.extract_to(stream=f)
|
ext = pim.extract_to(stream=f)
|
||||||
imgname.rename(imgname.with_suffix(ext))
|
imgname.rename(imgname.with_suffix(ext))
|
||||||
except pikepdf.UnsupportedImageTypeError:
|
except pikepdf.UnsupportedImageTypeError:
|
||||||
return None
|
return None
|
||||||
return xref, ext
|
return XrefExt(xref, ext)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def extract_image_generic(*, pike, root, image, xref, options):
|
def extract_image_generic(
|
||||||
|
*, pike: Pdf, root: Path, image: PdfImage, xref: Xref, options
|
||||||
|
) -> Optional[XrefExt]:
|
||||||
result = extract_image_filter(pike, root, image, xref)
|
result = extract_image_filter(pike, root, image, xref)
|
||||||
if result is None:
|
if result is None:
|
||||||
return None
|
return None
|
||||||
@@ -138,13 +166,13 @@ def extract_image_generic(*, pike, root, image, xref, options):
|
|||||||
# with Image.open(stream) as im:
|
# with Image.open(stream) as im:
|
||||||
# im.save(jpg_name(root, xref), icc_profile=iccbytes)
|
# im.save(jpg_name(root, xref), icc_profile=iccbytes)
|
||||||
try:
|
try:
|
||||||
imgname = Path(root / f'{xref:08d}')
|
imgname = root / f'{xref:08d}'
|
||||||
with imgname.open('wb') as f:
|
with imgname.open('wb') as f:
|
||||||
ext = pim.extract_to(stream=f)
|
ext = pim.extract_to(stream=f)
|
||||||
imgname.rename(imgname.with_suffix(ext))
|
imgname.rename(imgname.with_suffix(ext))
|
||||||
except pikepdf.UnsupportedImageTypeError:
|
except pikepdf.UnsupportedImageTypeError:
|
||||||
return None
|
return None
|
||||||
return xref, ext
|
return XrefExt(xref, ext)
|
||||||
elif (
|
elif (
|
||||||
pim.indexed
|
pim.indexed
|
||||||
and pim.colorspace in pim.SIMPLE_COLORSPACES
|
and pim.colorspace in pim.SIMPLE_COLORSPACES
|
||||||
@@ -153,12 +181,12 @@ def extract_image_generic(*, pike, root, image, xref, options):
|
|||||||
# Try to improve on indexed images - these are far from low hanging
|
# Try to improve on indexed images - these are far from low hanging
|
||||||
# fruit in most cases
|
# fruit in most cases
|
||||||
pim.as_pil_image().save(png_name(root, xref))
|
pim.as_pil_image().save(png_name(root, xref))
|
||||||
return xref, '.png'
|
return XrefExt(xref, '.png')
|
||||||
elif not pim.indexed and pim.colorspace in pim.SIMPLE_COLORSPACES:
|
elif not pim.indexed and pim.colorspace in pim.SIMPLE_COLORSPACES:
|
||||||
# An optimization opportunity here, not currently taken, is directly
|
# An optimization opportunity here, not currently taken, is directly
|
||||||
# generating a PNG from compressed data
|
# generating a PNG from compressed data
|
||||||
pim.as_pil_image().save(png_name(root, xref))
|
pim.as_pil_image().save(png_name(root, xref))
|
||||||
return xref, '.png'
|
return XrefExt(xref, '.png')
|
||||||
elif (
|
elif (
|
||||||
not pim.indexed
|
not pim.indexed
|
||||||
and pim.colorspace == Name.ICCBased
|
and pim.colorspace == Name.ICCBased
|
||||||
@@ -169,12 +197,14 @@ def extract_image_generic(*, pike, root, image, xref, options):
|
|||||||
# paying any attention to the ICC profile, provided we're not doing
|
# paying any attention to the ICC profile, provided we're not doing
|
||||||
# lossy JBIG2
|
# lossy JBIG2
|
||||||
pim.as_pil_image().save(png_name(root, xref))
|
pim.as_pil_image().save(png_name(root, xref))
|
||||||
return xref, '.png'
|
return XrefExt(xref, '.png')
|
||||||
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def extract_images(pike, root, options, extract_fn):
|
def extract_images(
|
||||||
|
pike: Pdf, root: Path, options, extract_fn: Callable[..., Optional[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.
|
||||||
@@ -190,8 +220,8 @@ def extract_images(pike, root, options, extract_fn):
|
|||||||
extension. extract_fn must also extract the file it finds interesting.
|
extension. extract_fn must also extract the file it finds interesting.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
include_xrefs = set()
|
include_xrefs: MutableSet[Xref] = set()
|
||||||
exclude_xrefs = set()
|
exclude_xrefs: MutableSet[Xref] = set()
|
||||||
pageno_for_xref = {}
|
pageno_for_xref = {}
|
||||||
errors = 0
|
errors = 0
|
||||||
for pageno, page in enumerate(pike.pages):
|
for pageno, page in enumerate(pike.pages):
|
||||||
@@ -202,10 +232,10 @@ def extract_images(pike, root, options, extract_fn):
|
|||||||
for _imname, image in dict(xobjs).items():
|
for _imname, image in dict(xobjs).items():
|
||||||
if image.objgen[1] != 0:
|
if image.objgen[1] != 0:
|
||||||
continue # Ignore images in an incremental PDF
|
continue # Ignore images in an incremental PDF
|
||||||
xref = image.objgen[0]
|
xref = Xref(image.objgen[0])
|
||||||
if hasattr(image, 'SMask'):
|
if hasattr(image, 'SMask'):
|
||||||
# Ignore soft masks
|
# Ignore soft masks
|
||||||
smask_xref = image.SMask.objgen[0]
|
smask_xref = Xref(image.SMask.objgen[0])
|
||||||
exclude_xrefs.add(smask_xref)
|
exclude_xrefs.add(smask_xref)
|
||||||
include_xrefs.add(xref)
|
include_xrefs.add(xref)
|
||||||
if xref not in pageno_for_xref:
|
if xref not in pageno_for_xref:
|
||||||
@@ -224,31 +254,33 @@ def extract_images(pike, root, options, extract_fn):
|
|||||||
else:
|
else:
|
||||||
if result:
|
if result:
|
||||||
_, ext = result
|
_, ext = result
|
||||||
yield pageno_for_xref[xref], xref, ext
|
yield pageno_for_xref[xref], XrefExt(xref, ext)
|
||||||
|
|
||||||
|
|
||||||
def extract_images_generic(pike, root, options):
|
def extract_images_generic(
|
||||||
|
pike: Pdf, root: Path, options
|
||||||
|
) -> 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(pike, root, options, extract_image_generic):
|
||||||
log.debug('xref = %s ext = %s', xref, ext)
|
log.debug('%s', xref_ext)
|
||||||
if ext == '.png':
|
if xref_ext.ext == '.png':
|
||||||
pngs.append(xref)
|
pngs.append(xref_ext.xref)
|
||||||
elif ext == '.jpg':
|
elif xref_ext.ext == '.jpg':
|
||||||
jpegs.append(xref)
|
jpegs.append(xref_ext.xref)
|
||||||
log.debug("Optimizable images: JPEGs: %s PNGs: %s", len(jpegs), len(pngs))
|
log.debug("Optimizable images: JPEGs: %s PNGs: %s", len(jpegs), len(pngs))
|
||||||
return jpegs, pngs
|
return jpegs, pngs
|
||||||
|
|
||||||
|
|
||||||
def extract_images_jbig2(pike, root, options):
|
def extract_images_jbig2(pike: 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(pike, 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)
|
||||||
|
|
||||||
# Elide empty groups
|
# Elide empty groups
|
||||||
jbig2_groups = {
|
jbig2_groups = {
|
||||||
@@ -258,10 +290,12 @@ def extract_images_jbig2(pike, root, options):
|
|||||||
return jbig2_groups
|
return jbig2_groups
|
||||||
|
|
||||||
|
|
||||||
def _produce_jbig2_images(jbig2_groups, root, options):
|
def _produce_jbig2_images(
|
||||||
|
jbig2_groups: Dict[int, List[XrefExt]], root: Path, options
|
||||||
|
) -> None:
|
||||||
"""Produce JBIG2 images from their groups"""
|
"""Produce JBIG2 images from their groups"""
|
||||||
|
|
||||||
def jbig2_group_args(root, groups):
|
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():
|
||||||
prefix = f'group{group:08d}'
|
prefix = f'group{group:08d}'
|
||||||
yield dict(
|
yield dict(
|
||||||
@@ -270,7 +304,7 @@ def _produce_jbig2_images(jbig2_groups, root, options):
|
|||||||
out_prefix=prefix,
|
out_prefix=prefix,
|
||||||
)
|
)
|
||||||
|
|
||||||
def jbig2_single_args(root, groups):
|
def jbig2_single_args(root, 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
|
||||||
@@ -306,7 +340,9 @@ def _produce_jbig2_images(jbig2_groups, root, options):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def convert_to_jbig2(pike, jbig2_groups, root, options):
|
def convert_to_jbig2(
|
||||||
|
pike: Pdf, jbig2_groups: Dict[int, List[XrefExt]], root: Path, options
|
||||||
|
) -> None:
|
||||||
"""Convert images to JBIG2 and insert into PDF.
|
"""Convert images to JBIG2 and insert into PDF.
|
||||||
|
|
||||||
When the JBIG2 page group size is > 1 we do several JBIG2 images at once
|
When the JBIG2 page group size is > 1 we do several JBIG2 images at once
|
||||||
@@ -344,19 +380,19 @@ def convert_to_jbig2(pike, jbig2_groups, root, options):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def transcode_jpegs(pike, jpegs, root, options):
|
def transcode_jpegs(pike: Pdf, jpegs: Sequence[Xref], root: Path, options) -> None:
|
||||||
for xref in tqdm(
|
for xref in tqdm(
|
||||||
jpegs, desc="JPEGs", unit='image', disable=not options.progress_bar
|
jpegs, desc="JPEGs", unit='image', disable=not options.progress_bar
|
||||||
):
|
):
|
||||||
in_jpg = Path(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')
|
||||||
|
|
||||||
# This produces a debug warning from PIL
|
# This produces a debug warning from PIL
|
||||||
# DEBUG:PIL.Image:Error closing: 'NoneType' object has no attribute
|
# DEBUG:PIL.Image:Error closing: 'NoneType' object has no attribute
|
||||||
# 'close'. Seems to be mostly harmless
|
# 'close'. Seems to be mostly harmless
|
||||||
# https://github.com/python-pillow/Pillow/issues/1144
|
# https://github.com/python-pillow/Pillow/issues/1144
|
||||||
with Image.open(fspath(in_jpg)) as im:
|
with Image.open(in_jpg) as im:
|
||||||
im.save(fspath(opt_jpg), optimize=True, quality=options.jpeg_quality)
|
im.save(opt_jpg, optimize=True, quality=options.jpeg_quality)
|
||||||
|
|
||||||
if opt_jpg.stat().st_size > in_jpg.stat().st_size:
|
if opt_jpg.stat().st_size > in_jpg.stat().st_size:
|
||||||
log.debug("xref %s, jpeg, made larger - skip", xref)
|
log.debug("xref %s, jpeg, made larger - skip", xref)
|
||||||
@@ -367,8 +403,14 @@ def transcode_jpegs(pike, jpegs, root, options):
|
|||||||
im_obj.write(compdata.read(), filter=Name.DCTDecode)
|
im_obj.write(compdata.read(), filter=Name.DCTDecode)
|
||||||
|
|
||||||
|
|
||||||
def transcode_pngs(pike, images, image_name_fn, root, options):
|
def transcode_pngs(
|
||||||
modified = set()
|
pike: Pdf,
|
||||||
|
images: Sequence[Xref],
|
||||||
|
image_name_fn: Callable[[Path, Xref], Path],
|
||||||
|
root: Path,
|
||||||
|
options,
|
||||||
|
) -> None:
|
||||||
|
modified: MutableSet[Xref] = set()
|
||||||
if options.optimize >= 2:
|
if options.optimize >= 2:
|
||||||
png_quality = (
|
png_quality = (
|
||||||
max(10, options.png_quality - 10),
|
max(10, options.png_quality - 10),
|
||||||
@@ -431,7 +473,7 @@ def transcode_pngs(pike, images, image_name_fn, root, options):
|
|||||||
rewrite_png_as_g4(pike, im_obj, compdata)
|
rewrite_png_as_g4(pike, im_obj, compdata)
|
||||||
|
|
||||||
|
|
||||||
def rewrite_png_as_g4(pike, im_obj, compdata):
|
def rewrite_png_as_g4(pike: Pdf, im_obj: Object, compdata) -> None:
|
||||||
im_obj.BitsPerComponent = 1
|
im_obj.BitsPerComponent = 1
|
||||||
im_obj.Width = compdata.w
|
im_obj.Width = compdata.w
|
||||||
im_obj.Height = compdata.h
|
im_obj.Height = compdata.h
|
||||||
@@ -451,7 +493,7 @@ def rewrite_png_as_g4(pike, im_obj, compdata):
|
|||||||
return
|
return
|
||||||
|
|
||||||
|
|
||||||
def rewrite_png(pike, im_obj, compdata):
|
def rewrite_png(pike: Pdf, im_obj: Object, compdata) -> None:
|
||||||
# When a PNG is inserted into a PDF, we more or less copy the IDAT section from
|
# When a PNG is inserted into a PDF, we more or less copy the IDAT section from
|
||||||
# the PDF and transfer the rest of the PNG headers to PDF image metadata.
|
# the PDF and transfer the rest of the PNG headers to PDF image metadata.
|
||||||
# One thing we have to do is tell the PDF reader whether a predictor was used
|
# One thing we have to do is tell the PDF reader whether a predictor was used
|
||||||
@@ -504,7 +546,7 @@ def rewrite_png(pike, im_obj, compdata):
|
|||||||
im_obj.write(compdata.read(), filter=Name.FlateDecode, decode_parms=dparms)
|
im_obj.write(compdata.read(), filter=Name.FlateDecode, decode_parms=dparms)
|
||||||
|
|
||||||
|
|
||||||
def optimize(input_file, output_file, context, save_settings):
|
def optimize(input_file: Path, output_file: Path, context, save_settings) -> None:
|
||||||
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)
|
||||||
@@ -518,7 +560,7 @@ def optimize(input_file, output_file, context, save_settings):
|
|||||||
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 pikepdf.Pdf.open(input_file) as pike:
|
with pikepdf.Pdf.open(input_file) as pike:
|
||||||
root = Path(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(pike, root, options)
|
||||||
@@ -531,12 +573,12 @@ def optimize(input_file, output_file, context, save_settings):
|
|||||||
jbig2_groups = extract_images_jbig2(pike, root, options)
|
jbig2_groups = extract_images_jbig2(pike, root, options)
|
||||||
convert_to_jbig2(pike, jbig2_groups, root, options)
|
convert_to_jbig2(pike, jbig2_groups, root, options)
|
||||||
|
|
||||||
target_file = Path(output_file).with_suffix('.opt.pdf')
|
target_file = output_file.with_suffix('.opt.pdf')
|
||||||
pike.remove_unreferenced_resources()
|
pike.remove_unreferenced_resources()
|
||||||
pike.save(target_file, **save_settings)
|
pike.save(target_file, **save_settings)
|
||||||
|
|
||||||
input_size = Path(input_file).stat().st_size
|
input_size = input_file.stat().st_size
|
||||||
output_size = Path(target_file).stat().st_size
|
output_size = target_file.stat().st_size
|
||||||
if output_size == 0:
|
if output_size == 0:
|
||||||
raise OutputFileAccessError(
|
raise OutputFileAccessError(
|
||||||
f"Output file not created after optimizing. We probably ran "
|
f"Output file not created after optimizing. We probably ran "
|
||||||
@@ -557,8 +599,8 @@ def optimize(input_file, output_file, context, save_settings):
|
|||||||
|
|
||||||
|
|
||||||
def main(infile, outfile, level, jobs=1):
|
def main(infile, outfile, level, jobs=1):
|
||||||
from tempfile import TemporaryDirectory # pylint: disable=import-outside-toplevel
|
|
||||||
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
|
||||||
|
|
||||||
class OptimizeOptions:
|
class OptimizeOptions:
|
||||||
"""Emulate ocrmypdf's options"""
|
"""Emulate ocrmypdf's options"""
|
||||||
@@ -576,6 +618,7 @@ def main(infile, outfile, level, jobs=1):
|
|||||||
self.quiet = True
|
self.quiet = True
|
||||||
self.progress_bar = False
|
self.progress_bar = False
|
||||||
|
|
||||||
|
infile = Path(infile)
|
||||||
options = OptimizeOptions(
|
options = OptimizeOptions(
|
||||||
input_file=infile,
|
input_file=infile,
|
||||||
jobs=jobs,
|
jobs=jobs,
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ from pikepdf import PdfMatrix
|
|||||||
|
|
||||||
from ocrmypdf._concurrent import exec_progress_pool
|
from ocrmypdf._concurrent import exec_progress_pool
|
||||||
from ocrmypdf.exceptions import EncryptedPdfError
|
from ocrmypdf.exceptions import EncryptedPdfError
|
||||||
from ocrmypdf.helpers import Resolution, available_cpu_count
|
from ocrmypdf.helpers import Resolution, available_cpu_count, pikepdf_enable_mmap
|
||||||
from ocrmypdf.pdfinfo.layout import get_page_analysis, get_text_boxes
|
from ocrmypdf.pdfinfo.layout import get_page_analysis, get_text_boxes
|
||||||
|
|
||||||
logger = logging.getLogger()
|
logger = logging.getLogger()
|
||||||
@@ -91,7 +91,7 @@ UNIT_SQUARE = (1.0, 0.0, 0.0, 1.0, 0.0, 0.0)
|
|||||||
def _is_unit_square(shorthand):
|
def _is_unit_square(shorthand):
|
||||||
values = map(float, shorthand)
|
values = map(float, shorthand)
|
||||||
pairwise = zip(values, UNIT_SQUARE)
|
pairwise = zip(values, UNIT_SQUARE)
|
||||||
return all([isclose(a, b, rel_tol=1e-3) for a, b in pairwise])
|
return all(isclose(a, b, rel_tol=1e-3) for a, b in pairwise)
|
||||||
|
|
||||||
|
|
||||||
XobjectSettings = namedtuple('XobjectSettings', ['name', 'shorthand', 'stack_depth'])
|
XobjectSettings = namedtuple('XobjectSettings', ['name', 'shorthand', 'stack_depth'])
|
||||||
@@ -639,6 +639,7 @@ worker_pdf = None
|
|||||||
|
|
||||||
def _pdf_pageinfo_sync_init(infile):
|
def _pdf_pageinfo_sync_init(infile):
|
||||||
global worker_pdf # pylint: disable=global-statement
|
global worker_pdf # pylint: disable=global-statement
|
||||||
|
pikepdf_enable_mmap()
|
||||||
worker_pdf = pikepdf.open(infile)
|
worker_pdf = pikepdf.open(infile)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -220,8 +220,16 @@ class TextPositionTracker(PDFLayoutAnalyzer):
|
|||||||
|
|
||||||
def get_page_analysis(infile, pageno, pscript5_mode):
|
def get_page_analysis(infile, pageno, pscript5_mode):
|
||||||
rman = pdfminer.pdfinterp.PDFResourceManager(caching=True)
|
rman = pdfminer.pdfinterp.PDFResourceManager(caching=True)
|
||||||
|
if pdfminer.__version__ < '20200402':
|
||||||
|
# Workaround for https://github.com/pdfminer/pdfminer.six/issues/395
|
||||||
|
disable_boxes_flow = 2
|
||||||
|
else:
|
||||||
|
disable_boxes_flow = None
|
||||||
dev = TextPositionTracker(
|
dev = TextPositionTracker(
|
||||||
rman, laparams=LAParams(all_texts=True, detect_vertical=True, boxes_flow=None)
|
rman,
|
||||||
|
laparams=LAParams(
|
||||||
|
all_texts=True, detect_vertical=True, boxes_flow=disable_boxes_flow
|
||||||
|
),
|
||||||
)
|
)
|
||||||
interp = pdfminer.pdfinterp.PDFPageInterpreter(rman, dev)
|
interp = pdfminer.pdfinterp.PDFPageInterpreter(rman, dev)
|
||||||
|
|
||||||
|
|||||||
@@ -26,9 +26,10 @@ import pluggy
|
|||||||
from ocrmypdf.helpers import Resolution
|
from ocrmypdf.helpers import Resolution
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
from ocrmypdf._jobcontext import PageContext
|
from ocrmypdf._jobcontext import PageContext
|
||||||
from ocrmypdf.pdfinfo import PdfInfo
|
from ocrmypdf.pdfinfo import PdfInfo
|
||||||
from PIL import Image
|
|
||||||
|
|
||||||
hookspec = pluggy.HookspecMarker('ocrmypdf')
|
hookspec = pluggy.HookspecMarker('ocrmypdf')
|
||||||
|
|
||||||
@@ -122,6 +123,8 @@ def rasterize_pdf_page(
|
|||||||
Note:
|
Note:
|
||||||
This hook will be called from child processes. Modifying global state
|
This hook will be called from child processes. Modifying global state
|
||||||
will not affect the main process or other child processes.
|
will not affect the main process or other child processes.
|
||||||
|
Note:
|
||||||
|
This is a :ref:`firstresult hook<firstresult>`.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
@@ -130,11 +133,25 @@ def filter_ocr_image(page: 'PageContext', image: 'Image') -> 'Image':
|
|||||||
"""Called to filter the image before it is sent to OCR.
|
"""Called to filter the image before it is sent to OCR.
|
||||||
|
|
||||||
This is the image that OCR sees, not what the user sees when they view the
|
This is the image that OCR sees, not what the user sees when they view the
|
||||||
PDF.
|
PDF. If ``redo_ocr`` is enabled, portions of the image will be masked so
|
||||||
|
they are not shown to OCR. The main use of this hook is expected to be hiding
|
||||||
|
content from OCR.
|
||||||
|
|
||||||
|
The input image may be color, grayscale, or monochrome, and the
|
||||||
|
output image may differ. The pixel width and height of the
|
||||||
|
output image must be identical to the input image, or misalignment between
|
||||||
|
the OCR text layer and visual position of the text will occur. Likewise,
|
||||||
|
the output must be a faithful representation of the input, or alignment
|
||||||
|
errors may occurs.
|
||||||
|
|
||||||
|
Tesseract OCR only deals with monochrome images, and internally converts
|
||||||
|
non-monochrome images to OCR.
|
||||||
|
|
||||||
Note:
|
Note:
|
||||||
This hook will be called from child processes. Modifying global state
|
This hook will be called from child processes. Modifying global state
|
||||||
will not affect the main process or other child processes.
|
will not affect the main process or other child processes.
|
||||||
|
Note:
|
||||||
|
This is a :ref:`firstresult hook<firstresult>`.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
@@ -155,6 +172,8 @@ def filter_page_image(page: 'PageContext', image_filename: Path) -> Path:
|
|||||||
Note:
|
Note:
|
||||||
This hook will be called from child processes. Modifying global state
|
This hook will be called from child processes. Modifying global state
|
||||||
will not affect the main process or other child processes.
|
will not affect the main process or other child processes.
|
||||||
|
Note:
|
||||||
|
This is a :ref:`firstresult hook<firstresult>`.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
@@ -239,6 +258,9 @@ def get_ocr_engine() -> OcrEngine:
|
|||||||
The OcrEngine may be instantiated multiple times, by both the main process
|
The OcrEngine may be instantiated multiple times, by both the main process
|
||||||
and child process. As such, it must be obtain store any state in ``options``
|
and child process. As such, it must be obtain store any state in ``options``
|
||||||
or some common location.
|
or some common location.
|
||||||
|
|
||||||
|
Note:
|
||||||
|
This is a :ref:`firstresult hook<firstresult>`.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
@@ -275,4 +297,7 @@ def generate_pdfa(
|
|||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Path: If successful, the hook should return ``output_file``.
|
Path: If successful, the hook should return ``output_file``.
|
||||||
|
|
||||||
|
Note:
|
||||||
|
This is a :ref:`firstresult hook<firstresult>`.
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -1,40 +0,0 @@
|
|||||||
# © 2019 James R. Barlow: github.com/jbarlow83
|
|
||||||
#
|
|
||||||
# Permission is hereby granted, free of charge, to any person obtaining a
|
|
||||||
# copy of this software and associated documentation files (the
|
|
||||||
# "Software"), to deal in the Software without restriction, including
|
|
||||||
# without limitation the rights to use, copy, modify, merge, publish,
|
|
||||||
# distribute, sublicense, and/or sell copies of the Software, and to
|
|
||||||
# permit persons to whom the Software is furnished to do so, subject to
|
|
||||||
# the following conditions:
|
|
||||||
#
|
|
||||||
# The above copyright notice and this permission notice shall be included
|
|
||||||
# in all copies or substantial portions of the Software.
|
|
||||||
#
|
|
||||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
|
||||||
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
||||||
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
|
||||||
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
|
||||||
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
|
||||||
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
|
||||||
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
||||||
|
|
||||||
"""Find Ghostscript executable"""
|
|
||||||
|
|
||||||
|
|
||||||
import os
|
|
||||||
import shutil
|
|
||||||
|
|
||||||
|
|
||||||
def real_ghostscript(argv):
|
|
||||||
if os.name != 'nt':
|
|
||||||
gs = shutil.which('gs')
|
|
||||||
gs_args = [gs] + argv[1:]
|
|
||||||
os.execv(gs_args[0], gs_args)
|
|
||||||
else:
|
|
||||||
gs = shutil.which('gswin64c')
|
|
||||||
if not gs:
|
|
||||||
gs = shutil.which('gswin32c')
|
|
||||||
os.execv(gs, argv[1:])
|
|
||||||
|
|
||||||
return # Not reachable
|
|
||||||
+17
-9
@@ -16,27 +16,25 @@
|
|||||||
# along with OCRmyPDF. If not, see <http://www.gnu.org/licenses/>.
|
# along with OCRmyPDF. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
|
||||||
import os
|
|
||||||
from os import fspath
|
from os import fspath
|
||||||
from pickle import dumps, loads
|
from pickle import dumps, loads
|
||||||
from unittest.mock import patch
|
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from PIL import Image, ImageChops
|
from PIL import Image, ImageChops
|
||||||
|
|
||||||
import ocrmypdf.leptonica as lept
|
from ocrmypdf import leptonica as lp
|
||||||
|
|
||||||
|
|
||||||
def test_colormap_backgroundnorm(resources):
|
def test_colormap_backgroundnorm(resources):
|
||||||
# Issue #262 - unclear how to reproduce exactly, so just ensure leptonica
|
# Issue #262 - unclear how to reproduce exactly, so just ensure leptonica
|
||||||
# can handle that case
|
# can handle that case
|
||||||
pix = lept.Pix.open(resources / 'baiona_colormapped.png')
|
pix = lp.Pix.open(resources / 'baiona_colormapped.png')
|
||||||
pix.background_norm()
|
pix.background_norm()
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def crom_pix(resources):
|
def crom_pix(resources):
|
||||||
pix = lept.Pix.open(resources / 'crom.png')
|
pix = lp.Pix.open(resources / 'crom.png')
|
||||||
im = Image.open(resources / 'crom.png')
|
im = Image.open(resources / 'crom.png')
|
||||||
yield pix, im
|
yield pix, im
|
||||||
im.close()
|
im.close()
|
||||||
@@ -64,17 +62,17 @@ def test_pix_otsu(crom_pix):
|
|||||||
|
|
||||||
|
|
||||||
@pytest.mark.skipif(
|
@pytest.mark.skipif(
|
||||||
lept.get_leptonica_version() < 'leptonica-1.76',
|
lp.get_leptonica_version() < 'leptonica-1.76',
|
||||||
reason="needs new leptonica for API change",
|
reason="needs new leptonica for API change",
|
||||||
)
|
)
|
||||||
def test_crop(resources):
|
def test_crop(resources):
|
||||||
pix = lept.Pix.open(resources / 'linn.png')
|
pix = lp.Pix.open(resources / 'linn.png')
|
||||||
foreground = pix.crop_to_foreground()
|
foreground = pix.crop_to_foreground()
|
||||||
assert foreground.width < pix.width
|
assert foreground.width < pix.width
|
||||||
|
|
||||||
|
|
||||||
def test_clean_bg(resources):
|
def test_clean_bg(resources):
|
||||||
pix = lept.Pix.open(resources / 'congress.jpg')
|
pix = lp.Pix.open(resources / 'congress.jpg')
|
||||||
imbg = pix.clean_background_to_white()
|
imbg = pix.clean_background_to_white()
|
||||||
|
|
||||||
|
|
||||||
@@ -96,4 +94,14 @@ def test_leptonica_compile(tmp_path):
|
|||||||
|
|
||||||
def test_file_not_found():
|
def test_file_not_found():
|
||||||
with pytest.raises(FileNotFoundError):
|
with pytest.raises(FileNotFoundError):
|
||||||
lept.Pix.open("does_not_exist1")
|
lp.Pix.open("does_not_exist1")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.skipif(
|
||||||
|
lp.get_leptonica_version() < 'leptonica-1.79.0',
|
||||||
|
reason="test not reliable on all platforms for old leptonica",
|
||||||
|
)
|
||||||
|
def test_error_trap():
|
||||||
|
with pytest.raises(lp.LeptonicaError, match=r"Error in pixReadMem"):
|
||||||
|
with lp._LeptonicaErrorTrap():
|
||||||
|
lp.Pix(lp.lept.pixReadMem(lp.ffi.NULL, 0))
|
||||||
|
|||||||
@@ -877,3 +877,17 @@ def test_image_dpi_not_image(caplog, resources, outpdf):
|
|||||||
'tests/plugins/tesseract_noop.py',
|
'tests/plugins/tesseract_noop.py',
|
||||||
)
|
)
|
||||||
assert '--image-dpi is being ignored' in caplog.text
|
assert '--image-dpi is being ignored' in caplog.text
|
||||||
|
|
||||||
|
|
||||||
|
def test_image_dpi_threshold(resources, outpdf):
|
||||||
|
check_ocrmypdf(
|
||||||
|
resources / 'typewriter.png',
|
||||||
|
outpdf,
|
||||||
|
'--threshold',
|
||||||
|
'--image-dpi=170',
|
||||||
|
'--output-type=pdf',
|
||||||
|
'--optimize=0',
|
||||||
|
'--plugin',
|
||||||
|
'tests/plugins/tesseract_noop.py',
|
||||||
|
)
|
||||||
|
assert outpdf.exists()
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ from unittest.mock import patch
|
|||||||
import pikepdf
|
import pikepdf
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
import ocrmypdf._validation as vd
|
from ocrmypdf import _validation as vd
|
||||||
from ocrmypdf._plugin_manager import get_plugin_manager
|
from ocrmypdf._plugin_manager import get_plugin_manager
|
||||||
from ocrmypdf.api import create_options
|
from ocrmypdf.api import create_options
|
||||||
from ocrmypdf.cli import get_parser
|
from ocrmypdf.cli import get_parser
|
||||||
@@ -141,7 +141,7 @@ def test_report_file_size(tmp_path, caplog):
|
|||||||
pdf = pikepdf.new()
|
pdf = pikepdf.new()
|
||||||
pdf.save(in_)
|
pdf.save(in_)
|
||||||
pdf.save(out)
|
pdf.save(out)
|
||||||
opts = make_opts()
|
opts = make_opts(output_type='pdf')
|
||||||
vd.report_output_file_size(opts, in_, out)
|
vd.report_output_file_size(opts, in_, out)
|
||||||
assert caplog.text == ''
|
assert caplog.text == ''
|
||||||
caplog.clear()
|
caplog.clear()
|
||||||
@@ -166,7 +166,7 @@ def test_report_file_size(tmp_path, caplog):
|
|||||||
assert 'optional dependency' in caplog.text
|
assert 'optional dependency' in caplog.text
|
||||||
caplog.clear()
|
caplog.clear()
|
||||||
|
|
||||||
opts = make_opts(in_, out, optimize=0)
|
opts = make_opts(in_, out, optimize=0, output_type='pdf')
|
||||||
vd.report_output_file_size(opts, in_, out)
|
vd.report_output_file_size(opts, in_, out)
|
||||||
assert 'disabled' in caplog.text
|
assert 'disabled' in caplog.text
|
||||||
caplog.clear()
|
caplog.clear()
|
||||||
|
|||||||
Reference in New Issue
Block a user