[
  {
    "path": ".gitignore",
    "content": "target/\n.idea/\n*.iml\n"
  },
  {
    "path": "CODEOWNERS",
    "content": "# This is the CODEOWNERS file for the textricator repo.\n\n# These owners will be the default owners for everything in the repo, unless a\n# later match takes precedence.\n*   @lschumann-mfj @wstumbo-mfj\n\n# Make sure that DevOps is aware of anything GitHub related\n/.github/    @lschumann-mfj @wstumbo-mfj @SB-MFJ @meghanbissonnette-mfj"
  },
  {
    "path": "COPYING",
    "content": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nour General Public Licenses are intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  Developers that use our General Public Licenses protect your rights\nwith two steps: (1) assert copyright on the software, and (2) offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\n  A secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate.  Many developers of free software are heartened and\nencouraged by the resulting cooperation.  However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\n  The GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community.  It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server.  Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\n  An older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals.  This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU Affero General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Remote Network Interaction; Use with the GNU General Public License.\n\n  Notwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software.  This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time.  Such new versions\nwill be similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU Affero General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU Affero General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU Affero General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source.  For example, if your program is a web application, its\ninterface could display a \"Source\" link that leads users to an archive\nof the code.  There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU AGPL, see\n<https://www.gnu.org/licenses/>.\n"
  },
  {
    "path": "NOTICE",
    "content": "Textricator\nCopyright 2018 Measures for Justice Institute.\n"
  },
  {
    "path": "README.md",
    "content": "# ![Textricator](./textricator-logo-text-paths.png)\n\n_Textricator_ is a tool to extract text from documents and generate structured data.\n\nIf you have a bunch of PDFs with the same format (or one big, consistently formatted PDF)\nand you want to extract the data to CSV, XML, or JSON, _Textricator_ can help!\nIt can even work on OCR'ed documents!\n\n_Textricator_ is released under the\n[GNU Affero General Public License Version 3](https://www.gnu.org/licenses/agpl-3.0.en.html).\n\n_Textricator_ is deployed to [Maven Central](https://repo1.maven.org/maven2/io/mfj/textricator/) with GAV `io.mfj:textricator`.\n\nThis application is actively used and developed by [Measures for Justice](https://measuresforjustice.org).\nWe welcome feedback, bug reports, and contributions. Create an issue, send a pull request,\nor email us at <textricator@mfj.io>. If you use _Textricator_, please let us know.\nSend us your mailing address and we will mail you a sticker.\n\n`io.mfj.textricator.Textricator` is the main entry point for library usage.\n\n`io.mfj.textricator.cli.TextricatorCli` is the command-line interface.\n\nThe CLI has three subcommands, to use the three main features of Textricator:\n  * text - Extract text from the PDF and generate JSON.\n  * table - Parse the text that is in columns and rows. See [Table](#table) section.\n  * form - Parse the text with a configured finite state machine. See [Form](#form) section.\n\n## Quick Start\n\n- Install Java (version 11+)\n  * Windows & Macos: Download from [https://java.com](https://java.com) and install.\n  * Linux: Use your package manager.\n- 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).\n- Extract it.\n- Run a shell\n  * Windows: run _Windows Powershell_ (it should be in the start menu)\n    * The following examples start with `./textricator`. On Windows, use `.\\textricator.bat`.\n  * MacOS: Run _Terminal_ (type \"terminal\" in Spotlight)\n- Show help\n    - `./textricator --help`\n- Download the example files to the textricator directory:\n  * https://github.com/measuresforjustice/textricator/blob/main/src/test/resources/io/mfj/textricator/examples/school-employee-list.pdf\n  * https://github.com/measuresforjustice/textricator/blob/main/src/test/resources/io/mfj/textricator/examples/school-employee-list.yml\n- Extract raw text from a PDF to standard out\n    - `./textricator text --input-format=pdf.pdfbox school-employee-list.pdf`\n- Parse a PDF to CSV\n    - `./textricator form --config=school-employee-list.yml school-employee-list.pdf school-employee-list.csv`\n      * This uses the configuration file `school-employee-list.yml` to parse `school-employee-list.pdf`.\n        To parse your own PDF form, you will need to write your own configuration file.\n        See the [Form](#form) section for details.\n        If your PDF has a tabular layout, see the [Table](#table) section.\n\n## Logging\n\nUse the `--debug` flag to log everything.\nLogging is written to standard error.\n\nTextricator uses [SLF4J](https://slf4j.org) for logging, with the [Logback](https://logback.qos.ch) implementation.\nIf you are using Textricator as a library, you may want to exclude `ch.qos.logback:logback-classic`.\nTextricator does *not* include a `/logback.xml`, so it will not conflict with other logging configurations,\nso long as `TextricatorCli.main()` is not invoked.\n\n## Extracting text\n\nTo extract the text from a PDF, run\n`textrictor text --input-format=pdf.itext5 input.pdf input-text.csv`\nfor any `input.pdf` and then open `input-text.csv` in your favorite spreadsheet program.\nIt will show you every bit of text that Textricator sees with its position, size,\nand font information. This information is very useful for building configuration to parse\ntables or forms using Textricator (see the following two sections).\n\nTry `--input-format=pdf.itext7` and `--input-format=pdf.pdfbox` to see how Textricator\nextracts the texts using the different parser engines. Some work better for some documents\nthan others.\n\n## Table\n\nIn table mode, the data is grouped into columns based on the x-coordinate of the text.\n\n### Example\n\nThis is an example for `src/test/resources/io/mfj/textricator/examples/probes.pdf`.\n\n```yaml\n# All measurements are in points. 1 point = 1/72 of an inch.\n# x-coordinates are from the left edge of the page.\n# y-coordinates are from the top edge of the page.\n\n# Use the built-in pdfbox extractor\nextractor: \"pdf.pdfbox\"\n\n# Ignore everything above 88pt from the top\ntop: 88\n\n# Ignore everything below 170pt from the top\nbottom: 170\n\n# If multiple text segments are withing 2pt vertically, consider them in the same row.\nmaxRowDistance: 2\n\n# Define the columns, based on the x-coordinate where the column starts:\ncols:\n  \"name\": 0\n  \"launched\": 132\n  \"speed\": 235\n  \"cospar\": 249\n  \"power\": 355\n  \"mass\": 415\n\ntypes:\n  \"name\":\n    label: \"Name\"\n\n  \"launched\":\n    label: \"Launch Date\"\n\n  \"speed\":\n    label: \"Speed (km/s)\"\n    type: \"number\"\n\n  \"cospar\":\n    label: \"COSPAR ID\"\n\n  \"power\":\n    label: \"Power (watts)\"\n    type: \"number\"\n\n  \"mass\":\n    label: \"Mass (pounds)\"\n    # Add .0 to the end of mass\n    replacements:\n      -\n        pattern: \"^(.*)$\"\n        replacement: \"$1.0\"\n\n# Omit if Power is less than 200\nfilter: 'power >= 200'\n```\n\n## Form\n\nIn form mode, the data is parsed by Textricator using a\n[finite-state machine](https://en.wikipedia.org/wiki/Finite-state_machine) (FSM),\nand the FSM and additional parsing and formatting parameters are configured with\n[YAML](https://en.wikipedia.org/wiki/YAML), indicated by command line option `--config`.\n\n### Conditions\n\nState transitions are selected by evaluating conditions. Conditions are expressions parsed by\n[Expr](https://github.com/measuresforjustice/expr).\n\n#### Available variables:\n\n  * `ulx` - x coordinate of the upper-left corner of the text box\n  * `uly` - y coordinate of the upper-left corner of the text box\n  * `lrx` - x coordinate of the lower-right corner of the text box\n  * `lry` - y coordinate of the lower-right corner of the text box\n  * `text` - the text\n  * `page` - page number\n  * `page_prev` - page number of the previous text\n  * `fontSize` - font size\n  * `font` - font name\n  * `color` - text color\n  * `bgcolor` - background color\n  * `width` - width of the text box\n  * `height` - height of the text box\n  * `ulx_rel` - difference in `ulx` between the previous and current texts\n  * `uly_rel` - difference in `uly` between the previous and current texts\n  * `lrx_rel` - difference in `lrx` between the previous and current texts\n  * `lry_rel` - difference in `lry` between the previous and current texts\n  * [added Variables](#variables)\n\n### Example\n\nThis is an example for `src/test/resources/io/mfj/textricator/examples/school-employee-list.pdf`.\n\n```yaml\n# Use the built-in pdfbox parser\nextractor: \"pdf.pdfbox\"\n\n# All measurements are in points. 1 point = 1/72 of an inch.\n# x-coordinates are from the left edge of the page.\n# y-coordinates are from the top edge of the page.\nheader:\n    # ignore anything less than this many points from the top, default and per-page\n  default: 130\nfooter:\n    # ignore anything more than this many points from the top, default and per-page\n  default: 700\n\n# Text segments are generally parsed in order, top to bottom, left to right.\n# If two text segments have y-coordinates within this many points, consider them on the same line,\n# and process the one further left first, even if it is 0.4pt lower on the page.\nmaxRowDistance: 2\n\n# Define the output data record.\n# Since the main record type we're collecting information on is our employees,\n# we'll have that be the root type for our harvested information.\nrootRecordType: employee\nrecordTypes:\n  employee:\n    label: \"employee\" # Labels are used when nested recordTypes come into play, like this document.\n    valueTypes:\n      # Not sure what to name a valueType? Just make something up!\n      - employee\n      - name\n      - hiredate\n      - occupation\n      - showinfo\n      - bool1\n      - bool2\n      - bool3\n      - salary\n    children:\n      # In this example, there are multiple children nested under an employee,\n      # so we'll treat it as a 'child' to the 'employee' recordType.\n      - child\n  child:\n    label: \"child\"\n    valueTypes:\n      - child\n      - grade\n\nvalueTypes:\n  employee:\n    # In the CSV, use \"Employee ID\" as the column header instead of \"employee\".\n    label: \"Employee ID\"\n  name:\n    label: \"Name\"\n  hiredate:\n    label: \"Hire Date\"\n  occupation:\n    label: \"Occupation\"\n  salary:\n    label: \"Salary\"\n  showinfo:\n    label: \"Important Info?\"\n  bool1:\n    label: \"Boolean 1\"\n  bool2:\n    label: \"Boolean 2\"\n  bool3:\n    label: \"Boolean 3\"\n  child:\n    label: \"Attending Child\"\n  grade:\n    label: \"Grade\"\n\n# Now we define the finite-state machine\n# Let's name the state that our machine starts off with:\ninitialState: \"INIT\"\n\n# When each text segment is encountered, each transition for the current state is checked.\nstates:\n  INIT:\n    transitions:\n      # The first bit of text we reach is 'ID-0001', so we'll try the only transition that should work here.\n      -\n        # If this condition matches (which it should)\n        condition: employee # Curious about the condition? Sxroll further down to the conditions section of this YAML.\n        # Then we'll switch to the 'employee' state!\n        nextState: employee\n\n  employee: # ID number with the format 'ID-####'\n    startRecord: true # When we enter this stage, we'll create a new \"case\" record.\n    transitions:\n      - # Now we move on to the name label. Once again, by varifying the condition and moving on after that.\n        condition: namelabel\n        nextState: namelabel\n\n  namelabel:\n    include: false # The label isn't important information in and of itself, so we can just not include it in the data.\n    transitions:\n      -\n        condition: name\n        nextState: name\n\n  name:\n    transitions:\n      -\n        # Sometimes a name will be in two segments, and we'll hit another 'name' text segment before anything else.\n        # In that case, a state can transition to itself, compounding the information picked up in it.\n        condition: name\n        nextState: name\n      -\n        # Does the first condition not match the text? We move onto the next one.\n        condition: hiredateLabel\n        nextState: hiredateLabel\n\n  hiredateLabel:\n    include: false\n    transitions:\n      -\n        condition: hiredateLabel\n        nextState: hiredateLabel\n      -\n        condition: hiredate\n        nextState: hiredate\n\n  hiredate:\n    transitions:\n      -\n        condition: occupationLabel\n        nextState: occupationLabel\n\n  occupationLabel:\n    include: false\n    transitions:\n      -\n        condition: occupation\n        nextState: occupation\n\n  occupation:\n    transitions:\n      -\n        condition: occupation\n        nextState: occupation\n      -\n        # This state and the next are an example of how you can choose, using conditions, what to include or not.\n        # They share the same area of a document, but have qualities to them that can be distinguishable.\n        # Does it meet 'showinfo' conditions? Then we go to the 'showinfo' state that includes it.\n        condition: showinfo\n        nextState: showinfo\n      -\n        # Doesn't meet 'showinfo'? Then check for 'notinfo' and exclude it.\n        condition: notinfo\n        nextState: notinfo\n  showinfo:\n    transitions:\n      -\n        condition: showinfo\n        nextState: showinfo\n      -\n        condition: bool1\n        nextState: bool1\n  notinfo:\n    include: false\n    transitions:\n      -\n        condition: notinfo\n        nextState: notinfo\n      -\n        condition: bool1\n        nextState: bool1\n\n  bool1:\n    transitions:\n      -\n        condition: bool2\n        nextState: bool2\n  bool2:\n    transitions:\n      -\n        condition: bool3\n        nextState: bool3\n  bool3:\n    transitions:\n      -\n        condition: salaryLabel\n        nextState: salaryLabel\n\n  salaryLabel:\n    include: false\n    transitions:\n      -\n        condition: salary\n        nextState: salary\n\n  salary:\n    transitions:\n      -\n        condition: childrenLabel\n        nextState: childrenLabel\n      -\n        condition: employee\n        nextState: employee\n      -\n        condition: end\n        nextState: end\n\n  childrenLabel:\n    include: false\n    transitions:\n      -\n        condition: childrenLabel\n        nextState: childrenLabel\n      -\n        condition: childLabel\n        nextState: childLabel\n\n  childLabel:\n    include: false\n    transitions:\n      -\n        condition: child\n        nextState: child\n\n  child:\n    # Here we reach a datatype nested within another datatype. We can start records using this child datatype.\n    # In the process, we'll be making multiple rows for the parent datatype, each one holding onto it's own child.\n    startRecord: true\n    transitions:\n      -\n        condition: child\n        nextState: child\n      -\n        condition: gradeLabel\n        nextState: gradeLabel\n      -\n        condition: childLabel\n        nextState: childLabel\n\n  gradeLabel:\n    include: false\n    transitions:\n      -\n        # Normally, there would always been an instance of a grade appearing right after the label.\n        # But in this document, we have one instance of that not happening under ID-0007's child.\n        condition: grade\n        nextState: grade\n      -\n        # So we just account for that possibility by adding a transition out of the label.\n        condition: employee\n        nextState: employee\n\n  grade:\n    transitions:\n      -\n        condition: employee\n        nextState: employee\n      -\n        condition: childLabel\n        nextState: childLabel\n      -\n        # Reach the end of the usable info in a document, but there's still text left to go?\n        # An easy fix is to just create a looping, not-included state to finish the document off.\n        condition: end\n        nextState: end\n\n  end:\n    # We reached a point in the document where all the useful information is gone, but we still have text to go.\n    include: false\n    transitions:\n      -\n        # By using an always-true condition such as 'any', we can loop this state until the document has been completely gone through.\n        condition: any\n        nextState: end\n\n# Here we define the conditions:\nconditions:\n\n  # An example of comparing text with regex.\n  # In this case, we're making sure that the text contains the characters 'ID-' followed by any amount of numbers.\n  employee: 'text =~ /ID-(\\\\d)*/'\n\n  # You can match based on the x- and y- coordinates of the upper left and lower right corners of the rectangle\n  # containing the text. ulx = Upper-Left X-coordinate. lry = Lower-Right Y-coordinate. Also uly and lrx.\n  # You can define the lower and upper limit for each, inclusive.\n  namelabel: '70 < ulx < 80 and font = \"BCDFEE+Calibri-Bold\"'\n\n  # You can also match based on the type of font used, including if it was bolded or italicized.\n  name: '112 < ulx < 200 and font = \"BCDEEE+Calibri\"'\n\n  hiredateLabel: '230 < ulx < 270 and font = \"BCDFEE+Calibri-Bold\"'\n\n  hiredate: '280 < ulx < 290 and font = \"BCDEEE+Calibri\"'\n\n  occupationLabel: '391 < ulx < 393 and font = \"BCDFEE+Calibri-Bold\"'\n\n  occupation: '394 < ulx < 700 and font = \"BCDEEE+Calibri\"'\n\n  showinfo: 'font = \"BCDJEE+Georgia\"'\n\n  notinfo:  'font = \"BCDEEE+Calibri\"'\n\n  bool1:  'font = \"BCDIEE+Cambria\"'\n\n  bool2:  'font = \"BCDIEE+Cambria\"'\n\n  bool3:  'font = \"BCDIEE+Cambria\"'\n\n  salaryLabel: '391 < ulx < 393 and font = \"BCDFEE+Calibri-Bold\"'\n\n  salary: '394 < ulx < 700 and font = \"BCDEEE+Calibri\"'\n\n  childrenLabel: '70 < ulx < 140 and font = \"BCDFEE+Calibri-Bold\" and text =~ /(Attending)|(Children:)/'\n\n  childLabel: '230 < ulx < 240 and font = \"BCDFEE+Calibri-Bold\"'\n\n  child: '230 < ulx < 380 and font = \"BCDEEE+Calibri\"'\n\n  gradeLabel: '391 < ulx < 393 and font = \"BCDFEE+Calibri-Bold\"'\n\n  grade: '394 < ulx < 700 and font = \"BCDEEE+Calibri\"'\n\n  # You can also match based on the size of the font and on specific text.\n  end: 'fontSize = 16.0 and text = \"TOTAL:\"'\n\n  # Need a condition that is always true? \"1=1\" does that for you.\n  any: \"1 = 1\"\n```\n\n### Advanced functionality\n\n#### Regex matching\n\nYou can use regular expression matching instead of exact string matching in conditions:\n\n```yaml\nconditions:\n  caseTypeLabel: 'text =~ /Case Type:?/' # maybe sometimes they forgot the \":\"\n```\n\n#### Font matching\n\nYou can match font and font size:\n\n```yaml\nconditions:\n  helvetica8: 'font =~ /.*Helvetica.*/ and fontSize = 8'\n```\n\n#### Page number matching\n\nYou can match the page number\n\n```yaml\nconditions:\n  # Match the textbox that starts at 100pt,120pt on page 9.\n  specificTextbox: 'page = 9 and ulx = 100 and uly = 120'\n```\n\n#### Requiring intermediate state\n\nThere may be cases where you want to transition from state \"B\" to state \"A\" and start a new record,\nbut ONLY if you were in state \"C\" since last starting a new record:\n\n```yaml\nstates:\n  A:\n    startRecord: true\n    startRecordRequiredState: C\n    # ...\n```\n\n#### Combining states\n\nYou may have 2 different states that you want to combine into one column in the output:\n\n```yaml\nrecordTypes:\n  record:\n    label: \"Record\"\n    valueTypes:\n      - A\n      # no A2\n      - B\n\nstates:\n  A:\n    # ...\n  A2:\n    valueTypes: [ A ] # combine this with state \"A\".\n    # ...\n```\n\n#### Joining text segments in a state\n\nWhen there are multiple text segments in the same state, by default they are concatenated with a space in between.\nAny string, including an empty string, can be used as the separator:\n\n```yaml\nvalueTypes:\n  recordId:\n    # concatenate without spaces between\n    label: \"Record ID\"\n    separator: \"\"\n  description:\n    # put newlines between text segments\n    label: \"Description\"\n    separator: \"\n\"\n```\n\n#### Exclude types from output\n\nA value type (`dataRecordMember`) can be excluded from the output.\nThis is useful if the type is repeated on the PDF and needed as a data type to set new records,\nbut should not be in the output.\n\n```yaml\nvalueTypes:\n  repeatedId:\n    include: false\n```\n#### Relative offsets\n\nConditions can evaluate coordinates relative to the coordinates of the previous text.\nThis is useful for matching only something on the next line:\n\n```yaml\nmaxRowDistance: 2\nconditions:\n  # These should generally be the same (absolute value) as maxRowDistance\n  descriptionSameLine: '-2 <= uly_rel <= 2'\n  descriptionOneLineDown: '12 <= uly_rel <= 16' # for 12pt, single-spaced font.\n```\n\n#### Control which page number in output\n\nIf a complex data record spans multiple pages, which page number is used for the output can be controlled.\nEach type (`dataRecordType`) has a page priority (default: 0).\nThe page number for the record comes from the type with the highest priority.\n\n```yaml\nrecordTypes:\n  agency:\n    label: \"Agency\"\n    valueTypes:\n      - agencyName\n    children:\n      - case\n    # Agency may span hundreds of pages\n    # default page priority of 0\n  case:\n    label: \"Case\"\n    valueTypes:\n      - caseNumber\n      - name\n    children:\n      - charge\n    # Case record may span multiple pages.\n    # Higher priority than agency but lower than charges,\n    so case is used if there are no charges.\n    pagePriority: 1\n  charge:\n    label: \"Charge\"\n    valueTypes:\n      - chargeNumber\n    # Highest priority. Use charge's page number.\n    pagePriority: 2\n```\n\n#### Exclude \n\nText segments can be excluded before processing by the finite-state machine\nby adding condition name to the `excludeConditions` list.\nIf any of the conditions match, the text segment is excluded.\n\nFor example, to exclude all text segments that consist solely of underscores:\n\n```yaml\nexcludeConditions:\n  - underline\n  \nconditions:\n  underline: 'text =~ /_+/'\n```\n\n#### Starting new records for each value\n\nTODO\n\n#### Regex replacement of values\n\nSometimes the value contains a label, or other text you want to remove.\nIn a `dataRecordMember`, add a `replacement`, which has a `pattern`,\nwhich is a regular expression with capturing groups,\nand `replacement`, which is a replacement string with group references.\nSee `java.util.regex.Pattern` and `java.util.regex.Matcher` for details.\n\n```yaml\n# Replace \"Bond Agency: Fred's Bonds\" with \"Fred's Bonds\"\nvalueTypes:\n  bondagency:\n    label: \"Bond Agency\"\n    replacements:\n      -\n        pattern: \"Bond Agency:\\ *(.*)\"\n        replacement: \"$1\"\n```\n\n#### Variables<a name=\"variables\"></a>\n\nOn entering a state, a variable can be set.\n\nIn `State`, add a `setVariable`, which has `name` of the variable and the `value` to set.\n\nIf the `value` starts with `{` and ends with `}`, the content can be any built-in variable or previously\nset `variable` - the same things usable as variables for conditions.\n\nFor example: a condition checks that has the same background color as the last caseNo:\n\n```yaml\nstates:\n  caseNo:\n    setVariables:\n      -\n        name: \"lastCaseBgColor\"\n        value: \"{bgcolor}\"\n\nconditions:\n  sameBgColor: >\n    145 <= ulx\n    and fontSize = 8\n    and bgcolor = lastCaseBgColor\n```\n\n#### Splitting one PDF field into multiple CSV columns\n\nOne field in the PDF can be broken up into multiple columns in the CSV file, based on\ndifferent regular expressions and replacements:\n\n```yaml\n# Take a field that contains lastName,firstName and split it into 2 fields - lastName and firstName\nrecordTypes:\n  inmateName:\n    label: \"inmateName\"\n    valueTypes:\n      - lastName\n      - firstName\n\nvalueTypes:\n  lastName:\n    label: \"Last Name\"\n    replacements:\n      -\n        # lastName column will contain what's before comma\n        pattern: \"(.*),.*\"\n        replacement: \"$1\"\n  firstName:\n    label: \"First Name\"\n    replacements:\n      -\n        # firstName column will contain what's after comma\n        pattern: \".*,(.*)\"\n        replacement: \"$1\"\n\nstates:\n  name:\n    # when FSM hits state \"name\", split data into lastName and firstName\n    valueTypes:\n      - lastName\n      - firstName\n```\n\n#### Hyperlinks\n\nIf the text is a hyperlink, the URL can be used intead of the text by\nsetting `valueTypes.attribute` to `url`.\n\nThis is supported only by the `itext5` and `itext7` parsers.\n\n```yaml\nrecordTypes:\n  company:\n    label: \"Company\"\n    valueTypes:\n      - name\n      - website\n\nvalueTypes:\n  name:\n    label: \"Company Name\"\n  website:\n    label: \"Website\"\n    attribute: url # use the link URL instead of the text.\n\nstates:\n  name:\n    # Put the value in both \"name\" and \"website\" to get both the\n    # text and the url into the output.\n    valueTypes:\n      - name\n      - website\n```\n\n#### Filtering records\n\nRecords can be filtered before output by setting a filter on the `dataRecordType`. Root records\nwith a non-matching filter will not be output. Child records with a non-matching filter will\nbe removed from their parent - the root will still be output.\n\nFilters are expressions parsed by\n[Expr](https://github.com/measuresforjustice/expr)\n\nThe variables are the fields in the record. The default type for variables is `STRING`.\nThe type can be set by setting `type` in the `dataRecordMember` to `string` or `number`.\n\n```yaml\nrecordTypes:\n  case:\n    label: \"Case\"\n    # Only include cases in 2009-2013\n    filter: \"2009 <= year <= 2013\"\n    valueTypes:\n      - year\n      - name\n    children:\n      - charge\n  charge:\n    label: \"Charge\"\n    # omit charges of type \"dummy\"\n    filter: >\n      not( type = \"dummy\" )\n    valueTypes:\n      - code\n      - type\n\nvalueTypes:\n  year:\n    type: number\n```\n\nFiltering happens after replacements and before member include checking.\nThis allows splitting a field (e.g.: extracting a year from a date)\nto use in the filter, and not including the split field in the output.\n\n#### Processing multiple files together\n\nMultiple files using the same form config can be parsed and written to a single output\nwith the `forms` CLI subcommand or with `io.mfj.textricator.Textricator.parseForms`.\nThe output will include the source file name for each record.\n\n## Extractors\n\nExtractors extract text (instances of `io.mfj.textricator.text.Text`) from a source.\nThere are four included extractors:\n\n  * _pdf.pdfbox_ - Extract text from PDF files using [Apache PDFBox](https://pdfbox.apache.org).\n  * _pdf.itext5_ - Extract text from PDF files using [iText 5](https://itextpdf.com/itext-5-core).\n  * _pdf.itext7_ - Extract text from PDF files using [iText 7](https://itextpdf.com/itext-7-core).\n  * _json_ - Parse text from the JSON format generated by the \"text\" subcommand of the CLI and by `io.mfj.textricator.Textricator.parseText()`.\n  * _csv_ - Parse text from the CSV format generatetd by the \"text\" subcommand of the CLI and by `io.mfj.textricator.Textricator.parseText()`\n\nOther extractors modules may be loaded, which may support different source types,\ncapture different information or split the text up differently.\nAn extractor module is loaded by adding a properties file\n`io/mfj/textricator/extractor/textExtractor.properties` to the classpath with a single property -\nthe key is the extractor name and the value is the fully-qualified class name of an implementation of\n`io.mfj.textricator.extractor.TextExtractorFactory`.\nTypically an extractor module will be distributed as a JAR that includes `textExtractor.properties`.\n\nIndicate which extractor to use by setting `extractor` in the yaml configuration,\nor overriding it by passing the extractor name to the `inputFormat`/`--input-format` option.\nIf the extractor is not specified and the input is PDF, `pdf.itext5` is used.\n\n## Versioning\n\n_Textricator_'s version is of the format `major.minor.build`.\n\nThe major number is incremented for breaking changes or major new features.\n\nThe minor number is incremented for minor new features.\n\nThe build number is generated by [Measures for Justice](https://measuresforjustice.org)'s private CI tool.\nIt is incremented for each build, regardless of the major and minor numbers\n(it does not reset to zero when minor or major numbers are increased).\n\n## Acknowledgements\n\nMuch credit is due to some people who do not show up in the commit history:\n\n* Joe Hale, for the original idea and prototype\n* John Castaneda and Abbie Miehle who, as the first end users, provided excellent\nbug reports, improvements, documentation, and examples.\n\n![mascot](./textricator-mascot.png)\n"
  },
  {
    "path": "pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\"\n         xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n         xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n\n  <groupId>io.mfj</groupId>\n  <artifactId>textricator</artifactId>\n  <version>10.2-SNAPSHOT</version>\n\n  <name>${project.groupId}:${project.artifactId}</name>\n  <description>A tool to extract text from documents and generate structured data</description>\n\n  <url>https://textricator.mfj.io/</url>\n\n  <developers>\n    <developer>\n      <name>Measures for Justice</name>\n      <email>opensource@measuresforjustice.org</email>\n      <organization>Measures for Justice</organization>\n      <organizationUrl>https://measuresforjustice.org/</organizationUrl>\n    </developer>\n  </developers>\n\n  <licenses>\n    <license>\n      <name>GNU Affero General Public License, Version 3</name>\n      <url>https://www.gnu.org/licenses/agpl-3.0.txt</url>\n    </license>\n  </licenses>\n\n  <properties>\n    <maven.compiler.source>11</maven.compiler.source>\n    <maven.compiler.target>11</maven.compiler.target>\n    <kotlin.compiler.jvmTarget>11</kotlin.compiler.jvmTarget>\n    <kotlin.version>1.9.25</kotlin.version>\n    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n    <copyright.year>2025</copyright.year>\n    <source.location>https://github.com/measuresforjustice/textricator</source.location>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.jetbrains.kotlinx</groupId>\n      <artifactId>kotlinx-coroutines-core</artifactId>\n      <version>1.7.3</version>\n    </dependency>\n\n    <dependency>\n      <groupId>org.jetbrains.kotlin</groupId>\n      <artifactId>kotlin-stdlib-jdk8</artifactId>\n      <version>${kotlin.version}</version>\n      <!-- Apache 2.0 -->\n    </dependency>\n    <dependency>\n      <groupId>org.jetbrains.kotlin</groupId>\n      <artifactId>kotlin-test-junit</artifactId>\n      <version>${kotlin.version}</version>\n      <!-- Apache 2.0 -->\n      <scope>test</scope>\n    </dependency>\n    <!-- kotlin-reflect is a dependency of com.fasterxml.jackson.module:jackson-module-kotlin.\n    Include it here and exclude it below to make sure it is the same version of Kotlin. -->\n    <dependency>\n      <groupId>org.jetbrains.kotlin</groupId>\n      <artifactId>kotlin-reflect</artifactId>\n      <version>${kotlin.version}</version>\n      <!-- Apache 2.0 -->\n    </dependency>\n\n    <dependency>\n      <groupId>io.mfj</groupId>\n      <artifactId>expr</artifactId>\n      <version>6.2.39</version>\n      <!-- Apache 2.0 -->\n    </dependency>\n\n    <!-- PDFBox -->\n    <dependency>\n      <groupId>org.apache.pdfbox</groupId>\n      <artifactId>pdfbox</artifactId>\n      <version>2.0.30</version>\n      <!-- Apache 2.0 -->\n    </dependency>\n    <dependency>\n      <groupId>org.apache.pdfbox</groupId>\n      <artifactId>pdfbox-tools</artifactId>\n      <version>2.0.30</version>\n      <!-- Apache 2.0 -->\n    </dependency>\n\n    <!-- iText 5 -->\n    <dependency>\n      <groupId>com.itextpdf</groupId>\n      <artifactId>itextpdf</artifactId>\n      <version>5.5.13.3</version>\n      <!-- AGPL -->\n    </dependency>\n    <dependency>\n      <groupId>org.bouncycastle</groupId>\n      <artifactId>bcprov-jdk18on</artifactId>\n      <version>1.78</version>\n      <!-- MIT -->\n    </dependency>\n\n    <!-- iText 7 -->\n    <dependency>\n      <groupId>com.itextpdf</groupId>\n      <artifactId>kernel</artifactId>\n      <version>8.0.2</version>\n      <!-- AGPL -->\n    </dependency>\n    <dependency>\n      <groupId>com.itextpdf</groupId>\n      <artifactId>layout</artifactId>\n      <version>8.0.2</version>\n      <!-- AGPL -->\n    </dependency>\n\n    <dependency>\n      <groupId>com.fasterxml.jackson.core</groupId>\n      <artifactId>jackson-databind</artifactId>\n      <version>2.15.3</version>\n      <!-- Apache 2.0 -->\n    </dependency>\n    <dependency>\n      <groupId>com.fasterxml.jackson.dataformat</groupId>\n      <artifactId>jackson-dataformat-xml</artifactId>\n      <version>2.15.3</version>\n      <!-- Apache 2.0 -->\n    </dependency>\n    <dependency>\n      <groupId>com.fasterxml.jackson.dataformat</groupId>\n      <artifactId>jackson-dataformat-yaml</artifactId>\n      <version>2.15.3</version>\n      <!-- Apache 2.0 -->\n    </dependency>\n    <dependency>\n      <groupId>com.fasterxml.jackson.module</groupId>\n      <artifactId>jackson-module-kotlin</artifactId>\n      <version>2.15.3</version>\n      <!-- Apache 2.0 -->\n      <exclusions>\n        <exclusion>\n          <groupId>org.jetbrains.kotlin</groupId>\n          <artifactId>kotlin-stdlib</artifactId>\n        </exclusion>\n        <exclusion>\n          <groupId>org.jetbrains.kotlin</groupId>\n          <artifactId>kotlin-reflect</artifactId>\n        </exclusion>\n      </exclusions>\n    </dependency>\n\n    <dependency>\n      <groupId>org.slf4j</groupId>\n      <artifactId>slf4j-api</artifactId>\n      <version>2.0.9</version>\n      <!-- MIT -->\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <version>1.4.12</version>\n    </dependency>\n\n    <dependency>\n      <groupId>org.apache.commons</groupId>\n      <artifactId>commons-csv</artifactId>\n      <version>1.10.0</version>\n      <!-- Apache 2.0 -->\n    </dependency>\n\n    <dependency>\n      <groupId>com.offbytwo</groupId>\n      <artifactId>docopt</artifactId>\n      <version>0.6.0.20150202</version>\n      <!-- MIT -->\n    </dependency>\n\n  </dependencies>\n\n  <build>\n\n    <!-- inject version into version.properties. -->\n    <!-- Is there a better way to do this (besides switching to gradle, obviously)? -->\n    <resources>\n      <resource>\n        <directory>src/main/resources</directory>\n        <filtering>true</filtering>\n        <includes>\n          <include>**/version.properties</include>\n        </includes>\n      </resource>\n      <resource>\n        <directory>src/main/resources</directory>\n        <filtering>false</filtering>\n        <excludes>\n          <exclude>**/version.properties</exclude>\n        </excludes>\n      </resource>\n    </resources>\n\n    <plugins>\n      <plugin>\n        <groupId>org.jetbrains.kotlin</groupId>\n        <artifactId>kotlin-maven-plugin</artifactId>\n        <version>${kotlin.version}</version>\n        <executions>\n          <execution>\n            <id>compile</id>\n            <phase>compile</phase>\n            <goals>\n              <goal>compile</goal>\n            </goals>\n            <configuration>\n              <sourceDirs>\n                <source>${project.basedir}/src/main/java</source>\n              </sourceDirs>\n            </configuration>\n          </execution>\n          <execution>\n            <id>test-compile</id>\n            <phase>test-compile</phase>\n            <goals>\n              <goal>test-compile</goal>\n            </goals>\n            <configuration>\n              <sourceDirs>\n                <source>${project.basedir}/src/test/java</source>\n              </sourceDirs>\n            </configuration>\n          </execution>\n        </executions>\n      </plugin>\n      <plugin>\n        <groupId>org.jetbrains.dokka</groupId>\n        <artifactId>dokka-maven-plugin</artifactId>\n        <version>2.0.0</version>\n        <executions>\n          <execution>\n            <phase>prepare-package</phase>\n            <goals>\n              <goal>dokka</goal>\n              <goal>javadoc</goal>\n              <goal>javadocJar</goal>\n            </goals>\n          </execution>\n        </executions>\n      </plugin>\n      <plugin>\n        <groupId>org.apache.maven.plugins</groupId>\n        <artifactId>maven-source-plugin</artifactId>\n        <version>3.2.1</version>\n        <executions>\n          <execution>\n            <id>attach-sources</id>\n            <goals>\n              <goal>jar</goal>\n            </goals>\n          </execution>\n        </executions>\n      </plugin>\n      <plugin>\n        <groupId>org.apache.maven.plugins</groupId>\n        <artifactId>maven-surefire-plugin</artifactId>\n        <version>2.22.1</version>\n        <configuration>\n          <useSystemClassLoader>false</useSystemClassLoader>\n        </configuration>\n      </plugin>\n      <plugin>\n        <groupId>org.apache.maven.plugins</groupId>\n        <artifactId>maven-assembly-plugin</artifactId>\n        <version>3.3.0</version>\n        <executions>\n          <execution>\n            <phase>package</phase>\n            <goals>\n              <goal>single</goal>\n            </goals>\n          </execution>\n        </executions>\n        <configuration>\n          <descriptors>\n            <descriptor>src/assembly/tgz.xml</descriptor>\n            <descriptor>src/assembly/zip.xml</descriptor>\n          </descriptors>\n        </configuration>\n      </plugin>\n\n      <plugin>\n        <groupId>org.apache.maven.plugins</groupId>\n        <artifactId>maven-enforcer-plugin</artifactId>\n        <version>1.4.1</version>\n        <executions>\n          <execution>\n            <id>enforce-no-snapshots</id>\n            <goals>\n              <goal>enforce</goal>\n            </goals>\n            <configuration>\n              <rules>\n                <requireReleaseDeps>\n                  <message>Cannot have snapshot dependencies of a release!</message>\n                  <onlyWhenRelease>true</onlyWhenRelease>\n                  <searchTransitive>true</searchTransitive>\n                  <failWhenParentIsSnapshot>true</failWhenParentIsSnapshot>\n                </requireReleaseDeps>\n              </rules>\n              <fail>true</fail>\n            </configuration>\n          </execution>\n        </executions>\n      </plugin>\n    </plugins>\n  </build>\n\n</project>\n"
  },
  {
    "path": "src/assembly/tgz.xml",
    "content": "<assembly xmlns=\"http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n  xsi:schemaLocation=\"http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd\">\n\t<id>bin</id>\n\t<formats>\n\t\t<format>tgz</format>\n\t</formats>\n\t<fileSets>\n\t\t<fileSet>\n\t\t\t<outputDirectory>/</outputDirectory>\n\t\t\t<directory>${project.basedir}/src/scripts</directory>\n\t\t\t<includes>\n\t\t\t\t<include>textricator</include>\n\t\t\t</includes>\n\t\t\t<fileMode>0755</fileMode>\n\t\t</fileSet>\n\t\t<fileSet>\n\t\t\t<directory>${project.basedir}</directory>\n\t\t\t<includes>\n\t\t\t\t<include>README.*</include>\n\t\t\t\t<include>NOTICE</include>\n\t\t\t\t<include>COPYING</include>\n\t\t\t\t<include>examples/</include>\n\t\t\t</includes>\n\t\t</fileSet>\n\t</fileSets>\n\t<dependencySets>\n\t\t<dependencySet>\n\t\t\t<outputDirectory>lib</outputDirectory>\n\t\t</dependencySet>\n\t</dependencySets>\n</assembly>\n"
  },
  {
    "path": "src/assembly/zip.xml",
    "content": "<assembly xmlns=\"http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n  xsi:schemaLocation=\"http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd\">\n\t<id>bin</id>\n\t<formats>\n\t\t<format>zip</format>\n\t</formats>\n\t<fileSets>\n\t\t<fileSet>\n\t\t\t<outputDirectory>/</outputDirectory>\n\t\t\t<directory>${project.basedir}/src/scripts</directory>\n\t\t\t<includes>\n\t\t\t\t<include>textricator.bat</include>\n\t\t\t</includes>\n\t\t</fileSet>\n\t\t<fileSet>\n\t\t\t<directory>${project.basedir}</directory>\n\t\t\t<includes>\n\t\t\t\t<include>README.*</include>\n\t\t\t\t<include>NOTICE</include>\n\t\t\t\t<include>COPYING</include>\n\t\t\t\t<include>examples/</include>\n\t\t\t</includes>\n\t\t</fileSet>\n\t</fileSets>\n\t<dependencySets>\n\t\t<dependencySet>\n\t\t\t<outputDirectory>lib</outputDirectory>\n\t\t</dependencySet>\n\t</dependencySets>\n</assembly>\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/Textricator.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator\n\nimport io.mfj.textricator.table.TableParser\nimport io.mfj.textricator.table.config.TableParseConfig\nimport io.mfj.textricator.extractor.TextExtractor\nimport io.mfj.textricator.extractor.TextExtractorFactory\nimport io.mfj.textricator.extractor.TextExtractorOptions\nimport io.mfj.textricator.form.*\nimport io.mfj.textricator.form.config.FormParseConfig\nimport io.mfj.textricator.form.config.FormParseConfigUtil\nimport io.mfj.textricator.record.Record\nimport io.mfj.textricator.record.RecordFilter\nimport io.mfj.textricator.record.RecordModel\nimport io.mfj.textricator.record.output.*\nimport io.mfj.textricator.table.config.TableParseConfigUtil\nimport io.mfj.textricator.text.*\nimport io.mfj.textricator.text.output.CsvTextOutput\nimport io.mfj.textricator.text.output.JsonTextOutput\nimport io.mfj.textricator.text.output.TextOutput\n\nimport java.io.File\nimport java.io.InputStream\nimport java.io.OutputStream\n\nimport org.slf4j.LoggerFactory\n\n/**\n * Textricator. This is the primary starting point.\n */\nobject Textricator {\n\n  const val DEFAULT_PDF_PARSER = \"pdf.itext5\"\n\n  const val TEXT_OUTPUT_FORMAT_CSV = \"csv\"\n  const val TEXT_OUTPUT_FORMAT_JSON = \"json\"\n\n  const val RECORD_OUTPUT_FORMAT_CSV = \"csv\"\n  const val RECORD_OUTPUT_FORMAT_JSON = \"json\"\n  const val RECORD_OUTPUT_FORMAT_JSON_FLAT = \"json-flat\"\n  const val RECORD_OUTPUT_FORMAT_NULL = \"null\"\n  const val RECORD_OUTPUT_FORMAT_XML = \"xml\"\n\n  private val log = LoggerFactory.getLogger( Textricator::class.java )\n\n  // extract text\n\n  @JvmStatic\n  fun extractText(\n      input:InputStream, inputFormat:String,\n      output:OutputStream, outputFormat:String,\n      pageFilter:PageFilter = ALL_PAGES,\n      textExtractorOptions:TextExtractorOptions = TextExtractorOptions(),\n      maxRowDistance:Float = 0f ) {\n\n    when ( outputFormat ) {\n      TEXT_OUTPUT_FORMAT_CSV -> CsvTextOutput(output)\n      TEXT_OUTPUT_FORMAT_JSON -> JsonTextOutput(output)\n      else -> throw Exception( \"Invalid output format: ${outputFormat}\" )\n    }.use { textOutput ->\n      getExtractor( input, inputFormat, textExtractorOptions ).use { extractor ->\n        extractText( extractor, textOutput, maxRowDistance, pageFilter )\n      }\n    }\n  }\n\n  @JvmStatic\n  fun extractText(\n      extractor:TextExtractor,\n      output:TextOutput,\n      maxRowDistance:Float = 0f,\n      pageFilter:PageFilter = ALL_PAGES ) {\n\n    output.write( extractText( extractor, maxRowDistance, pageFilter ) )\n\n  }\n\n  @JvmStatic\n  fun extractText(\n      extractor:TextExtractor,\n      maxRowDistance:Float = 0f,\n      pageFilter:PageFilter = ALL_PAGES ): Sequence<Text> {\n\n    return extract( extractor, pageFilter ).groupRows( maxRowDistance )\n\n  }\n\n  // parse form to records\n\n  @JvmStatic\n  fun parseForm(\n      inputFile:File,\n      outputFile:File,\n      configFile:File ) {\n\n    val config = FormParseConfigUtil.parseYaml(configFile)\n    val inputFormat = inputFile.extension.lowercase()\n    val outputFormat = outputFile.extension.lowercase()\n\n    inputFile.inputStream().use { input ->\n      outputFile.outputStream().use { output ->\n\n        parseForm(\n            input, inputFormat,\n            output, outputFormat,\n            config )\n\n      }\n\n    }\n  }\n\n  @JvmStatic\n  fun parseForm(\n      inputFile:File,\n      outputFile:File,\n      config:FormParseConfig ) {\n\n    val inputFormat = inputFile.extension.lowercase()\n    val outputFormat = outputFile.extension.lowercase()\n\n    inputFile.inputStream().use { input ->\n      outputFile.outputStream().use { output ->\n\n        parseForm(\n            input, inputFormat,\n            output, outputFormat,\n            config )\n\n      }\n\n    }\n  }\n\n  @JvmStatic\n  fun parseForm(\n      input:InputStream, inputFormat:String,\n      output:OutputStream, outputFormat:String,\n      config:FormParseConfig,\n      eventListener:FormParseEventListener = LoggingEventListener\n      ) {\n\n    getExtractor( input, inputFormat, config ).use { extractor ->\n      getRecordOutput( outputFormat, output, config, includeSource=false ).use { recordOutput ->\n        parseForm( source=null, extractor, recordOutput, config, eventListener )\n      }\n    }\n  }\n\n  @JvmStatic\n  fun parseForms(\n    inputs:Sequence<Triple<String,()->InputStream,String>>,\n    output:OutputStream, outputFormat:String,\n    config:FormParseConfig,\n    eventListener:FormParseEventListener = LoggingEventListener\n  ) {\n    getRecordOutput( outputFormat, output, config, includeSource=true ).use { recordOutput ->\n      val records = sequence<Record> {\n        inputs.forEach { (filename,input,inputFormat) ->\n          input().use { inputStream ->\n            getExtractor( inputStream, inputFormat, config ).use { extractor ->\n              val records = parseForm(filename,extractor,config,eventListener)\n              yieldAll(records)\n            }\n          }\n        }\n      }\n      recordOutput.write(records)\n    }\n  }\n\n  @JvmStatic\n  fun parseForm(\n      source:String?=null,\n      extractor:TextExtractor,\n      recordOutput:RecordOutput,\n      config:FormParseConfig,\n      eventListener:FormParseEventListener = LoggingEventListener\n  ) {\n    val records = parseForm(\n        source,\n        extractor,\n        config,\n        eventListener )\n\n    recordOutput.write( records )\n  }\n\n  @JvmStatic\n  fun parseForm(\n      source:String?,\n      extractor:TextExtractor,\n      config:FormParseConfig,\n      eventListener:FormParseEventListener = LoggingEventListener\n  ): Sequence<Record> {\n\n    // TextExtractor parses PDF to sequence of Text\n    val textSeq = extract( extractor, config.pages.toPageFilter() ).groupRows( config.maxRowDistance )\n\n    // FSMParser parse sequence of Text to sequence of StateValue\n    val stateTextsSeq = FsmParser( source, config, eventListener ).parse( textSeq )\n\n    // RecordParser parses sequence of StateValue to sequence of Record\n    val recSeq = RecordParser( config, eventListener ).parse( stateTextsSeq )\n\n    // RecordFilter filters out non-matching records.\n    val filteredRecSeq = RecordFilter( config ).filter( recSeq )\n\n    return filteredRecSeq\n  }\n\n  @JvmStatic\n  private fun getRecordOutput( outputFormat:String, output:OutputStream, config:RecordModel, includeSource:Boolean):RecordOutput {\n    return when ( outputFormat ) {\n      RECORD_OUTPUT_FORMAT_CSV -> CsvRecordOutput(config,output,includeSource)\n      RECORD_OUTPUT_FORMAT_JSON -> JsonRecordOutput(config,output)\n      RECORD_OUTPUT_FORMAT_JSON_FLAT -> JsonFlatRecordOutput(config,output,includeSource)\n      RECORD_OUTPUT_FORMAT_XML -> XmlRecordOutput(config,output)\n      RECORD_OUTPUT_FORMAT_NULL -> NullOutput\n      else -> throw IllegalArgumentException( \"Unsupported output format \\\"${outputFormat}\\\".\" )\n    }\n  }\n\n  // parse table to records\n\n  @JvmStatic\n  fun parseTable(\n      inputFile:File,\n      outputFile:File,\n      configFile:File ) {\n\n    val config = TableParseConfigUtil.parseYaml(configFile)\n    val inputFormat = inputFile.extension.lowercase()\n    val outputFormat = outputFile.extension.lowercase()\n\n    inputFile.inputStream().use { input ->\n      outputFile.outputStream().use { output ->\n        parseTable(\n            input, inputFormat,\n            output, outputFormat,\n            config )\n      }\n    }\n  }\n\n  @JvmStatic\n  fun parseTable(\n      input:InputStream, inputFormat:String,\n      output:OutputStream, outputFormat:String,\n      config:TableParseConfig) {\n\n    getExtractor( input, inputFormat, config ).use { extractor ->\n      getRecordOutput(outputFormat,output,config,includeSource=false).use { output ->\n        parseTable( extractor, output, config )\n      }\n    }\n  }\n\n  @JvmStatic\n  fun parseTable(\n      extractor:TextExtractor,\n      output:RecordOutput,\n      config:TableParseConfig) {\n\n    val records = parseTable( extractor, config )\n\n    output.write( records )\n  }\n\n  @JvmStatic\n  fun parseTable(\n      extractor:TextExtractor,\n      config:TableParseConfig): Sequence<Record> {\n\n    // TextExtractor parses PDF to sequence of Text\n    val pages = extractPages( extractor, config.pages.toPageFilter() ).groupRowsPaged( config.maxRowDistance )\n\n    val recSeq = TableParser(config).parse( pages )\n\n    // RecordFilter filters out non-matching records.\n    val filteredRecSeq = RecordFilter(config).filter( recSeq )\n\n    return filteredRecSeq\n  }\n\n  @JvmStatic\n  fun getExtractor( input:InputStream, inputFormat:String, options:TextExtractorOptions ): TextExtractor {\n\n    val extractorName:String =\n        if ( options.extractor == null ) {\n          inputFormat\n        } else {\n          val i = inputFormat.indexOf(\".\")\n          val fileType = if ( i > 0 ) inputFormat.substring(0,i) else inputFormat\n          if ( options.extractor!!.startsWith( \"${fileType}.\" ) ) {\n            options.extractor!!\n          } else {\n            // Using a different input format than [options.extractor] is set for.\n            inputFormat\n          }\n        }\n        .let { extractorName -> if ( extractorName == \"pdf\" ) DEFAULT_PDF_PARSER else extractorName }\n\n    log.debug( \"Using extractor \\\"${extractorName}\\\" for input format \\\"${inputFormat}\\\".\" )\n\n    return TextExtractorFactory\n        .getFactory( extractorName )\n        .create( input, options )\n  }\n\n  @JvmStatic\n  fun extract( extractor:TextExtractor, pageFilter:PageFilter = ALL_PAGES ): Sequence<Text> =\n      (1..extractor.getPageCount())\n          .asSequence()\n          .filter { pageNumber ->\n            pageFilter( pageNumber )\n          }\n          .flatMap { pageNumber ->\n            extractor.extract( pageNumber ).asSequence()\n          }\n\n  @JvmStatic\n  fun extractPages( extractor:TextExtractor, pageFilter:PageFilter = ALL_PAGES ): Sequence<Page> =\n      (1..extractor.getPageCount())\n          .asSequence()\n          .filter { pageNumber ->\n            pageFilter( pageNumber )\n          }\n          .map { pageNumber ->\n            Page( pageNumber, extractor.extract( pageNumber ) )\n          }\n\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/Version.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator\n\nimport java.util.*\n\nobject Version {\n\n  val version:String\n  val copyrightYear:String\n  val sourceLocation:String\n\n  init {\n    val props = Properties().apply {\n      Version::class.java.getResourceAsStream( \"version.properties\" ).use { input ->\n        load( input )\n      }\n    }\n    version = props.getProperty(\"version\")\n    copyrightYear = props.getProperty(\"copyright.year\")\n    sourceLocation = props.getProperty(\"source.location\")\n  }\n\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/cli/TextricatorCli.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.cli\n\nimport io.mfj.textricator.*\nimport io.mfj.textricator.extractor.TextExtractorFactory\nimport io.mfj.textricator.extractor.TextExtractorOptions\nimport io.mfj.textricator.form.config.FormParseConfigUtil\nimport io.mfj.textricator.table.config.TableParseConfigUtil\nimport io.mfj.textricator.text.toPageFilter\n\nimport java.io.File\nimport java.io.InputStream\n\nimport ch.qos.logback.classic.Logger\nimport ch.qos.logback.classic.Level\n\nimport org.docopt.Docopt\n\nimport org.slf4j.LoggerFactory\nimport kotlin.system.exitProcess\n\n/**\n * Command-line interface to [Textricator].\n *\n * Can just extract text or also run the form or table parser.\n */\nobject TextricatorCli {\n\n  private val help = \"\"\"\n    Textricator\n\n    Textricator extracts content from PDFs.\n\n    \"text\" extracts the text from a PDF and outputs to CSV or JSON.\n    \"form\" parse a form (using a finite state machine) and generate records.\n    \"table\" parses a table and generates records.\n\n    Output is to standard out if not specified.\n\n    Usage:\n      textricator text [--debug] [--pages=<pages>] [--max-row-distance=<max-row-distance>] [--box-precision=<points>] [--box-ignore-colors=<colors>] [--input-format=<input-format>] [--output-format=<output-format>] <input> [<output>]\n      textricator form [--debug] --config=<config> [--pages=<pages>] [--input-format=<input-format>] [--output-format=<output-format>] <input> [<output>]\n      textricator forms [--debug] --config=<config> --input-format=<input-format> [--output-format=<output-format>] <input-dir> [<output>]\n      textricator table [--debug] --config=<config> [--pages=<pages>] [--input-format=<input-format>] [--output-format=<output-format>] <input> [<output>]\n      textricator -h | --help\n      textricator --version\n\n    Options:\n      --config PATH               Path to config file.\n      --pages PAGES               Pages to include. E.g.: 1-4,5,9. Default: all pages.\n      --max-row-distance POINTS   Order text boxes within this distance (points) by x-position. E.g.: 0.5. Default: no ordering.\n      --box-precision POINTS      Consider text inside a box if it overflows by less than this many points (float).\n      --ignore-box-colors COLORS  Ignore boxes of these colors (comma-separated).\n      --input-format FORMAT       Input format. If not set, determine from file extension.\n                                  Valid values: ${TextExtractorFactory.extractorNames.sorted().joinToString(\", \")}\n                                  (\"pdf\" is an alias for ${Textricator.DEFAULT_PDF_PARSER})\n      --output-format FORMAT      Output format. If not set, determine from file extension.\n                                  Valid values:\n                                    ${Textricator.RECORD_OUTPUT_FORMAT_CSV} (default if output to standard out)\n                                    ${Textricator.RECORD_OUTPUT_FORMAT_JSON}\n                                    ${Textricator.RECORD_OUTPUT_FORMAT_JSON_FLAT}\n                                    ${Textricator.RECORD_OUTPUT_FORMAT_XML}\n                                    ${Textricator.RECORD_OUTPUT_FORMAT_NULL} (no output)\n      --debug                     Enable debug logging\n      --version                   Show version, copyright, and license information.\n    \"\"\".trimIndent().trim()\n\n  private fun Map<String,Any>.boolean( key:String ):Boolean = containsKey(key) && get(key) as Boolean\n  private fun Map<String,Any>.file( key:String ):File? = get(key)?.toString()?.let { File(it) }\n  private fun Map<String,Any>.string( key:String ):String? = get(key)?.toString()\n  private fun Map<String,Any>.float( key:String ):Float? = get(key)?.toString()?.toFloat()\n\n  @JvmStatic\n  fun main(args: Array<String>) {\n\n    // setup logging. This is done in main() (as opposed to with a logback.xml) so applications using Textricator\n    // as a library are not affected by our logging config.\n    System.setProperty(\"logback.configurationFile\", \"io/mfj/textricator/logback.xml\")\n\n    val opts = Docopt(help)\n        .withHelp(true)\n        .withExit(true)\n        .parse(args.toList())\n\n    if (opts.boolean(\"--debug\")) {\n      ( LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME) as Logger ).level = Level.DEBUG\n    }\n\n    try {\n      when {\n        opts.boolean(\"--version\") -> version()\n        opts.boolean(\"text\") -> text(opts)\n        opts.boolean(\"table\") -> table(opts)\n        opts.boolean(\"form\") -> form(opts)\n        opts.boolean(\"forms\") -> forms(opts)\n      }\n    } catch ( e:SystemExitException) {\n      System.err.println(e.message)\n      exitProcess(e.exitCode)\n    }\n  }\n\n  private fun version() {\n    println(\n        \"\"\"\n        Textricator ${Version.version}\n        Copyright ${Version.copyrightYear} Measures for Justice Institute.\n\n        Licensed under the GNU Affero General Public License, Version 3.\n        (Loaded modules may be licensed differently.)\n\n        Source code is available at ${Version.sourceLocation}\n        \"\"\".trimIndent()\n    )\n  }\n\n  private fun text( opts:Map<String,Any> ) {\n\n    val inputFile = opts.file(\"<input>\")!!\n    val inputFormat = opts.string(\"--input-format\") ?: inputFile.extension.lowercase()\n\n    val outputFile = opts.file(\"<output>\")\n    outputFile?.absoluteFile?.parentFile?.mkdirs()\n    val outputFormat = opts.string(\"--output-format\") ?:\n        if ( outputFile == null ) {\n          Textricator.TEXT_OUTPUT_FORMAT_CSV\n        } else {\n          outputFile.extension.lowercase()\n        }\n\n    val pages = opts.string(\"--pages\").toPageFilter()\n    val maxRowDistance = opts.float(\"--max-row-distance\") ?: 0f\n    val boxPrecision:Float = opts.float(\"--box-precision\") ?: 0f\n    val boxIgnoreColors:Set<String> = opts.string(\"--box-ignore-colors\")?.split(\",\")?.toSet() ?: emptySet()\n\n    val options = TextExtractorOptions(\n        boxPrecision = boxPrecision,\n        boxIgnoreColors = boxIgnoreColors )\n\n    inputFile.inputStream().use { input ->\n\n      ( if ( outputFile != null ) outputFile.outputStream() else System.out ).use { output ->\n\n        Textricator.extractText(\n            input = input,\n            inputFormat = inputFormat,\n            output = output,\n            outputFormat = outputFormat,\n            pageFilter = pages,\n            textExtractorOptions = options,\n            maxRowDistance = maxRowDistance )\n\n      }\n\n    }\n  }\n\n  private fun form( opts:Map<String,Any> ) {\n\n    val inputFile = opts.file(\"<input>\")!!\n    val inputFormat = opts.string(\"--input-format\") ?: inputFile.extension.lowercase()\n\n    val outputFile = opts.file(\"<output>\")\n    outputFile?.absoluteFile?.parentFile?.mkdirs()\n    val outputFormat = opts.string(\"--output-format\") ?:\n        if ( outputFile == null ) {\n          throw SystemExitException( \"--output-format is required if <output> is omitted.\", 1 )\n        } else {\n          outputFile.extension.lowercase()\n        }\n\n    val configFile = opts.file(\"--config\")!!\n\n    val config = FormParseConfigUtil.parseYaml(configFile)\n\n    opts.string(\"--pages\")?.apply { config.pages = this }\n\n    inputFile.inputStream().use { input ->\n\n      ( if ( outputFile != null ) outputFile.outputStream() else System.out ).use { output ->\n\n        Textricator.parseForm(\n            input = input,\n            inputFormat = inputFormat,\n            output = output,\n            outputFormat = outputFormat,\n            config = config )\n\n      }\n\n    }\n\n\n  }\n\n  private fun forms( opts:Map<String,Any> ) {\n\n    val inputDir = opts.file(\"<input-dir>\")!!\n\n    val inputFormat = opts.string(\"--input-format\")!!\n    val inputFormatUpper = inputFormat.uppercase()\n\n    val outputFile = opts.file(\"<output>\")\n    outputFile?.absoluteFile?.parentFile?.mkdirs()\n    val outputFormat = opts.string(\"--output-format\") ?:\n      if ( outputFile == null ) {\n        throw SystemExitException( \"--output-format is required if <output> is omitted.\", 1 )\n      } else {\n        outputFile.extension.lowercase()\n      }\n\n    val configFile = opts.file(\"--config\")!!\n\n    val config = FormParseConfigUtil.parseYaml(configFile)\n\n    val inputs:Sequence<Triple<String,()->InputStream,String>> = inputDir.walk().asSequence()\n        .filter { file -> file.isFile }\n        .filter { file -> file.extension.uppercase() == inputFormatUpper }\n        .sorted()\n        .map { inputFile ->\n          Triple( inputFile.relativeTo(inputDir).path, { inputFile.inputStream() }, inputFormat )\n        }\n\n    ( outputFile?.outputStream() ?: System.out ).use { output ->\n      Textricator.parseForms(\n        inputs = inputs,\n        output = output, outputFormat = outputFormat,\n        config = config\n      )\n    }\n  }\n\n  private fun table( opts:Map<String,Any> ) {\n\n    val inputFile = opts.file(\"<input>\")!!\n    val inputFormat = opts.string(\"--input-format\") ?: inputFile.extension.lowercase()\n\n    val outputFile = opts.file(\"<output>\")\n    outputFile?.absoluteFile?.parentFile?.mkdirs()\n    val outputFormat = opts.string(\"--output-format\") ?:\n        if ( outputFile == null ) {\n          throw SystemExitException( \"--output-format is required if <output> is omitted.\", 1 )\n        } else {\n          outputFile.extension.lowercase()\n        }\n\n    val configFile = opts.file(\"--config\")!!\n\n    val config = TableParseConfigUtil.parseYaml(configFile)\n\n    opts.string(\"--pages\")?.apply { config.pages = this }\n\n    inputFile.inputStream().use { input ->\n\n      ( if ( outputFile != null ) outputFile.outputStream() else System.out ).use { output ->\n\n        Textricator.parseTable(\n            input = input,\n            inputFormat = inputFormat,\n            output = output,\n            outputFormat = outputFormat,\n            config = config )\n\n      }\n\n    }\n\n  }\n\n  private class SystemExitException(message:String,val exitCode:Int): Exception(message)\n\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/extractor/TextExtractor.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.extractor\n\nimport io.mfj.textricator.text.Text\n\n/**\n * Interface to extract text from a PDF.\n *\n * Create an instance and call [extract] for each page.\n *\n * @constructor Create an instance for the supplied PDF.\n */\ninterface TextExtractor:AutoCloseable {\n\n  /**\n   * Get the number of pages.\n   */\n  fun getPageCount():Int\n\n  /**\n   * Extract text from the PDF, calling the callback for each text block.\n   *\n   * @param pageNumber Page to extract text from\n   *\n   */\n  fun extract(pageNumber:Int):List<Text>\n\n}\n\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/extractor/TextExtractorFactory.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.extractor\n\nimport java.io.InputStream\nimport java.util.*\n\ninterface TextExtractorFactory {\n\n  fun create( input:InputStream, options:TextExtractorOptions):TextExtractor\n\n  companion object {\n\n    /** path to properties files in classpath that has name=fqcn. */\n    private const val FACTORY_PROPERTIES = \"io/mfj/textricator/extractor/textExtractor.properties\"\n\n    /** Map of name->factory class, loaded from all io/mfj/unbox/factory.properties on classpath. */\n    val classMap:Map<String,Class<TextExtractorFactory>> by lazy {\n      TextExtractorFactory::class.java.classLoader.getResources(\n          FACTORY_PROPERTIES)\n          .asSequence()\n          .map { url ->\n            Properties().apply { url.openStream().use { load( it ) } }\n                .entries\n                .map { (k,v) ->\n                  val name = k as String\n                  val fqcn = v as String\n                  val factoryClass:Class<TextExtractorFactory> = getFactoryClassFromFqcn(\n                      fqcn)\n                  Pair( name, factoryClass )\n                }\n          }\n          .flatten()\n          .toMap()\n    }\n\n    val extractorNames:Collection<String> by lazy { classMap.keys }\n\n    /** Get the factory class for the specified FQCN. */\n    private fun getFactoryClassFromFqcn( fqcn:String ): Class<TextExtractorFactory> =\n        Class.forName(fqcn).let { class_ ->\n          if ( TextExtractorFactory::class.java.isAssignableFrom( class_ ) ) {\n            @Suppress(\"UNCHECKED_CAST\")\n            class_ as Class<TextExtractorFactory>\n          } else {\n            throw Exception( \"\\\"${fqcn}\\\" does not implement \\\"${TextExtractorFactory::class.java.name}\\\"\" )\n          }\n        }\n\n    fun getFactory( name:String ):TextExtractorFactory {\n      val factoryClass = classMap[name] ?: throw Exception( \"No factory \\\"${name}\\\"\" )\n      val factory = factoryClass.getDeclaredConstructor().newInstance()\n      return factory\n    }\n\n  }\n\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/extractor/TextExtractorOptions.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.extractor\n\nopen class TextExtractorOptions(\n    var boxPrecision:Float =0f,\n    var boxIgnoreColors:Set<String> = emptySet(),\n    var maxRowDistance:Float = 0f,\n    var extractor:String? = null,\n    var pages:String? = null\n)\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/extractor/csv/CsvTextExtractor.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.extractor.csv\n\nimport io.mfj.textricator.extractor.TextExtractor\nimport io.mfj.textricator.text.Text\nimport io.mfj.textricator.text.output.CsvTextOutput\n\nimport java.io.InputStream\n\nimport org.apache.commons.csv.CSVParser\nimport org.apache.commons.csv.CSVRecord\n\n/**\n * Parse the CSV output from [CsvTextOutput].\n */\nclass CsvTextExtractor(input:InputStream):TextExtractor {\n\n  // load into memory up front\n  // Do not assume that pages are in order in the CSV.\n  private val pages:MutableMap<Int,MutableList<Text>> = mutableMapOf<Int,MutableList<Text>>()\n      .apply {\n        CSVParser(input.bufferedReader(), CsvTextOutput.CSV_FORMAT).use { csvp ->\n          csvp.asSequence()\n              .drop(1) // header\n              .map(::parseRec)\n              .forEach { text ->\n                getOrPut(text.pageNumber) { mutableListOf() }.add(text)\n              }\n        }\n      }\n\n  private val pageCount = pages.keys.sorted().lastOrNull() ?: 0\n\n  // This matches CsvTextOutput.write(Text)\n  private fun parseRec(rec:CSVRecord): Text =\n      Text(\n          pageNumber = rec[0].toInt(),\n          ulx = rec[1].toFloat(),\n          uly = rec[2].toFloat(),\n          lrx = rec[3].toFloat(),\n          lry = rec[4].toFloat(),\n          // width (rec[5]) is calculated from ulx and lrx\n          // height (rec[6]) is calculated from uly and lry\n          content = rec[7],\n          font = rec[8],\n          fontSize = rec[9].toFloat(),\n          color = rec[10],\n          backgroundColor = rec[11],\n          link = rec[12]\n      )\n\n  override fun getPageCount():Int = pageCount\n\n  override fun extract(pageNumber:Int):List<Text> = pages[pageNumber] ?: emptyList()\n\n  override fun close() {}\n\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/extractor/csv/CvsTextExtractorFactory.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.extractor.csv\n\nimport io.mfj.textricator.extractor.TextExtractor\nimport io.mfj.textricator.extractor.TextExtractorFactory\nimport io.mfj.textricator.extractor.TextExtractorOptions\n\nimport java.io.InputStream\n\nclass CsvTextExtractorFactory: TextExtractorFactory {\n\n    override fun create(input:InputStream, options:TextExtractorOptions):TextExtractor = CsvTextExtractor(input)\n\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/extractor/itext5/Box.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.extractor.itext5\n\nimport java.beans.Transient\n\n/** A box drawn on the page. */\ninternal data class Box(\n    val ulx:Float,\n    val uly:Float,\n    val lrx:Float,\n    val lry:Float,\n    val color:String?\n) {\n  val width:Float\n    @Transient\n    get() = lrx - ulx\n  val height:Float\n    @Transient\n    get() = lry - uly\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/extractor/itext5/Boxtricator.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.extractor.itext5\n\nimport com.itextpdf.text.BaseColor\n\nimport com.itextpdf.text.pdf.*\nimport com.itextpdf.text.pdf.parser.*\nimport io.mfj.textricator.extractor.itext5.Itext5TextExtractor.Companion.color\n\nimport org.slf4j.LoggerFactory\n\n// adapted from\n// https://github.com/mkl-public/testarea-itext5/blob/master/src/test/java/mkl/testarea/itext5/extract/ExtractPaths.java\ninternal class Boxtricator(private val reader:PdfReader,\n    private val ignoreBoxColors:Set<String> ) {\n\n  companion object {\n    private val log = LoggerFactory.getLogger( Boxtricator::class.java )\n  }\n\n  fun getBoxes( pageNumber:Int, pageHeight:Float):List<Box> {\n\n    val boxes:MutableList<Box> = mutableListOf()\n\n    val parser = PdfReaderContentParser(reader)\n    parser.processContent(pageNumber,\n        MyExtRenderListener(boxes, pageHeight, ignoreBoxColors))\n    return boxes.ifEmpty { emptyList() }\n  }\n\n  private class MyExtRenderListener(val boxes:MutableList<Box>, val pageHeight:Float,\n      val ignoreColors:Set<String> ): ExtRenderListener {\n    private val pathInfos:MutableList<PathConstructionRenderInfo?> = mutableListOf()\n    override fun beginTextBlock() {}\n    override fun renderText(renderInfo:TextRenderInfo?) {}\n    override fun endTextBlock() {}\n    override fun renderImage(renderInfo:ImageRenderInfo?) {}\n    override fun modifyPath(renderInfo:PathConstructionRenderInfo?) {\n      pathInfos.add(renderInfo)\n    }\n    override fun renderPath(renderInfo:PathPaintingRenderInfo):Path? {\n      val graphicsState:GraphicsState = renderInfo.gs\n\n      val ctm = graphicsState.ctm\n\n      val fill = (renderInfo.operation and PathPaintingRenderInfo.FILL) != 0\n\n      if ( fill ) {\n        val fillColor = graphicsState.fillColor\n        val color = color(fillColor)\n\n        if ( ! ignoreColors.contains( color ) ) {\n\n          log.debug(\"\\tthe path:\")\n\n          pathInfos.forEach { pathConstructionRenderInfo ->\n            when ( pathConstructionRenderInfo?.operation ) {\n              PathConstructionRenderInfo.MOVETO -> {\n                log.debug(\"move to {} \", transform(ctm, pathConstructionRenderInfo.segmentData))\n              }\n              PathConstructionRenderInfo.CLOSE -> {\n                log.debug(\"\\tclose {} \", transform(ctm, pathConstructionRenderInfo.segmentData))\n\n              }\n              PathConstructionRenderInfo.CURVE_123 -> {\n                log.debug(\"\\tcurve123 {} \", transform(ctm, pathConstructionRenderInfo.segmentData))\n\n              }\n              PathConstructionRenderInfo.CURVE_13 -> {\n                log.debug(\"\\tcurve13 {} \", transform(ctm, pathConstructionRenderInfo.segmentData))\n\n              }\n              PathConstructionRenderInfo.CURVE_23 -> {\n                log.debug(\"\\tcurve23 {} \", transform(ctm, pathConstructionRenderInfo.segmentData))\n\n              }\n              PathConstructionRenderInfo.LINETO -> {\n                log.debug(\"\\tline to {} \", transform(ctm, pathConstructionRenderInfo.segmentData))\n\n              }\n              PathConstructionRenderInfo.RECT -> {\n                val matrix = transform(ctm, expandRectangleCoordinates(pathConstructionRenderInfo.segmentData))!!\n                log.debug(\"rectangle {} \", matrix)\n\n                val box = Box(ulx = matrix[0 /* or 6 */], uly = calcY(matrix[5 /* or 7 */]),\n                    lrx = matrix[4 /* or 2 */], lry = calcY(matrix[1 /* or 3 */]), color = color(fillColor))\n\n                log.debug( \"box: $box\" )\n                boxes.add( box )\n              }\n              /*\n              else -> {\n                throw Exception( \"\\t\\tunhandled ${pathConstructionRenderInfo?.operation}\" )\n              }\n              */\n            }\n          }\n        }\n      }\n\n      pathInfos.clear()\n      return null\n    }\n\n    override fun clipPath(rule:Int) {}\n\n    private fun transform(ctm:Matrix, coordinates:List<Float>? ):List<Float>? {\n      if ( coordinates == null ) return null\n      val result:MutableList<Float> = mutableListOf()\n      var i = 0\n      while ( i < coordinates.size-1) {\n        var vector = Vector(coordinates[i], coordinates[i + 1], 1f)\n        vector = vector.cross(ctm)\n        result.add(vector.get(Vector.I1))\n        result.add(vector.get(Vector.I2))\n        i+=2\n      }\n      return result\n    }\n\n    private fun expandRectangleCoordinates(rectangle:List<Float> ):List<Float> {\n      if (rectangle.size < 4) return emptyList()\n\n      return listOf(\n        rectangle[0], // x (left)\n        rectangle[1], // y (bottom) (from bottom)\n          rectangle[0] + rectangle[2], // x (right)\n        rectangle[1], // y (bottom) (from bottom)\n          rectangle[0] + rectangle[2], // x (right)\n          rectangle[1] + rectangle[3], // y (top) (from bottom)\n        rectangle[0], // x (left)\n          rectangle[1] + rectangle[3] // y (top) (from bottom)\n      )\n    }\n\n    private fun BaseColor?.format(): String = if (this == null) \"DEFAULT\" else \"${red},${green},${blue}\"\n\n    // in iText, if y is positive, it is from the bottom, if y is negative, it is from the top.\n    // We calculate from the top.\n    fun calcY(y:Float):Float {\n      return if (y >= 0) {\n        pageHeight - y\n      } else {\n        y * -1\n      }\n    }\n  }\n\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/extractor/itext5/Buffer.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.extractor.itext5\n\n/** Buffer for accumulating values when parsing. */\ninternal data class Buffer (\n    val pageNumber:Int,\n    val ulx:Float,\n    val uly:Float,\n    var lrx:Float,\n    var lry:Float,\n    val font:String,\n    val fontSize:Float,\n    val fontColor:String?,\n    val content:StringBuffer = StringBuffer())\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/extractor/itext5/Itext5TextExtractor.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.extractor.itext5\n\nimport io.mfj.textricator.extractor.TextExtractor\nimport io.mfj.textricator.text.Text\n\nimport com.itextpdf.text.BaseColor\nimport com.itextpdf.text.pdf.*\nimport com.itextpdf.text.pdf.parser.ContentOperator\nimport com.itextpdf.text.pdf.parser.FilteredTextRenderListener\nimport com.itextpdf.text.pdf.parser.LocationTextExtractionStrategy\nimport com.itextpdf.text.pdf.parser.PdfContentStreamProcessor\nimport com.itextpdf.text.pdf.parser.PdfTextExtractor\nimport com.itextpdf.text.pdf.parser.Vector\n\nimport java.io.InputStream\n\nimport kotlin.math.min\nimport kotlin.math.max\n\nimport org.slf4j.LoggerFactory\n\n/**\n * Class to extract text from a PDF.\n *\n * Create an instance and call [extract] for each page.\n *\n * @constructor Create an instance for the supplied PDF.\n */\nclass Itext5TextExtractor(input:InputStream, boxPrecision:Float?, boxIgnoreColors:Set<String>? ):\n    TextExtractor {\n\n  private val reader = PdfReader(input)\n\n  private val boxPrecision = boxPrecision?: 0f\n\n  private val boxtricator = Boxtricator(reader, boxIgnoreColors ?: emptySet())\n\n  /** Number of pages in the PDF */\n  private val pageCount:Int = reader.numberOfPages\n  private val pageRange = (1..pageCount)\n\n  override fun getPageCount():Int {\n    return pageCount\n  }\n\n  companion object {\n    private val log = LoggerFactory.getLogger(Itext5TextExtractor::class.java)\n\n    internal fun color( baseColor:BaseColor? ): String {\n      if ( baseColor == null ) return \"default\"\n      return \"#%02x%02x%02x\".format( baseColor.red, baseColor.green, baseColor.blue )\n    }\n\n    data class Link( val url:String, val lrx:Float, val lry:Float, val ulx:Float, val uly:Float)\n  }\n\n  override fun close() {\n    reader.close()\n  }\n\n  /**\n   * Get the size, in points, of the specified page, as a width/height pair.\n   *\n   * @param pageNumber Page number\n   */\n  private fun getPageSize(pageNumber:Int):Size {\n    val rect = reader.getPageSize(pageNumber)\n    return Size(rect.width, rect.height)\n  }\n\n  /**\n   * Extract text from the PDF, calling the callback for each text block.\n   *\n   * @param pageNumber Page to extract text from\n   *\n   */\n  override fun extract(pageNumber:Int):List<Text> {\n\n    if ( ! pageRange.contains( pageNumber ) ) {\n      throw IllegalArgumentException( \"Invalid page number: $pageNumber. Valid pages are $pageRange\" )\n    }\n\n    val pageHeight = getPageSize(pageNumber).height\n\n    // in iText, if y is positive, it is from the bottom, if y is negative, it is from the top.\n    // We calculate from the top.\n    fun calcY(y:Float):Float {\n      return if (y >= 0) {\n        pageHeight - y\n      } else {\n        y * -1\n      }\n    }\n\n    val boxes:List<Box> = boxtricator.getBoxes(pageNumber,pageHeight)\n\n    val links = reader.getLinks(pageNumber)\n        .mapNotNull { annotation ->\n          val a = annotation.parameters[PdfName.A]\n          if ( a is PdfDictionary ) {\n            val uriPdfString = a[PdfName.URI] as PdfString\n            val uri = uriPdfString.toUnicodeString()\n            val rect = annotation.rect.map { o -> ( o as PdfNumber ).floatValue() }\n            Link(\n                url = uri,\n                ulx = rect[0],\n                uly = calcY(rect[3]),\n                lrx = rect[2],\n                lry = calcY(rect[1])\n            )\n          } else {\n            // Found a file where it is a com.itextpdf.text.pdf.PRIndirectReference.\n            // Did not need to get links from that document, so did not figure out what to do.\n            null\n          }\n        }\n\n    fun Buffer.toText():Text {\n      val content = content.toString().trim()\n\n      val link = links\n          .firstOrNull { link ->\n            ulx >= link.ulx\n                && uly >= link.uly\n                && lrx <= link.lrx\n                && lry <= link.lry\n          }\n          ?.url\n\n      return Text(\n          content = content,\n          pageNumber = pageNumber,\n          ulx = ulx,\n          uly = uly,\n          lrx = lrx,\n          lry = lry,\n          font = font,\n          fontSize = fontSize,\n          color= fontColor,\n          backgroundColor = getBackground(boxes, this, content),\n          link = link )\n    }\n\n    val texts:MutableList<Text> = mutableListOf()\n\n    val strategy = FilteredTextRenderListener(LocationTextExtractionStrategy())\n\n    var buffer:Buffer? = null\n\n\n\n    // start a new text segment\n    fun start(x:Float, y:Float, font:String, fontSize:Float, fontColor:String?) {\n      if (buffer != null) throw Exception(\"Forgot to call flush(). Text: $buffer\")\n      buffer = Buffer(pageNumber, x, y, x, y, font, fontSize, fontColor)\n    }\n\n    // append text to an existing segment\n    // font and fontSize are ignored unless somebody forgot to call start()\n    fun append(x:Float, y:Float, text:String, font:String, fontSize:Float, fontColor:String? ) {\n      if ( buffer == null ) {\n        // ' or \" without Tj - I have seen this with some PDFs modified with qoppa's PDFStudio.\n        log.warn(\"Forgot to call start()\")\n        start(x,y,font,fontSize,fontColor)\n      }\n      buffer!!.content.append(text)\n      buffer!!.lrx = x\n      buffer!!.lry = y\n    }\n\n    // Call the callback with the buffer content.\n    fun flush() {\n      if (buffer != null) {\n        texts.add( buffer!!.toText() )\n        buffer = null\n      }\n    }\n\n    // Define operators to capture text from the content stream\n\n    // capture strings - start a new segment\n    val stringOperator = ContentOperator { processor:PdfContentStreamProcessor, operator:PdfLiteral?, operands:ArrayList<PdfObject> ->\n      val string = operands[0] as PdfString\n      val matrix = processor.textMatrix\n      val x = matrix[6]\n      val y = calcY( matrix[7] )\n      val bytes = string.bytes\n      val gs = processor.gs()\n      val text = gs.font.decode(bytes, 0, bytes.size)\n      val fontSize = getFontSize(processor)\n      val width = gs.font.getWidthPoint(text, fontSize)\n      val fontColor = color(gs.fillColor)\n\n      flush()\n\n      log.debug(\"{${pageNumber}} string [ ${x}, $y ] $text\")\n      start(x, y, gs.font.postscriptFontName, fontSize, fontColor)\n      append(x + width, y, text, gs.font.postscriptFontName, fontSize, fontColor )\n    }\n\n    // capture continuation of previous string - append to existing segment\n    val stringOperatorContinue = ContentOperator { processor:PdfContentStreamProcessor, operator:PdfLiteral?, operands:ArrayList<PdfObject> ->\n      val string = operands[0] as PdfString\n      val matrix = processor.textMatrix\n      val x = matrix[6]\n      val y = calcY( matrix[7] )\n      val bytes = string.bytes\n      val gs = processor.gs()\n      val text = gs.font.decode(bytes, 0, bytes.size)\n      val fontSize = getFontSize(processor)\n      val width = gs.font.getWidthPoint(text, fontSize)\n      val fontColor = color(gs.fillColor)\n\n      // continuation from stringOperator\n      log.debug(\"{${pageNumber}} continue [ ${x}, $y ] $text\")\n      append(x + width, y, \" $text\", gs.font.postscriptFontName, fontSize, fontColor)\n    }\n\n    // capture pdfarray - this is all one segment\n    val arrayOperator = ContentOperator { processor:PdfContentStreamProcessor, operator:PdfLiteral?, operands:ArrayList<PdfObject> ->\n      val array = operands[0] as PdfArray\n      val matrix = processor.textMatrix\n      val x = matrix[6]\n      val y = calcY( matrix[7] )\n      val gs = processor.gs()\n      val fontSize = getFontSize(processor)\n\n      // combine all PdfStrings in the PdfArray to one String\n      val text = array.asSequence().filter { it is PdfString }.map { it as PdfString }.map { pdfString ->\n        // PdfString.toUnicodeString() does not work in all cases.\n        val bytes = pdfString.bytes\n        gs.font.decode(bytes, 0, bytes.size)\n      }.joinToString(separator = \"\")\n      val width = gs.font.getWidthPoint(text, fontSize)\n      val fontColor = color(gs.fillColor)\n\n      flush()\n\n      log.debug(\"{${pageNumber}} array [ $x , $y ] $text\")\n      start(x, y, gs.font.postscriptFontName, fontSize, fontColor)\n      append(x + width, y, text, gs.font.postscriptFontName, fontSize, fontColor)\n      flush()\n    }\n\n    // This is setting up what PdfContentStreamProcesses does internally.\n    val twOperator = SetTextWordSpacing()\n    val tcOperator = SetTextCharacterSpacing()\n    val tdOperator = TextMoveStartNextLine()\n    val tstarOperator = TextMoveNextLine(tdOperator)\n    val tickOperator = MoveNextLineAndShowText(tstarOperator, stringOperatorContinue)\n    val quoteOperator = MoveNextLineAndShowTextWithSpacing(twOperator, tcOperator,\n        tickOperator)\n\n    // This results in calls to the content operators defined above. We do not care about its return value.\n    PdfTextExtractor.getTextFromPage(reader, pageNumber, strategy,\n        mapOf(\"Tj\" to stringOperator, \"TJ\" to arrayOperator, \"'\" to tickOperator, \"\\\"\" to quoteOperator))\n\n    flush()\n\n    return texts\n        .sortedWith( compareBy( {it.uly}, {it.ulx} ) )\n  }\n\n  private fun getBackground(all:List<Box>?,buffer:Buffer,content:String): String? {\n    if ( all == null ) return null\n    val boxes = all.filter { box -> isBufferInBox( buffer, box ) }\n    val box:Box? = boxes.lastOrNull()\n    return box?.color\n  }\n\n  private fun isBufferInBox( buffer:Buffer, box:Box): Boolean {\n    // shrink the buffer by the precision, but do not shrink width or height to negative.\n    return box.ulx <= min( buffer.ulx + boxPrecision, buffer.lrx )\n        && box.uly <= min( buffer.uly + boxPrecision, buffer.lry )\n        && box.lrx >= max( buffer.lrx - boxPrecision, buffer.ulx )\n        && box.lry >= max( buffer.lry - boxPrecision, buffer.uly )\n  }\n\n  private fun getFontSize( processor:PdfContentStreamProcessor ):Float {\n    val gs = processor.gs()\n    val effMatrix = processor.textMatrix.multiply( gs.ctm )\n    val fontSize = Vector(0f,gs.fontSize,0f).cross(effMatrix)[1]\n    return fontSize\n  }\n\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/extractor/itext5/Itext5TextExtractorFactory.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.extractor.itext5\n\nimport io.mfj.textricator.extractor.TextExtractor\nimport io.mfj.textricator.extractor.TextExtractorFactory\nimport io.mfj.textricator.extractor.TextExtractorOptions\n\nimport java.io.InputStream\n\nclass Itext5TextExtractorFactory:TextExtractorFactory {\n\n  override fun create(input:InputStream, options:TextExtractorOptions):TextExtractor =\n      Itext5TextExtractor( input, options.boxPrecision, options.boxIgnoreColors )\n\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/extractor/itext5/Shenanigans.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.extractor.itext5\n\nimport com.itextpdf.text.pdf.*\nimport com.itextpdf.text.pdf.parser.*\n\n// This is copies of a bunch of stuff that is private in IText's PdfContentStreamProcessor and GraphicsState\n// DO NOT USE THIS!!! (except in Itext5TextExtractortor.kt)\n\n/**\n * A content operator implementation (Td).\n */\nclass TextMoveStartNextLine:ContentOperator {\n  override fun invoke(processor:PdfContentStreamProcessor, operator:PdfLiteral?, operands:ArrayList<PdfObject>) {\n    val tx = (operands[0] as PdfNumber).floatValue()\n    val ty = (operands[1] as PdfNumber).floatValue()\n\n    val translationMatrix = Matrix(tx, ty)\n    processor.textMatrix = translationMatrix.multiply(processor.textLineMatrix)\n    processor.textLineMatrix = processor.textMatrix\n  }\n\n}\n\n/**\n * A content operator implementation (T*).\n */\nclass TextMoveNextLine(private val moveStartNextLine:TextMoveStartNextLine):ContentOperator {\n  override fun invoke(processor:PdfContentStreamProcessor, operator:PdfLiteral?, operands:ArrayList<PdfObject>) {\n    val tdoperands:ArrayList<PdfObject> = ArrayList(2)\n    tdoperands.add(0, PdfNumber(0))\n    tdoperands.add(1, PdfNumber(-processor.gs().leading))\n    moveStartNextLine.invoke(processor, null, tdoperands)\n  }\n}\n\n/**\n * A content operator implementation (').\n */\nclass MoveNextLineAndShowText(private val textMoveNextLine:TextMoveNextLine, private val showText:ContentOperator):\n    ContentOperator {\n  override fun invoke(processor:PdfContentStreamProcessor, operator:PdfLiteral?, operands:ArrayList<PdfObject>) {\n    textMoveNextLine.invoke(processor, null, ArrayList(0))\n    showText.invoke(processor, null, operands)\n  }\n}\n\n/**\n * A content operator implementation (Tw).\n */\nclass SetTextWordSpacing:ContentOperator {\n  override fun invoke(processor:PdfContentStreamProcessor, operator:PdfLiteral?, operands:ArrayList<PdfObject>) {\n    val wordSpace = operands[0] as PdfNumber\n    processor.gs().setWordSpacing(wordSpace.floatValue())\n  }\n}\n\n/**\n * A content operator implementation (Tc).\n */\nclass SetTextCharacterSpacing:ContentOperator {\n  override fun invoke(processor:PdfContentStreamProcessor, operator:PdfLiteral?, operands:ArrayList<PdfObject>) {\n    val charSpace = operands[0] as PdfNumber\n    processor.gs().setCharacterSpacing(charSpace.floatValue())\n  }\n}\n\n/**\n * A content operator implementation (\").\n */\nclass MoveNextLineAndShowTextWithSpacing(private val setTextWordSpacing:SetTextWordSpacing,\n    private val setTextCharacterSpacing:SetTextCharacterSpacing,\n    private val moveNextLineAndShowText:MoveNextLineAndShowText):ContentOperator {\n\n  override fun invoke(processor:PdfContentStreamProcessor, operator:PdfLiteral?, operands:ArrayList<PdfObject>) {\n\n    val aw:PdfNumber = operands[0] as PdfNumber\n    val ac:PdfNumber = operands[1] as PdfNumber\n    val string:PdfString = operands[2] as PdfString\n\n    val twOperands:ArrayList<PdfObject> = ArrayList(1)\n    twOperands.add(0, aw)\n    setTextWordSpacing.invoke(processor, null, twOperands)\n\n    val tcOperands:ArrayList<PdfObject> = ArrayList(1)\n    tcOperands.add(0, ac)\n    setTextCharacterSpacing.invoke(processor, null, tcOperands)\n\n    val tickOperands:ArrayList<PdfObject> = ArrayList(1)\n    tickOperands.add(0, string)\n    moveNextLineAndShowText.invoke(processor, null, tickOperands)\n  }\n}\n\n/**\n * private/protected things we need to access\n */\nvar PdfContentStreamProcessor.textMatrix:Matrix\n  get() = javaClass.getDeclaredField(\"textMatrix\").let {\n    it.isAccessible = true\n    it.get(this) as Matrix\n  }\n  set(textMatrix) = javaClass.getDeclaredField(\"textMatrix\").let {\n    it.isAccessible = true\n    it.set(this, textMatrix)\n  }\n\n/// accessors for private itext stuff\n\nvar PdfContentStreamProcessor.textLineMatrix:Matrix\n  get() = javaClass.getDeclaredField(\"textLineMatrix\").let {\n    it.isAccessible = true\n    it.get(this) as Matrix\n  }\n  set(textLineMatrix) = javaClass.getDeclaredField(\"textLineMatrix\").let {\n    it.isAccessible = true\n    it.set(this, textLineMatrix)\n  }\n\nfun GraphicsState.setWordSpacing(wordSpacing:Float) {\n  javaClass.getDeclaredField(\"wordSpacing\").let {\n    it.isAccessible = true\n    it.set(this, wordSpacing)\n  }\n}\n\nfun GraphicsState.setCharacterSpacing(wordSpacing:Float) {\n  javaClass.getDeclaredField(\"characterSpacing\").let {\n    it.isAccessible = true\n    it.set(this, wordSpacing)\n  }\n}\n\nval PathPaintingRenderInfo.gs:GraphicsState\n  get() = javaClass.getDeclaredField(\"gs\").let {\n    it.isAccessible = true\n    it.get(this) as GraphicsState\n  }\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/extractor/itext5/Size.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.extractor.itext5\n\n/** Width and height, in points. */\ndata class Size(val width:Float, val height:Float)\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/extractor/itext7/Itext7TextExtractor.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.extractor.itext7\nimport io.mfj.textricator.extractor.TextExtractor\nimport io.mfj.textricator.text.Text\n\nimport java.io.InputStream\n\nimport com.itextpdf.kernel.colors.*\nimport com.itextpdf.kernel.geom.Vector\nimport com.itextpdf.kernel.pdf.*\nimport com.itextpdf.kernel.pdf.canvas.parser.EventType\nimport com.itextpdf.kernel.pdf.canvas.parser.PdfTextExtractor\nimport com.itextpdf.kernel.pdf.canvas.parser.data.IEventData\nimport com.itextpdf.kernel.pdf.canvas.parser.data.TextRenderInfo\nimport com.itextpdf.kernel.pdf.canvas.parser.listener.LocationTextExtractionStrategy\n\n/**\n * Extract text using iText 7.\n *\n * This gets accurate locations, and does not attempt to group characters based on proximity or structure.\n */\nclass Itext7TextExtractor(input:InputStream):TextExtractor {\n\n  private val reader = PdfReader(input)\n  private val doc = PdfDocument(reader)\n\n  /** Number of pages in the PDF */\n  private val pageCount:Int = doc.numberOfPages\n\n  override fun getPageCount():Int {\n    return pageCount\n  }\n\n  override fun close() {\n    reader.close()\n  }\n\n\n  /**\n   * Extract text from the PDF, calling the callback for each text block.\n   *\n   * @param pageNumber Page to extract text from\n   *\n   */\n  override fun extract(pageNumber:Int):List<Text> {\n\n    val page = doc.getPage(pageNumber)\n\n    val pageHeight = page.pageSize.height\n\n    val links:List<Link> = page.annotations\n        .filter { anno ->\n          anno.subtype == PdfName.Link\n        }\n        .map { anno ->\n          val aObj = anno.pdfObject[PdfName.A] as PdfDictionary\n          val uriObj = (aObj[PdfName.URI] ?: aObj[PdfName.URL]) as PdfString\n          val uri = uriObj.value\n          // get the bounding box\n          val rect = (anno.pdfObject[PdfName.Rect] as PdfArray).map { (it as PdfNumber).floatValue() }\n          Link(\n              url = uri,\n              ulx = rect[0],\n              uly = calcY(pageHeight, rect[3]),\n              lrx = rect[2],\n              lry = calcY(pageHeight, rect[1])\n          )\n        }\n\n    val strategy = Strategy(pageNumber, pageHeight, links)\n\n    PdfTextExtractor.getTextFromPage(page,strategy)\n\n    return strategy.texts\n        .sortedWith( compareBy( {it.uly}, {it.ulx} ) )\n  }\n\n  private class Strategy( private val pageNumber:Int, private val pageHeight:Float, private val links:List<Link>):\n    LocationTextExtractionStrategy() {\n    val texts = mutableListOf<Text>()\n\n    override fun eventOccurred(data:IEventData?, type:EventType?) {\n      if ( type == EventType.RENDER_TEXT ) {\n        val ri = data as TextRenderInfo\n        val content = ri.text\n\n        val matrix = ri.textMatrix\n        val font = ri.font.fontProgram.fontNames.fontName\n\n        val ulx = matrix[6]\n        val lry = calcY( pageHeight, matrix[7] )\n        val width = ri.font.getWidth(content,ri.fontSize)\n        val height = ri.font.getAscent(content, ri.fontSize)\n        val uly = lry - height\n        val lrx = ulx + width\n\n        val color = ri.fillColor?.getHexColor()\n\n        val link = links\n            .firstOrNull { link ->\n              ulx >= link.ulx\n                  && uly >= link.uly\n                  && lrx <= link.lrx\n                  && lry <= link.lry\n            }\n            ?.url\n\n        val effMatrix = ri.textMatrix.multiply( ri.graphicsState.ctm )\n        val fontSize = Vector(0f,ri.fontSize,0f).cross(effMatrix)[1]\n\n        val text = Text(content = content, backgroundColor = null, pageNumber = pageNumber,\n            fontSize = fontSize, font = font, color = color,\n            ulx = ulx, uly = uly, lrx = lrx, lry = lry,\n            link = link )\n\n        texts.add( text )\n      }\n      super.eventOccurred(data, type)\n    }\n\n    private fun Color.getHexColor(): String? =\n        when ( this ) {\n          is DeviceRgb -> getRgb( this )\n          is DeviceCmyk -> getRgb( Color.convertCmykToRgb( this ) )\n          else -> null\n        }\n\n    private fun getRgb( color:DeviceRgb ): String {\n      val value = color.colorValue\n      val r = ( value[0] * 255 ).toInt()\n      val g = ( value[1] * 255 ).toInt()\n      val b = ( value[2] * 255 ).toInt()\n      return \"#%02x%02x%02x\".format( r, g, b )\n    }\n\n  }\n\n  companion object {\n    data class Link(val url:String, val lrx:Float, val lry:Float, val ulx:Float, val uly:Float)\n\n    // in iText, if y is positive, it is from the bottom, if y is negative, it is from the top.\n    // We calculate from the top.\n    fun calcY(pageHeight:Float, y:Float):Float {\n      return if (y >= 0) {\n        pageHeight - y\n      } else {\n        y * -1\n      }\n    }\n\n  }\n\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/extractor/itext7/Itext7TextExtractorFactory.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.extractor.itext7\n\nimport io.mfj.textricator.extractor.TextExtractor\nimport io.mfj.textricator.extractor.TextExtractorFactory\nimport io.mfj.textricator.extractor.TextExtractorOptions\n\nimport java.io.InputStream\n\nclass Itext7TextExtractorFactory:TextExtractorFactory {\n\n  override fun create(input:InputStream, options:TextExtractorOptions):TextExtractor = Itext7TextExtractor(\n      input)\n\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/extractor/json/JsonTextExtractor.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.extractor.json\n\nimport io.mfj.textricator.extractor.TextExtractor\nimport io.mfj.textricator.text.Text\n\nimport java.io.InputStream\nimport java.util.*\n\nimport com.fasterxml.jackson.core.JsonFactory\nimport com.fasterxml.jackson.databind.ObjectMapper\nimport com.fasterxml.jackson.module.kotlin.registerKotlinModule\n\nclass JsonTextExtractor(input:InputStream):TextExtractor {\n\n  private val texts:Map<Int,List<Text>>\n  private val pageCount:Int\n\n  // load into memory up front\n  init {\n    val mapper = ObjectMapper(JsonFactory()).registerKotlinModule()\n\n    val typeFactory = mapper.typeFactory\n\n    val type =\n        typeFactory.constructCollectionType( LinkedList::class.java,\n                mapper.constructType(Text::class.java ) )\n\n    val list:List<Text> = mapper.readValue(input,type)\n\n    val map:MutableMap<Int,MutableList<Text>> = mutableMapOf()\n    list.forEach { text ->\n      map\n          .getOrPut( text.pageNumber) { mutableListOf() }\n        .add( text )\n    }\n\n    this.texts = map\n    this.pageCount = texts.keys.maxOrNull() ?: 0\n  }\n\n  override fun getPageCount():Int {\n    return pageCount\n  }\n\n  override fun extract(pageNumber:Int):List<Text> {\n    return texts[pageNumber] ?: emptyList()\n  }\n\n  override fun close() {}\n\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/extractor/json/JsonTextExtractorFactory.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.extractor.json\n\nimport io.mfj.textricator.extractor.TextExtractor\nimport io.mfj.textricator.extractor.TextExtractorFactory\nimport io.mfj.textricator.extractor.TextExtractorOptions\n\nimport java.io.InputStream\n\nclass JsonTextExtractorFactory: TextExtractorFactory {\n\n  override fun create(input:InputStream, options:TextExtractorOptions):TextExtractor = JsonTextExtractor(input)\n\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/extractor/pdfbox/PdfboxTextExtractor.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.extractor.pdfbox\n\nimport io.mfj.textricator.text.Text\nimport io.mfj.textricator.extractor.TextExtractor\n\nimport java.io.InputStream\n\nimport org.apache.pdfbox.pdmodel.PDDocument\n\nclass PdfboxTextExtractor(input:InputStream):TextExtractor {\n\n  private val doc = PDDocument.load(input)\n\n  private val stripper = TextBoxPdfTextStripper()\n\n  override fun extract(pageNumber:Int):List<Text> {\n\n    stripper.startPage = pageNumber\n    stripper.endPage = pageNumber\n    stripper.getText(doc)\n\n    return stripper.wordList[pageNumber]?.sortedWith( compareBy( Text::uly, Text::ulx ) ) ?: emptyList()\n  }\n\n  override fun getPageCount():Int = doc.numberOfPages\n\n  override fun close() {\n    doc.close()\n  }\n\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/extractor/pdfbox/PdfboxTextExtractorFactory.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.extractor.pdfbox\n\nimport io.mfj.textricator.extractor.TextExtractor\nimport io.mfj.textricator.extractor.TextExtractorFactory\nimport io.mfj.textricator.extractor.TextExtractorOptions\n\nimport java.io.InputStream\n\nclass PdfboxTextExtractorFactory:TextExtractorFactory {\n\n  override fun create(pdf:InputStream, options:TextExtractorOptions):TextExtractor = PdfboxTextExtractor(\n      pdf)\n\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/extractor/pdfbox/TextBoxPdfTextStripper.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.extractor.pdfbox\n\nimport io.mfj.textricator.text.Text\n\nimport java.io.IOException\nimport java.util.regex.Pattern\n\nimport org.apache.pdfbox.text.PDFTextStripper\nimport org.apache.pdfbox.text.TextPosition\n\ninternal class TextBoxPdfTextStripper : PDFTextStripper() {\n\n  companion object {\n    const val NON_BREAKING_SPACE:String = \"\\u00A0\"\n    val NON_PRINTABLE:Pattern = Pattern.compile(\".*[\\\\u0000-\\\\u0019]+.*\")\n  }\n\n  internal val wordList: MutableMap<Int, MutableList<Text>> = mutableMapOf()\n\n  /**\n   * used to group words decoded at the same time.\n   */\n  private var chunkIndex:Long = 0\n\n  @Throws(IOException::class)\n  override fun writeString(text:String, textPositions:List<TextPosition> ) {\n    chunkIndex++\n    val sb = StringBuilder()\n    // add initial position\n\n    // look for huge space gaps:\n    var wordStart:Int = -1\n    var current:TextPosition = textPositions.get(0)\n    var previous: TextPosition\n    var maxHeight:Float = 0f\n\n    (0..textPositions.size-1).forEach { i ->\n      previous = current\n\n      current = textPositions.get(i)\n\n      val separation:Float = current.getX() - (previous.getX() + previous.getWidth())\n      val sameFont:Boolean = current.getFont().equals(previous.getFont())\n          && current.getFontSize() == previous.getFontSize()\n\n\n      if (current.getUnicode().endsWith(\" \") ||\n          current.getUnicode().endsWith(\n              NON_BREAKING_SPACE) ||\n          (wordStart != -1 && (separation >= previous.getWidthOfSpace()))) {\n        addWord(sb, wordStart, i, textPositions, maxHeight)\n        maxHeight = 0f\n        wordStart = -1\n      } else if ((i > 0 && separation < -(previous.getWidth()) / 2) || !sameFont) {\n        // split in cases where words overlay (eg in excel print outs! // TODO : this should be a configuable param\n        // have to exclude i = 0 as we set previous to the first char\n        addWord(sb, wordStart, i, textPositions, maxHeight)\n        maxHeight = 0f\n        wordStart = i\n        sb.append(current.getUnicode())\n      } else {\n        if (wordStart == -1) {\n          wordStart = i\n        }\n        sb.append(current.getUnicode())\n      }\n      val gs = graphicsState\n      val color = gs.strokingColor.toRGB()\n      val nscolor = gs.nonStrokingColor.toRGB()\n      maxHeight = Math.max(maxHeight, current.getHeight())\n\n    }\n\n    addWord(sb, wordStart, textPositions.size, textPositions, maxHeight)\n  }\n\n  private fun expandNonPrintableUnicode(string:String) :String {\n    if (NON_PRINTABLE.matcher(string).matches()) {\n      val sb = StringBuilder()\n      (0..string.length-1).forEach { i ->\n        val cp = string.codePointAt(i)\n        if (cp < 0x20) {\n          sb.append(String.format(\"\\\\x%02x\", cp))\n        } else {\n          sb.append(string[i])\n        }\n      }\n      return sb.toString()\n    } else {\n      return string\n    }\n  }\n\n  private fun addWord(sb: StringBuilder, startIndex:Int, endIndex:Int,\n      textPositions: List<TextPosition>, maxHeight:Float) {\n    if (sb.length > 0) {\n      val first = textPositions.get(startIndex)\n      val previous = textPositions.get(endIndex - 1)\n\n      val expanded = expandNonPrintableUnicode(sb.toString())\n\n      val textBox = Text(content = expanded, pageNumber = currentPageNo, ulx = first.x,\n          uly = first.y - first.height, lrx = previous.x + previous.width, lry = first.y, font = first.font?.name ?: \"\",\n          fontSize = first.fontSize, color = null, // TODO\n          backgroundColor = null)\n\n      wordList.putIfAbsent(textBox.pageNumber, mutableListOf())\n      val pageList = wordList.get(textBox.pageNumber)!!\n      pageList.add(textBox)\n      sb.setLength(0)\n    }\n  }\n\n\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/form/FormParseEventListener.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.form\n\ninterface FormParseEventListener: FsmEventListener, RecordParserEventListener\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/form/FsmEventListener.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.form\n\nimport io.mfj.textricator.text.Text\n\ninterface FsmEventListener {\n\n  fun onText( text:Text)\n\n  fun onHeader( text:Text)\n  fun onFooter( text:Text)\n  fun onLeftMargin( text:Text)\n  fun onRightMargin( text:Text)\n  fun onExclude( text:Text, condition:String )\n\n  fun onCheckTransition( currentState:String, condition:String, nextState:String )\n  fun onCheckTransition( currentState:String, condition:String, nextState:String, match:Boolean, message:String? )\n\n  fun onNoPrevious( source:String )\n  fun onCheckCondition( source:String, description:String, match:Boolean )\n\n  fun onPageStateChange( page:Int, state:String )\n\n  fun onStateChange( page:Int, state:String )\n\n  fun onVariableSet( currentState:String, name:String, value:String? )\n\n  fun onFsmEnd()\n\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/form/FsmParser.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.form\n\nimport io.mfj.expr.*\nimport io.mfj.textricator.form.config.*\nimport io.mfj.textricator.record.Value\nimport io.mfj.textricator.text.Text\nimport io.mfj.textricator.text.groupRows\n\nimport org.slf4j.LoggerFactory\n\n/**\n * Use a Finite State Machine config to parse\n * a sequence of Text to a sequence of StateValue,\n * which contains the FSM state and the value for that state.\n *\n * @param config FSM config\n * @param eventListener event listener\n */\nclass FsmParser( val source:String?, val config:FormParseConfig,\n    private val eventListener:FsmEventListener? =null ) {\n\n  companion object {\n    private val log = LoggerFactory.getLogger(FsmParser::class.java)\n  }\n\n  fun parse( texts:Sequence<Text> ): Sequence<StateValue> {\n\n    // parse state is a passed object instead of object-level to keep this thread-safe\n    val parseState = ParseState(source,config, eventListener)\n\n    return texts.groupRows(config.maxRowDistance)\n\n        // filter out header and footer\n        .filter { text -> boundsFilter(text) }\n\n        // group by state (run the FSM)\n        .plus( null as Text? ) // sentinel\n        .map { text -> parse( parseState, text ) }\n        .filterNotNull()\n        // remove skipped states and combine now-adjacent siblings of the same state\n        .filter { sv -> ! sv.state.skip }.combine()\n  }\n\n  /**\n   * Combine adjacent siblings with the same state.\n   */\n  private fun Sequence<StateValue>.combine():Sequence<StateValue> = sequence {\n    var last:StateValue? = null\n    forEach { sv ->\n      last = when {\n        last == null -> sv\n        last!!.state == sv.state -> last!!.copy( values = last!!.values + sv.values )\n        else -> {\n          yield(last!!)\n          sv\n        }\n      }\n    }\n    last?.let { yield(it) }\n  }\n\n  private class ExprState(val source:String?, val config:FormParseConfig, val eventListener: FsmEventListener?) {\n\n    companion object {\n\n      /**\n       * Built-in variables.\n       * The enum names match exactly the variables in the expression.\n       */\n      private enum class BuiltInVar(val type:ExDataType) {\n        /** x coordinate of the upper-left corner of the text box */\n        ulx(ExDataType.NUMBER),\n        /** y coordinate of the upper-left corner of the text box */\n        uly(ExDataType.NUMBER),\n        /** x coordinate of the lower-right corner of the text box */\n        lrx(ExDataType.NUMBER),\n        /** y coordinate of the lower-right corner of the text box */\n        lry(ExDataType.NUMBER),\n        /** The text. */\n        text(ExDataType.STRING),\n        /** page number . */\n        page(ExDataType.NUMBER),\n        /** page number of the previous text */\n        page_prev(ExDataType.NUMBER),\n        /** font size */\n        fontSize(ExDataType.NUMBER),\n        /** font name */\n        font(ExDataType.STRING),\n        /** text color */\n        color(ExDataType.STRING),\n        /** background color  */\n        bgcolor(ExDataType.STRING),\n        /** width of the text box */\n        width(ExDataType.NUMBER),\n        /** height of the text box */\n        height(ExDataType.NUMBER),\n        /** Difference in [ulx] from the previous text to this one */\n        ulx_rel(ExDataType.NUMBER),\n        /** Difference in [uly] from the previous text to this one */\n        uly_rel(ExDataType.NUMBER),\n        /** Difference in [lrx] from the previous text to this one */\n        lrx_rel(ExDataType.NUMBER),\n        /** Difference in [lry] from the previous text to this one */\n        lry_rel(ExDataType.NUMBER),\n        /** Data source; e.g. file name. */\n        source(ExDataType.STRING),\n      }\n\n      private val builtInVarNames = BuiltInVar.values().map(BuiltInVar::name).toSet()\n\n      // expr var type provider\n      // If you add a type, add it to ParseState.vp\n      private val VTP = ChainVarTypeProvider(\n        MapVarTypeProvider(\n            BuiltInVar\n                .values()\n                .associate {\n                  it.name to it.type\n                }\n        ),\n        object: VarTypeProvider {\n          override fun contains(varName:String):Boolean = true\n          override operator fun get(varName: String): ExDataType = ExDataType.STRING\n        } )\n\n      /**\n       * Compile the specified expression\n       */\n      private fun compile( e:String ): Expr {\n        return ExprParser.parseToExpr(e, VTP)\n      }\n\n    }\n\n    // cache of parsed expression\n    private val exprCache:MutableMap<String,Pair<String,Expr>> = mutableMapOf()\n\n    /**\n     * Get the expression and parsed Expr for the specified conditionId.\n     */\n    private fun getCondition( conditionId:String ):Pair<String,Expr> =\n        exprCache.getOrPut( conditionId ) {\n          val e = config.conditions[conditionId] ?: throw Exception( \"Missing condition \\\"${conditionId}\\\"\" )\n          Pair( e, compile(e))\n        }\n\n    /** The text referenced by \"last\" in the expressions. */\n    private var lastText:Text? = null\n\n    /** The text referenced by \"text\" in the expressions. */\n    private var text:Text? = null\n\n    val vars:MutableMap<String,String?> = mutableMapOf()\n\n    /** Expr variable provider */\n    val vp: VarProvider = object : VarProvider {\n\n      private fun noLast(source:String) = eventListener?.onNoPrevious(source)\n\n      override fun contains(varName:String):Boolean = true // if it is not built in, anything else is allowed as String\n\n      override operator fun get( varName: String ): Any? {\n        return if ( builtInVarNames.contains(varName) ) {\n          val builtInVar = BuiltInVar.valueOf(varName)\n          when ( builtInVar ) {\n            // built-ins\n            BuiltInVar.ulx -> text!!.ulx\n            BuiltInVar.uly -> text!!.uly\n            BuiltInVar.lrx -> text!!.lrx\n            BuiltInVar.lry -> text!!.lry\n            BuiltInVar.text -> text!!.content\n            BuiltInVar.page -> text!!.pageNumber\n            BuiltInVar.page_prev -> if ( lastText != null ) lastText!!.pageNumber else { noLast( varName ); -1 }\n            BuiltInVar.fontSize -> text!!.fontSize\n            BuiltInVar.font -> text!!.font\n            BuiltInVar.color -> text!!.color\n            BuiltInVar.bgcolor -> text!!.backgroundColor\n            BuiltInVar.width -> text!!.width\n            BuiltInVar.height -> text!!.height\n            BuiltInVar.ulx_rel -> if ( lastText != null ) text!!.ulx - lastText!!.ulx else { noLast( varName ); text!!.ulx }\n            BuiltInVar.uly_rel -> if ( lastText != null ) text!!.uly - lastText!!.uly else { noLast( varName ); text!!.uly }\n            BuiltInVar.lrx_rel -> if ( lastText != null ) text!!.lrx - lastText!!.lrx else { noLast( varName ); text!!.lrx }\n            BuiltInVar.lry_rel -> if ( lastText != null ) text!!.lry - lastText!!.lry else { noLast( varName ); text!!.lry }\n            BuiltInVar.source -> source\n          }\n        } else {\n          vars[varName]\n        }\n      }\n\n      override fun getKnownVars():Set<String> = builtInVarNames.plus( vars.keys )\n    }\n\n    fun matches( conditionId:String, last:Text?, text:Text ): Boolean {\n      val (exprStr,expr) = getCondition(conditionId)\n\n      this.lastText = last\n      this.text = text\n\n      val match = Eval.evaluate( expr, vp )\n\n      eventListener?.onCheckCondition( conditionId, exprStr, match )\n\n      return match\n    }\n  }\n\n  private class ParseState( private val source:String?, private val config:FormParseConfig, private val eventListener:FsmEventListener? ) {\n\n    val exprState = ExprState(source,config,eventListener)\n\n    // text currently being parsed\n    private var current:Text? = null\n    var text:Text?\n      get() = current\n      set(text) {\n        last = current\n        current = text\n      }\n\n    // last parsed text\n    private var last:Text? = null\n    val lastText:Text?\n      get() = last\n\n    var stateId:String\n    var state:State\n\n    private val buffer:MutableList<Text> = mutableListOf()\n\n\n    init {\n      val stateId = config.initialState\n      this.state = config.states[stateId] ?: throw Exception( \"Missing initial state ${stateId}\" )\n      this.stateId = stateId\n    }\n\n    /**\n     * Determine if the current state matches the specified condition.\n     */\n    fun matches( conditionId:String ): Boolean {\n      return exprState.matches(conditionId,last,text!!)\n    }\n\n    /**\n     * Determine if the next state matches the specified condition.\n     * Uses the current text as \"last\" and the supplied [next] text a \"text\".\n     */\n    fun matches( conditionId:String, next:Text ):Boolean {\n      return exprState.matches(conditionId,text,next)\n    }\n\n    fun setState( stateId:String ): StateValue? {\n      val ret = flush()\n      //log.debug( \"State = ${stateId} on pageNumber ${pageNumber}\" )\n      this.state = config.states[stateId] ?: throw Exception( \"Missing state ${stateId}\" )\n      this.stateId = stateId\n      return ret\n    }\n\n    /** Add the current text to the current state */\n    fun addText() {\n      buffer.add( text!! )\n      last = text\n\n      state.setVariables\n          .filter { it.name != null }\n          .forEach { vs:VariableSet ->\n            val value = getVariableValue( vs.value )\n            exprState.vars[vs.name!!] = value\n            eventListener?.onVariableSet( stateId, vs.name, value )\n            Unit\n          }\n    }\n\n    fun flush(): StateValue? {\n      val stateTexts:StateValue? = if ( buffer.isNotEmpty() ) {\n        StateValue(source,buffer.first().pageNumber, stateId, state, parseValues())\n      } else {\n        null\n      }\n      buffer.clear()\n      last = null\n\n      return stateTexts\n    }\n\n    private fun getVariableValue( value:String? ): String? =\n        if ( value == null ) {\n          null\n        } else if ( value.startsWith( \"{\" ) && value.endsWith( \"}\" ) ) {\n          exprState.vp[ value.drop(1).dropLast(1) ]?.toString()\n        } else {\n          value\n        }\n\n    /**\n     * Convert the Texts into Strings, combining them according to [State.combineLimit].\n     */\n    private fun parseValues(): List<Value> {\n      val values:MutableList<Value> = mutableListOf()\n\n      var last:Text? = null\n      for ( text in buffer ) {\n        if ( last != null && shouldCombine( last, text ) ) {\n          val lastValue = values.removeLast()\n          val content = \"${lastValue.text}${text.content}\"\n          val link = last.link\n          if ( text.link != null && text.link != link ) {\n            log.warn( \"Skipping link \\\"${text.link}\\\" from \\\"${text.content}\\\"; it does not overwrite link \\\"${link}\\\" from \\\"${lastValue.text}\\\"\")\n          }\n          values.add( Value( content, link ) )\n        } else {\n          values.add( Value(text.content,text.link) )\n        }\n        last = text\n      }\n\n      return values\n    }\n\n    private fun <T> MutableList<T>.removeLast(): T = removeAt( size-1 )\n\n    private val combineLimitMap:Map<String,Float?> by lazy {\n      val default:Float? = config.stateDefaults?.combineLimit\n      config.states.mapValues { (stateId,state) -> state.combineLimit ?: default }\n    }\n\n    private fun shouldCombine( last:Text, text:Text):Boolean {\n      val combineLimit:Float? = combineLimitMap[stateId]\n      return ( combineLimit != null ) && ( text.ulx - last.lrx <= combineLimit )\n    }\n\n\n  }\n\n  private fun parse( s:ParseState, text:Text? ): StateValue? {\n\n    // process sentinel\n    if ( text == null ) {\n      //log.debug( \"end of text sequence\" )\n      eventListener?.onFsmEnd()\n      return s.flush()\n    }\n\n    if ( text.content.isBlank() ) return null\n\n    //text.debug()\n    eventListener?.onText(text)\n\n    // excludes\n    if ( config.excludeConditions.isNotEmpty() ) {\n      for ( conditionId in config.excludeConditions ) {\n        if ( s.matches(conditionId,text) ) {\n          eventListener?.onExclude(text,conditionId)\n          s.text = s.lastText\n          return null\n        }\n      }\n    }\n\n    s.text = text\n\n    var ret:StateValue? = null // return value\n\n    // if pageNumber change, flush if newPageState is set\n    if ( text.pageNumber != ( s.lastText?.pageNumber ?: 1 ) && config.newPageState != null ) {\n      ret = s.setState( config.newPageState!! )\n      eventListener?.onPageStateChange(text.pageNumber, config.newPageState!! )\n    }\n\n    // find transition\n    var transition: Transition? = null\n    for (t in s.state.transitions) {\n      eventListener?.onCheckTransition(s.stateId,t.condition,t.nextState)\n      val match = s.matches(t.condition)\n      //log.debug(\"\\tcheck transition {${t.condition}} -> [${t.nextState}] : ${match}\")\n      eventListener?.onCheckTransition(s.stateId,t.condition,t.nextState,match, if ( match ) t.message else null )\n      if (match) {\n        if ( t.message != null ) {\n          log.warn( t.message )\n        }\n        transition = t\n        break\n      }\n    }\n    if (transition == null) {\n      throw Exception(\"Page ${text.pageNumber} at \\\"${text.content.t()}\\\" - no valid transition from ${s.stateId}\")\n    }\n\n    val nextStateId = transition.nextState\n\n    if ( nextStateId == s.stateId ) {\n      s.addText()\n    } else {\n      // state change\n\n      if ( ret != null ) {\n        // pageNumber transition happened\n        if ( s.lastText != null ) {\n          // texts were already added.\n          // Texts should not have been added.\n          throw Exception( \"BUG\" )\n        } else {\n          // PageNumber transition just happened, the new page state had nothing added to it.\n          // That's fine.\n          // Set the new state, but ignore the returned StateValue because it is empty\n          // (because of the page transition).\n          s.setState( nextStateId )\n          s.addText()\n        }\n      } else {\n        eventListener?.onStateChange(text.pageNumber, nextStateId)\n        ret = s.setState( nextStateId )\n        s.addText()\n      }\n\n    }\n\n    return ret\n  }\n\n  private fun boundsFilter( text:Text): Boolean {\n    // check header/footer/left/right\n\n    val top = getLimit( config.header, text.pageNumber )\n    if ( top != null && text.lry <= top ) {\n      eventListener?.onText(text)\n      eventListener?.onHeader(text)\n      return false\n    }\n\n    val bottom = getLimit( config.footer, text.pageNumber )\n    if ( bottom != null && text.uly >= bottom ) {\n      eventListener?.onText(text)\n      eventListener?.onFooter(text)\n      return false\n    }\n\n    val left = getLimit( config.left, text.pageNumber )\n    if ( left != null && text.lrx <= left ) {\n      eventListener?.onText(text)\n      eventListener?.onLeftMargin(text)\n      return false\n    }\n\n    val right = getLimit( config.right, text.pageNumber )\n    if ( right != null && text.ulx >= right ) {\n      eventListener?.onText(text)\n      eventListener?.onRightMargin(text)\n      return false\n    }\n\n    return true\n  }\n\n  private fun getLimit( rules:DefaultAndPages, pageNumber:Int ): Float? {\n    val s = if ( rules.pages.containsKey( pageNumber ) ) {\n      rules.pages[pageNumber]!!\n    } else {\n      rules.default\n    }\n    return s?.toFloat()\n  }\n\n  private fun Text.debug() {\n    log.debug(\"============================\")\n    log.debug(\"text: \\\"${content}\\\"\")\n    log.debug(\"\\tpageNumber: ${pageNumber} ul:[ ${ulx} , ${uly} ] lr: [ ${lrx} , ${lry} ]\")\n    log.debug(\"\\tfont: ${font} - ${fontSize}\")\n  }\n\n}\n\nprivate fun String?.t(l:Int = 20):String = when {\n  this == null -> \"\"\n  this.length <= l -> this\n  else -> this.take(l) + \"...\"\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/form/LoggingEventListener.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.form\n\nimport io.mfj.textricator.text.Text\nimport org.slf4j.LoggerFactory\n\nobject LoggingEventListener: FormParseEventListener {\n\n  private val log = LoggerFactory.getLogger( LoggingEventListener::class.java )\n\n  override fun onText(text:Text) {\n    if ( log.isDebugEnabled ) {\n      log.debug(\"============================\")\n      log.debug(\"text: \\\"${text.content}\\\"\")\n      log.debug(\"\\tpageNumber: ${text.pageNumber} ul:[ ${text.ulx} , ${text.uly} ] lr: [ ${text.lrx} , ${text.lry} ]\")\n      log.debug(\"\\tfont: ${text.font} - ${text.fontSize}\")\n      log.debug(\"\\tbgcolor: ${text.backgroundColor}\")\n      log.debug(\"\\tlink: ${text.link}\")\n    }\n  }\n\n  override fun onHeader(text:Text) {\n    log.debug(\"\\tpart of header. skip\")\n  }\n\n  override fun onFooter(text:Text) {\n    log.debug(\"\\tpart of footer. skip\")\n  }\n\n  override fun onLeftMargin(text:Text) {\n    log.debug(\"\\tpart of left gutter. skip\")\n  }\n\n  override fun onRightMargin(text:Text) {\n    log.debug(\"\\tpart of right gutter. skip\")\n  }\n\n  override fun onExclude(text: Text, condition: String) {\n    log.debug(\"\\texcluded by condition \\\"${condition}\\\"\")\n  }\n\n  override fun onCheckTransition(currentState:String, condition:String, nextState:String) {\n    log.debug(\"\\tcheck transition \\\"${condition}\\\" (\\\"${currentState}\\\" -> \\\"${nextState}\\\")...\")\n  }\n\n  override fun onNoPrevious(source:String) {\n    log.debug(\"\\t\\tno previous [${source}]\")\n  }\n\n  override fun onCheckTransition(currentState:String, condition:String, nextState:String, match:Boolean, message:String?) {\n    log.debug(\"\\t\\t${match} ${if (message != null) \" (${message})\" else \"\" }\")\n  }\n\n  override fun onCheckCondition(source:String, description:String, match:Boolean) {\n    log.debug(\"\\t\\tcheck condition [${source}] ${description} : ${match}\" )\n  }\n\n  override fun onPageStateChange(page:Int, state:String) {\n    log.debug( \"State = ${state} (page:${page} reset)\" )\n  }\n\n  override fun onStateChange(page:Int, state:String) {\n    log.debug( \"State = ${state} (page:${page})\" )\n  }\n\n  override fun onVariableSet(currentState:String, name:String, value:String?) {\n    log.debug( \"Variable ${name} = ${if ( value != null ) \"\\\"${value}\\\"\" else \"null\" }\" )\n  }\n\n  override fun onFsmEnd() {\n    log.debug( \"fsm end\" )\n  }\n\n  override fun onRecordsEnd() {\n    log.debug( \"records end\" )\n  }\n\n  override fun onStateValue(sv:StateValue) {\n    log.debug( \"parse StateValue: ${sv.stateId} : ${sv.values}\" )\n  }\n\n  override fun onNewRecord(typeId:String) {\n    log.debug( \"\\tnew ${typeId} record\" )\n  }\n\n  override fun onRecordAppend(typeId:String) {\n    log.debug( \"\\tadd to ${typeId} record\" )\n  }\n\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/form/RecordParser.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.form\n\nimport io.mfj.textricator.record.Record\nimport io.mfj.textricator.record.calculateValue\nimport io.mfj.textricator.form.config.FormParseConfig\nimport io.mfj.textricator.form.config.State\nimport io.mfj.textricator.record.Value\n\nimport java.util.*\n\n/**\n * Parses a sequence of StateValue\n * (probably the output of [FsmParser])\n * to a sequence of Record according to the config.\n *\n * @param config FormParseConfig\n */\nclass RecordParser( private val config:FormParseConfig, private val eventListener:RecordParserEventListener? =null ) {\n\n  fun parse( seq:Sequence<StateValue> ): Sequence<Record> {\n    val parseState = ParseState()\n\n    return seq\n        .map { stateTexts -> split(stateTexts) }.flatten()\n        .map { stateValue -> splitValueTypes(stateValue) }.flatten()\n        .plus( null as StateValue? ) // sentinel\n        .mapNotNull { stateTexts ->\n          parse( parseState, stateTexts )\n        }\n  }\n\n  /**\n   * If [State.startRecordForEachValue], split the StateValue\n   * so parse can create new records for each\n   */\n  private fun split( st:StateValue): List<StateValue> =\n      if ( st.state.startRecordForEachValue ) {\n        st.values.map { value ->\n          StateValue(st.source, st.pageNumber, st.stateId, st.state, listOf(value), false )\n        }\n      } else {\n        listOf( st )\n      }\n\n  /**\n   * If a State goes to multiple value types, split it\n   * into one for each value type.\n   */\n  private fun splitValueTypes(st:StateValue): List<StateValue> =\n      st.state.valueTypes\n          ?.mapIndexed { index, valueTypeId ->\n            val state = st.state.copy( valueTypes = mutableListOf( valueTypeId ) )\n            StateValue(st.source, st.pageNumber, st.stateId, state, st.values, (index > 0))\n          }\n          ?: listOf( st )\n\n  private class ParseState {\n    val stateStack: Stack<Pair<String,Boolean>> = Stack() // <stateId,isNewRecord>\n    var root: Record? = null\n\n    // map of record to its member valueTypes.\n    // We build this up as a list of strings, then collapse it to a single string before returning.\n    // see extension function Record.setValueTypes()\n    // Using IdentityHashMap is important - we need to distinguish between equal empty Records.\n    val buffer: MutableMap<Record,MutableMap<String,MutableList<Value>>> = IdentityHashMap()\n  }\n\n  private fun parse( s:ParseState, st:StateValue? ): Record? {\n\n    if ( st == null ) {\n      //log.debug( \"end of states\" )\n      eventListener?.onRecordsEnd()\n      // sentinel\n      return s.root?.setValues(s)\n    }\n\n    //log.debug( \"parse ${st.state} - ${st.valueTypes}\" )\n    eventListener?.onStateValue( st )\n\n    // figure out if we should start a new record\n    val newRecord = ( ! st.splitContinuation ) && isNewRecord( s, st.stateId )\n\n    if ( newRecord ) {\n      s.stateStack.popThrough { it.second && it.first == st.stateId }\n    }\n    s.stateStack.push( Pair( st.stateId, newRecord ) )\n\n    // return value, if a new record is started return the current root\n    var ret:Record? = null\n\n    // have to check this *after* the call to s.stateStack.push() so this state goes in the stack, even if not used.\n    if ( st.state.include ) {\n\n      // there is only one because of splitValueTypes()\n      val valueTypeId:String = st.state.valueTypes?.get(0) ?: st.stateId\n\n      // find the type the contains this state\n      val recordTypeId:String = findRecordTypeId( valueTypeId )\n\n      // if new\n      val rec:Record = if ( newRecord ) {\n\n        // if the type is root\n        val rec:Record = if ( recordTypeId == config.rootRecordType) {\n\n          // return the old one and start a new root\n          ret = s.root?.setValues(s)\n          s.buffer.clear()\n          s.root = Record(st.source, st.pageNumber, recordTypeId)\n          s.root!!\n\n        } else {\n          // find the parent record\n          val parent = findParentRecord( s, st.source, st.pageNumber, recordTypeId )\n\n          // start a new record\n          val rec = Record(st.source, st.pageNumber, recordTypeId)\n          parent.children.getOrPut( recordTypeId, { mutableListOf() } ).add( rec )\n          rec\n        }\n\n        //log.debug( \"new ${rec.typeId} record\" )\n        eventListener?.onNewRecord(rec.typeId)\n        rec\n\n      } else {\n        if ( s.root == null ) {\n          // not explicitly starting a new record, but no record exists.\n          // create a new root to add to.\n          // TODO is this okay?\n          s.root = Record(st.source, st.pageNumber, config.rootRecordType)\n        }\n\n        // find the root\n        val rec = findRecord( s.root!!, recordTypeId )\n        //log.debug( \"add to ${rec.typeId} record\" )\n        eventListener?.onRecordAppend( rec.typeId )\n        rec\n      }\n\n      // add data\n      s.buffer\n          .getOrPut( rec, {mutableMapOf()} )\n          .getOrPut( valueTypeId, {mutableListOf()} )\n          .addAll( st.values )\n    }\n\n    return ret\n  }\n\n  private val valueTypes = config.valueTypes\n\n  /**\n   * Set the valueTypes of the members from the buffer.\n   */\n  private fun Record.setValues( s:ParseState):Record {\n    val recBuffer = s.buffer.get(this)\n    if ( recBuffer != null ) {\n      recBuffer.forEach { valueTypeId, values ->\n        val value = valueTypes[valueTypeId].calculateValue(values)\n        this.values[valueTypeId] = value\n      }\n    }\n    this.children.forEach { childRecordTypeId, children ->\n      children.forEach { child ->\n        child.setValues(s)\n      }\n    }\n    return this\n  }\n\n\n  private fun isNewRecord( s:ParseState, stateId:String ): Boolean {\n\n    // Decide if a new record should be started\n\n    // It is more complex than just \"does this state start a new record\", because of this case:\n    // Imagine PDF that has records that look like this:\n\n    // Jonathan Zachary\t\t\t  Defendant pled to something or other blah blah blah says he didn't mean to blah blah\n    // Johnson\t\t\t\t\t\t\t  hurt anybody blah blah blah blah blah blah blah blah blah police brutality blah blah\n    //                        blah waste of taxpayer money blah blah only 2 ounces blah blah blah blah blah blah\n    // Case Type: F\t\t\t\t\t\tblah.\n    //\n    // John Doe\t\t\t\t\t\t\t\tThis is the next record blah blah blah\n\n    // \"Johnson\" on the 2nd line is part of the name, so we transition from the \"notes\" (the explanation at the right)\n    // state to the \"name\" state, but we should not start a new record as you would transitioning from \"notes\" for\n    // \"so windy\" to \"name\" for \"John Doe\"\n    // The way we handle this is to require entering a specific state (i.e. case_type) before starting a new record.\n\n    // 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)\n\n    // \"Jonathon Zackary\" - push \"name\"/true\n    // \"Defendant pled....\" - push \"notes\"/false\n    // \"Johnson\" - push \"name\"/false\n    // \"hurt anybody...\" - push \"notes\"/false\n    // \"blah waste...\" - push \"notes\"/false\n    // \"F\" - push \"case_type\"/false\n    // \"blah.\" - push \"notes\"/false\n    // \"John Doe\" - start new record, pop through last \"name\"/true (from \"Jonathon Zackary\"), push \"name\"/true\n\n    val state = config.states[stateId] ?: throw Exception( \"Missing state \\\"${stateId}\\\"\" )\n\n    if ( state.startRecordForEachValue ) return true\n\n    return state.startRecord && ( state.startRecordRequiredState == null\n        || s.stateStack.hasIntermediateState( state.startRecordRequiredState ) )\n  }\n\n  /** Map of value type ID to record type ID of the record that contains the value */\n  private val valueTypeIdToRecordTypeId:Map<String,String> by lazy {\n    val m:MutableMap<String,String> = mutableMapOf()\n    config.recordTypes.forEach { ( recordTypeId, recordType ) ->\n      recordType.valueTypes.forEach { valueTypeId ->\n        m.put( valueTypeId, recordTypeId )\n      }\n    }\n    m\n  }\n\n  private fun findRecordTypeId( valueTypeId:String ): String {\n    return valueTypeIdToRecordTypeId[valueTypeId] ?: throw Exception( \"No type containing value type \\\"${valueTypeId}\\\"\" )\n  }\n\n  /**\n   * Map of parent record type to\n   * ( map of record type to which child of the parent record type contains the type )\n   *\n   * e.g.:\n   * data record types:\n   *         A\n   *       /  \\\n   *     B     C\n   *    / \\  /  \\\n   *   D  E  F  G\n   *  / \\\n   * H  I\n   *\n   * will result in:\n   *  {\n   * \t\tA: {\n   * \t  \tB > B, D > B, E > B, H > B, I > B,\n   * \t\t  C > C, F > C, G > C\n   * \t\t},\n   * \t  B: {\n   * \t  \tD > D, H > D, I > D,\n   * \t  \tE > E\n   * \t  }\n   * \t  D: {\n   *      H > H,\n   *      I > I\n   * \t  },\n   * \t  C: {\n   *      F > F,\n   *      G > G\n   * \t  }\n   *  }\n   */\n  private val recordTypeToDescendantToChild:Map<String,Map<String,String>> by lazy {\n    config.recordTypes.mapValues { ( _, type ) ->\n\n      // descendant to child of type\n      val m:MutableMap<String,String> = mutableMapOf()\n\n      fun add( childTypeId:String, descendantTypeId:String ) {\n        m.put( descendantTypeId, childTypeId )\n        val descendantType = config.recordTypes[descendantTypeId] ?: throw Exception( \"Missing type \\\"${descendantTypeId}\\\"\" )\n        descendantType.children.forEach { furtherDescendantTypeId ->\n          add( childTypeId, furtherDescendantTypeId )\n        }\n      }\n\n      type.children.forEach { childTypeId ->\n        add( childTypeId, childTypeId )\n      }\n\n      m\n    }\n  }\n\n  private infix fun String.findAncestorThatIsAChildOf( parent:String ): String? {\n    val childRecordTypeId = recordTypeToDescendantToChild[parent]?.get( this )\n    return childRecordTypeId\n  }\n  // wrapper for unit tests\n  internal fun findAncestorThatIsAChildOf( type:String, parent:String ) = type findAncestorThatIsAChildOf parent\n\n  /**\n   * Find the Record for the typeId under the supplied root, creating child recs if necessary\n   */\n  private fun findRecord( rec:Record, recordTypeId:String ):Record {\n    if ( rec.typeId == recordTypeId ) {\n      // this is it\n      return rec\n    } else {\n      val childTypeId = recordTypeId findAncestorThatIsAChildOf rec.typeId\n      if ( childTypeId != null ) {\n        // the desired record is either this child type or under it\n        val children:MutableList<Record> = rec.children.getOrPut( childTypeId, { mutableListOf() } )\n        if ( children.isEmpty() ) {\n          children.add(Record(rec.source, rec.pageNumber, childTypeId))\n        }\n        return findRecord( children.last(), recordTypeId )\n      } else {\n        throw Exception( \"Cannot find record of type \\\"${recordTypeId}\\\" (under \\\"${rec.typeId}\\\")\" )\n      }\n    }\n  }\n\n  private fun findParentRecord( s:ParseState, source:String?, pageNumber:Int, recordTypeId:String ):Record {\n    if ( s.root == null ) {\n      s.root = Record(source, pageNumber, config.rootRecordType)\n    }\n    return findParentRecord( s.root!!, recordTypeId )\n  }\n\n  /**\n   * Find the parent root for the recordTypeId under the supplied root, creating child recs if necessary\n   */\n  private fun findParentRecord( rec:Record, recordTypeId:String ):Record {\n    if ( rec.typeId == recordTypeId) {\n      throw Exception( \"rec is type \\\"${recordTypeId}\\\"\" )\n    } else {\n\n      if ( rec.children.containsKey(recordTypeId) ) return rec // optimization\n\n      val childRecordTypeId = recordTypeId findAncestorThatIsAChildOf rec.typeId\n      if ( childRecordTypeId != null ) {\n        // the desired type is either this child type or under it\n\n        if ( childRecordTypeId == recordTypeId) {\n          // the desired type is this child type; return the parent\n          return rec\n        } else {\n          // the desired type is a child of the child type\n          val children:MutableList<Record> = rec.children.getOrPut( childRecordTypeId, { mutableListOf() } )\n          if ( children.isEmpty() ) {\n            children.add(Record(rec.source, rec.pageNumber, childRecordTypeId))\n          }\n          val last = children.last()\n          return if ( last.typeId == recordTypeId) {\n            rec\n          } else {\n            findParentRecord( last, recordTypeId)\n          }\n        }\n\n      } else {\n        throw Exception( \"Cannot find record of type \\\"${recordTypeId}\\\" (under \\\"${rec.typeId}\\\")\" )\n      }\n    }\n  }\n\n}\n\n/**\n * Determine if the state stack has the specified state since the latest new record.\n * If the latest new record is the latest record to have the specified state, returns false.\n */\nfun Stack<Pair<String,Boolean>>.hasIntermediateState( state:String ): Boolean {\n  val i = listIterator(size)\n  while ( i.hasPrevious() ) {\n    val p = i.previous()\n    if ( p.second ) return false\n    if ( p.first == state ) return true\n  }\n  return false\n}\n\n/**\n * Remove elements until an element matches the given predicate.\n */\nfun <T> Stack<T>.popUntil( predicate: (T)->Boolean ) {\n  while ( ! isEmpty() && ! predicate( peek() ) ) pop()\n}\n\n/**\n * Remove elements until an element matches the given predicate, and remove that element too.\n */\nfun <T> Stack<T>.popThrough( predicate: (T)->Boolean ) {\n  popUntil( predicate )\n  if ( ! isEmpty() && predicate( peek() ) ) pop()\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/form/RecordParserEventListener.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.form\n\ninterface RecordParserEventListener {\n\n  fun onRecordsEnd()\n\n  fun onStateValue( sv:StateValue)\n\n  fun onNewRecord( typeId:String )\n\n  fun onRecordAppend( typeId:String )\n\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/form/StateValue.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.form\n\nimport io.mfj.textricator.form.config.State\nimport io.mfj.textricator.record.Value\n\n/**\n * @param pageNumber The pageNumber that the state started on.\n */\ndata class StateValue( val source:String?, val pageNumber:Int, val stateId:String, val state:State, val values:List<Value>,\n    val splitContinuation:Boolean=false )\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/form/WriterEventListener.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.form\n\nimport io.mfj.textricator.text.Text\n\nimport java.io.Writer\n\nimport org.slf4j.LoggerFactory\n\nclass WriterEventListener(private val w:Writer): FormParseEventListener {\n\n  private val log = LoggerFactory.getLogger(LoggingEventListener::class.java)\n\n  override fun onText(text:Text) {\n    write(\"============================\")\n    write(\"text: \\\"${text.content}\\\"\")\n    write(\"\\tpageNumber: ${text.pageNumber} ul:[ ${text.ulx} , ${text.uly} ] lr: [ ${text.lrx} , ${text.lry} ]\")\n    write(\"\\tfont: ${text.font} - ${text.fontSize}\")\n    write(\"\\tbgcolor: ${text.backgroundColor}\")\n  }\n\n  override fun onHeader(text:Text) {\n    write(\"\\tpart of header. skip\")\n  }\n\n  override fun onFooter(text:Text) {\n    write(\"\\tpart of footer. skip\")\n  }\n\n  override fun onLeftMargin(text:Text) {\n    write(\"\\tpart of left gutter. skip\")\n  }\n\n  override fun onRightMargin(text:Text) {\n    write(\"\\tpart of right gutter. skip\")\n  }\n\n  override fun onExclude(text: Text, condition: String) {\n    write(\"\\texcluded by condition \\\"${condition}\\\"\")\n  }\n\n  override fun onCheckTransition(currentState:String, condition:String, nextState:String) {\n    write(\"\\tcheck transition \\\"${condition}\\\" (\\\"${currentState}\\\" -> \\\"${nextState}\\\")...\")\n  }\n\n  override fun onCheckTransition(currentState:String, condition:String, nextState:String, match:Boolean, message:String?) {\n    write(\"\\t\\t${match} ${if (message != null) \" (${message})\" else \"\" }\")\n  }\n\n  override fun onNoPrevious(source:String) {\n    write(\"\\t\\tno previous [${source}]\")\n  }\n\n  override fun onCheckCondition(source:String, description:String, match:Boolean) {\n    write(\"\\t\\tcheck condition [${source}] ${description} : ${match}\" )\n  }\n\n  override fun onPageStateChange(page:Int, state:String) {\n    write( \"State = ${state} (page:${page} reset)\" )\n  }\n\n  override fun onStateChange(page:Int, state:String) {\n    write( \"State = ${state} (page:${page})\" )\n  }\n\n  override fun onVariableSet(currentState:String, name:String, value:String?) {\n    write( \"Variable ${name} = ${if ( value != null ) \"\\\"${value}\\\"\" else \"null\" }\" )\n  }\n\n  override fun onFsmEnd() {\n    write( \"fsm end\" )\n  }\n\n  override fun onRecordsEnd() {\n    write( \"records end\" )\n  }\n\n  override fun onStateValue(sv:StateValue) {\n    write( \"parse StateValue: ${sv.stateId} : ${sv.values}\" )\n  }\n\n  override fun onNewRecord(typeId:String) {\n    write( \"\\tnew ${typeId} record\" )\n  }\n\n  override fun onRecordAppend(typeId:String) {\n    write( \"\\tadd to ${typeId} record\" )\n  }\n\n\n  var writes:Long = 0\n\n  private fun write( s:String ) {\n    try {\n      w.appendLine(s)\n      if ( writes++ % 100L == 0L ) w.flush()\n    } catch ( e:Exception ) {\n      log.error(e.message,e)\n    }\n  }\n\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/form/config/DefaultAndPages.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.form.config\n\n/**\n * A class to contain a default value along with page specific values which override the default on a given page.\n */\ndata class DefaultAndPages(val default: String? = null,val pages: Map<Int, String> = mapOf())\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/form/config/FormParseConfig.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.form.config\n\nimport io.mfj.textricator.record.RecordModel\nimport io.mfj.textricator.record.RecordType\nimport io.mfj.textricator.extractor.TextExtractorOptions\nimport io.mfj.textricator.record.ValueType\n\n/**\n * Defines the state machine\n */\nclass FormParseConfig(\n    var states: MutableMap<String, State> = mutableMapOf(),\n    var stateDefaults: State? = null,\n    var conditions: MutableMap<String, String> = mutableMapOf(),\n    var initialState: String = \"INITIAL_STATE\",\n    var newPageState: String? = null,\n    var header:DefaultAndPages = DefaultAndPages(),\n    var footer:DefaultAndPages = DefaultAndPages(),\n    var left:DefaultAndPages = DefaultAndPages(),\n    var right:DefaultAndPages = DefaultAndPages(),\n    override var rootRecordType: String = \"root\",\n    override var recordTypes: Map<String, RecordType> = emptyMap(),\n    override var valueTypes: Map<String, ValueType> = emptyMap(),\n    /** Any [Text]s that match any of these condition names (the key in [conditions])\n     *  are excluded; never processed by the finite-state machine. */\n    var excludeConditions: List<String> = emptyList(),\n    extractor:String? = null,\n    pages:String? = null,\n    maxRowDistance:Float = 0f,\n    boxPrecision:Float =0f,\n    boxIgnoreColors:MutableSet<String> = mutableSetOf()\n): TextExtractorOptions(\n    extractor = extractor,\n    boxPrecision =  boxPrecision,\n    boxIgnoreColors = boxIgnoreColors,\n    maxRowDistance = maxRowDistance,\n    pages = pages ), RecordModel\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/form/config/FormParseConfigUtil.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.form.config\n\nimport java.io.File\nimport java.io.InputStream\n\nimport com.fasterxml.jackson.databind.ObjectMapper\nimport com.fasterxml.jackson.dataformat.yaml.YAMLFactory\nimport com.fasterxml.jackson.module.kotlin.*\n\nobject FormParseConfigUtil {\n\n  private val mapper = ObjectMapper(YAMLFactory()).registerKotlinModule()\n\n  fun parseYaml(file: File):FormParseConfig = parseYaml(file.readText())\n\n  fun parseYaml(input:InputStream):FormParseConfig = mapper.readValue(input)\n\n  fun parseYaml(text:String):FormParseConfig = mapper.readValue(text)\n\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/form/config/State.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.form.config\n\nimport java.util.*\n\n/**\n * A state in the state machine\n */\n\ndata class State(\n    /** If true, remove text in this state before record processing. */\n    val skip:Boolean = false,\n    /** If false, do not create records for this state, but still include it in record processing\n     * so it can split adjacent states and affect if the next sibling starts a record. */\n    val include:Boolean = true,\n    val transitions: MutableList<Transition> = ArrayList(),\n    val startRecord: Boolean = false,\n    val startRecordRequiredState: String? = null,\n    val startRecordForEachValue:Boolean = false,\n    val valueTypes: MutableList<String>? = null,\n    val combineLimit: Float? = null,\n    val setVariables: MutableList<VariableSet> = mutableListOf()\n)\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/form/config/Transition.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.form.config\n\n/**\n * Defines a transition, consisting of a condition ID, the id of the next node and a unique id for this transition\n */\n\ndata class Transition(val condition: String, val nextState: String, val message:String? = null)\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/form/config/VariableSet.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.form.config\n\ndata class VariableSet( val name:String? = null, var value:String? = null )\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/record/Record.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.record\n\nimport java.beans.Transient\n\n// cannot be a data class, because used as a map key in RecordParser.\nclass Record(\n    val source:String?=null,\n    val pageNumber:Int,\n    val typeId:String,\n    val values:MutableMap<String,Value> = mutableMapOf(),\n    val children:MutableMap<String,MutableList<Record>> = mutableMapOf()\n) {\n\n  constructor(\n    pageNumber:Int,\n    typeId:String,\n    values:MutableMap<String,Value> = mutableMapOf(),\n    children:MutableMap<String,MutableList<Record>> = mutableMapOf()\n  ) : this(null,pageNumber,typeId,values,children)\n\n  val isLeaf:Boolean\n    @Transient\n    get() {\n      children.values.forEach { childList ->\n        if ( childList.isNotEmpty() ) {\n          return false\n        }\n      }\n      return true\n    }\n\n  fun getValue( valueTypeId:String, attribute:String? ): String? = values[valueTypeId]?.getValue(attribute)\n\n  override fun hashCode():Int = pageNumber + typeId.hashCode() + 17 * values.size + 27 * children.size\n\n  override fun equals(other:Any?):Boolean = ( other != null ) && ( other is Record) &&\n      pageNumber == other.pageNumber && typeId == other.typeId &&\n      values.size == other.values.size && children.size == other.children.size &&\n      values == other.values && children == other.children\n\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/record/RecordFilter.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.record\n\nimport io.mfj.expr.*\n\n/**\n * Filters records based on [RecordType.filter].\n *\n * @param config FormParseConfig\n */\nclass RecordFilter( private val config:RecordModel) {\n\n  companion object {\n    private val DEFAULT_TYPE:ExDataType = ExDataType.STRING\n  }\n\n  fun filter( seq:Sequence<Record> ): Sequence<Record> =\n      seq.mapNotNull { record ->\n        filter( record )\n      }\n\n  /** Map of value type id to ExDataType */\n  private val valueTypeMap = config.valueTypes.map { (id,member) ->\n    id to ( member.type?.let { ExDataType.valueOf( it.uppercase() ) } ?: DEFAULT_TYPE)\n  }.toMap()\n\n  /** Get the ExDataType for the specified member. */\n  private fun getExDataType( valueTypeId:String ) = valueTypeMap[valueTypeId] ?: DEFAULT_TYPE\n\n  /** Map of record type ID to the Expr to filter it, or null if no filter. */\n  private val recordTypeToExpr:Map<String,Expr?> =\n      config.recordTypes.entries\n          .associate { (recordTypeId, recordType) ->\n            recordTypeId to buildExpr(recordType)\n          }\n\n  /**\n   * Build Expr for the specified record type. Null if no filter.\n   */\n  private fun buildExpr( type:RecordType): Expr? {\n    val filter = type.filter\n    return if ( filter != null ) {\n      val vtp:VarTypeProvider = object:VarTypeProvider {\n        override fun contains(varName:String):Boolean = type.valueTypes.contains(varName)\n        override fun get(varName:String):ExDataType =\n            if ( type.valueTypes.contains(varName) ) {\n              getExDataType( varName )\n            } else {\n              throw IllegalArgumentException( \"No such var \\\"${varName}\\\"\" )\n            }\n        override fun getKnownVars():Map<String, ExDataType> =\n            type.valueTypes.associateWith { getExDataType(it) }\n      }\n      ExprParser.parseToExpr( filter, vtp )\n    } else {\n      null\n    }\n  }\n\n  /**\n   * Filter the supplied record.\n   * If the record's type's filter passes, return the record with the children also filtered.\n   * If the record's type's filter does not pass, return null.\n   */\n  private fun filter( record:Record): Record? {\n    return if ( evalFilter( record ) ) {\n      filterChildren( record )\n      record\n    } else {\n      null\n    }\n  }\n\n  /**\n   * Filter the children of the supplied record.\n   */\n  private fun filterChildren( record:Record) {\n    record.children.values.forEach { children ->\n      children.retainAll { child ->\n        evalFilter( child )\n      }\n      children.forEach { child ->\n        filterChildren( child )\n      }\n    }\n  }\n\n  /**\n   * Evaluate the filter for the specified record.\n   */\n  private fun evalFilter( record:Record): Boolean =\n      recordTypeToExpr[record.typeId]\n          ?.value(\n              object:VarProvider {\n                override fun contains(varName:String):Boolean = record.values.contains( varName )\n                override fun get(varName:String):Any? {\n                  val exDataType = getExDataType(varName)\n                  val s = record.values[varName]?.text // TODO filter based on other attributes\n                  return ExConvert.convertStr( s, exDataType )\n                }\n                override fun getKnownVars():Set<String> = record.values.keys\n              }\n          )\n          ?: true // accept if no filter\n\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/record/RecordModel.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.record\n\n/**\n * Defines the state machine\n */\ninterface RecordModel {\n  val rootRecordType: String\n  val recordTypes: Map<String, RecordType>\n  val valueTypes: Map<String, ValueType>\n}\n\ndata class RecordType(\n    var label: String, // user defined name\n    var children: List<String> = emptyList(), // List of child RecordType's ids\n    var valueTypes: List<String> = emptyList(), // List of the data and cell leaf states at this level.\n    var pagePriority: Int = 0, // for output, use the page from the type with the highest priority\n    var filter:String? = null\n)\n\nopen class ValueType(\n    val label:String? = null,\n\n    /** If true, remove duplicate values. */\n    val unrepeat:Boolean = false,\n\n    /** Separator when combining values. Values are combined after unrepeating */\n    val separator:String = \" \",\n\n    /** Replacements to make. Replacements are mae after values are unrepeated and combined. */\n    val replacements:MutableList<PatternReplacement>? = null,\n\n    /** If false, do not include in output.\n     * Useful when the same data is repeated for each child record and you need it to mark new records. */\n    val include:Boolean = true,\n\n    /** If set, use this attribute of [Value] instead of [Value.text]. */\n    val attribute:String? =null,\n\n    /** Data type (used for [RecordType.filter]). */\n    val type:String? = null // ExDataType\n\n) {\n\n  fun calcValue( values:List<Value> ): Value {\n    val text = values\n        .map(Value::text)\n        .unrepeat()\n        .joinToString(separator)\n        .replace()\n    val link = values\n        .asSequence()\n        .mapNotNull(Value::link)\n        .firstOrNull()\n    return Value(text,link)\n  }\n\n  private fun List<String>.unrepeat(): List<String> {\n    if ( ! unrepeat ) return this\n    (1..size).forEach { i ->\n      if ( isRepeated( this, i ) ) {\n        return this.subList(0,i).unrepeat()\n      }\n    }\n    return this\n  }\n\n  private fun isRepeated( list:List<String>, pos:Int ): Boolean {\n    if ( list.size < pos*2 ) return false\n    (0 until pos).forEach { i ->\n      if ( list[i] != list[pos+i] ) {\n        return false\n      }\n    }\n    return true\n  }\n\n  private fun String.replace(): String {\n    // if there's no replacements, return the original string\n    if ( replacements == null) {\n      return this\n    } else {\n      // otherwise check all possible regex patterns for a match\n      replacements.forEach { r ->\n        // if the string matches a pattern, replace it with the regex replacement and return\n        if ( r.regexPattern.containsMatchIn( this ) ) {\n          return r.regexPattern.replace(this, r.replacement)\n        }\n      }\n    }\n\n    // if the string matched no patterns, return the original string\n    return this\n  }\n\n}\n\nprivate fun List<Value>.join(separator:String):Value {\n  val text = map(Value::text).joinToString(separator)\n  val link = asSequence().mapNotNull(Value::link).firstOrNull()\n  return Value(text,link)\n}\n\nfun ValueType?.calculateValue( values:List<Value> ): Value =\n    this?.calcValue(values) ?: values.join(\" \")\n\ndata class PatternReplacement(val pattern:String, val replacement:String ) {\n  // lazy property to make regex from pattern\n  val regexPattern by lazy {\n    Regex(pattern)\n  }\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/record/Value.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.record\n\ndata class Value(\n\t\tval text:String,\n\t\tval link:String? = null\n) {\n\tfun getValue( attribute:String? ): String? =\n\t\t\twhen(attribute) {\n\t\t\t\tnull -> text\n\t\t\t\t\"link\" -> link\n\t\t\t\telse -> throw IllegalArgumentException(\"Unhandled attribute \\\"${attribute}\\\".\" )\n\t\t\t}\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/record/output/CsvRecordOutput.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.record.output\n\nimport org.apache.commons.csv.*\n\nimport io.mfj.textricator.record.Record\nimport io.mfj.textricator.record.RecordModel\nimport io.mfj.textricator.record.RecordType\n\nimport java.io.BufferedWriter\nimport java.io.OutputStream\nimport java.io.OutputStreamWriter\n\nimport kotlinx.coroutines.channels.ReceiveChannel\n\nclass CsvRecordOutput(private val config:RecordModel, output:OutputStream,\n  private val includeSource:Boolean=false ):RecordOutput {\n\n  private val w = BufferedWriter(OutputStreamWriter(output))\n\n  private val valueTypes = config.valueTypes\n\n  val p = CSVPrinter(w, CSVFormat.DEFAULT.withRecordSeparator(\"\\n\"))\n\n  var rowCount = 0\n\n  override fun write( seq:Sequence<Record> ) {\n    printHeader(p)\n    seq.forEach { rec -> printRows(p,rec) }\n  }\n\n  override suspend fun write(channel:ReceiveChannel<Record>) {\n    printHeader(p)\n    for ( rec in channel ) {\n      printRows(p,rec)\n    }\n  }\n\n  override fun close() {\n    p.flush()\n    // do NOT close p, the caller is responsible for closing w, and that is all that p.close() does.\n    //p.close()\n    w.close()\n  }\n\n  private fun printHeader(p:CSVPrinter) {\n\n    if ( includeSource ) p.print(\"source\")\n    p.print(\"page\")\n\n    fun printType( recordType:RecordType) {\n      recordType.valueTypes.forEach { valueTypeId ->\n        val valueType = valueTypes[valueTypeId]\n        if ( valueType?.include ?: true ) {\n          val label = valueType?.label ?: valueTypeId\n          p.print( label )\n        }\n      }\n      recordType.children\n          .map { config.recordTypes[it] ?: throw Exception(\"missing type ${it}\") }\n          .forEach { childRecordType ->\n            printType( childRecordType )\n          }\n    }\n    val rootRecordType = config.recordTypes[config.rootRecordType] ?: throw Exception(\"missing type ${config.rootRecordType}\")\n    printType(rootRecordType)\n\n    p.println()\n  }\n\n  private fun printRows(p:CSVPrinter,root:Record) {\n\n    val map:MutableMap<RecordType, Record> = mutableMapOf()\n\n    fun pr(rec:Record) {\n      val type = config.recordTypes[rec.typeId] ?: throw Exception( \"Missing type ${rec.typeId}\" )\n      map[type] = rec\n\n      if ( rec.isLeaf ) {\n        printRow(p,map)\n      } else {\n        rec.children.values.forEach { it.forEach { pr(it) } }\n      }\n\n      map.remove(type)\n    }\n\n    pr(root)\n  }\n\n  private fun printRow( p:CSVPrinter, map:Map<RecordType, Record> ) {\n\n    val cells:MutableList<Any> = mutableListOf()\n\n    var pageNumber:Int? = null\n    var pageNumberPriority:Int = -1\n\n    fun printType( recordType:RecordType) {\n      val rec = map[recordType]\n\n      if ( ( rec != null ) && ( pageNumber == null || recordType.pagePriority > pageNumberPriority ) ) {\n        pageNumber = rec.pageNumber\n        pageNumberPriority = recordType.pagePriority\n      }\n\n      recordType.valueTypes.forEach { valueTypeId ->\n        val valueType = valueTypes[valueTypeId]\n        if ( valueType?.include ?: true ) {\n          val attribute = valueType?.attribute\n          val value = rec?.getValue(valueTypeId,attribute) ?: \"\"\n          cells.add( value )\n        }\n      }\n      recordType.children\n          .map { config.recordTypes[it] ?: throw Exception(\"missing type ${it}\") }\n          .forEach { childRecordType ->\n            printType( childRecordType )\n          }\n    }\n    val rootRecordType = config.recordTypes[config.rootRecordType] ?: throw Exception(\"missing type ${config.rootRecordType}\")\n\n    printType(rootRecordType)\n\n    if ( includeSource ) p.print( map[rootRecordType]!!.source )\n    p.print( pageNumber )\n    p.printRecord( cells )\n\n    if ( rowCount++ % 100 == 0 ) p.flush()\n  }\n\n\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/record/output/JsonFlatRecordOutput.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.record.output\n\nimport io.mfj.textricator.record.Record\nimport io.mfj.textricator.record.RecordModel\nimport io.mfj.textricator.record.RecordType\nimport io.mfj.textricator.record.ValueType\n\nimport java.io.BufferedWriter\nimport java.io.OutputStream\nimport java.io.OutputStreamWriter\n\nimport java.util.concurrent.atomic.AtomicBoolean\n\nimport com.fasterxml.jackson.core.JsonGenerator\nimport com.fasterxml.jackson.databind.ObjectMapper\nimport kotlinx.coroutines.channels.ReceiveChannel\n\nclass JsonFlatRecordOutput(private val config:RecordModel, output:OutputStream, private val includeSource:Boolean):\n    RecordOutput {\n\n  private val w = BufferedWriter(OutputStreamWriter(output))\n\n  private val valueTypes = config.valueTypes\n\n  private val writer = ObjectMapper()\n      .configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET,false) // otherwise closes w\n      .writer().withDefaultPrettyPrinter()\n\n  var printHeader = true\n\n  override fun write( seq:Sequence<Record> ) {\n\n    w.append( \"[\" )\n\n    val notFirst = AtomicBoolean(false)\n\n    if ( printHeader ) {\n      printHeader()\n      notFirst.set(true)\n    }\n\n    seq.forEach { rec ->\n\n      printRows(rec,notFirst)\n\n    }\n\n    w.append( \"]\" )\n  }\n\n  override suspend fun write(channel:ReceiveChannel<Record>) {\n    w.append( \"[\" )\n\n    val notFirst = AtomicBoolean(false)\n\n    if ( printHeader ) {\n      printHeader()\n      notFirst.set(true)\n    }\n\n\t\tfor ( rec in channel ) {\n\n      printRows(rec,notFirst)\n\n    }\n\n    w.append( \"]\" )\n  }\n\n  override fun close() {\n    w.close()\n  }\n\n  private fun printHeader() {\n\n    val row:MutableMap<String,String> = mutableMapOf()\n    if ( includeSource ) row[\"source\"] = \"source\"\n    row[\"page\"] = \"page\"\n\n    fun print( recordType:RecordType) {\n      recordType.valueTypes.forEach { valueTypeId ->\n        val valueType:ValueType? = valueTypes[valueTypeId]\n        if ( valueType?.include ?: true ) {\n          val label = valueType?.label ?: valueTypeId\n          row[valueTypeId] = label\n        }\n      }\n      recordType.children\n          .map { config.recordTypes[it] ?: throw Exception(\"missing type ${it}\") }\n          .forEach { childRecordType ->\n            print( childRecordType )\n          }\n    }\n    val rootRecordType = config.recordTypes[config.rootRecordType] ?: throw Exception(\"missing type ${config.rootRecordType}\")\n    print(rootRecordType)\n\n    writer.writeValue(w,row)\n  }\n\n  private fun printRows(root:Record,notFirst:AtomicBoolean) {\n\n    val map:MutableMap<RecordType, Record> = mutableMapOf()\n\n    fun pr(rec:Record) {\n      val recType = config.recordTypes[rec.typeId] ?: throw Exception( \"Missing type ${rec.typeId}\" )\n      map[recType] = rec\n\n      if ( rec.isLeaf ) {\n        if ( notFirst.getAndSet(true) ) w.write(\",\")\n        printRow(map)\n      } else {\n        rec.children.values.forEach { it.forEach { pr(it) } }\n      }\n\n      map.remove(recType)\n    }\n\n    pr(root)\n  }\n\n  private fun printRow( map:Map<RecordType, Record> ) {\n\n    val row:MutableMap<String,String> = mutableMapOf()\n\n    var pageNumber:Int? = null\n    var pageNumberPriority:Int = -1\n\n    fun printType( type:RecordType) {\n      val rec = map[type]\n\n      if ( pageNumber == null && rec != null ) pageNumber = rec.pageNumber\n      if ( ( rec != null ) && ( pageNumber == null || type.pagePriority > pageNumberPriority ) ) {\n        pageNumber = rec.pageNumber\n        pageNumberPriority = type.pagePriority\n      }\n\n      type.valueTypes.forEach { valueTypeId ->\n        val valueType = valueTypes[valueTypeId]\n        if ( valueType?.include ?: true ) {\n          val attribute = valueType?.attribute\n          val value = rec?.getValue(valueTypeId,attribute) ?: \"\"\n          row[valueTypeId] = value\n        }\n      }\n      type.children\n          .map { config.recordTypes[it] ?: throw Exception(\"missing type ${it}\") }\n          .forEach { childRecordType ->\n            printType( childRecordType )\n          }\n    }\n    val rootRecordType = config.recordTypes[config.rootRecordType] ?: throw Exception(\"missing type ${config.rootRecordType}\")\n\n    printType(rootRecordType)\n\n    if ( includeSource ) {\n      row[\"source\"] = map[rootRecordType]!!.source ?: \"\"\n    }\n    row[\"page\"] = pageNumber.toString()\n\n    writer.writeValue(w,row)\n  }\n\n\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/record/output/JsonRecordOutput.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.record.output\n\nimport com.fasterxml.jackson.core.JsonGenerator\nimport com.fasterxml.jackson.databind.ObjectMapper\nimport io.mfj.textricator.record.Record\nimport io.mfj.textricator.record.RecordModel\n\nimport java.io.BufferedWriter\nimport java.io.OutputStream\nimport java.io.OutputStreamWriter\nimport java.io.Writer\n\nimport kotlinx.coroutines.channels.ReceiveChannel\n\nclass JsonRecordOutput(config:RecordModel,output:OutputStream):RecordOutput {\n\n  private val w = BufferedWriter(OutputStreamWriter(output))\n\n  private val writer = ObjectMapper()\n      .configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET,false) // otherwise closes w\n      .writer().withDefaultPrettyPrinter()\n\n  override fun write( seq:Sequence<Record> ) {\n\n    w.append( \"[\" )\n    var first = true\n\n    seq.forEach { rec ->\n\n      if ( first ) {\n        first = false\n      } else {\n        w.append( \",\" )\n      }\n\n      writeRec( w, rec )\n\n    }\n\n    w.append( \"]\" )\n  }\n\n  override suspend fun write(channel:ReceiveChannel<Record>) {\n    w.append( \"[\" )\n    var first = true\n\n\t\tfor ( rec in channel ) {\n\n      if ( first ) {\n        first = false\n      } else {\n        w.append( \",\" )\n      }\n\n      writeRec( w, rec )\n\n    }\n\n    w.append( \"]\" )\n  }\n\n  private fun writeRec( w:Writer, rec:Record) {\n    writer.writeValue(w,rec)\n  }\n\n  override fun close() {\n    w.close()\n  }\n\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/record/output/NullOutput.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.record.output\n\nimport io.mfj.textricator.record.Record\n\nimport kotlinx.coroutines.channels.ReceiveChannel\n\n/**\n * Run through the records but do not do anything with them.\n */\nobject NullOutput:RecordOutput {\n  override fun write(seq:Sequence<Record>) {\n    seq.forEach {}\n  }\n\n  override suspend fun write(channel:ReceiveChannel<Record>) {\n    for ( rec in channel ) {\n    }\n  }\n\n  override fun close() {}\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/record/output/RecordOutput.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.record.output\n\nimport io.mfj.textricator.record.Record\nimport java.io.Closeable\n\nimport kotlinx.coroutines.channels.ReceiveChannel\n\ninterface RecordOutput: Closeable {\n  fun write( seq:Sequence<Record> )\n  suspend fun write( channel:ReceiveChannel<Record>)\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/record/output/XmlRecordOutput.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2021 Stephen Byrne.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.record.output\n\nimport io.mfj.textricator.record.Record\nimport io.mfj.textricator.record.RecordModel\n\nimport java.io.BufferedWriter\nimport java.io.OutputStream\nimport java.io.OutputStreamWriter\nimport javax.xml.stream.XMLOutputFactory\n\nimport kotlinx.coroutines.channels.ReceiveChannel\n\nimport com.fasterxml.jackson.annotation.JsonInclude\nimport com.fasterxml.jackson.databind.SerializationFeature\nimport com.fasterxml.jackson.dataformat.xml.XmlMapper\n\nclass XmlRecordOutput(config:RecordModel,output:OutputStream):RecordOutput {\n\n  private val w = BufferedWriter(OutputStreamWriter(output))\n\n  // First create Stax components we need\n  private val xmlOutputFactory = XMLOutputFactory.newFactory()\n  private val sw = xmlOutputFactory.createXMLStreamWriter(w)\n  // then Jackson components\n  private val mapper = XmlMapper()\n      .apply {\n        enable(SerializationFeature.INDENT_OUTPUT)\n        setSerializationInclusion(JsonInclude.Include.NON_EMPTY) // omit empty elements e.g.: lots of <link />\n      }\n\n  init {\n    sw.writeStartDocument();\n    sw.writeStartElement(\"Records\");\n  }\n\n  override fun write( seq:Sequence<Record> ) {\n    seq.forEach { rec->\n      mapper.writeValue(sw, rec);\n    }\n  }\n\n  override suspend fun write(channel:ReceiveChannel<Record>) {\n    for ( rec in channel ) {\n      mapper.writeValue(sw,rec)\n    }\n  }\n\n  override fun close() {\n    try {\n      sw.writeEndElement();\n      sw.writeEndDocument();\n      sw.close()\n    } finally {\n      w.close()\n    }\n  }\n\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/table/Table.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.table\n\n\ninternal class Table(private val numberOfColumns:Int, private val maxRowDistance:Float) {\n\n  private val xtable:XTable = mutableMapOf()\n\n  private fun createXRow():XRow =\n      (0..numberOfColumns)\n          .map { createXCell() }\n          .toTypedArray()\n\n  private fun createXCell():XCell = mutableMapOf()\n\n  private fun createXValues():XValues = mutableListOf()\n\n\n  /** add an object to the model */\n  fun addToCell(x:Float, y:Float, columnIndex:Int, text:String) {\n    val xrow = xtable.getOrPut( y, { createXRow() } )\n    val xcell = xrow[columnIndex]\n    val xvalues = xcell.getOrPut( x, { createXValues() } )\n    xvalues.add( text )\n  }\n\n  fun getRows(): Sequence<Row> {\n\n    return xtable\n        .toSortedMap()\n        .group()\n        .asSequence()\n        .map { xrow -> xrow.toRow() }\n  }\n\n  /**\n   * Group rows that are within [maxRowDistance].\n   *\n   * This modifies the receiver!\n   */\n  private fun Map<Float, XRow>.group(): List<XRow> {\n\n    val grouped:MutableList<XRow> = mutableListOf()\n\n    var buffer:Pair<Float, XRow>? = null\n\n    for ( ( y, row ) in entries ) {\n      if ( buffer == null ) {\n        // first row\n        buffer = Pair(y,row)\n      } else if ( buffer.first + maxRowDistance < y ) {\n        // new row\n        grouped.add( buffer.second )\n        buffer = Pair(y,row)\n      } else {\n        // combine row with buffer.second\n        row.forEachIndexed { index, cell ->\n\n          // cell is a map of x-coords to value\n          // if 2 identical x-coords, space-separate them\n          val bufferCell = buffer.second[index]\n\n          cell.entries.forEach { (x,value) ->\n            bufferCell.getOrPut( x, { createXValues() } )\n                .addAll( value )\n          }\n        }\n      }\n    }\n\n    if ( buffer != null ) {\n      grouped.add( buffer.second )\n    }\n\n    return grouped\n  }\n\n  private fun XRow.toRow():Row = map { xcell -> xcell.toCell() }\n\n  // sort by x-coord, then combine the xvalues (which is already sorted by y-value)\n  private fun XCell.toCell():Cell = toSortedMap().values.flatten().toList()\n\n}\n\n///// internal data structure\n\n// map y-coord -> row\nprivate typealias XTable = MutableMap<Float, XRow>\n\n// cell index -> cell\nprivate typealias XRow = Array<XCell>\n\n// x-coord -> values\nprivate typealias XCell = MutableMap<Float, XValues>\n\nprivate typealias XValues = MutableList<String>\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/table/TableParser.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.table\n\nimport io.mfj.textricator.table.config.TableParseConfig\nimport io.mfj.textricator.record.Record\nimport io.mfj.textricator.record.Value\nimport io.mfj.textricator.text.Page\nimport io.mfj.textricator.text.PageFilter\nimport io.mfj.textricator.text.Text\nimport io.mfj.textricator.text.toPageFilter\n\nimport org.slf4j.LoggerFactory\n\n/**\n * Extract tabular data from a PDF where there is text in each \"cell\" that may overflow into the next cell.\n */\nclass TableParser( private val config:TableParseConfig) {\n\n  companion object {\n    private val log = LoggerFactory.getLogger( TableParser::class.java )\n\n    internal val ROOT_TYPE = \"row\"\n  }\n\n  fun parse(pages:Sequence<Page>): Sequence<Record> {\n\n    // just the start x-index of each column, sorted\n    val cols = config.cols.values.sorted().toTypedArray()\n\n    val pageFilter:PageFilter = config.pages.toPageFilter()\n\n    return pages\n        .filter { page -> pageFilter(page.pageNumber) }\n        .flatMap { page ->\n\n      val pageNumber = page.pageNumber\n\n      // position filter\n      val top:Float = config.getTop(pageNumber) ?: 0f\n      val bottom:Float = config.getBottom(pageNumber) ?: Float.MAX_VALUE\n      val pageLeft:Float = cols[0]\n      val pageRight:Float = config.getRight(pageNumber) ?: Float.MAX_VALUE\n      val positionFilter = { text:Text ->\n        val y = text.uly\n        val x = text.ulx\n        ( y >= top ) && ( y <= bottom ) && ( x >= pageLeft ) && ( x <= pageRight )\n      }\n\n      // find the column based on x-value\n      fun findCol( x:Float ):Int? {\n        cols.forEachIndexed { colIndex, left ->\n          val right = if ( colIndex+1 < cols.size ) {\n            cols[colIndex+1]\n          } else {\n            pageRight\n          }\n          if ( x >= left && x < right ) {\n            return colIndex\n          }\n        }\n        return null\n      }\n\n      // table to add text to\n      val table = Table(config.cols.size, config.maxRowDistance)\n\n      // Run the extraction\n      page.texts\n          .filter ( positionFilter )\n          .forEach { text ->\n            findCol(text.ulx)?.let { colIndex ->\n              log.debug( \"p${pageNumber} y${text.uly} c${colIndex} ${text.content}\" )\n              table.addToCell(text.ulx, text.uly, colIndex, text.content)\n            }\n          }\n\n      log.debug(\"processed page ${pageNumber}\")\n\n      table.getRows()\n          .map { row ->\n            createRecord( pageNumber, row )\n          }\n\n    }\n\n  }\n\n  private val valueTypes = config.valueTypes\n\n  private fun createRecord( pageNumber:Int, row:Row):Record {\n\n    // Create a single record per row.\n    // It has no children, just values.\n\n    val record = Record(source=null, pageNumber = pageNumber, typeId = ROOT_TYPE)\n\n    config.cols.keys\n        .forEachIndexed { i, colName ->\n          val cell = row[i].map { text -> Value(text) }\n          val value = valueTypes[colName]!!.calcValue( cell )\n          record.values[colName] = value\n        }\n\n    return record\n  }\n\n}\n\ninternal typealias Row = List<Cell>\ninternal typealias Cell = List<String>\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/table/config/TableParseConfig.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.table.config\n\nimport io.mfj.textricator.record.RecordModel\nimport io.mfj.textricator.record.RecordType\nimport io.mfj.textricator.extractor.TextExtractorOptions\nimport io.mfj.textricator.record.ValueType\nimport io.mfj.textricator.table.TableParser\n\n// Value types are dynamically generated from [cols].\n\nclass TableParseConfig(\n    var top:Float? = null,\n    var bottom:Float? = null,\n    var right:Float? = null,\n    var cols:Map<String, Float>,\n    var pageConfig:Map<Int, ConfigPage>? = null,\n    val types:Map<String,ValueType> = emptyMap(),\n    val filter:String? = null,\n    extractor:String? = null,\n    maxRowDistance: Float,\n    pageFilter:String? = null ):\n    TextExtractorOptions(\n        extractor = extractor,\n        maxRowDistance = maxRowDistance,\n        pages = pageFilter ), RecordModel\n{\n\n  override val recordTypes:Map<String, RecordType>\n    get() = mapOf( TableParser.ROOT_TYPE to\n        RecordType(\n            label = TableParser.ROOT_TYPE,\n            valueTypes = cols.keys.toList(),\n            filter = filter\n        ) )\n\n  override val rootRecordType:String\n    get() = TableParser.ROOT_TYPE\n\n  override val valueTypes:Map<String, ValueType>\n    get() = cols\n        .mapValues { (colName,_) ->\n          types[colName] ?: ValueType(colName)\n        }\n\n  fun getTop(page:Int):Float? {\n    return pageConfig?.get(page)?.top ?: top\n  }\n\n  fun getBottom(page:Int):Float? {\n    return pageConfig?.get(page)?.bottom ?: bottom\n  }\n\n  fun getRight(page:Int):Float? {\n    return pageConfig?.get(page)?.right ?: right\n  }\n}\n\ndata class ConfigPage(\n    var top:Float? = null,\n    var bottom:Float? = null,\n    var right:Float? = null,\n    var skip:Boolean = false)\n\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/table/config/TableParseConfigUtil.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.table.config\n\nimport java.io.File\nimport java.io.InputStream\n\nimport com.fasterxml.jackson.databind.ObjectMapper\nimport com.fasterxml.jackson.dataformat.yaml.YAMLFactory\nimport com.fasterxml.jackson.module.kotlin.*\n\nobject TableParseConfigUtil {\n\n  private val mapper = ObjectMapper(YAMLFactory()).registerKotlinModule()\n\n  fun parseYaml(configFile:File):TableParseConfig = mapper.readValue( configFile.readText() )\n\n  fun parseYaml(input:InputStream):TableParseConfig = mapper.readValue(input)\n\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/text/Page.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.text\n\nimport io.mfj.textricator.text.Text\n\ndata class Page(\n    /** Page number. */\n    val pageNumber:Int,\n    /** Texts on page. */\n    val texts:List<Text>\n)\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/text/PageFilter.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.text\n\ntypealias PageFilter = (Int)->Boolean\n\nval ALL_PAGES:PageFilter = { _:Int -> true }\n\n/**\n * Parse pages text to PageFilter.\n *\n * @param pages Pages: e.g.: 1,3-5,100-103,400\n */\nfun String?.toPageFilter():PageFilter {\n  return if (this != null && isNotBlank()) {\n    val ranges:List<(Int)->Boolean> = split(\",\").map { s ->\n      if (s.contains(\"-\")) {\n        val a = s.split(\"-\")\n        val min = a[0].toInt()\n        val max = intOrEnd(a[1])\n        ;\n        { page:Int ->\n          (min..max).contains(page)\n        }\n      } else {\n        val p = s.toInt();\n        { page:Int ->\n          (page == p)\n        }\n      }\n    };\n    { page:Int ->\n      ranges.any { it(page) }\n    }\n  } else {\n    ALL_PAGES\n  }\n}\n\nprivate fun intOrEnd( s:String? ): Int = if ( s == null || s.isBlank() ) { Int.MAX_VALUE } else { s.toInt() }\n\nfun PageFilter.and( pages:PageFilter):PageFilter = { i -> this(i) && pages(i) }\n\nfun PageFilter.and(s:String?):PageFilter = this.and( s.toPageFilter() )\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/text/RowGrouper.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.text\n\nclass RowGrouper( private val maxRowDistance:Float ) {\n\n  private class GroupByRowState {\n    var buffer:MutableList<Text> = mutableListOf()\n    var lastPage:Int = 1\n  }\n\n  fun group( source:Sequence<Text> ): Sequence<Text> {\n\n    val groupByRowState = GroupByRowState()\n\n    return source\n        .plus( null as Text? ) // sentinal\n        .map { text -> groupByRow( groupByRowState, text ) }\n        .filter { it != null }.map { it!! }\n        .flatten()\n  }\n\n  private fun groupByRow( s:GroupByRowState, text:Text? ): Sequence<Text>? {\n\n    // collect until find a pageNumber break or gap of $maxRowDistance, then flush\n\n    if ( text == null ) {\n      // sentintal\n      // flush and done.\n      return s.buffer.sortedBy( Text::ulx ).asSequence()\n    }\n\n    val ret:MutableList<Text> = mutableListOf()\n\n    if ( text.pageNumber != s.lastPage ) {\n      // new pageNumber\n      ret.addAll( s.buffer.sortedBy( Text::ulx ) )\n      s.buffer = mutableListOf()\n    }\n\n    if ( s.buffer.isEmpty() ) {\n    } else {\n      val last = s.buffer.last()\n      if ( text.uly - last.uly > maxRowDistance ) {\n        ret.addAll( s.buffer.sortedBy( Text::ulx ).asSequence() )\n        s.buffer = mutableListOf()\n      }\n    }\n\n    s.buffer.add( text )\n    s.lastPage = text.pageNumber\n\n    return if ( ret.isNotEmpty() ) ret.asSequence() else null\n  }\n\n}\n\nfun Sequence<Text>.groupRows(maxRowDistance:Float?): Sequence<Text> =\n    if ( maxRowDistance != null ) {\n      RowGrouper(maxRowDistance).group(this)\n    } else {\n      this\n    }\n\nfun Sequence<Page>.groupRowsPaged(maxRowDistance:Float?): Sequence<Page> =\n    if ( maxRowDistance != null ) {\n      this.map { page ->\n        Page(page.pageNumber, page.texts.asSequence().groupRows(maxRowDistance).toList())\n      }\n    } else {\n      this\n    }\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/text/Text.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.text\n\nimport java.beans.Transient\n\n/**\n * Extricated text.\n *\n * Positions and dimensions are in points.\n * x=0 is the left edge.\n * y=0 is the top edge.\n *\n * @property content The text.\n * @property pageNumber Page Number\n * @property ulx upper-left x-coordinate\n * @property uly upper-left y-coordinate\n * @property lrx lower-right x-coordinate\n * @property lry lower-right y-coordinate\n * @property link link url\n * @property font Font name\n * @property fontSize Font size, in points\n * @property color Text color\n * @property backgroundColor Background color\n *\n * @property width Width\n * @property height Height\n */\ndata class Text(\n    val content:String,\n    val pageNumber:Int,\n    val ulx:Float,\n    val uly:Float,\n    val lrx:Float,\n    val lry:Float,\n    val font:String,\n    val fontSize:Float,\n    val color:String? = null,\n    val backgroundColor:String? = null,\n    val link:String? = null ) {\n\n  val width:Float\n    @Transient\n    get() = lrx - ulx;\n\n  val height:Float\n    @Transient\n    get() = lry - uly;\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/text/output/CsvTextOutput.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.text.output\n\nimport io.mfj.textricator.text.Text\n\nimport java.io.OutputStream\n\nimport org.apache.commons.csv.*\n\nimport org.slf4j.LoggerFactory\nimport java.io.OutputStreamWriter\n\nclass CsvTextOutput(output:OutputStream):TextOutput {\n\n  private val w = OutputStreamWriter(output)\n  private val p = CSVPrinter(w, CSV_FORMAT)\n\n  companion object {\n    private val log = LoggerFactory.getLogger(CsvTextOutput::class.java)\n    val CSV_FORMAT = CSVFormat.DEFAULT.withRecordSeparator(\"\\n\")\n  }\n\n  override fun close() {\n    p.close()\n    w.close()\n  }\n\n  override fun write(seq:Sequence<Text>) {\n    writeHeader()\n    writeTexts(seq)\n  }\n\n  private fun writeTexts(seq:Sequence<Text>) {\n    seq.forEach { text ->\n      write( text )\n    }\n  }\n\n  private fun writeHeader() {\n    p.printRecord(\n        \"page\",\n        \"ulx\",\n        \"uly\",\n        \"lrx\",\n        \"lry\",\n        \"width\",\n        \"height\",\n        \"content\",\n        \"font\",\n        \"fontSize\",\n        \"fontColor\",\n        \"bgcolor\",\n        \"link\"\n    )\n  }\n\n  private fun write(text:Text) {\n    // If you change this, change CsvTextExtractor.parseRec(CSVRecord) to match.\n    p.printRecord(\n        text.pageNumber,\n        text.ulx,\n        text.uly,\n        text.lrx,\n        text.lry,\n        text.width,\n        text.height,\n        text.content,\n        text.font,\n        text.fontSize,\n        text.color,\n        text.backgroundColor,\n        text.link\n    )\n  }\n\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/text/output/JsonTextOutput.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.text.output\n\nimport io.mfj.textricator.text.Text\n\nimport java.io.OutputStream\n\nimport com.fasterxml.jackson.core.JsonGenerator\nimport com.fasterxml.jackson.databind.ObjectMapper\n\nimport org.slf4j.LoggerFactory\n\nclass JsonTextOutput(private val output:OutputStream):TextOutput {\n\n  private val writer = ObjectMapper()\n      .configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET,false)\n      .writer().withDefaultPrettyPrinter()\n\n  companion object {\n    private val log = LoggerFactory.getLogger(JsonTextOutput::class.java)\n  }\n\n  override fun close() {}\n\n  override fun write(seq:Sequence<Text>) {\n\n    write(\"[\")\n    var first = true\n    seq.forEach { text ->\n      if ( first ) first = false else output.write(\",\".toByteArray())\n      writer.writeValue(output,text)\n    }\n    write(\"]\")\n  }\n\n  private fun write(s:String) {\n    output.write( s.toByteArray() )\n  }\n\n}\n"
  },
  {
    "path": "src/main/java/io/mfj/textricator/text/output/TextOutput.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.text.output\n\nimport io.mfj.textricator.text.Text\nimport java.io.Closeable\n\ninterface TextOutput: Closeable {\n  fun write( seq:Sequence<Text> )\n}\n"
  },
  {
    "path": "src/main/resources/io/mfj/textricator/extractor/textExtractor.properties",
    "content": "pdf.itext5=io.mfj.textricator.extractor.itext5.Itext5TextExtractorFactory\npdf.itext7=io.mfj.textricator.extractor.itext7.Itext7TextExtractorFactory\npdf.pdfbox=io.mfj.textricator.extractor.pdfbox.PdfboxTextExtractorFactory\njson=io.mfj.textricator.extractor.json.JsonTextExtractorFactory\ncsv=io.mfj.textricator.extractor.csv.CsvTextExtractorFactory\n"
  },
  {
    "path": "src/main/resources/io/mfj/textricator/logback.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<!DOCTYPE configuration>\n\n<configuration>\n    <import class=\"ch.qos.logback.classic.encoder.PatternLayoutEncoder\"/>\n    <import class=\"ch.qos.logback.core.ConsoleAppender\"/>\n\n    <appender name=\"STDERR\" class=\"ConsoleAppender\">\n        <target>System.err</target>\n        <encoder class=\"PatternLayoutEncoder\">\n            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger -%kvp- %msg%n</pattern>\n        </encoder>\n    </appender>\n\n    <root level=\"WARN\">\n        <appender-ref ref=\"STDERR\"/>\n    </root>\n</configuration>"
  },
  {
    "path": "src/main/resources/io/mfj/textricator/version.properties",
    "content": "version=${project.version}\ncopyright.year=${copyright.year}\nsource.location=${source.location}"
  },
  {
    "path": "src/scripts/textricator",
    "content": "#!/usr/bin/env bash\n\n# Find script directory ($SCRIPT_DIR).\n# On linux (and cygwin) \"SCRIPT_DIR=$(basedir $(readlink -f $0))\" works,\n# but Macos' readlink is very different.\n# This works on linux, cygwin, and macos:\nSCRIPT_DIR=$(cd -P -- \"$(dirname -- \"$0\")\" && pwd -P) && SCRIPT_DIR=$SCRIPT_DIR/$(basename -- \"$0\")\nwhile [[ -h \"$SCRIPT_DIR\" ]]; do\n    DIR=$(dirname -- \"$SCRIPT_DIR\")\n    SYM=$(readlink \"$SCRIPT_DIR\")\n    SCRIPT_DIR=$(cd \"$DIR\" && cd \"$(dirname -- \"$SYM\")\" && pwd)/$(basename -- \"$SYM\")\ndone\nSCRIPT_DIR=$(dirname -- \"$SCRIPT_DIR\")\n\njava -cp \"${SCRIPT_DIR}/lib/*\" ${JAVA_OPTS} io.mfj.textricator.cli.TextricatorCli \"$@\"\n"
  },
  {
    "path": "src/scripts/textricator.bat",
    "content": "@echo off\nset batpath=%~dp0\njava -cp \"%batpath%lib/*\" io.mfj.textricator.cli.TextricatorCli %*"
  },
  {
    "path": "src/test/java/io/mfj/textricator/examples/ExamplesTest.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.examples\n\nimport io.mfj.textricator.Textricator\nimport io.mfj.textricator.form.config.FormParseConfigUtil\nimport io.mfj.textricator.table.config.TableParseConfigUtil\n\nimport java.io.BufferedReader\nimport java.io.File\n\nimport kotlin.test.assertEquals\nimport kotlin.test.assertFalse\nimport kotlin.test.assertTrue\n\nimport org.junit.Test\nimport org.junit.runner.RunWith\nimport org.junit.runners.Parameterized\n\n/**\n * Run the examples. They make pretty good tests.\n */\n@RunWith(Parameterized::class)\nclass ExamplesTest( private val name:String, private val type:Type) {\n\n  enum class Type { FORM, TABLE }\n\n  companion object {\n\n    /**\n     * Examples.\n     * Map of file name (without extension) to parse type.\n     * For each of these, there must be a .pdf, a .yml, and a .csv in src/test/resources/io/mfj/textricator/examples/.\n     */\n    val examples = mapOf(\n        \"rap-sheet\" to Type.FORM,\n        \"school-employee-list\" to Type.FORM\n    )\n\n    @JvmStatic\n    @Parameterized.Parameters(name=\"{1}:{0}\")\n    fun data() = examples.entries.map { (name,type) -> arrayOf( name, type ) }\n\n    private fun compare( a:BufferedReader, b:BufferedReader ) = compare(\n        a.lineSequence().iterator(), b.lineSequence().iterator())\n\n    private fun compare( a:Iterator<String>, b:Iterator<String> ) {\n      var line = 0\n      while ( a.hasNext() ) {\n        line++\n        assertTrue( \"Missing line @${line}\" ) { b.hasNext() }\n        val aline = a.next()\n        val bline = b.next()\n        assertEquals( aline, bline, \"Incorrect line @${line}\" )\n      }\n      line++\n      assertFalse( \"Extra line @${line}\" ) { b.hasNext() }\n    }\n  }\n\n  @Test\n  fun test() {\n    val outCsv = File.createTempFile( name, \".csv\" )\n    outCsv.deleteOnExit()\n    try {\n      // run textricator\n      outCsv.outputStream().use { out ->\n        ExamplesTest::class.java.getResourceAsStream( \"${name}.yml\" )!!.use { config ->\n          ExamplesTest::class.java.getResourceAsStream( \"${name}.pdf\" )!!.use { pdf ->\n            when ( type ) {\n              Type.FORM -> {\n                Textricator.parseForm(\n                    input = pdf,\n                    inputFormat = \"pdf\",\n                    output = out,\n                    outputFormat = \"csv\",\n                    config = FormParseConfigUtil.parseYaml( config )\n                )\n              }\n              Type.TABLE -> {\n                Textricator.parseTable(\n                    input = pdf,\n                    inputFormat = \"pdf\",\n                    output = out,\n                    outputFormat = \"csv\",\n                    config = TableParseConfigUtil.parseYaml( config )\n                )\n              }\n            }\n          }\n        }\n      }\n\n      // make sure CSVs match\n      outCsv.bufferedReader().use { b ->\n        ExamplesTest::class.java.getResourceAsStream( \"${name}.csv\" )!!.bufferedReader().use { a ->\n          compare(a, b)\n        }\n      }\n    } finally {\n      outCsv.delete()\n    }\n\n  }\n\n  /**\n   * Test that if we extract text to JSON and then use that as input, it works.\n   */\n  @Test\n  fun testJson() {\n    val textJson = File.createTempFile( name, \"-text.json\" )\n    textJson.deleteOnExit()\n    val outCsv = File.createTempFile( name, \".csv\")\n    outCsv.deleteOnExit()\n    try {\n      // pdf -> json\n      textJson.outputStream().use { out ->\n        ExamplesTest::class.java.getResourceAsStream( \"${name}.yml\" )!!.use { config ->\n          ExamplesTest::class.java.getResourceAsStream( \"${name}.pdf\" )!!.use { pdf ->\n            when ( type ) {\n              Type.FORM -> {\n                Textricator.extractText(\n                    input = pdf,\n                    inputFormat = \"pdf\",\n                    output = out,\n                    outputFormat = \"json\",\n                    textExtractorOptions = FormParseConfigUtil.parseYaml( config )\n                )\n              }\n              Type.TABLE -> TODO()\n            }\n          }\n        }\n      }\n\n      // json -> csv\n      outCsv.outputStream().use { csv ->\n        textJson.inputStream().use { json ->\n          ExamplesTest::class.java.getResourceAsStream( \"${name}.yml\" )!!.use { config ->\n            when ( type ) {\n              Type.FORM -> {\n                Textricator.parseForm(\n                    input = json,\n                    inputFormat = \"json\",\n                    output = csv,\n                    outputFormat = \"csv\",\n                    config = FormParseConfigUtil.parseYaml( config )\n                )\n              }\n              Type.TABLE -> TODO()\n            }\n          }\n        }\n      }\n\n      // make sure CSVs match\n      outCsv.bufferedReader().use { b ->\n        ExamplesTest::class.java.getResourceAsStream( \"${name}.csv\" )!!.bufferedReader().use { a ->\n          compare(a, b)\n        }\n      }\n    } finally {\n      outCsv.delete()\n      textJson.delete()\n    }\n  }\n\n  /**\n   * Test that if we extract text to CSV and then use that as input, it works.\n   */\n  @Test\n  fun testCSV() {\n    val textCsv = File.createTempFile( name, \"-text.csv\" )\n    textCsv.deleteOnExit()\n    val outCsv = File.createTempFile( name, \".csv\")\n    outCsv.deleteOnExit()\n    try {\n      // pdf -> json\n      textCsv.outputStream().use { out ->\n        ExamplesTest::class.java.getResourceAsStream( \"${name}.yml\" )!!.use { config ->\n          ExamplesTest::class.java.getResourceAsStream( \"${name}.pdf\" )!!.use { pdf ->\n            when ( type ) {\n              Type.FORM -> {\n                Textricator.extractText(\n                    input = pdf,\n                    inputFormat = \"pdf\",\n                    output = out,\n                    outputFormat = \"csv\",\n                    textExtractorOptions = FormParseConfigUtil.parseYaml( config )\n                )\n              }\n              Type.TABLE -> TODO()\n            }\n          }\n        }\n      }\n\n      // json -> csv\n      outCsv.outputStream().use { csv ->\n        textCsv.inputStream().use { textCsv ->\n          ExamplesTest::class.java.getResourceAsStream( \"${name}.yml\" )!!.use { config ->\n            when ( type ) {\n              Type.FORM -> {\n                Textricator.parseForm(\n                    input = textCsv,\n                    inputFormat = \"csv\",\n                    output = csv,\n                    outputFormat = \"csv\",\n                    config = FormParseConfigUtil.parseYaml( config )\n                )\n              }\n              Type.TABLE -> TODO()\n            }\n          }\n        }\n      }\n\n      // make sure CSVs match\n      outCsv.bufferedReader().use { b ->\n        ExamplesTest::class.java.getResourceAsStream( \"${name}.csv\" )!!.bufferedReader().use { a ->\n          compare(a, b)\n        }\n      }\n    } finally {\n      outCsv.delete()\n      textCsv.delete()\n    }\n  }\n\n}"
  },
  {
    "path": "src/test/java/io/mfj/textricator/form/NodeMembersTest.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.form\n\nimport io.mfj.textricator.form.config.FormParseConfig\nimport io.mfj.textricator.form.config.State\nimport io.mfj.textricator.record.PatternReplacement\nimport io.mfj.textricator.record.RecordType\nimport io.mfj.textricator.record.Value\nimport io.mfj.textricator.record.ValueType\n\nimport org.junit.Assert.*\nimport org.junit.Test\n\nclass NodeMembersTest {\n  val model = FormParseConfig(rootRecordType = \"name\", recordTypes = mutableMapOf(\n      \"name\" to RecordType(label = \"name\",\n          valueTypes = mutableListOf(\"inmateName\", \"city\", \"state\", \"inmateDOB\", \"arrestDate\"))),\n      valueTypes = mutableMapOf(\"inmateName\" to ValueType(label = \"Inmate Name\"),\n          \"city\" to ValueType(label = \"City\", replacements = mutableListOf(PatternReplacement(\"(.*),.*\", \"$1\"))),\n          \"state\" to ValueType(label = \"State\", replacements = mutableListOf(PatternReplacement(\".*,(.*)\", \"$1\"))),\n          \"inmateDOB\" to ValueType(label = \"Inmate DOB\"), \"arrestDate\" to ValueType(label = \"Arrest Date\")),\n      states = mutableMapOf(\"inmateName\" to State(startRecord = true),\n          \"cityState\" to State(valueTypes = mutableListOf(\"city\", \"state\")),\n          \"inmateDOB\" to State(),\n          \"arrestDate\" to State()))\n\n  val rp = RecordParser(model)\n\n  private fun sv(pageNumber: Int, stateId: String, vararg value: String) :StateValue = StateValue(\n      source = \"test\",\n      pageNumber = pageNumber, stateId = stateId,\n      state = model.states[stateId] ?: throw Exception(\"Missing State: ${stateId}\"), values = value.toList().map{ Value(it) })\n\n  @Test\n  fun testNodeMembers() {\n    val stateValues: List<StateValue> = listOf(\n        sv(1, \"inmateName\", \"John Doe\"),\n        sv(1, \"cityState\", \"New York,NY\"),\n        sv(1, \"inmateDOB\", \"01/01/1985\"),\n        sv(1, \"arrestDate\", \"02/15/2018\"),\n        sv(1, \"inmateName\", \"Jane Doe\"),\n        sv(1, \"cityState\", \"Rochester,NY\"),\n        sv(1, \"inmateDOB\", \"12/12/1975\"),\n        sv(1, \"arrestDate\", \"02/13/2018\")\n    )\n\n    val records = rp.parse(stateValues.asSequence()).toList()\n\n    assertEquals(\"New York\", records[0].values[\"city\"]?.text)\n    assertEquals(\"NY\", records[0].values[\"state\"]?.text)\n    assertEquals(\"Rochester\", records[1].values[\"city\"]?.text)\n    assertEquals(\"NY\", records[1].values[\"state\"]?.text)\n\n  }\n}\n"
  },
  {
    "path": "src/test/java/io/mfj/textricator/form/PatternReplacementTest.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.form\n\nimport io.mfj.textricator.form.config.FormParseConfig\nimport io.mfj.textricator.form.config.State\nimport io.mfj.textricator.record.PatternReplacement\nimport io.mfj.textricator.record.RecordType\nimport io.mfj.textricator.record.Value\nimport io.mfj.textricator.record.ValueType\n\nimport org.junit.Assert.*\nimport org.junit.Test\n\nclass PatternReplacementTest {\n  val model = FormParseConfig(rootRecordType = \"name\", recordTypes = mutableMapOf(\n      \"name\" to RecordType(label = \"name\",\n          valueTypes = mutableListOf(\"inmateName\", \"inmateAge\", \"inmateRace\", \"arrestDateTime\"))),\n      valueTypes = mutableMapOf(\"inmateName\" to ValueType(label = \"Inmate Name\"),\n          \"inmateAge\" to ValueType(label = \"Inmate Age\",\n              replacements = mutableListOf(PatternReplacement(\"30\", \"thirty\"), PatternReplacement(\"40\", \"forty\"))),\n          \"inmateRace\" to ValueType(label = \"Inmate Race\",\n              replacements = mutableListOf(PatternReplacement(\"W\", \"white\"), PatternReplacement(\"W\", \"black\"))),\n          \"arrestDateTime\" to ValueType(label = \"Arrest Date Time\", replacements = mutableListOf(\n              PatternReplacement(pattern = \"(.*)\\\\ 12/30/1899\\\\ (.*)\", replacement = \"$1 $2\")))),\n      states = mutableMapOf(\"inmateName\" to State(startRecord = true),\n          \"inmateAge\" to State(), \"inmateRace\" to State(),\n          \"arrestDateTime\" to State()))\n\n  val rp = RecordParser(model)\n\n  private fun sv(pageNumber: Int, stateId: String, vararg value: String) :StateValue = StateValue(\n    source = \"test\",\n    pageNumber = pageNumber, stateId = stateId,\n      state = model.states[stateId] ?: throw Exception(\"Missing State: ${stateId}\"), values = value.toList().map{ Value(it) })\n\n  @Test\n  fun testPatternReplacement() {\n    val stateValues: List<StateValue> = listOf(\n        sv(1, \"inmateName\", \"John Doe\"),\n        sv(1, \"inmateAge\", \"30\"),\n        sv(1, \"inmateRace\", \"W\"),\n        sv(1, \"arrestDateTime\", \"02/15/2018 12/30/1899 03:33:00 AM\"),\n        sv(1, \"inmateName\", \"Jane Doe\"),\n        sv(1, \"inmateAge\", \"40\"),\n        sv(1, \"inmateRace\", \"W\"),\n        sv(1, \"arrestDateTime\", \"02/13/2018 05:55:00 PM\")\n    )\n\n    val records = rp.parse(stateValues.asSequence()).toList()\n\n    // test that removing 12/30/1899 from arrestDateTime works\n    assertEquals(\"02/15/2018 03:33:00 AM\", records[0].values[\"arrestDateTime\"]?.text)\n\n    // test that nothing is removed from arrestDateTime when 12/30/1899 isn't there\n    assertEquals(\"02/13/2018 05:55:00 PM\", records[1].values[\"arrestDateTime\"]?.text)\n\n    // test that correct replacement is used when there are multiple patterns as options\n    assertEquals(\"thirty\", records[0].values[\"inmateAge\"]?.text)\n    assertEquals(\"forty\", records[1].values[\"inmateAge\"]?.text)\n\n    // test that first replacement is used when there are multiple matching patterns\n    assertEquals(\"white\", records[0].values[\"inmateRace\"]?.text)\n    assertEquals(\"white\", records[1].values[\"inmateRace\"]?.text)\n  }\n}\n"
  },
  {
    "path": "src/test/java/io/mfj/textricator/form/RecordParserTest.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.form\n\nimport io.mfj.textricator.record.Record\nimport io.mfj.textricator.record.RecordType\nimport io.mfj.textricator.form.config.FormParseConfig\nimport io.mfj.textricator.form.config.State\nimport io.mfj.textricator.record.Value\n\nimport org.junit.Assert.*\nimport org.junit.Test\n\nclass RecordParserTest {\n\n  val model = FormParseConfig(rootRecordType = \"date\", recordTypes = mutableMapOf(\n      \"date\" to RecordType(label = \"Date\", children = mutableListOf(\"person\"), valueTypes = mutableListOf(\"date\")),\n      \"person\" to RecordType(label = \"Person\", children = mutableListOf(\"case\"),\n          valueTypes = mutableListOf(\"name\", \"dob\")),\n      \"case\" to RecordType(label = \"Case\", children = mutableListOf(\"charge\"),\n          valueTypes = mutableListOf(\"caseId\", \"court\")),\n      \"charge\" to RecordType(label = \"Charge\", valueTypes = mutableListOf(\"chargeCode\", \"chargeDesc\"))),\n      states = mutableMapOf(\n          \"date\" to State(startRecord = true, startRecordForEachValue = true),\n          \"name\" to State(startRecord = true),\n          \"dob\" to State(),\n          \"caseId\" to State(startRecord = true),\n          \"court\" to State(),\n          \"chargeCode\" to State(startRecord = true),\n          \"chargeDesc\" to State()))\n\n  val rp = RecordParser(model)\n\n  private fun sv( pageNumber:Int, stateId:String, vararg value:String ):StateValue = StateValue(\n    source = \"test\",\n    pageNumber = pageNumber, stateId = stateId,\n      state = model.states[stateId] ?: throw Exception(\"Missing state ${stateId}\"), values = value.toList().map{ Value(it) })\n\n  @Test\n  fun testStructure() {\n\n    val stateValues:List<StateValue> = listOf(\n        sv( 1, \"date\", \"2018-01-01\" ),\n        sv( 1, \"date\", \"2018-01-02\" ),\n        sv( 1, \"name\", \"John Doe\" ),\n        sv( 1, \"dob\", \"1980-01-01\" ),\n        sv( 1, \"caseId\", \"CASE001\" ),\n        sv( 1, \"court\", \"Kangaroo\" ),\n        sv( 1, \"chargeCode\", \"AGGRAV ASSLT\" ),\n        sv( 1, \"chargeDesc\", \"W DEADLY WEAPON\" ),\n        sv( 1, \"chargeCode\", \"AGGRAV BATTERY\" ),\n        sv( 1, \"chargeDesc\", \"BODILY HARM\" ),\n        sv( 1, \"caseId\", \"CASE002\" ),\n        sv( 1, \"court\", \"Kangaroo\" ),\n        sv( 1, \"chargeCode\", \"MOVING VIOL\" ),\n        sv( 1, \"chargeDesc\", \"30+\" ),\n        sv( 1, \"chargeCode\", \"NONMOVING VIOL\" ),\n        sv( 1, \"chargeDesc\", \"NO LICENSE\" ),\n        sv( 1, \"name\", \"Jane Doe\" ),\n        sv( 1, \"dob\", \"1990-01-01\" ),\n        sv( 1, \"caseId\", \"CASE001\" ),\n        sv( 1, \"court\", \"Kangaroo\" ),\n        sv( 1, \"chargeCode\", \"VEH THEFT\" ),\n        sv( 1, \"chargeDesc\", \"GRAND 3RD\" ),\n        sv( 1, \"chargeCode\", \"NONMOVING VIOL\" ),\n        sv( 1, \"chargeDesc\", \"NO LICESNSE\" )\n    )\n\n    val records = rp.parse( stateValues.asSequence() ).toList()\n\n    validateRecordsAgainstModel( records )\n  }\n\n  private fun validateRecordsAgainstModel( records:List<Record> ) {\n    records.forEach { record ->\n      assertEquals( \"Root records must be of type \\\"${model.rootRecordType}\\\" -  found \\\"${record.typeId}\\\"\",\n          model.rootRecordType, record.typeId )\n\n      validateRecordAgainstModel( record )\n    }\n  }\n\n  private fun validateRecordAgainstModel( record:Record) {\n    val childAllowedTypes = model.recordTypes[record.typeId]!!.children.toSet()\n\n    record.children.keys.forEach { childType ->\n      assertTrue( \"Records of Type \\\"${record.typeId}\\\" may only contain children of types ${childAllowedTypes} - found \\\"${childType}\\\"\",\n          childAllowedTypes.contains( childType ) )\n    }\n    record.children.values.forEach { children ->\n      children.forEach { child ->\n        validateRecordAgainstModel( child )\n      }\n    }\n  }\n\n\n  @Test\n  fun testAncestorThatIsAChildOf() {\n    assertEquals( \"person\", rp.findAncestorThatIsAChildOf(\"person\",\"date\") )\n    assertEquals( \"person\", rp.findAncestorThatIsAChildOf(\"case\",\"date\") )\n    assertEquals( \"person\", rp.findAncestorThatIsAChildOf(\"charge\",\"date\") )\n    assertEquals( \"case\", rp.findAncestorThatIsAChildOf(\"case\",\"person\") )\n    assertEquals( \"case\", rp.findAncestorThatIsAChildOf(\"charge\",\"person\") )\n    assertEquals( \"charge\", rp.findAncestorThatIsAChildOf(\"charge\",\"case\") )\n  }\n\n  /**\n   * Make sure that if a state that is required for another state to start a new record\n   * ([State.startRecordRequiredState])\n   * has [State.include] = false\n   * that the state is still still noticed for the purposes of [State.startRecordRequiredState].\n   *\n   * Previously, the [StateValue]s with [State.include]=false were filtered out too early and this did not work.\n   */\n  @Test\n  fun testStartRecordIfSeenIgnoredState() {\n    val model = FormParseConfig(rootRecordType = \"person\",\n        recordTypes = mutableMapOf(\n            \"person\" to RecordType(label = \"Person\", valueTypes = mutableListOf(\"name\"))\n        ),\n        states = mutableMapOf(\n            \"name\" to State(startRecord = true, startRecordRequiredState = \"label\"),\n            \"label\" to State(include = false)\n        )\n    )\n    val stateValues = listOf(\n        StateValue(\n            source = \"test\",\n            pageNumber = 1,\n            values = listOf( Value(\"Fred\") ),\n            state = model.states[\"name\"]!!,\n            stateId = \"name\"\n        ),\n        StateValue(\n            source = \"test\",\n            pageNumber = 1,\n            values = listOf( Value(\"label\") ),\n            state = model.states[\"label\"]!!,\n            stateId = \"label\"\n        ),\n        StateValue(\n          source = \"test\",\n          pageNumber = 1,\n            values = listOf( Value(\"Sally\") ),\n            state = model.states[\"name\"]!!,\n            stateId = \"name\"\n        )\n    ).asSequence()\n\n    val records = RecordParser(model).parse( stateValues ).toList()\n\n    assertEquals( 2, records.size )\n    assertEquals( \"Fred\", records[0].values[\"name\"]?.text )\n    assertEquals( \"Sally\", records[1].values[\"name\"]?.text )\n  }\n\n}\n"
  },
  {
    "path": "src/test/java/io/mfj/textricator/record/RecordFilterTest.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.record\n\nimport io.mfj.expr.ExDataType\nimport io.mfj.textricator.form.config.FormParseConfig\n\nimport org.junit.Assert.*\nimport org.junit.Test\n\nclass RecordFilterTest {\n\n  @Test\n  fun testNoFilter() {\n\n    val model = FormParseConfig(rootRecordType = \"a\", recordTypes = mutableMapOf(\n        \"a\" to RecordType(label = \"A\", children = mutableListOf(\"b\", \"c\"), valueTypes = mutableListOf(\"a1\", \"a2\")),\n        \"b\" to RecordType(label = \"B\", children = mutableListOf(), valueTypes = mutableListOf(\"b1\", \"b2\")),\n        \"c\" to RecordType(label = \"C\", children = mutableListOf(\"d\"), valueTypes = mutableListOf(\"c1\", \"c2\")),\n        \"d\" to RecordType(label = \"D\", valueTypes = mutableListOf(\"d1\", \"d2\"))))\n\n    val records =\n        listOf(Record(1, \"a\", mutableMapOf(\"a1\" to Value(\"Hello\"), \"a2\" to Value(\"World\")), mutableMapOf(\n            \"b\" to mutableListOf(Record(1, \"b\", mutableMapOf(\"b1\" to Value(\"1\"), \"b2\" to Value(\"2\")))),\n            \"c\" to mutableListOf(Record(1, \"c\", mutableMapOf(\"c1\" to Value(\"1\"), \"c2\" to Value(\"2\")),\n                mutableMapOf(\"d\" to mutableListOf(\n                    Record(1, \"d\", mutableMapOf(\"d1\" to Value(\"1\"), \"d2\" to Value(\"2\")))))))))\n        )\n\n    val filtered = RecordFilter(model).filter(records.asSequence()).toList()\n\n    assertEquals( records, filtered )\n\n  }\n\n  @Test\n  fun testTopFilter() {\n\n    val model = FormParseConfig(rootRecordType = \"a\", recordTypes = mutableMapOf(\n        \"a\" to RecordType(label = \"A\", filter = \"\"\" a1 = \"x\" \"\"\", children = mutableListOf(\"b\", \"c\"),\n            valueTypes = mutableListOf(\"a1\", \"a2\")),\n        \"b\" to RecordType(label = \"B\", children = mutableListOf(), valueTypes = mutableListOf(\"b1\", \"b2\")),\n        \"c\" to RecordType(label = \"C\", children = mutableListOf(\"d\"), valueTypes = mutableListOf(\"c1\", \"c2\")),\n        \"d\" to RecordType(label = \"D\", valueTypes = mutableListOf(\"d1\", \"d2\"))))\n\n    val records =\n        listOf(Record(1, \"a\", mutableMapOf(\"a1\" to Value(\"Hello\"), \"a2\" to Value(\"World\")), mutableMapOf(\n            \"b\" to mutableListOf(Record(1, \"b\", mutableMapOf(\"b1\" to Value(\"1\"), \"b2\" to Value(\"2\")))),\n            \"c\" to mutableListOf(Record(1, \"c\", mutableMapOf(\"c1\" to Value(\"1\"), \"c2\" to Value(\"2\")),\n                mutableMapOf(\"d\" to mutableListOf(\n                    Record(1, \"d\", mutableMapOf(\"d1\" to Value(\"1\"), \"d2\" to Value(\"2\")))))))))\n        )\n\n    val filtered = RecordFilter(model).filter(records.asSequence()).toList()\n\n    assertTrue( filtered.isEmpty() )\n\n  }\n\n  @Test\n  fun testChildFilter() {\n\n    val model = FormParseConfig(rootRecordType = \"a\", recordTypes = mutableMapOf(\n        \"a\" to RecordType(label = \"A\", filter = \"\"\" a1 = \"Hello\" and a2 = \"World\" \"\"\",\n            children = mutableListOf(\"b\", \"c\"), valueTypes = mutableListOf(\"a1\", \"a2\")),\n        \"b\" to RecordType(label = \"B\", children = mutableListOf(), valueTypes = mutableListOf(\"b1\", \"b2\")),\n        \"c\" to RecordType(label = \"C\", filter = \"\"\" c1 = \"2\" \"\"\", children = mutableListOf(\"d\"),\n            valueTypes = mutableListOf(\"c1\", \"c2\")),\n        \"d\" to RecordType(label = \"D\", valueTypes = mutableListOf(\"d1\", \"d2\"))))\n\n    val records =\n        listOf(Record(1, \"a\", mutableMapOf(\"a1\" to Value(\"Hello\"), \"a2\" to Value(\"World\")), mutableMapOf(\n            \"b\" to mutableListOf(Record(1, \"b\", mutableMapOf(\"b1\" to Value(\"1\"), \"b2\" to Value(\"2\")))),\n            \"c\" to mutableListOf(Record(1, \"c\", mutableMapOf(\"c1\" to Value(\"1\"), \"c2\" to Value(\"2\")),\n                mutableMapOf(\"d\" to mutableListOf(\n                    Record(1, \"d\", mutableMapOf(\"d1\" to Value(\"1\"), \"d2\" to Value(\"2\")))))))))\n        )\n\n    val expected =\n        listOf(Record(1, \"a\", mutableMapOf(\"a1\" to Value(\"Hello\"), \"a2\" to Value(\"World\")), mutableMapOf(\n            \"b\" to mutableListOf(Record(1, \"b\", mutableMapOf(\"b1\" to Value(\"1\"), \"b2\" to Value(\"2\")))),\n            \"c\" to mutableListOf()))\n        )\n\n    val filtered = RecordFilter(model).filter(records.asSequence()).toList()\n\n    assertEquals( expected, filtered )\n\n  }\n\n  @Test\n  fun testChildFilterSome() {\n\n    val model = FormParseConfig(rootRecordType = \"a\", recordTypes = mutableMapOf(\n        \"a\" to RecordType(label = \"A\", filter = \"\"\" a1 = \"Hello\" and a2 = \"World\" \"\"\",\n            children = mutableListOf(\"b\", \"c\"), valueTypes = mutableListOf(\"a1\", \"a2\")),\n        \"b\" to RecordType(label = \"B\", children = mutableListOf(), valueTypes = mutableListOf(\"b1\", \"b2\")),\n        \"c\" to RecordType(label = \"C\", filter = \"\"\" c1 = \"2\" \"\"\", children = mutableListOf(\"d\"),\n            valueTypes = mutableListOf(\"c1\", \"c2\")),\n        \"d\" to RecordType(label = \"D\", valueTypes = mutableListOf(\"d1\", \"d2\"))))\n\n    val records =\n        listOf(Record(1, \"a\", mutableMapOf(\"a1\" to Value(\"Hello\"), \"a2\" to Value(\"World\")), mutableMapOf(\n            \"b\" to mutableListOf(Record(1, \"b\", mutableMapOf(\"b1\" to Value(\"1\"), \"b2\" to Value(\"2\")))),\n            \"c\" to mutableListOf(Record(1, \"c\", mutableMapOf(\"c1\" to Value(\"1\"), \"c2\" to Value(\"2\")),\n                mutableMapOf(\"d\" to mutableListOf(\n                    Record(1, \"d\", mutableMapOf(\"d1\" to Value(\"1\"), \"d2\" to Value(\"2\")))))),\n                Record(1, \"c\", mutableMapOf(\"c1\" to Value(\"2\"), \"c2\" to Value(\"3\")), mutableMapOf(\n                    \"d\" to mutableListOf(\n                        Record(1, \"d\", mutableMapOf(\"d1\" to Value(\"1\"), \"d2\" to Value(\"2\")))))))))\n        )\n\n    val expected =\n        listOf(Record(1, \"a\", mutableMapOf(\"a1\" to Value(\"Hello\"), \"a2\" to Value(\"World\")), mutableMapOf(\n            \"b\" to mutableListOf(Record(1, \"b\", mutableMapOf(\"b1\" to Value(\"1\"), \"b2\" to Value(\"2\")))),\n            \"c\" to mutableListOf(Record(1, \"c\", mutableMapOf(\"c1\" to Value(\"2\"), \"c2\" to Value(\"3\")),\n                mutableMapOf(\"d\" to mutableListOf(\n                    Record(1, \"d\", mutableMapOf(\"d1\" to Value(\"1\"), \"d2\" to Value(\"2\")))))))))\n        )\n\n    val filtered = RecordFilter(model).filter(records.asSequence()).toList()\n\n    assertEquals( expected, filtered )\n\n  }\n\n  @Test\n  fun testTypes() {\n\n    val model = FormParseConfig(rootRecordType = \"a\",\n        recordTypes = mutableMapOf(\"a\" to RecordType(label = \"A\", filter = \"\"\"\n                  str = \"a string\"\n                  and\n                  3 < int < 5\n                  and\n                  1.1 < dbl < 1.3\n                  and\n                  none = \"member type not set\"\n                  and\n                  undef = \"member not defined\"\n                   \"\"\", valueTypes = mutableListOf(\"str\", \"int\", \"dbl\", \"none\", \"undef\"), children = mutableListOf())),\n        valueTypes = mutableMapOf(\"str\" to ValueType(type = ExDataType.STRING.name.lowercase()),\n            \"int\" to ValueType(type = ExDataType.NUMBER.name.lowercase()),\n            \"dbl\" to ValueType(type = ExDataType.NUMBER.name.lowercase()), \"none\" to ValueType( /* type not set */)))\n\n    val records =\n        listOf(Record(1, \"a\",\n            mutableMapOf(\"str\" to Value(\"a string\"), \"int\" to Value(\"4\"), \"dbl\" to Value(\"1.2\"), \"none\" to Value(\"member type not set\"),\n                \"undef\" to Value(\"member not defined\"))), Record(2, \"a\",\n            mutableMapOf(\"str\" to Value(\"wrong\"), \"int\" to Value(\"4\"), \"dbl\" to Value(\"1.2\"), \"none\" to Value(\"member type not set\"),\n                \"undef\" to Value(\"member not defined\"))), Record(3, \"a\",\n            mutableMapOf(\"str\" to Value(\"a string\"), \"int\" to Value(\"6\"), \"dbl\" to Value(\"1.2\"), \"none\" to Value(\"member type not set\"),\n                \"undef\" to Value(\"member not defined\"))), Record(4, \"a\",\n            mutableMapOf(\"str\" to Value(\"a string\"), \"int\" to Value(\"4\"), \"dbl\" to Value(\"1.7\"), \"none\" to Value(\"member type not set\"),\n                \"undef\" to Value(\"member not defined\"))), Record(5, \"a\",\n            mutableMapOf(\"str\" to Value(\"a string\"), \"int\" to Value(\"4\"), \"dbl\" to Value(\"1.2\"), \"none\" to Value(\"wrong\"),\n                \"undef\" to Value(\"member not defined\"))), Record(6, \"a\",\n            mutableMapOf(\"str\" to Value(\"a string\"), \"int\" to Value(\"4\"), \"dbl\" to Value(\"1.2\"), \"none\" to Value(\"member type not set\"),\n                \"undef\" to Value(\"wrong\")))\n        )\n\n    val filtered = RecordFilter(model).filter(records.asSequence()).toList()\n\n    assertEquals( 1, filtered.size )\n    assertEquals( records[0], filtered[0] )\n\n  }\n}\n"
  },
  {
    "path": "src/test/java/io/mfj/textricator/record/output/CsvOutputTest.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.record.output\n\nimport io.mfj.textricator.record.Record\nimport io.mfj.textricator.form.config.FormParseConfigUtil\nimport io.mfj.textricator.record.Value\n\nimport java.io.ByteArrayOutputStream\n\nimport org.junit.*\nimport org.junit.Assert.*\n\nclass CsvOutputTest {\n\n  @Test\n  fun test() {\n    val model = FormParseConfigUtil.parseYaml( \"\"\"\nrootRecordType: person\nrecordTypes:\n  person:\n    label: \"Person\"\n    valueTypes:\n      - name\n      - dob\n    children:\n      - case\n      - address\n  case:\n    label: \"Case\"\n    valueTypes:\n      - caseId\n      - date\n    children:\n      - fee\n  fee:\n    label: \"Fee\"\n    valueTypes:\n      - desc\n      - amount\n  address:\n    label: \"Address\"\n    valueTypes:\n      - city\n      - state\nvalueTypes:\n  name:\n    label: \"Name\"\n  dob:\n    label: \"Date of Birth\"\n  caseId:\n    label: \"Case ID\"\n  date:\n    label: \"Date\"\n  desc:\n    label: \"Fee Description\"\n  amount:\n    label: \"Fee Amount\"\nstates:\n  name: {}\n  dob: {}\n  caseId: {}\n  date: {}\n  desc: {}\n  amount: {}\n  city: {}\n\"\"\" )\n\n    val root = Record(1, \"person\", mutableMapOf(\"name\" to Value(\"John Doe\"), \"dob\" to Value(\"1/1/1980\")),\n        mutableMapOf(\"case\" to mutableListOf(\n            Record(1, \"case\", mutableMapOf(\"caseId\" to Value(\"1\"), \"date\" to Value(\"1/1/2018\"))),\n            Record(1, \"case\", mutableMapOf(\"caseId\" to Value(\"2\"), \"date\" to Value(\"3/3/2018\")),\n                mutableMapOf(\"fee\" to mutableListOf(Record(1, \"fee\",\n                    mutableMapOf(\"desc\" to Value(\"court fee\"), \"amount\" to Value(\"99.95\")))))),\n            Record(1, \"case\", mutableMapOf(\"caseId\" to Value(\"3\"), \"date\" to Value(\"7/1/2018\")),\n                mutableMapOf(\"fee\" to mutableListOf(\n                    Record(1, \"fee\", mutableMapOf(\"desc\" to Value(\"court fee\"), \"amount\" to Value(\"10\"))),\n                    Record(1, \"fee\",\n                        mutableMapOf(\"desc\" to Value(\"jail fee\"), \"amount\" to Value(\"5.99\"))))))), \"address\" to mutableListOf(\n            Record(1, \"address\", mutableMapOf(\"city\" to Value(\"Rochester\"), \"state\" to Value(\"NY\"))),\n            Record(1, \"address\", mutableMapOf(\"city\" to Value(\"Pittsburgh\"), \"state\" to Value(\"PA\"))))))\n\n    val buffer = ByteArrayOutputStream()\n    CsvRecordOutput(model,buffer).use { it.write(sequenceOf(root) ) }\n\n    val expected = \"\"\"\npage,Name,Date of Birth,Case ID,Date,Fee Description,Fee Amount,city,state\n1,John Doe,1/1/1980,1,1/1/2018,,,,\n1,John Doe,1/1/1980,2,3/3/2018,court fee,99.95,,\n1,John Doe,1/1/1980,3,7/1/2018,court fee,10,,\n1,John Doe,1/1/1980,3,7/1/2018,jail fee,5.99,,\n1,John Doe,1/1/1980,,,,,Rochester,NY\n1,John Doe,1/1/1980,,,,,Pittsburgh,PA\n\"\"\"\n\n    assertEquals( expected.trim(), String(buffer.toByteArray()).trim())\n\n  }\n\n}\n"
  },
  {
    "path": "src/test/java/io/mfj/textricator/record/output/XmlOutputTest.kt",
    "content": "/*\nThis file is part of Textricator.\nCopyright 2018 Measures for Justice Institute.\nCopyright 2021 Stephen Byrne.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Affero General Public License version 3 as published by the\nFree Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along\nwith this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\npackage io.mfj.textricator.record.output\n\nimport io.mfj.textricator.record.Record\nimport io.mfj.textricator.form.config.FormParseConfigUtil\nimport io.mfj.textricator.record.Value\n\nimport java.io.ByteArrayOutputStream\n\nimport com.fasterxml.jackson.dataformat.xml.XmlMapper\n\nimport org.junit.*\nimport org.junit.Assert.*\n\nclass XmlOutputTest {\n\n  @Test\n  fun test() {\n    val model = FormParseConfigUtil.parseYaml( \"\"\"\nrootRecordType: person\nrecordTypes:\n  person:\n    label: \"Person\"\n    valueTypes:\n      - name\n      - dob\n    children:\n      - case\n      - address\n  case:\n    label: \"Case\"\n    valueTypes:\n      - caseId\n      - date\n    children:\n      - fee\n  fee:\n    label: \"Fee\"\n    valueTypes:\n      - desc\n      - amount\n  address:\n    label: \"Address\"\n    valueTypes:\n      - city\n      - state\nvalueTypes:\n  name:\n    label: \"Name\"\n  dob:\n    label: \"Date of Birth\"\n  caseId:\n    label: \"Case ID\"\n  date:\n    label: \"Date\"\n  desc:\n    label: \"Fee Description\"\n  amount:\n    label: \"Fee Amount\"\nstates:\n  name: {}\n  dob: {}\n  caseId: {}\n  date: {}\n  desc: {}\n  amount: {}\n  city: {}\n\"\"\" )\n\n    val root = Record(1, \"person\", mutableMapOf(\"name\" to Value(\"John Doe\"), \"dob\" to Value(\"1/1/1980\")),\n        mutableMapOf(\"case\" to mutableListOf(\n            Record(1, \"case\", mutableMapOf(\"caseId\" to Value(\"1\"), \"date\" to Value(\"1/1/2018\"))),\n            Record(1, \"case\", mutableMapOf(\"caseId\" to Value(\"2\"), \"date\" to Value(\"3/3/2018\")),\n                mutableMapOf(\"fee\" to mutableListOf(Record(1, \"fee\",\n                    mutableMapOf(\"desc\" to Value(\"court fee\"), \"amount\" to Value(\"99.95\")))))),\n            Record(1, \"case\", mutableMapOf(\"caseId\" to Value(\"3\"), \"date\" to Value(\"7/1/2018\")),\n                mutableMapOf(\"fee\" to mutableListOf(\n                    Record(1, \"fee\", mutableMapOf(\"desc\" to Value(\"court fee\"), \"amount\" to Value(\"10\"))),\n                    Record(1, \"fee\",\n                        mutableMapOf(\"desc\" to Value(\"jail fee\"), \"amount\" to Value(\"5.99\"))))))), \"address\" to mutableListOf(\n            Record(1, \"address\", mutableMapOf(\"city\" to Value(\"Rochester\"), \"state\" to Value(\"NY\"))),\n            Record(1, \"address\", mutableMapOf(\"city\" to Value(\"Pittsburgh\"), \"state\" to Value(\"PA\"))))))\n\n    val buffer = ByteArrayOutputStream()\n    XmlRecordOutput(model,buffer).use { it.write(sequenceOf(root) ) }\n    val str = String(buffer.toByteArray()).trim()\n    val normalized = normalize(str)\n\n    val expected = normalize( \"\"\"\n      <Records>\n        <Record>\n          <pageNumber>1</pageNumber>\n          <typeId>person</typeId>\n          <values>\n            <name>\n              <text>John Doe</text>\n            </name>\n            <dob>\n              <text>1/1/1980</text>\n            </dob>\n          </values>\n          <children>\n            <case>\n              <pageNumber>1</pageNumber>\n              <typeId>case</typeId>\n              <values>\n                <caseId>\n                  <text>1</text>\n                </caseId>\n                <date>\n                  <text>1/1/2018</text>\n                </date>\n              </values>\n            </case>\n            <case>\n              <pageNumber>1</pageNumber>\n              <typeId>case</typeId>\n              <values>\n                <caseId>\n                  <text>2</text>\n                </caseId>\n                <date>\n                  <text>3/3/2018</text>\n                </date>\n              </values>\n              <children>\n                <fee>\n                  <pageNumber>1</pageNumber>\n                  <typeId>fee</typeId>\n                  <values>\n                    <desc>\n                      <text>court fee</text>\n                    </desc>\n                    <amount>\n                      <text>99.95</text>\n                    </amount>\n                  </values>\n                </fee>\n              </children>\n            </case>\n            <case>\n              <pageNumber>1</pageNumber>\n              <typeId>case</typeId>\n              <values>\n                <caseId>\n                  <text>3</text>\n                </caseId>\n                <date>\n                  <text>7/1/2018</text>\n                </date>\n              </values>\n              <children>\n                <fee>\n                  <pageNumber>1</pageNumber>\n                  <typeId>fee</typeId>\n                  <values>\n                    <desc>\n                      <text>court fee</text>\n                    </desc>\n                    <amount>\n                      <text>10</text>\n                    </amount>\n                  </values>\n                </fee>\n                <fee>\n                  <pageNumber>1</pageNumber>\n                  <typeId>fee</typeId>\n                  <values>\n                    <desc>\n                      <text>jail fee</text>\n                    </desc>\n                    <amount>\n                      <text>5.99</text>\n                    </amount>\n                  </values>\n                </fee>\n              </children>\n            </case>\n            <address>\n              <pageNumber>1</pageNumber>\n              <typeId>address</typeId>\n              <values>\n                <city>\n                  <text>Rochester</text>\n                </city>\n                <state>\n                  <text>NY</text>\n                </state>\n              </values>\n            </address>\n            <address>\n              <pageNumber>1</pageNumber>\n              <typeId>address</typeId>\n              <values>\n                <city>\n                  <text>Pittsburgh</text>\n                </city>\n                <state>\n                  <text>PA</text>\n                </state>\n              </values>\n            </address>\n          </children>\n        </Record>\n      </Records>\n    \"\"\" )\n\n    assertEquals( expected, normalized )\n\n  }\n\n  /**\n   * Normalize the XML so we can compare 2 documents.\n   */\n  private fun normalize( input:String ):String {\n    val mapper = XmlMapper()\n    val tree = mapper.readTree(input)\n    val normalized = mapper.writeValueAsString(tree)\n    return normalized\n  }\n\n}\n"
  },
  {
    "path": "src/test/resources/io/mfj/textricator/examples/probes.yml",
    "content": "# All measurements are in points. 1 point = 1/72 of an inch.\n# x-coordinates are from the left edge of the page.\n# y-coordinates are from the top edge of the page.\n\n# Use the built-in pdfbox extractor\nextractor: \"pdf.pdfbox\"\n\n# Ignore everything above 88pt from the top\ntop: 88\n\n# Ignore everything below 170pt from the top\nbottom: 170\n\n# If multiple text segments are withing 2pt vertically, consider them in the same row.\nmaxRowDistance: 2\n\n# Define the columns, based on the x-coordinate where the column starts:\ncols:\n  \"name\": 0\n  \"launched\": 132\n  \"speed\": 235\n  \"cospar\": 249\n  \"power\": 355\n  \"mass\": 415\n\ntypes:\n  \"name\":\n    label: \"Name\"\n\n  \"launched\":\n    label: \"Launch Date\"\n\n  \"speed\":\n    label: \"Speed (km/s)\"\n    type: \"number\"\n\n  \"cospar\":\n    label: \"COSPAR ID\"\n\n  \"power\":\n    label: \"Power (watts)\"\n    type: \"number\"\n\n  \"mass\":\n    label: \"Mass (pounds)\"\n    # Add .0 to the end of mass\n    replacements:\n      -\n        pattern: \"^(.*)$\"\n        replacement: \"$1.0\"\n\n# Omit if Power is less than 200\nfilter: 'power >= 200'\n"
  },
  {
    "path": "src/test/resources/io/mfj/textricator/examples/rap-sheet.csv",
    "content": "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\n1,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\",,,,,,,,,,,,,,,,,,,,,\n1,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\",,,,,,,,,,,,,,,,,,,,,\n1,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,,,,,,,,,,,,\n1,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,,,,,,,,,,,\n1,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,,,,,,,,,,,,\n1,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,\n1,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\"\n1,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,\n1,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,,,,,,,,,,,,\n1,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\"\n"
  },
  {
    "path": "src/test/resources/io/mfj/textricator/examples/rap-sheet.yml",
    "content": "---\nextractor: \"pdf.pdfbox\"\n\nheader:\n  default: 0\nfooter:\n  default: 770\n\nmaxRowDistance: 2\n\nrootRecordType: rapsheet\nrecordTypes:\n  rapsheet:\n    label: \"Rap Sheet\"\n    valueTypes:\n      - requester\n      - requestDate\n      - requestTime\n      - attn\n      - header\n      - caDojId\n      - dob\n      - sex\n      - race\n      - height\n      - weight\n      - eyeColor\n      - hairColor\n      - birthState\n    children:\n      - name\n      - arrest\n  name:\n    label: \"name\"\n    valueTypes:\n      - nameId\n      - lastName\n      - firstName\n  arrest:\n    label: \"arrest\"\n    valueTypes:\n      - arrestDate\n      - arrestNameId\n      - arrestDob\n      - arrestDate\n      - arrestLocation\n    children:\n      - charge\n      - appearance\n  charge:\n    label: \"charge\"\n    valueTypes:\n      - chargeNumber\n      - chargeId\n      - chargeCode\n      - chargeName\n      - chargeDesc\n  appearance:\n    label: \"appearance\"\n    valueTypes:\n      - appearanceNameId\n      - appearanceDate\n      - appearanceCourt\n    children:\n      - dispo\n  dispo:\n    label: \"disposition\"\n    valueTypes:\n      - dispoChargeNumber\n      - dispoChargeId\n      - dispoChargeCode\n      - dispoChargeName\n      - dispoChargeDesc\n      - dispo\n      - dispoConvStatus\n      - dispoSentence\n\nvalueTypes:\n  requestDate:\n    replacements:\n      -\n        pattern: \"^DATE:(.*)$\"\n        replacement: \"$1\"\n  requestTime:\n    replacements:\n      -\n        pattern: \"^TIME:(.*)$\"\n        replacement: \"$1\"\n  attn:\n    replacements:\n      -\n        pattern: \"^ATTN:(.*)$\"\n        replacement: \"$1\"\n  caDojId:\n    replacements:\n      -\n        pattern: \"^CII/(.*)$\"\n        replacement: \"$1\"\n  dob:\n    replacements:\n      -\n        pattern: \"^DOB/(.*)$\"\n        replacement: \"$1\"\n  sex:\n    replacements:\n      -\n        pattern: \"^SEX/(.*)$\"\n        replacement: \"$1\"\n  race:\n    replacements:\n      -\n        pattern: \"^RAC/(.*)$\"\n        replacement: \"$1\"\n  height:\n    replacements:\n      -\n        pattern: \"^HGT/(.*)$\"\n        replacement: \"$1\"\n  weight:\n    replacements:\n      -\n        pattern: \"^WGT/(.*)$\"\n        replacement: \"$1\"\n  eyeColor:\n    replacements:\n      -\n        pattern: \"^EYE/(.*)$\"\n        replacement: \"$1\"\n  hairColor:\n    replacements:\n      -\n        pattern: \"^HAIR/(.*)$\"\n        replacement: \"$1\"\n  birthState:\n    replacements:\n      -\n        pattern: \"^POB/(.*)$\"\n        replacement: \"$1\"\n\n  nameId:\n    replacements:\n      -\n        pattern: \"^NAM/(.*)$\"\n        replacement: \"$1\"\n\n  lastName:\n    replacements:\n      -\n        pattern: \"^([^,]),.*$\"\n        replacement: \"$1\"\n  firstName:\n    replacements:\n      -\n        pattern: \"^[^,],(.*)$\"\n        replacement: \"$1\"\n\n  arrestNameId:\n    replacements:\n      -\n        pattern: \"^NAM:(.*)$\"\n        replacement: \"$1\"\n\n  arrestDob:\n    replacements:\n      -\n        pattern: \"^DOB:(.*)$\"\n        replacement: \"$1\"\n\n  chargeNumber:\n    replacements:\n      -\n        pattern: \"^CNT:(.*)$\"\n        replacement: \"$1\"\n\n  chargeId:\n    replacements:\n      -\n        pattern: \"^#(.*)$\"\n        replacement: \"$1\"\n\n  appearanceNameId:\n    replacements:\n      -\n        pattern: \"^NAM:(.*)$\"\n        replacement: \"$1\"\n\n  dispoChargeNumber:\n    replacements:\n      -\n        pattern: \"^CNT:(.*)$\"\n        replacement: \"$1\"\n\n  dispoChargeId:\n    replacements:\n      -\n        pattern: \"^#(.*)$\"\n        replacement: \"$1\"\n\n  dispo:\n    replacements:\n      -\n        pattern: \"^\\\\*DISPO:(.*)$\"\n        replacement: \"$1\"\n\n  dispoConvStatus:\n    replacements:\n      -\n        pattern: \"^CONV STATUS:(.*)$\"\n        replacement: \"$1\"\n\n  dispoSentence:\n    replacements:\n      -\n        pattern: \"^SEN:(.*)$\"\n        replacement: \"$1\"\n\ninitialState: \"INIT\"\n\nstates:\n  INIT:\n    transitions:\n      -\n        condition: re\n        nextState: re\n\n  re:\n    include: false\n    transitions:\n      -\n        condition: sameLine\n        nextState: requester\n\n  requester:\n    startRecord: true\n    transitions:\n      -\n        condition: requestDate\n        nextState: requestDate\n\n  requestDate:\n    transitions:\n      -\n        condition: requestTime\n        nextState: requestTime\n\n  requestTime:\n    transitions:\n      -\n        condition: nextLine\n        nextState: restricted\n\n  restricted:\n    include: false\n    transitions:\n      -\n        condition: sameLine\n        nextState: restricted\n      -\n        condition: attn\n        nextState: attn\n\n  attn:\n    transitions:\n      -\n        condition: sameLine\n        nextState: attn\n      -\n        condition: any\n        nextState: header\n\n  header:\n    transitions:\n      -\n        condition: liveScan\n        nextState: liveScan\n      -\n        condition: any\n        nextState: header\n\n  liveScan:\n    include: false\n    transitions:\n      -\n        condition: sameLine\n        nextState: liveScan\n      -\n        condition: caDojId\n        nextState: caDojId\n\n  caDojId:\n    transitions:\n      -\n        condition: dob\n        nextState: dob\n\n  dob:\n    transitions:\n      -\n        condition: sex\n        nextState: sex\n\n  sex:\n    transitions:\n      -\n        condition: race\n        nextState: race\n\n  race:\n    transitions:\n      -\n        condition: height\n        nextState: height\n\n  height:\n    transitions:\n      -\n        condition: weight\n        nextState: weight\n\n  weight:\n    transitions:\n      -\n        condition: eyeColor\n        nextState: eyeColor\n\n  eyeColor:\n    transitions:\n      -\n        condition: hairColor\n        nextState: hairColor\n\n  hairColor:\n    transitions:\n      -\n        condition: birthState\n        nextState: birthState\n\n  birthState:\n    transitions:\n      -\n        condition: nam01\n        nextState: nameId\n\n  nameId:\n    startRecord: true\n    transitions:\n      -\n        condition: sameLine\n        nextState: name\n\n  name:\n    valueTypes: [ lastName, firstName ]\n    transitions:\n      -\n        condition: sameLine\n        nextState: name\n      -\n        condition: nameId\n        nextState: nameId\n      -\n        condition: cycleDelimiterStart\n        nextState: cycleDelimiter\n\n  cycleDelimiter:\n    include: false\n    transitions:\n      -\n        condition: cycleDelimiterContinue\n        nextState: cycleDelimiter\n      -\n        condition: arrest\n        nextState: arrest\n\n  arrest:\n    include: false\n    transitions:\n      -\n        condition: eventNameId\n        nextState: arrestNameId\n\n  arrestNameId:\n    startRecord: true\n    transitions:\n      -\n        condition: arrestDob\n        nextState: arrestDob\n\n  arrestDob:\n    transitions:\n      -\n        condition: eventDate\n        nextState: arrestDate\n\n  arrestDate:\n    transitions:\n      -\n        condition: sameLine\n        nextState: arrestLocation\n\n  arrestLocation:\n    transitions:\n      -\n        condition: sameLine\n        nextState: arrestLocation\n      -\n        condition: chargeNumber\n        nextState: chargeNumber\n\n  chargeNumber:\n    startRecord: true\n    transitions:\n      -\n        condition: chargeId\n        nextState: chargeId\n      -\n        condition: chargeCode\n        nextState: chargeCode\n\n  chargeId:\n    transitions:\n      -\n        condition: chargeCode\n        nextState: chargeCode\n\n  chargeCode:\n    transitions:\n      -\n        condition: sameLine\n        nextState: chargeName\n\n  chargeName:\n    transitions:\n      -\n        condition: sameLine\n        nextState: chargeName\n      -\n        condition: chargeDesc\n        nextState: chargeDesc\n      -\n        condition: chargeNumber\n        nextState: chargeNumber\n      -\n        condition: eventDelimiterStart\n        nextState: eventDelimiter\n      -\n        condition: endStart\n        nextState: endStart\n\n  chargeDesc:\n    transitions:\n      -\n        condition: chargeNumber\n        nextState: chargeNumber\n      -\n        condition: chargeDesc\n        nextState: chargeDesc\n      -\n        condition: endStart\n        nextState: endStart\n\n  eventDelimiter:\n    include: false\n    transitions:\n      -\n        condition: eventDelimiterContinue\n        nextState: eventDelimiter\n      -\n        condition: court\n        nextState: court\n\n  court:\n    include: false\n    transitions:\n      -\n        condition: eventNameId\n        nextState: appearanceNameId\n\n  appearanceNameId:\n    startRecord: true\n    transitions:\n      -\n        condition: eventDate\n        nextState: appearanceDate\n\n  appearanceDate:\n    transitions:\n      -\n        condition: sameLine\n        nextState: appearanceCourt\n\n  appearanceCourt:\n    transitions:\n      -\n        condition: sameLine\n        nextState: appearanceCourt\n      -\n        condition: chargeNumber\n        nextState: dispoChargeNumber\n\n  dispoChargeNumber:\n    startRecord: true\n    transitions:\n      -\n        condition: chargeId\n        nextState: dispoChargeId\n      -\n        condition: chargeCode\n        nextState: dispoChargeCode\n\n  dispoChargeId:\n    transitions:\n      -\n        condition: chargeCode\n        nextState: dispoChargeCode\n\n  dispoChargeCode:\n    transitions:\n      -\n        condition: sameLine\n        nextState: dispoChargeName\n\n  dispoChargeName:\n    transitions:\n      -\n        condition: sameLine\n        nextState: dispoChargeName\n      -\n        condition: dispo\n        nextState: dispo\n\n  dispo:\n    transitions:\n      -\n        condition: sameLine\n        nextState: dispo\n      -\n        condition: dispoConv\n        nextState: dispoConvStatus\n      -\n        condition: endStart\n        nextState: endStart\n\n  dispoConvStatus:\n    transitions:\n      -\n        condition: sameLine\n        nextState: dispoConvStatus\n      -\n        condition: dispoWrap\n        nextState: dispoConvStatus\n      -\n        condition: dispoSentence\n        nextState: dispoSentence\n      -\n        condition: chargeNumber\n        nextState: dispoChargeNumber\n      -\n        condition: eventDelimiterStart\n        nextState: eventDelimiter\n      -\n        condition: cycleDelimiterStart\n        nextState: cycleDelimiter\n      -\n        condition: endStart\n        nextState: endStart\n\n  dispoSentence:\n    transitions:\n      -\n        condition: sameLine\n        nextState: dispoSentence\n      -\n        condition: dispoWrap\n        nextState: dispoSentence\n      -\n        condition: chargeNumber\n        nextState: dispoChargeNumber\n      -\n        condition: eventDelimiterStart\n        nextState: eventDelimiter\n      -\n        condition: cycleDelimiterStart\n        nextState: cycleDelimiter\n      -\n        condition: endStart\n        nextState: endStart\n\n  endStart:\n    include: false\n    transitions:\n      -\n        condition: asterisk\n        nextState: end2\n  end2:\n    include: false\n    transitions:\n      -\n        condition: asterisk\n        nextState: end3\n  end3:\n    include: false\n    transitions:\n      -\n        condition: endOfMessage\n        nextState: end\n  end:\n    include: false\n    transitions:\n      -\n        condition: any\n        nextState: end\n\nconditions:\n\n  any: '0 = 0'\n\n  sameLine: '-2 <= uly_rel <= 2'\n\n  nextLine: 'uly_rel > 2'\n\n  re: '53 < ulx < 54 and text = \"RE:\"'\n\n  requestDate: 'text =~ /^DATE:.*/'\n\n  requestTime: 'text =~ /^TIME:.*/'\n\n  attn: 'text =~ /^ATTN:.*/'\n\n  liveScan: '53 <= ulx <= 54 and text = \"**LIVE\"'\n\n  caDojId: 'text =~ /^CII\\/.*/'\n\n  dob: 'text =~ /^DOB\\/.*/'\n\n  sex: 'text =~ /^SEX\\/.*/'\n\n  race : 'text =~ /^RAC\\/.*/'\n\n  height: 'text =~ /^HGT\\/.*/'\n\n  weight: 'text =~ /^WGT\\/.*/'\n\n  eyeColor: 'text =~ /^EYE\\/.*/'\n\n  hairColor: 'text =~ /^HAIR\\/.*/'\n\n  birthState: 'text =~ /^POB\\/.*/'\n\n  nam01: 'text = \"NAM/01\"'\n\n  nameId: '76 <= ulx <= 77 and text =~ /^[0-9]+$/'\n\n  cycleDelimiterStart: '53 < ulx < 54 and text = \"*\"'\n  cycleDelimiterContinue: '-2 <= uly_rel <= 2 and text = \"*\"'\n\n  arrest: '53 < ulx < 54 and text = \"ARR/DET/CITE:\"'\n\n  eventNameId: 'text =~ /^NAM:[0-9]+$/'\n\n  arrestDob: 'text =~ /^DOB:[0-9]+$/'\n\n  eventDate: '53 < ulx < 54 and text =~ /^[0-9]+$/'\n\n  chargeNumber: '53 < ulx < 54 and text =~ /^CNT:[0-9]+$/'\n\n  chargeId: '-2 <= uly_rel <= 2 and text =~ /^#[0-9]+$/'\n\n  chargeCode: '65 < ulx < 66 and text =~ /^[0-9]+$/'\n\n  chargeDesc: '70 < ulx'\n\n  eventDelimiterStart: '53 < ulx < 54 and text = \"-\"'\n\n  eventDelimiterContinue: '-2 <= uly_rel <= 2 and text = \"-\"'\n\n  court: '53 < ulx < 54 and text = \"COURT:\"'\n\n  dispo: '53 < ulx < 54 and text =~ /^\\\\*DISPO:.*$/'\n\n  dispoConv: '70 < ulx < 71 and text = \"CONV\"'\n\n  dispoSentence: '70 < ulx < 71 and text = \"SEN:\"'\n\n  dispoWrap: '100 < ulx'\n\n  endStart: '82 < ulx < 83 and text = \"*\"'\n\n  asterisk: '-2 <= uly_rel <= 2 and text = \"*\"'\n\n  endOfMessage: '-2 <= uly_rel <= 2 and text = \"END\"'\n"
  },
  {
    "path": "src/test/resources/io/mfj/textricator/examples/school-employee-list.csv",
    "content": "page,Employee ID,Name,Hire Date,Occupation,Important Info?,Boolean 1,Boolean 2,Boolean 3,Salary,Attending Child,Grade\n1,ID-0001,Mam Bargera,01/21/20XX,Librarian,,No,No,Yes,\"29,990\",Maria,Fifth\n1,ID-0001,Mam Bargera,01/21/20XX,Librarian,,No,No,Yes,\"29,990\",Mario,Fourth\n1,ID-0002,Hony Tawk,03/13/20XX,Teacher,NECESSARY INFO,No,Yes,No,\"38,749\",,\n1,ID-0003,Gune Rilfberg,11/15/20XX,Superintendent,,Yes,Yes,No,\"94,839\",Johnny,Second\n1,ID-0004,Spric Earrow,04/21/20XX,Janitor,NECESSARY INFO,No,Yes,Yes,\"12,239\",,\n1,ID-0005,Modney Rullen,08/05/20XX,Secretary,,Yes,No,No,\"24,391\",Johnny,Second\n1,ID-0005,Modney Rullen,08/05/20XX,Secretary,,Yes,No,No,\"24,391\",Lucina Ellegancia,Second\n1,ID-0005,Modney Rullen,08/05/20XX,Secretary,,Yes,No,No,\"24,391\",Horace,Third\n1,ID-0006,Stellisa Eamer,06/30/20XX,Principal,,Yes,No,Yes,\"94,139\",,\n1,ID-0007,Kric Eoston,12/21/20XX,Assistant,NECESSARY INFO,No,No,No,\"11,192\",Justin,\n2,ID-0008,Dob Rydek,02/11/20XX,Janitor,,Yes,Yes,Yes,\"20,002\",,\n2,ID-0009,Shan Ryeckler,03/19/20XX,Teacher,NECESSARY INFO,No,Yes,Yes,\"42,910\",,\n"
  },
  {
    "path": "src/test/resources/io/mfj/textricator/examples/school-employee-list.yml",
    "content": "---\n# Use the pdfbox parser, since it's the same one we used to originally etract the text to build this planning document.\nextractor: \"pdf.pdfbox\"\n\n# All measurements are in points. 1 point = 1/72 of an inch.\n# x-coordinates are from the left edge of the page.\n# y-coordinates are from the top edge of the page.\nheader:\n    # ignore anything less than this many points from the top, default and per-page\n  default: 130\nfooter:\n    # ignore anything less than this many points from the bottom, default and per-page\n  default: 700\n\n# Text segments are generally parsed in order, top to bottom, left to right.\n# If two text segments have y-coordinates within this many points, consider them on the same line,\n# and process the one further left first, even if it is 0.4pt lower on the page.\nmaxRowDistance: 2\n\n# Define the output data record.\n# Since the main record type we're collecting information on is our employees,\n# we'll have that be the root type for our harvested information.\nrootRecordType: employee\nrecordTypes:\n  employee:\n    label: \"employee\" # Labels are used when nested recordTypes come into play, like this document.\n    valueTypes:\n      # Not sure what to name a valueType? Just make something up!\n      - employee\n      - name\n      - hiredate\n      - occupation\n      - showinfo\n      - bool1\n      - bool2\n      - bool3\n      - salary\n    children:\n      # In this example, there are multiple children nested under an employee,\n      # so we'll treat it as a 'child' to the 'employee' recordType.\n      - child\n  child:\n    label: \"child\"\n    valueTypes:\n      - child\n      - grade\n\nvalueTypes:\n  employee:\n    # In the CSV, use \"Employee ID\" as the column header instead of \"employee\".\n    label: \"Employee ID\"\n  name:\n    label: \"Name\"\n  hiredate:\n    label: \"Hire Date\"\n  occupation:\n    label: \"Occupation\"\n  salary:\n    label: \"Salary\"\n  showinfo:\n    label: \"Important Info?\"\n  bool1:\n    label: \"Boolean 1\"\n  bool2:\n    label: \"Boolean 2\"\n  bool3:\n    label: \"Boolean 3\"\n  child:\n    label: \"Attending Child\"\n  grade:\n    label: \"Grade\"\n\n# Now we define the finite-state machine\n# Let's name the state that our machine starts off with:\ninitialState: \"INIT\"\n\n# When each text segment is encountered, each transition for the current state is checked.\nstates:\n  INIT:\n    transitions:\n      # The first bit of text we reach is 'ID-0001', so we'll try the only transition that should work here.\n      -\n        # If this condition matches (which it should)\n        condition: employee # Curious about the condition? Sxroll further down to the conditions section of this YAML.\n        # Then we'll switch to the 'employee' state!\n        nextState: employee\n\n  employee: # ID number with the format 'ID-####'\n    startRecord: true # When we enter this stage, we'll create a new \"case\" record.\n    transitions:\n      - # Now we move on to the name label. Once again, by varifying the condition and moving on after that.\n        condition: namelabel\n        nextState: namelabel\n\n  namelabel:\n    include: false # The label isn't important information in and of itself, so we can just not include it in the data.\n    transitions:\n      -\n        condition: name\n        nextState: name\n\n  name:\n    transitions:\n      -\n        # Sometimes a name will be in two segments, and we'll hit another 'name' text segment before anything else.\n        # In that case, a state can transition to itself, compounding the information picked up in it.\n        condition: name\n        nextState: name\n      -\n        # Does the first condition not match the text? We move onto the next one.\n        condition: hiredateLabel\n        nextState: hiredateLabel\n\n  hiredateLabel:\n    include: false\n    transitions:\n      -\n        condition: hiredateLabel\n        nextState: hiredateLabel\n      -\n        condition: hiredate\n        nextState: hiredate\n\n  hiredate:\n    transitions:\n      -\n        condition: occupationLabel\n        nextState: occupationLabel\n\n  occupationLabel:\n    include: false\n    transitions:\n      -\n        condition: occupation\n        nextState: occupation\n\n  occupation:\n    transitions:\n      -\n        condition: occupation\n        nextState: occupation\n      -\n        # This state and the next are an example of how you can choose, using conditions, what to include or not.\n        # They share the same area of a document, but have qualities to them that can be distinguishable.\n        # Does it meet 'showinfo' conditions? Then we go to the 'showinfo' state that includes it.\n        condition: showinfo\n        nextState: showinfo\n      -\n        # Doesn't meet 'showinfo'? Then check for 'notinfo' and exclude it.\n        condition: notinfo\n        nextState: notinfo\n  showinfo:\n    transitions:\n      -\n        condition: showinfo\n        nextState: showinfo\n      -\n        condition: bool1\n        nextState: bool1\n  notinfo:\n    include: false\n    transitions:\n      -\n        condition: notinfo\n        nextState: notinfo\n      -\n        condition: bool1\n        nextState: bool1\n\n  bool1:\n    transitions:\n      -\n        condition: bool2\n        nextState: bool2\n  bool2:\n    transitions:\n      -\n        condition: bool3\n        nextState: bool3\n  bool3:\n    transitions:\n      -\n        condition: salaryLabel\n        nextState: salaryLabel\n\n  salaryLabel:\n    include: false\n    transitions:\n      -\n        condition: salary\n        nextState: salary\n\n  salary:\n    transitions:\n      -\n        condition: childrenLabel\n        nextState: childrenLabel\n      -\n        condition: employee\n        nextState: employee\n      -\n        condition: end\n        nextState: end\n\n  childrenLabel:\n    include: false\n    transitions:\n      -\n        condition: childrenLabel\n        nextState: childrenLabel\n      -\n        condition: childLabel\n        nextState: childLabel\n\n  childLabel:\n    include: false\n    transitions:\n      -\n        condition: child\n        nextState: child\n\n  child:\n    # Here we reach a datatype nested within another datatype. We can start records using this child datatype.\n    # In the process, we'll be making multiple rows for the parent datatype, each one holding onto it's own child.\n    startRecord: true\n    transitions:\n      -\n        condition: child\n        nextState: child\n      -\n        condition: gradeLabel\n        nextState: gradeLabel\n      -\n        condition: childLabel\n        nextState: childLabel\n\n  gradeLabel:\n    include: false\n    transitions:\n      -\n        # Normally, there would always been an instance of a grade appearing right after the label.\n        # But in this document, we have one instance of that not happening under ID-0007's child.\n        condition: grade\n        nextState: grade\n      -\n        # So we just account for that possibility by adding a transition out of the label.\n        condition: employee\n        nextState: employee\n\n  grade:\n    transitions:\n      -\n        condition: employee\n        nextState: employee\n      -\n        condition: childLabel\n        nextState: childLabel\n      -\n        # Reach the end of the usable info in a document, but there's still text left to go?\n        # An easy fix is to just create a looping, not-included state to finish the document off.\n        condition: end\n        nextState: end\n\n  end:\n    # We reached a point in the document where all the useful information is gone, but we still have text to go.\n    include: false\n    transitions:\n      -\n        # By using an always-true condition such as 'any', we can loop this state until the document has been completely gone through.\n        condition: any\n        nextState: end\n\n# Here we define the conditions:\nconditions:\n\n  # An example of comparing text with regex.\n  # In this case, we're making sure that the text contains the characters 'ID-' followed by any amount of numbers.\n  employee: 'text =~ /ID-(\\\\d)*/'\n\n  # You can match based on the x- and y- coordinates of the upper left and lower right corners of the rectangle\n  # containing the text. ulx = Upper-Left X-coordinate. lry = Lower-Right Y-coordinate. Also uly and lrx.\n  # You can define the lower and upper limit for each, inclusive.\n  namelabel: '70 < ulx < 80 and font = \"BCDFEE+Calibri-Bold\"'\n\n  # You can also match based on the type of font used, including if it was bolded or italicized.\n  name: '112 < ulx < 200 and font = \"BCDEEE+Calibri\"'\n\n  hiredateLabel: '230 < ulx < 270 and font = \"BCDFEE+Calibri-Bold\"'\n\n  hiredate: '280 < ulx < 290 and font = \"BCDEEE+Calibri\"'\n\n  occupationLabel: '391 < ulx < 393 and font = \"BCDFEE+Calibri-Bold\"'\n\n  occupation: '394 < ulx < 700 and font = \"BCDEEE+Calibri\"'\n\n  showinfo: 'font = \"BCDJEE+Georgia\"'\n\n  notinfo:  'font = \"BCDEEE+Calibri\"'\n\n  bool1:  'font = \"BCDIEE+Cambria\"'\n\n  bool2:  'font = \"BCDIEE+Cambria\"'\n\n  bool3:  'font = \"BCDIEE+Cambria\"'\n\n  salaryLabel: '391 < ulx < 393 and font = \"BCDFEE+Calibri-Bold\"'\n\n  salary: '394 < ulx < 700 and font = \"BCDEEE+Calibri\"'\n\n  childrenLabel: '70 < ulx < 140 and font = \"BCDFEE+Calibri-Bold\" and text =~ /(Attending)|(Children:)/'\n\n  childLabel: '230 < ulx < 240 and font = \"BCDFEE+Calibri-Bold\"'\n\n  child: '230 < ulx < 380 and font = \"BCDEEE+Calibri\"'\n\n  gradeLabel: '391 < ulx < 393 and font = \"BCDFEE+Calibri-Bold\"'\n\n  grade: '394 < ulx < 700 and font = \"BCDEEE+Calibri\"'\n\n  # You can also match based on the size of the font and on specific text.\n  end: 'fontSize = 16.0 and text = \"TOTAL:\"'\n\n  # Need a condition that is always true? \"1=1\" does that for you.\n  any: \"1 = 1\"\n"
  }
]