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. 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. Copyright (C) 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 . 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 . ================================================ FILE: NOTICE ================================================ Textricator Copyright 2018 Measures for Justice Institute. ================================================ FILE: README.md ================================================ # ![Textricator](./textricator-logo-text-paths.png) _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 . 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 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. ![mascot](./textricator-mascot.png) ================================================ FILE: pom.xml ================================================ 4.0.0 io.mfj textricator 10.2-SNAPSHOT ${project.groupId}:${project.artifactId} A tool to extract text from documents and generate structured data https://textricator.mfj.io/ Measures for Justice opensource@measuresforjustice.org Measures for Justice https://measuresforjustice.org/ GNU Affero General Public License, Version 3 https://www.gnu.org/licenses/agpl-3.0.txt 11 11 11 1.9.25 UTF-8 2025 https://github.com/measuresforjustice/textricator org.jetbrains.kotlinx kotlinx-coroutines-core 1.7.3 org.jetbrains.kotlin kotlin-stdlib-jdk8 ${kotlin.version} org.jetbrains.kotlin kotlin-test-junit ${kotlin.version} test org.jetbrains.kotlin kotlin-reflect ${kotlin.version} io.mfj expr 6.2.39 org.apache.pdfbox pdfbox 2.0.30 org.apache.pdfbox pdfbox-tools 2.0.30 com.itextpdf itextpdf 5.5.13.3 org.bouncycastle bcprov-jdk18on 1.78 com.itextpdf kernel 8.0.2 com.itextpdf layout 8.0.2 com.fasterxml.jackson.core jackson-databind 2.15.3 com.fasterxml.jackson.dataformat jackson-dataformat-xml 2.15.3 com.fasterxml.jackson.dataformat jackson-dataformat-yaml 2.15.3 com.fasterxml.jackson.module jackson-module-kotlin 2.15.3 org.jetbrains.kotlin kotlin-stdlib org.jetbrains.kotlin kotlin-reflect org.slf4j slf4j-api 2.0.9 ch.qos.logback logback-classic 1.4.12 org.apache.commons commons-csv 1.10.0 com.offbytwo docopt 0.6.0.20150202 src/main/resources true **/version.properties src/main/resources false **/version.properties org.jetbrains.kotlin kotlin-maven-plugin ${kotlin.version} compile compile compile ${project.basedir}/src/main/java test-compile test-compile test-compile ${project.basedir}/src/test/java org.jetbrains.dokka dokka-maven-plugin 2.0.0 prepare-package dokka javadoc javadocJar org.apache.maven.plugins maven-source-plugin 3.2.1 attach-sources jar org.apache.maven.plugins maven-surefire-plugin 2.22.1 false org.apache.maven.plugins maven-assembly-plugin 3.3.0 package single src/assembly/tgz.xml src/assembly/zip.xml org.apache.maven.plugins maven-enforcer-plugin 1.4.1 enforce-no-snapshots enforce Cannot have snapshot dependencies of a release! true true true true ================================================ FILE: src/assembly/tgz.xml ================================================ bin tgz / ${project.basedir}/src/scripts textricator 0755 ${project.basedir} README.* NOTICE COPYING examples/ lib ================================================ FILE: src/assembly/zip.xml ================================================ bin zip / ${project.basedir}/src/scripts textricator.bat ${project.basedir} README.* NOTICE COPYING examples/ lib ================================================ 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 . */ 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 { 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:SequenceInputStream,String>>, output:OutputStream, outputFormat:String, config:FormParseConfig, eventListener:FormParseEventListener = LoggingEventListener ) { getRecordOutput( outputFormat, output, config, includeSource=true ).use { recordOutput -> val records = sequence { 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 { // 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 { // 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 = (1..extractor.getPageCount()) .asSequence() .filter { pageNumber -> pageFilter( pageNumber ) } .flatMap { pageNumber -> extractor.extract( pageNumber ).asSequence() } @JvmStatic fun extractPages( extractor:TextExtractor, pageFilter:PageFilter = ALL_PAGES ): Sequence = (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 . */ 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 . */ 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=] [--max-row-distance=] [--box-precision=] [--box-ignore-colors=] [--input-format=] [--output-format=] [] textricator form [--debug] --config= [--pages=] [--input-format=] [--output-format=] [] textricator forms [--debug] --config= --input-format= [--output-format=] [] textricator table [--debug] --config= [--pages=] [--input-format=] [--output-format=] [] 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.boolean( key:String ):Boolean = containsKey(key) && get(key) as Boolean private fun Map.file( key:String ):File? = get(key)?.toString()?.let { File(it) } private fun Map.string( key:String ):String? = get(key)?.toString() private fun Map.float( key:String ):Float? = get(key)?.toString()?.toFloat() @JvmStatic fun main(args: Array) { // 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 ) { val inputFile = opts.file("")!! val inputFormat = opts.string("--input-format") ?: inputFile.extension.lowercase() val outputFile = opts.file("") 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 = 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 ) { val inputFile = opts.file("")!! val inputFormat = opts.string("--input-format") ?: inputFile.extension.lowercase() val outputFile = opts.file("") outputFile?.absoluteFile?.parentFile?.mkdirs() val outputFormat = opts.string("--output-format") ?: if ( outputFile == null ) { throw SystemExitException( "--output-format is required if 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 ) { val inputDir = opts.file("")!! val inputFormat = opts.string("--input-format")!! val inputFormatUpper = inputFormat.uppercase() val outputFile = opts.file("") outputFile?.absoluteFile?.parentFile?.mkdirs() val outputFormat = opts.string("--output-format") ?: if ( outputFile == null ) { throw SystemExitException( "--output-format is required if is omitted.", 1 ) } else { outputFile.extension.lowercase() } val configFile = opts.file("--config")!! val config = FormParseConfigUtil.parseYaml(configFile) val inputs:SequenceInputStream,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 ) { val inputFile = opts.file("")!! val inputFormat = opts.string("--input-format") ?: inputFile.extension.lowercase() val outputFile = opts.file("") outputFile?.absoluteFile?.parentFile?.mkdirs() val outputFormat = opts.string("--output-format") ?: if ( outputFile == null ) { throw SystemExitException( "--output-format is required if 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 . */ 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 } ================================================ 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 . */ 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> 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 = getFactoryClassFromFqcn( fqcn) Pair( name, factoryClass ) } } .flatten() .toMap() } val extractorNames:Collection by lazy { classMap.keys } /** Get the factory class for the specified FQCN. */ private fun getFactoryClassFromFqcn( fqcn:String ): Class = Class.forName(fqcn).let { class_ -> if ( TextExtractorFactory::class.java.isAssignableFrom( class_ ) ) { @Suppress("UNCHECKED_CAST") class_ as Class } 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 . */ package io.mfj.textricator.extractor open class TextExtractorOptions( var boxPrecision:Float =0f, var boxIgnoreColors:Set = 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 . */ 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> = mutableMapOf>() .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 = 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 . */ 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 . */ 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 . */ 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 ) { companion object { private val log = LoggerFactory.getLogger( Boxtricator::class.java ) } fun getBoxes( pageNumber:Int, pageHeight:Float):List { val boxes:MutableList = mutableListOf() val parser = PdfReaderContentParser(reader) parser.processContent(pageNumber, MyExtRenderListener(boxes, pageHeight, ignoreBoxColors)) return boxes.ifEmpty { emptyList() } } private class MyExtRenderListener(val boxes:MutableList, val pageHeight:Float, val ignoreColors:Set ): ExtRenderListener { private val pathInfos:MutableList = 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? ):List? { if ( coordinates == null ) return null val result:MutableList = 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 ):List { 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 . */ 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 . */ 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? ): 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 { 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 = 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 = 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 -> 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 -> 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 -> 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?,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 . */ 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 . */ 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) { 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) { val tdoperands:ArrayList = 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) { 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) { 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) { 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) { val aw:PdfNumber = operands[0] as PdfNumber val ac:PdfNumber = operands[1] as PdfNumber val string:PdfString = operands[2] as PdfString val twOperands:ArrayList = ArrayList(1) twOperands.add(0, aw) setTextWordSpacing.invoke(processor, null, twOperands) val tcOperands:ArrayList = ArrayList(1) tcOperands.add(0, ac) setTextCharacterSpacing.invoke(processor, null, tcOperands) val tickOperands:ArrayList = 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 . */ 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 . */ 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 { val page = doc.getPage(pageNumber) val pageHeight = page.pageSize.height val links:List = 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): LocationTextExtractionStrategy() { val texts = mutableListOf() 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 . */ 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 . */ 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> 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 = mapper.readValue(input,type) val map:MutableMap> = 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 { 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 . */ 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 . */ 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 { 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 . */ 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 . */ 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> = 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 ) { 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, 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 . */ 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 . */ 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 . */ 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 ): Sequence { // 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.combine():Sequence = 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> = mutableMapOf() /** * Get the expression and parsed Expr for the specified conditionId. */ private fun getCondition( conditionId:String ):Pair = 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 = 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 = 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 = 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 { val values:MutableList = 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 MutableList.removeLast(): T = removeAt( size-1 ) private val combineLimitMap:Map 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 . */ 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 . */ 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 ): Sequence { 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 = 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 = 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> = Stack() // 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>> = 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 by lazy { val m:MutableMap = 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> by lazy { config.recordTypes.mapValues { ( _, type ) -> // descendant to child of type val m:MutableMap = 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 = 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 = 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>.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 Stack.popUntil( predicate: (T)->Boolean ) { while ( ! isEmpty() && ! predicate( peek() ) ) pop() } /** * Remove elements until an element matches the given predicate, and remove that element too. */ fun Stack.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 . */ 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 . */ 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, 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 . */ 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 . */ 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 = 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 . */ 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 = mutableMapOf(), var stateDefaults: State? = null, var conditions: MutableMap = 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 = emptyMap(), override var valueTypes: Map = 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 = emptyList(), extractor:String? = null, pages:String? = null, maxRowDistance:Float = 0f, boxPrecision:Float =0f, boxIgnoreColors:MutableSet = 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 . */ 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 . */ 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 = ArrayList(), val startRecord: Boolean = false, val startRecordRequiredState: String? = null, val startRecordForEachValue:Boolean = false, val valueTypes: MutableList? = null, val combineLimit: Float? = null, val setVariables: MutableList = 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 . */ 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 . */ package io.mfj.textricator.form.config data class VariableSet( val name:String? = null, var value:String? = null ) ================================================ FILE: src/main/java/io/mfj/textricator/record/Record.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 . */ package io.mfj.textricator.record import java.beans.Transient // cannot be a data class, because used as a map key in RecordParser. class Record( val source:String?=null, val pageNumber:Int, val typeId:String, val values:MutableMap = mutableMapOf(), val children:MutableMap> = mutableMapOf() ) { constructor( pageNumber:Int, typeId:String, values:MutableMap = mutableMapOf(), children:MutableMap> = mutableMapOf() ) : this(null,pageNumber,typeId,values,children) val isLeaf:Boolean @Transient get() { children.values.forEach { childList -> if ( childList.isNotEmpty() ) { return false } } return true } fun getValue( valueTypeId:String, attribute:String? ): String? = values[valueTypeId]?.getValue(attribute) override fun hashCode():Int = pageNumber + typeId.hashCode() + 17 * values.size + 27 * children.size override fun equals(other:Any?):Boolean = ( other != null ) && ( other is Record) && pageNumber == other.pageNumber && typeId == other.typeId && values.size == other.values.size && children.size == other.children.size && values == other.values && children == other.children } ================================================ FILE: src/main/java/io/mfj/textricator/record/RecordFilter.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 . */ package io.mfj.textricator.record import io.mfj.expr.* /** * Filters records based on [RecordType.filter]. * * @param config FormParseConfig */ class RecordFilter( private val config:RecordModel) { companion object { private val DEFAULT_TYPE:ExDataType = ExDataType.STRING } fun filter( seq:Sequence ): Sequence = seq.mapNotNull { record -> filter( record ) } /** Map of value type id to ExDataType */ private val valueTypeMap = config.valueTypes.map { (id,member) -> id to ( member.type?.let { ExDataType.valueOf( it.uppercase() ) } ?: DEFAULT_TYPE) }.toMap() /** Get the ExDataType for the specified member. */ private fun getExDataType( valueTypeId:String ) = valueTypeMap[valueTypeId] ?: DEFAULT_TYPE /** Map of record type ID to the Expr to filter it, or null if no filter. */ private val recordTypeToExpr:Map = config.recordTypes.entries .associate { (recordTypeId, recordType) -> recordTypeId to buildExpr(recordType) } /** * Build Expr for the specified record type. Null if no filter. */ private fun buildExpr( type:RecordType): Expr? { val filter = type.filter return if ( filter != null ) { val vtp:VarTypeProvider = object:VarTypeProvider { override fun contains(varName:String):Boolean = type.valueTypes.contains(varName) override fun get(varName:String):ExDataType = if ( type.valueTypes.contains(varName) ) { getExDataType( varName ) } else { throw IllegalArgumentException( "No such var \"${varName}\"" ) } override fun getKnownVars():Map = type.valueTypes.associateWith { getExDataType(it) } } ExprParser.parseToExpr( filter, vtp ) } else { null } } /** * Filter the supplied record. * If the record's type's filter passes, return the record with the children also filtered. * If the record's type's filter does not pass, return null. */ private fun filter( record:Record): Record? { return if ( evalFilter( record ) ) { filterChildren( record ) record } else { null } } /** * Filter the children of the supplied record. */ private fun filterChildren( record:Record) { record.children.values.forEach { children -> children.retainAll { child -> evalFilter( child ) } children.forEach { child -> filterChildren( child ) } } } /** * Evaluate the filter for the specified record. */ private fun evalFilter( record:Record): Boolean = recordTypeToExpr[record.typeId] ?.value( object:VarProvider { override fun contains(varName:String):Boolean = record.values.contains( varName ) override fun get(varName:String):Any? { val exDataType = getExDataType(varName) val s = record.values[varName]?.text // TODO filter based on other attributes return ExConvert.convertStr( s, exDataType ) } override fun getKnownVars():Set = record.values.keys } ) ?: true // accept if no filter } ================================================ FILE: src/main/java/io/mfj/textricator/record/RecordModel.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 . */ package io.mfj.textricator.record /** * Defines the state machine */ interface RecordModel { val rootRecordType: String val recordTypes: Map val valueTypes: Map } data class RecordType( var label: String, // user defined name var children: List = emptyList(), // List of child RecordType's ids var valueTypes: List = emptyList(), // List of the data and cell leaf states at this level. var pagePriority: Int = 0, // for output, use the page from the type with the highest priority var filter:String? = null ) open class ValueType( val label:String? = null, /** If true, remove duplicate values. */ val unrepeat:Boolean = false, /** Separator when combining values. Values are combined after unrepeating */ val separator:String = " ", /** Replacements to make. Replacements are mae after values are unrepeated and combined. */ val replacements:MutableList? = null, /** If false, do not include in output. * Useful when the same data is repeated for each child record and you need it to mark new records. */ val include:Boolean = true, /** If set, use this attribute of [Value] instead of [Value.text]. */ val attribute:String? =null, /** Data type (used for [RecordType.filter]). */ val type:String? = null // ExDataType ) { fun calcValue( values:List ): Value { val text = values .map(Value::text) .unrepeat() .joinToString(separator) .replace() val link = values .asSequence() .mapNotNull(Value::link) .firstOrNull() return Value(text,link) } private fun List.unrepeat(): List { if ( ! unrepeat ) return this (1..size).forEach { i -> if ( isRepeated( this, i ) ) { return this.subList(0,i).unrepeat() } } return this } private fun isRepeated( list:List, pos:Int ): Boolean { if ( list.size < pos*2 ) return false (0 until pos).forEach { i -> if ( list[i] != list[pos+i] ) { return false } } return true } private fun String.replace(): String { // if there's no replacements, return the original string if ( replacements == null) { return this } else { // otherwise check all possible regex patterns for a match replacements.forEach { r -> // if the string matches a pattern, replace it with the regex replacement and return if ( r.regexPattern.containsMatchIn( this ) ) { return r.regexPattern.replace(this, r.replacement) } } } // if the string matched no patterns, return the original string return this } } private fun List.join(separator:String):Value { val text = map(Value::text).joinToString(separator) val link = asSequence().mapNotNull(Value::link).firstOrNull() return Value(text,link) } fun ValueType?.calculateValue( values:List ): Value = this?.calcValue(values) ?: values.join(" ") data class PatternReplacement(val pattern:String, val replacement:String ) { // lazy property to make regex from pattern val regexPattern by lazy { Regex(pattern) } } ================================================ FILE: src/main/java/io/mfj/textricator/record/Value.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 . */ package io.mfj.textricator.record data class Value( val text:String, val link:String? = null ) { fun getValue( attribute:String? ): String? = when(attribute) { null -> text "link" -> link else -> throw IllegalArgumentException("Unhandled attribute \"${attribute}\"." ) } } ================================================ FILE: src/main/java/io/mfj/textricator/record/output/CsvRecordOutput.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 . */ package io.mfj.textricator.record.output import org.apache.commons.csv.* import io.mfj.textricator.record.Record import io.mfj.textricator.record.RecordModel import io.mfj.textricator.record.RecordType import java.io.BufferedWriter import java.io.OutputStream import java.io.OutputStreamWriter import kotlinx.coroutines.channels.ReceiveChannel class CsvRecordOutput(private val config:RecordModel, output:OutputStream, private val includeSource:Boolean=false ):RecordOutput { private val w = BufferedWriter(OutputStreamWriter(output)) private val valueTypes = config.valueTypes val p = CSVPrinter(w, CSVFormat.DEFAULT.withRecordSeparator("\n")) var rowCount = 0 override fun write( seq:Sequence ) { printHeader(p) seq.forEach { rec -> printRows(p,rec) } } override suspend fun write(channel:ReceiveChannel) { printHeader(p) for ( rec in channel ) { printRows(p,rec) } } override fun close() { p.flush() // do NOT close p, the caller is responsible for closing w, and that is all that p.close() does. //p.close() w.close() } private fun printHeader(p:CSVPrinter) { if ( includeSource ) p.print("source") p.print("page") fun printType( recordType:RecordType) { recordType.valueTypes.forEach { valueTypeId -> val valueType = valueTypes[valueTypeId] if ( valueType?.include ?: true ) { val label = valueType?.label ?: valueTypeId p.print( label ) } } recordType.children .map { config.recordTypes[it] ?: throw Exception("missing type ${it}") } .forEach { childRecordType -> printType( childRecordType ) } } val rootRecordType = config.recordTypes[config.rootRecordType] ?: throw Exception("missing type ${config.rootRecordType}") printType(rootRecordType) p.println() } private fun printRows(p:CSVPrinter,root:Record) { val map:MutableMap = mutableMapOf() fun pr(rec:Record) { val type = config.recordTypes[rec.typeId] ?: throw Exception( "Missing type ${rec.typeId}" ) map[type] = rec if ( rec.isLeaf ) { printRow(p,map) } else { rec.children.values.forEach { it.forEach { pr(it) } } } map.remove(type) } pr(root) } private fun printRow( p:CSVPrinter, map:Map ) { val cells:MutableList = mutableListOf() var pageNumber:Int? = null var pageNumberPriority:Int = -1 fun printType( recordType:RecordType) { val rec = map[recordType] if ( ( rec != null ) && ( pageNumber == null || recordType.pagePriority > pageNumberPriority ) ) { pageNumber = rec.pageNumber pageNumberPriority = recordType.pagePriority } recordType.valueTypes.forEach { valueTypeId -> val valueType = valueTypes[valueTypeId] if ( valueType?.include ?: true ) { val attribute = valueType?.attribute val value = rec?.getValue(valueTypeId,attribute) ?: "" cells.add( value ) } } recordType.children .map { config.recordTypes[it] ?: throw Exception("missing type ${it}") } .forEach { childRecordType -> printType( childRecordType ) } } val rootRecordType = config.recordTypes[config.rootRecordType] ?: throw Exception("missing type ${config.rootRecordType}") printType(rootRecordType) if ( includeSource ) p.print( map[rootRecordType]!!.source ) p.print( pageNumber ) p.printRecord( cells ) if ( rowCount++ % 100 == 0 ) p.flush() } } ================================================ FILE: src/main/java/io/mfj/textricator/record/output/JsonFlatRecordOutput.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 . */ package io.mfj.textricator.record.output import io.mfj.textricator.record.Record import io.mfj.textricator.record.RecordModel import io.mfj.textricator.record.RecordType import io.mfj.textricator.record.ValueType import java.io.BufferedWriter import java.io.OutputStream import java.io.OutputStreamWriter import java.util.concurrent.atomic.AtomicBoolean import com.fasterxml.jackson.core.JsonGenerator import com.fasterxml.jackson.databind.ObjectMapper import kotlinx.coroutines.channels.ReceiveChannel class JsonFlatRecordOutput(private val config:RecordModel, output:OutputStream, private val includeSource:Boolean): RecordOutput { private val w = BufferedWriter(OutputStreamWriter(output)) private val valueTypes = config.valueTypes private val writer = ObjectMapper() .configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET,false) // otherwise closes w .writer().withDefaultPrettyPrinter() var printHeader = true override fun write( seq:Sequence ) { w.append( "[" ) val notFirst = AtomicBoolean(false) if ( printHeader ) { printHeader() notFirst.set(true) } seq.forEach { rec -> printRows(rec,notFirst) } w.append( "]" ) } override suspend fun write(channel:ReceiveChannel) { w.append( "[" ) val notFirst = AtomicBoolean(false) if ( printHeader ) { printHeader() notFirst.set(true) } for ( rec in channel ) { printRows(rec,notFirst) } w.append( "]" ) } override fun close() { w.close() } private fun printHeader() { val row:MutableMap = mutableMapOf() if ( includeSource ) row["source"] = "source" row["page"] = "page" fun print( recordType:RecordType) { recordType.valueTypes.forEach { valueTypeId -> val valueType:ValueType? = valueTypes[valueTypeId] if ( valueType?.include ?: true ) { val label = valueType?.label ?: valueTypeId row[valueTypeId] = label } } recordType.children .map { config.recordTypes[it] ?: throw Exception("missing type ${it}") } .forEach { childRecordType -> print( childRecordType ) } } val rootRecordType = config.recordTypes[config.rootRecordType] ?: throw Exception("missing type ${config.rootRecordType}") print(rootRecordType) writer.writeValue(w,row) } private fun printRows(root:Record,notFirst:AtomicBoolean) { val map:MutableMap = mutableMapOf() fun pr(rec:Record) { val recType = config.recordTypes[rec.typeId] ?: throw Exception( "Missing type ${rec.typeId}" ) map[recType] = rec if ( rec.isLeaf ) { if ( notFirst.getAndSet(true) ) w.write(",") printRow(map) } else { rec.children.values.forEach { it.forEach { pr(it) } } } map.remove(recType) } pr(root) } private fun printRow( map:Map ) { val row:MutableMap = mutableMapOf() var pageNumber:Int? = null var pageNumberPriority:Int = -1 fun printType( type:RecordType) { val rec = map[type] if ( pageNumber == null && rec != null ) pageNumber = rec.pageNumber if ( ( rec != null ) && ( pageNumber == null || type.pagePriority > pageNumberPriority ) ) { pageNumber = rec.pageNumber pageNumberPriority = type.pagePriority } type.valueTypes.forEach { valueTypeId -> val valueType = valueTypes[valueTypeId] if ( valueType?.include ?: true ) { val attribute = valueType?.attribute val value = rec?.getValue(valueTypeId,attribute) ?: "" row[valueTypeId] = value } } type.children .map { config.recordTypes[it] ?: throw Exception("missing type ${it}") } .forEach { childRecordType -> printType( childRecordType ) } } val rootRecordType = config.recordTypes[config.rootRecordType] ?: throw Exception("missing type ${config.rootRecordType}") printType(rootRecordType) if ( includeSource ) { row["source"] = map[rootRecordType]!!.source ?: "" } row["page"] = pageNumber.toString() writer.writeValue(w,row) } } ================================================ FILE: src/main/java/io/mfj/textricator/record/output/JsonRecordOutput.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 . */ package io.mfj.textricator.record.output import com.fasterxml.jackson.core.JsonGenerator import com.fasterxml.jackson.databind.ObjectMapper import io.mfj.textricator.record.Record import io.mfj.textricator.record.RecordModel import java.io.BufferedWriter import java.io.OutputStream import java.io.OutputStreamWriter import java.io.Writer import kotlinx.coroutines.channels.ReceiveChannel class JsonRecordOutput(config:RecordModel,output:OutputStream):RecordOutput { private val w = BufferedWriter(OutputStreamWriter(output)) private val writer = ObjectMapper() .configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET,false) // otherwise closes w .writer().withDefaultPrettyPrinter() override fun write( seq:Sequence ) { w.append( "[" ) var first = true seq.forEach { rec -> if ( first ) { first = false } else { w.append( "," ) } writeRec( w, rec ) } w.append( "]" ) } override suspend fun write(channel:ReceiveChannel) { w.append( "[" ) var first = true for ( rec in channel ) { if ( first ) { first = false } else { w.append( "," ) } writeRec( w, rec ) } w.append( "]" ) } private fun writeRec( w:Writer, rec:Record) { writer.writeValue(w,rec) } override fun close() { w.close() } } ================================================ FILE: src/main/java/io/mfj/textricator/record/output/NullOutput.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 . */ package io.mfj.textricator.record.output import io.mfj.textricator.record.Record import kotlinx.coroutines.channels.ReceiveChannel /** * Run through the records but do not do anything with them. */ object NullOutput:RecordOutput { override fun write(seq:Sequence) { seq.forEach {} } override suspend fun write(channel:ReceiveChannel) { for ( rec in channel ) { } } override fun close() {} } ================================================ FILE: src/main/java/io/mfj/textricator/record/output/RecordOutput.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 . */ package io.mfj.textricator.record.output import io.mfj.textricator.record.Record import java.io.Closeable import kotlinx.coroutines.channels.ReceiveChannel interface RecordOutput: Closeable { fun write( seq:Sequence ) suspend fun write( channel:ReceiveChannel) } ================================================ FILE: src/main/java/io/mfj/textricator/record/output/XmlRecordOutput.kt ================================================ /* This file is part of Textricator. Copyright 2021 Stephen Byrne. 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 . */ package io.mfj.textricator.record.output import io.mfj.textricator.record.Record import io.mfj.textricator.record.RecordModel import java.io.BufferedWriter import java.io.OutputStream import java.io.OutputStreamWriter import javax.xml.stream.XMLOutputFactory import kotlinx.coroutines.channels.ReceiveChannel import com.fasterxml.jackson.annotation.JsonInclude import com.fasterxml.jackson.databind.SerializationFeature import com.fasterxml.jackson.dataformat.xml.XmlMapper class XmlRecordOutput(config:RecordModel,output:OutputStream):RecordOutput { private val w = BufferedWriter(OutputStreamWriter(output)) // First create Stax components we need private val xmlOutputFactory = XMLOutputFactory.newFactory() private val sw = xmlOutputFactory.createXMLStreamWriter(w) // then Jackson components private val mapper = XmlMapper() .apply { enable(SerializationFeature.INDENT_OUTPUT) setSerializationInclusion(JsonInclude.Include.NON_EMPTY) // omit empty elements e.g.: lots of } init { sw.writeStartDocument(); sw.writeStartElement("Records"); } override fun write( seq:Sequence ) { seq.forEach { rec-> mapper.writeValue(sw, rec); } } override suspend fun write(channel:ReceiveChannel) { for ( rec in channel ) { mapper.writeValue(sw,rec) } } override fun close() { try { sw.writeEndElement(); sw.writeEndDocument(); sw.close() } finally { w.close() } } } ================================================ FILE: src/main/java/io/mfj/textricator/table/Table.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 . */ package io.mfj.textricator.table internal class Table(private val numberOfColumns:Int, private val maxRowDistance:Float) { private val xtable:XTable = mutableMapOf() private fun createXRow():XRow = (0..numberOfColumns) .map { createXCell() } .toTypedArray() private fun createXCell():XCell = mutableMapOf() private fun createXValues():XValues = mutableListOf() /** add an object to the model */ fun addToCell(x:Float, y:Float, columnIndex:Int, text:String) { val xrow = xtable.getOrPut( y, { createXRow() } ) val xcell = xrow[columnIndex] val xvalues = xcell.getOrPut( x, { createXValues() } ) xvalues.add( text ) } fun getRows(): Sequence { return xtable .toSortedMap() .group() .asSequence() .map { xrow -> xrow.toRow() } } /** * Group rows that are within [maxRowDistance]. * * This modifies the receiver! */ private fun Map.group(): List { val grouped:MutableList = mutableListOf() var buffer:Pair? = null for ( ( y, row ) in entries ) { if ( buffer == null ) { // first row buffer = Pair(y,row) } else if ( buffer.first + maxRowDistance < y ) { // new row grouped.add( buffer.second ) buffer = Pair(y,row) } else { // combine row with buffer.second row.forEachIndexed { index, cell -> // cell is a map of x-coords to value // if 2 identical x-coords, space-separate them val bufferCell = buffer.second[index] cell.entries.forEach { (x,value) -> bufferCell.getOrPut( x, { createXValues() } ) .addAll( value ) } } } } if ( buffer != null ) { grouped.add( buffer.second ) } return grouped } private fun XRow.toRow():Row = map { xcell -> xcell.toCell() } // sort by x-coord, then combine the xvalues (which is already sorted by y-value) private fun XCell.toCell():Cell = toSortedMap().values.flatten().toList() } ///// internal data structure // map y-coord -> row private typealias XTable = MutableMap // cell index -> cell private typealias XRow = Array // x-coord -> values private typealias XCell = MutableMap private typealias XValues = MutableList ================================================ FILE: src/main/java/io/mfj/textricator/table/TableParser.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 . */ package io.mfj.textricator.table import io.mfj.textricator.table.config.TableParseConfig import io.mfj.textricator.record.Record import io.mfj.textricator.record.Value import io.mfj.textricator.text.Page import io.mfj.textricator.text.PageFilter import io.mfj.textricator.text.Text import io.mfj.textricator.text.toPageFilter import org.slf4j.LoggerFactory /** * Extract tabular data from a PDF where there is text in each "cell" that may overflow into the next cell. */ class TableParser( private val config:TableParseConfig) { companion object { private val log = LoggerFactory.getLogger( TableParser::class.java ) internal val ROOT_TYPE = "row" } fun parse(pages:Sequence): Sequence { // just the start x-index of each column, sorted val cols = config.cols.values.sorted().toTypedArray() val pageFilter:PageFilter = config.pages.toPageFilter() return pages .filter { page -> pageFilter(page.pageNumber) } .flatMap { page -> val pageNumber = page.pageNumber // position filter val top:Float = config.getTop(pageNumber) ?: 0f val bottom:Float = config.getBottom(pageNumber) ?: Float.MAX_VALUE val pageLeft:Float = cols[0] val pageRight:Float = config.getRight(pageNumber) ?: Float.MAX_VALUE val positionFilter = { text:Text -> val y = text.uly val x = text.ulx ( y >= top ) && ( y <= bottom ) && ( x >= pageLeft ) && ( x <= pageRight ) } // find the column based on x-value fun findCol( x:Float ):Int? { cols.forEachIndexed { colIndex, left -> val right = if ( colIndex+1 < cols.size ) { cols[colIndex+1] } else { pageRight } if ( x >= left && x < right ) { return colIndex } } return null } // table to add text to val table = Table(config.cols.size, config.maxRowDistance) // Run the extraction page.texts .filter ( positionFilter ) .forEach { text -> findCol(text.ulx)?.let { colIndex -> log.debug( "p${pageNumber} y${text.uly} c${colIndex} ${text.content}" ) table.addToCell(text.ulx, text.uly, colIndex, text.content) } } log.debug("processed page ${pageNumber}") table.getRows() .map { row -> createRecord( pageNumber, row ) } } } private val valueTypes = config.valueTypes private fun createRecord( pageNumber:Int, row:Row):Record { // Create a single record per row. // It has no children, just values. val record = Record(source=null, pageNumber = pageNumber, typeId = ROOT_TYPE) config.cols.keys .forEachIndexed { i, colName -> val cell = row[i].map { text -> Value(text) } val value = valueTypes[colName]!!.calcValue( cell ) record.values[colName] = value } return record } } internal typealias Row = List internal typealias Cell = List ================================================ FILE: src/main/java/io/mfj/textricator/table/config/TableParseConfig.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 . */ package io.mfj.textricator.table.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 import io.mfj.textricator.table.TableParser // Value types are dynamically generated from [cols]. class TableParseConfig( var top:Float? = null, var bottom:Float? = null, var right:Float? = null, var cols:Map, var pageConfig:Map? = null, val types:Map = emptyMap(), val filter:String? = null, extractor:String? = null, maxRowDistance: Float, pageFilter:String? = null ): TextExtractorOptions( extractor = extractor, maxRowDistance = maxRowDistance, pages = pageFilter ), RecordModel { override val recordTypes:Map get() = mapOf( TableParser.ROOT_TYPE to RecordType( label = TableParser.ROOT_TYPE, valueTypes = cols.keys.toList(), filter = filter ) ) override val rootRecordType:String get() = TableParser.ROOT_TYPE override val valueTypes:Map get() = cols .mapValues { (colName,_) -> types[colName] ?: ValueType(colName) } fun getTop(page:Int):Float? { return pageConfig?.get(page)?.top ?: top } fun getBottom(page:Int):Float? { return pageConfig?.get(page)?.bottom ?: bottom } fun getRight(page:Int):Float? { return pageConfig?.get(page)?.right ?: right } } data class ConfigPage( var top:Float? = null, var bottom:Float? = null, var right:Float? = null, var skip:Boolean = false) ================================================ FILE: src/main/java/io/mfj/textricator/table/config/TableParseConfigUtil.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 . */ package io.mfj.textricator.table.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 TableParseConfigUtil { private val mapper = ObjectMapper(YAMLFactory()).registerKotlinModule() fun parseYaml(configFile:File):TableParseConfig = mapper.readValue( configFile.readText() ) fun parseYaml(input:InputStream):TableParseConfig = mapper.readValue(input) } ================================================ FILE: src/main/java/io/mfj/textricator/text/Page.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 . */ package io.mfj.textricator.text import io.mfj.textricator.text.Text data class Page( /** Page number. */ val pageNumber:Int, /** Texts on page. */ val texts:List ) ================================================ FILE: src/main/java/io/mfj/textricator/text/PageFilter.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 . */ package io.mfj.textricator.text typealias PageFilter = (Int)->Boolean val ALL_PAGES:PageFilter = { _:Int -> true } /** * Parse pages text to PageFilter. * * @param pages Pages: e.g.: 1,3-5,100-103,400 */ fun String?.toPageFilter():PageFilter { return if (this != null && isNotBlank()) { val ranges:List<(Int)->Boolean> = split(",").map { s -> if (s.contains("-")) { val a = s.split("-") val min = a[0].toInt() val max = intOrEnd(a[1]) ; { page:Int -> (min..max).contains(page) } } else { val p = s.toInt(); { page:Int -> (page == p) } } }; { page:Int -> ranges.any { it(page) } } } else { ALL_PAGES } } private fun intOrEnd( s:String? ): Int = if ( s == null || s.isBlank() ) { Int.MAX_VALUE } else { s.toInt() } fun PageFilter.and( pages:PageFilter):PageFilter = { i -> this(i) && pages(i) } fun PageFilter.and(s:String?):PageFilter = this.and( s.toPageFilter() ) ================================================ FILE: src/main/java/io/mfj/textricator/text/RowGrouper.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 . */ package io.mfj.textricator.text class RowGrouper( private val maxRowDistance:Float ) { private class GroupByRowState { var buffer:MutableList = mutableListOf() var lastPage:Int = 1 } fun group( source:Sequence ): Sequence { val groupByRowState = GroupByRowState() return source .plus( null as Text? ) // sentinal .map { text -> groupByRow( groupByRowState, text ) } .filter { it != null }.map { it!! } .flatten() } private fun groupByRow( s:GroupByRowState, text:Text? ): Sequence? { // collect until find a pageNumber break or gap of $maxRowDistance, then flush if ( text == null ) { // sentintal // flush and done. return s.buffer.sortedBy( Text::ulx ).asSequence() } val ret:MutableList = mutableListOf() if ( text.pageNumber != s.lastPage ) { // new pageNumber ret.addAll( s.buffer.sortedBy( Text::ulx ) ) s.buffer = mutableListOf() } if ( s.buffer.isEmpty() ) { } else { val last = s.buffer.last() if ( text.uly - last.uly > maxRowDistance ) { ret.addAll( s.buffer.sortedBy( Text::ulx ).asSequence() ) s.buffer = mutableListOf() } } s.buffer.add( text ) s.lastPage = text.pageNumber return if ( ret.isNotEmpty() ) ret.asSequence() else null } } fun Sequence.groupRows(maxRowDistance:Float?): Sequence = if ( maxRowDistance != null ) { RowGrouper(maxRowDistance).group(this) } else { this } fun Sequence.groupRowsPaged(maxRowDistance:Float?): Sequence = if ( maxRowDistance != null ) { this.map { page -> Page(page.pageNumber, page.texts.asSequence().groupRows(maxRowDistance).toList()) } } else { this } ================================================ FILE: src/main/java/io/mfj/textricator/text/Text.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 . */ package io.mfj.textricator.text import java.beans.Transient /** * Extricated text. * * Positions and dimensions are in points. * x=0 is the left edge. * y=0 is the top edge. * * @property content The text. * @property pageNumber Page Number * @property ulx upper-left x-coordinate * @property uly upper-left y-coordinate * @property lrx lower-right x-coordinate * @property lry lower-right y-coordinate * @property link link url * @property font Font name * @property fontSize Font size, in points * @property color Text color * @property backgroundColor Background color * * @property width Width * @property height Height */ data class Text( val content:String, val pageNumber:Int, val ulx:Float, val uly:Float, val lrx:Float, val lry:Float, val font:String, val fontSize:Float, val color:String? = null, val backgroundColor:String? = null, val link:String? = null ) { val width:Float @Transient get() = lrx - ulx; val height:Float @Transient get() = lry - uly; } ================================================ FILE: src/main/java/io/mfj/textricator/text/output/CsvTextOutput.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 . */ package io.mfj.textricator.text.output import io.mfj.textricator.text.Text import java.io.OutputStream import org.apache.commons.csv.* import org.slf4j.LoggerFactory import java.io.OutputStreamWriter class CsvTextOutput(output:OutputStream):TextOutput { private val w = OutputStreamWriter(output) private val p = CSVPrinter(w, CSV_FORMAT) companion object { private val log = LoggerFactory.getLogger(CsvTextOutput::class.java) val CSV_FORMAT = CSVFormat.DEFAULT.withRecordSeparator("\n") } override fun close() { p.close() w.close() } override fun write(seq:Sequence) { writeHeader() writeTexts(seq) } private fun writeTexts(seq:Sequence) { seq.forEach { text -> write( text ) } } private fun writeHeader() { p.printRecord( "page", "ulx", "uly", "lrx", "lry", "width", "height", "content", "font", "fontSize", "fontColor", "bgcolor", "link" ) } private fun write(text:Text) { // If you change this, change CsvTextExtractor.parseRec(CSVRecord) to match. p.printRecord( text.pageNumber, text.ulx, text.uly, text.lrx, text.lry, text.width, text.height, text.content, text.font, text.fontSize, text.color, text.backgroundColor, text.link ) } } ================================================ FILE: src/main/java/io/mfj/textricator/text/output/JsonTextOutput.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 . */ package io.mfj.textricator.text.output import io.mfj.textricator.text.Text import java.io.OutputStream import com.fasterxml.jackson.core.JsonGenerator import com.fasterxml.jackson.databind.ObjectMapper import org.slf4j.LoggerFactory class JsonTextOutput(private val output:OutputStream):TextOutput { private val writer = ObjectMapper() .configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET,false) .writer().withDefaultPrettyPrinter() companion object { private val log = LoggerFactory.getLogger(JsonTextOutput::class.java) } override fun close() {} override fun write(seq:Sequence) { write("[") var first = true seq.forEach { text -> if ( first ) first = false else output.write(",".toByteArray()) writer.writeValue(output,text) } write("]") } private fun write(s:String) { output.write( s.toByteArray() ) } } ================================================ FILE: src/main/java/io/mfj/textricator/text/output/TextOutput.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 . */ package io.mfj.textricator.text.output import io.mfj.textricator.text.Text import java.io.Closeable interface TextOutput: Closeable { fun write( seq:Sequence ) } ================================================ FILE: src/main/resources/io/mfj/textricator/extractor/textExtractor.properties ================================================ pdf.itext5=io.mfj.textricator.extractor.itext5.Itext5TextExtractorFactory pdf.itext7=io.mfj.textricator.extractor.itext7.Itext7TextExtractorFactory pdf.pdfbox=io.mfj.textricator.extractor.pdfbox.PdfboxTextExtractorFactory json=io.mfj.textricator.extractor.json.JsonTextExtractorFactory csv=io.mfj.textricator.extractor.csv.CsvTextExtractorFactory ================================================ FILE: src/main/resources/io/mfj/textricator/logback.xml ================================================ System.err %d{HH:mm:ss.SSS} [%thread] %-5level %logger -%kvp- %msg%n ================================================ FILE: src/main/resources/io/mfj/textricator/version.properties ================================================ version=${project.version} copyright.year=${copyright.year} source.location=${source.location} ================================================ FILE: src/scripts/textricator ================================================ #!/usr/bin/env bash # Find script directory ($SCRIPT_DIR). # On linux (and cygwin) "SCRIPT_DIR=$(basedir $(readlink -f $0))" works, # but Macos' readlink is very different. # This works on linux, cygwin, and macos: SCRIPT_DIR=$(cd -P -- "$(dirname -- "$0")" && pwd -P) && SCRIPT_DIR=$SCRIPT_DIR/$(basename -- "$0") while [[ -h "$SCRIPT_DIR" ]]; do DIR=$(dirname -- "$SCRIPT_DIR") SYM=$(readlink "$SCRIPT_DIR") SCRIPT_DIR=$(cd "$DIR" && cd "$(dirname -- "$SYM")" && pwd)/$(basename -- "$SYM") done SCRIPT_DIR=$(dirname -- "$SCRIPT_DIR") java -cp "${SCRIPT_DIR}/lib/*" ${JAVA_OPTS} io.mfj.textricator.cli.TextricatorCli "$@" ================================================ FILE: src/scripts/textricator.bat ================================================ @echo off set batpath=%~dp0 java -cp "%batpath%lib/*" io.mfj.textricator.cli.TextricatorCli %* ================================================ FILE: src/test/java/io/mfj/textricator/examples/ExamplesTest.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 . */ package io.mfj.textricator.examples import io.mfj.textricator.Textricator import io.mfj.textricator.form.config.FormParseConfigUtil import io.mfj.textricator.table.config.TableParseConfigUtil import java.io.BufferedReader import java.io.File import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized /** * Run the examples. They make pretty good tests. */ @RunWith(Parameterized::class) class ExamplesTest( private val name:String, private val type:Type) { enum class Type { FORM, TABLE } companion object { /** * Examples. * Map of file name (without extension) to parse type. * For each of these, there must be a .pdf, a .yml, and a .csv in src/test/resources/io/mfj/textricator/examples/. */ val examples = mapOf( "rap-sheet" to Type.FORM, "school-employee-list" to Type.FORM ) @JvmStatic @Parameterized.Parameters(name="{1}:{0}") fun data() = examples.entries.map { (name,type) -> arrayOf( name, type ) } private fun compare( a:BufferedReader, b:BufferedReader ) = compare( a.lineSequence().iterator(), b.lineSequence().iterator()) private fun compare( a:Iterator, b:Iterator ) { var line = 0 while ( a.hasNext() ) { line++ assertTrue( "Missing line @${line}" ) { b.hasNext() } val aline = a.next() val bline = b.next() assertEquals( aline, bline, "Incorrect line @${line}" ) } line++ assertFalse( "Extra line @${line}" ) { b.hasNext() } } } @Test fun test() { val outCsv = File.createTempFile( name, ".csv" ) outCsv.deleteOnExit() try { // run textricator outCsv.outputStream().use { out -> ExamplesTest::class.java.getResourceAsStream( "${name}.yml" )!!.use { config -> ExamplesTest::class.java.getResourceAsStream( "${name}.pdf" )!!.use { pdf -> when ( type ) { Type.FORM -> { Textricator.parseForm( input = pdf, inputFormat = "pdf", output = out, outputFormat = "csv", config = FormParseConfigUtil.parseYaml( config ) ) } Type.TABLE -> { Textricator.parseTable( input = pdf, inputFormat = "pdf", output = out, outputFormat = "csv", config = TableParseConfigUtil.parseYaml( config ) ) } } } } } // make sure CSVs match outCsv.bufferedReader().use { b -> ExamplesTest::class.java.getResourceAsStream( "${name}.csv" )!!.bufferedReader().use { a -> compare(a, b) } } } finally { outCsv.delete() } } /** * Test that if we extract text to JSON and then use that as input, it works. */ @Test fun testJson() { val textJson = File.createTempFile( name, "-text.json" ) textJson.deleteOnExit() val outCsv = File.createTempFile( name, ".csv") outCsv.deleteOnExit() try { // pdf -> json textJson.outputStream().use { out -> ExamplesTest::class.java.getResourceAsStream( "${name}.yml" )!!.use { config -> ExamplesTest::class.java.getResourceAsStream( "${name}.pdf" )!!.use { pdf -> when ( type ) { Type.FORM -> { Textricator.extractText( input = pdf, inputFormat = "pdf", output = out, outputFormat = "json", textExtractorOptions = FormParseConfigUtil.parseYaml( config ) ) } Type.TABLE -> TODO() } } } } // json -> csv outCsv.outputStream().use { csv -> textJson.inputStream().use { json -> ExamplesTest::class.java.getResourceAsStream( "${name}.yml" )!!.use { config -> when ( type ) { Type.FORM -> { Textricator.parseForm( input = json, inputFormat = "json", output = csv, outputFormat = "csv", config = FormParseConfigUtil.parseYaml( config ) ) } Type.TABLE -> TODO() } } } } // make sure CSVs match outCsv.bufferedReader().use { b -> ExamplesTest::class.java.getResourceAsStream( "${name}.csv" )!!.bufferedReader().use { a -> compare(a, b) } } } finally { outCsv.delete() textJson.delete() } } /** * Test that if we extract text to CSV and then use that as input, it works. */ @Test fun testCSV() { val textCsv = File.createTempFile( name, "-text.csv" ) textCsv.deleteOnExit() val outCsv = File.createTempFile( name, ".csv") outCsv.deleteOnExit() try { // pdf -> json textCsv.outputStream().use { out -> ExamplesTest::class.java.getResourceAsStream( "${name}.yml" )!!.use { config -> ExamplesTest::class.java.getResourceAsStream( "${name}.pdf" )!!.use { pdf -> when ( type ) { Type.FORM -> { Textricator.extractText( input = pdf, inputFormat = "pdf", output = out, outputFormat = "csv", textExtractorOptions = FormParseConfigUtil.parseYaml( config ) ) } Type.TABLE -> TODO() } } } } // json -> csv outCsv.outputStream().use { csv -> textCsv.inputStream().use { textCsv -> ExamplesTest::class.java.getResourceAsStream( "${name}.yml" )!!.use { config -> when ( type ) { Type.FORM -> { Textricator.parseForm( input = textCsv, inputFormat = "csv", output = csv, outputFormat = "csv", config = FormParseConfigUtil.parseYaml( config ) ) } Type.TABLE -> TODO() } } } } // make sure CSVs match outCsv.bufferedReader().use { b -> ExamplesTest::class.java.getResourceAsStream( "${name}.csv" )!!.bufferedReader().use { a -> compare(a, b) } } } finally { outCsv.delete() textCsv.delete() } } } ================================================ FILE: src/test/java/io/mfj/textricator/form/NodeMembersTest.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 . */ package io.mfj.textricator.form import io.mfj.textricator.form.config.FormParseConfig import io.mfj.textricator.form.config.State import io.mfj.textricator.record.PatternReplacement import io.mfj.textricator.record.RecordType import io.mfj.textricator.record.Value import io.mfj.textricator.record.ValueType import org.junit.Assert.* import org.junit.Test class NodeMembersTest { val model = FormParseConfig(rootRecordType = "name", recordTypes = mutableMapOf( "name" to RecordType(label = "name", valueTypes = mutableListOf("inmateName", "city", "state", "inmateDOB", "arrestDate"))), valueTypes = mutableMapOf("inmateName" to ValueType(label = "Inmate Name"), "city" to ValueType(label = "City", replacements = mutableListOf(PatternReplacement("(.*),.*", "$1"))), "state" to ValueType(label = "State", replacements = mutableListOf(PatternReplacement(".*,(.*)", "$1"))), "inmateDOB" to ValueType(label = "Inmate DOB"), "arrestDate" to ValueType(label = "Arrest Date")), states = mutableMapOf("inmateName" to State(startRecord = true), "cityState" to State(valueTypes = mutableListOf("city", "state")), "inmateDOB" to State(), "arrestDate" to State())) val rp = RecordParser(model) private fun sv(pageNumber: Int, stateId: String, vararg value: String) :StateValue = StateValue( source = "test", pageNumber = pageNumber, stateId = stateId, state = model.states[stateId] ?: throw Exception("Missing State: ${stateId}"), values = value.toList().map{ Value(it) }) @Test fun testNodeMembers() { val stateValues: List = listOf( sv(1, "inmateName", "John Doe"), sv(1, "cityState", "New York,NY"), sv(1, "inmateDOB", "01/01/1985"), sv(1, "arrestDate", "02/15/2018"), sv(1, "inmateName", "Jane Doe"), sv(1, "cityState", "Rochester,NY"), sv(1, "inmateDOB", "12/12/1975"), sv(1, "arrestDate", "02/13/2018") ) val records = rp.parse(stateValues.asSequence()).toList() assertEquals("New York", records[0].values["city"]?.text) assertEquals("NY", records[0].values["state"]?.text) assertEquals("Rochester", records[1].values["city"]?.text) assertEquals("NY", records[1].values["state"]?.text) } } ================================================ FILE: src/test/java/io/mfj/textricator/form/PatternReplacementTest.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 . */ package io.mfj.textricator.form import io.mfj.textricator.form.config.FormParseConfig import io.mfj.textricator.form.config.State import io.mfj.textricator.record.PatternReplacement import io.mfj.textricator.record.RecordType import io.mfj.textricator.record.Value import io.mfj.textricator.record.ValueType import org.junit.Assert.* import org.junit.Test class PatternReplacementTest { val model = FormParseConfig(rootRecordType = "name", recordTypes = mutableMapOf( "name" to RecordType(label = "name", valueTypes = mutableListOf("inmateName", "inmateAge", "inmateRace", "arrestDateTime"))), valueTypes = mutableMapOf("inmateName" to ValueType(label = "Inmate Name"), "inmateAge" to ValueType(label = "Inmate Age", replacements = mutableListOf(PatternReplacement("30", "thirty"), PatternReplacement("40", "forty"))), "inmateRace" to ValueType(label = "Inmate Race", replacements = mutableListOf(PatternReplacement("W", "white"), PatternReplacement("W", "black"))), "arrestDateTime" to ValueType(label = "Arrest Date Time", replacements = mutableListOf( PatternReplacement(pattern = "(.*)\\ 12/30/1899\\ (.*)", replacement = "$1 $2")))), states = mutableMapOf("inmateName" to State(startRecord = true), "inmateAge" to State(), "inmateRace" to State(), "arrestDateTime" to State())) val rp = RecordParser(model) private fun sv(pageNumber: Int, stateId: String, vararg value: String) :StateValue = StateValue( source = "test", pageNumber = pageNumber, stateId = stateId, state = model.states[stateId] ?: throw Exception("Missing State: ${stateId}"), values = value.toList().map{ Value(it) }) @Test fun testPatternReplacement() { val stateValues: List = listOf( sv(1, "inmateName", "John Doe"), sv(1, "inmateAge", "30"), sv(1, "inmateRace", "W"), sv(1, "arrestDateTime", "02/15/2018 12/30/1899 03:33:00 AM"), sv(1, "inmateName", "Jane Doe"), sv(1, "inmateAge", "40"), sv(1, "inmateRace", "W"), sv(1, "arrestDateTime", "02/13/2018 05:55:00 PM") ) val records = rp.parse(stateValues.asSequence()).toList() // test that removing 12/30/1899 from arrestDateTime works assertEquals("02/15/2018 03:33:00 AM", records[0].values["arrestDateTime"]?.text) // test that nothing is removed from arrestDateTime when 12/30/1899 isn't there assertEquals("02/13/2018 05:55:00 PM", records[1].values["arrestDateTime"]?.text) // test that correct replacement is used when there are multiple patterns as options assertEquals("thirty", records[0].values["inmateAge"]?.text) assertEquals("forty", records[1].values["inmateAge"]?.text) // test that first replacement is used when there are multiple matching patterns assertEquals("white", records[0].values["inmateRace"]?.text) assertEquals("white", records[1].values["inmateRace"]?.text) } } ================================================ FILE: src/test/java/io/mfj/textricator/form/RecordParserTest.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 . */ package io.mfj.textricator.form import io.mfj.textricator.record.Record import io.mfj.textricator.record.RecordType import io.mfj.textricator.form.config.FormParseConfig import io.mfj.textricator.form.config.State import io.mfj.textricator.record.Value import org.junit.Assert.* import org.junit.Test class RecordParserTest { val model = FormParseConfig(rootRecordType = "date", recordTypes = mutableMapOf( "date" to RecordType(label = "Date", children = mutableListOf("person"), valueTypes = mutableListOf("date")), "person" to RecordType(label = "Person", children = mutableListOf("case"), valueTypes = mutableListOf("name", "dob")), "case" to RecordType(label = "Case", children = mutableListOf("charge"), valueTypes = mutableListOf("caseId", "court")), "charge" to RecordType(label = "Charge", valueTypes = mutableListOf("chargeCode", "chargeDesc"))), states = mutableMapOf( "date" to State(startRecord = true, startRecordForEachValue = true), "name" to State(startRecord = true), "dob" to State(), "caseId" to State(startRecord = true), "court" to State(), "chargeCode" to State(startRecord = true), "chargeDesc" to State())) val rp = RecordParser(model) private fun sv( pageNumber:Int, stateId:String, vararg value:String ):StateValue = StateValue( source = "test", pageNumber = pageNumber, stateId = stateId, state = model.states[stateId] ?: throw Exception("Missing state ${stateId}"), values = value.toList().map{ Value(it) }) @Test fun testStructure() { val stateValues:List = listOf( sv( 1, "date", "2018-01-01" ), sv( 1, "date", "2018-01-02" ), sv( 1, "name", "John Doe" ), sv( 1, "dob", "1980-01-01" ), sv( 1, "caseId", "CASE001" ), sv( 1, "court", "Kangaroo" ), sv( 1, "chargeCode", "AGGRAV ASSLT" ), sv( 1, "chargeDesc", "W DEADLY WEAPON" ), sv( 1, "chargeCode", "AGGRAV BATTERY" ), sv( 1, "chargeDesc", "BODILY HARM" ), sv( 1, "caseId", "CASE002" ), sv( 1, "court", "Kangaroo" ), sv( 1, "chargeCode", "MOVING VIOL" ), sv( 1, "chargeDesc", "30+" ), sv( 1, "chargeCode", "NONMOVING VIOL" ), sv( 1, "chargeDesc", "NO LICENSE" ), sv( 1, "name", "Jane Doe" ), sv( 1, "dob", "1990-01-01" ), sv( 1, "caseId", "CASE001" ), sv( 1, "court", "Kangaroo" ), sv( 1, "chargeCode", "VEH THEFT" ), sv( 1, "chargeDesc", "GRAND 3RD" ), sv( 1, "chargeCode", "NONMOVING VIOL" ), sv( 1, "chargeDesc", "NO LICESNSE" ) ) val records = rp.parse( stateValues.asSequence() ).toList() validateRecordsAgainstModel( records ) } private fun validateRecordsAgainstModel( records:List ) { records.forEach { record -> assertEquals( "Root records must be of type \"${model.rootRecordType}\" - found \"${record.typeId}\"", model.rootRecordType, record.typeId ) validateRecordAgainstModel( record ) } } private fun validateRecordAgainstModel( record:Record) { val childAllowedTypes = model.recordTypes[record.typeId]!!.children.toSet() record.children.keys.forEach { childType -> assertTrue( "Records of Type \"${record.typeId}\" may only contain children of types ${childAllowedTypes} - found \"${childType}\"", childAllowedTypes.contains( childType ) ) } record.children.values.forEach { children -> children.forEach { child -> validateRecordAgainstModel( child ) } } } @Test fun testAncestorThatIsAChildOf() { assertEquals( "person", rp.findAncestorThatIsAChildOf("person","date") ) assertEquals( "person", rp.findAncestorThatIsAChildOf("case","date") ) assertEquals( "person", rp.findAncestorThatIsAChildOf("charge","date") ) assertEquals( "case", rp.findAncestorThatIsAChildOf("case","person") ) assertEquals( "case", rp.findAncestorThatIsAChildOf("charge","person") ) assertEquals( "charge", rp.findAncestorThatIsAChildOf("charge","case") ) } /** * Make sure that if a state that is required for another state to start a new record * ([State.startRecordRequiredState]) * has [State.include] = false * that the state is still still noticed for the purposes of [State.startRecordRequiredState]. * * Previously, the [StateValue]s with [State.include]=false were filtered out too early and this did not work. */ @Test fun testStartRecordIfSeenIgnoredState() { val model = FormParseConfig(rootRecordType = "person", recordTypes = mutableMapOf( "person" to RecordType(label = "Person", valueTypes = mutableListOf("name")) ), states = mutableMapOf( "name" to State(startRecord = true, startRecordRequiredState = "label"), "label" to State(include = false) ) ) val stateValues = listOf( StateValue( source = "test", pageNumber = 1, values = listOf( Value("Fred") ), state = model.states["name"]!!, stateId = "name" ), StateValue( source = "test", pageNumber = 1, values = listOf( Value("label") ), state = model.states["label"]!!, stateId = "label" ), StateValue( source = "test", pageNumber = 1, values = listOf( Value("Sally") ), state = model.states["name"]!!, stateId = "name" ) ).asSequence() val records = RecordParser(model).parse( stateValues ).toList() assertEquals( 2, records.size ) assertEquals( "Fred", records[0].values["name"]?.text ) assertEquals( "Sally", records[1].values["name"]?.text ) } } ================================================ FILE: src/test/java/io/mfj/textricator/record/RecordFilterTest.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 . */ package io.mfj.textricator.record import io.mfj.expr.ExDataType import io.mfj.textricator.form.config.FormParseConfig import org.junit.Assert.* import org.junit.Test class RecordFilterTest { @Test fun testNoFilter() { val model = FormParseConfig(rootRecordType = "a", recordTypes = mutableMapOf( "a" to RecordType(label = "A", children = mutableListOf("b", "c"), valueTypes = mutableListOf("a1", "a2")), "b" to RecordType(label = "B", children = mutableListOf(), valueTypes = mutableListOf("b1", "b2")), "c" to RecordType(label = "C", children = mutableListOf("d"), valueTypes = mutableListOf("c1", "c2")), "d" to RecordType(label = "D", valueTypes = mutableListOf("d1", "d2")))) val records = listOf(Record(1, "a", mutableMapOf("a1" to Value("Hello"), "a2" to Value("World")), mutableMapOf( "b" to mutableListOf(Record(1, "b", mutableMapOf("b1" to Value("1"), "b2" to Value("2")))), "c" to mutableListOf(Record(1, "c", mutableMapOf("c1" to Value("1"), "c2" to Value("2")), mutableMapOf("d" to mutableListOf( Record(1, "d", mutableMapOf("d1" to Value("1"), "d2" to Value("2"))))))))) ) val filtered = RecordFilter(model).filter(records.asSequence()).toList() assertEquals( records, filtered ) } @Test fun testTopFilter() { val model = FormParseConfig(rootRecordType = "a", recordTypes = mutableMapOf( "a" to RecordType(label = "A", filter = """ a1 = "x" """, children = mutableListOf("b", "c"), valueTypes = mutableListOf("a1", "a2")), "b" to RecordType(label = "B", children = mutableListOf(), valueTypes = mutableListOf("b1", "b2")), "c" to RecordType(label = "C", children = mutableListOf("d"), valueTypes = mutableListOf("c1", "c2")), "d" to RecordType(label = "D", valueTypes = mutableListOf("d1", "d2")))) val records = listOf(Record(1, "a", mutableMapOf("a1" to Value("Hello"), "a2" to Value("World")), mutableMapOf( "b" to mutableListOf(Record(1, "b", mutableMapOf("b1" to Value("1"), "b2" to Value("2")))), "c" to mutableListOf(Record(1, "c", mutableMapOf("c1" to Value("1"), "c2" to Value("2")), mutableMapOf("d" to mutableListOf( Record(1, "d", mutableMapOf("d1" to Value("1"), "d2" to Value("2"))))))))) ) val filtered = RecordFilter(model).filter(records.asSequence()).toList() assertTrue( filtered.isEmpty() ) } @Test fun testChildFilter() { val model = FormParseConfig(rootRecordType = "a", recordTypes = mutableMapOf( "a" to RecordType(label = "A", filter = """ a1 = "Hello" and a2 = "World" """, children = mutableListOf("b", "c"), valueTypes = mutableListOf("a1", "a2")), "b" to RecordType(label = "B", children = mutableListOf(), valueTypes = mutableListOf("b1", "b2")), "c" to RecordType(label = "C", filter = """ c1 = "2" """, children = mutableListOf("d"), valueTypes = mutableListOf("c1", "c2")), "d" to RecordType(label = "D", valueTypes = mutableListOf("d1", "d2")))) val records = listOf(Record(1, "a", mutableMapOf("a1" to Value("Hello"), "a2" to Value("World")), mutableMapOf( "b" to mutableListOf(Record(1, "b", mutableMapOf("b1" to Value("1"), "b2" to Value("2")))), "c" to mutableListOf(Record(1, "c", mutableMapOf("c1" to Value("1"), "c2" to Value("2")), mutableMapOf("d" to mutableListOf( Record(1, "d", mutableMapOf("d1" to Value("1"), "d2" to Value("2"))))))))) ) val expected = listOf(Record(1, "a", mutableMapOf("a1" to Value("Hello"), "a2" to Value("World")), mutableMapOf( "b" to mutableListOf(Record(1, "b", mutableMapOf("b1" to Value("1"), "b2" to Value("2")))), "c" to mutableListOf())) ) val filtered = RecordFilter(model).filter(records.asSequence()).toList() assertEquals( expected, filtered ) } @Test fun testChildFilterSome() { val model = FormParseConfig(rootRecordType = "a", recordTypes = mutableMapOf( "a" to RecordType(label = "A", filter = """ a1 = "Hello" and a2 = "World" """, children = mutableListOf("b", "c"), valueTypes = mutableListOf("a1", "a2")), "b" to RecordType(label = "B", children = mutableListOf(), valueTypes = mutableListOf("b1", "b2")), "c" to RecordType(label = "C", filter = """ c1 = "2" """, children = mutableListOf("d"), valueTypes = mutableListOf("c1", "c2")), "d" to RecordType(label = "D", valueTypes = mutableListOf("d1", "d2")))) val records = listOf(Record(1, "a", mutableMapOf("a1" to Value("Hello"), "a2" to Value("World")), mutableMapOf( "b" to mutableListOf(Record(1, "b", mutableMapOf("b1" to Value("1"), "b2" to Value("2")))), "c" to mutableListOf(Record(1, "c", mutableMapOf("c1" to Value("1"), "c2" to Value("2")), mutableMapOf("d" to mutableListOf( Record(1, "d", mutableMapOf("d1" to Value("1"), "d2" to Value("2")))))), Record(1, "c", mutableMapOf("c1" to Value("2"), "c2" to Value("3")), mutableMapOf( "d" to mutableListOf( Record(1, "d", mutableMapOf("d1" to Value("1"), "d2" to Value("2"))))))))) ) val expected = listOf(Record(1, "a", mutableMapOf("a1" to Value("Hello"), "a2" to Value("World")), mutableMapOf( "b" to mutableListOf(Record(1, "b", mutableMapOf("b1" to Value("1"), "b2" to Value("2")))), "c" to mutableListOf(Record(1, "c", mutableMapOf("c1" to Value("2"), "c2" to Value("3")), mutableMapOf("d" to mutableListOf( Record(1, "d", mutableMapOf("d1" to Value("1"), "d2" to Value("2"))))))))) ) val filtered = RecordFilter(model).filter(records.asSequence()).toList() assertEquals( expected, filtered ) } @Test fun testTypes() { val model = FormParseConfig(rootRecordType = "a", recordTypes = mutableMapOf("a" to RecordType(label = "A", filter = """ str = "a string" and 3 < int < 5 and 1.1 < dbl < 1.3 and none = "member type not set" and undef = "member not defined" """, valueTypes = mutableListOf("str", "int", "dbl", "none", "undef"), children = mutableListOf())), valueTypes = mutableMapOf("str" to ValueType(type = ExDataType.STRING.name.lowercase()), "int" to ValueType(type = ExDataType.NUMBER.name.lowercase()), "dbl" to ValueType(type = ExDataType.NUMBER.name.lowercase()), "none" to ValueType( /* type not set */))) val records = listOf(Record(1, "a", mutableMapOf("str" to Value("a string"), "int" to Value("4"), "dbl" to Value("1.2"), "none" to Value("member type not set"), "undef" to Value("member not defined"))), Record(2, "a", mutableMapOf("str" to Value("wrong"), "int" to Value("4"), "dbl" to Value("1.2"), "none" to Value("member type not set"), "undef" to Value("member not defined"))), Record(3, "a", mutableMapOf("str" to Value("a string"), "int" to Value("6"), "dbl" to Value("1.2"), "none" to Value("member type not set"), "undef" to Value("member not defined"))), Record(4, "a", mutableMapOf("str" to Value("a string"), "int" to Value("4"), "dbl" to Value("1.7"), "none" to Value("member type not set"), "undef" to Value("member not defined"))), Record(5, "a", mutableMapOf("str" to Value("a string"), "int" to Value("4"), "dbl" to Value("1.2"), "none" to Value("wrong"), "undef" to Value("member not defined"))), Record(6, "a", mutableMapOf("str" to Value("a string"), "int" to Value("4"), "dbl" to Value("1.2"), "none" to Value("member type not set"), "undef" to Value("wrong"))) ) val filtered = RecordFilter(model).filter(records.asSequence()).toList() assertEquals( 1, filtered.size ) assertEquals( records[0], filtered[0] ) } } ================================================ FILE: src/test/java/io/mfj/textricator/record/output/CsvOutputTest.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 . */ package io.mfj.textricator.record.output import io.mfj.textricator.record.Record import io.mfj.textricator.form.config.FormParseConfigUtil import io.mfj.textricator.record.Value import java.io.ByteArrayOutputStream import org.junit.* import org.junit.Assert.* class CsvOutputTest { @Test fun test() { val model = FormParseConfigUtil.parseYaml( """ rootRecordType: person recordTypes: person: label: "Person" valueTypes: - name - dob children: - case - address case: label: "Case" valueTypes: - caseId - date children: - fee fee: label: "Fee" valueTypes: - desc - amount address: label: "Address" valueTypes: - city - state valueTypes: name: label: "Name" dob: label: "Date of Birth" caseId: label: "Case ID" date: label: "Date" desc: label: "Fee Description" amount: label: "Fee Amount" states: name: {} dob: {} caseId: {} date: {} desc: {} amount: {} city: {} """ ) val root = Record(1, "person", mutableMapOf("name" to Value("John Doe"), "dob" to Value("1/1/1980")), mutableMapOf("case" to mutableListOf( Record(1, "case", mutableMapOf("caseId" to Value("1"), "date" to Value("1/1/2018"))), Record(1, "case", mutableMapOf("caseId" to Value("2"), "date" to Value("3/3/2018")), mutableMapOf("fee" to mutableListOf(Record(1, "fee", mutableMapOf("desc" to Value("court fee"), "amount" to Value("99.95")))))), Record(1, "case", mutableMapOf("caseId" to Value("3"), "date" to Value("7/1/2018")), mutableMapOf("fee" to mutableListOf( Record(1, "fee", mutableMapOf("desc" to Value("court fee"), "amount" to Value("10"))), Record(1, "fee", mutableMapOf("desc" to Value("jail fee"), "amount" to Value("5.99"))))))), "address" to mutableListOf( Record(1, "address", mutableMapOf("city" to Value("Rochester"), "state" to Value("NY"))), Record(1, "address", mutableMapOf("city" to Value("Pittsburgh"), "state" to Value("PA")))))) val buffer = ByteArrayOutputStream() CsvRecordOutput(model,buffer).use { it.write(sequenceOf(root) ) } val expected = """ page,Name,Date of Birth,Case ID,Date,Fee Description,Fee Amount,city,state 1,John Doe,1/1/1980,1,1/1/2018,,,, 1,John Doe,1/1/1980,2,3/3/2018,court fee,99.95,, 1,John Doe,1/1/1980,3,7/1/2018,court fee,10,, 1,John Doe,1/1/1980,3,7/1/2018,jail fee,5.99,, 1,John Doe,1/1/1980,,,,,Rochester,NY 1,John Doe,1/1/1980,,,,,Pittsburgh,PA """ assertEquals( expected.trim(), String(buffer.toByteArray()).trim()) } } ================================================ FILE: src/test/java/io/mfj/textricator/record/output/XmlOutputTest.kt ================================================ /* This file is part of Textricator. Copyright 2018 Measures for Justice Institute. Copyright 2021 Stephen Byrne. 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 . */ package io.mfj.textricator.record.output import io.mfj.textricator.record.Record import io.mfj.textricator.form.config.FormParseConfigUtil import io.mfj.textricator.record.Value import java.io.ByteArrayOutputStream import com.fasterxml.jackson.dataformat.xml.XmlMapper import org.junit.* import org.junit.Assert.* class XmlOutputTest { @Test fun test() { val model = FormParseConfigUtil.parseYaml( """ rootRecordType: person recordTypes: person: label: "Person" valueTypes: - name - dob children: - case - address case: label: "Case" valueTypes: - caseId - date children: - fee fee: label: "Fee" valueTypes: - desc - amount address: label: "Address" valueTypes: - city - state valueTypes: name: label: "Name" dob: label: "Date of Birth" caseId: label: "Case ID" date: label: "Date" desc: label: "Fee Description" amount: label: "Fee Amount" states: name: {} dob: {} caseId: {} date: {} desc: {} amount: {} city: {} """ ) val root = Record(1, "person", mutableMapOf("name" to Value("John Doe"), "dob" to Value("1/1/1980")), mutableMapOf("case" to mutableListOf( Record(1, "case", mutableMapOf("caseId" to Value("1"), "date" to Value("1/1/2018"))), Record(1, "case", mutableMapOf("caseId" to Value("2"), "date" to Value("3/3/2018")), mutableMapOf("fee" to mutableListOf(Record(1, "fee", mutableMapOf("desc" to Value("court fee"), "amount" to Value("99.95")))))), Record(1, "case", mutableMapOf("caseId" to Value("3"), "date" to Value("7/1/2018")), mutableMapOf("fee" to mutableListOf( Record(1, "fee", mutableMapOf("desc" to Value("court fee"), "amount" to Value("10"))), Record(1, "fee", mutableMapOf("desc" to Value("jail fee"), "amount" to Value("5.99"))))))), "address" to mutableListOf( Record(1, "address", mutableMapOf("city" to Value("Rochester"), "state" to Value("NY"))), Record(1, "address", mutableMapOf("city" to Value("Pittsburgh"), "state" to Value("PA")))))) val buffer = ByteArrayOutputStream() XmlRecordOutput(model,buffer).use { it.write(sequenceOf(root) ) } val str = String(buffer.toByteArray()).trim() val normalized = normalize(str) val expected = normalize( """ 1 person John Doe 1/1/1980 1 case 1 1/1/2018 1 case 2 3/3/2018 1 fee court fee 99.95 1 case 3 7/1/2018 1 fee court fee 10 1 fee jail fee 5.99
1 address Rochester NY
1 address Pittsburgh PA
""" ) assertEquals( expected, normalized ) } /** * Normalize the XML so we can compare 2 documents. */ private fun normalize( input:String ):String { val mapper = XmlMapper() val tree = mapper.readTree(input) val normalized = mapper.writeValueAsString(tree) return normalized } } ================================================ FILE: src/test/resources/io/mfj/textricator/examples/probes.yml ================================================ # 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' ================================================ FILE: src/test/resources/io/mfj/textricator/examples/rap-sheet.csv ================================================ page,requester,requestDate,requestTime,attn,header,caDojId,dob,sex,race,height,weight,eyeColor,hairColor,birthState,nameId,lastName,firstName,arrestDate,arrestNameId,arrestDob,arrestDate,arrestLocation,chargeNumber,chargeId,chargeCode,chargeName,chargeDesc,appearanceNameId,appearanceDate,appearanceCourt,dispoChargeNumber,dispoChargeId,dispoChargeCode,dispoChargeName,dispoChargeDesc,dispo,dispoConvStatus,dispoSentence 1,QHY.CA0190043.99000015.ORGANA-,20060508,06:32:53,ORGANA-061020343,* * * * * * * * * * * * * * * * * * * * * ** PALM PRINT ON FILE AT DOJ FOR ADDITIONAL INFORMATION PLEASE E- MAIL PALM.PRINT@DOJ.CA.GOV III CALIFORNIA ONLY SOURCE RECORD,A99000099,19660119,M,WHITE,502,317,GRN,PNK,CA,01,"SKYWALKER,LUKE JAY","SKYWALKER,LUKE JAY",,,,,,,,,,,,,,,,,,,,, 1,QHY.CA0190043.99000015.ORGANA-,20060508,06:32:53,ORGANA-061020343,* * * * * * * * * * * * * * * * * * * * * ** PALM PRINT ON FILE AT DOJ FOR ADDITIONAL INFORMATION PLEASE E- MAIL PALM.PRINT@DOJ.CA.GOV III CALIFORNIA ONLY SOURCE RECORD,A99000099,19660119,M,WHITE,502,317,GRN,PNK,CA,02,"SKYWALKER,LUKE","SKYWALKER,LUKE",,,,,,,,,,,,,,,,,,,,, 1,QHY.CA0190043.99000015.ORGANA-,20060508,06:32:53,ORGANA-061020343,* * * * * * * * * * * * * * * * * * * * * ** PALM PRINT ON FILE AT DOJ FOR ADDITIONAL INFORMATION PLEASE E- MAIL PALM.PRINT@DOJ.CA.GOV III CALIFORNIA ONLY SOURCE RECORD,A99000099,19660119,M,WHITE,502,317,GRN,PNK,CA,,,,19840725,02,19550505,19840725,CASO LOS ANGELES,01,1111111,11357,HS-POSSESS MARIJUANA,,,,,,,,,,,, 1,QHY.CA0190043.99000015.ORGANA-,20060508,06:32:53,ORGANA-061020343,* * * * * * * * * * * * * * * * * * * * * ** PALM PRINT ON FILE AT DOJ FOR ADDITIONAL INFORMATION PLEASE E- MAIL PALM.PRINT@DOJ.CA.GOV III CALIFORNIA ONLY SOURCE RECORD,A99000099,19660119,M,WHITE,502,317,GRN,PNK,CA,,,,19840725,02,19550505,19840725,CASO LOS ANGELES,02,,496,PC-RECEIVE/ETC KNOWN STOLEN PROPERTY,COM: WARRANT NBR A-400000 BOTH CNTS,,,,,,,,,,, 1,QHY.CA0190043.99000015.ORGANA-,20060508,06:32:53,ORGANA-061020343,* * * * * * * * * * * * * * * * * * * * * ** PALM PRINT ON FILE AT DOJ FOR ADDITIONAL INFORMATION PLEASE E- MAIL PALM.PRINT@DOJ.CA.GOV III CALIFORNIA ONLY SOURCE RECORD,A99000099,19660119,M,WHITE,502,317,GRN,PNK,CA,,,,19840725,02,19550505,19840725,CASO LOS ANGELES,03,,11358,HS-CULTIVATION MARIJUANA,,,,,,,,,,,, 1,QHY.CA0190043.99000015.ORGANA-,20060508,06:32:53,ORGANA-061020343,* * * * * * * * * * * * * * * * * * * * * ** PALM PRINT ON FILE AT DOJ FOR ADDITIONAL INFORMATION PLEASE E- MAIL PALM.PRINT@DOJ.CA.GOV III CALIFORNIA ONLY SOURCE RECORD,A99000099,19660119,M,WHITE,502,317,GRN,PNK,CA,,,,19840725,02,19550505,19840725,CASO LOS ANGELES,,,,,,01,19840918,CASC LOS ANGELES,01,1234567,11357,HS-POSSESS MARIJUANA,,CONVICTED,MISDEMEANOR, 1,QHY.CA0190043.99000015.ORGANA-,20060508,06:32:53,ORGANA-061020343,* * * * * * * * * * * * * * * * * * * * * ** PALM PRINT ON FILE AT DOJ FOR ADDITIONAL INFORMATION PLEASE E- MAIL PALM.PRINT@DOJ.CA.GOV III CALIFORNIA ONLY SOURCE RECORD,A99000099,19660119,M,WHITE,502,317,GRN,PNK,CA,,,,19840725,02,19550505,19840725,CASO LOS ANGELES,,,,,,01,19840918,CASC LOS ANGELES,02,,496,PC-RECEIVE/ETC KNOWN STOLEN PROPERTY,,CONVICTED,MISDEMEANOR," 3 YEARS PROBATION, 30 DAYS JAIL, FINE, RESTN" 1,QHY.CA0190043.99000015.ORGANA-,20060508,06:32:53,ORGANA-061020343,* * * * * * * * * * * * * * * * * * * * * ** PALM PRINT ON FILE AT DOJ FOR ADDITIONAL INFORMATION PLEASE E- MAIL PALM.PRINT@DOJ.CA.GOV III CALIFORNIA ONLY SOURCE RECORD,A99000099,19660119,M,WHITE,502,317,GRN,PNK,CA,,,,19840725,02,19550505,19840725,CASO LOS ANGELES,,,,,,01,19840918,CASC LOS ANGELES,03,,11358,HS-CULTIVATION MARIJUANA,,CONVICTED,MISDEMEANOR, 1,QHY.CA0190043.99000015.ORGANA-,20060508,06:32:53,ORGANA-061020343,* * * * * * * * * * * * * * * * * * * * * ** PALM PRINT ON FILE AT DOJ FOR ADDITIONAL INFORMATION PLEASE E- MAIL PALM.PRINT@DOJ.CA.GOV III CALIFORNIA ONLY SOURCE RECORD,A99000099,19660119,M,WHITE,502,317,GRN,PNK,CA,,,,20040319,02,19550505,20040319,CASO LOS ANGELES,01,2222222,11357,HS-POSSESS MARIJUANA,,,,,,,,,,,, 1,QHY.CA0190043.99000015.ORGANA-,20060508,06:32:53,ORGANA-061020343,* * * * * * * * * * * * * * * * * * * * * ** PALM PRINT ON FILE AT DOJ FOR ADDITIONAL INFORMATION PLEASE E- MAIL PALM.PRINT@DOJ.CA.GOV III CALIFORNIA ONLY SOURCE RECORD,A99000099,19660119,M,WHITE,502,317,GRN,PNK,CA,,,,20040319,02,19550505,20040319,CASO LOS ANGELES,,,,,,01,20040413,CASC LOS ANGELES,01,3456789,11358,HS-CULTIVATION MARIJUANA,,CONVICTED,FELONY," 2 YEARS PROBATION, 5 DAYS JAIL" ================================================ FILE: src/test/resources/io/mfj/textricator/examples/rap-sheet.yml ================================================ --- extractor: "pdf.pdfbox" header: default: 0 footer: default: 770 maxRowDistance: 2 rootRecordType: rapsheet recordTypes: rapsheet: label: "Rap Sheet" valueTypes: - requester - requestDate - requestTime - attn - header - caDojId - dob - sex - race - height - weight - eyeColor - hairColor - birthState children: - name - arrest name: label: "name" valueTypes: - nameId - lastName - firstName arrest: label: "arrest" valueTypes: - arrestDate - arrestNameId - arrestDob - arrestDate - arrestLocation children: - charge - appearance charge: label: "charge" valueTypes: - chargeNumber - chargeId - chargeCode - chargeName - chargeDesc appearance: label: "appearance" valueTypes: - appearanceNameId - appearanceDate - appearanceCourt children: - dispo dispo: label: "disposition" valueTypes: - dispoChargeNumber - dispoChargeId - dispoChargeCode - dispoChargeName - dispoChargeDesc - dispo - dispoConvStatus - dispoSentence valueTypes: requestDate: replacements: - pattern: "^DATE:(.*)$" replacement: "$1" requestTime: replacements: - pattern: "^TIME:(.*)$" replacement: "$1" attn: replacements: - pattern: "^ATTN:(.*)$" replacement: "$1" caDojId: replacements: - pattern: "^CII/(.*)$" replacement: "$1" dob: replacements: - pattern: "^DOB/(.*)$" replacement: "$1" sex: replacements: - pattern: "^SEX/(.*)$" replacement: "$1" race: replacements: - pattern: "^RAC/(.*)$" replacement: "$1" height: replacements: - pattern: "^HGT/(.*)$" replacement: "$1" weight: replacements: - pattern: "^WGT/(.*)$" replacement: "$1" eyeColor: replacements: - pattern: "^EYE/(.*)$" replacement: "$1" hairColor: replacements: - pattern: "^HAIR/(.*)$" replacement: "$1" birthState: replacements: - pattern: "^POB/(.*)$" replacement: "$1" nameId: replacements: - pattern: "^NAM/(.*)$" replacement: "$1" lastName: replacements: - pattern: "^([^,]),.*$" replacement: "$1" firstName: replacements: - pattern: "^[^,],(.*)$" replacement: "$1" arrestNameId: replacements: - pattern: "^NAM:(.*)$" replacement: "$1" arrestDob: replacements: - pattern: "^DOB:(.*)$" replacement: "$1" chargeNumber: replacements: - pattern: "^CNT:(.*)$" replacement: "$1" chargeId: replacements: - pattern: "^#(.*)$" replacement: "$1" appearanceNameId: replacements: - pattern: "^NAM:(.*)$" replacement: "$1" dispoChargeNumber: replacements: - pattern: "^CNT:(.*)$" replacement: "$1" dispoChargeId: replacements: - pattern: "^#(.*)$" replacement: "$1" dispo: replacements: - pattern: "^\\*DISPO:(.*)$" replacement: "$1" dispoConvStatus: replacements: - pattern: "^CONV STATUS:(.*)$" replacement: "$1" dispoSentence: replacements: - pattern: "^SEN:(.*)$" replacement: "$1" initialState: "INIT" states: INIT: transitions: - condition: re nextState: re re: include: false transitions: - condition: sameLine nextState: requester requester: startRecord: true transitions: - condition: requestDate nextState: requestDate requestDate: transitions: - condition: requestTime nextState: requestTime requestTime: transitions: - condition: nextLine nextState: restricted restricted: include: false transitions: - condition: sameLine nextState: restricted - condition: attn nextState: attn attn: transitions: - condition: sameLine nextState: attn - condition: any nextState: header header: transitions: - condition: liveScan nextState: liveScan - condition: any nextState: header liveScan: include: false transitions: - condition: sameLine nextState: liveScan - condition: caDojId nextState: caDojId caDojId: transitions: - condition: dob nextState: dob dob: transitions: - condition: sex nextState: sex sex: transitions: - condition: race nextState: race race: transitions: - condition: height nextState: height height: transitions: - condition: weight nextState: weight weight: transitions: - condition: eyeColor nextState: eyeColor eyeColor: transitions: - condition: hairColor nextState: hairColor hairColor: transitions: - condition: birthState nextState: birthState birthState: transitions: - condition: nam01 nextState: nameId nameId: startRecord: true transitions: - condition: sameLine nextState: name name: valueTypes: [ lastName, firstName ] transitions: - condition: sameLine nextState: name - condition: nameId nextState: nameId - condition: cycleDelimiterStart nextState: cycleDelimiter cycleDelimiter: include: false transitions: - condition: cycleDelimiterContinue nextState: cycleDelimiter - condition: arrest nextState: arrest arrest: include: false transitions: - condition: eventNameId nextState: arrestNameId arrestNameId: startRecord: true transitions: - condition: arrestDob nextState: arrestDob arrestDob: transitions: - condition: eventDate nextState: arrestDate arrestDate: transitions: - condition: sameLine nextState: arrestLocation arrestLocation: transitions: - condition: sameLine nextState: arrestLocation - condition: chargeNumber nextState: chargeNumber chargeNumber: startRecord: true transitions: - condition: chargeId nextState: chargeId - condition: chargeCode nextState: chargeCode chargeId: transitions: - condition: chargeCode nextState: chargeCode chargeCode: transitions: - condition: sameLine nextState: chargeName chargeName: transitions: - condition: sameLine nextState: chargeName - condition: chargeDesc nextState: chargeDesc - condition: chargeNumber nextState: chargeNumber - condition: eventDelimiterStart nextState: eventDelimiter - condition: endStart nextState: endStart chargeDesc: transitions: - condition: chargeNumber nextState: chargeNumber - condition: chargeDesc nextState: chargeDesc - condition: endStart nextState: endStart eventDelimiter: include: false transitions: - condition: eventDelimiterContinue nextState: eventDelimiter - condition: court nextState: court court: include: false transitions: - condition: eventNameId nextState: appearanceNameId appearanceNameId: startRecord: true transitions: - condition: eventDate nextState: appearanceDate appearanceDate: transitions: - condition: sameLine nextState: appearanceCourt appearanceCourt: transitions: - condition: sameLine nextState: appearanceCourt - condition: chargeNumber nextState: dispoChargeNumber dispoChargeNumber: startRecord: true transitions: - condition: chargeId nextState: dispoChargeId - condition: chargeCode nextState: dispoChargeCode dispoChargeId: transitions: - condition: chargeCode nextState: dispoChargeCode dispoChargeCode: transitions: - condition: sameLine nextState: dispoChargeName dispoChargeName: transitions: - condition: sameLine nextState: dispoChargeName - condition: dispo nextState: dispo dispo: transitions: - condition: sameLine nextState: dispo - condition: dispoConv nextState: dispoConvStatus - condition: endStart nextState: endStart dispoConvStatus: transitions: - condition: sameLine nextState: dispoConvStatus - condition: dispoWrap nextState: dispoConvStatus - condition: dispoSentence nextState: dispoSentence - condition: chargeNumber nextState: dispoChargeNumber - condition: eventDelimiterStart nextState: eventDelimiter - condition: cycleDelimiterStart nextState: cycleDelimiter - condition: endStart nextState: endStart dispoSentence: transitions: - condition: sameLine nextState: dispoSentence - condition: dispoWrap nextState: dispoSentence - condition: chargeNumber nextState: dispoChargeNumber - condition: eventDelimiterStart nextState: eventDelimiter - condition: cycleDelimiterStart nextState: cycleDelimiter - condition: endStart nextState: endStart endStart: include: false transitions: - condition: asterisk nextState: end2 end2: include: false transitions: - condition: asterisk nextState: end3 end3: include: false transitions: - condition: endOfMessage nextState: end end: include: false transitions: - condition: any nextState: end conditions: any: '0 = 0' sameLine: '-2 <= uly_rel <= 2' nextLine: 'uly_rel > 2' re: '53 < ulx < 54 and text = "RE:"' requestDate: 'text =~ /^DATE:.*/' requestTime: 'text =~ /^TIME:.*/' attn: 'text =~ /^ATTN:.*/' liveScan: '53 <= ulx <= 54 and text = "**LIVE"' caDojId: 'text =~ /^CII\/.*/' dob: 'text =~ /^DOB\/.*/' sex: 'text =~ /^SEX\/.*/' race : 'text =~ /^RAC\/.*/' height: 'text =~ /^HGT\/.*/' weight: 'text =~ /^WGT\/.*/' eyeColor: 'text =~ /^EYE\/.*/' hairColor: 'text =~ /^HAIR\/.*/' birthState: 'text =~ /^POB\/.*/' nam01: 'text = "NAM/01"' nameId: '76 <= ulx <= 77 and text =~ /^[0-9]+$/' cycleDelimiterStart: '53 < ulx < 54 and text = "*"' cycleDelimiterContinue: '-2 <= uly_rel <= 2 and text = "*"' arrest: '53 < ulx < 54 and text = "ARR/DET/CITE:"' eventNameId: 'text =~ /^NAM:[0-9]+$/' arrestDob: 'text =~ /^DOB:[0-9]+$/' eventDate: '53 < ulx < 54 and text =~ /^[0-9]+$/' chargeNumber: '53 < ulx < 54 and text =~ /^CNT:[0-9]+$/' chargeId: '-2 <= uly_rel <= 2 and text =~ /^#[0-9]+$/' chargeCode: '65 < ulx < 66 and text =~ /^[0-9]+$/' chargeDesc: '70 < ulx' eventDelimiterStart: '53 < ulx < 54 and text = "-"' eventDelimiterContinue: '-2 <= uly_rel <= 2 and text = "-"' court: '53 < ulx < 54 and text = "COURT:"' dispo: '53 < ulx < 54 and text =~ /^\\*DISPO:.*$/' dispoConv: '70 < ulx < 71 and text = "CONV"' dispoSentence: '70 < ulx < 71 and text = "SEN:"' dispoWrap: '100 < ulx' endStart: '82 < ulx < 83 and text = "*"' asterisk: '-2 <= uly_rel <= 2 and text = "*"' endOfMessage: '-2 <= uly_rel <= 2 and text = "END"' ================================================ FILE: src/test/resources/io/mfj/textricator/examples/school-employee-list.csv ================================================ page,Employee ID,Name,Hire Date,Occupation,Important Info?,Boolean 1,Boolean 2,Boolean 3,Salary,Attending Child,Grade 1,ID-0001,Mam Bargera,01/21/20XX,Librarian,,No,No,Yes,"29,990",Maria,Fifth 1,ID-0001,Mam Bargera,01/21/20XX,Librarian,,No,No,Yes,"29,990",Mario,Fourth 1,ID-0002,Hony Tawk,03/13/20XX,Teacher,NECESSARY INFO,No,Yes,No,"38,749",, 1,ID-0003,Gune Rilfberg,11/15/20XX,Superintendent,,Yes,Yes,No,"94,839",Johnny,Second 1,ID-0004,Spric Earrow,04/21/20XX,Janitor,NECESSARY INFO,No,Yes,Yes,"12,239",, 1,ID-0005,Modney Rullen,08/05/20XX,Secretary,,Yes,No,No,"24,391",Johnny,Second 1,ID-0005,Modney Rullen,08/05/20XX,Secretary,,Yes,No,No,"24,391",Lucina Ellegancia,Second 1,ID-0005,Modney Rullen,08/05/20XX,Secretary,,Yes,No,No,"24,391",Horace,Third 1,ID-0006,Stellisa Eamer,06/30/20XX,Principal,,Yes,No,Yes,"94,139",, 1,ID-0007,Kric Eoston,12/21/20XX,Assistant,NECESSARY INFO,No,No,No,"11,192",Justin, 2,ID-0008,Dob Rydek,02/11/20XX,Janitor,,Yes,Yes,Yes,"20,002",, 2,ID-0009,Shan Ryeckler,03/19/20XX,Teacher,NECESSARY INFO,No,Yes,Yes,"42,910",, ================================================ FILE: src/test/resources/io/mfj/textricator/examples/school-employee-list.yml ================================================ --- # Use the pdfbox parser, since it's the same one we used to originally etract the text to build this planning document. 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 less than this many points from the bottom, 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"