Showing preview only (331K chars total). Download the full file or copy to clipboard to get everything.
Repository: measuresforjustice/textricator
Branch: main
Commit: 9c9a5cdeba4a
Files: 82
Total size: 303.5 KB
Directory structure:
gitextract_24_mshfj/
├── .gitignore
├── CODEOWNERS
├── COPYING
├── NOTICE
├── README.md
├── pom.xml
└── src/
├── assembly/
│ ├── tgz.xml
│ └── zip.xml
├── main/
│ ├── java/
│ │ └── io/
│ │ └── mfj/
│ │ └── textricator/
│ │ ├── Textricator.kt
│ │ ├── Version.kt
│ │ ├── cli/
│ │ │ └── TextricatorCli.kt
│ │ ├── extractor/
│ │ │ ├── TextExtractor.kt
│ │ │ ├── TextExtractorFactory.kt
│ │ │ ├── TextExtractorOptions.kt
│ │ │ ├── csv/
│ │ │ │ ├── CsvTextExtractor.kt
│ │ │ │ └── CvsTextExtractorFactory.kt
│ │ │ ├── itext5/
│ │ │ │ ├── Box.kt
│ │ │ │ ├── Boxtricator.kt
│ │ │ │ ├── Buffer.kt
│ │ │ │ ├── Itext5TextExtractor.kt
│ │ │ │ ├── Itext5TextExtractorFactory.kt
│ │ │ │ ├── Shenanigans.kt
│ │ │ │ └── Size.kt
│ │ │ ├── itext7/
│ │ │ │ ├── Itext7TextExtractor.kt
│ │ │ │ └── Itext7TextExtractorFactory.kt
│ │ │ ├── json/
│ │ │ │ ├── JsonTextExtractor.kt
│ │ │ │ └── JsonTextExtractorFactory.kt
│ │ │ └── pdfbox/
│ │ │ ├── PdfboxTextExtractor.kt
│ │ │ ├── PdfboxTextExtractorFactory.kt
│ │ │ └── TextBoxPdfTextStripper.kt
│ │ ├── form/
│ │ │ ├── FormParseEventListener.kt
│ │ │ ├── FsmEventListener.kt
│ │ │ ├── FsmParser.kt
│ │ │ ├── LoggingEventListener.kt
│ │ │ ├── RecordParser.kt
│ │ │ ├── RecordParserEventListener.kt
│ │ │ ├── StateValue.kt
│ │ │ ├── WriterEventListener.kt
│ │ │ └── config/
│ │ │ ├── DefaultAndPages.kt
│ │ │ ├── FormParseConfig.kt
│ │ │ ├── FormParseConfigUtil.kt
│ │ │ ├── State.kt
│ │ │ ├── Transition.kt
│ │ │ └── VariableSet.kt
│ │ ├── record/
│ │ │ ├── Record.kt
│ │ │ ├── RecordFilter.kt
│ │ │ ├── RecordModel.kt
│ │ │ ├── Value.kt
│ │ │ └── output/
│ │ │ ├── CsvRecordOutput.kt
│ │ │ ├── JsonFlatRecordOutput.kt
│ │ │ ├── JsonRecordOutput.kt
│ │ │ ├── NullOutput.kt
│ │ │ ├── RecordOutput.kt
│ │ │ └── XmlRecordOutput.kt
│ │ ├── table/
│ │ │ ├── Table.kt
│ │ │ ├── TableParser.kt
│ │ │ └── config/
│ │ │ ├── TableParseConfig.kt
│ │ │ └── TableParseConfigUtil.kt
│ │ └── text/
│ │ ├── Page.kt
│ │ ├── PageFilter.kt
│ │ ├── RowGrouper.kt
│ │ ├── Text.kt
│ │ └── output/
│ │ ├── CsvTextOutput.kt
│ │ ├── JsonTextOutput.kt
│ │ └── TextOutput.kt
│ └── resources/
│ └── io/
│ └── mfj/
│ └── textricator/
│ ├── extractor/
│ │ └── textExtractor.properties
│ ├── logback.xml
│ └── version.properties
├── scripts/
│ ├── textricator
│ └── textricator.bat
└── test/
├── java/
│ └── io/
│ └── mfj/
│ └── textricator/
│ ├── examples/
│ │ └── ExamplesTest.kt
│ ├── form/
│ │ ├── NodeMembersTest.kt
│ │ ├── PatternReplacementTest.kt
│ │ └── RecordParserTest.kt
│ └── record/
│ ├── RecordFilterTest.kt
│ └── output/
│ ├── CsvOutputTest.kt
│ └── XmlOutputTest.kt
└── resources/
└── io/
└── mfj/
└── textricator/
└── examples/
├── probes.yml
├── rap-sheet.csv
├── rap-sheet.yml
├── school-employee-list.csv
└── school-employee-list.yml
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
target/
.idea/
*.iml
================================================
FILE: CODEOWNERS
================================================
# This is the CODEOWNERS file for the textricator repo.
# These owners will be the default owners for everything in the repo, unless a
# later match takes precedence.
* @lschumann-mfj @wstumbo-mfj
# Make sure that DevOps is aware of anything GitHub related
/.github/ @lschumann-mfj @wstumbo-mfj @SB-MFJ @meghanbissonnette-mfj
================================================
FILE: COPYING
================================================
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://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 <https://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
<https://www.gnu.org/licenses/>.
================================================
FILE: NOTICE
================================================
Textricator
Copyright 2018 Measures for Justice Institute.
================================================
FILE: README.md
================================================
# 
_Textricator_ is a tool to extract text from documents and generate structured data.
If you have a bunch of PDFs with the same format (or one big, consistently formatted PDF)
and you want to extract the data to CSV, XML, or JSON, _Textricator_ can help!
It can even work on OCR'ed documents!
_Textricator_ is released under the
[GNU Affero General Public License Version 3](https://www.gnu.org/licenses/agpl-3.0.en.html).
_Textricator_ is deployed to [Maven Central](https://repo1.maven.org/maven2/io/mfj/textricator/) with GAV `io.mfj:textricator`.
This application is actively used and developed by [Measures for Justice](https://measuresforjustice.org).
We welcome feedback, bug reports, and contributions. Create an issue, send a pull request,
or email us at <textricator@mfj.io>. If you use _Textricator_, please let us know.
Send us your mailing address and we will mail you a sticker.
`io.mfj.textricator.Textricator` is the main entry point for library usage.
`io.mfj.textricator.cli.TextricatorCli` is the command-line interface.
The CLI has three subcommands, to use the three main features of Textricator:
* text - Extract text from the PDF and generate JSON.
* table - Parse the text that is in columns and rows. See [Table](#table) section.
* form - Parse the text with a configured finite state machine. See [Form](#form) section.
## Quick Start
- Install Java (version 11+)
* Windows & Macos: Download from [https://java.com](https://java.com) and install.
* Linux: Use your package manager.
- Download the latest build of _Textricator_ from [https://repo1.maven.org/maven2/io/mfj/textricator/](https://repo1.maven.org/maven2/io/mfj/textricator/) - click on the directory for the latest version and download `textricator-VERSION-bin.tgz` (or `textricator-VERSION-bin.zip` for Windows).
- Extract it.
- Run a shell
* Windows: run _Windows Powershell_ (it should be in the start menu)
* The following examples start with `./textricator`. On Windows, use `.\textricator.bat`.
* MacOS: Run _Terminal_ (type "terminal" in Spotlight)
- Show help
- `./textricator --help`
- Download the example files to the textricator directory:
* https://github.com/measuresforjustice/textricator/blob/main/src/test/resources/io/mfj/textricator/examples/school-employee-list.pdf
* https://github.com/measuresforjustice/textricator/blob/main/src/test/resources/io/mfj/textricator/examples/school-employee-list.yml
- Extract raw text from a PDF to standard out
- `./textricator text --input-format=pdf.pdfbox school-employee-list.pdf`
- Parse a PDF to CSV
- `./textricator form --config=school-employee-list.yml school-employee-list.pdf school-employee-list.csv`
* This uses the configuration file `school-employee-list.yml` to parse `school-employee-list.pdf`.
To parse your own PDF form, you will need to write your own configuration file.
See the [Form](#form) section for details.
If your PDF has a tabular layout, see the [Table](#table) section.
## Logging
Use the `--debug` flag to log everything.
Logging is written to standard error.
Textricator uses [SLF4J](https://slf4j.org) for logging, with the [Logback](https://logback.qos.ch) implementation.
If you are using Textricator as a library, you may want to exclude `ch.qos.logback:logback-classic`.
Textricator does *not* include a `/logback.xml`, so it will not conflict with other logging configurations,
so long as `TextricatorCli.main()` is not invoked.
## Extracting text
To extract the text from a PDF, run
`textrictor text --input-format=pdf.itext5 input.pdf input-text.csv`
for any `input.pdf` and then open `input-text.csv` in your favorite spreadsheet program.
It will show you every bit of text that Textricator sees with its position, size,
and font information. This information is very useful for building configuration to parse
tables or forms using Textricator (see the following two sections).
Try `--input-format=pdf.itext7` and `--input-format=pdf.pdfbox` to see how Textricator
extracts the texts using the different parser engines. Some work better for some documents
than others.
## Table
In table mode, the data is grouped into columns based on the x-coordinate of the text.
### Example
This is an example for `src/test/resources/io/mfj/textricator/examples/probes.pdf`.
```yaml
# All measurements are in points. 1 point = 1/72 of an inch.
# x-coordinates are from the left edge of the page.
# y-coordinates are from the top edge of the page.
# Use the built-in pdfbox extractor
extractor: "pdf.pdfbox"
# Ignore everything above 88pt from the top
top: 88
# Ignore everything below 170pt from the top
bottom: 170
# If multiple text segments are withing 2pt vertically, consider them in the same row.
maxRowDistance: 2
# Define the columns, based on the x-coordinate where the column starts:
cols:
"name": 0
"launched": 132
"speed": 235
"cospar": 249
"power": 355
"mass": 415
types:
"name":
label: "Name"
"launched":
label: "Launch Date"
"speed":
label: "Speed (km/s)"
type: "number"
"cospar":
label: "COSPAR ID"
"power":
label: "Power (watts)"
type: "number"
"mass":
label: "Mass (pounds)"
# Add .0 to the end of mass
replacements:
-
pattern: "^(.*)$"
replacement: "$1.0"
# Omit if Power is less than 200
filter: 'power >= 200'
```
## Form
In form mode, the data is parsed by Textricator using a
[finite-state machine](https://en.wikipedia.org/wiki/Finite-state_machine) (FSM),
and the FSM and additional parsing and formatting parameters are configured with
[YAML](https://en.wikipedia.org/wiki/YAML), indicated by command line option `--config`.
### Conditions
State transitions are selected by evaluating conditions. Conditions are expressions parsed by
[Expr](https://github.com/measuresforjustice/expr).
#### Available variables:
* `ulx` - x coordinate of the upper-left corner of the text box
* `uly` - y coordinate of the upper-left corner of the text box
* `lrx` - x coordinate of the lower-right corner of the text box
* `lry` - y coordinate of the lower-right corner of the text box
* `text` - the text
* `page` - page number
* `page_prev` - page number of the previous text
* `fontSize` - font size
* `font` - font name
* `color` - text color
* `bgcolor` - background color
* `width` - width of the text box
* `height` - height of the text box
* `ulx_rel` - difference in `ulx` between the previous and current texts
* `uly_rel` - difference in `uly` between the previous and current texts
* `lrx_rel` - difference in `lrx` between the previous and current texts
* `lry_rel` - difference in `lry` between the previous and current texts
* [added Variables](#variables)
### Example
This is an example for `src/test/resources/io/mfj/textricator/examples/school-employee-list.pdf`.
```yaml
# Use the built-in pdfbox parser
extractor: "pdf.pdfbox"
# All measurements are in points. 1 point = 1/72 of an inch.
# x-coordinates are from the left edge of the page.
# y-coordinates are from the top edge of the page.
header:
# ignore anything less than this many points from the top, default and per-page
default: 130
footer:
# ignore anything more than this many points from the top, default and per-page
default: 700
# Text segments are generally parsed in order, top to bottom, left to right.
# If two text segments have y-coordinates within this many points, consider them on the same line,
# and process the one further left first, even if it is 0.4pt lower on the page.
maxRowDistance: 2
# Define the output data record.
# Since the main record type we're collecting information on is our employees,
# we'll have that be the root type for our harvested information.
rootRecordType: employee
recordTypes:
employee:
label: "employee" # Labels are used when nested recordTypes come into play, like this document.
valueTypes:
# Not sure what to name a valueType? Just make something up!
- employee
- name
- hiredate
- occupation
- showinfo
- bool1
- bool2
- bool3
- salary
children:
# In this example, there are multiple children nested under an employee,
# so we'll treat it as a 'child' to the 'employee' recordType.
- child
child:
label: "child"
valueTypes:
- child
- grade
valueTypes:
employee:
# In the CSV, use "Employee ID" as the column header instead of "employee".
label: "Employee ID"
name:
label: "Name"
hiredate:
label: "Hire Date"
occupation:
label: "Occupation"
salary:
label: "Salary"
showinfo:
label: "Important Info?"
bool1:
label: "Boolean 1"
bool2:
label: "Boolean 2"
bool3:
label: "Boolean 3"
child:
label: "Attending Child"
grade:
label: "Grade"
# Now we define the finite-state machine
# Let's name the state that our machine starts off with:
initialState: "INIT"
# When each text segment is encountered, each transition for the current state is checked.
states:
INIT:
transitions:
# The first bit of text we reach is 'ID-0001', so we'll try the only transition that should work here.
-
# If this condition matches (which it should)
condition: employee # Curious about the condition? Sxroll further down to the conditions section of this YAML.
# Then we'll switch to the 'employee' state!
nextState: employee
employee: # ID number with the format 'ID-####'
startRecord: true # When we enter this stage, we'll create a new "case" record.
transitions:
- # Now we move on to the name label. Once again, by varifying the condition and moving on after that.
condition: namelabel
nextState: namelabel
namelabel:
include: false # The label isn't important information in and of itself, so we can just not include it in the data.
transitions:
-
condition: name
nextState: name
name:
transitions:
-
# Sometimes a name will be in two segments, and we'll hit another 'name' text segment before anything else.
# In that case, a state can transition to itself, compounding the information picked up in it.
condition: name
nextState: name
-
# Does the first condition not match the text? We move onto the next one.
condition: hiredateLabel
nextState: hiredateLabel
hiredateLabel:
include: false
transitions:
-
condition: hiredateLabel
nextState: hiredateLabel
-
condition: hiredate
nextState: hiredate
hiredate:
transitions:
-
condition: occupationLabel
nextState: occupationLabel
occupationLabel:
include: false
transitions:
-
condition: occupation
nextState: occupation
occupation:
transitions:
-
condition: occupation
nextState: occupation
-
# This state and the next are an example of how you can choose, using conditions, what to include or not.
# They share the same area of a document, but have qualities to them that can be distinguishable.
# Does it meet 'showinfo' conditions? Then we go to the 'showinfo' state that includes it.
condition: showinfo
nextState: showinfo
-
# Doesn't meet 'showinfo'? Then check for 'notinfo' and exclude it.
condition: notinfo
nextState: notinfo
showinfo:
transitions:
-
condition: showinfo
nextState: showinfo
-
condition: bool1
nextState: bool1
notinfo:
include: false
transitions:
-
condition: notinfo
nextState: notinfo
-
condition: bool1
nextState: bool1
bool1:
transitions:
-
condition: bool2
nextState: bool2
bool2:
transitions:
-
condition: bool3
nextState: bool3
bool3:
transitions:
-
condition: salaryLabel
nextState: salaryLabel
salaryLabel:
include: false
transitions:
-
condition: salary
nextState: salary
salary:
transitions:
-
condition: childrenLabel
nextState: childrenLabel
-
condition: employee
nextState: employee
-
condition: end
nextState: end
childrenLabel:
include: false
transitions:
-
condition: childrenLabel
nextState: childrenLabel
-
condition: childLabel
nextState: childLabel
childLabel:
include: false
transitions:
-
condition: child
nextState: child
child:
# Here we reach a datatype nested within another datatype. We can start records using this child datatype.
# In the process, we'll be making multiple rows for the parent datatype, each one holding onto it's own child.
startRecord: true
transitions:
-
condition: child
nextState: child
-
condition: gradeLabel
nextState: gradeLabel
-
condition: childLabel
nextState: childLabel
gradeLabel:
include: false
transitions:
-
# Normally, there would always been an instance of a grade appearing right after the label.
# But in this document, we have one instance of that not happening under ID-0007's child.
condition: grade
nextState: grade
-
# So we just account for that possibility by adding a transition out of the label.
condition: employee
nextState: employee
grade:
transitions:
-
condition: employee
nextState: employee
-
condition: childLabel
nextState: childLabel
-
# Reach the end of the usable info in a document, but there's still text left to go?
# An easy fix is to just create a looping, not-included state to finish the document off.
condition: end
nextState: end
end:
# We reached a point in the document where all the useful information is gone, but we still have text to go.
include: false
transitions:
-
# By using an always-true condition such as 'any', we can loop this state until the document has been completely gone through.
condition: any
nextState: end
# Here we define the conditions:
conditions:
# An example of comparing text with regex.
# In this case, we're making sure that the text contains the characters 'ID-' followed by any amount of numbers.
employee: 'text =~ /ID-(\\d)*/'
# You can match based on the x- and y- coordinates of the upper left and lower right corners of the rectangle
# containing the text. ulx = Upper-Left X-coordinate. lry = Lower-Right Y-coordinate. Also uly and lrx.
# You can define the lower and upper limit for each, inclusive.
namelabel: '70 < ulx < 80 and font = "BCDFEE+Calibri-Bold"'
# You can also match based on the type of font used, including if it was bolded or italicized.
name: '112 < ulx < 200 and font = "BCDEEE+Calibri"'
hiredateLabel: '230 < ulx < 270 and font = "BCDFEE+Calibri-Bold"'
hiredate: '280 < ulx < 290 and font = "BCDEEE+Calibri"'
occupationLabel: '391 < ulx < 393 and font = "BCDFEE+Calibri-Bold"'
occupation: '394 < ulx < 700 and font = "BCDEEE+Calibri"'
showinfo: 'font = "BCDJEE+Georgia"'
notinfo: 'font = "BCDEEE+Calibri"'
bool1: 'font = "BCDIEE+Cambria"'
bool2: 'font = "BCDIEE+Cambria"'
bool3: 'font = "BCDIEE+Cambria"'
salaryLabel: '391 < ulx < 393 and font = "BCDFEE+Calibri-Bold"'
salary: '394 < ulx < 700 and font = "BCDEEE+Calibri"'
childrenLabel: '70 < ulx < 140 and font = "BCDFEE+Calibri-Bold" and text =~ /(Attending)|(Children:)/'
childLabel: '230 < ulx < 240 and font = "BCDFEE+Calibri-Bold"'
child: '230 < ulx < 380 and font = "BCDEEE+Calibri"'
gradeLabel: '391 < ulx < 393 and font = "BCDFEE+Calibri-Bold"'
grade: '394 < ulx < 700 and font = "BCDEEE+Calibri"'
# You can also match based on the size of the font and on specific text.
end: 'fontSize = 16.0 and text = "TOTAL:"'
# Need a condition that is always true? "1=1" does that for you.
any: "1 = 1"
```
### Advanced functionality
#### Regex matching
You can use regular expression matching instead of exact string matching in conditions:
```yaml
conditions:
caseTypeLabel: 'text =~ /Case Type:?/' # maybe sometimes they forgot the ":"
```
#### Font matching
You can match font and font size:
```yaml
conditions:
helvetica8: 'font =~ /.*Helvetica.*/ and fontSize = 8'
```
#### Page number matching
You can match the page number
```yaml
conditions:
# Match the textbox that starts at 100pt,120pt on page 9.
specificTextbox: 'page = 9 and ulx = 100 and uly = 120'
```
#### Requiring intermediate state
There may be cases where you want to transition from state "B" to state "A" and start a new record,
but ONLY if you were in state "C" since last starting a new record:
```yaml
states:
A:
startRecord: true
startRecordRequiredState: C
# ...
```
#### Combining states
You may have 2 different states that you want to combine into one column in the output:
```yaml
recordTypes:
record:
label: "Record"
valueTypes:
- A
# no A2
- B
states:
A:
# ...
A2:
valueTypes: [ A ] # combine this with state "A".
# ...
```
#### Joining text segments in a state
When there are multiple text segments in the same state, by default they are concatenated with a space in between.
Any string, including an empty string, can be used as the separator:
```yaml
valueTypes:
recordId:
# concatenate without spaces between
label: "Record ID"
separator: ""
description:
# put newlines between text segments
label: "Description"
separator: "
"
```
#### Exclude types from output
A value type (`dataRecordMember`) can be excluded from the output.
This is useful if the type is repeated on the PDF and needed as a data type to set new records,
but should not be in the output.
```yaml
valueTypes:
repeatedId:
include: false
```
#### Relative offsets
Conditions can evaluate coordinates relative to the coordinates of the previous text.
This is useful for matching only something on the next line:
```yaml
maxRowDistance: 2
conditions:
# These should generally be the same (absolute value) as maxRowDistance
descriptionSameLine: '-2 <= uly_rel <= 2'
descriptionOneLineDown: '12 <= uly_rel <= 16' # for 12pt, single-spaced font.
```
#### Control which page number in output
If a complex data record spans multiple pages, which page number is used for the output can be controlled.
Each type (`dataRecordType`) has a page priority (default: 0).
The page number for the record comes from the type with the highest priority.
```yaml
recordTypes:
agency:
label: "Agency"
valueTypes:
- agencyName
children:
- case
# Agency may span hundreds of pages
# default page priority of 0
case:
label: "Case"
valueTypes:
- caseNumber
- name
children:
- charge
# Case record may span multiple pages.
# Higher priority than agency but lower than charges,
so case is used if there are no charges.
pagePriority: 1
charge:
label: "Charge"
valueTypes:
- chargeNumber
# Highest priority. Use charge's page number.
pagePriority: 2
```
#### Exclude
Text segments can be excluded before processing by the finite-state machine
by adding condition name to the `excludeConditions` list.
If any of the conditions match, the text segment is excluded.
For example, to exclude all text segments that consist solely of underscores:
```yaml
excludeConditions:
- underline
conditions:
underline: 'text =~ /_+/'
```
#### Starting new records for each value
TODO
#### Regex replacement of values
Sometimes the value contains a label, or other text you want to remove.
In a `dataRecordMember`, add a `replacement`, which has a `pattern`,
which is a regular expression with capturing groups,
and `replacement`, which is a replacement string with group references.
See `java.util.regex.Pattern` and `java.util.regex.Matcher` for details.
```yaml
# Replace "Bond Agency: Fred's Bonds" with "Fred's Bonds"
valueTypes:
bondagency:
label: "Bond Agency"
replacements:
-
pattern: "Bond Agency:\ *(.*)"
replacement: "$1"
```
#### Variables<a name="variables"></a>
On entering a state, a variable can be set.
In `State`, add a `setVariable`, which has `name` of the variable and the `value` to set.
If the `value` starts with `{` and ends with `}`, the content can be any built-in variable or previously
set `variable` - the same things usable as variables for conditions.
For example: a condition checks that has the same background color as the last caseNo:
```yaml
states:
caseNo:
setVariables:
-
name: "lastCaseBgColor"
value: "{bgcolor}"
conditions:
sameBgColor: >
145 <= ulx
and fontSize = 8
and bgcolor = lastCaseBgColor
```
#### Splitting one PDF field into multiple CSV columns
One field in the PDF can be broken up into multiple columns in the CSV file, based on
different regular expressions and replacements:
```yaml
# Take a field that contains lastName,firstName and split it into 2 fields - lastName and firstName
recordTypes:
inmateName:
label: "inmateName"
valueTypes:
- lastName
- firstName
valueTypes:
lastName:
label: "Last Name"
replacements:
-
# lastName column will contain what's before comma
pattern: "(.*),.*"
replacement: "$1"
firstName:
label: "First Name"
replacements:
-
# firstName column will contain what's after comma
pattern: ".*,(.*)"
replacement: "$1"
states:
name:
# when FSM hits state "name", split data into lastName and firstName
valueTypes:
- lastName
- firstName
```
#### Hyperlinks
If the text is a hyperlink, the URL can be used intead of the text by
setting `valueTypes.attribute` to `url`.
This is supported only by the `itext5` and `itext7` parsers.
```yaml
recordTypes:
company:
label: "Company"
valueTypes:
- name
- website
valueTypes:
name:
label: "Company Name"
website:
label: "Website"
attribute: url # use the link URL instead of the text.
states:
name:
# Put the value in both "name" and "website" to get both the
# text and the url into the output.
valueTypes:
- name
- website
```
#### Filtering records
Records can be filtered before output by setting a filter on the `dataRecordType`. Root records
with a non-matching filter will not be output. Child records with a non-matching filter will
be removed from their parent - the root will still be output.
Filters are expressions parsed by
[Expr](https://github.com/measuresforjustice/expr)
The variables are the fields in the record. The default type for variables is `STRING`.
The type can be set by setting `type` in the `dataRecordMember` to `string` or `number`.
```yaml
recordTypes:
case:
label: "Case"
# Only include cases in 2009-2013
filter: "2009 <= year <= 2013"
valueTypes:
- year
- name
children:
- charge
charge:
label: "Charge"
# omit charges of type "dummy"
filter: >
not( type = "dummy" )
valueTypes:
- code
- type
valueTypes:
year:
type: number
```
Filtering happens after replacements and before member include checking.
This allows splitting a field (e.g.: extracting a year from a date)
to use in the filter, and not including the split field in the output.
#### Processing multiple files together
Multiple files using the same form config can be parsed and written to a single output
with the `forms` CLI subcommand or with `io.mfj.textricator.Textricator.parseForms`.
The output will include the source file name for each record.
## Extractors
Extractors extract text (instances of `io.mfj.textricator.text.Text`) from a source.
There are four included extractors:
* _pdf.pdfbox_ - Extract text from PDF files using [Apache PDFBox](https://pdfbox.apache.org).
* _pdf.itext5_ - Extract text from PDF files using [iText 5](https://itextpdf.com/itext-5-core).
* _pdf.itext7_ - Extract text from PDF files using [iText 7](https://itextpdf.com/itext-7-core).
* _json_ - Parse text from the JSON format generated by the "text" subcommand of the CLI and by `io.mfj.textricator.Textricator.parseText()`.
* _csv_ - Parse text from the CSV format generatetd by the "text" subcommand of the CLI and by `io.mfj.textricator.Textricator.parseText()`
Other extractors modules may be loaded, which may support different source types,
capture different information or split the text up differently.
An extractor module is loaded by adding a properties file
`io/mfj/textricator/extractor/textExtractor.properties` to the classpath with a single property -
the key is the extractor name and the value is the fully-qualified class name of an implementation of
`io.mfj.textricator.extractor.TextExtractorFactory`.
Typically an extractor module will be distributed as a JAR that includes `textExtractor.properties`.
Indicate which extractor to use by setting `extractor` in the yaml configuration,
or overriding it by passing the extractor name to the `inputFormat`/`--input-format` option.
If the extractor is not specified and the input is PDF, `pdf.itext5` is used.
## Versioning
_Textricator_'s version is of the format `major.minor.build`.
The major number is incremented for breaking changes or major new features.
The minor number is incremented for minor new features.
The build number is generated by [Measures for Justice](https://measuresforjustice.org)'s private CI tool.
It is incremented for each build, regardless of the major and minor numbers
(it does not reset to zero when minor or major numbers are increased).
## Acknowledgements
Much credit is due to some people who do not show up in the commit history:
* Joe Hale, for the original idea and prototype
* John Castaneda and Abbie Miehle who, as the first end users, provided excellent
bug reports, improvements, documentation, and examples.

================================================
FILE: pom.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.mfj</groupId>
<artifactId>textricator</artifactId>
<version>10.2-SNAPSHOT</version>
<name>${project.groupId}:${project.artifactId}</name>
<description>A tool to extract text from documents and generate structured data</description>
<url>https://textricator.mfj.io/</url>
<developers>
<developer>
<name>Measures for Justice</name>
<email>opensource@measuresforjustice.org</email>
<organization>Measures for Justice</organization>
<organizationUrl>https://measuresforjustice.org/</organizationUrl>
</developer>
</developers>
<licenses>
<license>
<name>GNU Affero General Public License, Version 3</name>
<url>https://www.gnu.org/licenses/agpl-3.0.txt</url>
</license>
</licenses>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<kotlin.compiler.jvmTarget>11</kotlin.compiler.jvmTarget>
<kotlin.version>1.9.25</kotlin.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<copyright.year>2025</copyright.year>
<source.location>https://github.com/measuresforjustice/textricator</source.location>
</properties>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlinx</groupId>
<artifactId>kotlinx-coroutines-core</artifactId>
<version>1.7.3</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
<version>${kotlin.version}</version>
<!-- Apache 2.0 -->
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-test-junit</artifactId>
<version>${kotlin.version}</version>
<!-- Apache 2.0 -->
<scope>test</scope>
</dependency>
<!-- kotlin-reflect is a dependency of com.fasterxml.jackson.module:jackson-module-kotlin.
Include it here and exclude it below to make sure it is the same version of Kotlin. -->
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId>
<version>${kotlin.version}</version>
<!-- Apache 2.0 -->
</dependency>
<dependency>
<groupId>io.mfj</groupId>
<artifactId>expr</artifactId>
<version>6.2.39</version>
<!-- Apache 2.0 -->
</dependency>
<!-- PDFBox -->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.30</version>
<!-- Apache 2.0 -->
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox-tools</artifactId>
<version>2.0.30</version>
<!-- Apache 2.0 -->
</dependency>
<!-- iText 5 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.3</version>
<!-- AGPL -->
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk18on</artifactId>
<version>1.78</version>
<!-- MIT -->
</dependency>
<!-- iText 7 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>kernel</artifactId>
<version>8.0.2</version>
<!-- AGPL -->
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>layout</artifactId>
<version>8.0.2</version>
<!-- AGPL -->
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.3</version>
<!-- Apache 2.0 -->
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.15.3</version>
<!-- Apache 2.0 -->
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>2.15.3</version>
<!-- Apache 2.0 -->
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-kotlin</artifactId>
<version>2.15.3</version>
<!-- Apache 2.0 -->
<exclusions>
<exclusion>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
</exclusion>
<exclusion>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.9</version>
<!-- MIT -->
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.4.12</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.10.0</version>
<!-- Apache 2.0 -->
</dependency>
<dependency>
<groupId>com.offbytwo</groupId>
<artifactId>docopt</artifactId>
<version>0.6.0.20150202</version>
<!-- MIT -->
</dependency>
</dependencies>
<build>
<!-- inject version into version.properties. -->
<!-- Is there a better way to do this (besides switching to gradle, obviously)? -->
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/version.properties</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
<excludes>
<exclude>**/version.properties</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin.version}</version>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
<configuration>
<sourceDirs>
<source>${project.basedir}/src/main/java</source>
</sourceDirs>
</configuration>
</execution>
<execution>
<id>test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>test-compile</goal>
</goals>
<configuration>
<sourceDirs>
<source>${project.basedir}/src/test/java</source>
</sourceDirs>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.jetbrains.dokka</groupId>
<artifactId>dokka-maven-plugin</artifactId>
<version>2.0.0</version>
<executions>
<execution>
<phase>prepare-package</phase>
<goals>
<goal>dokka</goal>
<goal>javadoc</goal>
<goal>javadocJar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.1</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
<configuration>
<useSystemClassLoader>false</useSystemClassLoader>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.3.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
<configuration>
<descriptors>
<descriptor>src/assembly/tgz.xml</descriptor>
<descriptor>src/assembly/zip.xml</descriptor>
</descriptors>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>1.4.1</version>
<executions>
<execution>
<id>enforce-no-snapshots</id>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<requireReleaseDeps>
<message>Cannot have snapshot dependencies of a release!</message>
<onlyWhenRelease>true</onlyWhenRelease>
<searchTransitive>true</searchTransitive>
<failWhenParentIsSnapshot>true</failWhenParentIsSnapshot>
</requireReleaseDeps>
</rules>
<fail>true</fail>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
================================================
FILE: src/assembly/tgz.xml
================================================
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">
<id>bin</id>
<formats>
<format>tgz</format>
</formats>
<fileSets>
<fileSet>
<outputDirectory>/</outputDirectory>
<directory>${project.basedir}/src/scripts</directory>
<includes>
<include>textricator</include>
</includes>
<fileMode>0755</fileMode>
</fileSet>
<fileSet>
<directory>${project.basedir}</directory>
<includes>
<include>README.*</include>
<include>NOTICE</include>
<include>COPYING</include>
<include>examples/</include>
</includes>
</fileSet>
</fileSets>
<dependencySets>
<dependencySet>
<outputDirectory>lib</outputDirectory>
</dependencySet>
</dependencySets>
</assembly>
================================================
FILE: src/assembly/zip.xml
================================================
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">
<id>bin</id>
<formats>
<format>zip</format>
</formats>
<fileSets>
<fileSet>
<outputDirectory>/</outputDirectory>
<directory>${project.basedir}/src/scripts</directory>
<includes>
<include>textricator.bat</include>
</includes>
</fileSet>
<fileSet>
<directory>${project.basedir}</directory>
<includes>
<include>README.*</include>
<include>NOTICE</include>
<include>COPYING</include>
<include>examples/</include>
</includes>
</fileSet>
</fileSets>
<dependencySets>
<dependencySet>
<outputDirectory>lib</outputDirectory>
</dependencySet>
</dependencySets>
</assembly>
================================================
FILE: src/main/java/io/mfj/textricator/Textricator.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator
import io.mfj.textricator.table.TableParser
import io.mfj.textricator.table.config.TableParseConfig
import io.mfj.textricator.extractor.TextExtractor
import io.mfj.textricator.extractor.TextExtractorFactory
import io.mfj.textricator.extractor.TextExtractorOptions
import io.mfj.textricator.form.*
import io.mfj.textricator.form.config.FormParseConfig
import io.mfj.textricator.form.config.FormParseConfigUtil
import io.mfj.textricator.record.Record
import io.mfj.textricator.record.RecordFilter
import io.mfj.textricator.record.RecordModel
import io.mfj.textricator.record.output.*
import io.mfj.textricator.table.config.TableParseConfigUtil
import io.mfj.textricator.text.*
import io.mfj.textricator.text.output.CsvTextOutput
import io.mfj.textricator.text.output.JsonTextOutput
import io.mfj.textricator.text.output.TextOutput
import java.io.File
import java.io.InputStream
import java.io.OutputStream
import org.slf4j.LoggerFactory
/**
* Textricator. This is the primary starting point.
*/
object Textricator {
const val DEFAULT_PDF_PARSER = "pdf.itext5"
const val TEXT_OUTPUT_FORMAT_CSV = "csv"
const val TEXT_OUTPUT_FORMAT_JSON = "json"
const val RECORD_OUTPUT_FORMAT_CSV = "csv"
const val RECORD_OUTPUT_FORMAT_JSON = "json"
const val RECORD_OUTPUT_FORMAT_JSON_FLAT = "json-flat"
const val RECORD_OUTPUT_FORMAT_NULL = "null"
const val RECORD_OUTPUT_FORMAT_XML = "xml"
private val log = LoggerFactory.getLogger( Textricator::class.java )
// extract text
@JvmStatic
fun extractText(
input:InputStream, inputFormat:String,
output:OutputStream, outputFormat:String,
pageFilter:PageFilter = ALL_PAGES,
textExtractorOptions:TextExtractorOptions = TextExtractorOptions(),
maxRowDistance:Float = 0f ) {
when ( outputFormat ) {
TEXT_OUTPUT_FORMAT_CSV -> CsvTextOutput(output)
TEXT_OUTPUT_FORMAT_JSON -> JsonTextOutput(output)
else -> throw Exception( "Invalid output format: ${outputFormat}" )
}.use { textOutput ->
getExtractor( input, inputFormat, textExtractorOptions ).use { extractor ->
extractText( extractor, textOutput, maxRowDistance, pageFilter )
}
}
}
@JvmStatic
fun extractText(
extractor:TextExtractor,
output:TextOutput,
maxRowDistance:Float = 0f,
pageFilter:PageFilter = ALL_PAGES ) {
output.write( extractText( extractor, maxRowDistance, pageFilter ) )
}
@JvmStatic
fun extractText(
extractor:TextExtractor,
maxRowDistance:Float = 0f,
pageFilter:PageFilter = ALL_PAGES ): Sequence<Text> {
return extract( extractor, pageFilter ).groupRows( maxRowDistance )
}
// parse form to records
@JvmStatic
fun parseForm(
inputFile:File,
outputFile:File,
configFile:File ) {
val config = FormParseConfigUtil.parseYaml(configFile)
val inputFormat = inputFile.extension.lowercase()
val outputFormat = outputFile.extension.lowercase()
inputFile.inputStream().use { input ->
outputFile.outputStream().use { output ->
parseForm(
input, inputFormat,
output, outputFormat,
config )
}
}
}
@JvmStatic
fun parseForm(
inputFile:File,
outputFile:File,
config:FormParseConfig ) {
val inputFormat = inputFile.extension.lowercase()
val outputFormat = outputFile.extension.lowercase()
inputFile.inputStream().use { input ->
outputFile.outputStream().use { output ->
parseForm(
input, inputFormat,
output, outputFormat,
config )
}
}
}
@JvmStatic
fun parseForm(
input:InputStream, inputFormat:String,
output:OutputStream, outputFormat:String,
config:FormParseConfig,
eventListener:FormParseEventListener = LoggingEventListener
) {
getExtractor( input, inputFormat, config ).use { extractor ->
getRecordOutput( outputFormat, output, config, includeSource=false ).use { recordOutput ->
parseForm( source=null, extractor, recordOutput, config, eventListener )
}
}
}
@JvmStatic
fun parseForms(
inputs:Sequence<Triple<String,()->InputStream,String>>,
output:OutputStream, outputFormat:String,
config:FormParseConfig,
eventListener:FormParseEventListener = LoggingEventListener
) {
getRecordOutput( outputFormat, output, config, includeSource=true ).use { recordOutput ->
val records = sequence<Record> {
inputs.forEach { (filename,input,inputFormat) ->
input().use { inputStream ->
getExtractor( inputStream, inputFormat, config ).use { extractor ->
val records = parseForm(filename,extractor,config,eventListener)
yieldAll(records)
}
}
}
}
recordOutput.write(records)
}
}
@JvmStatic
fun parseForm(
source:String?=null,
extractor:TextExtractor,
recordOutput:RecordOutput,
config:FormParseConfig,
eventListener:FormParseEventListener = LoggingEventListener
) {
val records = parseForm(
source,
extractor,
config,
eventListener )
recordOutput.write( records )
}
@JvmStatic
fun parseForm(
source:String?,
extractor:TextExtractor,
config:FormParseConfig,
eventListener:FormParseEventListener = LoggingEventListener
): Sequence<Record> {
// TextExtractor parses PDF to sequence of Text
val textSeq = extract( extractor, config.pages.toPageFilter() ).groupRows( config.maxRowDistance )
// FSMParser parse sequence of Text to sequence of StateValue
val stateTextsSeq = FsmParser( source, config, eventListener ).parse( textSeq )
// RecordParser parses sequence of StateValue to sequence of Record
val recSeq = RecordParser( config, eventListener ).parse( stateTextsSeq )
// RecordFilter filters out non-matching records.
val filteredRecSeq = RecordFilter( config ).filter( recSeq )
return filteredRecSeq
}
@JvmStatic
private fun getRecordOutput( outputFormat:String, output:OutputStream, config:RecordModel, includeSource:Boolean):RecordOutput {
return when ( outputFormat ) {
RECORD_OUTPUT_FORMAT_CSV -> CsvRecordOutput(config,output,includeSource)
RECORD_OUTPUT_FORMAT_JSON -> JsonRecordOutput(config,output)
RECORD_OUTPUT_FORMAT_JSON_FLAT -> JsonFlatRecordOutput(config,output,includeSource)
RECORD_OUTPUT_FORMAT_XML -> XmlRecordOutput(config,output)
RECORD_OUTPUT_FORMAT_NULL -> NullOutput
else -> throw IllegalArgumentException( "Unsupported output format \"${outputFormat}\"." )
}
}
// parse table to records
@JvmStatic
fun parseTable(
inputFile:File,
outputFile:File,
configFile:File ) {
val config = TableParseConfigUtil.parseYaml(configFile)
val inputFormat = inputFile.extension.lowercase()
val outputFormat = outputFile.extension.lowercase()
inputFile.inputStream().use { input ->
outputFile.outputStream().use { output ->
parseTable(
input, inputFormat,
output, outputFormat,
config )
}
}
}
@JvmStatic
fun parseTable(
input:InputStream, inputFormat:String,
output:OutputStream, outputFormat:String,
config:TableParseConfig) {
getExtractor( input, inputFormat, config ).use { extractor ->
getRecordOutput(outputFormat,output,config,includeSource=false).use { output ->
parseTable( extractor, output, config )
}
}
}
@JvmStatic
fun parseTable(
extractor:TextExtractor,
output:RecordOutput,
config:TableParseConfig) {
val records = parseTable( extractor, config )
output.write( records )
}
@JvmStatic
fun parseTable(
extractor:TextExtractor,
config:TableParseConfig): Sequence<Record> {
// TextExtractor parses PDF to sequence of Text
val pages = extractPages( extractor, config.pages.toPageFilter() ).groupRowsPaged( config.maxRowDistance )
val recSeq = TableParser(config).parse( pages )
// RecordFilter filters out non-matching records.
val filteredRecSeq = RecordFilter(config).filter( recSeq )
return filteredRecSeq
}
@JvmStatic
fun getExtractor( input:InputStream, inputFormat:String, options:TextExtractorOptions ): TextExtractor {
val extractorName:String =
if ( options.extractor == null ) {
inputFormat
} else {
val i = inputFormat.indexOf(".")
val fileType = if ( i > 0 ) inputFormat.substring(0,i) else inputFormat
if ( options.extractor!!.startsWith( "${fileType}." ) ) {
options.extractor!!
} else {
// Using a different input format than [options.extractor] is set for.
inputFormat
}
}
.let { extractorName -> if ( extractorName == "pdf" ) DEFAULT_PDF_PARSER else extractorName }
log.debug( "Using extractor \"${extractorName}\" for input format \"${inputFormat}\"." )
return TextExtractorFactory
.getFactory( extractorName )
.create( input, options )
}
@JvmStatic
fun extract( extractor:TextExtractor, pageFilter:PageFilter = ALL_PAGES ): Sequence<Text> =
(1..extractor.getPageCount())
.asSequence()
.filter { pageNumber ->
pageFilter( pageNumber )
}
.flatMap { pageNumber ->
extractor.extract( pageNumber ).asSequence()
}
@JvmStatic
fun extractPages( extractor:TextExtractor, pageFilter:PageFilter = ALL_PAGES ): Sequence<Page> =
(1..extractor.getPageCount())
.asSequence()
.filter { pageNumber ->
pageFilter( pageNumber )
}
.map { pageNumber ->
Page( pageNumber, extractor.extract( pageNumber ) )
}
}
================================================
FILE: src/main/java/io/mfj/textricator/Version.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator
import java.util.*
object Version {
val version:String
val copyrightYear:String
val sourceLocation:String
init {
val props = Properties().apply {
Version::class.java.getResourceAsStream( "version.properties" ).use { input ->
load( input )
}
}
version = props.getProperty("version")
copyrightYear = props.getProperty("copyright.year")
sourceLocation = props.getProperty("source.location")
}
}
================================================
FILE: src/main/java/io/mfj/textricator/cli/TextricatorCli.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.cli
import io.mfj.textricator.*
import io.mfj.textricator.extractor.TextExtractorFactory
import io.mfj.textricator.extractor.TextExtractorOptions
import io.mfj.textricator.form.config.FormParseConfigUtil
import io.mfj.textricator.table.config.TableParseConfigUtil
import io.mfj.textricator.text.toPageFilter
import java.io.File
import java.io.InputStream
import ch.qos.logback.classic.Logger
import ch.qos.logback.classic.Level
import org.docopt.Docopt
import org.slf4j.LoggerFactory
import kotlin.system.exitProcess
/**
* Command-line interface to [Textricator].
*
* Can just extract text or also run the form or table parser.
*/
object TextricatorCli {
private val help = """
Textricator
Textricator extracts content from PDFs.
"text" extracts the text from a PDF and outputs to CSV or JSON.
"form" parse a form (using a finite state machine) and generate records.
"table" parses a table and generates records.
Output is to standard out if not specified.
Usage:
textricator text [--debug] [--pages=<pages>] [--max-row-distance=<max-row-distance>] [--box-precision=<points>] [--box-ignore-colors=<colors>] [--input-format=<input-format>] [--output-format=<output-format>] <input> [<output>]
textricator form [--debug] --config=<config> [--pages=<pages>] [--input-format=<input-format>] [--output-format=<output-format>] <input> [<output>]
textricator forms [--debug] --config=<config> --input-format=<input-format> [--output-format=<output-format>] <input-dir> [<output>]
textricator table [--debug] --config=<config> [--pages=<pages>] [--input-format=<input-format>] [--output-format=<output-format>] <input> [<output>]
textricator -h | --help
textricator --version
Options:
--config PATH Path to config file.
--pages PAGES Pages to include. E.g.: 1-4,5,9. Default: all pages.
--max-row-distance POINTS Order text boxes within this distance (points) by x-position. E.g.: 0.5. Default: no ordering.
--box-precision POINTS Consider text inside a box if it overflows by less than this many points (float).
--ignore-box-colors COLORS Ignore boxes of these colors (comma-separated).
--input-format FORMAT Input format. If not set, determine from file extension.
Valid values: ${TextExtractorFactory.extractorNames.sorted().joinToString(", ")}
("pdf" is an alias for ${Textricator.DEFAULT_PDF_PARSER})
--output-format FORMAT Output format. If not set, determine from file extension.
Valid values:
${Textricator.RECORD_OUTPUT_FORMAT_CSV} (default if output to standard out)
${Textricator.RECORD_OUTPUT_FORMAT_JSON}
${Textricator.RECORD_OUTPUT_FORMAT_JSON_FLAT}
${Textricator.RECORD_OUTPUT_FORMAT_XML}
${Textricator.RECORD_OUTPUT_FORMAT_NULL} (no output)
--debug Enable debug logging
--version Show version, copyright, and license information.
""".trimIndent().trim()
private fun Map<String,Any>.boolean( key:String ):Boolean = containsKey(key) && get(key) as Boolean
private fun Map<String,Any>.file( key:String ):File? = get(key)?.toString()?.let { File(it) }
private fun Map<String,Any>.string( key:String ):String? = get(key)?.toString()
private fun Map<String,Any>.float( key:String ):Float? = get(key)?.toString()?.toFloat()
@JvmStatic
fun main(args: Array<String>) {
// setup logging. This is done in main() (as opposed to with a logback.xml) so applications using Textricator
// as a library are not affected by our logging config.
System.setProperty("logback.configurationFile", "io/mfj/textricator/logback.xml")
val opts = Docopt(help)
.withHelp(true)
.withExit(true)
.parse(args.toList())
if (opts.boolean("--debug")) {
( LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME) as Logger ).level = Level.DEBUG
}
try {
when {
opts.boolean("--version") -> version()
opts.boolean("text") -> text(opts)
opts.boolean("table") -> table(opts)
opts.boolean("form") -> form(opts)
opts.boolean("forms") -> forms(opts)
}
} catch ( e:SystemExitException) {
System.err.println(e.message)
exitProcess(e.exitCode)
}
}
private fun version() {
println(
"""
Textricator ${Version.version}
Copyright ${Version.copyrightYear} Measures for Justice Institute.
Licensed under the GNU Affero General Public License, Version 3.
(Loaded modules may be licensed differently.)
Source code is available at ${Version.sourceLocation}
""".trimIndent()
)
}
private fun text( opts:Map<String,Any> ) {
val inputFile = opts.file("<input>")!!
val inputFormat = opts.string("--input-format") ?: inputFile.extension.lowercase()
val outputFile = opts.file("<output>")
outputFile?.absoluteFile?.parentFile?.mkdirs()
val outputFormat = opts.string("--output-format") ?:
if ( outputFile == null ) {
Textricator.TEXT_OUTPUT_FORMAT_CSV
} else {
outputFile.extension.lowercase()
}
val pages = opts.string("--pages").toPageFilter()
val maxRowDistance = opts.float("--max-row-distance") ?: 0f
val boxPrecision:Float = opts.float("--box-precision") ?: 0f
val boxIgnoreColors:Set<String> = opts.string("--box-ignore-colors")?.split(",")?.toSet() ?: emptySet()
val options = TextExtractorOptions(
boxPrecision = boxPrecision,
boxIgnoreColors = boxIgnoreColors )
inputFile.inputStream().use { input ->
( if ( outputFile != null ) outputFile.outputStream() else System.out ).use { output ->
Textricator.extractText(
input = input,
inputFormat = inputFormat,
output = output,
outputFormat = outputFormat,
pageFilter = pages,
textExtractorOptions = options,
maxRowDistance = maxRowDistance )
}
}
}
private fun form( opts:Map<String,Any> ) {
val inputFile = opts.file("<input>")!!
val inputFormat = opts.string("--input-format") ?: inputFile.extension.lowercase()
val outputFile = opts.file("<output>")
outputFile?.absoluteFile?.parentFile?.mkdirs()
val outputFormat = opts.string("--output-format") ?:
if ( outputFile == null ) {
throw SystemExitException( "--output-format is required if <output> is omitted.", 1 )
} else {
outputFile.extension.lowercase()
}
val configFile = opts.file("--config")!!
val config = FormParseConfigUtil.parseYaml(configFile)
opts.string("--pages")?.apply { config.pages = this }
inputFile.inputStream().use { input ->
( if ( outputFile != null ) outputFile.outputStream() else System.out ).use { output ->
Textricator.parseForm(
input = input,
inputFormat = inputFormat,
output = output,
outputFormat = outputFormat,
config = config )
}
}
}
private fun forms( opts:Map<String,Any> ) {
val inputDir = opts.file("<input-dir>")!!
val inputFormat = opts.string("--input-format")!!
val inputFormatUpper = inputFormat.uppercase()
val outputFile = opts.file("<output>")
outputFile?.absoluteFile?.parentFile?.mkdirs()
val outputFormat = opts.string("--output-format") ?:
if ( outputFile == null ) {
throw SystemExitException( "--output-format is required if <output> is omitted.", 1 )
} else {
outputFile.extension.lowercase()
}
val configFile = opts.file("--config")!!
val config = FormParseConfigUtil.parseYaml(configFile)
val inputs:Sequence<Triple<String,()->InputStream,String>> = inputDir.walk().asSequence()
.filter { file -> file.isFile }
.filter { file -> file.extension.uppercase() == inputFormatUpper }
.sorted()
.map { inputFile ->
Triple( inputFile.relativeTo(inputDir).path, { inputFile.inputStream() }, inputFormat )
}
( outputFile?.outputStream() ?: System.out ).use { output ->
Textricator.parseForms(
inputs = inputs,
output = output, outputFormat = outputFormat,
config = config
)
}
}
private fun table( opts:Map<String,Any> ) {
val inputFile = opts.file("<input>")!!
val inputFormat = opts.string("--input-format") ?: inputFile.extension.lowercase()
val outputFile = opts.file("<output>")
outputFile?.absoluteFile?.parentFile?.mkdirs()
val outputFormat = opts.string("--output-format") ?:
if ( outputFile == null ) {
throw SystemExitException( "--output-format is required if <output> is omitted.", 1 )
} else {
outputFile.extension.lowercase()
}
val configFile = opts.file("--config")!!
val config = TableParseConfigUtil.parseYaml(configFile)
opts.string("--pages")?.apply { config.pages = this }
inputFile.inputStream().use { input ->
( if ( outputFile != null ) outputFile.outputStream() else System.out ).use { output ->
Textricator.parseTable(
input = input,
inputFormat = inputFormat,
output = output,
outputFormat = outputFormat,
config = config )
}
}
}
private class SystemExitException(message:String,val exitCode:Int): Exception(message)
}
================================================
FILE: src/main/java/io/mfj/textricator/extractor/TextExtractor.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.extractor
import io.mfj.textricator.text.Text
/**
* Interface to extract text from a PDF.
*
* Create an instance and call [extract] for each page.
*
* @constructor Create an instance for the supplied PDF.
*/
interface TextExtractor:AutoCloseable {
/**
* Get the number of pages.
*/
fun getPageCount():Int
/**
* Extract text from the PDF, calling the callback for each text block.
*
* @param pageNumber Page to extract text from
*
*/
fun extract(pageNumber:Int):List<Text>
}
================================================
FILE: src/main/java/io/mfj/textricator/extractor/TextExtractorFactory.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.extractor
import java.io.InputStream
import java.util.*
interface TextExtractorFactory {
fun create( input:InputStream, options:TextExtractorOptions):TextExtractor
companion object {
/** path to properties files in classpath that has name=fqcn. */
private const val FACTORY_PROPERTIES = "io/mfj/textricator/extractor/textExtractor.properties"
/** Map of name->factory class, loaded from all io/mfj/unbox/factory.properties on classpath. */
val classMap:Map<String,Class<TextExtractorFactory>> by lazy {
TextExtractorFactory::class.java.classLoader.getResources(
FACTORY_PROPERTIES)
.asSequence()
.map { url ->
Properties().apply { url.openStream().use { load( it ) } }
.entries
.map { (k,v) ->
val name = k as String
val fqcn = v as String
val factoryClass:Class<TextExtractorFactory> = getFactoryClassFromFqcn(
fqcn)
Pair( name, factoryClass )
}
}
.flatten()
.toMap()
}
val extractorNames:Collection<String> by lazy { classMap.keys }
/** Get the factory class for the specified FQCN. */
private fun getFactoryClassFromFqcn( fqcn:String ): Class<TextExtractorFactory> =
Class.forName(fqcn).let { class_ ->
if ( TextExtractorFactory::class.java.isAssignableFrom( class_ ) ) {
@Suppress("UNCHECKED_CAST")
class_ as Class<TextExtractorFactory>
} else {
throw Exception( "\"${fqcn}\" does not implement \"${TextExtractorFactory::class.java.name}\"" )
}
}
fun getFactory( name:String ):TextExtractorFactory {
val factoryClass = classMap[name] ?: throw Exception( "No factory \"${name}\"" )
val factory = factoryClass.getDeclaredConstructor().newInstance()
return factory
}
}
}
================================================
FILE: src/main/java/io/mfj/textricator/extractor/TextExtractorOptions.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.extractor
open class TextExtractorOptions(
var boxPrecision:Float =0f,
var boxIgnoreColors:Set<String> = emptySet(),
var maxRowDistance:Float = 0f,
var extractor:String? = null,
var pages:String? = null
)
================================================
FILE: src/main/java/io/mfj/textricator/extractor/csv/CsvTextExtractor.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.extractor.csv
import io.mfj.textricator.extractor.TextExtractor
import io.mfj.textricator.text.Text
import io.mfj.textricator.text.output.CsvTextOutput
import java.io.InputStream
import org.apache.commons.csv.CSVParser
import org.apache.commons.csv.CSVRecord
/**
* Parse the CSV output from [CsvTextOutput].
*/
class CsvTextExtractor(input:InputStream):TextExtractor {
// load into memory up front
// Do not assume that pages are in order in the CSV.
private val pages:MutableMap<Int,MutableList<Text>> = mutableMapOf<Int,MutableList<Text>>()
.apply {
CSVParser(input.bufferedReader(), CsvTextOutput.CSV_FORMAT).use { csvp ->
csvp.asSequence()
.drop(1) // header
.map(::parseRec)
.forEach { text ->
getOrPut(text.pageNumber) { mutableListOf() }.add(text)
}
}
}
private val pageCount = pages.keys.sorted().lastOrNull() ?: 0
// This matches CsvTextOutput.write(Text)
private fun parseRec(rec:CSVRecord): Text =
Text(
pageNumber = rec[0].toInt(),
ulx = rec[1].toFloat(),
uly = rec[2].toFloat(),
lrx = rec[3].toFloat(),
lry = rec[4].toFloat(),
// width (rec[5]) is calculated from ulx and lrx
// height (rec[6]) is calculated from uly and lry
content = rec[7],
font = rec[8],
fontSize = rec[9].toFloat(),
color = rec[10],
backgroundColor = rec[11],
link = rec[12]
)
override fun getPageCount():Int = pageCount
override fun extract(pageNumber:Int):List<Text> = pages[pageNumber] ?: emptyList()
override fun close() {}
}
================================================
FILE: src/main/java/io/mfj/textricator/extractor/csv/CvsTextExtractorFactory.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.extractor.csv
import io.mfj.textricator.extractor.TextExtractor
import io.mfj.textricator.extractor.TextExtractorFactory
import io.mfj.textricator.extractor.TextExtractorOptions
import java.io.InputStream
class CsvTextExtractorFactory: TextExtractorFactory {
override fun create(input:InputStream, options:TextExtractorOptions):TextExtractor = CsvTextExtractor(input)
}
================================================
FILE: src/main/java/io/mfj/textricator/extractor/itext5/Box.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.extractor.itext5
import java.beans.Transient
/** A box drawn on the page. */
internal data class Box(
val ulx:Float,
val uly:Float,
val lrx:Float,
val lry:Float,
val color:String?
) {
val width:Float
@Transient
get() = lrx - ulx
val height:Float
@Transient
get() = lry - uly
}
================================================
FILE: src/main/java/io/mfj/textricator/extractor/itext5/Boxtricator.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.extractor.itext5
import com.itextpdf.text.BaseColor
import com.itextpdf.text.pdf.*
import com.itextpdf.text.pdf.parser.*
import io.mfj.textricator.extractor.itext5.Itext5TextExtractor.Companion.color
import org.slf4j.LoggerFactory
// adapted from
// https://github.com/mkl-public/testarea-itext5/blob/master/src/test/java/mkl/testarea/itext5/extract/ExtractPaths.java
internal class Boxtricator(private val reader:PdfReader,
private val ignoreBoxColors:Set<String> ) {
companion object {
private val log = LoggerFactory.getLogger( Boxtricator::class.java )
}
fun getBoxes( pageNumber:Int, pageHeight:Float):List<Box> {
val boxes:MutableList<Box> = mutableListOf()
val parser = PdfReaderContentParser(reader)
parser.processContent(pageNumber,
MyExtRenderListener(boxes, pageHeight, ignoreBoxColors))
return boxes.ifEmpty { emptyList() }
}
private class MyExtRenderListener(val boxes:MutableList<Box>, val pageHeight:Float,
val ignoreColors:Set<String> ): ExtRenderListener {
private val pathInfos:MutableList<PathConstructionRenderInfo?> = mutableListOf()
override fun beginTextBlock() {}
override fun renderText(renderInfo:TextRenderInfo?) {}
override fun endTextBlock() {}
override fun renderImage(renderInfo:ImageRenderInfo?) {}
override fun modifyPath(renderInfo:PathConstructionRenderInfo?) {
pathInfos.add(renderInfo)
}
override fun renderPath(renderInfo:PathPaintingRenderInfo):Path? {
val graphicsState:GraphicsState = renderInfo.gs
val ctm = graphicsState.ctm
val fill = (renderInfo.operation and PathPaintingRenderInfo.FILL) != 0
if ( fill ) {
val fillColor = graphicsState.fillColor
val color = color(fillColor)
if ( ! ignoreColors.contains( color ) ) {
log.debug("\tthe path:")
pathInfos.forEach { pathConstructionRenderInfo ->
when ( pathConstructionRenderInfo?.operation ) {
PathConstructionRenderInfo.MOVETO -> {
log.debug("move to {} ", transform(ctm, pathConstructionRenderInfo.segmentData))
}
PathConstructionRenderInfo.CLOSE -> {
log.debug("\tclose {} ", transform(ctm, pathConstructionRenderInfo.segmentData))
}
PathConstructionRenderInfo.CURVE_123 -> {
log.debug("\tcurve123 {} ", transform(ctm, pathConstructionRenderInfo.segmentData))
}
PathConstructionRenderInfo.CURVE_13 -> {
log.debug("\tcurve13 {} ", transform(ctm, pathConstructionRenderInfo.segmentData))
}
PathConstructionRenderInfo.CURVE_23 -> {
log.debug("\tcurve23 {} ", transform(ctm, pathConstructionRenderInfo.segmentData))
}
PathConstructionRenderInfo.LINETO -> {
log.debug("\tline to {} ", transform(ctm, pathConstructionRenderInfo.segmentData))
}
PathConstructionRenderInfo.RECT -> {
val matrix = transform(ctm, expandRectangleCoordinates(pathConstructionRenderInfo.segmentData))!!
log.debug("rectangle {} ", matrix)
val box = Box(ulx = matrix[0 /* or 6 */], uly = calcY(matrix[5 /* or 7 */]),
lrx = matrix[4 /* or 2 */], lry = calcY(matrix[1 /* or 3 */]), color = color(fillColor))
log.debug( "box: $box" )
boxes.add( box )
}
/*
else -> {
throw Exception( "\t\tunhandled ${pathConstructionRenderInfo?.operation}" )
}
*/
}
}
}
}
pathInfos.clear()
return null
}
override fun clipPath(rule:Int) {}
private fun transform(ctm:Matrix, coordinates:List<Float>? ):List<Float>? {
if ( coordinates == null ) return null
val result:MutableList<Float> = mutableListOf()
var i = 0
while ( i < coordinates.size-1) {
var vector = Vector(coordinates[i], coordinates[i + 1], 1f)
vector = vector.cross(ctm)
result.add(vector.get(Vector.I1))
result.add(vector.get(Vector.I2))
i+=2
}
return result
}
private fun expandRectangleCoordinates(rectangle:List<Float> ):List<Float> {
if (rectangle.size < 4) return emptyList()
return listOf(
rectangle[0], // x (left)
rectangle[1], // y (bottom) (from bottom)
rectangle[0] + rectangle[2], // x (right)
rectangle[1], // y (bottom) (from bottom)
rectangle[0] + rectangle[2], // x (right)
rectangle[1] + rectangle[3], // y (top) (from bottom)
rectangle[0], // x (left)
rectangle[1] + rectangle[3] // y (top) (from bottom)
)
}
private fun BaseColor?.format(): String = if (this == null) "DEFAULT" else "${red},${green},${blue}"
// in iText, if y is positive, it is from the bottom, if y is negative, it is from the top.
// We calculate from the top.
fun calcY(y:Float):Float {
return if (y >= 0) {
pageHeight - y
} else {
y * -1
}
}
}
}
================================================
FILE: src/main/java/io/mfj/textricator/extractor/itext5/Buffer.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.extractor.itext5
/** Buffer for accumulating values when parsing. */
internal data class Buffer (
val pageNumber:Int,
val ulx:Float,
val uly:Float,
var lrx:Float,
var lry:Float,
val font:String,
val fontSize:Float,
val fontColor:String?,
val content:StringBuffer = StringBuffer())
================================================
FILE: src/main/java/io/mfj/textricator/extractor/itext5/Itext5TextExtractor.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.extractor.itext5
import io.mfj.textricator.extractor.TextExtractor
import io.mfj.textricator.text.Text
import com.itextpdf.text.BaseColor
import com.itextpdf.text.pdf.*
import com.itextpdf.text.pdf.parser.ContentOperator
import com.itextpdf.text.pdf.parser.FilteredTextRenderListener
import com.itextpdf.text.pdf.parser.LocationTextExtractionStrategy
import com.itextpdf.text.pdf.parser.PdfContentStreamProcessor
import com.itextpdf.text.pdf.parser.PdfTextExtractor
import com.itextpdf.text.pdf.parser.Vector
import java.io.InputStream
import kotlin.math.min
import kotlin.math.max
import org.slf4j.LoggerFactory
/**
* Class to extract text from a PDF.
*
* Create an instance and call [extract] for each page.
*
* @constructor Create an instance for the supplied PDF.
*/
class Itext5TextExtractor(input:InputStream, boxPrecision:Float?, boxIgnoreColors:Set<String>? ):
TextExtractor {
private val reader = PdfReader(input)
private val boxPrecision = boxPrecision?: 0f
private val boxtricator = Boxtricator(reader, boxIgnoreColors ?: emptySet())
/** Number of pages in the PDF */
private val pageCount:Int = reader.numberOfPages
private val pageRange = (1..pageCount)
override fun getPageCount():Int {
return pageCount
}
companion object {
private val log = LoggerFactory.getLogger(Itext5TextExtractor::class.java)
internal fun color( baseColor:BaseColor? ): String {
if ( baseColor == null ) return "default"
return "#%02x%02x%02x".format( baseColor.red, baseColor.green, baseColor.blue )
}
data class Link( val url:String, val lrx:Float, val lry:Float, val ulx:Float, val uly:Float)
}
override fun close() {
reader.close()
}
/**
* Get the size, in points, of the specified page, as a width/height pair.
*
* @param pageNumber Page number
*/
private fun getPageSize(pageNumber:Int):Size {
val rect = reader.getPageSize(pageNumber)
return Size(rect.width, rect.height)
}
/**
* Extract text from the PDF, calling the callback for each text block.
*
* @param pageNumber Page to extract text from
*
*/
override fun extract(pageNumber:Int):List<Text> {
if ( ! pageRange.contains( pageNumber ) ) {
throw IllegalArgumentException( "Invalid page number: $pageNumber. Valid pages are $pageRange" )
}
val pageHeight = getPageSize(pageNumber).height
// in iText, if y is positive, it is from the bottom, if y is negative, it is from the top.
// We calculate from the top.
fun calcY(y:Float):Float {
return if (y >= 0) {
pageHeight - y
} else {
y * -1
}
}
val boxes:List<Box> = boxtricator.getBoxes(pageNumber,pageHeight)
val links = reader.getLinks(pageNumber)
.mapNotNull { annotation ->
val a = annotation.parameters[PdfName.A]
if ( a is PdfDictionary ) {
val uriPdfString = a[PdfName.URI] as PdfString
val uri = uriPdfString.toUnicodeString()
val rect = annotation.rect.map { o -> ( o as PdfNumber ).floatValue() }
Link(
url = uri,
ulx = rect[0],
uly = calcY(rect[3]),
lrx = rect[2],
lry = calcY(rect[1])
)
} else {
// Found a file where it is a com.itextpdf.text.pdf.PRIndirectReference.
// Did not need to get links from that document, so did not figure out what to do.
null
}
}
fun Buffer.toText():Text {
val content = content.toString().trim()
val link = links
.firstOrNull { link ->
ulx >= link.ulx
&& uly >= link.uly
&& lrx <= link.lrx
&& lry <= link.lry
}
?.url
return Text(
content = content,
pageNumber = pageNumber,
ulx = ulx,
uly = uly,
lrx = lrx,
lry = lry,
font = font,
fontSize = fontSize,
color= fontColor,
backgroundColor = getBackground(boxes, this, content),
link = link )
}
val texts:MutableList<Text> = mutableListOf()
val strategy = FilteredTextRenderListener(LocationTextExtractionStrategy())
var buffer:Buffer? = null
// start a new text segment
fun start(x:Float, y:Float, font:String, fontSize:Float, fontColor:String?) {
if (buffer != null) throw Exception("Forgot to call flush(). Text: $buffer")
buffer = Buffer(pageNumber, x, y, x, y, font, fontSize, fontColor)
}
// append text to an existing segment
// font and fontSize are ignored unless somebody forgot to call start()
fun append(x:Float, y:Float, text:String, font:String, fontSize:Float, fontColor:String? ) {
if ( buffer == null ) {
// ' or " without Tj - I have seen this with some PDFs modified with qoppa's PDFStudio.
log.warn("Forgot to call start()")
start(x,y,font,fontSize,fontColor)
}
buffer!!.content.append(text)
buffer!!.lrx = x
buffer!!.lry = y
}
// Call the callback with the buffer content.
fun flush() {
if (buffer != null) {
texts.add( buffer!!.toText() )
buffer = null
}
}
// Define operators to capture text from the content stream
// capture strings - start a new segment
val stringOperator = ContentOperator { processor:PdfContentStreamProcessor, operator:PdfLiteral?, operands:ArrayList<PdfObject> ->
val string = operands[0] as PdfString
val matrix = processor.textMatrix
val x = matrix[6]
val y = calcY( matrix[7] )
val bytes = string.bytes
val gs = processor.gs()
val text = gs.font.decode(bytes, 0, bytes.size)
val fontSize = getFontSize(processor)
val width = gs.font.getWidthPoint(text, fontSize)
val fontColor = color(gs.fillColor)
flush()
log.debug("{${pageNumber}} string [ ${x}, $y ] $text")
start(x, y, gs.font.postscriptFontName, fontSize, fontColor)
append(x + width, y, text, gs.font.postscriptFontName, fontSize, fontColor )
}
// capture continuation of previous string - append to existing segment
val stringOperatorContinue = ContentOperator { processor:PdfContentStreamProcessor, operator:PdfLiteral?, operands:ArrayList<PdfObject> ->
val string = operands[0] as PdfString
val matrix = processor.textMatrix
val x = matrix[6]
val y = calcY( matrix[7] )
val bytes = string.bytes
val gs = processor.gs()
val text = gs.font.decode(bytes, 0, bytes.size)
val fontSize = getFontSize(processor)
val width = gs.font.getWidthPoint(text, fontSize)
val fontColor = color(gs.fillColor)
// continuation from stringOperator
log.debug("{${pageNumber}} continue [ ${x}, $y ] $text")
append(x + width, y, " $text", gs.font.postscriptFontName, fontSize, fontColor)
}
// capture pdfarray - this is all one segment
val arrayOperator = ContentOperator { processor:PdfContentStreamProcessor, operator:PdfLiteral?, operands:ArrayList<PdfObject> ->
val array = operands[0] as PdfArray
val matrix = processor.textMatrix
val x = matrix[6]
val y = calcY( matrix[7] )
val gs = processor.gs()
val fontSize = getFontSize(processor)
// combine all PdfStrings in the PdfArray to one String
val text = array.asSequence().filter { it is PdfString }.map { it as PdfString }.map { pdfString ->
// PdfString.toUnicodeString() does not work in all cases.
val bytes = pdfString.bytes
gs.font.decode(bytes, 0, bytes.size)
}.joinToString(separator = "")
val width = gs.font.getWidthPoint(text, fontSize)
val fontColor = color(gs.fillColor)
flush()
log.debug("{${pageNumber}} array [ $x , $y ] $text")
start(x, y, gs.font.postscriptFontName, fontSize, fontColor)
append(x + width, y, text, gs.font.postscriptFontName, fontSize, fontColor)
flush()
}
// This is setting up what PdfContentStreamProcesses does internally.
val twOperator = SetTextWordSpacing()
val tcOperator = SetTextCharacterSpacing()
val tdOperator = TextMoveStartNextLine()
val tstarOperator = TextMoveNextLine(tdOperator)
val tickOperator = MoveNextLineAndShowText(tstarOperator, stringOperatorContinue)
val quoteOperator = MoveNextLineAndShowTextWithSpacing(twOperator, tcOperator,
tickOperator)
// This results in calls to the content operators defined above. We do not care about its return value.
PdfTextExtractor.getTextFromPage(reader, pageNumber, strategy,
mapOf("Tj" to stringOperator, "TJ" to arrayOperator, "'" to tickOperator, "\"" to quoteOperator))
flush()
return texts
.sortedWith( compareBy( {it.uly}, {it.ulx} ) )
}
private fun getBackground(all:List<Box>?,buffer:Buffer,content:String): String? {
if ( all == null ) return null
val boxes = all.filter { box -> isBufferInBox( buffer, box ) }
val box:Box? = boxes.lastOrNull()
return box?.color
}
private fun isBufferInBox( buffer:Buffer, box:Box): Boolean {
// shrink the buffer by the precision, but do not shrink width or height to negative.
return box.ulx <= min( buffer.ulx + boxPrecision, buffer.lrx )
&& box.uly <= min( buffer.uly + boxPrecision, buffer.lry )
&& box.lrx >= max( buffer.lrx - boxPrecision, buffer.ulx )
&& box.lry >= max( buffer.lry - boxPrecision, buffer.uly )
}
private fun getFontSize( processor:PdfContentStreamProcessor ):Float {
val gs = processor.gs()
val effMatrix = processor.textMatrix.multiply( gs.ctm )
val fontSize = Vector(0f,gs.fontSize,0f).cross(effMatrix)[1]
return fontSize
}
}
================================================
FILE: src/main/java/io/mfj/textricator/extractor/itext5/Itext5TextExtractorFactory.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.extractor.itext5
import io.mfj.textricator.extractor.TextExtractor
import io.mfj.textricator.extractor.TextExtractorFactory
import io.mfj.textricator.extractor.TextExtractorOptions
import java.io.InputStream
class Itext5TextExtractorFactory:TextExtractorFactory {
override fun create(input:InputStream, options:TextExtractorOptions):TextExtractor =
Itext5TextExtractor( input, options.boxPrecision, options.boxIgnoreColors )
}
================================================
FILE: src/main/java/io/mfj/textricator/extractor/itext5/Shenanigans.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.extractor.itext5
import com.itextpdf.text.pdf.*
import com.itextpdf.text.pdf.parser.*
// This is copies of a bunch of stuff that is private in IText's PdfContentStreamProcessor and GraphicsState
// DO NOT USE THIS!!! (except in Itext5TextExtractortor.kt)
/**
* A content operator implementation (Td).
*/
class TextMoveStartNextLine:ContentOperator {
override fun invoke(processor:PdfContentStreamProcessor, operator:PdfLiteral?, operands:ArrayList<PdfObject>) {
val tx = (operands[0] as PdfNumber).floatValue()
val ty = (operands[1] as PdfNumber).floatValue()
val translationMatrix = Matrix(tx, ty)
processor.textMatrix = translationMatrix.multiply(processor.textLineMatrix)
processor.textLineMatrix = processor.textMatrix
}
}
/**
* A content operator implementation (T*).
*/
class TextMoveNextLine(private val moveStartNextLine:TextMoveStartNextLine):ContentOperator {
override fun invoke(processor:PdfContentStreamProcessor, operator:PdfLiteral?, operands:ArrayList<PdfObject>) {
val tdoperands:ArrayList<PdfObject> = ArrayList(2)
tdoperands.add(0, PdfNumber(0))
tdoperands.add(1, PdfNumber(-processor.gs().leading))
moveStartNextLine.invoke(processor, null, tdoperands)
}
}
/**
* A content operator implementation (').
*/
class MoveNextLineAndShowText(private val textMoveNextLine:TextMoveNextLine, private val showText:ContentOperator):
ContentOperator {
override fun invoke(processor:PdfContentStreamProcessor, operator:PdfLiteral?, operands:ArrayList<PdfObject>) {
textMoveNextLine.invoke(processor, null, ArrayList(0))
showText.invoke(processor, null, operands)
}
}
/**
* A content operator implementation (Tw).
*/
class SetTextWordSpacing:ContentOperator {
override fun invoke(processor:PdfContentStreamProcessor, operator:PdfLiteral?, operands:ArrayList<PdfObject>) {
val wordSpace = operands[0] as PdfNumber
processor.gs().setWordSpacing(wordSpace.floatValue())
}
}
/**
* A content operator implementation (Tc).
*/
class SetTextCharacterSpacing:ContentOperator {
override fun invoke(processor:PdfContentStreamProcessor, operator:PdfLiteral?, operands:ArrayList<PdfObject>) {
val charSpace = operands[0] as PdfNumber
processor.gs().setCharacterSpacing(charSpace.floatValue())
}
}
/**
* A content operator implementation (").
*/
class MoveNextLineAndShowTextWithSpacing(private val setTextWordSpacing:SetTextWordSpacing,
private val setTextCharacterSpacing:SetTextCharacterSpacing,
private val moveNextLineAndShowText:MoveNextLineAndShowText):ContentOperator {
override fun invoke(processor:PdfContentStreamProcessor, operator:PdfLiteral?, operands:ArrayList<PdfObject>) {
val aw:PdfNumber = operands[0] as PdfNumber
val ac:PdfNumber = operands[1] as PdfNumber
val string:PdfString = operands[2] as PdfString
val twOperands:ArrayList<PdfObject> = ArrayList(1)
twOperands.add(0, aw)
setTextWordSpacing.invoke(processor, null, twOperands)
val tcOperands:ArrayList<PdfObject> = ArrayList(1)
tcOperands.add(0, ac)
setTextCharacterSpacing.invoke(processor, null, tcOperands)
val tickOperands:ArrayList<PdfObject> = ArrayList(1)
tickOperands.add(0, string)
moveNextLineAndShowText.invoke(processor, null, tickOperands)
}
}
/**
* private/protected things we need to access
*/
var PdfContentStreamProcessor.textMatrix:Matrix
get() = javaClass.getDeclaredField("textMatrix").let {
it.isAccessible = true
it.get(this) as Matrix
}
set(textMatrix) = javaClass.getDeclaredField("textMatrix").let {
it.isAccessible = true
it.set(this, textMatrix)
}
/// accessors for private itext stuff
var PdfContentStreamProcessor.textLineMatrix:Matrix
get() = javaClass.getDeclaredField("textLineMatrix").let {
it.isAccessible = true
it.get(this) as Matrix
}
set(textLineMatrix) = javaClass.getDeclaredField("textLineMatrix").let {
it.isAccessible = true
it.set(this, textLineMatrix)
}
fun GraphicsState.setWordSpacing(wordSpacing:Float) {
javaClass.getDeclaredField("wordSpacing").let {
it.isAccessible = true
it.set(this, wordSpacing)
}
}
fun GraphicsState.setCharacterSpacing(wordSpacing:Float) {
javaClass.getDeclaredField("characterSpacing").let {
it.isAccessible = true
it.set(this, wordSpacing)
}
}
val PathPaintingRenderInfo.gs:GraphicsState
get() = javaClass.getDeclaredField("gs").let {
it.isAccessible = true
it.get(this) as GraphicsState
}
================================================
FILE: src/main/java/io/mfj/textricator/extractor/itext5/Size.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.extractor.itext5
/** Width and height, in points. */
data class Size(val width:Float, val height:Float)
================================================
FILE: src/main/java/io/mfj/textricator/extractor/itext7/Itext7TextExtractor.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.extractor.itext7
import io.mfj.textricator.extractor.TextExtractor
import io.mfj.textricator.text.Text
import java.io.InputStream
import com.itextpdf.kernel.colors.*
import com.itextpdf.kernel.geom.Vector
import com.itextpdf.kernel.pdf.*
import com.itextpdf.kernel.pdf.canvas.parser.EventType
import com.itextpdf.kernel.pdf.canvas.parser.PdfTextExtractor
import com.itextpdf.kernel.pdf.canvas.parser.data.IEventData
import com.itextpdf.kernel.pdf.canvas.parser.data.TextRenderInfo
import com.itextpdf.kernel.pdf.canvas.parser.listener.LocationTextExtractionStrategy
/**
* Extract text using iText 7.
*
* This gets accurate locations, and does not attempt to group characters based on proximity or structure.
*/
class Itext7TextExtractor(input:InputStream):TextExtractor {
private val reader = PdfReader(input)
private val doc = PdfDocument(reader)
/** Number of pages in the PDF */
private val pageCount:Int = doc.numberOfPages
override fun getPageCount():Int {
return pageCount
}
override fun close() {
reader.close()
}
/**
* Extract text from the PDF, calling the callback for each text block.
*
* @param pageNumber Page to extract text from
*
*/
override fun extract(pageNumber:Int):List<Text> {
val page = doc.getPage(pageNumber)
val pageHeight = page.pageSize.height
val links:List<Link> = page.annotations
.filter { anno ->
anno.subtype == PdfName.Link
}
.map { anno ->
val aObj = anno.pdfObject[PdfName.A] as PdfDictionary
val uriObj = (aObj[PdfName.URI] ?: aObj[PdfName.URL]) as PdfString
val uri = uriObj.value
// get the bounding box
val rect = (anno.pdfObject[PdfName.Rect] as PdfArray).map { (it as PdfNumber).floatValue() }
Link(
url = uri,
ulx = rect[0],
uly = calcY(pageHeight, rect[3]),
lrx = rect[2],
lry = calcY(pageHeight, rect[1])
)
}
val strategy = Strategy(pageNumber, pageHeight, links)
PdfTextExtractor.getTextFromPage(page,strategy)
return strategy.texts
.sortedWith( compareBy( {it.uly}, {it.ulx} ) )
}
private class Strategy( private val pageNumber:Int, private val pageHeight:Float, private val links:List<Link>):
LocationTextExtractionStrategy() {
val texts = mutableListOf<Text>()
override fun eventOccurred(data:IEventData?, type:EventType?) {
if ( type == EventType.RENDER_TEXT ) {
val ri = data as TextRenderInfo
val content = ri.text
val matrix = ri.textMatrix
val font = ri.font.fontProgram.fontNames.fontName
val ulx = matrix[6]
val lry = calcY( pageHeight, matrix[7] )
val width = ri.font.getWidth(content,ri.fontSize)
val height = ri.font.getAscent(content, ri.fontSize)
val uly = lry - height
val lrx = ulx + width
val color = ri.fillColor?.getHexColor()
val link = links
.firstOrNull { link ->
ulx >= link.ulx
&& uly >= link.uly
&& lrx <= link.lrx
&& lry <= link.lry
}
?.url
val effMatrix = ri.textMatrix.multiply( ri.graphicsState.ctm )
val fontSize = Vector(0f,ri.fontSize,0f).cross(effMatrix)[1]
val text = Text(content = content, backgroundColor = null, pageNumber = pageNumber,
fontSize = fontSize, font = font, color = color,
ulx = ulx, uly = uly, lrx = lrx, lry = lry,
link = link )
texts.add( text )
}
super.eventOccurred(data, type)
}
private fun Color.getHexColor(): String? =
when ( this ) {
is DeviceRgb -> getRgb( this )
is DeviceCmyk -> getRgb( Color.convertCmykToRgb( this ) )
else -> null
}
private fun getRgb( color:DeviceRgb ): String {
val value = color.colorValue
val r = ( value[0] * 255 ).toInt()
val g = ( value[1] * 255 ).toInt()
val b = ( value[2] * 255 ).toInt()
return "#%02x%02x%02x".format( r, g, b )
}
}
companion object {
data class Link(val url:String, val lrx:Float, val lry:Float, val ulx:Float, val uly:Float)
// in iText, if y is positive, it is from the bottom, if y is negative, it is from the top.
// We calculate from the top.
fun calcY(pageHeight:Float, y:Float):Float {
return if (y >= 0) {
pageHeight - y
} else {
y * -1
}
}
}
}
================================================
FILE: src/main/java/io/mfj/textricator/extractor/itext7/Itext7TextExtractorFactory.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.extractor.itext7
import io.mfj.textricator.extractor.TextExtractor
import io.mfj.textricator.extractor.TextExtractorFactory
import io.mfj.textricator.extractor.TextExtractorOptions
import java.io.InputStream
class Itext7TextExtractorFactory:TextExtractorFactory {
override fun create(input:InputStream, options:TextExtractorOptions):TextExtractor = Itext7TextExtractor(
input)
}
================================================
FILE: src/main/java/io/mfj/textricator/extractor/json/JsonTextExtractor.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.extractor.json
import io.mfj.textricator.extractor.TextExtractor
import io.mfj.textricator.text.Text
import java.io.InputStream
import java.util.*
import com.fasterxml.jackson.core.JsonFactory
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
class JsonTextExtractor(input:InputStream):TextExtractor {
private val texts:Map<Int,List<Text>>
private val pageCount:Int
// load into memory up front
init {
val mapper = ObjectMapper(JsonFactory()).registerKotlinModule()
val typeFactory = mapper.typeFactory
val type =
typeFactory.constructCollectionType( LinkedList::class.java,
mapper.constructType(Text::class.java ) )
val list:List<Text> = mapper.readValue(input,type)
val map:MutableMap<Int,MutableList<Text>> = mutableMapOf()
list.forEach { text ->
map
.getOrPut( text.pageNumber) { mutableListOf() }
.add( text )
}
this.texts = map
this.pageCount = texts.keys.maxOrNull() ?: 0
}
override fun getPageCount():Int {
return pageCount
}
override fun extract(pageNumber:Int):List<Text> {
return texts[pageNumber] ?: emptyList()
}
override fun close() {}
}
================================================
FILE: src/main/java/io/mfj/textricator/extractor/json/JsonTextExtractorFactory.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.extractor.json
import io.mfj.textricator.extractor.TextExtractor
import io.mfj.textricator.extractor.TextExtractorFactory
import io.mfj.textricator.extractor.TextExtractorOptions
import java.io.InputStream
class JsonTextExtractorFactory: TextExtractorFactory {
override fun create(input:InputStream, options:TextExtractorOptions):TextExtractor = JsonTextExtractor(input)
}
================================================
FILE: src/main/java/io/mfj/textricator/extractor/pdfbox/PdfboxTextExtractor.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.extractor.pdfbox
import io.mfj.textricator.text.Text
import io.mfj.textricator.extractor.TextExtractor
import java.io.InputStream
import org.apache.pdfbox.pdmodel.PDDocument
class PdfboxTextExtractor(input:InputStream):TextExtractor {
private val doc = PDDocument.load(input)
private val stripper = TextBoxPdfTextStripper()
override fun extract(pageNumber:Int):List<Text> {
stripper.startPage = pageNumber
stripper.endPage = pageNumber
stripper.getText(doc)
return stripper.wordList[pageNumber]?.sortedWith( compareBy( Text::uly, Text::ulx ) ) ?: emptyList()
}
override fun getPageCount():Int = doc.numberOfPages
override fun close() {
doc.close()
}
}
================================================
FILE: src/main/java/io/mfj/textricator/extractor/pdfbox/PdfboxTextExtractorFactory.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.extractor.pdfbox
import io.mfj.textricator.extractor.TextExtractor
import io.mfj.textricator.extractor.TextExtractorFactory
import io.mfj.textricator.extractor.TextExtractorOptions
import java.io.InputStream
class PdfboxTextExtractorFactory:TextExtractorFactory {
override fun create(pdf:InputStream, options:TextExtractorOptions):TextExtractor = PdfboxTextExtractor(
pdf)
}
================================================
FILE: src/main/java/io/mfj/textricator/extractor/pdfbox/TextBoxPdfTextStripper.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.extractor.pdfbox
import io.mfj.textricator.text.Text
import java.io.IOException
import java.util.regex.Pattern
import org.apache.pdfbox.text.PDFTextStripper
import org.apache.pdfbox.text.TextPosition
internal class TextBoxPdfTextStripper : PDFTextStripper() {
companion object {
const val NON_BREAKING_SPACE:String = "\u00A0"
val NON_PRINTABLE:Pattern = Pattern.compile(".*[\\u0000-\\u0019]+.*")
}
internal val wordList: MutableMap<Int, MutableList<Text>> = mutableMapOf()
/**
* used to group words decoded at the same time.
*/
private var chunkIndex:Long = 0
@Throws(IOException::class)
override fun writeString(text:String, textPositions:List<TextPosition> ) {
chunkIndex++
val sb = StringBuilder()
// add initial position
// look for huge space gaps:
var wordStart:Int = -1
var current:TextPosition = textPositions.get(0)
var previous: TextPosition
var maxHeight:Float = 0f
(0..textPositions.size-1).forEach { i ->
previous = current
current = textPositions.get(i)
val separation:Float = current.getX() - (previous.getX() + previous.getWidth())
val sameFont:Boolean = current.getFont().equals(previous.getFont())
&& current.getFontSize() == previous.getFontSize()
if (current.getUnicode().endsWith(" ") ||
current.getUnicode().endsWith(
NON_BREAKING_SPACE) ||
(wordStart != -1 && (separation >= previous.getWidthOfSpace()))) {
addWord(sb, wordStart, i, textPositions, maxHeight)
maxHeight = 0f
wordStart = -1
} else if ((i > 0 && separation < -(previous.getWidth()) / 2) || !sameFont) {
// split in cases where words overlay (eg in excel print outs! // TODO : this should be a configuable param
// have to exclude i = 0 as we set previous to the first char
addWord(sb, wordStart, i, textPositions, maxHeight)
maxHeight = 0f
wordStart = i
sb.append(current.getUnicode())
} else {
if (wordStart == -1) {
wordStart = i
}
sb.append(current.getUnicode())
}
val gs = graphicsState
val color = gs.strokingColor.toRGB()
val nscolor = gs.nonStrokingColor.toRGB()
maxHeight = Math.max(maxHeight, current.getHeight())
}
addWord(sb, wordStart, textPositions.size, textPositions, maxHeight)
}
private fun expandNonPrintableUnicode(string:String) :String {
if (NON_PRINTABLE.matcher(string).matches()) {
val sb = StringBuilder()
(0..string.length-1).forEach { i ->
val cp = string.codePointAt(i)
if (cp < 0x20) {
sb.append(String.format("\\x%02x", cp))
} else {
sb.append(string[i])
}
}
return sb.toString()
} else {
return string
}
}
private fun addWord(sb: StringBuilder, startIndex:Int, endIndex:Int,
textPositions: List<TextPosition>, maxHeight:Float) {
if (sb.length > 0) {
val first = textPositions.get(startIndex)
val previous = textPositions.get(endIndex - 1)
val expanded = expandNonPrintableUnicode(sb.toString())
val textBox = Text(content = expanded, pageNumber = currentPageNo, ulx = first.x,
uly = first.y - first.height, lrx = previous.x + previous.width, lry = first.y, font = first.font?.name ?: "",
fontSize = first.fontSize, color = null, // TODO
backgroundColor = null)
wordList.putIfAbsent(textBox.pageNumber, mutableListOf())
val pageList = wordList.get(textBox.pageNumber)!!
pageList.add(textBox)
sb.setLength(0)
}
}
}
================================================
FILE: src/main/java/io/mfj/textricator/form/FormParseEventListener.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.form
interface FormParseEventListener: FsmEventListener, RecordParserEventListener
================================================
FILE: src/main/java/io/mfj/textricator/form/FsmEventListener.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.form
import io.mfj.textricator.text.Text
interface FsmEventListener {
fun onText( text:Text)
fun onHeader( text:Text)
fun onFooter( text:Text)
fun onLeftMargin( text:Text)
fun onRightMargin( text:Text)
fun onExclude( text:Text, condition:String )
fun onCheckTransition( currentState:String, condition:String, nextState:String )
fun onCheckTransition( currentState:String, condition:String, nextState:String, match:Boolean, message:String? )
fun onNoPrevious( source:String )
fun onCheckCondition( source:String, description:String, match:Boolean )
fun onPageStateChange( page:Int, state:String )
fun onStateChange( page:Int, state:String )
fun onVariableSet( currentState:String, name:String, value:String? )
fun onFsmEnd()
}
================================================
FILE: src/main/java/io/mfj/textricator/form/FsmParser.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.form
import io.mfj.expr.*
import io.mfj.textricator.form.config.*
import io.mfj.textricator.record.Value
import io.mfj.textricator.text.Text
import io.mfj.textricator.text.groupRows
import org.slf4j.LoggerFactory
/**
* Use a Finite State Machine config to parse
* a sequence of Text to a sequence of StateValue,
* which contains the FSM state and the value for that state.
*
* @param config FSM config
* @param eventListener event listener
*/
class FsmParser( val source:String?, val config:FormParseConfig,
private val eventListener:FsmEventListener? =null ) {
companion object {
private val log = LoggerFactory.getLogger(FsmParser::class.java)
}
fun parse( texts:Sequence<Text> ): Sequence<StateValue> {
// parse state is a passed object instead of object-level to keep this thread-safe
val parseState = ParseState(source,config, eventListener)
return texts.groupRows(config.maxRowDistance)
// filter out header and footer
.filter { text -> boundsFilter(text) }
// group by state (run the FSM)
.plus( null as Text? ) // sentinel
.map { text -> parse( parseState, text ) }
.filterNotNull()
// remove skipped states and combine now-adjacent siblings of the same state
.filter { sv -> ! sv.state.skip }.combine()
}
/**
* Combine adjacent siblings with the same state.
*/
private fun Sequence<StateValue>.combine():Sequence<StateValue> = sequence {
var last:StateValue? = null
forEach { sv ->
last = when {
last == null -> sv
last!!.state == sv.state -> last!!.copy( values = last!!.values + sv.values )
else -> {
yield(last!!)
sv
}
}
}
last?.let { yield(it) }
}
private class ExprState(val source:String?, val config:FormParseConfig, val eventListener: FsmEventListener?) {
companion object {
/**
* Built-in variables.
* The enum names match exactly the variables in the expression.
*/
private enum class BuiltInVar(val type:ExDataType) {
/** x coordinate of the upper-left corner of the text box */
ulx(ExDataType.NUMBER),
/** y coordinate of the upper-left corner of the text box */
uly(ExDataType.NUMBER),
/** x coordinate of the lower-right corner of the text box */
lrx(ExDataType.NUMBER),
/** y coordinate of the lower-right corner of the text box */
lry(ExDataType.NUMBER),
/** The text. */
text(ExDataType.STRING),
/** page number . */
page(ExDataType.NUMBER),
/** page number of the previous text */
page_prev(ExDataType.NUMBER),
/** font size */
fontSize(ExDataType.NUMBER),
/** font name */
font(ExDataType.STRING),
/** text color */
color(ExDataType.STRING),
/** background color */
bgcolor(ExDataType.STRING),
/** width of the text box */
width(ExDataType.NUMBER),
/** height of the text box */
height(ExDataType.NUMBER),
/** Difference in [ulx] from the previous text to this one */
ulx_rel(ExDataType.NUMBER),
/** Difference in [uly] from the previous text to this one */
uly_rel(ExDataType.NUMBER),
/** Difference in [lrx] from the previous text to this one */
lrx_rel(ExDataType.NUMBER),
/** Difference in [lry] from the previous text to this one */
lry_rel(ExDataType.NUMBER),
/** Data source; e.g. file name. */
source(ExDataType.STRING),
}
private val builtInVarNames = BuiltInVar.values().map(BuiltInVar::name).toSet()
// expr var type provider
// If you add a type, add it to ParseState.vp
private val VTP = ChainVarTypeProvider(
MapVarTypeProvider(
BuiltInVar
.values()
.associate {
it.name to it.type
}
),
object: VarTypeProvider {
override fun contains(varName:String):Boolean = true
override operator fun get(varName: String): ExDataType = ExDataType.STRING
} )
/**
* Compile the specified expression
*/
private fun compile( e:String ): Expr {
return ExprParser.parseToExpr(e, VTP)
}
}
// cache of parsed expression
private val exprCache:MutableMap<String,Pair<String,Expr>> = mutableMapOf()
/**
* Get the expression and parsed Expr for the specified conditionId.
*/
private fun getCondition( conditionId:String ):Pair<String,Expr> =
exprCache.getOrPut( conditionId ) {
val e = config.conditions[conditionId] ?: throw Exception( "Missing condition \"${conditionId}\"" )
Pair( e, compile(e))
}
/** The text referenced by "last" in the expressions. */
private var lastText:Text? = null
/** The text referenced by "text" in the expressions. */
private var text:Text? = null
val vars:MutableMap<String,String?> = mutableMapOf()
/** Expr variable provider */
val vp: VarProvider = object : VarProvider {
private fun noLast(source:String) = eventListener?.onNoPrevious(source)
override fun contains(varName:String):Boolean = true // if it is not built in, anything else is allowed as String
override operator fun get( varName: String ): Any? {
return if ( builtInVarNames.contains(varName) ) {
val builtInVar = BuiltInVar.valueOf(varName)
when ( builtInVar ) {
// built-ins
BuiltInVar.ulx -> text!!.ulx
BuiltInVar.uly -> text!!.uly
BuiltInVar.lrx -> text!!.lrx
BuiltInVar.lry -> text!!.lry
BuiltInVar.text -> text!!.content
BuiltInVar.page -> text!!.pageNumber
BuiltInVar.page_prev -> if ( lastText != null ) lastText!!.pageNumber else { noLast( varName ); -1 }
BuiltInVar.fontSize -> text!!.fontSize
BuiltInVar.font -> text!!.font
BuiltInVar.color -> text!!.color
BuiltInVar.bgcolor -> text!!.backgroundColor
BuiltInVar.width -> text!!.width
BuiltInVar.height -> text!!.height
BuiltInVar.ulx_rel -> if ( lastText != null ) text!!.ulx - lastText!!.ulx else { noLast( varName ); text!!.ulx }
BuiltInVar.uly_rel -> if ( lastText != null ) text!!.uly - lastText!!.uly else { noLast( varName ); text!!.uly }
BuiltInVar.lrx_rel -> if ( lastText != null ) text!!.lrx - lastText!!.lrx else { noLast( varName ); text!!.lrx }
BuiltInVar.lry_rel -> if ( lastText != null ) text!!.lry - lastText!!.lry else { noLast( varName ); text!!.lry }
BuiltInVar.source -> source
}
} else {
vars[varName]
}
}
override fun getKnownVars():Set<String> = builtInVarNames.plus( vars.keys )
}
fun matches( conditionId:String, last:Text?, text:Text ): Boolean {
val (exprStr,expr) = getCondition(conditionId)
this.lastText = last
this.text = text
val match = Eval.evaluate( expr, vp )
eventListener?.onCheckCondition( conditionId, exprStr, match )
return match
}
}
private class ParseState( private val source:String?, private val config:FormParseConfig, private val eventListener:FsmEventListener? ) {
val exprState = ExprState(source,config,eventListener)
// text currently being parsed
private var current:Text? = null
var text:Text?
get() = current
set(text) {
last = current
current = text
}
// last parsed text
private var last:Text? = null
val lastText:Text?
get() = last
var stateId:String
var state:State
private val buffer:MutableList<Text> = mutableListOf()
init {
val stateId = config.initialState
this.state = config.states[stateId] ?: throw Exception( "Missing initial state ${stateId}" )
this.stateId = stateId
}
/**
* Determine if the current state matches the specified condition.
*/
fun matches( conditionId:String ): Boolean {
return exprState.matches(conditionId,last,text!!)
}
/**
* Determine if the next state matches the specified condition.
* Uses the current text as "last" and the supplied [next] text a "text".
*/
fun matches( conditionId:String, next:Text ):Boolean {
return exprState.matches(conditionId,text,next)
}
fun setState( stateId:String ): StateValue? {
val ret = flush()
//log.debug( "State = ${stateId} on pageNumber ${pageNumber}" )
this.state = config.states[stateId] ?: throw Exception( "Missing state ${stateId}" )
this.stateId = stateId
return ret
}
/** Add the current text to the current state */
fun addText() {
buffer.add( text!! )
last = text
state.setVariables
.filter { it.name != null }
.forEach { vs:VariableSet ->
val value = getVariableValue( vs.value )
exprState.vars[vs.name!!] = value
eventListener?.onVariableSet( stateId, vs.name, value )
Unit
}
}
fun flush(): StateValue? {
val stateTexts:StateValue? = if ( buffer.isNotEmpty() ) {
StateValue(source,buffer.first().pageNumber, stateId, state, parseValues())
} else {
null
}
buffer.clear()
last = null
return stateTexts
}
private fun getVariableValue( value:String? ): String? =
if ( value == null ) {
null
} else if ( value.startsWith( "{" ) && value.endsWith( "}" ) ) {
exprState.vp[ value.drop(1).dropLast(1) ]?.toString()
} else {
value
}
/**
* Convert the Texts into Strings, combining them according to [State.combineLimit].
*/
private fun parseValues(): List<Value> {
val values:MutableList<Value> = mutableListOf()
var last:Text? = null
for ( text in buffer ) {
if ( last != null && shouldCombine( last, text ) ) {
val lastValue = values.removeLast()
val content = "${lastValue.text}${text.content}"
val link = last.link
if ( text.link != null && text.link != link ) {
log.warn( "Skipping link \"${text.link}\" from \"${text.content}\"; it does not overwrite link \"${link}\" from \"${lastValue.text}\"")
}
values.add( Value( content, link ) )
} else {
values.add( Value(text.content,text.link) )
}
last = text
}
return values
}
private fun <T> MutableList<T>.removeLast(): T = removeAt( size-1 )
private val combineLimitMap:Map<String,Float?> by lazy {
val default:Float? = config.stateDefaults?.combineLimit
config.states.mapValues { (stateId,state) -> state.combineLimit ?: default }
}
private fun shouldCombine( last:Text, text:Text):Boolean {
val combineLimit:Float? = combineLimitMap[stateId]
return ( combineLimit != null ) && ( text.ulx - last.lrx <= combineLimit )
}
}
private fun parse( s:ParseState, text:Text? ): StateValue? {
// process sentinel
if ( text == null ) {
//log.debug( "end of text sequence" )
eventListener?.onFsmEnd()
return s.flush()
}
if ( text.content.isBlank() ) return null
//text.debug()
eventListener?.onText(text)
// excludes
if ( config.excludeConditions.isNotEmpty() ) {
for ( conditionId in config.excludeConditions ) {
if ( s.matches(conditionId,text) ) {
eventListener?.onExclude(text,conditionId)
s.text = s.lastText
return null
}
}
}
s.text = text
var ret:StateValue? = null // return value
// if pageNumber change, flush if newPageState is set
if ( text.pageNumber != ( s.lastText?.pageNumber ?: 1 ) && config.newPageState != null ) {
ret = s.setState( config.newPageState!! )
eventListener?.onPageStateChange(text.pageNumber, config.newPageState!! )
}
// find transition
var transition: Transition? = null
for (t in s.state.transitions) {
eventListener?.onCheckTransition(s.stateId,t.condition,t.nextState)
val match = s.matches(t.condition)
//log.debug("\tcheck transition {${t.condition}} -> [${t.nextState}] : ${match}")
eventListener?.onCheckTransition(s.stateId,t.condition,t.nextState,match, if ( match ) t.message else null )
if (match) {
if ( t.message != null ) {
log.warn( t.message )
}
transition = t
break
}
}
if (transition == null) {
throw Exception("Page ${text.pageNumber} at \"${text.content.t()}\" - no valid transition from ${s.stateId}")
}
val nextStateId = transition.nextState
if ( nextStateId == s.stateId ) {
s.addText()
} else {
// state change
if ( ret != null ) {
// pageNumber transition happened
if ( s.lastText != null ) {
// texts were already added.
// Texts should not have been added.
throw Exception( "BUG" )
} else {
// PageNumber transition just happened, the new page state had nothing added to it.
// That's fine.
// Set the new state, but ignore the returned StateValue because it is empty
// (because of the page transition).
s.setState( nextStateId )
s.addText()
}
} else {
eventListener?.onStateChange(text.pageNumber, nextStateId)
ret = s.setState( nextStateId )
s.addText()
}
}
return ret
}
private fun boundsFilter( text:Text): Boolean {
// check header/footer/left/right
val top = getLimit( config.header, text.pageNumber )
if ( top != null && text.lry <= top ) {
eventListener?.onText(text)
eventListener?.onHeader(text)
return false
}
val bottom = getLimit( config.footer, text.pageNumber )
if ( bottom != null && text.uly >= bottom ) {
eventListener?.onText(text)
eventListener?.onFooter(text)
return false
}
val left = getLimit( config.left, text.pageNumber )
if ( left != null && text.lrx <= left ) {
eventListener?.onText(text)
eventListener?.onLeftMargin(text)
return false
}
val right = getLimit( config.right, text.pageNumber )
if ( right != null && text.ulx >= right ) {
eventListener?.onText(text)
eventListener?.onRightMargin(text)
return false
}
return true
}
private fun getLimit( rules:DefaultAndPages, pageNumber:Int ): Float? {
val s = if ( rules.pages.containsKey( pageNumber ) ) {
rules.pages[pageNumber]!!
} else {
rules.default
}
return s?.toFloat()
}
private fun Text.debug() {
log.debug("============================")
log.debug("text: \"${content}\"")
log.debug("\tpageNumber: ${pageNumber} ul:[ ${ulx} , ${uly} ] lr: [ ${lrx} , ${lry} ]")
log.debug("\tfont: ${font} - ${fontSize}")
}
}
private fun String?.t(l:Int = 20):String = when {
this == null -> ""
this.length <= l -> this
else -> this.take(l) + "..."
}
================================================
FILE: src/main/java/io/mfj/textricator/form/LoggingEventListener.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.form
import io.mfj.textricator.text.Text
import org.slf4j.LoggerFactory
object LoggingEventListener: FormParseEventListener {
private val log = LoggerFactory.getLogger( LoggingEventListener::class.java )
override fun onText(text:Text) {
if ( log.isDebugEnabled ) {
log.debug("============================")
log.debug("text: \"${text.content}\"")
log.debug("\tpageNumber: ${text.pageNumber} ul:[ ${text.ulx} , ${text.uly} ] lr: [ ${text.lrx} , ${text.lry} ]")
log.debug("\tfont: ${text.font} - ${text.fontSize}")
log.debug("\tbgcolor: ${text.backgroundColor}")
log.debug("\tlink: ${text.link}")
}
}
override fun onHeader(text:Text) {
log.debug("\tpart of header. skip")
}
override fun onFooter(text:Text) {
log.debug("\tpart of footer. skip")
}
override fun onLeftMargin(text:Text) {
log.debug("\tpart of left gutter. skip")
}
override fun onRightMargin(text:Text) {
log.debug("\tpart of right gutter. skip")
}
override fun onExclude(text: Text, condition: String) {
log.debug("\texcluded by condition \"${condition}\"")
}
override fun onCheckTransition(currentState:String, condition:String, nextState:String) {
log.debug("\tcheck transition \"${condition}\" (\"${currentState}\" -> \"${nextState}\")...")
}
override fun onNoPrevious(source:String) {
log.debug("\t\tno previous [${source}]")
}
override fun onCheckTransition(currentState:String, condition:String, nextState:String, match:Boolean, message:String?) {
log.debug("\t\t${match} ${if (message != null) " (${message})" else "" }")
}
override fun onCheckCondition(source:String, description:String, match:Boolean) {
log.debug("\t\tcheck condition [${source}] ${description} : ${match}" )
}
override fun onPageStateChange(page:Int, state:String) {
log.debug( "State = ${state} (page:${page} reset)" )
}
override fun onStateChange(page:Int, state:String) {
log.debug( "State = ${state} (page:${page})" )
}
override fun onVariableSet(currentState:String, name:String, value:String?) {
log.debug( "Variable ${name} = ${if ( value != null ) "\"${value}\"" else "null" }" )
}
override fun onFsmEnd() {
log.debug( "fsm end" )
}
override fun onRecordsEnd() {
log.debug( "records end" )
}
override fun onStateValue(sv:StateValue) {
log.debug( "parse StateValue: ${sv.stateId} : ${sv.values}" )
}
override fun onNewRecord(typeId:String) {
log.debug( "\tnew ${typeId} record" )
}
override fun onRecordAppend(typeId:String) {
log.debug( "\tadd to ${typeId} record" )
}
}
================================================
FILE: src/main/java/io/mfj/textricator/form/RecordParser.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.form
import io.mfj.textricator.record.Record
import io.mfj.textricator.record.calculateValue
import io.mfj.textricator.form.config.FormParseConfig
import io.mfj.textricator.form.config.State
import io.mfj.textricator.record.Value
import java.util.*
/**
* Parses a sequence of StateValue
* (probably the output of [FsmParser])
* to a sequence of Record according to the config.
*
* @param config FormParseConfig
*/
class RecordParser( private val config:FormParseConfig, private val eventListener:RecordParserEventListener? =null ) {
fun parse( seq:Sequence<StateValue> ): Sequence<Record> {
val parseState = ParseState()
return seq
.map { stateTexts -> split(stateTexts) }.flatten()
.map { stateValue -> splitValueTypes(stateValue) }.flatten()
.plus( null as StateValue? ) // sentinel
.mapNotNull { stateTexts ->
parse( parseState, stateTexts )
}
}
/**
* If [State.startRecordForEachValue], split the StateValue
* so parse can create new records for each
*/
private fun split( st:StateValue): List<StateValue> =
if ( st.state.startRecordForEachValue ) {
st.values.map { value ->
StateValue(st.source, st.pageNumber, st.stateId, st.state, listOf(value), false )
}
} else {
listOf( st )
}
/**
* If a State goes to multiple value types, split it
* into one for each value type.
*/
private fun splitValueTypes(st:StateValue): List<StateValue> =
st.state.valueTypes
?.mapIndexed { index, valueTypeId ->
val state = st.state.copy( valueTypes = mutableListOf( valueTypeId ) )
StateValue(st.source, st.pageNumber, st.stateId, state, st.values, (index > 0))
}
?: listOf( st )
private class ParseState {
val stateStack: Stack<Pair<String,Boolean>> = Stack() // <stateId,isNewRecord>
var root: Record? = null
// map of record to its member valueTypes.
// We build this up as a list of strings, then collapse it to a single string before returning.
// see extension function Record.setValueTypes()
// Using IdentityHashMap is important - we need to distinguish between equal empty Records.
val buffer: MutableMap<Record,MutableMap<String,MutableList<Value>>> = IdentityHashMap()
}
private fun parse( s:ParseState, st:StateValue? ): Record? {
if ( st == null ) {
//log.debug( "end of states" )
eventListener?.onRecordsEnd()
// sentinel
return s.root?.setValues(s)
}
//log.debug( "parse ${st.state} - ${st.valueTypes}" )
eventListener?.onStateValue( st )
// figure out if we should start a new record
val newRecord = ( ! st.splitContinuation ) && isNewRecord( s, st.stateId )
if ( newRecord ) {
s.stateStack.popThrough { it.second && it.first == st.stateId }
}
s.stateStack.push( Pair( st.stateId, newRecord ) )
// return value, if a new record is started return the current root
var ret:Record? = null
// have to check this *after* the call to s.stateStack.push() so this state goes in the stack, even if not used.
if ( st.state.include ) {
// there is only one because of splitValueTypes()
val valueTypeId:String = st.state.valueTypes?.get(0) ?: st.stateId
// find the type the contains this state
val recordTypeId:String = findRecordTypeId( valueTypeId )
// if new
val rec:Record = if ( newRecord ) {
// if the type is root
val rec:Record = if ( recordTypeId == config.rootRecordType) {
// return the old one and start a new root
ret = s.root?.setValues(s)
s.buffer.clear()
s.root = Record(st.source, st.pageNumber, recordTypeId)
s.root!!
} else {
// find the parent record
val parent = findParentRecord( s, st.source, st.pageNumber, recordTypeId )
// start a new record
val rec = Record(st.source, st.pageNumber, recordTypeId)
parent.children.getOrPut( recordTypeId, { mutableListOf() } ).add( rec )
rec
}
//log.debug( "new ${rec.typeId} record" )
eventListener?.onNewRecord(rec.typeId)
rec
} else {
if ( s.root == null ) {
// not explicitly starting a new record, but no record exists.
// create a new root to add to.
// TODO is this okay?
s.root = Record(st.source, st.pageNumber, config.rootRecordType)
}
// find the root
val rec = findRecord( s.root!!, recordTypeId )
//log.debug( "add to ${rec.typeId} record" )
eventListener?.onRecordAppend( rec.typeId )
rec
}
// add data
s.buffer
.getOrPut( rec, {mutableMapOf()} )
.getOrPut( valueTypeId, {mutableListOf()} )
.addAll( st.values )
}
return ret
}
private val valueTypes = config.valueTypes
/**
* Set the valueTypes of the members from the buffer.
*/
private fun Record.setValues( s:ParseState):Record {
val recBuffer = s.buffer.get(this)
if ( recBuffer != null ) {
recBuffer.forEach { valueTypeId, values ->
val value = valueTypes[valueTypeId].calculateValue(values)
this.values[valueTypeId] = value
}
}
this.children.forEach { childRecordTypeId, children ->
children.forEach { child ->
child.setValues(s)
}
}
return this
}
private fun isNewRecord( s:ParseState, stateId:String ): Boolean {
// Decide if a new record should be started
// It is more complex than just "does this state start a new record", because of this case:
// Imagine PDF that has records that look like this:
// Jonathan Zachary Defendant pled to something or other blah blah blah says he didn't mean to blah blah
// Johnson hurt anybody blah blah blah blah blah blah blah blah blah police brutality blah blah
// blah waste of taxpayer money blah blah only 2 ounces blah blah blah blah blah blah
// Case Type: F blah.
//
// John Doe This is the next record blah blah blah
// "Johnson" on the 2nd line is part of the name, so we transition from the "notes" (the explanation at the right)
// state to the "name" state, but we should not start a new record as you would transitioning from "notes" for
// "so windy" to "name" for "John Doe"
// The way we handle this is to require entering a specific state (i.e. case_type) before starting a new record.
// To do this, we keep a stack of states (a pair of a string (the state) and a boolean for if it is a new record)
// "Jonathon Zackary" - push "name"/true
// "Defendant pled...." - push "notes"/false
// "Johnson" - push "name"/false
// "hurt anybody..." - push "notes"/false
// "blah waste..." - push "notes"/false
// "F" - push "case_type"/false
// "blah." - push "notes"/false
// "John Doe" - start new record, pop through last "name"/true (from "Jonathon Zackary"), push "name"/true
val state = config.states[stateId] ?: throw Exception( "Missing state \"${stateId}\"" )
if ( state.startRecordForEachValue ) return true
return state.startRecord && ( state.startRecordRequiredState == null
|| s.stateStack.hasIntermediateState( state.startRecordRequiredState ) )
}
/** Map of value type ID to record type ID of the record that contains the value */
private val valueTypeIdToRecordTypeId:Map<String,String> by lazy {
val m:MutableMap<String,String> = mutableMapOf()
config.recordTypes.forEach { ( recordTypeId, recordType ) ->
recordType.valueTypes.forEach { valueTypeId ->
m.put( valueTypeId, recordTypeId )
}
}
m
}
private fun findRecordTypeId( valueTypeId:String ): String {
return valueTypeIdToRecordTypeId[valueTypeId] ?: throw Exception( "No type containing value type \"${valueTypeId}\"" )
}
/**
* Map of parent record type to
* ( map of record type to which child of the parent record type contains the type )
*
* e.g.:
* data record types:
* A
* / \
* B C
* / \ / \
* D E F G
* / \
* H I
*
* will result in:
* {
* A: {
* B > B, D > B, E > B, H > B, I > B,
* C > C, F > C, G > C
* },
* B: {
* D > D, H > D, I > D,
* E > E
* }
* D: {
* H > H,
* I > I
* },
* C: {
* F > F,
* G > G
* }
* }
*/
private val recordTypeToDescendantToChild:Map<String,Map<String,String>> by lazy {
config.recordTypes.mapValues { ( _, type ) ->
// descendant to child of type
val m:MutableMap<String,String> = mutableMapOf()
fun add( childTypeId:String, descendantTypeId:String ) {
m.put( descendantTypeId, childTypeId )
val descendantType = config.recordTypes[descendantTypeId] ?: throw Exception( "Missing type \"${descendantTypeId}\"" )
descendantType.children.forEach { furtherDescendantTypeId ->
add( childTypeId, furtherDescendantTypeId )
}
}
type.children.forEach { childTypeId ->
add( childTypeId, childTypeId )
}
m
}
}
private infix fun String.findAncestorThatIsAChildOf( parent:String ): String? {
val childRecordTypeId = recordTypeToDescendantToChild[parent]?.get( this )
return childRecordTypeId
}
// wrapper for unit tests
internal fun findAncestorThatIsAChildOf( type:String, parent:String ) = type findAncestorThatIsAChildOf parent
/**
* Find the Record for the typeId under the supplied root, creating child recs if necessary
*/
private fun findRecord( rec:Record, recordTypeId:String ):Record {
if ( rec.typeId == recordTypeId ) {
// this is it
return rec
} else {
val childTypeId = recordTypeId findAncestorThatIsAChildOf rec.typeId
if ( childTypeId != null ) {
// the desired record is either this child type or under it
val children:MutableList<Record> = rec.children.getOrPut( childTypeId, { mutableListOf() } )
if ( children.isEmpty() ) {
children.add(Record(rec.source, rec.pageNumber, childTypeId))
}
return findRecord( children.last(), recordTypeId )
} else {
throw Exception( "Cannot find record of type \"${recordTypeId}\" (under \"${rec.typeId}\")" )
}
}
}
private fun findParentRecord( s:ParseState, source:String?, pageNumber:Int, recordTypeId:String ):Record {
if ( s.root == null ) {
s.root = Record(source, pageNumber, config.rootRecordType)
}
return findParentRecord( s.root!!, recordTypeId )
}
/**
* Find the parent root for the recordTypeId under the supplied root, creating child recs if necessary
*/
private fun findParentRecord( rec:Record, recordTypeId:String ):Record {
if ( rec.typeId == recordTypeId) {
throw Exception( "rec is type \"${recordTypeId}\"" )
} else {
if ( rec.children.containsKey(recordTypeId) ) return rec // optimization
val childRecordTypeId = recordTypeId findAncestorThatIsAChildOf rec.typeId
if ( childRecordTypeId != null ) {
// the desired type is either this child type or under it
if ( childRecordTypeId == recordTypeId) {
// the desired type is this child type; return the parent
return rec
} else {
// the desired type is a child of the child type
val children:MutableList<Record> = rec.children.getOrPut( childRecordTypeId, { mutableListOf() } )
if ( children.isEmpty() ) {
children.add(Record(rec.source, rec.pageNumber, childRecordTypeId))
}
val last = children.last()
return if ( last.typeId == recordTypeId) {
rec
} else {
findParentRecord( last, recordTypeId)
}
}
} else {
throw Exception( "Cannot find record of type \"${recordTypeId}\" (under \"${rec.typeId}\")" )
}
}
}
}
/**
* Determine if the state stack has the specified state since the latest new record.
* If the latest new record is the latest record to have the specified state, returns false.
*/
fun Stack<Pair<String,Boolean>>.hasIntermediateState( state:String ): Boolean {
val i = listIterator(size)
while ( i.hasPrevious() ) {
val p = i.previous()
if ( p.second ) return false
if ( p.first == state ) return true
}
return false
}
/**
* Remove elements until an element matches the given predicate.
*/
fun <T> Stack<T>.popUntil( predicate: (T)->Boolean ) {
while ( ! isEmpty() && ! predicate( peek() ) ) pop()
}
/**
* Remove elements until an element matches the given predicate, and remove that element too.
*/
fun <T> Stack<T>.popThrough( predicate: (T)->Boolean ) {
popUntil( predicate )
if ( ! isEmpty() && predicate( peek() ) ) pop()
}
================================================
FILE: src/main/java/io/mfj/textricator/form/RecordParserEventListener.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.form
interface RecordParserEventListener {
fun onRecordsEnd()
fun onStateValue( sv:StateValue)
fun onNewRecord( typeId:String )
fun onRecordAppend( typeId:String )
}
================================================
FILE: src/main/java/io/mfj/textricator/form/StateValue.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.form
import io.mfj.textricator.form.config.State
import io.mfj.textricator.record.Value
/**
* @param pageNumber The pageNumber that the state started on.
*/
data class StateValue( val source:String?, val pageNumber:Int, val stateId:String, val state:State, val values:List<Value>,
val splitContinuation:Boolean=false )
================================================
FILE: src/main/java/io/mfj/textricator/form/WriterEventListener.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.form
import io.mfj.textricator.text.Text
import java.io.Writer
import org.slf4j.LoggerFactory
class WriterEventListener(private val w:Writer): FormParseEventListener {
private val log = LoggerFactory.getLogger(LoggingEventListener::class.java)
override fun onText(text:Text) {
write("============================")
write("text: \"${text.content}\"")
write("\tpageNumber: ${text.pageNumber} ul:[ ${text.ulx} , ${text.uly} ] lr: [ ${text.lrx} , ${text.lry} ]")
write("\tfont: ${text.font} - ${text.fontSize}")
write("\tbgcolor: ${text.backgroundColor}")
}
override fun onHeader(text:Text) {
write("\tpart of header. skip")
}
override fun onFooter(text:Text) {
write("\tpart of footer. skip")
}
override fun onLeftMargin(text:Text) {
write("\tpart of left gutter. skip")
}
override fun onRightMargin(text:Text) {
write("\tpart of right gutter. skip")
}
override fun onExclude(text: Text, condition: String) {
write("\texcluded by condition \"${condition}\"")
}
override fun onCheckTransition(currentState:String, condition:String, nextState:String) {
write("\tcheck transition \"${condition}\" (\"${currentState}\" -> \"${nextState}\")...")
}
override fun onCheckTransition(currentState:String, condition:String, nextState:String, match:Boolean, message:String?) {
write("\t\t${match} ${if (message != null) " (${message})" else "" }")
}
override fun onNoPrevious(source:String) {
write("\t\tno previous [${source}]")
}
override fun onCheckCondition(source:String, description:String, match:Boolean) {
write("\t\tcheck condition [${source}] ${description} : ${match}" )
}
override fun onPageStateChange(page:Int, state:String) {
write( "State = ${state} (page:${page} reset)" )
}
override fun onStateChange(page:Int, state:String) {
write( "State = ${state} (page:${page})" )
}
override fun onVariableSet(currentState:String, name:String, value:String?) {
write( "Variable ${name} = ${if ( value != null ) "\"${value}\"" else "null" }" )
}
override fun onFsmEnd() {
write( "fsm end" )
}
override fun onRecordsEnd() {
write( "records end" )
}
override fun onStateValue(sv:StateValue) {
write( "parse StateValue: ${sv.stateId} : ${sv.values}" )
}
override fun onNewRecord(typeId:String) {
write( "\tnew ${typeId} record" )
}
override fun onRecordAppend(typeId:String) {
write( "\tadd to ${typeId} record" )
}
var writes:Long = 0
private fun write( s:String ) {
try {
w.appendLine(s)
if ( writes++ % 100L == 0L ) w.flush()
} catch ( e:Exception ) {
log.error(e.message,e)
}
}
}
================================================
FILE: src/main/java/io/mfj/textricator/form/config/DefaultAndPages.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.form.config
/**
* A class to contain a default value along with page specific values which override the default on a given page.
*/
data class DefaultAndPages(val default: String? = null,val pages: Map<Int, String> = mapOf())
================================================
FILE: src/main/java/io/mfj/textricator/form/config/FormParseConfig.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.form.config
import io.mfj.textricator.record.RecordModel
import io.mfj.textricator.record.RecordType
import io.mfj.textricator.extractor.TextExtractorOptions
import io.mfj.textricator.record.ValueType
/**
* Defines the state machine
*/
class FormParseConfig(
var states: MutableMap<String, State> = mutableMapOf(),
var stateDefaults: State? = null,
var conditions: MutableMap<String, String> = mutableMapOf(),
var initialState: String = "INITIAL_STATE",
var newPageState: String? = null,
var header:DefaultAndPages = DefaultAndPages(),
var footer:DefaultAndPages = DefaultAndPages(),
var left:DefaultAndPages = DefaultAndPages(),
var right:DefaultAndPages = DefaultAndPages(),
override var rootRecordType: String = "root",
override var recordTypes: Map<String, RecordType> = emptyMap(),
override var valueTypes: Map<String, ValueType> = emptyMap(),
/** Any [Text]s that match any of these condition names (the key in [conditions])
* are excluded; never processed by the finite-state machine. */
var excludeConditions: List<String> = emptyList(),
extractor:String? = null,
pages:String? = null,
maxRowDistance:Float = 0f,
boxPrecision:Float =0f,
boxIgnoreColors:MutableSet<String> = mutableSetOf()
): TextExtractorOptions(
extractor = extractor,
boxPrecision = boxPrecision,
boxIgnoreColors = boxIgnoreColors,
maxRowDistance = maxRowDistance,
pages = pages ), RecordModel
================================================
FILE: src/main/java/io/mfj/textricator/form/config/FormParseConfigUtil.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.form.config
import java.io.File
import java.io.InputStream
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory
import com.fasterxml.jackson.module.kotlin.*
object FormParseConfigUtil {
private val mapper = ObjectMapper(YAMLFactory()).registerKotlinModule()
fun parseYaml(file: File):FormParseConfig = parseYaml(file.readText())
fun parseYaml(input:InputStream):FormParseConfig = mapper.readValue(input)
fun parseYaml(text:String):FormParseConfig = mapper.readValue(text)
}
================================================
FILE: src/main/java/io/mfj/textricator/form/config/State.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.form.config
import java.util.*
/**
* A state in the state machine
*/
data class State(
/** If true, remove text in this state before record processing. */
val skip:Boolean = false,
/** If false, do not create records for this state, but still include it in record processing
* so it can split adjacent states and affect if the next sibling starts a record. */
val include:Boolean = true,
val transitions: MutableList<Transition> = ArrayList(),
val startRecord: Boolean = false,
val startRecordRequiredState: String? = null,
val startRecordForEachValue:Boolean = false,
val valueTypes: MutableList<String>? = null,
val combineLimit: Float? = null,
val setVariables: MutableList<VariableSet> = mutableListOf()
)
================================================
FILE: src/main/java/io/mfj/textricator/form/config/Transition.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.form.config
/**
* Defines a transition, consisting of a condition ID, the id of the next node and a unique id for this transition
*/
data class Transition(val condition: String, val nextState: String, val message:String? = null)
================================================
FILE: src/main/java/io/mfj/textricator/form/config/VariableSet.kt
================================================
/*
This file is part of Textricator.
Copyright 2018 Measures for Justice Institute.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3 as published by the
Free Software Foundation.
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 <https://www.gnu.org/licenses/>.
*/
package io.mfj.textricator.form.config
data class VariableSet( val name:String? = null, var value:String? = null )
==================================
gitextract_24_mshfj/
├── .gitignore
├── CODEOWNERS
├── COPYING
├── NOTICE
├── README.md
├── pom.xml
└── src/
├── assembly/
│ ├── tgz.xml
│ └── zip.xml
├── main/
│ ├── java/
│ │ └── io/
│ │ └── mfj/
│ │ └── textricator/
│ │ ├── Textricator.kt
│ │ ├── Version.kt
│ │ ├── cli/
│ │ │ └── TextricatorCli.kt
│ │ ├── extractor/
│ │ │ ├── TextExtractor.kt
│ │ │ ├── TextExtractorFactory.kt
│ │ │ ├── TextExtractorOptions.kt
│ │ │ ├── csv/
│ │ │ │ ├── CsvTextExtractor.kt
│ │ │ │ └── CvsTextExtractorFactory.kt
│ │ │ ├── itext5/
│ │ │ │ ├── Box.kt
│ │ │ │ ├── Boxtricator.kt
│ │ │ │ ├── Buffer.kt
│ │ │ │ ├── Itext5TextExtractor.kt
│ │ │ │ ├── Itext5TextExtractorFactory.kt
│ │ │ │ ├── Shenanigans.kt
│ │ │ │ └── Size.kt
│ │ │ ├── itext7/
│ │ │ │ ├── Itext7TextExtractor.kt
│ │ │ │ └── Itext7TextExtractorFactory.kt
│ │ │ ├── json/
│ │ │ │ ├── JsonTextExtractor.kt
│ │ │ │ └── JsonTextExtractorFactory.kt
│ │ │ └── pdfbox/
│ │ │ ├── PdfboxTextExtractor.kt
│ │ │ ├── PdfboxTextExtractorFactory.kt
│ │ │ └── TextBoxPdfTextStripper.kt
│ │ ├── form/
│ │ │ ├── FormParseEventListener.kt
│ │ │ ├── FsmEventListener.kt
│ │ │ ├── FsmParser.kt
│ │ │ ├── LoggingEventListener.kt
│ │ │ ├── RecordParser.kt
│ │ │ ├── RecordParserEventListener.kt
│ │ │ ├── StateValue.kt
│ │ │ ├── WriterEventListener.kt
│ │ │ └── config/
│ │ │ ├── DefaultAndPages.kt
│ │ │ ├── FormParseConfig.kt
│ │ │ ├── FormParseConfigUtil.kt
│ │ │ ├── State.kt
│ │ │ ├── Transition.kt
│ │ │ └── VariableSet.kt
│ │ ├── record/
│ │ │ ├── Record.kt
│ │ │ ├── RecordFilter.kt
│ │ │ ├── RecordModel.kt
│ │ │ ├── Value.kt
│ │ │ └── output/
│ │ │ ├── CsvRecordOutput.kt
│ │ │ ├── JsonFlatRecordOutput.kt
│ │ │ ├── JsonRecordOutput.kt
│ │ │ ├── NullOutput.kt
│ │ │ ├── RecordOutput.kt
│ │ │ └── XmlRecordOutput.kt
│ │ ├── table/
│ │ │ ├── Table.kt
│ │ │ ├── TableParser.kt
│ │ │ └── config/
│ │ │ ├── TableParseConfig.kt
│ │ │ └── TableParseConfigUtil.kt
│ │ └── text/
│ │ ├── Page.kt
│ │ ├── PageFilter.kt
│ │ ├── RowGrouper.kt
│ │ ├── Text.kt
│ │ └── output/
│ │ ├── CsvTextOutput.kt
│ │ ├── JsonTextOutput.kt
│ │ └── TextOutput.kt
│ └── resources/
│ └── io/
│ └── mfj/
│ └── textricator/
│ ├── extractor/
│ │ └── textExtractor.properties
│ ├── logback.xml
│ └── version.properties
├── scripts/
│ ├── textricator
│ └── textricator.bat
└── test/
├── java/
│ └── io/
│ └── mfj/
│ └── textricator/
│ ├── examples/
│ │ └── ExamplesTest.kt
│ ├── form/
│ │ ├── NodeMembersTest.kt
│ │ ├── PatternReplacementTest.kt
│ │ └── RecordParserTest.kt
│ └── record/
│ ├── RecordFilterTest.kt
│ └── output/
│ ├── CsvOutputTest.kt
│ └── XmlOutputTest.kt
└── resources/
└── io/
└── mfj/
└── textricator/
└── examples/
├── probes.yml
├── rap-sheet.csv
├── rap-sheet.yml
├── school-employee-list.csv
└── school-employee-list.yml
Condensed preview — 82 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (330K chars).
[
{
"path": ".gitignore",
"chars": 21,
"preview": "target/\n.idea/\n*.iml\n"
},
{
"path": "CODEOWNERS",
"chars": 332,
"preview": "# This is the CODEOWNERS file for the textricator repo.\n\n# These owners will be the default owners for everything in the"
},
{
"path": "COPYING",
"chars": 34523,
"preview": " GNU AFFERO GENERAL PUBLIC LICENSE\n Version 3, 19 November 2007\n\n Copyright (C)"
},
{
"path": "NOTICE",
"chars": 59,
"preview": "Textricator\nCopyright 2018 Measures for Justice Institute.\n"
},
{
"path": "README.md",
"chars": 26466,
"preview": "# \n\n_Textricator_ is a tool to extract text from documents and generate"
},
{
"path": "pom.xml",
"chars": 9725,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\"\n xmlns:xsi=\"http://www"
},
{
"path": "src/assembly/tgz.xml",
"chars": 934,
"preview": "<assembly xmlns=\"http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3\" xmlns:xsi=\"http://www.w3.org/2001"
},
{
"path": "src/assembly/zip.xml",
"chars": 909,
"preview": "<assembly xmlns=\"http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3\" xmlns:xsi=\"http://www.w3.org/2001"
},
{
"path": "src/main/java/io/mfj/textricator/Textricator.kt",
"chars": 10572,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/Version.kt",
"chars": 1135,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/cli/TextricatorCli.kt",
"chars": 10423,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/extractor/TextExtractor.kt",
"chars": 1203,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/extractor/TextExtractorFactory.kt",
"chars": 2637,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/extractor/TextExtractorOptions.kt",
"chars": 914,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/extractor/csv/CsvTextExtractor.kt",
"chars": 2386,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/extractor/csv/CvsTextExtractorFactory.kt",
"chars": 1067,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/extractor/itext5/Box.kt",
"chars": 1007,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/extractor/itext5/Boxtricator.kt",
"chars": 5887,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/extractor/itext5/Buffer.kt",
"chars": 1006,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/extractor/itext5/Itext5TextExtractor.kt",
"chars": 10528,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/extractor/itext5/Itext5TextExtractorFactory.kt",
"chars": 1128,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/extractor/itext5/Shenanigans.kt",
"chars": 5184,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/extractor/itext5/Size.kt",
"chars": 793,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/extractor/itext7/Itext7TextExtractor.kt",
"chars": 5246,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/extractor/itext7/Itext7TextExtractorFactory.kt",
"chars": 1080,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/extractor/json/JsonTextExtractor.kt",
"chars": 1932,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/extractor/json/JsonTextExtractorFactory.kt",
"chars": 1068,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/extractor/pdfbox/PdfboxTextExtractor.kt",
"chars": 1386,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/extractor/pdfbox/PdfboxTextExtractorFactory.kt",
"chars": 1076,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/extractor/pdfbox/TextBoxPdfTextStripper.kt",
"chars": 4332,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/form/FormParseEventListener.kt",
"chars": 772,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/form/FsmEventListener.kt",
"chars": 1453,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/form/FsmParser.kt",
"chars": 15984,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/form/LoggingEventListener.kt",
"chars": 3314,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/form/RecordParser.kt",
"chars": 13684,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/form/RecordParserEventListener.kt",
"chars": 868,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/form/StateValue.kt",
"chars": 1015,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/form/WriterEventListener.kt",
"chars": 3385,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/form/config/DefaultAndPages.kt",
"chars": 917,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/form/config/FormParseConfig.kt",
"chars": 2166,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/form/config/FormParseConfigUtil.kt",
"chars": 1233,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/form/config/State.kt",
"chars": 1452,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/form/config/Transition.kt",
"chars": 921,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/form/config/VariableSet.kt",
"chars": 777,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/record/Record.kt",
"chars": 1959,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/record/RecordFilter.kt",
"chars": 3958,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/record/RecordModel.kt",
"chars": 3907,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/record/Value.kt",
"chars": 958,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/record/output/CsvRecordOutput.kt",
"chars": 4315,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/record/output/JsonFlatRecordOutput.kt",
"chars": 4937,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/record/output/JsonRecordOutput.kt",
"chars": 2038,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/record/output/NullOutput.kt",
"chars": 1097,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/record/output/RecordOutput.kt",
"chars": 947,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/record/output/XmlRecordOutput.kt",
"chars": 2164,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2021 Stephen Byrne.\n\nThis program is free software: you can redistribute "
},
{
"path": "src/main/java/io/mfj/textricator/table/Table.kt",
"chars": 3049,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/table/TableParser.kt",
"chars": 3740,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/table/config/TableParseConfig.kt",
"chars": 2376,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/table/config/TableParseConfigUtil.kt",
"chars": 1186,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/text/Page.kt",
"chars": 849,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/text/PageFilter.kt",
"chars": 1678,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/text/RowGrouper.kt",
"chars": 2480,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/text/Text.kt",
"chars": 1716,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/text/output/CsvTextOutput.kt",
"chars": 2120,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/text/output/JsonTextOutput.kt",
"chars": 1554,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/java/io/mfj/textricator/text/output/TextOutput.kt",
"chars": 833,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/main/resources/io/mfj/textricator/extractor/textExtractor.properties",
"chars": 347,
"preview": "pdf.itext5=io.mfj.textricator.extractor.itext5.Itext5TextExtractorFactory\npdf.itext7=io.mfj.textricator.extractor.itext7"
},
{
"path": "src/main/resources/io/mfj/textricator/logback.xml",
"chars": 565,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<!DOCTYPE configuration>\n\n<configuration>\n <import class=\"ch.qos.logback.clas"
},
{
"path": "src/main/resources/io/mfj/textricator/version.properties",
"chars": 94,
"preview": "version=${project.version}\ncopyright.year=${copyright.year}\nsource.location=${source.location}"
},
{
"path": "src/scripts/textricator",
"chars": 637,
"preview": "#!/usr/bin/env bash\n\n# Find script directory ($SCRIPT_DIR).\n# On linux (and cygwin) \"SCRIPT_DIR=$(basedir $(readlink -f "
},
{
"path": "src/scripts/textricator.bat",
"chars": 94,
"preview": "@echo off\nset batpath=%~dp0\njava -cp \"%batpath%lib/*\" io.mfj.textricator.cli.TextricatorCli %*"
},
{
"path": "src/test/java/io/mfj/textricator/examples/ExamplesTest.kt",
"chars": 7442,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/test/java/io/mfj/textricator/form/NodeMembersTest.kt",
"chars": 2976,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/test/java/io/mfj/textricator/form/PatternReplacementTest.kt",
"chars": 3664,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/test/java/io/mfj/textricator/form/RecordParserTest.kt",
"chars": 6521,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/test/java/io/mfj/textricator/record/RecordFilterTest.kt",
"chars": 8961,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/test/java/io/mfj/textricator/record/output/CsvOutputTest.kt",
"chars": 3394,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you "
},
{
"path": "src/test/java/io/mfj/textricator/record/output/XmlOutputTest.kt",
"chars": 6793,
"preview": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\nCopyright 2021 Stephen Byrne.\n\nThis "
},
{
"path": "src/test/resources/io/mfj/textricator/examples/probes.yml",
"chars": 1046,
"preview": "# All measurements are in points. 1 point = 1/72 of an inch.\n# x-coordinates are from the left edge of the page.\n# y-coo"
},
{
"path": "src/test/resources/io/mfj/textricator/examples/rap-sheet.csv",
"chars": 4481,
"preview": "page,requester,requestDate,requestTime,attn,header,caDojId,dob,sex,race,height,weight,eyeColor,hairColor,birthState,name"
},
{
"path": "src/test/resources/io/mfj/textricator/examples/rap-sheet.yml",
"chars": 12496,
"preview": "---\nextractor: \"pdf.pdfbox\"\n\nheader:\n default: 0\nfooter:\n default: 770\n\nmaxRowDistance: 2\n\nrootRecordType: rapsheet\nre"
},
{
"path": "src/test/resources/io/mfj/textricator/examples/school-employee-list.csv",
"chars": 1051,
"preview": "page,Employee ID,Name,Hire Date,Occupation,Important Info?,Boolean 1,Boolean 2,Boolean 3,Salary,Attending Child,Grade\n1,"
},
{
"path": "src/test/resources/io/mfj/textricator/examples/school-employee-list.yml",
"chars": 9480,
"preview": "---\n# Use the pdfbox parser, since it's the same one we used to originally etract the text to build this planning docume"
}
]
About this extraction
This page contains the full source code of the measuresforjustice/textricator GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 82 files (303.5 KB), approximately 79.1k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.