From 35673c94d9126db47db57949ffba566aa0a2f5ca Mon Sep 17 00:00:00 2001 From: Marie Roald Date: Sat, 28 Feb 2026 11:35:06 +0000 Subject: [PATCH] Add tool comparison code Co-authored-by: Yngve Mardal Moe --- .pre-commit-config.yaml | 4 - Cargo.lock | 2 +- .../README.md | 9 + .../calamari/evaluate.py | 835 ++++++++++++++++++ .../calamari/run_calamari.Dockerfile | 9 + .../calamari/run_calamari.py | 30 + .../calamari/run_calamari.sh | 10 + .../calamari/textprocessors.py | 831 +++++++++++++++++ ...k_for_multi_codepoint_grapheme_clusters.py | 15 + .../dinglehopper/container_script.sh | 11 + .../dinglehopper/run_dinglehopper.Dockerfile | 11 + .../dinglehopper/run_dinglehopper.sh | 10 + .../hip21_get_data.py | 56 ++ .../hip21_get_results.py | 140 +++ .../hip21_run_analysis.sh | 51 ++ .../isri/run_isri.Dockerfile | 14 + .../isri/run_isri.sh | 10 + .../isri/run_isri_analysis.py | 30 + .../jiwer/run_jiwer.Dockerfile | 9 + .../jiwer/run_jiwer.py | 37 + .../jiwer/run_jiwer.sh | 10 + .../meeteval/run_meeteval.Dockerfile | 9 + .../meeteval/run_meeteval.py | 30 + .../meeteval/run_meeteval.sh | 10 + .../ocrevalUAtion/container_script.sh | 13 + .../run_ocrevalUAtion.Dockerfile | 13 + .../ocrevalUAtion/run_ocrevalUAtion.sh | 9 + .../stringalign/run_stringalign.Dockerfile | 9 + .../stringalign/run_stringalign.py | 136 +++ .../stringalign/run_stringalign.sh | 10 + .../synthetic_emoji_get_results.py | 98 ++ .../synthetic_emoji_make_data.sh | 6 + .../synthetic_emoji_run_analysis.sh | 44 + 33 files changed, 2516 insertions(+), 5 deletions(-) create mode 100644 examples/compare_transcription_eval_tools/README.md create mode 100644 examples/compare_transcription_eval_tools/calamari/evaluate.py create mode 100644 examples/compare_transcription_eval_tools/calamari/run_calamari.Dockerfile create mode 100644 examples/compare_transcription_eval_tools/calamari/run_calamari.py create mode 100644 examples/compare_transcription_eval_tools/calamari/run_calamari.sh create mode 100644 examples/compare_transcription_eval_tools/calamari/textprocessors.py create mode 100644 examples/compare_transcription_eval_tools/check_for_multi_codepoint_grapheme_clusters.py create mode 100644 examples/compare_transcription_eval_tools/dinglehopper/container_script.sh create mode 100644 examples/compare_transcription_eval_tools/dinglehopper/run_dinglehopper.Dockerfile create mode 100644 examples/compare_transcription_eval_tools/dinglehopper/run_dinglehopper.sh create mode 100644 examples/compare_transcription_eval_tools/hip21_get_data.py create mode 100644 examples/compare_transcription_eval_tools/hip21_get_results.py create mode 100644 examples/compare_transcription_eval_tools/hip21_run_analysis.sh create mode 100644 examples/compare_transcription_eval_tools/isri/run_isri.Dockerfile create mode 100644 examples/compare_transcription_eval_tools/isri/run_isri.sh create mode 100644 examples/compare_transcription_eval_tools/isri/run_isri_analysis.py create mode 100644 examples/compare_transcription_eval_tools/jiwer/run_jiwer.Dockerfile create mode 100644 examples/compare_transcription_eval_tools/jiwer/run_jiwer.py create mode 100644 examples/compare_transcription_eval_tools/jiwer/run_jiwer.sh create mode 100644 examples/compare_transcription_eval_tools/meeteval/run_meeteval.Dockerfile create mode 100644 examples/compare_transcription_eval_tools/meeteval/run_meeteval.py create mode 100644 examples/compare_transcription_eval_tools/meeteval/run_meeteval.sh create mode 100644 examples/compare_transcription_eval_tools/ocrevalUAtion/container_script.sh create mode 100644 examples/compare_transcription_eval_tools/ocrevalUAtion/run_ocrevalUAtion.Dockerfile create mode 100644 examples/compare_transcription_eval_tools/ocrevalUAtion/run_ocrevalUAtion.sh create mode 100644 examples/compare_transcription_eval_tools/stringalign/run_stringalign.Dockerfile create mode 100644 examples/compare_transcription_eval_tools/stringalign/run_stringalign.py create mode 100644 examples/compare_transcription_eval_tools/stringalign/run_stringalign.sh create mode 100644 examples/compare_transcription_eval_tools/synthetic_emoji_get_results.py create mode 100644 examples/compare_transcription_eval_tools/synthetic_emoji_make_data.sh create mode 100644 examples/compare_transcription_eval_tools/synthetic_emoji_run_analysis.sh diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 02d31b7..7dac0d9 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -9,10 +9,6 @@ repos: - id: check-yaml - id: check-added-large-files args: ['--maxkb=4096'] -- repo: https://github.com/shellcheck-py/shellcheck-py - rev: v0.10.0.1 - hooks: - - id: shellcheck - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.12.2 hooks: diff --git a/Cargo.lock b/Cargo.lock index 9c651b9..3d39a13 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -258,7 +258,7 @@ checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" [[package]] name = "stringalign" -version = "0.1.3" +version = "0.1.4" dependencies = [ "numpy", "pyo3", diff --git a/examples/compare_transcription_eval_tools/README.md b/examples/compare_transcription_eval_tools/README.md new file mode 100644 index 0000000..2f14d0c --- /dev/null +++ b/examples/compare_transcription_eval_tools/README.md @@ -0,0 +1,9 @@ +# Code for comparing the WER and CER across tools + +This analysis is inspired by [https://dl.acm.org/doi/epdf/10.1145/3476887.3476888](https://dl.acm.org/doi/epdf/10.1145/3476887.3476888). Use the following code to run it. + +``` +bash synthetic_emoji_run_analysis.sh && bash hip21_run_analysis.sh +``` + +Note that running the analysis requires pipx and Docker are installed on your system. diff --git a/examples/compare_transcription_eval_tools/calamari/evaluate.py b/examples/compare_transcription_eval_tools/calamari/evaluate.py new file mode 100644 index 0000000..e361619 --- /dev/null +++ b/examples/compare_transcription_eval_tools/calamari/evaluate.py @@ -0,0 +1,835 @@ +""" +Modified from calamari: https://github.com/Calamari-OCR/calamari + +Copyright 2020 The tfaip Authors. All rights reserved. + + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. +""" + +import logging +from collections import namedtuple + +from edit_distance import edit_distance +from textprocessors import synchronize + +logger = logging.getLogger(__name__) +SingleEvalData = namedtuple("SingleEvalData", ["chars", "char_errs", "sync_errs", "conf", "gt_pred"]) + + +class Evaluator: + @staticmethod + def evaluate_single_args(args): + return Evaluator.evaluate_single(**args) + + @staticmethod + def evaluate_single(_sentinel=None, gt="", pred="", skip_empty_gt=False): + """Evaluate a single pair of data + + Parameters + ---------- + _sentinel : None + Sentinel to force to specify gt and pred manually + gt : str + ground truth + pred : str + prediction + skip_empty_gt : bool + skip gt text lines that are empty + + Returns + ------- + int + length of ground truth + int + number of errors + int + number of synchronisation errors + dict + confusions dictionary + tuple(str, str) + ground_truth, prediction (same as input) + + """ + confusion = {} + total_sync_errs = 0 + + if len(gt) == 0 and skip_empty_gt: + return 0, 0, 0, confusion, (gt, pred) + + errs, trues = edit_distance(gt, pred) + synclist = synchronize([gt, pred]) + for sync in synclist: + gt_str, pred_str = sync.get_text() + if gt_str != pred_str: + key = f"{gt_str!r} -> {pred_str!r}" + total_sync_errs += max(len(gt_str), len(pred_str)) + if key not in confusion: + confusion[key] = 1 + else: + confusion[key] += 1 + + return len(gt), errs, total_sync_errs, confusion, (gt, pred) + + @staticmethod + def evaluate_single_list(eval_results, store_all=False): + # sum all errors up + all_eval = [] + total_instances = 0 + total_chars = 0 + total_char_errs = 0 + confusion = {} + total_sync_errs = 0 + for chars, char_errs, sync_errs, conf, gt_pred in eval_results: + if store_all: + all_eval.append(SingleEvalData(chars, char_errs, sync_errs, conf, gt_pred)._asdict()) + + total_instances += 1 + total_chars += chars + total_char_errs += char_errs + total_sync_errs += sync_errs + for key, value in conf.items(): + if key not in confusion: + confusion[key] = value + else: + confusion[key] += value + + # Note the sync errs can be higher than the true edit distance because + # replacements are counted as 1 + # e.g. ed(in ewych, ierg ch) = 5 + # sync(in ewych, ierg ch) = [{i: i}, {n: erg}, {ewy: }, {ch: ch}] = 6 + + return { + "single": all_eval, + "total_instances": total_instances, + "avg_ler": total_char_errs / total_chars, + "total_chars": total_chars, + "total_char_errs": total_char_errs, + "total_sync_errs": total_sync_errs, + "confusion": confusion, + } + + def evaluate(self, *, gt_data: dict[str, str], pred_data: dict[str, str]): + """evaluate on the given raw data + + Parameters + ---------- + gt_data : Dataset, optional + the ground truth + pred_data : Dataset + the prediction dataset + + Returns + ------- + evaluation dictionary + """ + non_existing_pred_handling_mode = "empty" # This is the default + if non_existing_pred_handling_mode != "error": + n_empty = 0 + mapped_pred_data = {} + for sample_id in list(gt_data.keys()): + if sample_id in pred_data: + mapped_pred_data[sample_id] = pred_data[sample_id] + else: + if non_existing_pred_handling_mode == "empty": + mapped_pred_data[sample_id] = "" + else: + del gt_data[sample_id] # skip + n_empty += 1 + logger.info(f"{n_empty}/{len(gt_data)} lines could not be matched during the evaluation.") + if n_empty == len(gt_data): + raise ValueError( + f"No lines could be matched by their ID. First 10 gt ids " + f"{list(gt_data.keys())[:10]}, first 10 pred ids {list(pred_data.keys())[:10]}" + ) + pred_data = mapped_pred_data + + gt_ids, pred_ids = set(gt_data.keys()), set(pred_data.keys()) + if len(gt_ids) != len(gt_data): + raise ValueError("Non unique keys in ground truth data.") + if gt_ids != pred_ids: + raise Exception( + f"Mismatch in gt and pred. Samples could not be matched by ID. " + f"GT without PRED: {gt_ids.difference(pred_ids)}. " + f"PRED without GT: {pred_ids.difference(gt_ids)}" + ) + + gt_pred = [(gt_data[s_id], pred_data[s_id]) for s_id in gt_ids] + + out = [Evaluator.evaluate_single_args({"gt": gt, "pred": pred, "skip_empty_gt": False}) for gt, pred in gt_pred] + + res = Evaluator.evaluate_single_list(out, True) + res["ids"] = list(gt_ids) + return res diff --git a/examples/compare_transcription_eval_tools/calamari/run_calamari.Dockerfile b/examples/compare_transcription_eval_tools/calamari/run_calamari.Dockerfile new file mode 100644 index 0000000..24ad5d5 --- /dev/null +++ b/examples/compare_transcription_eval_tools/calamari/run_calamari.Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.14-trixie + +RUN pip install edit_distance==1.0.7 numpy==2.4.2 + +WORKDIR /analysis +COPY ocr_results/ ./ocr_results/ +COPY evaluate.py textprocessors.py run_calamari.py . + +CMD ["python", "run_calamari.py"] diff --git a/examples/compare_transcription_eval_tools/calamari/run_calamari.py b/examples/compare_transcription_eval_tools/calamari/run_calamari.py new file mode 100644 index 0000000..ad0ede9 --- /dev/null +++ b/examples/compare_transcription_eval_tools/calamari/run_calamari.py @@ -0,0 +1,30 @@ +import json +import pathlib + +import evaluate + +input_dir = pathlib.Path("ocr_results") +out_dir = pathlib.Path("output") + +char_report_files = [] +word_report_files = [] + +all_ref = {} +all_pred = {} + +result = {} +for i, ref_file in enumerate(input_dir.glob("*.ref.txt")): + print(f"Analysing file {i}") + name = ref_file.name.partition(".")[0] + ref = {name: (input_dir / f"{name}.ref.txt").read_text(encoding="utf-8")} + pred = {name: (input_dir / f"{name}.pred.txt").read_text(encoding="utf-8")} + + all_ref |= ref + all_pred |= pred + + result[name] = evaluate.Evaluator().evaluate(gt_data=ref, pred_data=pred) + +result["overall"] = evaluate.Evaluator().evaluate(gt_data=all_ref, pred_data=all_pred) + +with open(out_dir / "result.json", "w") as f: + json.dump(result, f, indent=2) diff --git a/examples/compare_transcription_eval_tools/calamari/run_calamari.sh b/examples/compare_transcription_eval_tools/calamari/run_calamari.sh new file mode 100644 index 0000000..f110259 --- /dev/null +++ b/examples/compare_transcription_eval_tools/calamari/run_calamari.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +cp -r ../ocr_results ./ocr_results/ +docker build -f run_calamari.Dockerfile -t stringalign_run_calamari . +rm -rf ./ocr_results/ +mkdir -p calamari_results + + +docker run --rm --volume $(pwd)/calamari_results:/analysis/output stringalign_run_calamari +docker image rm stringalign_run_calamari diff --git a/examples/compare_transcription_eval_tools/calamari/textprocessors.py b/examples/compare_transcription_eval_tools/calamari/textprocessors.py new file mode 100644 index 0000000..dd56706 --- /dev/null +++ b/examples/compare_transcription_eval_tools/calamari/textprocessors.py @@ -0,0 +1,831 @@ +""" + +Modified from calamari: https://github.com/Calamari-OCR/calamari + +Copyright 2020 The tfaip Authors. All rights reserved. + + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. +""" + +import numpy as np + + +class Sync: + def __init__(self, texts, substr=None, match=None): + self.texts = texts + + if substr: + assert substr.shape[0] == len(self.texts) + self.substr = substr + else: + self.substr = np.zeros((len(texts), 3), dtype=int) + + self.match = match + + def __str__(self): + return str(self.substr) + + def get_text(self): + return [self.texts[i][start : start + length] for i, (start, end, length) in enumerate(self.substr)] + + def is_valid(self): + return np.any(self.substr[:, 2] > 0) + + def lengths(self): + return self.substr[:, 2] + + def start(self, idx): + return self.substr[idx, 0] + + def stop(self, idx): + return self.substr[idx, 1] + + def length(self, idx): + return self.substr[idx, 2] + + def set_start(self, idx, v): + self.substr[idx, 0] = v + + def set_stop(self, idx, v): + self.substr[idx, 1] = v + + def set_length(self, idx, v): + self.substr[idx, 2] = v + + def set_all(self, idx, v): + self.substr[idx, :] = v + + +def synchronize(texts): + def init(): + sync = Sync(texts) + for i, text in enumerate(texts): + sync.set_all(i, [0, len(text) - 1, len(text)]) + + if sync.is_valid(): + return [sync] + + return [] + + def longest_match(maxlen, c1, start1, stop1, c2, start2, stop2): + mstart1 = 0 + mstart2 = 0 + s1limit = stop1 - maxlen + s2limit = stop2 - maxlen + for s1 in range(start1, s1limit + 1): + for s2 in range(start2, s2limit + 1): + if c1[s1] == c2[s2]: + i1 = s1 + 1 + i2 = s2 + 1 + while i1 <= stop1 and i2 <= stop2 and c1[i1] == c2[i2]: + i1 += 1 + i2 += 1 + + increase = i1 - s1 - maxlen + if increase > 0: + s1limit -= increase + s2limit -= increase + maxlen += increase + mstart1 = s1 + mstart2 = s2 + + return maxlen, mstart1, mstart2 + + def save_match(synclist, num_text, sync, start, length, match): + left, right = Sync(texts), Sync(texts) + for i in range(num_text): + stop = start[i] + length - 1 + left.set_all(i, [sync.start(i), start[i] - 1, start[i] - sync.start(i)]) + right.set_all(i, [stop + 1, sync.stop(i), sync.stop(i) - stop]) + sync.set_all(i, [start[i], stop, length]) + + sync.match = match + if left.is_valid(): + synclist.insert(synclist.index(sync), left) + + if right.is_valid(): + synclist.insert(synclist.index(sync) + 1, right) + + def recursive_sync(synclist, texts, start_index): + sync = synclist[start_index] + if np.any(sync.lengths() == 0): + return + + start = np.zeros(len(texts), dtype=int) + start[0] = sync.start(0) + length = sync.length(0) + for i, text in enumerate(texts[1:], 1): + length, new_start, start[i] = longest_match( + 0, + texts[0], + start[0], + start[0] + length - 1, + text, + sync.start(i), + sync.stop(i), + ) + + if length == 0: + return + + change = new_start - start[0] + if change > 0: + for j in range(i): + start[j] += change + + save_match(synclist, len(texts), sync, start, length, True) + + start_index = synclist.index(sync) + if start_index - 1 >= 0: + recursive_sync(synclist, texts, start_index - 1) + + start_index = synclist.index(sync) + if start_index + 1 < len(synclist): + recursive_sync(synclist, texts, start_index + 1) + + return + + synclist = init() + + if len(synclist) > 0: + recursive_sync(synclist, texts, 0) + + return synclist + + +if __name__ == "__main__": + synclist = synchronize(["AbcdEfG", "cdEFG"]) + print([s.get_text() for s in synclist]) diff --git a/examples/compare_transcription_eval_tools/check_for_multi_codepoint_grapheme_clusters.py b/examples/compare_transcription_eval_tools/check_for_multi_codepoint_grapheme_clusters.py new file mode 100644 index 0000000..964e047 --- /dev/null +++ b/examples/compare_transcription_eval_tools/check_for_multi_codepoint_grapheme_clusters.py @@ -0,0 +1,15 @@ +# /// script +# requires-python = ">=3.13" +# dependencies = ["regex"] +# /// + +import unicodedata +from pathlib import Path + +import regex + +text = Path("data.txt").read_text() +matches = regex.findall(r"\X", text) +for match in matches: + if len(unicodedata.normalize("NFC", match)) > 1: + print(match) diff --git a/examples/compare_transcription_eval_tools/dinglehopper/container_script.sh b/examples/compare_transcription_eval_tools/dinglehopper/container_script.sh new file mode 100644 index 0000000..38c5c24 --- /dev/null +++ b/examples/compare_transcription_eval_tools/dinglehopper/container_script.sh @@ -0,0 +1,11 @@ +mkdir pred ref && \ + bash -c 'for f in ocr_results/*ref.txt; do cp "$f" "ref/$(basename "$f" .ref.txt).txt"; done' && \ + bash -c 'for f in ocr_results/*pred.txt; do cp "$f" "pred/$(basename "$f" .pred.txt).txt"; done' + + +dinglehopper ref/ \ + pred/ \ + report \ + output/ \ + --plain-encoding utf-8 && \ + dinglehopper-summarize output/ diff --git a/examples/compare_transcription_eval_tools/dinglehopper/run_dinglehopper.Dockerfile b/examples/compare_transcription_eval_tools/dinglehopper/run_dinglehopper.Dockerfile new file mode 100644 index 0000000..4ca27f4 --- /dev/null +++ b/examples/compare_transcription_eval_tools/dinglehopper/run_dinglehopper.Dockerfile @@ -0,0 +1,11 @@ +FROM python:3.14-trixie + +RUN pip install dinglehopper==0.11.0 + +WORKDIR /analysis +COPY ocr_results/ ./ocr_results/ +RUN mkdir pred ref && \ + bash -c 'for f in ocr_results/*ref.txt; do cp "$f" "ref/$(basename "$f" .ref.txt).txt"; done' && \ + bash -c 'for f in ocr_results/*pred.txt; do cp "$f" "pred/$(basename "$f" .pred.txt).txt"; done' + +CMD ["bash", "-c", "dinglehopper ref/ pred/ report output/ --plain-encoding utf-8 && dinglehopper-summarize output/"] diff --git a/examples/compare_transcription_eval_tools/dinglehopper/run_dinglehopper.sh b/examples/compare_transcription_eval_tools/dinglehopper/run_dinglehopper.sh new file mode 100644 index 0000000..811f55e --- /dev/null +++ b/examples/compare_transcription_eval_tools/dinglehopper/run_dinglehopper.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +cp -r ../ocr_results ./ocr_results/ +docker build -f run_dinglehopper.Dockerfile -t stringalign_run_dinglehopper . +rm -rf ./ocr_results/ +mkdir -p dinglehopper_results + + +docker run --rm --volume $(pwd)/dinglehopper_results:/analysis/output stringalign_run_dinglehopper +docker image rm stringalign_run_dinglehopper diff --git a/examples/compare_transcription_eval_tools/hip21_get_data.py b/examples/compare_transcription_eval_tools/hip21_get_data.py new file mode 100644 index 0000000..0f2c2b0 --- /dev/null +++ b/examples/compare_transcription_eval_tools/hip21_get_data.py @@ -0,0 +1,56 @@ +import csv +import xml.etree.ElementTree as ET +from collections.abc import Generator +from pathlib import Path + +from tqdm import tqdm + + +def get_page_text(file: Path) -> Generator[str]: + root = ET.parse(file) + ns = {"PAGE": "http://schema.primaresearch.org/PAGE/gts/pagecontent/2010-03-19"} + unicode_tags = root.findall(".//PAGE:TextRegion/PAGE:TextEquiv/PAGE:Unicode", ns) + for unicode_tag in unicode_tags: + if text := unicode_tag.text.strip(): # type: ignore + yield text + "\n" + + +def get_alto_text(file: Path) -> Generator[str]: + root = ET.parse(file) + ns = "http://www.loc.gov/standards/alto/ns-v3#" + text_line_tags = root.findall(".//ALTO:TextLine", {"ALTO": ns}) + for text_line_tag in text_line_tags: + out = [] + for tag in text_line_tag: + tag_type = tag.tag.casefold() + if tag_type == f"{{{ns}}}string": + out.append(tag.attrib["CONTENT"]) + elif tag_type == f"{{{ns}}}sp": + out.append(" ") + elif tag_type == f"{{{ns}}}hyp": + out.append(tag.attrib["CONTENT"]) + else: + raise ValueError() + + if text := "".join(out).strip(): + yield text + "\n" + + +repo_parent = Path(__file__).parent / "hip21_ocrevaluation" +data_parent = repo_parent / "data" +output_dir = Path(__file__).parent / "ocr_results" +output_dir.mkdir(exist_ok=True) + +with open(repo_parent / "primaID.csv") as f: + reader = csv.DictReader(f) + stems = [row["\ufeffprimaID"] for row in reader if row["dataset"] == "impact"] + +for stem in tqdm(sorted(stems)): + gt_xml = data_parent / f"{stem}.gt.xml" + gt4hist_xml = data_parent / f"{stem}.gt4hist.xml" + + with open(output_dir / f"{stem}.ref.txt", "w", encoding="utf-8") as f: + f.writelines(get_page_text(gt_xml)) + + with open(output_dir / f"{stem}.pred.txt", "w", encoding="utf-8") as f: + f.writelines(get_alto_text(gt4hist_xml)) diff --git a/examples/compare_transcription_eval_tools/hip21_get_results.py b/examples/compare_transcription_eval_tools/hip21_get_results.py new file mode 100644 index 0000000..3b9aff1 --- /dev/null +++ b/examples/compare_transcription_eval_tools/hip21_get_results.py @@ -0,0 +1,140 @@ +# /// script +# requires-python = ">=3.13" +# dependencies = ["pandas", "jinja2"] +# /// +""" +This script gets the results from all the string comparison tools and creates a single DataFrame to display them +""" + +import json +import pathlib +import re + +import pandas as pd + +pages = [f.stem.partition(".")[0] for f in pathlib.Path("ocr_results").iterdir()] + +results = {} + + +# Load Calamari results +with open("calamari/calamari_results/result.json", "r") as f: + calamari = json.load(f) +results["Calamari"] = {key: {"cer": value["avg_ler"]} for key, value in calamari.items()} + + +# Load Dinglehopper results +dinglehopper_path = pathlib.Path("dinglehopper/dinglehopper_results") +results["Dinglehopper"] = {} + +for page in pages: + with open(dinglehopper_path / f"{page}.txt-report.json", "r") as f: + page_data = json.load(f) + + results["Dinglehopper"][page] = {"cer": page_data["cer"], "wer": page_data["wer"]} + +with open(dinglehopper_path / "summary.json", "r") as f: + summary_data = json.load(f) +results["Dinglehopper"]["overall"] = {"cer": summary_data["cer_avg"], "wer": summary_data["wer_avg"]} + +# Load ISRI results +isri_path = pathlib.Path("isri/isri_results") +results["ISRI"] = {} + + +def get_isri_error_rate(file: pathlib.Path) -> float: + with open(file, "r") as f: + report = f.readlines() + + accuracy_line = report[4] + (accuracy_match,) = re.findall(r"(\d+(?:\.\d+)?)%\s+Accuracy", accuracy_line) + return 1 - float(accuracy_match) / 100 + + +results["ISRI"]["overall"] = { + "cer": get_isri_error_rate(isri_path / "character_report.txt"), + "wer": get_isri_error_rate(isri_path / "word_report.txt"), +} + +for page in pages: + results["ISRI"][page] = { + "cer": get_isri_error_rate(isri_path / f"{page}.char_report.txt"), + "wer": get_isri_error_rate(isri_path / f"{page}.word_report.txt"), + } + +# Load jiwer +with open("jiwer/jiwer_results/result.json", "r") as f: + results["Jiwer"] = json.load(f) + +# Load meeteval +with open("meeteval/meeteval_results/result.json", "r") as f: + results["Meeteval"] = json.load(f) + + +# Load ocrevalUAtion +def parse_ocrevalUAtion_report(file: pathlib.Path) -> dict[str, float]: + with open(file, "r") as f: + report = f.readlines() + cer_line = report[10] + (cer,) = re.findall(r"CER(\d+(?:\.\d+)?)", cer_line) + + wer_line = report[13] + (wer,) = re.findall(r"WER(\d+(?:\.\d+)?)", wer_line) + + return {"cer": float(cer) / 100, "wer": float(wer) / 100} + + +ocrevalUAtion_path = pathlib.Path("ocrevalUAtion/ocrevalUAtion_results") +results["ocrevalUAtion"] = { + page: parse_ocrevalUAtion_report(ocrevalUAtion_path / f"{page}.report.html") for page in pages +} + +# Load stringalign +with open("stringalign/stringalign_results/result.json", "r") as f: + results["Stringalign"] = json.load(f) +# Load stringalign +with open("stringalign/stringalign_results/result_dinglehopper_processing.json", "r") as f: + results["Stringalign (Dinglehopper)"] = json.load(f) + +# Convert results to records +result_records = [] +for method, single_method_results in results.items(): + for sample, sample_result in single_method_results.items(): + result_records.append({"method": method, "sample": sample, **sample_result}) + +# Assemble in DataFrame +df = pd.DataFrame(result_records).sort_values(["sample", "method"]).set_index(["sample", "method"]) +df_no_overall = df.drop("overall", level="sample", errors="ignore") +df.loc[("overall", "ocrevalUAtion"),] = df.loc[(slice(None), "ocrevalUAtion"),].mean() + +dinglehopper_diff_df = df.loc[(slice(None), "Dinglehopper"),].reset_index(level="method", drop=True) - df.loc[ + (slice(None), "Stringalign (Dinglehopper)"), +].reset_index(level="method", drop=True) +df = df.drop("Stringalign (Dinglehopper)", level="method", errors="ignore") + +# Get dispersion measures +mean_absolute_deviation_from_mean = ( + df.drop("overall", level="sample", errors="ignore") # This time without the Dinglehopper data as well + .groupby("sample") # Get dataframes for each sample with all methods + .transform( + lambda s: abs(s - s.median()) + ) # For each method, compute its absolute deviation from the mean in that sample + .groupby("method") # Get dataframes for each tools with all samples + .mean() +) + +overall_res = df.loc["overall"].copy() +overall_res.columns = pd.MultiIndex.from_tuples([("Overall measure", metric.upper()) for metric in df.columns]) +mean_absolute_deviation_from_mean.columns = pd.MultiIndex.from_tuples( + [("MADM", metric.upper()) for metric in df.columns] +) + +out_df = pd.merge(overall_res, mean_absolute_deviation_from_mean, how="outer", on="method") +with open("hip21_table.tex", "w", encoding="utf-8") as f: + f.write(out_df.to_latex(na_rep="--", float_format="%.4f")) + +print(out_df) +print( + "Diff between Stringalign and Dinglehopper when confusables are resolved equally\n", + dinglehopper_diff_df.drop("overall", errors="ignore").max(), +) diff --git a/examples/compare_transcription_eval_tools/hip21_run_analysis.sh b/examples/compare_transcription_eval_tools/hip21_run_analysis.sh new file mode 100644 index 0000000..4d75dd2 --- /dev/null +++ b/examples/compare_transcription_eval_tools/hip21_run_analysis.sh @@ -0,0 +1,51 @@ +#!/bin/bash +# shellcheck disable=all +run_analysis() { + + + cd isri + rm -rf isri_results + time bash run_isri.sh + cd .. + + cd jiwer + rm -rf jiwer_results + time bash run_jiwer.sh + cd .. + + cd meeteval + rm -rf meeteval_results + time bash run_meeteval.sh + cd .. + + cd ocrevalUAtion + rm -rf ocrevalUAtion_results + time bash run_ocrevalUAtion.sh + cd .. + + cd stringalign + rm -rf stringalign_results + time bash run_stringalign.sh + cd .. + + cd dinglehopper + rm -rf dinglehopper_results + time bash run_dinglehopper.sh + cd .. + + cd calamari + rm -rf calamari_results + time bash run_calamari.sh + cd .. +} + +rm -rf ocr_results + +git clone https://github.com/cneud/hip21_ocrevaluation.git +cd hip21_ocrevaluation +git checkout 9979dacfeebef65b419a44ea3f12a0bcba153c6f +cd .. + +pipx run hip21_get_data.py +run_analysis +pipx run hip21_get_results.py diff --git a/examples/compare_transcription_eval_tools/isri/run_isri.Dockerfile b/examples/compare_transcription_eval_tools/isri/run_isri.Dockerfile new file mode 100644 index 0000000..a6733ce --- /dev/null +++ b/examples/compare_transcription_eval_tools/isri/run_isri.Dockerfile @@ -0,0 +1,14 @@ +FROM python:3.14-trixie + +RUN apt-get update && \ + apt-get install -y build-essential libutf8proc-dev git && \ + git clone https://github.com/eddieantonio/ocreval && \ + cd ocreval && \ + git checkout 873a0de5796c0b9ccf07a549afdd30159a9e0b3e && \ + make && make install + +WORKDIR /analysis +COPY ocr_results/ ./ocr_results/ +COPY run_isri_analysis.py . + +CMD ["python3", "run_isri_analysis.py"] diff --git a/examples/compare_transcription_eval_tools/isri/run_isri.sh b/examples/compare_transcription_eval_tools/isri/run_isri.sh new file mode 100644 index 0000000..7b603ed --- /dev/null +++ b/examples/compare_transcription_eval_tools/isri/run_isri.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +cp -r ../ocr_results ./ocr_results/ +docker build -f run_isri.Dockerfile -t stringalign_run_isri . +rm -rf ./ocr_results/ +mkdir -p isri_results + + +docker run --rm --volume $(pwd)/isri_results:/analysis/output stringalign_run_isri +docker image rm stringalign_run_isri diff --git a/examples/compare_transcription_eval_tools/isri/run_isri_analysis.py b/examples/compare_transcription_eval_tools/isri/run_isri_analysis.py new file mode 100644 index 0000000..ca658d2 --- /dev/null +++ b/examples/compare_transcription_eval_tools/isri/run_isri_analysis.py @@ -0,0 +1,30 @@ +import pathlib +import subprocess + +input_dir = pathlib.Path("ocr_results") +out_dir = pathlib.Path("output") + +char_report_files = [] +word_report_files = [] + +for ref_file in input_dir.glob("*.ref.txt"): + name = ref_file.name.partition(".")[0] + ref = str(input_dir / f"{name}.ref.txt") + pred = str(input_dir / f"{name}.pred.txt") + + char_report_file = str(out_dir / f"{name}.char_report.txt") + word_report_file = str(out_dir / f"{name}.word_report.txt") + + subprocess.run(["accuracy", f"ocr_results/{name}.ref.txt", f"ocr_results/{name}.pred.txt", char_report_file]) + + subprocess.run(["wordacc", f"ocr_results/{name}.ref.txt", f"ocr_results/{name}.pred.txt", word_report_file]) + + char_report_files.append(char_report_file) + word_report_files.append(word_report_file) + + +with open(out_dir / "character_report.txt", "w") as f: + subprocess.run(["accsum"] + char_report_files, stdout=f) + +with open(out_dir / "word_report.txt", "w") as f: + subprocess.run(["wordaccsum"] + word_report_files, stdout=f) diff --git a/examples/compare_transcription_eval_tools/jiwer/run_jiwer.Dockerfile b/examples/compare_transcription_eval_tools/jiwer/run_jiwer.Dockerfile new file mode 100644 index 0000000..2b6bb55 --- /dev/null +++ b/examples/compare_transcription_eval_tools/jiwer/run_jiwer.Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.14-trixie + +RUN pip install jiwer==4.0.0 + +WORKDIR /analysis +COPY ocr_results/ ./ocr_results/ +COPY run_jiwer.py . + +CMD ["python", "run_jiwer.py"] diff --git a/examples/compare_transcription_eval_tools/jiwer/run_jiwer.py b/examples/compare_transcription_eval_tools/jiwer/run_jiwer.py new file mode 100644 index 0000000..a5f4c5f --- /dev/null +++ b/examples/compare_transcription_eval_tools/jiwer/run_jiwer.py @@ -0,0 +1,37 @@ +# /// script +# requires-python = "==3.14.*" +# dependencies = ["jiwer==4.0.0"] +# /// + +import json +import pathlib + +import jiwer + +input_dir = pathlib.Path("ocr_results") +out_dir = pathlib.Path("output") + +char_report_files = [] +word_report_files = [] + +all_ref = [] +all_pred = [] + +result = {} +for ref_file in input_dir.glob("*.ref.txt"): + name = ref_file.name.partition(".")[0] + ref = (input_dir / f"{name}.ref.txt").read_text(encoding="utf-8") + pred = (input_dir / f"{name}.pred.txt").read_text(encoding="utf-8") + + all_ref.append(ref) + all_pred.append(pred) + + result[name] = {"cer": jiwer.cer(reference=ref, hypothesis=pred), "wer": jiwer.wer(reference=ref, hypothesis=pred)} + +result["overall"] = { + "cer": jiwer.cer(reference=all_ref, hypothesis=all_pred), + "wer": jiwer.wer(reference=all_ref, hypothesis=all_pred), +} + +with open(out_dir / "result.json", "w") as f: + json.dump(result, f) diff --git a/examples/compare_transcription_eval_tools/jiwer/run_jiwer.sh b/examples/compare_transcription_eval_tools/jiwer/run_jiwer.sh new file mode 100644 index 0000000..db3607e --- /dev/null +++ b/examples/compare_transcription_eval_tools/jiwer/run_jiwer.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +cp -r ../ocr_results ./ocr_results/ +docker build -f run_jiwer.Dockerfile -t stringalign_run_jiwer . +rm -rf ./ocr_results/ +mkdir -p jiwer_results + + +docker run --rm --volume $(pwd)/jiwer_results:/analysis/output stringalign_run_jiwer +docker image rm stringalign_run_jiwer diff --git a/examples/compare_transcription_eval_tools/meeteval/run_meeteval.Dockerfile b/examples/compare_transcription_eval_tools/meeteval/run_meeteval.Dockerfile new file mode 100644 index 0000000..154cb02 --- /dev/null +++ b/examples/compare_transcription_eval_tools/meeteval/run_meeteval.Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.14-trixie + +RUN pip install meeteval==0.4.3 + +WORKDIR /analysis +COPY ocr_results/ ./ocr_results/ +COPY run_meeteval.py . + +CMD ["python", "run_meeteval.py"] diff --git a/examples/compare_transcription_eval_tools/meeteval/run_meeteval.py b/examples/compare_transcription_eval_tools/meeteval/run_meeteval.py new file mode 100644 index 0000000..be2a4fd --- /dev/null +++ b/examples/compare_transcription_eval_tools/meeteval/run_meeteval.py @@ -0,0 +1,30 @@ +import json +import pathlib + +import meeteval + +input_dir = pathlib.Path("ocr_results") +out_dir = pathlib.Path("output") + +char_report_files = [] +word_report_files = [] + +result = {} +error_rates = [] +for ref_file in input_dir.glob("*.ref.txt"): + name = ref_file.name.partition(".")[0] + ref = (input_dir / f"{name}.ref.txt").read_text(encoding="utf-8") + pred = (input_dir / f"{name}.pred.txt").read_text(encoding="utf-8") + + wer = meeteval.wer.wer.siso.siso_word_error_rate( + reference=ref, + hypothesis=pred, + ) + result[name] = {"wer": wer.error_rate} + error_rates.append(wer) + +avg = meeteval.wer.combine_error_rates(error_rates) +result["overall"] = {"wer": avg.error_rate} + +with open(out_dir / "result.json", "w") as f: + json.dump(result, f, indent=2) diff --git a/examples/compare_transcription_eval_tools/meeteval/run_meeteval.sh b/examples/compare_transcription_eval_tools/meeteval/run_meeteval.sh new file mode 100644 index 0000000..53f27a0 --- /dev/null +++ b/examples/compare_transcription_eval_tools/meeteval/run_meeteval.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +cp -r ../ocr_results ./ocr_results/ +docker build -f run_meeteval.Dockerfile -t stringalign_run_meeteval . +rm -rf ./ocr_results/ +mkdir -p meeteval_results + + +docker run --rm --volume $(pwd)/meeteval_results:/analysis/output stringalign_run_meeteval +docker image rm stringalign_run_meeteval diff --git a/examples/compare_transcription_eval_tools/ocrevalUAtion/container_script.sh b/examples/compare_transcription_eval_tools/ocrevalUAtion/container_script.sh new file mode 100644 index 0000000..af24079 --- /dev/null +++ b/examples/compare_transcription_eval_tools/ocrevalUAtion/container_script.sh @@ -0,0 +1,13 @@ +for reference_file in ocr_results/*.ref.txt +do + name=$(basename "$reference_file" .ref.txt) + predicted_file="ocr_results/$name.pred.txt" + output_file="output/$name.report.html" + + java -cp ocrevalUAtion-1.3.4-jar-with-dependencies.jar \ + eu.digitisation.Main \ + -gt "$reference_file" \ + -ocr "$predicted_file" \ + -e utf-8 \ + -o "$output_file" +done diff --git a/examples/compare_transcription_eval_tools/ocrevalUAtion/run_ocrevalUAtion.Dockerfile b/examples/compare_transcription_eval_tools/ocrevalUAtion/run_ocrevalUAtion.Dockerfile new file mode 100644 index 0000000..28e28c8 --- /dev/null +++ b/examples/compare_transcription_eval_tools/ocrevalUAtion/run_ocrevalUAtion.Dockerfile @@ -0,0 +1,13 @@ +FROM python:3.14-trixie + +WORKDIR /analysis +RUN apt-get update && \ + apt-get install -y openjdk-25-jre-headless wget && \ + wget https://github.com/impactcentre/ocrevalUAtion/releases/download/v1.3.4/ocrevalUAtion-1.3.4-jar-with-dependencies.jar + + +WORKDIR /analysis +COPY ocr_results/ ./ocr_results/ +COPY container_script.sh run_eval.sh + +CMD ["bash", "run_eval.sh"] diff --git a/examples/compare_transcription_eval_tools/ocrevalUAtion/run_ocrevalUAtion.sh b/examples/compare_transcription_eval_tools/ocrevalUAtion/run_ocrevalUAtion.sh new file mode 100644 index 0000000..cec7a49 --- /dev/null +++ b/examples/compare_transcription_eval_tools/ocrevalUAtion/run_ocrevalUAtion.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +cp -r ../ocr_results ./ocr_results +docker build -f run_ocrevalUAtion.Dockerfile -t stringalign_run_ocrevaluation . +rm -rf ocr_results +mkdir -p ocrevalUAtion_results + +docker run --rm --volume $(pwd)/../ocr_results:/analysis/ocr_results --volume $(pwd)/ocrevalUAtion_results:/analysis/output stringalign_run_ocrevaluation +docker image rm stringalign_run_ocrevaluation diff --git a/examples/compare_transcription_eval_tools/stringalign/run_stringalign.Dockerfile b/examples/compare_transcription_eval_tools/stringalign/run_stringalign.Dockerfile new file mode 100644 index 0000000..4d04ec4 --- /dev/null +++ b/examples/compare_transcription_eval_tools/stringalign/run_stringalign.Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-trixie + +RUN pip install stringalign==0.1.4 + +WORKDIR /analysis +COPY ocr_results/ ./ocr_results/ +COPY run_stringalign.py . + +CMD ["python", "run_stringalign.py"] diff --git a/examples/compare_transcription_eval_tools/stringalign/run_stringalign.py b/examples/compare_transcription_eval_tools/stringalign/run_stringalign.py new file mode 100644 index 0000000..7be68f2 --- /dev/null +++ b/examples/compare_transcription_eval_tools/stringalign/run_stringalign.py @@ -0,0 +1,136 @@ +# /// script +# requires-python = "==3.14.*" +# dependencies = ["stringalign"] +# /// + +import json +import pathlib + +import stringalign + +input_dir = pathlib.Path("ocr_results") +out_dir = pathlib.Path("output") +char_tokenizer = stringalign.tokenize.GraphemeClusterTokenizer() +word_tokenizer = stringalign.tokenize.SplitAtWhitespaceTokenizer() + +dinglehopper_normalizer = stringalign.normalize.StringNormalizer( + # These confusable mappings are copied from Dinglehopper's source code. + # Dinglehopper is Apache 2.0 licensed, which is compatible with the MIT license. + # See the Dinglehopper source code for more information + # https://github.com/qurator-spk/dinglehopper/blob/master/src/dinglehopper/extracted_text.py + resolve_confusables={ + "": "ſſ", + "\ueba7": "ſſi", # MUFI: LATIN SMALL LIGATURE LONG S LONG S I + "": "ch", + "": "ck", + "": "ll", + "": "ſi", + "": "ſt", + "fi": "fi", + "ff": "ff", + "fl": "fl", + "ffi": "ffi", + "": "ct", + "": "tz", # MUFI: LATIN SMALL LIGATURE TZ + "\uf532": "as", # eMOP: Latin small ligature as + "\uf533": "is", # eMOP: Latin small ligature is + "\uf534": "us", # eMOP: Latin small ligature us + "\uf535": "Qu", # eMOP: Latin ligature capital Q small u + "ij": "ij", # U+0133 LATIN SMALL LIGATURE IJ + "\ue8bf": "q&", + # MUFI: LATIN SMALL LETTER Q LIGATED WITH FINAL ET + # XXX How to replace this correctly? + "\ueba5": "ſp", # MUFI: LATIN SMALL LIGATURE LONG S P + "st": "st", # U+FB06 LATIN SMALL LIGATURE ST + } + | { + "": "ü", + "": "ä", + "==": "–", # → en-dash + "—": "–", # em-dash → en-dash + "": "ö", + "’": "'", + "⸗": "-", + "aͤ": "ä", # LATIN SMALL LETTER A, COMBINING LATIN SMALL LETTER E + "oͤ": "ö", # LATIN SMALL LETTER O, COMBINING LATIN SMALL LETTER E + "uͤ": "ü", # LATIN SMALL LETTER U, COMBINING LATIN SMALL LETTER E + "\uf50e": "q́", # U+F50E LATIN SMALL LETTER Q WITH ACUTE ACCENT + } +) +dinglehopper_char_tokenizer = stringalign.tokenize.GraphemeClusterTokenizer( + pre_tokenization_normalizer=dinglehopper_normalizer +) +dinglehopper_word_tokenizer = stringalign.tokenize.UnicodeWordTokenizer( + pre_tokenization_normalizer=dinglehopper_normalizer +) + +char_report_files = [] +word_report_files = [] + +all_ref = [] +all_pred = [] + +result = {} +result_dinglehopper_confusable_handling = {} +for ref_file in input_dir.glob("*.ref.txt"): + name = ref_file.name.partition(".")[0] + ref = "\n".join((input_dir / f"{name}.ref.txt").read_text(encoding="utf-8").splitlines()) + pred = "\n".join((input_dir / f"{name}.pred.txt").read_text(encoding="utf-8").splitlines()) + + all_ref.append(ref) + all_pred.append(pred) + + result[name] = { + "cer": ( + stringalign.statistics.StringConfusionMatrix.from_strings( + reference=ref, predicted=pred, tokenizer=char_tokenizer + ).compute_token_error_rate() + ), + "wer": ( + stringalign.statistics.StringConfusionMatrix.from_strings( + reference=ref, predicted=pred, tokenizer=word_tokenizer + ).compute_token_error_rate() + ), + } + result_dinglehopper_confusable_handling[name] = { + "cer": ( + stringalign.statistics.StringConfusionMatrix.from_strings( + reference=ref, predicted=pred, tokenizer=dinglehopper_char_tokenizer + ).compute_token_error_rate() + ), + "wer": ( + stringalign.statistics.StringConfusionMatrix.from_strings( + reference=ref, predicted=pred, tokenizer=dinglehopper_word_tokenizer + ).compute_token_error_rate() + ), + } + +result["overall"] = { + "cer": ( + stringalign.statistics.StringConfusionMatrix.from_string_collections( + references=all_ref, predictions=all_pred, tokenizer=char_tokenizer + ).compute_token_error_rate() + ), + "wer": ( + stringalign.statistics.StringConfusionMatrix.from_string_collections( + references=all_ref, predictions=all_pred, tokenizer=word_tokenizer + ).compute_token_error_rate() + ), +} +result_dinglehopper_confusable_handling["overall"] = { + "cer": ( + stringalign.statistics.StringConfusionMatrix.from_string_collections( + references=all_ref, predictions=all_pred, tokenizer=dinglehopper_char_tokenizer + ).compute_token_error_rate() + ), + "wer": ( + stringalign.statistics.StringConfusionMatrix.from_string_collections( + references=all_ref, predictions=all_pred, tokenizer=dinglehopper_word_tokenizer + ).compute_token_error_rate() + ), +} + +with open(out_dir / "result.json", "w") as f: + json.dump(result, f) +with open(out_dir / "result_dinglehopper_processing.json", "w") as f: + json.dump(result_dinglehopper_confusable_handling, f) diff --git a/examples/compare_transcription_eval_tools/stringalign/run_stringalign.sh b/examples/compare_transcription_eval_tools/stringalign/run_stringalign.sh new file mode 100644 index 0000000..0505ee7 --- /dev/null +++ b/examples/compare_transcription_eval_tools/stringalign/run_stringalign.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +cp -r ../ocr_results ./ocr_results/ +docker build -f run_stringalign.Dockerfile -t stringalign_run_stringalign . +rm -rf ./ocr_results/ +mkdir -p stringalign_results + + +docker run --rm --volume $(pwd)/stringalign_results:/analysis/output stringalign_run_stringalign +docker image rm stringalign_run_stringalign diff --git a/examples/compare_transcription_eval_tools/synthetic_emoji_get_results.py b/examples/compare_transcription_eval_tools/synthetic_emoji_get_results.py new file mode 100644 index 0000000..c7b9f43 --- /dev/null +++ b/examples/compare_transcription_eval_tools/synthetic_emoji_get_results.py @@ -0,0 +1,98 @@ +# /// script +# requires-python = ">=3.13" +# dependencies = ["pandas", "jinja2"] +# /// + +""" +This script gets the results from all the string comparison tools and creates a single DataFrame to display them +""" + +import json +import pathlib +import re + +import pandas as pd + +pages = [ + "page00000", + "page00001", + "page00002", + "page00003", + "page00004", + "page00005", +] + +results = {} + + +# Load Calamari results +with open("calamari/calamari_results/result.json", "r") as f: + results["calamari"] = {"cer": json.load(f)["overall"]["avg_ler"]} + + +# Load Dinglehopper results +with open("dinglehopper/dinglehopper_results/page00000.txt-report.json", "r") as f: + summary_data = json.load(f) +results["dinglehopper"] = {"cer": summary_data["cer"], "wer": summary_data["wer"]} + + +# Load ISRI results +def get_isri_error_rate(file: pathlib.Path) -> float: + with open(file, "r") as f: + report = f.readlines() + + accuracy_line = report[4] + (accuracy_match,) = re.findall(r"(\d+(?:\.\d+)?)%\s+Accuracy", accuracy_line) + return 1 - float(accuracy_match) / 100 + + +isri_path = pathlib.Path("isri/isri_results") +results["isri"] = { + "cer": get_isri_error_rate(isri_path / "page00000.char_report.txt"), + "wer": get_isri_error_rate(isri_path / "page00000.word_report.txt"), +} + +# Load jiwer +jiwer_path = pathlib.Path("jiwer/jiwer_results") +with open("jiwer/jiwer_results/result.json", "r") as f: + results["jiwer"] = json.load(f)["overall"] + +# Load meeteval +jiwer_path = pathlib.Path("meeteval/meeteval_results") +with open("meeteval/meeteval_results/result.json", "r") as f: + results["meeteval"] = json.load(f)["overall"] + + +# Load ocrevalUAtion +def parse_ocrevalUAtion_report(file: pathlib.Path) -> dict[str, float]: + with open(file, "r") as f: + report = f.readlines() + cer_line = report[10] + (cer,) = re.findall(r"CER(\d+(?:\.\d+)?)", cer_line) + + wer_line = report[13] + (wer,) = re.findall(r"WER(\d+(?:\.\d+)?)", wer_line) + + return {"cer": float(cer) / 100, "wer": float(wer) / 100} + + +try: + ocrevalUAtion_path = pathlib.Path("ocrevalUAtion/ocrevalUAtion_results") + results["ocrevalUAtion"] = parse_ocrevalUAtion_report(ocrevalUAtion_path / "page00000.report.html") +except Exception: + print("ocrevalUAtion failed") + +# Load stringalign +with open("stringalign/stringalign_results/result.json", "r") as f: + results["stringalign"] = json.load(f)["overall"] + +# Convert results to records +result_records = [] +for method, single_method_results in results.items(): + result_records.append({"method": method, **single_method_results}) + +df = pd.DataFrame(result_records).sort_values(["method"]).set_index(["method"]) + +print(df) +with open("synthetic_emoji_table.tex", "w", encoding="utf-8") as f: + f.write(df.to_latex(na_rep="--", float_format="%.4f")) diff --git a/examples/compare_transcription_eval_tools/synthetic_emoji_make_data.sh b/examples/compare_transcription_eval_tools/synthetic_emoji_make_data.sh new file mode 100644 index 0000000..2403dd5 --- /dev/null +++ b/examples/compare_transcription_eval_tools/synthetic_emoji_make_data.sh @@ -0,0 +1,6 @@ +#!/bin/bash + +rm -r ocr_results +mkdir ocr_results +printf "That was\nclose! 😮‍💨" > ocr_results/page00000.ref.txt +printf "That was\nclose!" > ocr_results/page00000.pred.txt diff --git a/examples/compare_transcription_eval_tools/synthetic_emoji_run_analysis.sh b/examples/compare_transcription_eval_tools/synthetic_emoji_run_analysis.sh new file mode 100644 index 0000000..d41715c --- /dev/null +++ b/examples/compare_transcription_eval_tools/synthetic_emoji_run_analysis.sh @@ -0,0 +1,44 @@ +#!/bin/bash + +run_analysis() { + cd calamari + rm -rf calamari_results + bash run_calamari.sh + cd .. + + + cd dinglehopper + rm -rf dinglehopper_results + bash run_dinglehopper.sh + cd .. + + + cd isri + rm -rf isri_results + bash run_isri.sh + cd .. + + cd jiwer + rm -rf jiwer_results + bash run_jiwer.sh + cd .. + + cd meeteval + rm -rf meeteval_results + bash run_meeteval.sh + cd .. + + cd ocrevalUAtion + rm -rf ocrevalUAtion_results + bash run_ocrevalUAtion.sh + cd .. + + cd stringalign + rm -rf stringalign_results + bash run_stringalign.sh + cd .. +} + +bash synthetic_emoji_make_data.sh +run_analysis +pipx synthetic_emoji_get_results.py