diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..a6344aac8c09253b3b630fb776ae94478aa0275b --- /dev/null +++ b/.gitattributes @@ -0,0 +1,35 @@ +*.7z filter=lfs diff=lfs merge=lfs -text +*.arrow filter=lfs diff=lfs merge=lfs -text +*.bin filter=lfs diff=lfs merge=lfs -text +*.bz2 filter=lfs diff=lfs merge=lfs -text +*.ckpt filter=lfs diff=lfs merge=lfs -text +*.ftz filter=lfs diff=lfs merge=lfs -text +*.gz filter=lfs diff=lfs merge=lfs -text +*.h5 filter=lfs diff=lfs merge=lfs -text +*.joblib filter=lfs diff=lfs merge=lfs -text +*.lfs.* filter=lfs diff=lfs merge=lfs -text +*.mlmodel filter=lfs diff=lfs merge=lfs -text +*.model filter=lfs diff=lfs merge=lfs -text +*.msgpack filter=lfs diff=lfs merge=lfs -text +*.npy filter=lfs diff=lfs merge=lfs -text +*.npz filter=lfs diff=lfs merge=lfs -text +*.onnx filter=lfs diff=lfs merge=lfs -text +*.ot filter=lfs diff=lfs merge=lfs -text +*.parquet filter=lfs diff=lfs merge=lfs -text +*.pb filter=lfs diff=lfs merge=lfs -text +*.pickle filter=lfs diff=lfs merge=lfs -text +*.pkl filter=lfs diff=lfs merge=lfs -text +*.pt filter=lfs diff=lfs merge=lfs -text +*.pth filter=lfs diff=lfs merge=lfs -text +*.rar filter=lfs diff=lfs merge=lfs -text +*.safetensors filter=lfs diff=lfs merge=lfs -text +saved_model/**/* filter=lfs diff=lfs merge=lfs -text +*.tar.* filter=lfs diff=lfs merge=lfs -text +*.tar filter=lfs diff=lfs merge=lfs -text +*.tflite filter=lfs diff=lfs merge=lfs -text +*.tgz filter=lfs diff=lfs merge=lfs -text +*.wasm filter=lfs diff=lfs merge=lfs -text +*.xz filter=lfs diff=lfs merge=lfs -text +*.zip filter=lfs diff=lfs merge=lfs -text +*.zst filter=lfs diff=lfs merge=lfs -text +*tfevents* filter=lfs diff=lfs merge=lfs -text diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSE.AGPL-3.0 b/LICENSE.AGPL-3.0 new file mode 100644 index 0000000000000000000000000000000000000000..be3f7b28e564e7dd05eaf59d64adba1a4065ac0e --- /dev/null +++ b/LICENSE.AGPL-3.0 @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..1f5c1fd472218052e5049186c907ffd99579eaf6 --- /dev/null +++ b/NOTICE @@ -0,0 +1,60 @@ +Turkic OCR: code of the generator, training and evaluation (release candidate rc1_code) + +Copyright 2026 Anuar Suleimenov, Zhalgasbek Bolatov, Aidana Baglanova, Anel Kadirbekova + +Cite as: Suleimenov, A., Bolatov, Z., Baglanova, A., Kadirbekova, A., Nguyen, A. T. (2026). A Handwriting Recognition +Model for Turkic Languages in Latin and Cyrillic Script. Project report, Nazarbayev University. + + +LICENCES + +1. Apache License 2.0 (full text in LICENSE) applies to every file of this package except those listed under 2, 3 and 4. + +2. GNU Affero General Public License v3.0 (full text in LICENSE.AGPL-3.0) applies to the training and inference path of the + line detector and to the page pipeline. The detector is trained and run with Ultralytics YOLO, which is AGPL-3.0, and + Ultralytics states that models trained with its code fall under AGPL-3.0 (https://www.ultralytics.com/license). + Files under AGPL-3.0: + src/linedet/det_prep.py + src/linedet/det_yolo.py + src/linedet/det_eval.py + src/linedet/det_overlay.py + src/linedet/det_school_stats.py + scripts/r5_linedet/det_prep_school.sbatch + scripts/release2/rel2_d5_prep.py + scripts/release2/rel2_d5_prep.sbatch + scripts/release2/rel2_d5_detector_retrain.sbatch + scripts/release2/rel2_d5_check.py + scripts/release2/rel2_d5_check.sbatch + scripts/release2/rel2_d5_install.sbatch + scripts/r5_release/rc1_prep_det.py + scripts/r5_testpass2/tp2_tob_detect.py + scripts/r5_loopguard/lg_detect.py + scripts/r5_showcase/showcase_detect.py + release/turkic-line-detector-yolo11s/infer.py + release/turkic-line-detector-yolo11s/requirements.txt + release/page-pipeline/infer.py + release/page-pipeline/requirements.txt + +3. MIT License (third-party code, vendored without changes; only its README.md is left out): + the HTR-Flor folder in src/ref/ (its path is set in scripts/r5_ref/ref_common.py) + HTR-Flor, https://github.com/arthurflor23/handwritten-text-recognition, repository state of 23 June 2021, + Copyright (c) 2019 Arthur Flôr. Its LICENSE file is kept in that folder. Used for the HTR-Flor reference re-run. + +4. Public domain data: src/pagesynth/assets/naturalearth/*.geojson, Natural Earth vector map data (1:50m), + https://www.naturalearthdata.com. Its terms of use state: "All versions of Natural Earth raster + vector map data found on + this website are in the public domain." The generator draws its maps from these files. + + +THIRD-PARTY SOFTWARE NOT INCLUDED + +The code imports third-party packages (PyTorch, Hugging Face Transformers, kraken, Ultralytics, KenLM, PaddleOCR and others) +that are installed separately under their own licences; the environments/ folder lists the versions used. +The PP-OCRv3 reference re-run (scripts/r5_ref, arm R2) expects PaddleOCR release v2.10.0 +(7 March 2025) of https://github.com/PaddlePaddle/PaddleOCR (Apache-2.0) in the folder under src/ref/ that +scripts/r5_ref/ref_common.py sets (PPOCR_ROOT); it is not included. + + +NOT INCLUDED + +No data, no font files and no weights of the fine-tuned readers (PaddleOCR-VL-1.6, Qwen3-VL-2B, PP-OCRv6-medium and its +character language model). See README. diff --git a/README b/README new file mode 100644 index 0000000000000000000000000000000000000000..22d366d9da9c4cc05d33ff506fd25fbb6fb6ad56 --- /dev/null +++ b/README @@ -0,0 +1,224 @@ +TURKIC OCR: CODE OF THE GENERATOR, TRAINING AND EVALUATION +(release candidate rc1_code) + +This package holds the code behind the project report + + Suleimenov, A., Bolatov, Z., Baglanova, A., Kadirbekova, A., Nguyen, A. T. (2026). A Handwriting Recognition Model + for Turkic Languages in Latin and Cyrillic Script. Project report, Nazarbayev University. + + @techreport{suleimenov2026turkic, + author = {Suleimenov, Anuar and Bolatov, Zhalgasbek and Baglanova, Aidana and Kadirbekova, Anel and Nguyen, Anh Tu}, + title = {A Handwriting Recognition Model for Turkic Languages in Latin and Cyrillic Script}, + institution = {Nazarbayev University}, + type = {Project report}, + year = {2026} + } + +It contains the page and line generator (pagesynth 0.3.0) with its text filters, the builders of the real-data +manifests and of the training mix, the training code of the vision-language readers and of the CTC line recognizers, +the training and inference code of the line detector, the scorer with its bootstrap intervals and selection rules, the +test-pass and page-scoring scripts, the inference scripts of the release packages, and the code of the planned RQ2 +augmentation study. "The paper" below means the report cited above; section numbers refer to it (S1 to S11 are the +sections of its supplementary material). Comments in the code name the project's work stages in capitals (for example +GEN for the generator, DATA for the real-data manifests, PRINT, FREEZE, LINEDET, REF, VLMA, VLMB, EVALCODE) and use the +round name R5 for the run that produced the paper's results. + + +1. WHAT IS NOT IN THIS PACKAGE + +- No data. None of the real datasets is included, and neither are the project's generated data, manifests, splits or + predictions. Where to obtain the real datasets is listed in part 6. The generated data are released separately under + CC BY-SA 4.0. +- No reader weights. The fine-tuned weights of the three readers (PaddleOCR-VL-1.6, the final model; Qwen3-VL-2B; and + the PP-OCRv6-medium line recognizer with its character language model) are not released. They were trained on KOHTD + and HKR, whose terms limit use to the applicant's group and to academic research, and their authors have not given + permission to share models trained on them. The code here lets others train their own readers from the released + generated data and the real datasets obtained from their sources. +- The line detector's weights are released separately, with this code path, under AGPL-3.0. +- No font files. The generator needs the 73 fonts listed in src/pagesynth/assets/fonts_manifest.tsv (file name, + content fingerprint, licence class, and whether the font is held out of training). Place them in src/pagesynth/assets/fonts/ or + point the environment variable PAGESYNTH_FONTS to their folder. Eight of them are personal-use fonts (licence class + personal_use_only); they may not be redistributed, and the released generated data contain no item drawn with them. +- Not included: the vendored PaddleOCR source used only by the PP-OCRv3 reference re-run (see NOTICE), earlier + generator versions (0.1 and 0.2.0; the text filters of 0.2.0 are identical to those of 0.3.0), staging and test copies of + scripts, one-off probes, the corrector pilot (never trained), the unfinished full-schedule PP-OCRv3 re-run, and the + download and extraction scripts of KOHTD, which need access credentials from its authors. +- config_r5eval/sota_checklist.json is not included. scripts/r5_select_verdict.sbatch passes it to + scripts/r5eval/verdict.py; remove that argument (verdict.py runs without it) or supply your own checklist. + + +2. LICENCES + +Apache-2.0 (LICENSE) for everything except: the line detector's training and inference path and the page pipeline, +which are AGPL-3.0 (LICENSE.AGPL-3.0; the files are listed in NOTICE); the vendored HTR-Flor copy in +src/ref/ (repository state of 23 June 2021; MIT, its own LICENSE); and the Natural Earth map files in +src/pagesynth/assets/naturalearth/ (public domain). Copyright and third-party notices are in NOTICE. + + +3. SETTING UP + +3.1 Paths. The code ran on a Slurm cluster with one code folder and one data folder. Every absolute path in the +package now starts with a placeholder: + + /path/to/TURKIC_OCR_CODE the folder that holds this package (src/, scripts/, ... and the virtual environments) + /path/to/TURKIC_OCR_DATA the data folder, with data/raw, data/processed, outputs, checkpoints, logs, hf_cache, tmp + +Replace both with your own folders before running anything, for example: + + grep -rlF /path/to/TURKIC_OCR_CODE . | xargs sed -i 's#/path/to/TURKIC_OCR_CODE#/home/me/turkic_ocr#g' + grep -rlF /path/to/TURKIC_OCR_DATA . | xargs sed -i 's#/path/to/TURKIC_OCR_DATA#/data/turkic_ocr#g' + +Neither placeholder is a prefix of the other, so the order does not matter. The Slurm headers name +the partitions (H100, ZEN4) and quality-of-service names of the original cluster; adapt them to yours. Many scripts +and comments refer to the project's working records (paths that begin with records/, or files under the data folder +such as manifests and score files); these records are not part of this package. + +3.2 Python environments. The scripts call the interpreter of a project environment, for example +/path/to/TURKIC_OCR_CODE/.venv_gen/bin/python. The folder environments/ holds the exact package list of each +environment, made with 'uv pip freeze'. To rebuild one: + + uv venv --python 3.12 /path/to/TURKIC_OCR_CODE/.venv_gen + uv pip install --python /path/to/TURKIC_OCR_CODE/.venv_gen/bin/python -r environments/venv_gen.requirements + +PyTorch builds with a +cu suffix in the lists come from the PyTorch package index (add +--extra-index-url https://download.pytorch.org/whl/, the tag matching the suffix). + + environment (file) Python main use + .venv (venv.requirements) 3.12 real-data manifests (scripts/r5), KOHTD split and leak checks, zero-shot screen + .venv_gen (venv_gen.requirements) 3.12 generator, training-mix freeze, release data build + .venv_kraken 3.12 CTC line recognizers, letter model, detector, scorer jobs, test pass 2, RQ2 + .venv_vlm 3.12 vision-language training and evaluation (scripts/r5_vlma), single page model, + loop guard, page check, showcase + .venv_vlm_ (9 files) 3.12 * one per extra candidate in scripts/r5_vlmb (* unlimited_ocr_2: 3.10) + .venv_print 3.12 real printed lines (scripts/r5_print) + .venv_ref_tf 3.11 HTR-Flor reference re-run (R1) + .venv_ref_paddle, .venv_ref_paddle_cpu 3.11 PP-OCRv3 reference re-run (R2) + .venv_dl see file download tools (Kazakh web benchmark) + +The exact Python version of each environment is in its file's first line. Each shell and sbatch file names the +environment its step used. The release packages in release/ carry their own requirements.txt. + + +4. FOLDERS AND WHERE THEY APPEAR IN THE PAPER + +src/pagesynth/ Page and line generator 0.3.0: text cleaning and filters (text.py, langtext.py, + textbuild.py, vocab.py), fonts and the glyph gate, the simulated writer, layouts, paper, + marks, maps, capture, cropping; produce_r5.py and scripts/ run the text build, the text + split by source document and the production. Paper: Section 2.2, S2. +src/linedet/ CTC line recognizers (PP-OCRv6 medium and small, CRNN, HTR-VT-style model), training + driver, prediction, the character 6-gram letter model with beam search and its gate, and + (det_*.py, AGPL-3.0) the YOLO11s line detector: data preparation, training, evaluation. + Paper: Sections 3.4 and 3.5, S6, S9, S10. +src/r5eval/, scripts/r5eval/ Scorer: text normalisation, CER and WER, look-alike repair, form-level bootstrap, +config_r5eval/, tests_r5eval/ Holm correction, selection of leaders and of the final model, decision rules, report + cards; with its configuration and tests. Paper: Section 4, S7. +scripts/r5_score.sbatch and Scoring, selection, verdict, learning-curve and self-test jobs of the scorer. + the other scripts/r5_*.sbatch Paper: Section 4, S7. +scripts/r5_gate/ Gate files that kept the test sets sealed until the single test pass. Paper: Section 4, S7. +scripts/r5/ Real-data manifests (KOHTD, HKR, Cyrillic Handwriting Dataset, School Notebooks, RUKOPYS, + LocalDoc), de-duplication against held-out images, the registry of training, validation + and test sets, validation subsets and the unseen-word slice. Paper: Section 2.1, S1, S4, S7. +scripts/k1_labels_all.py, KOHTD split by exam form (a salted deterministic function of the form number). Paper: Section 2.1, S4. + scripts/k1_build_split.py +scripts/kohtd_leak_* Checks that no KOHTD training crop without a form number is a copy of a validation or + test crop. Paper: S4. +scripts/r5_print/ Real printed lines: candidate PDFs from FinePDFs, text-layer check, line cutting, pixel + checks, split by document. Paper: Section 2.1, S3. +scripts/r5_freeze/ Freeze of the training mix (shares, de-duplication against held-out sets, sample + sequences). Paper: Section 2.3, S2. +scripts/j2/ Zero-shot screen of released document models on KOHTD validation words. Paper: Section 3.2. +scripts/r5_vlma/ Fine-tuning and evaluation of the vision-language readers (shared recipe, short and long + runs, slot runners), preference post-training (DPO, GRPO), and the sealed test pass. + Paper: Sections 3.2, 3.3 and 4, S5, S6, S7. +scripts/r5_vlmb/ Adapters, environments and runner for the extra vision-language candidates. Paper: S5, S6. +scripts/r5_linedet/ Jobs of the line recognizers, the detector and the letter model. Paper: Sections 3.4, 3.5, S6. +scripts/r5_ref/, src/ref/ Reference re-runs: HTR-Flor (R1, vendored copy in src/ref/) and PP-OCRv3 (R2, PaddleOCR + not included). Paper: Section 5, S10. +scripts/r5_testpass2/ Second test pass and its amendments: real handwriting and print tests, page tests + (TurkishOCR-Bench, Kazakh web benchmark), label-free re-reading of the line recognizer, + per-language tables, error analysis. Paper: Section 5, S7, S8, S9. +scripts/tp2_proposal_metrics.py Measures for the research questions. Paper: Section 6.1, S8. +scripts/r5_erran/ Error analysis of validation outputs (label errors, ambiguous handwriting). Paper: S7. +scripts/b1_page_check/ Page check: the final model on whole pages, alone and after the detector. Paper: S9. +scripts/r5_onemodel/ Single page model: page records, training, page scoring. Paper: S6, S9. +scripts/r5_loopguard/ Loop guard for the single page model. Paper: S9, S10. +scripts/r5_showcase/ Showcase pages: the generator stages of chosen validation pages (material for Figure 2) + and pages read by the pipeline. Paper: Section 2.2, S11. +scripts/r5_release/ Checks of the first release candidate, including the batching diagnostic of the line + recognizer. Paper: S7 (the batching leak). +scripts/release2/ Release build: data package, Parquet shards, regeneration check of every released page, + Sakha-text check, cards and file verification; rel2_d5_* (AGPL-3.0) retrain and check the + released detector without the personal-use-font pages. Paper: S11. +release/ Inference scripts and requirements of the release packages: the three readers (whose + weights are not released), the line detector and the page pipeline (AGPL-3.0). Paper: S11. +src/rq2/, scripts/r5_rq2/, RQ2 augmentation study (line height 32 or 64 px crossed with a typical or a diacritic-safe +src/lettersynth/ augmentation policy) and its pixel probe; src/lettersynth holds only the letter-sheet + reader that the probe uses. This code was written after the paper's results; the paper + states that the study was not run, and no RQ2 result is part of it. +environments/ Package lists of the Python environments (part 3.2). + + +5. KNOWN ISSUES + +- Content pins. Some files pin the exact content of other files as it was on the cluster, and a few check it at start. + Making the paths configurable changed some pinned files, so those pins no longer match (the list of affected pins + is in part 7). Update the pinned values after configuring the paths, or skip the check. +- release/turkic-ocr-ppocrv6-medium/infer.py is the inference script of the withheld PP-OCRv6 package. Its docstring + was written before the corrections the paper reports in S7 (the batching leak) and was not updated; the paper's + figures supersede the ones it quotes. +- The generator reproduces the content of a page from its seed but not every byte (paper, S11). +- The scripts were written for one cluster and one run of the project: many take their inputs from fixed paths and + write records of that run. They document what was done; running them elsewhere needs the data, the paths and the + job headers set up as described in part 3. + + +6. REAL DATASETS: NOT INCLUDED, WHERE TO OBTAIN THEM + + KOHTD (Kazakh handwriting) https://github.com/abdoelsayed2016/KOHTD (the authors' application form) + HKR (Kazakh and Russian) https://github.com/abdoelsayed2016/HKR_Dataset (the authors' application form) + School Notebooks RU https://huggingface.co/datasets/ai-forever/school_notebooks_RU + Cyrillic Handwriting Dataset https://www.kaggle.com/datasets/constantinwerner/cyrillic-handwriting-dataset + Azerbaijani Handwritten OCR + Benchmark (LocalDoc) https://huggingface.co/datasets/LocalDoc/azerbaijani-htr-benchmark + TurkishOCR-Bench https://huggingface.co/datasets/moganai/TurkishOCR-Bench + RUKOPYS (Ukrainian) https://huggingface.co/datasets/UkrainianCatholicUniversity/rukopys + FinePDFs (real printed lines) https://huggingface.co/datasets/HuggingFaceFW/finepdfs + FineWeb-2 (generator text) https://huggingface.co/datasets/HuggingFaceFW/fineweb-2 + Wikipedia (generator text) https://huggingface.co/datasets/wikimedia/wikipedia (snapshot 20231101) + PP-OCRv6 medium base weights https://doi.org/10.5281/zenodo.21788410 + +Each dataset keeps its own licence and terms. Three further sources are read by the code but are not in the paper's +reference list; their identifiers are taken from the code: + Kazakh web benchmark Hugging Face dataset Omar-2002/kz_benchmark_data (scripts/r5_testpass2/tp2_kzb_fetch.py) + Sakha newspaper corpus Hugging Face dataset ailabykt/sakha-corpus-mono (generator text for Sakha) + Kazakh handwritten letter sheets https://github.com/Nuray-Sheriyeva/Kazakh_Handwritten_Letter_Dataset (dataset_split_v2; + read by the RQ2 pixel probe) + + +7. EDITS MADE FOR THE PACKAGE, AND CONTENT PINS + +The package was made from the project's files by these edits only: absolute paths were replaced by the placeholders of +part 3.1; comments and descriptive strings were reworded; the folder scripts/r5_gate was renamed; two output fields +were renamed (endpoints_confirmed in the verdict written by scripts/r5eval/verdict.py, added_beyond_plan in the set +registry written by scripts/r5/r5_registry.py); one verdict text of scripts/r5_freeze/dedupe_verdict.py now reads +"NEEDS MANUAL REVIEW"; and scripts/r5_testpass2/tp2_make_plan.py no longer records the fingerprint of a planning note. + +Two pins that the code checks at run time were updated to the shipped files, so they match: + src/r5eval/cards.py (label-rule pin) the content of config_r5eval/r5_descriptive_labels.txt (reworded first line), + checked by scripts/r5eval/report_cards.py. + src/r5eval/frozen.py (frozen-file pin) the content of src/r5eval/frozen/postproc_vlma.py (one reworded docstring line; + scripts/r5_vlma/postproc.py and scripts/r5_vlmb/postproc.py are identical + copies), checked whenever the scorer is imported. + +Four pins refer to a file that these edits changed and were left as they were: + + src/rq2/geom.py pins src/linedet/common.py (paths). Checked at start: the RQ2 wrappers stop + with "REFUSED". After configuring the paths, put the new fingerprint of + src/linedet/common.py into PINNED in src/rq2/geom.py. The same table pins + four kraken files of the installed kraken package and three data files. + scripts/r5_vlma/make_vlmb_testpass.py pins scripts/r5_vlmb/vlmb_eval_vlm.py (a reworded comment); it is the one-time + builder of scripts/r5_vlmb/vlmb_eval_vlm_testpass.py, which also quotes that + fingerprint in a comment. + scripts/r5_vlma/testpass_config.json quotes the fingerprint of scripts/r5_linedet/test_pass_commands.sh (paths) in a note. + +All other pins inside the package still match. diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7a4217767f763ac97d2e8580f216602a85f6079c --- /dev/null +++ b/README.md @@ -0,0 +1,251 @@ +--- +# Licence: Apache-2.0 for the package, except the line detector's training and inference path and the page +# pipeline, which are AGPL-3.0 (LICENSE.AGPL-3.0; the files are listed in NOTICE); see also README part 2. +license: apache-2.0 +language: +- kk +- ky +- uz +- tr +- az +- tt +- ba +- tk +- sah +pipeline_tag: image-to-text +tags: +- ocr +- handwriting +- handwritten-text-recognition +- text-line-detection +- synthetic-data +- document-images +- turkic-languages +- cyrillic +- latin-script +--- + +TURKIC OCR: CODE OF THE GENERATOR, TRAINING AND EVALUATION +(release candidate rc1_code) + +This package holds the code behind the project report + + Suleimenov, A., Bolatov, Z., Baglanova, A., Kadirbekova, A., Nguyen, A. T. (2026). A Handwriting Recognition Model + for Turkic Languages in Latin and Cyrillic Script. Project report, Nazarbayev University. + + @techreport{suleimenov2026turkic, + author = {Suleimenov, Anuar and Bolatov, Zhalgasbek and Baglanova, Aidana and Kadirbekova, Anel and Nguyen, Anh Tu}, + title = {A Handwriting Recognition Model for Turkic Languages in Latin and Cyrillic Script}, + institution = {Nazarbayev University}, + type = {Project report}, + year = {2026} + } + +It contains the page and line generator (pagesynth 0.3.0) with its text filters, the builders of the real-data +manifests and of the training mix, the training code of the vision-language readers and of the CTC line recognizers, +the training and inference code of the line detector, the scorer with its bootstrap intervals and selection rules, the +test-pass and page-scoring scripts, the inference scripts of the release packages, and the code of the planned RQ2 +augmentation study. "The paper" below means the report cited above; section numbers refer to it (S1 to S11 are the +sections of its supplementary material). Comments in the code name the project's work stages in capitals (for example +GEN for the generator, DATA for the real-data manifests, PRINT, FREEZE, LINEDET, REF, VLMA, VLMB, EVALCODE) and use the +round name R5 for the run that produced the paper's results. + + +1. WHAT IS NOT IN THIS PACKAGE + +- No data. None of the real datasets is included, and neither are the project's generated data, manifests, splits or + predictions. Where to obtain the real datasets is listed in part 6. The generated data are released separately under + CC BY-SA 4.0. +- No reader weights. The fine-tuned weights of the three readers (PaddleOCR-VL-1.6, the final model; Qwen3-VL-2B; and + the PP-OCRv6-medium line recognizer with its character language model) are not released. They were trained on KOHTD + and HKR, whose terms limit use to the applicant's group and to academic research, and their authors have not given + permission to share models trained on them. The code here lets others train their own readers from the released + generated data and the real datasets obtained from their sources. +- The line detector's weights are released separately, with this code path, under AGPL-3.0. +- No font files. The generator needs the 73 fonts listed in src/pagesynth/assets/fonts_manifest.tsv (file name, + content fingerprint, licence class, and whether the font is held out of training). Place them in src/pagesynth/assets/fonts/ or + point the environment variable PAGESYNTH_FONTS to their folder. Eight of them are personal-use fonts (licence class + personal_use_only); they may not be redistributed, and the released generated data contain no item drawn with them. +- Not included: the vendored PaddleOCR source used only by the PP-OCRv3 reference re-run (see NOTICE), earlier + generator versions (0.1 and 0.2.0; the text filters of 0.2.0 are identical to those of 0.3.0), staging and test copies of + scripts, one-off probes, the corrector pilot (never trained), the unfinished full-schedule PP-OCRv3 re-run, and the + download and extraction scripts of KOHTD, which need access credentials from its authors. +- config_r5eval/sota_checklist.json is not included. scripts/r5_select_verdict.sbatch passes it to + scripts/r5eval/verdict.py; remove that argument (verdict.py runs without it) or supply your own checklist. + + +2. LICENCES + +Apache-2.0 (LICENSE) for everything except: the line detector's training and inference path and the page pipeline, +which are AGPL-3.0 (LICENSE.AGPL-3.0; the files are listed in NOTICE); the vendored HTR-Flor copy in +src/ref/ (repository state of 23 June 2021; MIT, its own LICENSE); and the Natural Earth map files in +src/pagesynth/assets/naturalearth/ (public domain). Copyright and third-party notices are in NOTICE. + + +3. SETTING UP + +3.1 Paths. The code ran on a Slurm cluster with one code folder and one data folder. Every absolute path in the +package now starts with a placeholder: + + /path/to/TURKIC_OCR_CODE the folder that holds this package (src/, scripts/, ... and the virtual environments) + /path/to/TURKIC_OCR_DATA the data folder, with data/raw, data/processed, outputs, checkpoints, logs, hf_cache, tmp + +Replace both with your own folders before running anything, for example: + + grep -rlF /path/to/TURKIC_OCR_CODE . | xargs sed -i 's#/path/to/TURKIC_OCR_CODE#/home/me/turkic_ocr#g' + grep -rlF /path/to/TURKIC_OCR_DATA . | xargs sed -i 's#/path/to/TURKIC_OCR_DATA#/data/turkic_ocr#g' + +Neither placeholder is a prefix of the other, so the order does not matter. The Slurm headers name +the partitions (H100, ZEN4) and quality-of-service names of the original cluster; adapt them to yours. Many scripts +and comments refer to the project's working records (paths that begin with records/, or files under the data folder +such as manifests and score files); these records are not part of this package. + +3.2 Python environments. The scripts call the interpreter of a project environment, for example +/path/to/TURKIC_OCR_CODE/.venv_gen/bin/python. The folder environments/ holds the exact package list of each +environment, made with 'uv pip freeze'. To rebuild one: + + uv venv --python 3.12 /path/to/TURKIC_OCR_CODE/.venv_gen + uv pip install --python /path/to/TURKIC_OCR_CODE/.venv_gen/bin/python -r environments/venv_gen.requirements + +PyTorch builds with a +cu suffix in the lists come from the PyTorch package index (add +--extra-index-url https://download.pytorch.org/whl/, the tag matching the suffix). + + environment (file) Python main use + .venv (venv.requirements) 3.12 real-data manifests (scripts/r5), KOHTD split and leak checks, zero-shot screen + .venv_gen (venv_gen.requirements) 3.12 generator, training-mix freeze, release data build + .venv_kraken 3.12 CTC line recognizers, letter model, detector, scorer jobs, test pass 2, RQ2 + .venv_vlm 3.12 vision-language training and evaluation (scripts/r5_vlma), single page model, + loop guard, page check, showcase + .venv_vlm_ (9 files) 3.12 * one per extra candidate in scripts/r5_vlmb (* unlimited_ocr_2: 3.10) + .venv_print 3.12 real printed lines (scripts/r5_print) + .venv_ref_tf 3.11 HTR-Flor reference re-run (R1) + .venv_ref_paddle, .venv_ref_paddle_cpu 3.11 PP-OCRv3 reference re-run (R2) + .venv_dl see file download tools (Kazakh web benchmark) + +The exact Python version of each environment is in its file's first line. Each shell and sbatch file names the +environment its step used. The release packages in release/ carry their own requirements.txt. + + +4. FOLDERS AND WHERE THEY APPEAR IN THE PAPER + +src/pagesynth/ Page and line generator 0.3.0: text cleaning and filters (text.py, langtext.py, + textbuild.py, vocab.py), fonts and the glyph gate, the simulated writer, layouts, paper, + marks, maps, capture, cropping; produce_r5.py and scripts/ run the text build, the text + split by source document and the production. Paper: Section 2.2, S2. +src/linedet/ CTC line recognizers (PP-OCRv6 medium and small, CRNN, HTR-VT-style model), training + driver, prediction, the character 6-gram letter model with beam search and its gate, and + (det_*.py, AGPL-3.0) the YOLO11s line detector: data preparation, training, evaluation. + Paper: Sections 3.4 and 3.5, S6, S9, S10. +src/r5eval/, scripts/r5eval/ Scorer: text normalisation, CER and WER, look-alike repair, form-level bootstrap, +config_r5eval/, tests_r5eval/ Holm correction, selection of leaders and of the final model, decision rules, report + cards; with its configuration and tests. Paper: Section 4, S7. +scripts/r5_score.sbatch and Scoring, selection, verdict, learning-curve and self-test jobs of the scorer. + the other scripts/r5_*.sbatch Paper: Section 4, S7. +scripts/r5_gate/ Gate files that kept the test sets sealed until the single test pass. Paper: Section 4, S7. +scripts/r5/ Real-data manifests (KOHTD, HKR, Cyrillic Handwriting Dataset, School Notebooks, RUKOPYS, + LocalDoc), de-duplication against held-out images, the registry of training, validation + and test sets, validation subsets and the unseen-word slice. Paper: Section 2.1, S1, S4, S7. +scripts/k1_labels_all.py, KOHTD split by exam form (a salted deterministic function of the form number). Paper: Section 2.1, S4. + scripts/k1_build_split.py +scripts/kohtd_leak_* Checks that no KOHTD training crop without a form number is a copy of a validation or + test crop. Paper: S4. +scripts/r5_print/ Real printed lines: candidate PDFs from FinePDFs, text-layer check, line cutting, pixel + checks, split by document. Paper: Section 2.1, S3. +scripts/r5_freeze/ Freeze of the training mix (shares, de-duplication against held-out sets, sample + sequences). Paper: Section 2.3, S2. +scripts/j2/ Zero-shot screen of released document models on KOHTD validation words. Paper: Section 3.2. +scripts/r5_vlma/ Fine-tuning and evaluation of the vision-language readers (shared recipe, short and long + runs, slot runners), preference post-training (DPO, GRPO), and the sealed test pass. + Paper: Sections 3.2, 3.3 and 4, S5, S6, S7. +scripts/r5_vlmb/ Adapters, environments and runner for the extra vision-language candidates. Paper: S5, S6. +scripts/r5_linedet/ Jobs of the line recognizers, the detector and the letter model. Paper: Sections 3.4, 3.5, S6. +scripts/r5_ref/, src/ref/ Reference re-runs: HTR-Flor (R1, vendored copy in src/ref/) and PP-OCRv3 (R2, PaddleOCR + not included). Paper: Section 5, S10. +scripts/r5_testpass2/ Second test pass and its amendments: real handwriting and print tests, page tests + (TurkishOCR-Bench, Kazakh web benchmark), label-free re-reading of the line recognizer, + per-language tables, error analysis. Paper: Section 5, S7, S8, S9. +scripts/tp2_proposal_metrics.py Measures for the research questions. Paper: Section 6.1, S8. +scripts/r5_erran/ Error analysis of validation outputs (label errors, ambiguous handwriting). Paper: S7. +scripts/b1_page_check/ Page check: the final model on whole pages, alone and after the detector. Paper: S9. +scripts/r5_onemodel/ Single page model: page records, training, page scoring. Paper: S6, S9. +scripts/r5_loopguard/ Loop guard for the single page model. Paper: S9, S10. +scripts/r5_showcase/ Showcase pages: the generator stages of chosen validation pages (material for Figure 2) + and pages read by the pipeline. Paper: Section 2.2, S11. +scripts/r5_release/ Checks of the first release candidate, including the batching diagnostic of the line + recognizer. Paper: S7 (the batching leak). +scripts/release2/ Release build: data package, Parquet shards, regeneration check of every released page, + Sakha-text check, cards and file verification; rel2_d5_* (AGPL-3.0) retrain and check the + released detector without the personal-use-font pages. Paper: S11. +release/ Inference scripts and requirements of the release packages: the three readers (whose + weights are not released), the line detector and the page pipeline (AGPL-3.0). Paper: S11. +src/rq2/, scripts/r5_rq2/, RQ2 augmentation study (line height 32 or 64 px crossed with a typical or a diacritic-safe +src/lettersynth/ augmentation policy) and its pixel probe; src/lettersynth holds only the letter-sheet + reader that the probe uses. This code was written after the paper's results; the paper + states that the study was not run, and no RQ2 result is part of it. +environments/ Package lists of the Python environments (part 3.2). + + +5. KNOWN ISSUES + +- Content pins. Some files pin the exact content of other files as it was on the cluster, and a few check it at start. + Making the paths configurable changed some pinned files, so those pins no longer match (the list of affected pins + is in part 7). Update the pinned values after configuring the paths, or skip the check. +- release/turkic-ocr-ppocrv6-medium/infer.py is the inference script of the withheld PP-OCRv6 package. Its docstring + was written before the corrections the paper reports in S7 (the batching leak) and was not updated; the paper's + figures supersede the ones it quotes. +- The generator reproduces the content of a page from its seed but not every byte (paper, S11). +- The scripts were written for one cluster and one run of the project: many take their inputs from fixed paths and + write records of that run. They document what was done; running them elsewhere needs the data, the paths and the + job headers set up as described in part 3. + + +6. REAL DATASETS: NOT INCLUDED, WHERE TO OBTAIN THEM + + KOHTD (Kazakh handwriting) https://github.com/abdoelsayed2016/KOHTD (the authors' application form) + HKR (Kazakh and Russian) https://github.com/abdoelsayed2016/HKR_Dataset (the authors' application form) + School Notebooks RU https://huggingface.co/datasets/ai-forever/school_notebooks_RU + Cyrillic Handwriting Dataset https://www.kaggle.com/datasets/constantinwerner/cyrillic-handwriting-dataset + Azerbaijani Handwritten OCR + Benchmark (LocalDoc) https://huggingface.co/datasets/LocalDoc/azerbaijani-htr-benchmark + TurkishOCR-Bench https://huggingface.co/datasets/moganai/TurkishOCR-Bench + RUKOPYS (Ukrainian) https://huggingface.co/datasets/UkrainianCatholicUniversity/rukopys + FinePDFs (real printed lines) https://huggingface.co/datasets/HuggingFaceFW/finepdfs + FineWeb-2 (generator text) https://huggingface.co/datasets/HuggingFaceFW/fineweb-2 + Wikipedia (generator text) https://huggingface.co/datasets/wikimedia/wikipedia (snapshot 20231101) + PP-OCRv6 medium base weights https://doi.org/10.5281/zenodo.21788410 + +Each dataset keeps its own licence and terms. Three further sources are read by the code but are not in the paper's +reference list; their identifiers are taken from the code: + Kazakh web benchmark Hugging Face dataset Omar-2002/kz_benchmark_data (scripts/r5_testpass2/tp2_kzb_fetch.py) + Sakha newspaper corpus Hugging Face dataset ailabykt/sakha-corpus-mono (generator text for Sakha) + Kazakh handwritten letter sheets https://github.com/Nuray-Sheriyeva/Kazakh_Handwritten_Letter_Dataset (dataset_split_v2; + read by the RQ2 pixel probe) + + +7. EDITS MADE FOR THE PACKAGE, AND CONTENT PINS + +The package was made from the project's files by these edits only: absolute paths were replaced by the placeholders of +part 3.1; comments and descriptive strings were reworded; the folder scripts/r5_gate was renamed; two output fields +were renamed (endpoints_confirmed in the verdict written by scripts/r5eval/verdict.py, added_beyond_plan in the set +registry written by scripts/r5/r5_registry.py); one verdict text of scripts/r5_freeze/dedupe_verdict.py now reads +"NEEDS MANUAL REVIEW"; and scripts/r5_testpass2/tp2_make_plan.py no longer records the fingerprint of a planning note. + +Two pins that the code checks at run time were updated to the shipped files, so they match: + src/r5eval/cards.py (label-rule pin) the content of config_r5eval/r5_descriptive_labels.txt (reworded first line), + checked by scripts/r5eval/report_cards.py. + src/r5eval/frozen.py (frozen-file pin) the content of src/r5eval/frozen/postproc_vlma.py (one reworded docstring line; + scripts/r5_vlma/postproc.py and scripts/r5_vlmb/postproc.py are identical + copies), checked whenever the scorer is imported. + +Four pins refer to a file that these edits changed and were left as they were: + + src/rq2/geom.py pins src/linedet/common.py (paths). Checked at start: the RQ2 wrappers stop + with "REFUSED". After configuring the paths, put the new fingerprint of + src/linedet/common.py into PINNED in src/rq2/geom.py. The same table pins + four kraken files of the installed kraken package and three data files. + scripts/r5_vlma/make_vlmb_testpass.py pins scripts/r5_vlmb/vlmb_eval_vlm.py (a reworded comment); it is the one-time + builder of scripts/r5_vlmb/vlmb_eval_vlm_testpass.py, which also quotes that + fingerprint in a comment. + scripts/r5_vlma/testpass_config.json quotes the fingerprint of scripts/r5_linedet/test_pass_commands.sh (paths) in a note. + +All other pins inside the package still match. diff --git a/config_r5eval/arms_info_template.json b/config_r5eval/arms_info_template.json new file mode 100644 index 0000000000000000000000000000000000000000..3922cdd0c6ea3894815463c4f13cd3a4b5304ed1 --- /dev/null +++ b/config_r5eval/arms_info_template.json @@ -0,0 +1,6 @@ +{ + "_how_to_use": "arms_info.json for select_b1b2.py and report_cards.py. Only list what is known; unique_params_b comes from CODE/scripts/r5_vlma/models_r5.tsv when this file lacks it. flags are free text shown on the card. not_trained_reason: set it when the arm could not be trained (status NOT TRAINED). broken_run_reason: set it when the loss became NaN or infinite or the run ended early for a reason other than the time cap (status BROKEN RUN). final_checkpoint: the checkpoint that counts as final (default: final, leader, long, short in that order). seed2_checkpoint: default _seed2.", + "paddleocr_vl_1_6": {"unique_params_b": 0.9586, "flags": [], "final_checkpoint": "short"}, + "teleocr": {"not_trained_reason": "example: needs the maker's code and failed the 20-step save-and-resume test"}, + "example_broken": {"broken_run_reason": "example: loss became NaN at step 312"} +} diff --git a/config_r5eval/endpoints_proposal.json b/config_r5eval/endpoints_proposal.json new file mode 100644 index 0000000000000000000000000000000000000000..f582a219ce9c49c21f915059362dafb2d4b07949 --- /dev/null +++ b/config_r5eval/endpoints_proposal.json @@ -0,0 +1,26 @@ +{ + "config_version": "r5-endpoints-1", + "status": "PROPOSED by EVALCODE on 21 Nov 2026; it is confirmed (confirmed set to true) before the test pass; verdict.json records its sha256", + "confirmed": false, + "B": 10000, + "seed": 20261121, + "margin": 0.10, + "T1": {"evalsets": ["kohtd_test"], "P1_group": "all", "P2_group": "slice:P2", + "note": "P1 = all KOHTD test crops; P2 = the unseen-word slice of clarification G3, computed inside the gated pass from the frozen K_train"}, + "T1_rand": {"evalsets": ["kohtd_rand_test"], "P1_group": "all", + "note": "test part of the seeded crop-level random 70/15/15 split of KOHTD (amendment 3.3 D5 variant ii); replication check only, never compared with our arms"}, + "T2": {"evalsets": ["print_real_test"], "audited_languages": null, + "note": "typed non-inferiority (N): the real born-digital line test built by stage PRINT. audited_languages must be filled from PRINT's audit (languages with at least 49 of 50 test lines matching); null makes clauses 3.1.b, 3.3.n, 3.5.n and 4.c not evaluable. Alternative if print_real_test is unusable: synth_typed_test (synthetic lines, exact by construction)."}, + "clutter": {"evalsets": ["synth_clutter_test"], "note": "clutter-only crops for HR1; the registry name may carry a suffix such as ' (T4)': the file stem decides"}, + "validation": {"kohtd_val": ["kohtd_val"], "V1": ["V1", "kohtd_screen_v1"]}, + "reader_only_counts_as_pipeline": false, + "reader_only_note": "gate G needs the memory of the whole pipeline; if no detector was measured the clause stays not evaluable unless this is set to true", + "reference_arms": { + "R1": {"name": "HTR-Flor", "published": {"cer_percent": 6.52, "wer_percent": 24.52, "ser_percent": 26.98, "metric": "HTR-Flor style (lower case, longer-string denominator, mean over crops) probably", + "source": "Toiganbayeva et al., arXiv 2110.04075v1, p.19 Table 4; records/R5/RESEVAL/sota_table.json"}}, + "R2": {"name": "SVTR-Tiny", "published": {"cer_percent": 4.59, "wer_percent": 20.00, "metric": "CER = (S+I+D)/N; WER = share of wrongly recognised images", + "source": "Bimurat et al., SDU Bulletin 65(2) 2024, p.11 Table 3 and p.10 section 2.5; records/R5/RESEVAL/sota_table.json"}} + }, + "seed_convention": "a second seed is a second checkpoint of the same arm named _seed2 (for example long_seed2, short_seed2, leader_seed2); selection.json roles carry it as seed2_checkpoint. Voted outputs are the checkpoint 'vote' of the arm.", + "reference_roles": "selection.json roles R1 and R2 (variant i: trained on KOHTD train of our form split, scored on kohtd_test); R1_rand and R2_rand (variant ii: scored on kohtd_rand_test)" +} diff --git a/config_r5eval/mix_scratch.yaml b/config_r5eval/mix_scratch.yaml new file mode 100644 index 0000000000000000000000000000000000000000..604235accdf6e3e2f7a4b6af4e2923972fbb7281 --- /dev/null +++ b/config_r5eval/mix_scratch.yaml @@ -0,0 +1,8 @@ +# SCRATCH mix used only to time and size-check build_ktrain.py on the real train manifests before mix_v1 is frozen. +# It is NOT mix_v1 and nothing reads it for training or scoring. Output goes to DATA/tmp/evalcode_ktrain_scratch. +mix: + members: + - {name: kohtd_train, manifest: /path/to/TURKIC_OCR_DATA/data/processed/r5/manifests/kohtd_train.tsv, share: 0.25} + - {name: hkr_train, manifest: /path/to/TURKIC_OCR_DATA/data/processed/r5/manifests/hkr_train.tsv, share: 0.25} + - {name: chd_train, manifest: /path/to/TURKIC_OCR_DATA/data/processed/r5/manifests/chd_train.tsv, share: 0.25} + - {name: school_train, manifest: /path/to/TURKIC_OCR_DATA/data/processed/r5/manifests/school_train.tsv, share: 0.25} diff --git a/config_r5eval/r5_descriptive_labels.txt b/config_r5eval/r5_descriptive_labels.txt new file mode 100644 index 0000000000000000000000000000000000000000..43126ca0b614b832908f32a57986d433690ca010 --- /dev/null +++ b/config_r5eval/r5_descriptive_labels.txt @@ -0,0 +1,17 @@ +DESCRIPTIVE LABELS FOR EVERY ARM (R5). Written on 20 Nov 2026, before any arm has trained on mix_v1 and before any validation figure of a fine-tuned arm exists. Fingerprinted in r5_descriptive_labels.sha256. + +The owner asked (21 Nov) for results that show "what are prosperous models and which ones have failed so far". These labels describe the arms on the pages. They do NOT change the decision rule: B1, B2 and the verdict follow version 3 + 3.1 + 3.2 and its clarifications. The labels use validation data only, at the P_short checkpoint (the equal comparison), with greedy decoding. Every label is stored with the figures that produced it. + +Exactly one status per arm, checked in this order: +1. NOT TRAINED: set-up failed within the 3-hour budget, or the 20-step plus save-and-resume test failed. The reason is recorded. +2. BROKEN RUN: training loss became NaN or infinite, or the run ended early for a reason other than the time cap. The reason is recorded. +3. NO GAIN: V1 CER at P_short is not lower than the arm's own zero-shot V1 CER (VLM arms that ran in the zero-shot screen only). +4. FAILS MEMORY GATE: peak torch.cuda.max_memory_reserved above 24 GB when reading one crop at batch 1 (pages come later). +5. HALLUCINATES: on validation analogues of the veto, HR1 on synth_clutter_val above max(2 x HR1 of A1, HR1 of A1 + 2 points) or above 5% absolute; or HR4 (loops) above 0.1% on V1. +6. NOT COMPETITIVE: V1 CER more than 1.5 x the lowest V1 CER of any arm at P_short. +7. COMPETITIVE: V1 CER within 1.5 x the lowest, but not PROMISING. +8. PROMISING: V1 CER within 10% (relative) of the lowest V1 CER at P_short, or the lowest V1 CER in its size class (line; VLM below 0.5B; 0.5B to 1.5B; above 1.5B). +LEADER is added to the two arms chosen under amendment 3.2 C4. + +Language flags (any status): an arm is flagged "weak on " when its CER on that language-script, in synth_hand_val, synth_typed_val or print_real_val, is more than 2 x its own macro CER over the language-scripts of that set. +Learning-curve flag: "still improving" when V1-curve CER fell by more than 10% (relative) between the 75% and the 100% points of P_short. "Plateaued" otherwise. diff --git a/config_r5eval/sota_attestations_template.json b/config_r5eval/sota_attestations_template.json new file mode 100644 index 0000000000000000000000000000000000000000..144760f9fa369295772c5304097eca15e87896db --- /dev/null +++ b/config_r5eval/sota_attestations_template.json @@ -0,0 +1,8 @@ +{ + "_how_to_use": "Copy to sota_attestations.json and set holds to true or false for the items that no code can decide. Items the code decides itself (C01-C05, C09-C11, C13-C15) ignore this file. Leave holds null to keep the item 'not evaluable'. Pass the file to verdict.py with --sota-attestations.", + "C06": {"holds": null, "note": "same decoding rules: greedy for every arm, no language model or lexicon with test text; state what R1 and R2 used"}, + "C07": {"holds": null, "note": "no train-test overlap: DATA dedupe.json, form-disjoint KOHTD split, generator text split by document; scan-named KOHTD crops are a leak risk that was not tested"}, + "C08": {"holds": null, "note": "same or disclosed training data: our arms use mix_v1, R1 and R2 use KOHTD train only; say whether this difference is disclosed in the claim"}, + "C12": {"holds": null, "note": "test labels exact or human-checked: KOHTD test labels are crowd labels agreed by two volunteers"}, + "C16": {"holds": null, "note": "release enough to recompute: prediction files and scorer code; no data release (owner rule)"} +} diff --git a/config_r5eval/zero_shot_results.tsv b/config_r5eval/zero_shot_results.tsv new file mode 100644 index 0000000000000000000000000000000000000000..e96eac1451fe73f9e6d4324375a97f9e88c7c103 --- /dev/null +++ b/config_r5eval/zero_shot_results.tsv @@ -0,0 +1,28 @@ +model scale complete prompt_source version_revision params_unique gpu crops_done crops_in_list cer_pooled cer_mean cer_mean_cap1 exact_match hr2_ins_per_ref_char hr3_share_refs_ge5 hr4_loop_share empty_share other_script_share ref_other_script_share cer_pooled_casefold exact_casefold hit_cap_share mean_image_tokens crops_per_s_H100_not_5090 crops_per_s_excl_first_batch_H100_not_5090 crops_per_s_median_full_batch_H100_not_5090 new_tokens_per_s_H100_not_5090 disk_read_s_per_crop peak_gpu_mem_GiB_H100_not_5090 batch_size job_ids errors bad_lines best_of_scales_pooled_cer scales_finished +glm_ocr 1 yes card 2e85a62840ccac27daa451df36c736c4636b8628 1107405824 NVIDIA H100 80GB HBM3 3678 3678 1.0695 1.1055 0.9299 0.0087 0.1804 0.4040 0.0041 0.0005 0.0285 0.0000 1.0662 0.0103 0.0033 15.3896 21.5245 22.4950 112.0448 105.6901 0.0012 3.5272 16 50781,50801 0 0 1.0617 1,2,3 +glm_ocr 2 yes card 2e85a62840ccac27daa451df36c736c4636b8628 1107405824 NVIDIA H100 80GB HBM3 3678 3678 1.0617 1.0910 0.9336 0.0079 0.1727 0.4476 0.0005 0.0000 0.0302 0.0000 1.0584 0.0084 0.0005 53.6555 10.8193 11.1040 83.0306 50.6867 0.0013 7.7812 16 50781,50801 0 0 1.0617 1,2,3 +glm_ocr 3 yes card 2e85a62840ccac27daa451df36c736c4636b8628 1107405824 NVIDIA H100 80GB HBM3 3678 3678 1.0871 1.1143 0.9365 0.0073 0.1923 0.4707 0.0011 0.0000 0.0272 0.0000 1.0835 0.0079 0.0011 120.5541 6.8569 6.9783 17.1196 32.1086 0.0029 13.2988 16 50781,50801 0 0 1.0617 1,2,3 +granite_docling_258m 1 yes nearest documented (page prompt) 982fe3b40f2fa73c365bdb1bcacf6c81b7184bfe 257517120 NVIDIA H100 80GB HBM3 3678 3678 1.5829 1.6734 0.9950 0.0005 0.5978 0.5311 0.0182 0.3051 0.0030 0.0000 1.5825 0.0005 0.0791 576.6264 3.7770 3.8776 4.2015 134.0745 0.0014 6.0687 16 50779,50799 0 0 1.5322 1,2,3 +granite_docling_258m 2 yes nearest documented (page prompt) 982fe3b40f2fa73c365bdb1bcacf6c81b7184bfe 257517120 NVIDIA H100 80GB HBM3 3678 3678 1.5322 1.6323 0.9951 0.0005 0.5474 0.5274 0.0160 0.3105 0.0030 0.0000 1.5318 0.0005 0.0704 576.6264 3.8111 3.9132 4.2785 134.4285 0.0014 6.0687 16 50779,50799 0 0 1.5322 1,2,3 +granite_docling_258m 3 yes nearest documented (page prompt) 982fe3b40f2fa73c365bdb1bcacf6c81b7184bfe 257517120 NVIDIA H100 80GB HBM3 3678 3678 1.5553 1.6548 0.9948 0.0005 0.5702 0.5311 0.0155 0.3048 0.0027 0.0000 1.5566 0.0005 0.0721 576.6264 3.7484 3.8470 4.2363 132.7906 0.0020 6.0687 16 50779,50799 0 0 1.5322 1,2,3 +hunyuanocr 1 yes card 47644ecc4fc854efa4f505155158831f36773ee4 996208112 NVIDIA H100 80GB HBM3 3678 3678 1.0890 1.0995 0.9842 0.0068 0.1066 0.4018 0.0000 0.0003 0.0038 0.0000 1.0889 0.0071 0.0000 287.2526 5.5095 5.5792 5.6180 51.0710 0.0006 3.4244 16 50780,50800 0 0 1.0890 1,2,3 +hunyuanocr 2 yes card 47644ecc4fc854efa4f505155158831f36773ee4 996208112 NVIDIA H100 80GB HBM3 3678 3678 1.0900 1.1024 0.9844 0.0071 0.1075 0.3988 0.0000 0.0003 0.0038 0.0000 1.0899 0.0073 0.0000 287.9182 5.1241 5.1864 5.1556 47.5250 0.0014 7.7323 16 50780,50800 0 0 1.0890 1,2,3 +hunyuanocr 3 yes card 47644ecc4fc854efa4f505155158831f36773ee4 996208112 NVIDIA H100 80GB HBM3 3678 3678 1.0896 1.1001 0.9847 0.0068 0.1068 0.3973 0.0000 0.0003 0.0044 0.0000 1.0895 0.0071 0.0000 290.6381 4.0917 4.1287 4.6459 37.8253 0.0020 14.7718 16 50780,50800 0 0 1.0890 1,2,3 +lightonocr_3_0_8b 1 yes card 36d8636925327c671bd8e479c517a004f7566bd9 852985920 NVIDIA H100 80GB HBM3 3678 3678 5.5027 9.6069 0.8769 0.0120 4.6944 0.3504 0.0022 0.0003 0.0060 0.0000 5.4972 0.0128 0.1721 73.8494 6.1216 6.6146 8.6026 78.2636 0.0006 2.9552 16 50779,50799 0 0 5.5027 1,2,3 +lightonocr_3_0_8b 2 yes card 36d8636925327c671bd8e479c517a004f7566bd9 852985920 NVIDIA H100 80GB HBM3 3678 3678 6.1313 10.5883 0.8845 0.0114 5.3166 0.3682 0.0033 0.0005 0.0065 0.0000 6.1260 0.0125 0.1987 77.2308 3.8823 4.0721 8.0104 53.7154 0.0013 6.3925 16 50779,50799 0 0 5.5027 1,2,3 +lightonocr_3_0_8b 3 yes card 36d8636925327c671bd8e479c517a004f7566bd9 852985920 NVIDIA H100 80GB HBM3 3678 3678 6.6171 10.9027 0.8866 0.0117 5.8011 0.3873 0.0014 0.0003 0.0079 0.0000 6.6118 0.0125 0.2197 105.7569 2.2981 2.3636 4.6470 33.5795 0.0020 12.0682 16 50779,50799 0 0 5.5027 1,2,3 +lightonocr_3_1b 1 yes card 23d544085c886bbdace647bcfab91203299417e2 1005647872 NVIDIA H100 80GB HBM3 3678 3678 7.8892 11.9248 0.9748 0.0019 6.9524 0.5926 0.1123 0.1188 0.0601 0.0000 7.8864 0.0022 0.3184 13.2316 6.9719 7.3915 11.1042 141.8738 0.0005 3.3976 16 50780,50800 0 0 3.8715 1,2,3 +lightonocr_3_1b 2 yes card 23d544085c886bbdace647bcfab91203299417e2 1005647872 NVIDIA H100 80GB HBM3 3678 3678 4.9369 7.6376 0.9733 0.0049 3.9826 0.5043 0.0049 0.0122 0.0386 0.0000 4.9347 0.0052 0.1381 52.3638 5.3593 5.6002 10.9327 64.6920 0.0012 3.6582 16 50780,50800 0 0 3.8715 1,2,3 +lightonocr_3_1b 3 yes card 23d544085c886bbdace647bcfab91203299417e2 1005647872 NVIDIA H100 80GB HBM3 3678 3678 3.8715 6.0153 0.9785 0.0054 2.9091 0.5535 0.0054 0.0046 0.0519 0.0000 3.8701 0.0060 0.1006 117.6011 4.3636 4.5199 10.3520 46.2122 0.0020 4.1474 16 50780,50800 0 0 3.8715 1,2,3 +minicpm_ocr_1_0 1 yes card 883ca368d17335b9ce5aa6fef4d000ef0684fcaa 1300434160 NVIDIA H100 80GB HBM3 3678 3678 1.0792 1.1094 0.9665 0.0087 0.1267 0.4324 0.0000 0.0000 0.0150 0.0000 1.0789 0.0092 0.0000 255.2675 5.2258 5.3106 5.1470 23.3772 0.0007 14.6410 16 50781,50801 0 0 1.0761 1,2,3 +minicpm_ocr_1_0 2 yes card 883ca368d17335b9ce5aa6fef4d000ef0684fcaa 1300434160 NVIDIA H100 80GB HBM3 3678 3678 1.0761 1.1065 0.9658 0.0087 0.1241 0.4178 0.0000 0.0000 0.0131 0.0000 1.0757 0.0092 0.0000 258.2303 4.5423 4.5936 4.9869 20.2609 0.0014 20.3590 16 50781,50801 0 0 1.0761 1,2,3 +minicpm_ocr_1_0 3 yes card 883ca368d17335b9ce5aa6fef4d000ef0684fcaa 1300434160 NVIDIA H100 80GB HBM3 3678 3678 1.0776 1.1074 0.9657 0.0087 0.1257 0.4245 0.0000 0.0000 0.0131 0.0000 1.0772 0.0092 0.0000 301.9706 3.1926 3.2181 3.8247 14.2090 0.0026 20.3592 16 50781,50801 0 0 1.0761 1,2,3 +ovisocr2 1 yes nearest documented (page prompt) cbdede82e048659b83310476ff807da825f8fe78 852985920 NVIDIA H100 80GB HBM3 3678 3678 1.0779 1.0876 0.9786 0.0071 0.1032 0.2836 0.0038 0.0000 0.0060 0.0000 1.0770 0.0071 0.0038 212.6718 18.4014 19.4534 48.0192 109.6891 0.0006 3.5022 16 50779,50799 0 0 1.0779 1,2,3 +ovisocr2 2 yes nearest documented (page prompt) cbdede82e048659b83310476ff807da825f8fe78 852985920 NVIDIA H100 80GB HBM3 3678 3678 1.0840 1.0951 0.9793 0.0065 0.1091 0.2941 0.0046 0.0000 0.0063 0.0000 1.0833 0.0068 0.0046 213.4038 15.3536 16.0665 46.2161 91.6371 0.0013 7.2218 16 50779,50799 0 0 1.0779 1,2,3 +ovisocr2 3 yes nearest documented (page prompt) cbdede82e048659b83310476ff807da825f8fe78 852985920 NVIDIA H100 80GB HBM3 3678 3678 1.0843 1.0949 0.9798 0.0063 0.1087 0.2941 0.0049 0.0000 0.0063 0.0000 1.0835 0.0065 0.0046 217.8059 6.9907 7.1324 40.3735 41.0137 0.0020 13.3416 16 50779,50799 0 0 1.0779 1,2,3 +paddleocr_vl_1_6 1 yes card 132c45f52c0a26ed5a6b2f6bd8e3985794cc27dd 905601648 NVIDIA H100 80GB HBM3 3678 3678 1.2003 1.2259 0.9811 0.0076 0.2257 0.5650 0.0005 0.0000 0.0402 0.0000 1.2005 0.0079 0.0003 158.6142 32.1315 34.3730 94.3953 155.1345 0.0014 2.2374 16 50780,50800 0 0 1.2003 1,2,3 +paddleocr_vl_1_6 2 yes card 132c45f52c0a26ed5a6b2f6bd8e3985794cc27dd 905601648 NVIDIA H100 80GB HBM3 3678 3678 1.2193 1.2460 0.9813 0.0073 0.2451 0.5818 0.0014 0.0000 0.0372 0.0000 1.2195 0.0076 0.0005 159.9478 15.0712 15.6913 88.8889 71.7253 0.0012 2.3305 16 50780,50800 0 0 1.2003 1,2,3 +paddleocr_vl_1_6 3 yes card 132c45f52c0a26ed5a6b2f6bd8e3985794cc27dd 905601648 NVIDIA H100 80GB HBM3 3678 3678 1.2248 1.2467 0.9816 0.0073 0.2482 0.5885 0.0016 0.0000 0.0411 0.0000 1.2247 0.0076 0.0014 176.7662 7.6205 7.7506 52.1173 36.1534 0.0020 2.4528 16 50780,50800 0 0 1.2003 1,2,3 +qwen3_vl_2b 1 yes J2 departure (not from the card) 89644892e4d85e24eaac8bacfd4f463576704203 2127532032 NVIDIA H100 80GB HBM3 3678 3678 0.6027 0.6346 0.5880 0.0734 0.1114 0.0619 0.0016 0.0000 0.0054 0.0000 0.5894 0.0816 0.0016 73.8494 28.3111 30.6432 68.9953 156.7720 0.0007 5.6108 16 50781,50801 0 0 0.6027 1,2,3 +qwen3_vl_2b 2 yes J2 departure (not from the card) 89644892e4d85e24eaac8bacfd4f463576704203 2127532032 NVIDIA H100 80GB HBM3 3678 3678 0.6064 0.6409 0.5951 0.0726 0.1123 0.0652 0.0016 0.0000 0.0063 0.0000 0.5920 0.0805 0.0016 77.2308 13.3094 13.8036 67.4821 72.9700 0.0014 10.4457 16 50781,50801 0 0 0.6027 1,2,3 +qwen3_vl_2b 3 yes J2 departure (not from the card) 89644892e4d85e24eaac8bacfd4f463576704203 2127532032 NVIDIA H100 80GB HBM3 3678 3678 0.6194 0.6500 0.6020 0.0696 0.1152 0.0727 0.0019 0.0000 0.0060 0.0000 0.6045 0.0767 0.0019 105.7569 7.4065 7.5396 21.3875 40.7017 0.0020 18.4164 16 50781,50801 0 0 0.6027 1,2,3 diff --git a/environments/venv.requirements b/environments/venv.requirements new file mode 100644 index 0000000000000000000000000000000000000000..01ba1581b4852f4573af0714522a31d71129aba8 --- /dev/null +++ b/environments/venv.requirements @@ -0,0 +1,45 @@ +# environment .venv, Python 3.12.13; package list from 'uv pip freeze' on 2026-11-26 +contourpy==1.4.0 +cuda-bindings==12.9.7 +cuda-pathfinder==1.6.0 +cuda-toolkit==12.8.1 +cycler==0.12.1 +filelock==4.2.4 +fonttools==4.68.0 +fsspec==2026.9.0 +jinja2==3.1.6 +kiwisolver==1.5.1 +markupsafe==3.0.3 +matplotlib==3.11.2 +mpmath==1.3.0 +networkx==3.7 +numpy==2.5.4 +nvidia-cublas-cu12==12.8.4.1 +nvidia-cuda-cupti-cu12==12.8.90 +nvidia-cuda-nvrtc-cu12==12.8.93 +nvidia-cuda-runtime-cu12==12.8.90 +nvidia-cudnn-cu12==9.19.0.56 +nvidia-cufft-cu12==11.3.3.83 +nvidia-cufile-cu12==1.13.1.3 +nvidia-curand-cu12==10.3.9.90 +nvidia-cusolver-cu12==11.7.3.90 +nvidia-cusparse-cu12==12.5.8.93 +nvidia-cusparselt-cu12==0.7.1 +nvidia-nccl-cu12==2.28.9 +nvidia-nvjitlink-cu12==12.8.93 +nvidia-nvshmem-cu12==3.4.5 +nvidia-nvtx-cu12==12.8.90 +opencv-python-headless==5.1.0.95 +packaging==26.3 +pandas==3.1.1 +pillow==13.0.0 +pyarrow==26.0.1 +pyparsing==3.3.3 +python-dateutil==4.0.0 +setuptools==78.1.0 +sympy==1.14.0 +torch==2.11.0+cu128 +torchvision==0.26.0+cu128 +triton==3.6.0 +typing-extensions==4.16.0 +tzdata==2026.6 diff --git a/environments/venv_dl.requirements b/environments/venv_dl.requirements new file mode 100644 index 0000000000000000000000000000000000000000..f2fc51cf54a0395c8da23e35530aae129581504b --- /dev/null +++ b/environments/venv_dl.requirements @@ -0,0 +1,40 @@ +# environment .venv_dl, Python 3.12.13; package list from 'uv pip freeze' on 2026-11-26 +anyio==4.16.0 +backports-zstd==1.8.0 +beautifulsoup4==4.15.0 +brotli==1.2.1 +certifi==2026.10.23 +cffi==2.1.1 +charset-normalizer==3.5.2 +click==8.5.1 +filelock==4.2.12 +fsspec==2026.9.0 +gdown==6.5.1 +h11==0.16.0 +hf-xet==1.8.0 +httpcore2==2.16.2 +httpx2==2.16.2 +huggingface-hub==2.4.0 +idna==3.20 +inflate64==1.0.4 +libarchive-c==5.3 +multivolumefile==0.2.3 +packaging==26.3 +psutil==7.2.2 +py7zr==1.1.4 +pyarrow==26.0.1 +pybcj==1.0.8 +pycparser==3.12 +pycryptodomex==3.24.2 +pyppmd==1.3.1 +pysocks==1.7.1 +pyyaml==6.0.3 +pyzipper==0.4.0 +requests==2.34.2 +soupsieve==4.1.1 +texttable==1.7.3 +tqdm==4.70.1 +truststore==0.10.5 +typing-extensions==4.16.0 +unrar-cffi==0.2.2 +urllib3==2.8.0 diff --git a/environments/venv_gen.requirements b/environments/venv_gen.requirements new file mode 100644 index 0000000000000000000000000000000000000000..4f6704d3615da89bf4e39e3d71dbf7bc9a9e40a8 --- /dev/null +++ b/environments/venv_gen.requirements @@ -0,0 +1,31 @@ +# environment .venv_gen, Python 3.12.13; package list from 'uv pip freeze' on 2026-11-26 +anyio==4.16.0 +click==8.5.1 +contourpy==1.4.0 +cycler==0.12.1 +filelock==4.2.12 +fonttools==4.68.0 +fsspec==2026.9.0 +h11==0.16.0 +hf-xet==1.8.0 +httpcore2==2.16.2 +httpx2==2.16.2 +huggingface-hub==2.4.0 +idna==3.20 +kiwisolver==1.5.1 +matplotlib==3.11.2 +numpy==2.5.5 +opencv-python-headless==5.1.0.95 +packaging==26.3 +pillow==13.0.0 +pyarrow==26.0.1 +pyparsing==3.3.3 +python-dateutil==4.0.0 +pyyaml==6.0.3 +rdkit==2026.9.2 +schemdraw==0.23 +scipy==1.18.1 +tqdm==4.70.1 +truststore==0.10.5 +typing-extensions==4.16.0 +tzdata==2026.6 diff --git a/environments/venv_kraken.requirements b/environments/venv_kraken.requirements new file mode 100644 index 0000000000000000000000000000000000000000..08677b19eef2add4b059443e656d517fd7064c7c --- /dev/null +++ b/environments/venv_kraken.requirements @@ -0,0 +1,110 @@ +# environment .venv_kraken, Python 3.12.13; package list from 'uv pip freeze' on 2026-11-26 +aiohappyeyeballs==2.7.1 +aiohttp==3.14.5 +aiosignal==1.4.0 +anyio==4.16.0 +atpublic==9.0.0 +attrs==26.1.0 +cattrs==26.2.1 +certifi==2026.10.23 +charset-normalizer==3.5.2 +click==8.2.1 +cloudpickle==3.1.3 +contourpy==1.4.0 +coremltools==9.0 +cuda-bindings==12.9.7 +cuda-pathfinder==1.6.0 +cuda-toolkit==12.8.1 +cycler==0.12.1 +filelock==4.2.4 +flufl-lock==10.0.0 +fonttools==4.68.0 +frozenlist==1.8.0 +fsspec==2026.9.0 +h11==0.16.0 +htrmopo==0.6 +httpcore==1.0.9 +httpx==0.28.1 +idna==3.20 +imageio==2.38.2 +iso639-lang==2.6.3 +jinja2==3.1.6 +joblib==1.6.0 +jsonschema==4.26.0 +jsonschema-specifications==2025.9.1 +kenlm==0.3.0 +kiwisolver==1.5.1 +kraken==7.2 +lazy-loader==0.6 +lightning==2.6.6 +lightning-utilities==0.15.3 +lxml==6.1.3 +markdown==3.11.3 +markdown-it-py==4.3.0 +markupsafe==3.0.3 +matplotlib==3.11.2 +mdurl==0.1.2 +mpmath==1.3.0 +multidict==7.2.1 +networkx==3.7 +numpy==2.4.6 +nvidia-cublas-cu12==12.8.4.1 +nvidia-cuda-cupti-cu12==12.8.90 +nvidia-cuda-nvrtc-cu12==12.8.93 +nvidia-cuda-runtime-cu12==12.8.90 +nvidia-cudnn-cu12==9.19.0.56 +nvidia-cufft-cu12==11.3.3.83 +nvidia-cufile-cu12==1.13.1.3 +nvidia-curand-cu12==10.3.9.90 +nvidia-cusolver-cu12==11.7.3.90 +nvidia-cusparse-cu12==12.5.8.93 +nvidia-cusparselt-cu12==0.7.1 +nvidia-ml-py==13.615.71 +nvidia-nccl-cu12==2.28.9 +nvidia-nvjitlink-cu12==12.8.93 +nvidia-nvshmem-cu12==3.4.5 +nvidia-nvtx-cu12==12.8.90 +opencv-python==5.1.0.95 +packaging==26.3 +pillow==13.0.0 +platformdirs==4.14.8 +polars==2.1.0 +polars-runtime-32==2.1.0 +propcache==0.5.4 +protobuf==7.36.2 +psutil==7.2.2 +pyaml==26.7.0 +pyarrow==26.0.1 +pygments==2.21.0 +pyparsing==3.3.3 +python-dateutil==4.0.0 +pytorch-lightning==2.6.6 +pyyaml==6.0.3 +rapidfuzz==3.14.6 +referencing==0.37.0 +regex==2026.11.19 +requests==2.34.2 +rich==14.0.0 +rpds-py==2026.9.1 +safetensors==0.7.0 +scikit-image==0.26.0 +scikit-learn==1.7.2 +scipy==1.16.3 +setuptools==78.1.0 +shapely==2.1.2 +sickle==0.7.0 +sympy==1.14.0 +threadpoolctl==3.6.0 +tifffile==2026.11.16 +torch==2.11.0+cu128 +torchmetrics==1.9.0 +torchvision==0.26.0+cu128 +tqdm==4.70.1 +triton==3.6.0 +typing-extensions==4.16.0 +tzdata==2026.6 +ultralytics==8.4.216 +ultralytics-platform==0.1.119 +ultralytics-thop==2.2.5 +urllib3==2.8.0 +yarl==1.25.1 diff --git a/environments/venv_print.requirements b/environments/venv_print.requirements new file mode 100644 index 0000000000000000000000000000000000000000..7cb67d785af21f0e4ea87509ad71d5093d55bcfd --- /dev/null +++ b/environments/venv_print.requirements @@ -0,0 +1,32 @@ +# environment .venv_print, Python 3.12.13; package list from 'uv pip freeze' on 2026-11-26 +anyio==4.16.0 +certifi==2026.10.23 +charset-normalizer==3.5.2 +click==8.5.1 +filelock==4.2.12 +flatbuffers==25.12.19 +fsspec==2026.9.0 +h11==0.16.0 +hf-xet==1.8.0 +httpcore2==2.16.2 +httpx2==2.16.2 +huggingface-hub==2.4.0 +idna==3.20 +networkx==3.7 +numpy==2.5.5 +onnxruntime==1.32.0 +packaging==26.3 +pillow==13.0.0 +protobuf==7.36.2 +psutil==7.2.2 +pyarrow==26.0.1 +pymupdf==2.1 +pymupdf-layout==2.1 +pymupdf4llm==2.1 +pyyaml==6.0.3 +requests==2.34.2 +tabulate==0.10.0 +tqdm==4.70.1 +truststore==0.10.5 +typing-extensions==4.16.0 +urllib3==2.8.0 diff --git a/environments/venv_ref_paddle.requirements b/environments/venv_ref_paddle.requirements new file mode 100644 index 0000000000000000000000000000000000000000..6bb899b7ef06ed91bc22dd590007c15d9efc935d --- /dev/null +++ b/environments/venv_ref_paddle.requirements @@ -0,0 +1,57 @@ +# environment .venv_ref_paddle, Python 3.11.15; package list from 'uv pip freeze' on 2026-11-26 +albucore==0.0.24 +albumentations==2.0.8 +annotated-types==0.8.0 +anyio==4.16.0 +astor==0.8.1 +certifi==2026.11.20 +charset-normalizer==3.5.2 +cython==3.3.1 +decorator==5.3.1 +editdistance==0.8.1 +h11==0.16.0 +httpcore==1.0.9 +httpx==0.28.1 +idna==3.20 +imageio==2.38.2 +lazy-loader==0.6 +lmdb==3.0.0 +networkx==3.6.1 +numpy==1.26.4 +nvidia-cublas-cu12==12.6.4.1 +nvidia-cuda-cupti-cu12==12.6.80 +nvidia-cuda-nvrtc-cu12==12.6.77 +nvidia-cuda-runtime-cu12==12.6.77 +nvidia-cudnn-cu12==9.5.1.17 +nvidia-cufft-cu12==11.3.0.4 +nvidia-cufile-cu12==1.11.1.6 +nvidia-curand-cu12==10.3.7.77 +nvidia-cusolver-cu12==11.7.1.2 +nvidia-cusparse-cu12==12.5.4.2 +nvidia-cusparselt-cu12==0.6.3 +nvidia-nccl-cu12==2.25.1 +nvidia-nvjitlink-cu12==12.6.85 +nvidia-nvtx-cu12==12.6.77 +opencv-python-headless==4.11.0.86 +opt-einsum==3.3.0 +packaging==26.3 +paddlepaddle-gpu==3.0.0 +pillow==13.0.0 +protobuf==7.36.2 +pyclipper==1.4.0 +pydantic==2.14.4 +pydantic-core==2.50.5 +pyyaml==6.0.4 +rapidfuzz==3.14.6 +requests==2.34.2 +scikit-image==0.26.0 +scipy==1.17.1 +setuptools==84.2.1 +shapely==2.2.0 +simsimd==6.5.16 +stringzilla==5.3.2 +tifffile==2026.3.3 +tqdm==4.70.1 +typing-extensions==4.16.0 +typing-inspection==0.4.5 +urllib3==2.8.0 diff --git a/environments/venv_ref_paddle_cpu.requirements b/environments/venv_ref_paddle_cpu.requirements new file mode 100644 index 0000000000000000000000000000000000000000..efc7b8fa4510d6700bc8ebb8ab18b8ca55c179c9 --- /dev/null +++ b/environments/venv_ref_paddle_cpu.requirements @@ -0,0 +1,43 @@ +# environment .venv_ref_paddle_cpu, Python 3.11.15; package list from 'uv pip freeze' on 2026-11-26 +albucore==0.0.24 +albumentations==2.0.8 +annotated-types==0.8.0 +anyio==4.16.0 +astor==0.8.1 +certifi==2026.11.20 +charset-normalizer==3.5.2 +cython==3.3.1 +decorator==5.3.1 +editdistance==0.8.1 +h11==0.16.0 +httpcore==1.0.9 +httpx==0.28.1 +idna==3.20 +imageio==2.38.2 +lazy-loader==0.6 +lmdb==3.0.0 +networkx==3.6.1 +numpy==1.26.4 +opencv-python-headless==4.11.0.86 +opt-einsum==3.3.0 +packaging==26.3 +paddlepaddle==3.0.0 +pillow==13.0.0 +protobuf==7.36.2 +pyclipper==1.4.0 +pydantic==2.14.4 +pydantic-core==2.50.5 +pyyaml==6.0.4 +rapidfuzz==3.14.6 +requests==2.34.2 +scikit-image==0.26.0 +scipy==1.17.1 +setuptools==84.2.1 +shapely==2.2.0 +simsimd==6.5.16 +stringzilla==5.3.2 +tifffile==2026.3.3 +tqdm==4.70.1 +typing-extensions==4.16.0 +typing-inspection==0.4.5 +urllib3==2.8.0 diff --git a/environments/venv_ref_tf.requirements b/environments/venv_ref_tf.requirements new file mode 100644 index 0000000000000000000000000000000000000000..4e6b990437a404104c35915e0958cd83be54b744 --- /dev/null +++ b/environments/venv_ref_tf.requirements @@ -0,0 +1,58 @@ +# environment .venv_ref_tf, Python 3.11.15; package list from 'uv pip freeze' on 2026-11-26 +absl-py==2.5.1 +astunparse==1.6.3 +certifi==2026.11.20 +cffi==2.1.1 +charset-normalizer==3.5.2 +cryptography==50.0.2 +editdistance==0.8.1 +flatbuffers==25.12.19 +gast==0.7.0 +google-auth==2.63.0 +google-auth-oauthlib==1.5.0 +google-pasta==0.2.0 +grpcio==1.85.3 +h5py==3.16.0 +idna==3.20 +keras==2.15.0 +libclang==18.1.1 +markdown==3.11.3 +markupsafe==3.0.4 +ml-dtypes==0.3.2 +numpy==1.26.4 +nvidia-cublas-cu12==12.2.5.6 +nvidia-cuda-cupti-cu12==12.2.142 +nvidia-cuda-nvcc-cu12==12.2.140 +nvidia-cuda-nvrtc-cu12==12.2.140 +nvidia-cuda-runtime-cu12==12.2.140 +nvidia-cudnn-cu12==8.9.4.25 +nvidia-cufft-cu12==11.0.8.103 +nvidia-curand-cu12==10.3.3.141 +nvidia-cusolver-cu12==11.5.2.141 +nvidia-cusparse-cu12==12.1.2.141 +nvidia-nccl-cu12==2.16.5 +nvidia-nvjitlink-cu12==12.2.140 +oauthlib==4.0.1 +opencv-python-headless==4.11.0.86 +opt-einsum==3.4.0 +packaging==26.3 +protobuf==4.25.9 +pyasn1==0.6.5 +pyasn1-modules==0.4.2 +pycparser==3.12 +requests==2.34.2 +requests-oauthlib==2.0.0 +setuptools==84.2.1 +six==1.17.0 +tensorboard==2.15.2 +tensorboard-data-server==0.7.2 +tensorflow==2.15.1 +tensorflow-estimator==2.15.0 +tensorflow-io-gcs-filesystem==0.37.1 +termcolor==3.3.0 +tqdm==4.70.1 +typing-extensions==4.16.0 +urllib3==2.8.0 +werkzeug==3.1.9 +wheel==0.48.0 +wrapt==1.14.2 diff --git a/environments/venv_vlm.requirements b/environments/venv_vlm.requirements new file mode 100644 index 0000000000000000000000000000000000000000..074521716e9a5b0494a95c028e70bc81471b3b77 --- /dev/null +++ b/environments/venv_vlm.requirements @@ -0,0 +1,64 @@ +# environment .venv_vlm, Python 3.12.13; package list from 'uv pip freeze' on 2026-11-26 +accelerate==1.16.0 +annotated-doc==0.0.7 +annotated-types==0.8.0 +anyio==4.16.0 +click==8.5.1 +cuda-bindings==12.9.7 +cuda-pathfinder==1.6.0 +cuda-toolkit==12.8.1 +filelock==4.2.4 +fsspec==2026.9.0 +h11==0.16.0 +hf-xet==1.8.0 +httpcore2==2.16.2 +httpx2==2.16.2 +huggingface-hub==2.4.0 +idna==3.20 +jinja2==3.1.6 +markdown-it-py==4.3.0 +markupsafe==3.0.3 +mdurl==0.1.2 +mpmath==1.3.0 +networkx==3.7 +numpy==2.5.4 +nvidia-cublas-cu12==12.8.4.1 +nvidia-cuda-cupti-cu12==12.8.90 +nvidia-cuda-nvrtc-cu12==12.8.93 +nvidia-cuda-runtime-cu12==12.8.90 +nvidia-cudnn-cu12==9.19.0.56 +nvidia-cufft-cu12==11.3.3.83 +nvidia-cufile-cu12==1.13.1.3 +nvidia-curand-cu12==10.3.9.90 +nvidia-cusolver-cu12==11.7.3.90 +nvidia-cusparse-cu12==12.5.8.93 +nvidia-cusparselt-cu12==0.7.1 +nvidia-nccl-cu12==2.28.9 +nvidia-nvjitlink-cu12==12.8.93 +nvidia-nvshmem-cu12==3.4.5 +nvidia-nvtx-cu12==12.8.90 +packaging==26.3 +pillow==13.0.0 +protobuf==7.36.2 +psutil==7.2.2 +pydantic==2.14.4 +pydantic-core==2.50.5 +pygments==2.21.0 +pyyaml==6.0.3 +regex==2026.11.19 +rich==15.0.0 +safetensors==0.8.0 +sentencepiece==0.2.3 +setuptools==78.1.0 +shellingham==1.5.4 +sympy==1.14.0 +tokenizers==0.23.3 +torch==2.11.0+cu128 +torchvision==0.26.0+cu128 +tqdm==4.70.1 +transformers==5.23.0 +triton==3.6.0 +truststore==0.10.5 +typer==0.29.2 +typing-extensions==4.16.0 +typing-inspection==0.4.5 diff --git a/environments/venv_vlm_deepseek_ocr_2.requirements b/environments/venv_vlm_deepseek_ocr_2.requirements new file mode 100644 index 0000000000000000000000000000000000000000..8318b9264d96057232811062d6283b5865d94b8c --- /dev/null +++ b/environments/venv_vlm_deepseek_ocr_2.requirements @@ -0,0 +1,46 @@ +# environment .venv_vlm_deepseek_ocr_2, Python 3.12.13; package list from 'uv pip freeze' on 2026-11-26 +accelerate==1.2.1 +addict==2.4.0 +certifi==2026.10.23 +charset-normalizer==3.5.2 +easydict==1.13 +einops==0.8.0 +filelock==4.2.4 +fsspec==2026.9.0 +huggingface-hub==0.26.5 +idna==3.20 +jinja2==3.1.6 +markupsafe==3.0.3 +mpmath==1.3.0 +networkx==3.7 +numpy==1.26.4 +nvidia-cublas-cu12==12.4.5.8 +nvidia-cuda-cupti-cu12==12.4.127 +nvidia-cuda-nvrtc-cu12==12.4.127 +nvidia-cuda-runtime-cu12==12.4.127 +nvidia-cudnn-cu12==9.1.0.70 +nvidia-cufft-cu12==11.2.1.3 +nvidia-curand-cu12==10.3.5.147 +nvidia-cusolver-cu12==11.6.1.9 +nvidia-cusparse-cu12==12.3.1.170 +nvidia-cusparselt-cu12==0.6.2 +nvidia-nccl-cu12==2.21.5 +nvidia-nvjitlink-cu12==12.4.127 +nvidia-nvtx-cu12==12.4.127 +packaging==26.3 +pillow==11.0.0 +psutil==7.2.2 +pyyaml==6.0.3 +regex==2026.11.19 +requests==2.34.2 +safetensors==0.4.5 +setuptools==78.1.0 +sympy==1.13.1 +tokenizers==0.20.3 +torch==2.6.0+cu124 +torchvision==0.21.0+cu124 +tqdm==4.70.1 +transformers==4.46.3 +triton==3.2.0 +typing-extensions==4.16.0 +urllib3==2.8.0 diff --git a/environments/venv_vlm_dots_mocr.requirements b/environments/venv_vlm_dots_mocr.requirements new file mode 100644 index 0000000000000000000000000000000000000000..75302d31cf1e0d2b58fb88eabb8342e647e6ed5c --- /dev/null +++ b/environments/venv_vlm_dots_mocr.requirements @@ -0,0 +1,64 @@ +# environment .venv_vlm_dots_mocr, Python 3.12.13; package list from 'uv pip freeze' on 2026-11-26 +accelerate==1.16.0 +annotated-doc==0.0.7 +annotated-types==0.8.0 +anyio==4.16.0 +click==8.5.1 +cuda-bindings==12.9.7 +cuda-pathfinder==1.6.0 +cuda-toolkit==12.8.1 +filelock==4.2.4 +fsspec==2026.9.0 +h11==0.16.0 +hf-xet==1.8.0 +httpcore2==2.16.2 +httpx2==2.16.2 +huggingface-hub==2.4.0 +idna==3.20 +jinja2==3.1.6 +markdown-it-py==4.3.0 +markupsafe==3.0.3 +mdurl==0.1.2 +mpmath==1.3.0 +networkx==3.7 +numpy==2.5.4 +nvidia-cublas-cu12==12.8.4.1 +nvidia-cuda-cupti-cu12==12.8.90 +nvidia-cuda-nvrtc-cu12==12.8.93 +nvidia-cuda-runtime-cu12==12.8.90 +nvidia-cudnn-cu12==9.19.0.56 +nvidia-cufft-cu12==11.3.3.83 +nvidia-cufile-cu12==1.13.1.3 +nvidia-curand-cu12==10.3.9.90 +nvidia-cusolver-cu12==11.7.3.90 +nvidia-cusparse-cu12==12.5.8.93 +nvidia-cusparselt-cu12==0.7.1 +nvidia-nccl-cu12==2.28.9 +nvidia-nvjitlink-cu12==12.8.93 +nvidia-nvshmem-cu12==3.4.5 +nvidia-nvtx-cu12==12.8.90 +packaging==26.3 +pillow==13.0.0 +protobuf==7.36.2 +psutil==7.2.2 +pydantic==2.14.4 +pydantic-core==2.50.5 +pygments==2.21.0 +pyyaml==6.0.3 +regex==2026.11.19 +rich==15.0.0 +safetensors==0.8.0 +sentencepiece==0.2.3 +setuptools==78.1.0 +shellingham==1.5.4 +sympy==1.14.0 +tokenizers==0.23.3 +torch==2.11.0+cu128 +torchvision==0.26.0+cu128 +tqdm==4.70.1 +transformers==5.23.0 +triton==3.6.0 +truststore==0.10.5 +typer==0.29.2 +typing-extensions==4.16.0 +typing-inspection==0.4.5 diff --git a/environments/venv_vlm_falcon_ocr.requirements b/environments/venv_vlm_falcon_ocr.requirements new file mode 100644 index 0000000000000000000000000000000000000000..5c1b4b213e3632d36aa3b5743178862a08a2a135 --- /dev/null +++ b/environments/venv_vlm_falcon_ocr.requirements @@ -0,0 +1,69 @@ +# environment .venv_vlm_falcon_ocr, Python 3.12.13; package list from 'uv pip freeze' on 2026-11-26 +accelerate==1.16.0 +annotated-doc==0.0.7 +annotated-types==0.8.0 +anyio==4.16.0 +certifi==2026.10.23 +charset-normalizer==3.5.2 +click==8.5.1 +cuda-bindings==12.9.7 +cuda-pathfinder==1.6.0 +cuda-toolkit==12.8.1 +einops==0.8.2 +filelock==4.2.4 +fsspec==2026.9.0 +h11==0.16.0 +hf-xet==1.8.0 +httpcore2==2.16.2 +httpx2==2.16.2 +huggingface-hub==2.4.0 +idna==3.20 +jinja2==3.1.6 +markdown-it-py==4.3.0 +markupsafe==3.0.3 +mdurl==0.1.2 +mpmath==1.3.0 +networkx==3.7 +numpy==2.5.4 +nvidia-cublas-cu12==12.8.4.1 +nvidia-cuda-cupti-cu12==12.8.90 +nvidia-cuda-nvrtc-cu12==12.8.93 +nvidia-cuda-runtime-cu12==12.8.90 +nvidia-cudnn-cu12==9.19.0.56 +nvidia-cufft-cu12==11.3.3.83 +nvidia-cufile-cu12==1.13.1.3 +nvidia-curand-cu12==10.3.9.90 +nvidia-cusolver-cu12==11.7.3.90 +nvidia-cusparse-cu12==12.5.8.93 +nvidia-cusparselt-cu12==0.7.1 +nvidia-nccl-cu12==2.28.9 +nvidia-nvjitlink-cu12==12.8.93 +nvidia-nvshmem-cu12==3.4.5 +nvidia-nvtx-cu12==12.8.90 +packaging==26.3 +pillow==13.0.0 +protobuf==7.36.2 +psutil==7.2.2 +pydantic==2.14.4 +pydantic-core==2.50.5 +pygments==2.21.0 +pyyaml==6.0.3 +regex==2026.11.19 +requests==2.34.2 +rich==15.0.0 +safetensors==0.8.0 +sentencepiece==0.2.3 +setuptools==78.1.0 +shellingham==1.5.4 +sympy==1.14.0 +tokenizers==0.23.3 +torch==2.11.0+cu128 +torchvision==0.26.0+cu128 +tqdm==4.70.1 +transformers==5.23.0 +triton==3.6.0 +truststore==0.10.5 +typer==0.29.2 +typing-extensions==4.16.0 +typing-inspection==0.4.5 +urllib3==2.8.0 diff --git a/environments/venv_vlm_jina_ocr_v1.requirements b/environments/venv_vlm_jina_ocr_v1.requirements new file mode 100644 index 0000000000000000000000000000000000000000..c7614307cf7f3e9c580ac29ca8f616d82c175bef --- /dev/null +++ b/environments/venv_vlm_jina_ocr_v1.requirements @@ -0,0 +1,46 @@ +# environment .venv_vlm_jina_ocr_v1, Python 3.12.13; package list from 'uv pip freeze' on 2026-11-26 +accelerate==1.16.0 +certifi==2026.11.20 +charset-normalizer==3.5.2 +einops==0.8.2 +filelock==4.2.4 +fsspec==2026.9.0 +hf-xet==1.8.0 +huggingface-hub==0.36.2 +idna==3.20 +jinja2==3.1.6 +markupsafe==3.0.3 +mpmath==1.3.0 +networkx==3.7 +numpy==2.5.4 +nvidia-cublas-cu12==12.8.4.1 +nvidia-cuda-cupti-cu12==12.8.90 +nvidia-cuda-nvrtc-cu12==12.8.93 +nvidia-cuda-runtime-cu12==12.8.90 +nvidia-cudnn-cu12==9.10.2.21 +nvidia-cufft-cu12==11.3.3.83 +nvidia-cufile-cu12==1.13.1.3 +nvidia-curand-cu12==10.3.9.90 +nvidia-cusolver-cu12==11.7.3.90 +nvidia-cusparse-cu12==12.5.8.93 +nvidia-cusparselt-cu12==0.7.1 +nvidia-nccl-cu12==2.27.3 +nvidia-nvjitlink-cu12==12.8.93 +nvidia-nvtx-cu12==12.8.90 +packaging==26.3 +pillow==13.0.0 +psutil==7.2.2 +pyyaml==6.0.4 +regex==2026.11.19 +requests==2.34.2 +safetensors==0.8.0 +setuptools==78.1.0 +sympy==1.14.0 +tokenizers==0.22.2 +torch==2.8.0+cu128 +torchvision==0.23.0+cu128 +tqdm==4.70.1 +transformers==4.57.3 +triton==3.4.0 +typing-extensions==4.16.0 +urllib3==2.8.0 diff --git a/environments/venv_vlm_nemotron_3_5_parse.requirements b/environments/venv_vlm_nemotron_3_5_parse.requirements new file mode 100644 index 0000000000000000000000000000000000000000..d7257e9ec4e4564195c256d529bb844274d9f6cc --- /dev/null +++ b/environments/venv_vlm_nemotron_3_5_parse.requirements @@ -0,0 +1,64 @@ +# environment .venv_vlm_nemotron_3_5_parse, Python 3.12.13; package list from 'uv pip freeze' on 2026-11-26 +accelerate==1.12.0 +annotated-doc==0.0.7 +annotated-types==0.8.0 +anyio==4.16.0 +certifi==2026.11.20 +click==8.5.1 +cuda-bindings==12.9.7 +cuda-pathfinder==1.6.0 +cuda-toolkit==12.8.1 +einops==0.8.1 +filelock==4.2.4 +fsspec==2026.9.0 +h11==0.16.0 +hf-xet==1.8.0 +httpcore==1.0.9 +httpx==0.28.1 +huggingface-hub==1.24.0 +idna==3.20 +jinja2==3.1.6 +markdown-it-py==4.3.0 +markupsafe==3.0.3 +mdurl==0.1.2 +mpmath==1.3.0 +networkx==3.7 +numpy==2.2.6 +nvidia-cublas-cu12==12.8.4.1 +nvidia-cuda-cupti-cu12==12.8.90 +nvidia-cuda-nvrtc-cu12==12.8.93 +nvidia-cuda-runtime-cu12==12.8.90 +nvidia-cudnn-cu12==9.19.0.56 +nvidia-cufft-cu12==11.3.3.83 +nvidia-cufile-cu12==1.13.1.3 +nvidia-curand-cu12==10.3.9.90 +nvidia-cusolver-cu12==11.7.3.90 +nvidia-cusparse-cu12==12.5.8.93 +nvidia-cusparselt-cu12==0.7.1 +nvidia-nccl-cu12==2.28.9 +nvidia-nvjitlink-cu12==12.8.93 +nvidia-nvshmem-cu12==3.4.5 +nvidia-nvtx-cu12==12.8.90 +packaging==26.3 +pillow==12.2.0 +psutil==7.2.2 +pydantic==2.14.4 +pydantic-core==2.50.5 +pygments==2.21.0 +pyyaml==6.0.4 +regex==2026.11.19 +rich==15.0.0 +safetensors==0.8.0 +setuptools==78.1.0 +shellingham==1.5.4 +sympy==1.14.0 +timm==1.0.22 +tokenizers==0.22.2 +torch==2.11.0+cu128 +torchvision==0.26.0+cu128 +tqdm==4.70.1 +transformers==5.14.1 +triton==3.6.0 +typer==0.29.2 +typing-extensions==4.16.0 +typing-inspection==0.4.5 diff --git a/environments/venv_vlm_oxr_1_0.requirements b/environments/venv_vlm_oxr_1_0.requirements new file mode 100644 index 0000000000000000000000000000000000000000..1a84d4de9220dd941c4b6d660bb5fb7ba6f830af --- /dev/null +++ b/environments/venv_vlm_oxr_1_0.requirements @@ -0,0 +1,64 @@ +# environment .venv_vlm_oxr_1_0, Python 3.12.13; package list from 'uv pip freeze' on 2026-11-26 +accelerate==1.16.0 +annotated-doc==0.0.7 +annotated-types==0.8.0 +anyio==4.16.0 +click==8.5.1 +cuda-bindings==12.9.7 +cuda-pathfinder==1.6.0 +cuda-toolkit==12.8.1 +filelock==4.2.4 +fsspec==2026.9.0 +h11==0.16.0 +hf-xet==1.8.0 +httpcore2==2.16.2 +httpx2==2.16.2 +huggingface-hub==2.4.0 +idna==3.20 +jinja2==3.1.6 +markdown-it-py==4.3.0 +markupsafe==3.0.3 +mdurl==0.1.2 +mpmath==1.3.0 +networkx==3.7 +numpy==2.5.4 +nvidia-cublas-cu12==12.8.4.1 +nvidia-cuda-cupti-cu12==12.8.90 +nvidia-cuda-nvrtc-cu12==12.8.93 +nvidia-cuda-runtime-cu12==12.8.90 +nvidia-cudnn-cu12==9.19.0.56 +nvidia-cufft-cu12==11.3.3.83 +nvidia-cufile-cu12==1.13.1.3 +nvidia-curand-cu12==10.3.9.90 +nvidia-cusolver-cu12==11.7.3.90 +nvidia-cusparse-cu12==12.5.8.93 +nvidia-cusparselt-cu12==0.7.1 +nvidia-nccl-cu12==2.28.9 +nvidia-nvjitlink-cu12==12.8.93 +nvidia-nvshmem-cu12==3.4.5 +nvidia-nvtx-cu12==12.8.90 +packaging==26.3 +pillow==13.0.0 +protobuf==7.36.2 +psutil==7.2.2 +pydantic==2.14.4 +pydantic-core==2.50.5 +pygments==2.21.0 +pyyaml==6.0.3 +regex==2026.11.19 +rich==15.0.0 +safetensors==0.8.0 +sentencepiece==0.2.3 +setuptools==78.1.0 +shellingham==1.5.4 +sympy==1.14.0 +tokenizers==0.23.3 +torch==2.11.0+cu128 +torchvision==0.26.0+cu128 +tqdm==4.70.1 +transformers==5.23.0 +triton==3.6.0 +truststore==0.10.5 +typer==0.29.2 +typing-extensions==4.16.0 +typing-inspection==0.4.5 diff --git a/environments/venv_vlm_teleocr.requirements b/environments/venv_vlm_teleocr.requirements new file mode 100644 index 0000000000000000000000000000000000000000..fcf3ab9c03931901215eeed41d92134b8b39161a --- /dev/null +++ b/environments/venv_vlm_teleocr.requirements @@ -0,0 +1,45 @@ +# environment .venv_vlm_teleocr, Python 3.12.13; package list from 'uv pip freeze' on 2026-11-26 +accelerate==1.16.0 +certifi==2026.10.23 +charset-normalizer==3.5.2 +filelock==4.2.4 +fsspec==2026.9.0 +hf-xet==1.8.0 +huggingface-hub==0.36.2 +idna==3.20 +jinja2==3.1.6 +markupsafe==3.0.3 +mpmath==1.3.0 +networkx==3.7 +numpy==2.5.4 +nvidia-cublas-cu12==12.8.4.1 +nvidia-cuda-cupti-cu12==12.8.90 +nvidia-cuda-nvrtc-cu12==12.8.93 +nvidia-cuda-runtime-cu12==12.8.90 +nvidia-cudnn-cu12==9.10.2.21 +nvidia-cufft-cu12==11.3.3.83 +nvidia-cufile-cu12==1.13.1.3 +nvidia-curand-cu12==10.3.9.90 +nvidia-cusolver-cu12==11.7.3.90 +nvidia-cusparse-cu12==12.5.8.93 +nvidia-cusparselt-cu12==0.7.1 +nvidia-nccl-cu12==2.27.3 +nvidia-nvjitlink-cu12==12.8.93 +nvidia-nvtx-cu12==12.8.90 +packaging==26.3 +pillow==13.0.0 +psutil==7.2.2 +pyyaml==6.0.3 +regex==2026.11.19 +requests==2.34.2 +safetensors==0.8.0 +setuptools==78.1.0 +sympy==1.14.0 +tokenizers==0.22.2 +torch==2.8.0+cu128 +torchvision==0.23.0+cu128 +tqdm==4.70.1 +transformers==4.57.1 +triton==3.4.0 +typing-extensions==4.16.0 +urllib3==2.8.0 diff --git a/environments/venv_vlm_unlimited_ocr_2.requirements b/environments/venv_vlm_unlimited_ocr_2.requirements new file mode 100644 index 0000000000000000000000000000000000000000..988818f5fd7f649d993291bde3065380506c5525 --- /dev/null +++ b/environments/venv_vlm_unlimited_ocr_2.requirements @@ -0,0 +1,52 @@ +# environment .venv_vlm_unlimited_ocr_2, Python 3.10.20; package list from 'uv pip freeze' on 2026-11-26 +accelerate==1.15.0 +addict==2.4.0 +certifi==2026.11.20 +charset-normalizer==3.5.2 +cuda-bindings==13.4.4 +cuda-pathfinder==1.8.3 +cuda-toolkit==13.0.3.0 +easydict==1.13 +einops==0.8.2 +filelock==4.1.0 +fsspec==2026.9.0 +hf-xet==1.8.0 +huggingface-hub==0.36.0 +idna==3.20 +jinja2==3.1.6 +markupsafe==3.0.3 +mpmath==1.3.0 +networkx==3.4.2 +numpy==2.2.6 +nvidia-cublas==13.1.1.3 +nvidia-cuda-cupti==13.0.85 +nvidia-cuda-nvrtc==13.0.88 +nvidia-cuda-runtime==13.0.96 +nvidia-cudnn-cu13==9.20.0.48 +nvidia-cufft==12.0.0.61 +nvidia-cufile==1.15.1.6 +nvidia-curand==10.4.0.35 +nvidia-cusolver==12.0.4.66 +nvidia-cusparse==12.6.3.3 +nvidia-cusparselt-cu13==0.8.1 +nvidia-nccl-cu13==2.29.7 +nvidia-nvjitlink==13.4.92 +nvidia-nvshmem-cu13==3.4.5 +nvidia-nvtx==13.0.85 +packaging==26.3 +pillow==12.3.0 +psutil==7.2.2 +pyyaml==6.0.4 +regex==2026.9.29 +requests==2.34.2 +safetensors==0.8.0 +setuptools==78.1.0 +sympy==1.14.0 +tokenizers==0.21.4 +torch==2.13.0+cu130 +torchvision==0.28.0+cu130 +tqdm==4.70.1 +transformers==4.52.1 +triton==3.7.1 +typing-extensions==4.16.0 +urllib3==2.8.0 diff --git a/environments/venv_vlm_youtu_parsing.requirements b/environments/venv_vlm_youtu_parsing.requirements new file mode 100644 index 0000000000000000000000000000000000000000..f141f18452aead5ee4ba0c37203e5183d97c87e9 --- /dev/null +++ b/environments/venv_vlm_youtu_parsing.requirements @@ -0,0 +1,46 @@ +# environment .venv_vlm_youtu_parsing, Python 3.12.13; package list from 'uv pip freeze' on 2026-11-26 +accelerate==1.16.0 +certifi==2026.11.20 +charset-normalizer==3.5.2 +einops==0.8.2 +filelock==4.2.4 +fsspec==2026.9.0 +hf-xet==1.8.0 +huggingface-hub==0.36.2 +idna==3.20 +jinja2==3.1.6 +markupsafe==3.0.3 +mpmath==1.3.0 +networkx==3.7 +numpy==2.5.4 +nvidia-cublas-cu12==12.8.4.1 +nvidia-cuda-cupti-cu12==12.8.90 +nvidia-cuda-nvrtc-cu12==12.8.93 +nvidia-cuda-runtime-cu12==12.8.90 +nvidia-cudnn-cu12==9.10.2.21 +nvidia-cufft-cu12==11.3.3.83 +nvidia-cufile-cu12==1.13.1.3 +nvidia-curand-cu12==10.3.9.90 +nvidia-cusolver-cu12==11.7.3.90 +nvidia-cusparse-cu12==12.5.8.93 +nvidia-cusparselt-cu12==0.7.1 +nvidia-nccl-cu12==2.27.3 +nvidia-nvjitlink-cu12==12.8.93 +nvidia-nvtx-cu12==12.8.90 +packaging==26.3 +pillow==13.0.0 +psutil==7.2.2 +pyyaml==6.0.4 +regex==2026.11.19 +requests==2.34.2 +safetensors==0.8.0 +setuptools==78.1.0 +sympy==1.14.0 +tokenizers==0.22.2 +torch==2.8.0+cu128 +torchvision==0.23.0+cu128 +tqdm==4.70.1 +transformers==4.56.0 +triton==3.4.0 +typing-extensions==4.16.0 +urllib3==2.8.0 diff --git a/release/page-pipeline/infer.py b/release/page-pipeline/infer.py new file mode 100644 index 0000000000000000000000000000000000000000..578169120fba713df52a39a3462e3cdb1052775f --- /dev/null +++ b/release/page-pipeline/infer.py @@ -0,0 +1,190 @@ +#!/usr/bin/env python +"""Read whole pages: find the text lines, cut a crop for every line, read every crop (Turkic OCR, release candidate 1). + +Stage 1 runs the detector package (turkic-line-detector-yolo11s) on the page image as a subprocess, because it needs ultralytics, which +the reader's environment does not contain: pass --detector-python with a Python that has ultralytics (the default is this Python). +Stage 2 cuts one crop per box and reads every crop with the reader package (turkic-ocr-paddleocr-vl-1.6, final model of this release, +greedy, bfloat16, at most 192 new tokens per line, batches of 16 crops in reading order), in this process. + +Crop and reading-order logic are those of our evaluation (CODE/src/linedet/det_eval.py and the page check detb1_page_check.py): + - reading order: boxes sorted by (centre_y // band, centre_x) in the detection image, band = 15 px in a page whose longer side is + 1280 px (the band grows in proportion for a larger or smaller page); + - crop: the box widened by 1 % of its width plus 2 px on each side and heightened by 10 % of its height plus 1 px above and below, + clipped to the image; a crop narrower or lower than 4 px is dropped; + - text: the reader's normalised output; a crop whose text is empty is kept in the lines table and left out of the page text. +For a photograph that is much larger than the page the detector sees (our School Notebooks pages: detection on 1280 px, reading from the +full-resolution photograph) give the reading images with --hires-tsv. + +Outputs: --out, a TSV with one row per page: id, n_lines, text (the lines in reading order joined by one space); + --lines-out, a TSV with one row per crop: id, line, x0, y0, x1, y1, score, text (boxes in detection-image pixels). + +usage: + python infer.py --images page.jpg --out pages.tsv --lines-out lines.tsv + python infer.py --manifest pages.tsv --out pages.tsv --lines-out lines.tsv --detector-python /path/to/venv-with-ultralytics/bin/python +""" +import os + +os.environ.setdefault("HF_HUB_OFFLINE", "1") +os.environ.setdefault("TRANSFORMERS_OFFLINE", "1") + +import argparse # noqa: E402 +import csv # noqa: E402 +import importlib.util # noqa: E402 +import json # noqa: E402 +import subprocess # noqa: E402 +import sys # noqa: E402 +import tempfile # noqa: E402 +import time # noqa: E402 + +from PIL import Image # noqa: E402 + +HERE = os.path.dirname(os.path.abspath(__file__)) +IMG_EXT = (".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff", ".webp") + + +def collect_inputs(images=None, manifest=None): + """List of (id, path). A manifest is a TSV with a header and the columns id and image (other columns are ignored).""" + if manifest: + rows = [] + with open(manifest, encoding="utf-8", newline="") as f: + for r in csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE): + rows.append((r["id"], r["image"])) + return rows + if os.path.isdir(images): + names = sorted(n for n in os.listdir(images) if n.lower().endswith(IMG_EXT)) + return [(n, os.path.join(images, n)) for n in names] + return [(os.path.basename(images), images)] + + +def load_module(name, path): + spec = importlib.util.spec_from_file_location(name, path) + mod = importlib.util.module_from_spec(spec) + sys.modules[name] = mod + spec.loader.exec_module(mod) + return mod + + +def reading_order(boxes, band): + return sorted(range(len(boxes)), key=lambda i: (int(((boxes[i][1] + boxes[i][3]) / 2) // band), (boxes[i][0] + boxes[i][2]) / 2)) + + +def make_crop(big, box, sc): + """The crop of one box, or None. sc: pixels of the reading image per pixel of the detection image.""" + W, H = big.size + x0, y0, x1, y1 = box + hh = y1 - y0 + x0, x1 = x0 - 0.01 * (x1 - x0) - 2, x1 + 0.01 * (x1 - x0) + 2 + y0, y1 = y0 - 0.1 * hh - 1, y1 + 0.1 * hh + 1 + X0, Y0, X1, Y1 = [int(round(v * sc)) for v in (max(x0, 0), max(y0, 0), x1, y1)] + X0, Y0, X1, Y1 = max(X0, 0), max(Y0, 0), min(X1, W), min(Y1, H) + if X1 - X0 < 4 or Y1 - Y0 < 4: + return None + return big.crop((X0, Y0, X1, Y1)) + + +def read_hires(path): + """TSV with a header and the columns id and image, optionally scale (reading-image pixels per detection-image pixel).""" + out = {} + with open(path, encoding="utf-8", newline="") as f: + for r in csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE): + out[r["id"]] = (r["image"], float(r["scale"]) if r.get("scale") else None) + return out + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + g = ap.add_mutually_exclusive_group(required=True) + g.add_argument("--images", help="one page image or a folder of page images (ids are the file names)") + g.add_argument("--manifest", help="TSV with a header and the columns id and image (the detection images)") + ap.add_argument("--out", required=True, help="page TSV: id, n_lines, text") + ap.add_argument("--lines-out", default=None, help="line TSV: id, line, x0, y0, x1, y1, score, text") + ap.add_argument("--detector-dir", default=os.path.join(HERE, "..", "turkic-line-detector-yolo11s")) + ap.add_argument("--reader-dir", default=os.path.join(HERE, "..", "turkic-ocr-paddleocr-vl-1.6")) + ap.add_argument("--detector-python", default=sys.executable, help="Python with ultralytics installed (runs the detector package)") + ap.add_argument("--device", default="auto", help="auto, cpu or cuda: used for the detector and the reader") + ap.add_argument("--conf", type=float, default=0.25, help="detector confidence threshold") + ap.add_argument("--hires-tsv", default=None, help="TSV (id, image, optional scale): the image to cut crops from, for pages whose detection image is a downscaled copy") + ap.add_argument("--band-px", type=float, default=None, help="reading-order row height in detection-image pixels (default: 15 for a 1280 px page)") + ap.add_argument("--batch-size", type=int, default=16) + ap.add_argument("--threads", type=int, default=0) + ap.add_argument("--keep-boxes", default=None, help="also write the detector's boxes TSV here") + ap.add_argument("--report-modules", default=None, help="write the file paths of all loaded Python modules to this JSON (checks)") + a = ap.parse_args() + items = collect_inputs(a.images, a.manifest) + det_dir = os.path.abspath(a.detector_dir) + rd_dir = os.path.abspath(a.reader_dir) + hires = read_hires(a.hires_tsv) if a.hires_tsv else {} + t_all = time.time() + + # stage 1: boxes + work = tempfile.mkdtemp(prefix="turkic_ocr_pages_") + man = os.path.join(work, "pages_manifest.tsv") + with open(man, "w", encoding="utf-8", newline="") as f: + f.write("id\timage\n") + for rid, p in items: + f.write("%s\t%s\n" % (rid, os.path.abspath(p))) + boxes_tsv = a.keep_boxes or os.path.join(work, "boxes.tsv") + det_dev = {"cuda": "0", "auto": "auto"}.get(a.device, a.device) + cmd = [a.detector_python, "-B", os.path.join(det_dir, "infer.py"), "--manifest", man, "--out", boxes_tsv, "--device", det_dev, + "--conf", str(a.conf), "--weights", os.path.join(det_dir, "best.pt")] + t0 = time.time() + r = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + sys.stderr.write(r.stderr[-600:]) + if r.returncode != 0: + raise SystemExit("the detector failed (exit %d): %s" % (r.returncode, r.stderr[-1500:])) + t_det = time.time() - t0 + boxes = {} + with open(boxes_tsv, encoding="utf-8", newline="") as f: + for row in csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE): + boxes[row["id"]] = (json.loads(row["boxes"]), json.loads(row["scores"])) + + # stage 2: crops and reading + rdr = load_module("turkic_reader_infer", os.path.join(rd_dir, "infer.py")) + reader = rdr.Reader(os.path.join(rd_dir, "model"), a.device, "bfloat16", a.threads) + fp = open(a.out, "w", encoding="utf-8", newline="") + fp.write("id\tn_lines\ttext\n") + fl = open(a.lines_out, "w", encoding="utf-8", newline="") if a.lines_out else None + if fl: + fl.write("id\tline\tx0\ty0\tx1\ty1\tscore\ttext\n") + t_read = 0.0 + for rid, path in items: + bx, sc_list = boxes.get(rid, ([], [])) + det_img = Image.open(path) + dw, dh = det_img.size + if rid in hires: + hp, hs = hires[rid] + big = Image.open(hp).convert("RGB") + sc = hs if hs else big.size[0] / float(dw) + else: + big, sc = det_img.convert("RGB"), 1.0 + band = a.band_px if a.band_px else 15.0 * max(dw, dh) / 1280.0 + order = reading_order(bx, band) + crops, idxs = [], [] + for i in order: + c = make_crop(big, bx[i], sc) + if c is not None: + crops.append(c) + idxs.append(i) + t1 = time.time() + recs = reader.read(crops, "line", a.batch_size) if crops else [] + t_read += time.time() - t1 + texts = [x["text"] for x in recs] + if fl: + for k, (i, t) in enumerate(zip(idxs, texts)): + b = bx[i] + fl.write("%s\t%d\t%.1f\t%.1f\t%.1f\t%.1f\t%.4f\t%s\n" % (rid, k, b[0], b[1], b[2], b[3], sc_list[i], t)) + kept = [t for t in texts if t] + fp.write("%s\t%d\t%s\n" % (rid, len(kept), " ".join(kept))) + fp.flush() + fp.close() + if fl: + fl.close() + sys.stderr.write("pages %d; detector %.1f s, reading %.1f s, total %.1f s\n" % (len(items), t_det, t_read, time.time() - t_all)) + if a.report_modules: + mods = sorted({getattr(m, "__file__", None) for m in sys.modules.values() if getattr(m, "__file__", None)}) + with open(a.report_modules, "w", encoding="utf-8") as f: + json.dump({"script": os.path.abspath(__file__), "modules": mods, "sys_path": sys.path}, f, indent=1) + + +if __name__ == "__main__": + main() diff --git a/release/page-pipeline/requirements.txt b/release/page-pipeline/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..1c66c1bb25dbefd28b29a193b54143285d7bfcb5 --- /dev/null +++ b/release/page-pipeline/requirements.txt @@ -0,0 +1,70 @@ +# The page pipeline runs in the READER's environment (infer.py here and the reader's code): exact package versions of CODE/.venv_vlm, +# Python 3.12.13. The detector needs ultralytics, which this environment does not have: install the requirements.txt of +# turkic-line-detector-yolo11s in a second environment and pass its Python as --detector-python (one environment holding both also works). +# Frozen with `uv pip freeze` on 2026-11-25 (cluster job 55104, file DATA/tmp/rc1_check/freeze_vlm.txt). +# torch and torchvision are the CUDA 12.8 builds ("+cu128"); the index line below lets pip find them. On a machine without a GPU the same +# versions run on the CPU (bfloat16 matrix products are used on CPU as well), or install torch==2.11.0 and torchvision==0.26.0 from PyPI. +--extra-index-url https://download.pytorch.org/whl/cu128 +accelerate==1.16.0 +annotated-doc==0.0.7 +annotated-types==0.8.0 +anyio==4.16.0 +click==8.5.1 +cuda-bindings==12.9.7 +cuda-pathfinder==1.6.0 +cuda-toolkit==12.8.1 +filelock==4.2.4 +fsspec==2026.9.0 +h11==0.16.0 +hf-xet==1.8.0 +httpcore2==2.16.2 +httpx2==2.16.2 +huggingface-hub==2.4.0 +idna==3.20 +jinja2==3.1.6 +markdown-it-py==4.3.0 +markupsafe==3.0.3 +mdurl==0.1.2 +mpmath==1.3.0 +networkx==3.7 +numpy==2.5.4 +nvidia-cublas-cu12==12.8.4.1 +nvidia-cuda-cupti-cu12==12.8.90 +nvidia-cuda-nvrtc-cu12==12.8.93 +nvidia-cuda-runtime-cu12==12.8.90 +nvidia-cudnn-cu12==9.19.0.56 +nvidia-cufft-cu12==11.3.3.83 +nvidia-cufile-cu12==1.13.1.3 +nvidia-curand-cu12==10.3.9.90 +nvidia-cusolver-cu12==11.7.3.90 +nvidia-cusparse-cu12==12.5.8.93 +nvidia-cusparselt-cu12==0.7.1 +nvidia-nccl-cu12==2.28.9 +nvidia-nvjitlink-cu12==12.8.93 +nvidia-nvshmem-cu12==3.4.5 +nvidia-nvtx-cu12==12.8.90 +packaging==26.3 +pillow==13.0.0 +protobuf==7.36.2 +psutil==7.2.2 +pydantic==2.14.4 +pydantic-core==2.50.5 +pygments==2.21.0 +pyyaml==6.0.3 +regex==2026.11.19 +rich==15.0.0 +safetensors==0.8.0 +sentencepiece==0.2.3 +setuptools==78.1.0 +shellingham==1.5.4 +sympy==1.14.0 +tokenizers==0.23.3 +torch==2.11.0+cu128 +torchvision==0.26.0+cu128 +tqdm==4.70.1 +transformers==5.23.0 +triton==3.6.0 +truststore==0.10.5 +typer==0.29.2 +typing-extensions==4.16.0 +typing-inspection==0.4.5 diff --git a/release/turkic-line-detector-yolo11s/infer.py b/release/turkic-line-detector-yolo11s/infer.py new file mode 100644 index 0000000000000000000000000000000000000000..fcc3363e7d31b1241898e860d400ef7f4f328db1 --- /dev/null +++ b/release/turkic-line-detector-yolo11s/infer.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python +"""Find text lines on page images with the YOLO11s line detector of Turkic OCR (release candidate 1, stage-2 weights best.pt). + +Input: one image, a folder of images, or a TSV manifest (columns id, image). Output: a TSV with one row per page image and the columns + id, n_lines, boxes, scores +where boxes is a JSON list of [x0, y0, x1, y1] in pixels of the input image (rounded to 0.1) and scores a JSON list of the detection +confidences (rounded to 0.0001), in the detector's own order. A detector finds boxes, not text, so this TSV replaces the (id, text) table +of the readers; the reader of the page-pipeline package turns the boxes into text. +The settings are those of our detection evaluation (CODE/src/linedet/det_eval.py): the image file is passed to ultralytics, image size +1280, confidence threshold 0.25, NMS IoU 0.6, at most 300 boxes, one class "text_line". + +usage: + python infer.py --images page.jpg --out boxes.tsv + python infer.py --manifest pages.tsv --out boxes.tsv --device cpu +""" +import os +import tempfile + +os.environ.setdefault("YOLO_OFFLINE", "1") # no network access, no analytics, no font download +os.environ.setdefault("YOLO_CONFIG_DIR", os.path.join(tempfile.gettempdir(), "ultralytics_cfg_turkic_ocr")) + +import argparse # noqa: E402 +import csv # noqa: E402 +import json # noqa: E402 +import sys # noqa: E402 +import time # noqa: E402 + +HERE = os.path.dirname(os.path.abspath(__file__)) +IMG_EXT = (".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff", ".webp") + + +def collect_inputs(images=None, manifest=None): + """List of (id, path). A manifest is a TSV with a header and the columns id and image (other columns are ignored).""" + if manifest: + rows = [] + with open(manifest, encoding="utf-8", newline="") as f: + for r in csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE): + rows.append((r["id"], r["image"])) + return rows + if os.path.isdir(images): + names = sorted(n for n in os.listdir(images) if n.lower().endswith(IMG_EXT)) + return [(n, os.path.join(images, n)) for n in names] + return [(os.path.basename(images), images)] + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + g = ap.add_mutually_exclusive_group(required=True) + g.add_argument("--images", help="one image file or a folder of images (ids are the file names)") + g.add_argument("--manifest", help="TSV with a header and the columns id and image") + ap.add_argument("--out", default="-", help="output TSV (default: standard output)") + ap.add_argument("--device", default="auto", help="auto (GPU 0 if there is one, else cpu), cpu, 0, 1, ...") + ap.add_argument("--conf", type=float, default=0.25) + ap.add_argument("--weights", default=os.path.join(HERE, "best.pt")) + ap.add_argument("--report-modules", default=None, help="write the file paths of all loaded Python modules to this JSON (checks)") + a = ap.parse_args() + import torch + from ultralytics import YOLO + dev = a.device + if dev == "auto": + dev = 0 if torch.cuda.is_available() else "cpu" + elif dev.isdigit(): + dev = int(dev) + items = collect_inputs(a.images, a.manifest) + t0 = time.time() + det = YOLO(a.weights) + t_load = time.time() - t0 + fo = sys.stdout if a.out == "-" else open(a.out, "w", encoding="utf-8", newline="") + fo.write("id\tn_lines\tboxes\tscores\n") + t1 = time.time() + for rid, path in items: + try: + r = det.predict(path, imgsz=1280, conf=a.conf, iou=0.6, max_det=300, device=dev, verbose=False)[0] + except Exception as ex: # noqa: BLE001 + sys.stderr.write("cannot read %s: %s\n" % (path, repr(ex)[:120])) + fo.write("%s\t0\t[]\t[]\n" % rid) + continue + boxes = [[round(v, 1) for v in b] for b in r.boxes.xyxy.cpu().numpy().tolist()] + scores = [round(float(s), 4) for s in r.boxes.conf.cpu().numpy().tolist()] + fo.write("%s\t%d\t%s\t%s\n" % (rid, len(boxes), json.dumps(boxes), json.dumps(scores))) + if fo is not sys.stdout: + fo.close() + sys.stderr.write("detected on %d images (device %s) in %.1f s (load %.1f s)\n" % (len(items), dev, time.time() - t1, t_load)) + if a.report_modules: + mods = sorted({getattr(m, "__file__", None) for m in sys.modules.values() if getattr(m, "__file__", None)}) + with open(a.report_modules, "w", encoding="utf-8") as f: + json.dump({"script": os.path.abspath(__file__), "modules": mods, "sys_path": sys.path}, f, indent=1) + + +if __name__ == "__main__": + main() diff --git a/release/turkic-line-detector-yolo11s/requirements.txt b/release/turkic-line-detector-yolo11s/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..3eca15017baad45dc7c2ea2134eb551cb9535ada --- /dev/null +++ b/release/turkic-line-detector-yolo11s/requirements.txt @@ -0,0 +1,115 @@ +# Exact package versions of the environment this detector was trained and evaluated in: CODE/.venv_kraken, Python 3.12.13. +# Frozen with `uv pip freeze` on 2026-11-25 (cluster job 55104, file DATA/tmp/rc1_check/freeze_kraken.txt). +# What infer.py imports directly: ultralytics (8.4.216; AGPL-3.0), torch, and through ultralytics numpy, opencv-python, pillow, scipy, pyyaml. +# torch and torchvision are the CUDA 12.8 builds ("+cu128"); the index line below lets pip find them. On a machine without a GPU the same +# versions run on the CPU. +--extra-index-url https://download.pytorch.org/whl/cu128 +aiohappyeyeballs==2.7.1 +aiohttp==3.14.5 +aiosignal==1.4.0 +anyio==4.16.0 +atpublic==9.0.0 +attrs==26.1.0 +cattrs==26.2.1 +certifi==2026.10.23 +charset-normalizer==3.5.2 +click==8.2.1 +cloudpickle==3.1.3 +contourpy==1.4.0 +coremltools==9.0 +cuda-bindings==12.9.7 +cuda-pathfinder==1.6.0 +cuda-toolkit==12.8.1 +cycler==0.12.1 +filelock==4.2.4 +flufl-lock==10.0.0 +fonttools==4.68.0 +frozenlist==1.8.0 +fsspec==2026.9.0 +h11==0.16.0 +htrmopo==0.6 +httpcore==1.0.9 +httpx==0.28.1 +idna==3.20 +imageio==2.38.2 +iso639-lang==2.6.3 +jinja2==3.1.6 +joblib==1.6.0 +jsonschema==4.26.0 +jsonschema-specifications==2025.9.1 +kenlm==0.3.0 +kiwisolver==1.5.1 +kraken==7.2 +lazy-loader==0.6 +lightning==2.6.6 +lightning-utilities==0.15.3 +lxml==6.1.3 +markdown==3.11.3 +markdown-it-py==4.3.0 +markupsafe==3.0.3 +matplotlib==3.11.2 +mdurl==0.1.2 +mpmath==1.3.0 +multidict==7.2.1 +networkx==3.7 +numpy==2.4.6 +nvidia-cublas-cu12==12.8.4.1 +nvidia-cuda-cupti-cu12==12.8.90 +nvidia-cuda-nvrtc-cu12==12.8.93 +nvidia-cuda-runtime-cu12==12.8.90 +nvidia-cudnn-cu12==9.19.0.56 +nvidia-cufft-cu12==11.3.3.83 +nvidia-cufile-cu12==1.13.1.3 +nvidia-curand-cu12==10.3.9.90 +nvidia-cusolver-cu12==11.7.3.90 +nvidia-cusparse-cu12==12.5.8.93 +nvidia-cusparselt-cu12==0.7.1 +nvidia-ml-py==13.615.71 +nvidia-nccl-cu12==2.28.9 +nvidia-nvjitlink-cu12==12.8.93 +nvidia-nvshmem-cu12==3.4.5 +nvidia-nvtx-cu12==12.8.90 +opencv-python==5.1.0.95 +packaging==26.3 +pillow==13.0.0 +platformdirs==4.14.8 +polars==2.1.0 +polars-runtime-32==2.1.0 +propcache==0.5.4 +protobuf==7.36.2 +psutil==7.2.2 +pyaml==26.7.0 +pyarrow==26.0.1 +pygments==2.21.0 +pyparsing==3.3.3 +python-dateutil==4.0.0 +pytorch-lightning==2.6.6 +pyyaml==6.0.3 +rapidfuzz==3.14.6 +referencing==0.37.0 +regex==2026.11.19 +requests==2.34.2 +rich==14.0.0 +rpds-py==2026.9.1 +safetensors==0.7.0 +scikit-image==0.26.0 +scikit-learn==1.7.2 +scipy==1.16.3 +setuptools==78.1.0 +shapely==2.1.2 +sickle==0.7.0 +sympy==1.14.0 +threadpoolctl==3.6.0 +tifffile==2026.11.16 +torch==2.11.0+cu128 +torchmetrics==1.9.0 +torchvision==0.26.0+cu128 +tqdm==4.70.1 +triton==3.6.0 +typing-extensions==4.16.0 +tzdata==2026.6 +ultralytics==8.4.216 +ultralytics-platform==0.1.119 +ultralytics-thop==2.2.5 +urllib3==2.8.0 +yarl==1.25.1 diff --git a/release/turkic-ocr-paddleocr-vl-1.6/infer.py b/release/turkic-ocr-paddleocr-vl-1.6/infer.py new file mode 100644 index 0000000000000000000000000000000000000000..642aec7511015427124a3ca527c9f0df9cca3397 --- /dev/null +++ b/release/turkic-ocr-paddleocr-vl-1.6/infer.py @@ -0,0 +1,260 @@ +#!/usr/bin/env python +"""Read word or line crops with the vision-language model in ./model (Turkic OCR, release candidate 1). + +Input: one image, a folder of images, or a TSV manifest (columns id, image). Output: a TSV with the columns id and text. +The decoding is the one of our evaluation (CODE/scripts/r5_vlma/vlm_common.py and eval_vlm.py), copied here so the package stands alone: + - the single instruction "Transcribe the text in this image exactly." with one image, the model's own chat template, + generation prompt on, chat-template variables and answer-end token read from model/r5_export.json; + - greedy decoding, one beam, no repetition penalty, left padding, stop on the generation-config end ids, the tokenizer end id and + the trained answer-end token; at most 48 new tokens for a word crop (--unit word) or 192 for a line crop (--unit line); + - bfloat16 weights and inputs, scaled dot-product attention; the same code runs on CPU and on a GPU; + - the text written is the raw output with Unicode NFC, every run of white space turned into one space, outer white space stripped. +Not part of this release: the cap-retry rule of the evaluation (sampling at temperature 0.3 when the 48 or 192 token cap is hit), +which was a separate post-processed figure; --with-conf writes hit_cap so such rows can be found. + +usage: + python infer.py --images crop.png --out out.tsv --unit line + python infer.py --images folder/ --out out.tsv --unit word --device cuda + python infer.py --manifest crops.tsv --out out.tsv --unit word --with-conf +""" +import os + +for _k in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"): + os.environ.pop(_k, None) +os.environ.setdefault("HF_HUB_OFFLINE", "1") +os.environ.setdefault("TRANSFORMERS_OFFLINE", "1") +os.environ.setdefault("TOKENIZERS_PARALLELISM", "false") + +import argparse # noqa: E402 +import copy # noqa: E402 +import csv # noqa: E402 +import json # noqa: E402 +import re # noqa: E402 +import sys # noqa: E402 +import time # noqa: E402 +import unicodedata # noqa: E402 + +import torch # noqa: E402 +import transformers # noqa: E402 +from PIL import Image # noqa: E402 + +HERE = os.path.dirname(os.path.abspath(__file__)) +INSTR = "Transcribe the text in this image exactly." +MAXNEW = {"word": 48, "line": 192} +IMG_EXT = (".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff", ".webp") +_WS = re.compile(r"\s+") + + +def norm(text): + """postproc.plain_output of the evaluation: NFC, white space runs to one space, outer white space stripped.""" + return _WS.sub(" ", unicodedata.normalize("NFC", text or "")).strip() + + +# ----------------------------------------------------------------------------------------- copied from vlm_common.py +def template_kwargs(proc, tok): + """enable_thinking=False for every model whose chat template uses that variable; others get no extra variable.""" + texts = [] + for o in (proc, tok): + ct = getattr(o, "chat_template", None) + if isinstance(ct, dict): + texts.extend(str(v) for v in ct.values()) + elif ct: + texts.append(str(ct)) + return {"enable_thinking": False} if any("enable_thinking" in t for t in texts) else {} + + +def prompt_batch(proc, imgs, tmpl_kw): + """The one prompt builder (training and evaluation): user turn = one image + INSTR, generation prompt on.""" + convs = [[{"role": "user", "content": [{"type": "image", "image": im}, {"type": "text", "text": INSTR}]}] for im in imgs] + return proc.apply_chat_template(convs, add_generation_prompt=True, tokenize=True, return_dict=True, + return_tensors="pt", padding=True, **tmpl_kw) + + +def stop_ids(model_gen_cfg, tok): + s = set() + for e in (getattr(model_gen_cfg, "eos_token_id", None), getattr(tok, "eos_token_id", None)): + if isinstance(e, (list, tuple)): + s.update(int(x) for x in e) + elif e is not None: + s.add(int(e)) + return s + + +def gen_setup(model, tok, suffix_ids=None): + """Greedy generation config. Stops on the generation-config end ids, the tokenizer eos and the trained answer-end token.""" + gc = copy.deepcopy(model.generation_config) + gc.do_sample = False + gc.num_beams = 1 + gc.repetition_penalty = 1.0 + gc.no_repeat_ngram_size = 0 + gc.temperature = None + gc.top_p = None + gc.top_k = None + gc.use_cache = True + if gc.pad_token_id is None: + gc.pad_token_id = tok.pad_token_id + stops = stop_ids(model.generation_config, tok) + if suffix_ids: + stops.add(int(suffix_ids[-1])) + gc.eos_token_id = sorted(stops) + stop_set = set(stops) + if gc.pad_token_id is not None: + stop_set.add(gc.pad_token_id) + return gc, sorted(stops), stop_set + + +def generate_batch(model, proc, tok, imgs, max_new, tmpl_kw, gc, stop_set, dev, dtype): + """Greedy reading of a batch (tokenizer padding side must be 'left'). Returns per image: raw text, n_new, hit_cap, conf, conf_min. + conf = mean natural-log probability of the generated tokens up to and including the first stop token; hit_cap = generation + reached max_new_tokens without a stop token. (Same as vlm_common.generate_batch; the dtype of the inputs is a parameter here, + bfloat16 in the evaluation.)""" + inputs = prompt_batch(proc, imgs, tmpl_kw) + am = inputs["attention_mask"] + assert bool(am[:, -1].all()), "padding is not on the left" + inputs = inputs.to(dev, dtype=dtype) + g = copy.deepcopy(gc) + g.max_new_tokens = max_new + with torch.inference_mode(): + out = model.generate(**inputs, generation_config=g, output_scores=True, return_dict_in_generate=True) + new = out.sequences[:, inputs["input_ids"].shape[1]:] + lp = torch.stack([torch.log_softmax(s.float(), dim=-1).gather(1, new[:, t:t + 1]).squeeze(1) + for t, s in enumerate(out.scores[: new.shape[1]])], dim=1).cpu() + texts = tok.batch_decode(new, skip_special_tokens=True, clean_up_tokenization_spaces=False) + recs = [] + for r in range(new.shape[0]): + row = new[r].tolist() + n_new, hit = len(row), False + for j, t in enumerate(row): + if t in stop_set: + n_new, hit = j + 1, True + break + v = lp[r, :n_new] + recs.append({"raw": texts[r], "n_new": n_new, "hit_cap": (not hit) and n_new >= max_new, + "conf": round(float(v.mean()), 6) if n_new else None, + "conf_min": round(float(v.min()), 6) if n_new else None}) + return recs + + +# ----------------------------------------------------------------------------------------- the reader +class Reader: + """Loads the model of this package once; read() turns PIL images into texts.""" + + def __init__(self, model_dir=None, device="auto", dtype="bfloat16", threads=0): + self.model_dir = model_dir or os.path.join(HERE, "model") + if device == "auto": + device = "cuda" if torch.cuda.is_available() else "cpu" + self.dev = device + self.dtype = {"bfloat16": torch.bfloat16, "float32": torch.float32}[dtype] + if threads: + torch.set_num_threads(threads) + if device.startswith("cuda"): + # performance only, as in the evaluation: the cuDNN backend of scaled_dot_product_attention builds a new plan for every + # new sequence shape; the flash / memory-efficient / math backends are used instead + torch.backends.cuda.enable_cudnn_sdp(False) + assert not any(f.endswith(".py") for f in os.listdir(self.model_dir)), "a .py file in the model folder" + self.proc = transformers.AutoProcessor.from_pretrained(self.model_dir, trust_remote_code=False) + self.tok = getattr(self.proc, "tokenizer", self.proc) + if getattr(self.tok, "pad_token_id", None) is None: + self.tok.pad_token = self.tok.eos_token + self.tok.padding_side = "left" + with open(os.path.join(self.model_dir, "r5_export.json"), encoding="utf-8") as f: + self.export = json.load(f) + self.tmpl_kw = self.export.get("chat_template_kwargs", template_kwargs(self.proc, self.tok)) + model, info = transformers.AutoModelForImageTextToText.from_pretrained( + self.model_dir, dtype=self.dtype, trust_remote_code=False, use_safetensors=True, attn_implementation="sdpa", + output_loading_info=True) + bad = {k: list(info.get(k, []))[:10] for k in ("missing_keys", "unexpected_keys", "mismatched_keys") if info.get(k)} + if bad: + raise RuntimeError("the exported checkpoint does not reload exactly: " + json.dumps(bad)[:600]) + self.model = model.to(self.dev).eval() + self.gc, self.stops, self.stop_set = gen_setup(self.model, self.tok, self.export.get("answer_suffix_ids")) + + def read(self, images, unit="line", batch_size=16): + """images: list of PIL images (RGB). Returns a list of dicts (raw, text, n_new, hit_cap, conf, conf_min), same order.""" + max_new = MAXNEW[unit] + out = [] + for b in range(0, len(images), batch_size): + chunk = images[b:b + batch_size] + try: + recs = generate_batch(self.model, self.proc, self.tok, chunk, max_new, self.tmpl_kw, self.gc, self.stop_set, + self.dev, self.dtype) + except Exception as ex: # noqa: BLE001 (as in the evaluation: one at a time, an unreadable image gives an empty text) + sys.stderr.write("batch failed (%s); reading one image at a time\n" % repr(ex)[:150]) + recs = [] + for im in chunk: + try: + recs += generate_batch(self.model, self.proc, self.tok, [im], max_new, self.tmpl_kw, self.gc, self.stop_set, + self.dev, self.dtype) + except Exception as ex2: # noqa: BLE001 + recs.append({"raw": "", "n_new": 0, "hit_cap": False, "conf": None, "conf_min": None, "error": repr(ex2)[:200]}) + for r in recs: + r["text"] = norm(r["raw"]) + out += recs + return out + + +# ----------------------------------------------------------------------------------------- input and output +def collect_inputs(images=None, manifest=None): + """List of (id, path). A manifest is a TSV with a header and the columns id and image (other columns are ignored).""" + if manifest: + rows = [] + with open(manifest, encoding="utf-8", newline="") as f: + for r in csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE): + rows.append((r["id"], r["image"])) + return rows + if os.path.isdir(images): + names = sorted(n for n in os.listdir(images) if n.lower().endswith(IMG_EXT)) + return [(n, os.path.join(images, n)) for n in names] + return [(os.path.basename(images), images)] + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + g = ap.add_mutually_exclusive_group(required=True) + g.add_argument("--images", help="one image file or a folder of images (ids are the file names)") + g.add_argument("--manifest", help="TSV with a header and the columns id and image") + ap.add_argument("--out", default="-", help="output TSV (default: standard output)") + ap.add_argument("--unit", choices=["word", "line"], default="line", help="word crop: at most 48 new tokens; line crop: 192") + ap.add_argument("--batch-size", type=int, default=16) + ap.add_argument("--device", default="auto", help="auto, cpu, cuda or cuda:N") + ap.add_argument("--dtype", choices=["bfloat16", "float32"], default="bfloat16", help="bfloat16 is what was evaluated") + ap.add_argument("--threads", type=int, default=0, help="CPU threads (0 = torch default)") + ap.add_argument("--model-dir", default=None, help="default: the model folder next to this script") + ap.add_argument("--with-conf", action="store_true", help="add the columns conf and hit_cap") + ap.add_argument("--report-modules", default=None, help="write the file paths of all loaded Python modules to this JSON (checks)") + a = ap.parse_args() + items = collect_inputs(a.images, a.manifest) + t0 = time.time() + reader = Reader(a.model_dir, a.device, a.dtype, a.threads) + t_load = time.time() - t0 + imgs, keep = [], [] + for i, (rid, p) in enumerate(items): + try: + imgs.append(Image.open(p).convert("RGB")) + keep.append(i) + except Exception as ex: # noqa: BLE001 + sys.stderr.write("cannot read %s: %s\n" % (p, repr(ex)[:120])) + t1 = time.time() + recs = reader.read(imgs, a.unit, a.batch_size) + res = {items[i][0]: r for i, r in zip(keep, recs)} + fo = sys.stdout if a.out == "-" else open(a.out, "w", encoding="utf-8", newline="") + fo.write("id\ttext" + ("\tconf\thit_cap" if a.with_conf else "") + "\n") + for rid, _ in items: + r = res.get(rid) + text = r["text"] if r else "" + if a.with_conf: + fo.write("%s\t%s\t%s\t%d\n" % (rid, text, "" if not r or r["conf"] is None else r["conf"], int(bool(r and r["hit_cap"])))) + else: + fo.write("%s\t%s\n" % (rid, text)) + if fo is not sys.stdout: + fo.close() + sys.stderr.write("read %d images on %s (%s) in %.1f s (model load %.1f s); transformers %s, torch %s\n" % ( + len(imgs), reader.dev, a.dtype, time.time() - t1, t_load, transformers.__version__, torch.__version__)) + if a.report_modules: + mods = sorted({getattr(m, "__file__", None) for m in sys.modules.values() if getattr(m, "__file__", None)}) + with open(a.report_modules, "w", encoding="utf-8") as f: + json.dump({"script": os.path.abspath(__file__), "modules": mods, "sys_path": sys.path}, f, indent=1) + + +if __name__ == "__main__": + main() diff --git a/release/turkic-ocr-paddleocr-vl-1.6/requirements.txt b/release/turkic-ocr-paddleocr-vl-1.6/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..2b539297c5d3d0da2c22c571d10516d3f25c0f3c --- /dev/null +++ b/release/turkic-ocr-paddleocr-vl-1.6/requirements.txt @@ -0,0 +1,68 @@ +# Exact package versions of the environment this model was evaluated in: CODE/.venv_vlm, Python 3.12.13. +# Frozen with `uv pip freeze` on 2026-11-25 (cluster job 55104, file DATA/tmp/rc1_check/freeze_vlm.txt). +# torch and torchvision are the CUDA 12.8 builds ("+cu128"); the index line below lets pip find them. On a machine without a GPU the same +# versions run on the CPU (bfloat16 matrix products are used on CPU as well), or install torch==2.11.0 and torchvision==0.26.0 from PyPI. +--extra-index-url https://download.pytorch.org/whl/cu128 +accelerate==1.16.0 +annotated-doc==0.0.7 +annotated-types==0.8.0 +anyio==4.16.0 +click==8.5.1 +cuda-bindings==12.9.7 +cuda-pathfinder==1.6.0 +cuda-toolkit==12.8.1 +filelock==4.2.4 +fsspec==2026.9.0 +h11==0.16.0 +hf-xet==1.8.0 +httpcore2==2.16.2 +httpx2==2.16.2 +huggingface-hub==2.4.0 +idna==3.20 +jinja2==3.1.6 +markdown-it-py==4.3.0 +markupsafe==3.0.3 +mdurl==0.1.2 +mpmath==1.3.0 +networkx==3.7 +numpy==2.5.4 +nvidia-cublas-cu12==12.8.4.1 +nvidia-cuda-cupti-cu12==12.8.90 +nvidia-cuda-nvrtc-cu12==12.8.93 +nvidia-cuda-runtime-cu12==12.8.90 +nvidia-cudnn-cu12==9.19.0.56 +nvidia-cufft-cu12==11.3.3.83 +nvidia-cufile-cu12==1.13.1.3 +nvidia-curand-cu12==10.3.9.90 +nvidia-cusolver-cu12==11.7.3.90 +nvidia-cusparse-cu12==12.5.8.93 +nvidia-cusparselt-cu12==0.7.1 +nvidia-nccl-cu12==2.28.9 +nvidia-nvjitlink-cu12==12.8.93 +nvidia-nvshmem-cu12==3.4.5 +nvidia-nvtx-cu12==12.8.90 +packaging==26.3 +pillow==13.0.0 +protobuf==7.36.2 +psutil==7.2.2 +pydantic==2.14.4 +pydantic-core==2.50.5 +pygments==2.21.0 +pyyaml==6.0.3 +regex==2026.11.19 +rich==15.0.0 +safetensors==0.8.0 +sentencepiece==0.2.3 +setuptools==78.1.0 +shellingham==1.5.4 +sympy==1.14.0 +tokenizers==0.23.3 +torch==2.11.0+cu128 +torchvision==0.26.0+cu128 +tqdm==4.70.1 +transformers==5.23.0 +triton==3.6.0 +truststore==0.10.5 +typer==0.29.2 +typing-extensions==4.16.0 +typing-inspection==0.4.5 diff --git a/release/turkic-ocr-ppocrv6-medium/infer.py b/release/turkic-ocr-ppocrv6-medium/infer.py new file mode 100644 index 0000000000000000000000000000000000000000..50bbf85d929e378a452a9d5978c5de360967f15e --- /dev/null +++ b/release/turkic-ocr-ppocrv6-medium/infer.py @@ -0,0 +1,363 @@ +#!/usr/bin/env python +"""Read word or line crops with the small recognizer A1 (kraken PP-OCRv6 medium, our checkpoint long2x) - Turkic OCR, release candidate 1. + +Input: one image, a folder of images, or a TSV manifest (columns id, image). Output: a TSV with the columns id and text. +The code path is the one of our evaluation (CODE/src/linedet/data.py, models.py, predict.py, lm_decode.py, lm_gate.py), copied here so +the package stands alone: + - image: RGB, scaled to 96 px height with Lanczos (width keeps the aspect ratio), 16 px white padding left and right, scaled to + [0, 1], inverted (ink bright); a batch is padded with zeros on the right to its widest image; + - BATCH PADDING MATTERS (read this before using the output): the network is NOT invariant to the zero padding of a batch. The + squeeze-and-excite layers of kraken's backbone average over the whole padded width (kraken/lib/ppocr/backbone.py, SELayer), while only + the attention of the neck masks the padded columns (network.py, _lengths_and_mask). The evaluation read batches of 32 sorted by + LABEL length, so every batch carried white margin on its narrower crops, and the network was trained that way; without labels that + cannot be repeated. Measured on the 3,678 KOHTD validation crops V1 (greedy, CPU float32, character error rate; jobs 55155 and + 55176): evaluation batches 6.2% (the recorded GPU file: 6.2%); batches sorted by width 14.1%; every crop alone 14.2%; batches in + manifest order 7.9%; in a seeded shuffle 7.3%; sorted by width plus 64, 128, 256, 512, 1024 extra zero columns: 10.4%, 8.1%, 6.55%, + 6.50%, 7.5%. This script therefore sorts by width and appends --batch-pad (default 256) zero columns to every batch: a label-free + approximation chosen on V1 (word crops; the value for line crops is untested), not the evaluation's own condition. To reproduce the + evaluation use --sort none --batch-pad 0 --batch-size 32 with the crops listed in the order of their label length (stable sort); + - network: kraken 7.2 PP-OCRv6 medium (weights in model/model.safetensors, character codec in model/codec.json); on a GPU the + forward pass runs under bfloat16 autocast as in the evaluation, on the CPU in float32; + - --decode greedy (default): CTC greedy decoding (argmax per frame, collapse repeats, drop the blank), NFC; + - --decode lm: CTC prefix beam search, beam 16, with the KenLM character 6-gram in lm/char6.klm, alpha 0.40, beta 1.00, the top 6 + labels of every frame (stored as int16 and float16 as in the evaluation), prune -10; + - --decode lm_gated: as lm, but a row whose greedy output is empty or only white space gets the empty text (the gate "H9" of the + evaluation). This is the decoding named long2x_lm_gated in our result files. + +usage: + python infer.py --images crop.png --out out.tsv + python infer.py --images folder/ --out out.tsv --decode lm_gated --device cuda + python infer.py --manifest crops.tsv --out out.tsv --decode lm_gated --with-conf +""" +import os + +os.environ.setdefault("HF_HUB_OFFLINE", "1") + +import argparse # noqa: E402 +import csv # noqa: E402 +import json # noqa: E402 +import math # noqa: E402 +import sys # noqa: E402 +import time # noqa: E402 +import unicodedata # noqa: E402 + +import numpy as np # noqa: E402 +import torch # noqa: E402 +import torch.nn.functional as F # noqa: E402 +from PIL import Image # noqa: E402 +from safetensors.torch import load_file # noqa: E402 + +HERE = os.path.dirname(os.path.abspath(__file__)) +IMG_EXT = (".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff", ".webp") +PAD = 16 +BATCH_PAD_DEFAULT = 256 # extra zero columns per batch, chosen on V1 from {0, 64, 128, 256, 512, 1024} (job 55176) +TOPK = 6 +BEAM = 16 +ALPHA, BETA = 0.40, 1.00 +SP_TOKEN = "▁" +NEG = -1e30 +LN10 = math.log(10.0) + + +# ----------------------------------------------------------------------------------------- images (data.py pil_tensor, collate) +def pil_tensor(im, height): + im = im.convert("RGB") + w, h = im.size + nw = max(int(w * height / h), 1) + im = im.resize((nw, height), Image.LANCZOS) + arr = np.asarray(im, dtype=np.uint8) + arr = np.pad(arr, ((0, 0), (PAD, PAD), (0, 0)), constant_values=255) + t = torch.from_numpy(arr).permute(2, 0, 1).float().div_(255.0) + return t.max() - t + + +def collate(tensors): + seq_lens = torch.LongTensor([s.shape[2] for s in tensors]) + wmax = int(seq_lens.max()) + return torch.stack([F.pad(s, (0, wmax - s.shape[2])) for s in tensors]), seq_lens + + +# ----------------------------------------------------------------------------------------- network (models.py PPOCRArm.infer) +class Recognizer: + def __init__(self, model_dir=None, device="auto", threads=0): + from kraken.lib.codec import PytorchCodec + from kraken.lib.ppocr import PPOCRv6Model + self.model_dir = model_dir or os.path.join(HERE, "model") + if device == "auto": + device = "cuda" if torch.cuda.is_available() else "cpu" + self.dev = torch.device(device) + if threads: + torch.set_num_threads(threads) + with open(os.path.join(self.model_dir, "config.json"), encoding="utf-8") as f: + self.cfg = json.load(f) + with open(os.path.join(self.model_dir, "codec.json"), encoding="utf-8") as f: + self.c2l = json.load(f)["c2l"] + self.codec = PytorchCodec(self.c2l) + self.l2c_single = self.codec.l2c_single + net = PPOCRv6Model(variant=self.cfg["variant"], num_classes=self.codec.max_label + 1, height=self.cfg["height"], + codec=self.codec.c2l, seg_type=self.cfg["seg_type"], one_channel_mode=self.cfg["one_channel_mode"], + legacy_polygons=self.cfg["legacy_polygons"]) + net.load_state_dict(load_file(os.path.join(self.model_dir, "model.safetensors")), strict=True) + self.net = net.to(self.dev).eval() + self.height = self.cfg["height"] + + @torch.no_grad() + def log_probs(self, images, seq_lens): + with torch.autocast("cuda", dtype=torch.bfloat16, enabled=(self.dev.type == "cuda")): + logits, out_lens = self.net.nn(images.to(self.dev), seq_lens.to(self.dev)) + lp = logits.float().log_softmax(1).squeeze(2).permute(0, 2, 1) # B, T, C + return lp.cpu().numpy(), out_lens.cpu().numpy() + + def greedy(self, lp, out_lens): + """predict.greedy_strings: strings (NFD, as the codec), mean and minimum frame probability of the emitted characters.""" + best = lp.argmax(-1) + bestp = np.exp(lp.max(-1)) + res = [] + for b in range(lp.shape[0]): + T = int(out_lens[b]) + row = best[b, :T] + prev = 0 + chars, confs = [], [] + for t in range(T): + k = int(row[t]) + if k != prev and k != 0: + chars.append(self.l2c_single.get(k, "")) + confs.append(float(bestp[b, t])) + prev = k + res.append(("".join(chars), float(np.mean(confs)) if confs else 1.0, float(np.min(confs)) if confs else 1.0)) + return res + + @staticmethod + def topk(lp, out_lens): + """predict.run_set: the top-6 labels per frame, stored as int16 labels and float16 log-probabilities.""" + k = min(TOPK, lp.shape[-1]) + idx = np.argpartition(-lp, k - 1, axis=-1)[..., :k] + vals = np.take_along_axis(lp, idx, axis=-1) + return [(idx[j, :int(out_lens[j])].astype(np.int16), vals[j, :int(out_lens[j])].astype(np.float16)) for j in range(lp.shape[0])] + + def read(self, images, batch_size=32, decode="greedy", lm=None, workers=1, sort="width", batch_pad=BATCH_PAD_DEFAULT): + """images: list of PIL images. Returns a list of dicts (same order as images): text (NFC, as written), greedy (NFC), conf. + sort="width": the images are read in batches of similar width (narrowest first); sort="none": batches are consecutive images of + the input order. batch_pad: zero columns (white margin) appended on the right of every batch, on top of the padding to the + widest image of the batch; the real widths are passed on, so the attention of the neck ignores them, but the squeeze-and-excite + layers of the backbone average over them. The network is NOT invariant to this padding (see the docstring of this file), so + the batch and batch_pad matter.""" + tens = [pil_tensor(im, self.height) for im in images] + out = [None] * len(images) + tops = [None] * len(images) + order = sorted(range(len(tens)), key=lambda i: tens[i].shape[-1]) if sort == "width" else list(range(len(tens))) + for b in range(0, len(order), batch_size): + idx = order[b:b + batch_size] + x, sl = collate([tens[i] for i in idx]) + if batch_pad: + x = F.pad(x, (0, int(batch_pad))) + lp, ol = self.log_probs(x, sl) + res = self.greedy(lp, ol) + tk = self.topk(lp, ol) if decode != "greedy" else None + for j, i in enumerate(idx): + g = unicodedata.normalize("NFC", res[j][0]) + out[i] = {"greedy": g, "text": g, "conf": res[j][1]} + if tk is not None: + tops[i] = tk[j] + if decode != "greedy": + dec = lm.decode_many([(t[0].astype(np.int64), t[1].astype(np.float32)) for t in tops], workers) + for i, (h, sc) in enumerate(dec): + hn = unicodedata.normalize("NFC", h) + if decode == "lm_gated" and out[i]["greedy"].strip() == "": + out[i]["text"] = "" + else: + out[i]["text"] = hn + out[i]["conf"] = sc + out[i]["lm_raw"] = hn + return out + + +# ----------------------------------------------------------------------------------------- character language model (lm_decode.py) +_LM = None +_L2C = None + + +def _init_lm(lm_path, c2l): + global _LM, _L2C + import kenlm + _LM = kenlm.Model(lm_path) + _L2C = {v[0]: k for k, v in c2l.items() if len(v) == 1} + + +def _lse(a, b): + if a < b: + a, b = b, a + if b <= NEG: + return a + return a + math.log1p(math.exp(b - a)) + + +def beam_search(idx, lp, alpha, beta, beam=BEAM, prune=-10.0): + """CTC prefix beam search with a KenLM character model. idx (T,K) int labels, lp (T,K) natural-log probabilities (the top-K of + each frame), blank is label 0. Returns (best prefix as a string in NFD, normalised score). lm_decode.beam_search, unchanged.""" + import kenlm + lm = _LM + st0 = kenlm.State() + lm.BeginSentenceWrite(st0) + beams = {(): [0.0, NEG, 0.0, st0]} # prefix -> [p_blank, p_nonblank, lm_total(weighted), state] + lm_cache = {} + + def lm_extend(prefix, c): + key = (prefix, c) + r = lm_cache.get(key) + if r is None: + parent = beams.get(prefix) + pstate = parent[3] if parent is not None else lm_cache[("state", prefix)] + out = kenlm.State() + tok = _L2C.get(c, "") + tok = SP_TOKEN if tok == " " else tok + s = lm.BaseScore(pstate, tok, out) * LN10 + r = (alpha * s + beta, out) + lm_cache[key] = r + return r + + for t in range(idx.shape[0]): + cand = {} + ids = idx[t] + lps = lp[t].astype(np.float64) + pb_t = None + for j in range(len(ids)): + if int(ids[j]) == 0: + pb_t = float(lps[j]) + if pb_t is None: + pb_t = -20.0 + for prefix, (pb, pnb, lmt, st) in beams.items(): + tot = _lse(pb, pnb) + e = cand.get(prefix) + if e is None: + cand[prefix] = [tot + pb_t, NEG, lmt, st] + else: + e[0] = _lse(e[0], tot + pb_t) + for j in range(len(ids)): + c = int(ids[j]) + if c == 0: + continue + p = float(lps[j]) + if p < prune: + continue + last = prefix[-1] if prefix else None + if c == last: + e = cand.get(prefix) + if e is None: + cand[prefix] = [NEG, pnb + p, lmt, st] + else: + e[1] = _lse(e[1], pnb + p) + src = pb + else: + src = tot + if src <= NEG: + continue + newp = prefix + (c,) + lm_cache[("state", prefix)] = st + add, nst = lm_extend(prefix, c) + e = cand.get(newp) + if e is None: + cand[newp] = [NEG, src + p, lmt + add, nst] + else: + e[1] = _lse(e[1], src + p) + items = sorted(cand.items(), key=lambda kv: _lse(kv[1][0], kv[1][1]) + kv[1][2], reverse=True)[:beam] + beams = {k: v for k, v in items} + best, best_s = (), NEG + for prefix, (pb, pnb, lmt, st) in beams.items(): + out = kenlm.State() + eos = lm.BaseScore(st, "", out) * LN10 + s = _lse(pb, pnb) + lmt + alpha * eos + if s > best_s: + best, best_s = prefix, s + text = "".join(_L2C.get(c, "") for c in best) + return text, (best_s / max(len(best), 1) if best_s > NEG else float("nan")) + + +def _decode_one(args): + idx, lp, alpha, beta = args + return beam_search(idx, lp, alpha, beta) + + +class CharLM: + def __init__(self, lm_path, c2l, alpha=ALPHA, beta=BETA): + self.lm_path, self.c2l, self.alpha, self.beta = lm_path, c2l, alpha, beta + _init_lm(lm_path, c2l) + + def decode_many(self, items, workers=1): + jobs = [(i, l, self.alpha, self.beta) for i, l in items] + if workers > 1 and len(jobs) > 1: + import multiprocessing as mp + with mp.get_context("spawn").Pool(workers, initializer=_init_lm, initargs=(self.lm_path, self.c2l)) as pool: + return pool.map(_decode_one, jobs, chunksize=8) + return [_decode_one(j) for j in jobs] + + +# ----------------------------------------------------------------------------------------- input and output +def collect_inputs(images=None, manifest=None): + """List of (id, path). A manifest is a TSV with a header and the columns id and image (other columns are ignored).""" + if manifest: + rows = [] + with open(manifest, encoding="utf-8", newline="") as f: + for r in csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE): + rows.append((r["id"], r["image"])) + return rows + if os.path.isdir(images): + names = sorted(n for n in os.listdir(images) if n.lower().endswith(IMG_EXT)) + return [(n, os.path.join(images, n)) for n in names] + return [(os.path.basename(images), images)] + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + g = ap.add_mutually_exclusive_group(required=True) + g.add_argument("--images", help="one image file or a folder of images (ids are the file names)") + g.add_argument("--manifest", help="TSV with a header and the columns id and image") + ap.add_argument("--out", default="-", help="output TSV (default: standard output)") + ap.add_argument("--decode", choices=["greedy", "lm", "lm_gated"], default="greedy") + ap.add_argument("--batch-size", type=int, default=32) + ap.add_argument("--sort", choices=["width", "none"], default="width", + help="width (default): read images of similar width together, narrowest first; none: batches follow the input order. " + "The network's output can depend on the batch (padding), see the limits in model_card.json") + ap.add_argument("--batch-pad", type=int, default=BATCH_PAD_DEFAULT, + help="zero columns appended on the right of every batch (default %d); 0 = only the padding to the widest image of the batch" % BATCH_PAD_DEFAULT) + ap.add_argument("--device", default="auto", help="auto, cpu, cuda or cuda:N") + ap.add_argument("--threads", type=int, default=0, help="CPU threads (0 = torch default)") + ap.add_argument("--workers", type=int, default=1, help="processes for the language-model beam search") + ap.add_argument("--model-dir", default=None, help="default: the model folder next to this script") + ap.add_argument("--lm", default=None, help="default: lm/char6.klm next to this script") + ap.add_argument("--with-conf", action="store_true", + help="add the column conf (greedy: mean frame probability of the emitted characters; lm: beam score per character)") + ap.add_argument("--report-modules", default=None, help="write the file paths of all loaded Python modules to this JSON (checks)") + a = ap.parse_args() + items = collect_inputs(a.images, a.manifest) + t0 = time.time() + rec = Recognizer(a.model_dir, a.device, a.threads) + lm = CharLM(a.lm or os.path.join(HERE, "lm", "char6.klm"), rec.c2l) if a.decode != "greedy" else None + t_load = time.time() - t0 + imgs, keep = [], [] + for i, (rid, p) in enumerate(items): + try: + imgs.append(Image.open(p).convert("RGB")) + keep.append(i) + except Exception as ex: # noqa: BLE001 + sys.stderr.write("cannot read %s: %s\n" % (p, repr(ex)[:120])) + t1 = time.time() + outs = rec.read(imgs, a.batch_size, a.decode, lm, a.workers, a.sort, a.batch_pad) + res = {items[i][0]: r for i, r in zip(keep, outs)} + fo = sys.stdout if a.out == "-" else open(a.out, "w", encoding="utf-8", newline="") + fo.write("id\ttext" + ("\tconf" if a.with_conf else "") + "\n") + for rid, _ in items: + r = res.get(rid) + text = (r["text"] if r else "").replace("\t", " ").replace("\n", " ") + fo.write("%s\t%s%s\n" % (rid, text, ("\t%.4f" % r["conf"]) if (a.with_conf and r) else ("\t" if a.with_conf else ""))) + if fo is not sys.stdout: + fo.close() + sys.stderr.write("read %d images on %s, decode %s, in %.1f s (load %.1f s)\n" % (len(imgs), rec.dev, a.decode, time.time() - t1, t_load)) + if a.report_modules: + mods = sorted({getattr(m, "__file__", None) for m in sys.modules.values() if getattr(m, "__file__", None)}) + with open(a.report_modules, "w", encoding="utf-8") as f: + json.dump({"script": os.path.abspath(__file__), "modules": mods, "sys_path": sys.path}, f, indent=1) + + +if __name__ == "__main__": + main() diff --git a/release/turkic-ocr-ppocrv6-medium/requirements.txt b/release/turkic-ocr-ppocrv6-medium/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..e4dfbade207eb65a72bcff888442d3acd077ad90 --- /dev/null +++ b/release/turkic-ocr-ppocrv6-medium/requirements.txt @@ -0,0 +1,115 @@ +# Exact package versions of the environment this model was trained and evaluated in: CODE/.venv_kraken, Python 3.12.13. +# Frozen with `uv pip freeze` on 2026-11-25 (cluster job 55104, file DATA/tmp/rc1_check/freeze_kraken.txt). +# What infer.py imports directly: kraken (PPOCRv6Model, PytorchCodec), torch, numpy, pillow, safetensors, and kenlm for --decode lm and lm_gated. +# kenlm==0.3.0 is built from source on installation (needs a C++ compiler). torch and torchvision are the CUDA 12.8 builds ("+cu128"); the +# index line below lets pip find them. On a machine without a GPU the same versions run on the CPU (float32 there). +--extra-index-url https://download.pytorch.org/whl/cu128 +aiohappyeyeballs==2.7.1 +aiohttp==3.14.5 +aiosignal==1.4.0 +anyio==4.16.0 +atpublic==9.0.0 +attrs==26.1.0 +cattrs==26.2.1 +certifi==2026.10.23 +charset-normalizer==3.5.2 +click==8.2.1 +cloudpickle==3.1.3 +contourpy==1.4.0 +coremltools==9.0 +cuda-bindings==12.9.7 +cuda-pathfinder==1.6.0 +cuda-toolkit==12.8.1 +cycler==0.12.1 +filelock==4.2.4 +flufl-lock==10.0.0 +fonttools==4.68.0 +frozenlist==1.8.0 +fsspec==2026.9.0 +h11==0.16.0 +htrmopo==0.6 +httpcore==1.0.9 +httpx==0.28.1 +idna==3.20 +imageio==2.38.2 +iso639-lang==2.6.3 +jinja2==3.1.6 +joblib==1.6.0 +jsonschema==4.26.0 +jsonschema-specifications==2025.9.1 +kenlm==0.3.0 +kiwisolver==1.5.1 +kraken==7.2 +lazy-loader==0.6 +lightning==2.6.6 +lightning-utilities==0.15.3 +lxml==6.1.3 +markdown==3.11.3 +markdown-it-py==4.3.0 +markupsafe==3.0.3 +matplotlib==3.11.2 +mdurl==0.1.2 +mpmath==1.3.0 +multidict==7.2.1 +networkx==3.7 +numpy==2.4.6 +nvidia-cublas-cu12==12.8.4.1 +nvidia-cuda-cupti-cu12==12.8.90 +nvidia-cuda-nvrtc-cu12==12.8.93 +nvidia-cuda-runtime-cu12==12.8.90 +nvidia-cudnn-cu12==9.19.0.56 +nvidia-cufft-cu12==11.3.3.83 +nvidia-cufile-cu12==1.13.1.3 +nvidia-curand-cu12==10.3.9.90 +nvidia-cusolver-cu12==11.7.3.90 +nvidia-cusparse-cu12==12.5.8.93 +nvidia-cusparselt-cu12==0.7.1 +nvidia-ml-py==13.615.71 +nvidia-nccl-cu12==2.28.9 +nvidia-nvjitlink-cu12==12.8.93 +nvidia-nvshmem-cu12==3.4.5 +nvidia-nvtx-cu12==12.8.90 +opencv-python==5.1.0.95 +packaging==26.3 +pillow==13.0.0 +platformdirs==4.14.8 +polars==2.1.0 +polars-runtime-32==2.1.0 +propcache==0.5.4 +protobuf==7.36.2 +psutil==7.2.2 +pyaml==26.7.0 +pyarrow==26.0.1 +pygments==2.21.0 +pyparsing==3.3.3 +python-dateutil==4.0.0 +pytorch-lightning==2.6.6 +pyyaml==6.0.3 +rapidfuzz==3.14.6 +referencing==0.37.0 +regex==2026.11.19 +requests==2.34.2 +rich==14.0.0 +rpds-py==2026.9.1 +safetensors==0.7.0 +scikit-image==0.26.0 +scikit-learn==1.7.2 +scipy==1.16.3 +setuptools==78.1.0 +shapely==2.1.2 +sickle==0.7.0 +sympy==1.14.0 +threadpoolctl==3.6.0 +tifffile==2026.11.16 +torch==2.11.0+cu128 +torchmetrics==1.9.0 +torchvision==0.26.0+cu128 +tqdm==4.70.1 +triton==3.6.0 +typing-extensions==4.16.0 +tzdata==2026.6 +ultralytics==8.4.216 +ultralytics-platform==0.1.119 +ultralytics-thop==2.2.5 +urllib3==2.8.0 +yarl==1.25.1 diff --git a/release/turkic-ocr-qwen3-vl-2b/infer.py b/release/turkic-ocr-qwen3-vl-2b/infer.py new file mode 100644 index 0000000000000000000000000000000000000000..642aec7511015427124a3ca527c9f0df9cca3397 --- /dev/null +++ b/release/turkic-ocr-qwen3-vl-2b/infer.py @@ -0,0 +1,260 @@ +#!/usr/bin/env python +"""Read word or line crops with the vision-language model in ./model (Turkic OCR, release candidate 1). + +Input: one image, a folder of images, or a TSV manifest (columns id, image). Output: a TSV with the columns id and text. +The decoding is the one of our evaluation (CODE/scripts/r5_vlma/vlm_common.py and eval_vlm.py), copied here so the package stands alone: + - the single instruction "Transcribe the text in this image exactly." with one image, the model's own chat template, + generation prompt on, chat-template variables and answer-end token read from model/r5_export.json; + - greedy decoding, one beam, no repetition penalty, left padding, stop on the generation-config end ids, the tokenizer end id and + the trained answer-end token; at most 48 new tokens for a word crop (--unit word) or 192 for a line crop (--unit line); + - bfloat16 weights and inputs, scaled dot-product attention; the same code runs on CPU and on a GPU; + - the text written is the raw output with Unicode NFC, every run of white space turned into one space, outer white space stripped. +Not part of this release: the cap-retry rule of the evaluation (sampling at temperature 0.3 when the 48 or 192 token cap is hit), +which was a separate post-processed figure; --with-conf writes hit_cap so such rows can be found. + +usage: + python infer.py --images crop.png --out out.tsv --unit line + python infer.py --images folder/ --out out.tsv --unit word --device cuda + python infer.py --manifest crops.tsv --out out.tsv --unit word --with-conf +""" +import os + +for _k in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"): + os.environ.pop(_k, None) +os.environ.setdefault("HF_HUB_OFFLINE", "1") +os.environ.setdefault("TRANSFORMERS_OFFLINE", "1") +os.environ.setdefault("TOKENIZERS_PARALLELISM", "false") + +import argparse # noqa: E402 +import copy # noqa: E402 +import csv # noqa: E402 +import json # noqa: E402 +import re # noqa: E402 +import sys # noqa: E402 +import time # noqa: E402 +import unicodedata # noqa: E402 + +import torch # noqa: E402 +import transformers # noqa: E402 +from PIL import Image # noqa: E402 + +HERE = os.path.dirname(os.path.abspath(__file__)) +INSTR = "Transcribe the text in this image exactly." +MAXNEW = {"word": 48, "line": 192} +IMG_EXT = (".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff", ".webp") +_WS = re.compile(r"\s+") + + +def norm(text): + """postproc.plain_output of the evaluation: NFC, white space runs to one space, outer white space stripped.""" + return _WS.sub(" ", unicodedata.normalize("NFC", text or "")).strip() + + +# ----------------------------------------------------------------------------------------- copied from vlm_common.py +def template_kwargs(proc, tok): + """enable_thinking=False for every model whose chat template uses that variable; others get no extra variable.""" + texts = [] + for o in (proc, tok): + ct = getattr(o, "chat_template", None) + if isinstance(ct, dict): + texts.extend(str(v) for v in ct.values()) + elif ct: + texts.append(str(ct)) + return {"enable_thinking": False} if any("enable_thinking" in t for t in texts) else {} + + +def prompt_batch(proc, imgs, tmpl_kw): + """The one prompt builder (training and evaluation): user turn = one image + INSTR, generation prompt on.""" + convs = [[{"role": "user", "content": [{"type": "image", "image": im}, {"type": "text", "text": INSTR}]}] for im in imgs] + return proc.apply_chat_template(convs, add_generation_prompt=True, tokenize=True, return_dict=True, + return_tensors="pt", padding=True, **tmpl_kw) + + +def stop_ids(model_gen_cfg, tok): + s = set() + for e in (getattr(model_gen_cfg, "eos_token_id", None), getattr(tok, "eos_token_id", None)): + if isinstance(e, (list, tuple)): + s.update(int(x) for x in e) + elif e is not None: + s.add(int(e)) + return s + + +def gen_setup(model, tok, suffix_ids=None): + """Greedy generation config. Stops on the generation-config end ids, the tokenizer eos and the trained answer-end token.""" + gc = copy.deepcopy(model.generation_config) + gc.do_sample = False + gc.num_beams = 1 + gc.repetition_penalty = 1.0 + gc.no_repeat_ngram_size = 0 + gc.temperature = None + gc.top_p = None + gc.top_k = None + gc.use_cache = True + if gc.pad_token_id is None: + gc.pad_token_id = tok.pad_token_id + stops = stop_ids(model.generation_config, tok) + if suffix_ids: + stops.add(int(suffix_ids[-1])) + gc.eos_token_id = sorted(stops) + stop_set = set(stops) + if gc.pad_token_id is not None: + stop_set.add(gc.pad_token_id) + return gc, sorted(stops), stop_set + + +def generate_batch(model, proc, tok, imgs, max_new, tmpl_kw, gc, stop_set, dev, dtype): + """Greedy reading of a batch (tokenizer padding side must be 'left'). Returns per image: raw text, n_new, hit_cap, conf, conf_min. + conf = mean natural-log probability of the generated tokens up to and including the first stop token; hit_cap = generation + reached max_new_tokens without a stop token. (Same as vlm_common.generate_batch; the dtype of the inputs is a parameter here, + bfloat16 in the evaluation.)""" + inputs = prompt_batch(proc, imgs, tmpl_kw) + am = inputs["attention_mask"] + assert bool(am[:, -1].all()), "padding is not on the left" + inputs = inputs.to(dev, dtype=dtype) + g = copy.deepcopy(gc) + g.max_new_tokens = max_new + with torch.inference_mode(): + out = model.generate(**inputs, generation_config=g, output_scores=True, return_dict_in_generate=True) + new = out.sequences[:, inputs["input_ids"].shape[1]:] + lp = torch.stack([torch.log_softmax(s.float(), dim=-1).gather(1, new[:, t:t + 1]).squeeze(1) + for t, s in enumerate(out.scores[: new.shape[1]])], dim=1).cpu() + texts = tok.batch_decode(new, skip_special_tokens=True, clean_up_tokenization_spaces=False) + recs = [] + for r in range(new.shape[0]): + row = new[r].tolist() + n_new, hit = len(row), False + for j, t in enumerate(row): + if t in stop_set: + n_new, hit = j + 1, True + break + v = lp[r, :n_new] + recs.append({"raw": texts[r], "n_new": n_new, "hit_cap": (not hit) and n_new >= max_new, + "conf": round(float(v.mean()), 6) if n_new else None, + "conf_min": round(float(v.min()), 6) if n_new else None}) + return recs + + +# ----------------------------------------------------------------------------------------- the reader +class Reader: + """Loads the model of this package once; read() turns PIL images into texts.""" + + def __init__(self, model_dir=None, device="auto", dtype="bfloat16", threads=0): + self.model_dir = model_dir or os.path.join(HERE, "model") + if device == "auto": + device = "cuda" if torch.cuda.is_available() else "cpu" + self.dev = device + self.dtype = {"bfloat16": torch.bfloat16, "float32": torch.float32}[dtype] + if threads: + torch.set_num_threads(threads) + if device.startswith("cuda"): + # performance only, as in the evaluation: the cuDNN backend of scaled_dot_product_attention builds a new plan for every + # new sequence shape; the flash / memory-efficient / math backends are used instead + torch.backends.cuda.enable_cudnn_sdp(False) + assert not any(f.endswith(".py") for f in os.listdir(self.model_dir)), "a .py file in the model folder" + self.proc = transformers.AutoProcessor.from_pretrained(self.model_dir, trust_remote_code=False) + self.tok = getattr(self.proc, "tokenizer", self.proc) + if getattr(self.tok, "pad_token_id", None) is None: + self.tok.pad_token = self.tok.eos_token + self.tok.padding_side = "left" + with open(os.path.join(self.model_dir, "r5_export.json"), encoding="utf-8") as f: + self.export = json.load(f) + self.tmpl_kw = self.export.get("chat_template_kwargs", template_kwargs(self.proc, self.tok)) + model, info = transformers.AutoModelForImageTextToText.from_pretrained( + self.model_dir, dtype=self.dtype, trust_remote_code=False, use_safetensors=True, attn_implementation="sdpa", + output_loading_info=True) + bad = {k: list(info.get(k, []))[:10] for k in ("missing_keys", "unexpected_keys", "mismatched_keys") if info.get(k)} + if bad: + raise RuntimeError("the exported checkpoint does not reload exactly: " + json.dumps(bad)[:600]) + self.model = model.to(self.dev).eval() + self.gc, self.stops, self.stop_set = gen_setup(self.model, self.tok, self.export.get("answer_suffix_ids")) + + def read(self, images, unit="line", batch_size=16): + """images: list of PIL images (RGB). Returns a list of dicts (raw, text, n_new, hit_cap, conf, conf_min), same order.""" + max_new = MAXNEW[unit] + out = [] + for b in range(0, len(images), batch_size): + chunk = images[b:b + batch_size] + try: + recs = generate_batch(self.model, self.proc, self.tok, chunk, max_new, self.tmpl_kw, self.gc, self.stop_set, + self.dev, self.dtype) + except Exception as ex: # noqa: BLE001 (as in the evaluation: one at a time, an unreadable image gives an empty text) + sys.stderr.write("batch failed (%s); reading one image at a time\n" % repr(ex)[:150]) + recs = [] + for im in chunk: + try: + recs += generate_batch(self.model, self.proc, self.tok, [im], max_new, self.tmpl_kw, self.gc, self.stop_set, + self.dev, self.dtype) + except Exception as ex2: # noqa: BLE001 + recs.append({"raw": "", "n_new": 0, "hit_cap": False, "conf": None, "conf_min": None, "error": repr(ex2)[:200]}) + for r in recs: + r["text"] = norm(r["raw"]) + out += recs + return out + + +# ----------------------------------------------------------------------------------------- input and output +def collect_inputs(images=None, manifest=None): + """List of (id, path). A manifest is a TSV with a header and the columns id and image (other columns are ignored).""" + if manifest: + rows = [] + with open(manifest, encoding="utf-8", newline="") as f: + for r in csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE): + rows.append((r["id"], r["image"])) + return rows + if os.path.isdir(images): + names = sorted(n for n in os.listdir(images) if n.lower().endswith(IMG_EXT)) + return [(n, os.path.join(images, n)) for n in names] + return [(os.path.basename(images), images)] + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + g = ap.add_mutually_exclusive_group(required=True) + g.add_argument("--images", help="one image file or a folder of images (ids are the file names)") + g.add_argument("--manifest", help="TSV with a header and the columns id and image") + ap.add_argument("--out", default="-", help="output TSV (default: standard output)") + ap.add_argument("--unit", choices=["word", "line"], default="line", help="word crop: at most 48 new tokens; line crop: 192") + ap.add_argument("--batch-size", type=int, default=16) + ap.add_argument("--device", default="auto", help="auto, cpu, cuda or cuda:N") + ap.add_argument("--dtype", choices=["bfloat16", "float32"], default="bfloat16", help="bfloat16 is what was evaluated") + ap.add_argument("--threads", type=int, default=0, help="CPU threads (0 = torch default)") + ap.add_argument("--model-dir", default=None, help="default: the model folder next to this script") + ap.add_argument("--with-conf", action="store_true", help="add the columns conf and hit_cap") + ap.add_argument("--report-modules", default=None, help="write the file paths of all loaded Python modules to this JSON (checks)") + a = ap.parse_args() + items = collect_inputs(a.images, a.manifest) + t0 = time.time() + reader = Reader(a.model_dir, a.device, a.dtype, a.threads) + t_load = time.time() - t0 + imgs, keep = [], [] + for i, (rid, p) in enumerate(items): + try: + imgs.append(Image.open(p).convert("RGB")) + keep.append(i) + except Exception as ex: # noqa: BLE001 + sys.stderr.write("cannot read %s: %s\n" % (p, repr(ex)[:120])) + t1 = time.time() + recs = reader.read(imgs, a.unit, a.batch_size) + res = {items[i][0]: r for i, r in zip(keep, recs)} + fo = sys.stdout if a.out == "-" else open(a.out, "w", encoding="utf-8", newline="") + fo.write("id\ttext" + ("\tconf\thit_cap" if a.with_conf else "") + "\n") + for rid, _ in items: + r = res.get(rid) + text = r["text"] if r else "" + if a.with_conf: + fo.write("%s\t%s\t%s\t%d\n" % (rid, text, "" if not r or r["conf"] is None else r["conf"], int(bool(r and r["hit_cap"])))) + else: + fo.write("%s\t%s\n" % (rid, text)) + if fo is not sys.stdout: + fo.close() + sys.stderr.write("read %d images on %s (%s) in %.1f s (model load %.1f s); transformers %s, torch %s\n" % ( + len(imgs), reader.dev, a.dtype, time.time() - t1, t_load, transformers.__version__, torch.__version__)) + if a.report_modules: + mods = sorted({getattr(m, "__file__", None) for m in sys.modules.values() if getattr(m, "__file__", None)}) + with open(a.report_modules, "w", encoding="utf-8") as f: + json.dump({"script": os.path.abspath(__file__), "modules": mods, "sys_path": sys.path}, f, indent=1) + + +if __name__ == "__main__": + main() diff --git a/release/turkic-ocr-qwen3-vl-2b/requirements.txt b/release/turkic-ocr-qwen3-vl-2b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..2b539297c5d3d0da2c22c571d10516d3f25c0f3c --- /dev/null +++ b/release/turkic-ocr-qwen3-vl-2b/requirements.txt @@ -0,0 +1,68 @@ +# Exact package versions of the environment this model was evaluated in: CODE/.venv_vlm, Python 3.12.13. +# Frozen with `uv pip freeze` on 2026-11-25 (cluster job 55104, file DATA/tmp/rc1_check/freeze_vlm.txt). +# torch and torchvision are the CUDA 12.8 builds ("+cu128"); the index line below lets pip find them. On a machine without a GPU the same +# versions run on the CPU (bfloat16 matrix products are used on CPU as well), or install torch==2.11.0 and torchvision==0.26.0 from PyPI. +--extra-index-url https://download.pytorch.org/whl/cu128 +accelerate==1.16.0 +annotated-doc==0.0.7 +annotated-types==0.8.0 +anyio==4.16.0 +click==8.5.1 +cuda-bindings==12.9.7 +cuda-pathfinder==1.6.0 +cuda-toolkit==12.8.1 +filelock==4.2.4 +fsspec==2026.9.0 +h11==0.16.0 +hf-xet==1.8.0 +httpcore2==2.16.2 +httpx2==2.16.2 +huggingface-hub==2.4.0 +idna==3.20 +jinja2==3.1.6 +markdown-it-py==4.3.0 +markupsafe==3.0.3 +mdurl==0.1.2 +mpmath==1.3.0 +networkx==3.7 +numpy==2.5.4 +nvidia-cublas-cu12==12.8.4.1 +nvidia-cuda-cupti-cu12==12.8.90 +nvidia-cuda-nvrtc-cu12==12.8.93 +nvidia-cuda-runtime-cu12==12.8.90 +nvidia-cudnn-cu12==9.19.0.56 +nvidia-cufft-cu12==11.3.3.83 +nvidia-cufile-cu12==1.13.1.3 +nvidia-curand-cu12==10.3.9.90 +nvidia-cusolver-cu12==11.7.3.90 +nvidia-cusparse-cu12==12.5.8.93 +nvidia-cusparselt-cu12==0.7.1 +nvidia-nccl-cu12==2.28.9 +nvidia-nvjitlink-cu12==12.8.93 +nvidia-nvshmem-cu12==3.4.5 +nvidia-nvtx-cu12==12.8.90 +packaging==26.3 +pillow==13.0.0 +protobuf==7.36.2 +psutil==7.2.2 +pydantic==2.14.4 +pydantic-core==2.50.5 +pygments==2.21.0 +pyyaml==6.0.3 +regex==2026.11.19 +rich==15.0.0 +safetensors==0.8.0 +sentencepiece==0.2.3 +setuptools==78.1.0 +shellingham==1.5.4 +sympy==1.14.0 +tokenizers==0.23.3 +torch==2.11.0+cu128 +torchvision==0.26.0+cu128 +tqdm==4.70.1 +transformers==5.23.0 +triton==3.6.0 +truststore==0.10.5 +typer==0.29.2 +typing-extensions==4.16.0 +typing-inspection==0.4.5 diff --git a/scripts/b1_page_check/b1_page_check.py b/scripts/b1_page_check/b1_page_check.py new file mode 100644 index 0000000000000000000000000000000000000000..4e5eec042cdcd08db8fe58baf2b00b4c063aafd5 --- /dev/null +++ b/scripts/b1_page_check/b1_page_check.py @@ -0,0 +1,120 @@ +"""Quick whole-page check of B1 (PaddleOCR-VL 1.6 R5 leader) on CPU: one prompt, a few validation pages. + +Not a benchmark: a smoke sample before a deadline. Validation pages only. Reuses the R5 loader and prompt builder +(CODE/scripts/r5_vlma/vlm_common.py) with the instruction swapped, greedy decoding, bf16 as in the R5 evaluation. +Writes one JSON line per page as soon as it is read, and stops before --stop_utc. + +usage: b1_page_check.py --model DIR --pages TSV --start K --n N --prompt spot|instr|ocr --out JSONL --stop_utc HH:MM +""" +import argparse +import json +import os +import re +import sys +import time +import unicodedata +from datetime import datetime, timezone + +ap = argparse.ArgumentParser() +ap.add_argument("--model", required=True) +ap.add_argument("--pages", required=True) +ap.add_argument("--stride", type=int, default=1) +ap.add_argument("--n", type=int, default=10) +ap.add_argument("--chunk", type=int, default=0) +ap.add_argument("--chunks", type=int, default=1) +ap.add_argument("--prompt", choices=["spot", "instr", "ocr"], required=True) +ap.add_argument("--out", required=True) +ap.add_argument("--stop_utc", required=True) +ap.add_argument("--max_new", type=int, default=2048) +ap.add_argument("--threads", type=int, default=16) +ap.add_argument("--vlma", default="/path/to/TURKIC_OCR_CODE/scripts/r5_vlma") +a = ap.parse_args() +assert "test" not in os.path.basename(a.pages).lower(), "refusing a test page list" + +sys.path.insert(0, a.vlma) +import torch # noqa: E402 +from PIL import Image # noqa: E402 + +import vlm_common as vc # noqa: E402 + +torch.set_num_threads(a.threads) +PROMPTS = {"spot": "Spotting:", "ocr": "OCR:", "instr": vc.INSTR} +vc.INSTR = PROMPTS[a.prompt] # prompt_batch reads the module global at call time +SCHOOL = "/path/to/TURKIC_OCR_DATA/data/raw/school_notebooks_ru" +LOC = re.compile(r"<\|LOC_\d+\|>") +SPECIAL = re.compile(r"<\|[A-Za-z_]+\|>||") + +stop_h, stop_m = (int(x) for x in a.stop_utc.split(":")) + + +def now(): + return datetime.now(timezone.utc) + + +def past_stop(): + t = now() + return (t.hour, t.minute) >= (stop_h, stop_m) + + +def school_orig(pid): + # same lookup as linedet.det_eval.school_orig: the full-resolution photograph of a school val page + sp, num = pid.split("_")[1], int(pid.split("_")[2]) + d = json.load(open("%s/annotations_%s.json" % (SCHOOL, sp), encoding="utf-8")) + fn = {im["id"]: im["file_name"] for im in d["images"]}[num] + return "%s/val_test_images/%s/%s" % (SCHOOL, sp, fn) + + +def lines_from(raw_special): + """Page text lines from the raw output: location tokens and other special tokens removed, one line per newline.""" + out = [] + for ln in raw_special.split("\n"): + t = SPECIAL.sub("", LOC.sub("", ln)) + t = " ".join(unicodedata.normalize("NFC", t).split()) + if t: + out.append(t) + return out + + +with open(a.pages, encoding="utf-8") as f: + hdr = f.readline().rstrip("\n").split("\t") + pages = [dict(zip(hdr, ln.rstrip("\n").split("\t"))) for ln in f] +# every stride-th page spreads the sample over page kinds and languages (the lists are sorted by kind, then language) +sel = pages[::a.stride][:a.n] +pages = sel[a.chunk::a.chunks] + +t0 = time.time() +proc, tok = vc.load_processor("paddleocr_vl_1_6", a.model) +tok.padding_side = "left" +model = vc.load_model("paddleocr_vl_1_6", a.model, torch.bfloat16) +model.eval() +gc, stops, stop_set = vc.gen_setup(model, tok) +tmpl_kw = vc.template_kwargs(proc, tok) +load_s = time.time() - t0 +print("loaded in %.1f s; prompt %r; %d pages" % (load_s, vc.INSTR, len(pages)), flush=True) + +dev = torch.device("cpu") +with open(a.out, "a", encoding="utf-8") as fo: + for pg in pages: + if past_stop(): + print("stop time reached before page", pg["id"], flush=True) + break + path = school_orig(pg["id"]) if pg["id"].startswith("school_") else pg["image"] + im = Image.open(path).convert("RGB") + t1 = time.time() + inputs = vc.prompt_batch("paddleocr_vl_1_6", proc, [im], tmpl_kw).to(dev, dtype=torch.bfloat16) + g = __import__("copy").deepcopy(gc) + g.max_new_tokens = a.max_new + with torch.inference_mode(): + out = model.generate(**inputs, generation_config=g) + new = out[0, inputs["input_ids"].shape[1]:].tolist() + hit = any(t in stop_set for t in new) + raw_sp = tok.decode(new, skip_special_tokens=False, clean_up_tokenization_spaces=False) + rec = {"id": pg["id"], "prompt": a.prompt, "image": path, "image_size": list(im.size), + "n_visual_tokens": int((inputs["input_ids"][0] == getattr(model.config, "image_token_id", -1)).sum()), + "n_new": len(new), "stopped": hit, "seconds": round(time.time() - t1, 1), + "hyp_lines": lines_from(raw_sp), "ref_lines": json.loads(pg["ref_lines_json"]) if pg.get("ref_lines_json") else [], + "raw": raw_sp} + fo.write(json.dumps(rec, ensure_ascii=False) + "\n") + fo.flush() + print(pg["id"], "%.1f s" % rec["seconds"], "new", len(new), "stopped", hit, "lines", len(rec["hyp_lines"]), flush=True) +print("done", now().isoformat(), flush=True) diff --git a/scripts/b1_page_check/b1_page_check.sbatch b/scripts/b1_page_check/b1_page_check.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..9d6b4384e7a5480cafca51871a55154e33f6a56f --- /dev/null +++ b/scripts/b1_page_check/b1_page_check.sbatch @@ -0,0 +1,24 @@ +#!/bin/bash +#SBATCH --job-name=b1_page_check +#SBATCH --partition=ZEN4 +#SBATCH --cpus-per-task=16 +#SBATCH --mem=48G +#SBATCH --time=00:45:00 +#SBATCH --array=0-7 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%A_%a.out +# Task t: prompt = spot (t<4) or instr; set = gen (t%4<2) or school; chunk = t%2 of 2 (5 pages each). +set -u +CODE=/path/to/TURKIC_OCR_CODE +D=/path/to/TURKIC_OCR_DATA +P=$D/data/processed/r5_linedet_det +OUT=$D/outputs/r5/b1_page_check +mkdir -p $OUT +t=$SLURM_ARRAY_TASK_ID +if [ $t -lt 4 ]; then PR=spot; else PR=instr; fi +if [ $((t % 4)) -lt 2 ]; then S=gen; PAGES=$P/gen/pages_gen_val.tsv; STRIDE=30; else S=school; PAGES=$P/school2/pages_school_val.tsv; STRIDE=15; fi +C=$((t % 2)) +export HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 OMP_NUM_THREADS=16 +hostname; date -u +$CODE/.venv_vlm/bin/python -I $CODE/scripts/b1_page_check/b1_page_check.py --model $D/checkpoints/r5/paddleocr_vl_1_6/leader \ + --pages $PAGES --stride $STRIDE --n 10 --chunk $C --chunks 2 --prompt $PR --out $OUT/${S}_${PR}_c${C}.jsonl --stop_utc 03:42 --threads 16 +echo "=== exit $? $(date -u)" diff --git a/scripts/b1_page_check/b1_page_score.py b/scripts/b1_page_check/b1_page_score.py new file mode 100644 index 0000000000000000000000000000000000000000..a3ffb1af6f58e07c6d65c9b41be69258ed52b0d6 --- /dev/null +++ b/scripts/b1_page_check/b1_page_score.py @@ -0,0 +1,82 @@ +"""Score the B1 whole-page check, and route A (YOLO11s stage 2 + A1 long) on the SAME pages for comparison. + +Page CER exactly as linedet.det_eval.page_cers (metric M28 reading order: lines joined by one space; M29 order free: +lines matched one to one by minimum edit distance, unmatched lines count in full). Micro average: summed edits over +summed reference characters. B1 lines keep the model's own output order. + +usage: b1_page_score.py --dir OUT_DIR --routeA_dir DET_EVAL_DIR --out JSON +""" +import argparse +import glob +import json +import os + +import numpy as np +from rapidfuzz import process +from rapidfuzz.distance import Levenshtein +from scipy.optimize import linear_sum_assignment + + +def page_cers(hyp_lines, ref_lines): + # copied from linedet.det_eval.page_cers so the figures are comparable with route A's 0.16 and 0.43 + nref = sum(len(r) for r in ref_lines) + ro = Levenshtein.distance(" ".join(hyp_lines), " ".join(ref_lines)) + if not hyp_lines or not ref_lines: + of = sum(len(h) for h in hyp_lines) + nref + else: + C = process.cdist(hyp_lines, ref_lines, scorer=Levenshtein.distance, dtype=np.int32) + ri, ci = linear_sum_assignment(C) + matched = int(C[ri, ci].sum()) + un_h = sum(len(hyp_lines[i]) for i in range(len(hyp_lines)) if i not in set(ri.tolist())) + un_r = sum(len(ref_lines[j]) for j in range(len(ref_lines)) if j not in set(ci.tolist())) + of = matched + un_h + un_r + return ro, of, nref + + +ap = argparse.ArgumentParser() +ap.add_argument("--dir", required=True) +ap.add_argument("--routeA_dir", required=True) +ap.add_argument("--out", required=True) +a = ap.parse_args() + +recs = {} +for fn in sorted(glob.glob(os.path.join(a.dir, "*.jsonl"))): + s, pr = os.path.basename(fn).split("_")[:2] + for ln in open(fn, encoding="utf-8"): + r = json.loads(ln) + recs.setdefault((s, pr), {})[r["id"]] = r + +routeA = {} +for s, name in (("gen", "e2e_yolo_s2_gen_val_A1_long"), ("school", "e2e_yolo_s2_school_val_A1_long")): + p = os.path.join(a.routeA_dir, name + "_pages.jsonl") + if os.path.exists(p): + routeA[s] = {json.loads(ln)["id"]: json.loads(ln) for ln in open(p, encoding="utf-8")} + +res = {"note": "smoke sample of validation pages, not a benchmark; B1 = PaddleOCR-VL 1.6 R5 leader, bf16 on CPU, greedy, " + "default processor size (at most 1,003,520 pixels)", "cells": []} +for (s, pr), pages in sorted(recs.items()): + ro = of = n = 0 + aro = aof = an = 0 + per = [] + for pid, r in sorted(pages.items()): + e_ro, e_of, nr = page_cers(r["hyp_lines"], r["ref_lines"]) + ro, of, n = ro + e_ro, of + e_of, n + nr + row = {"id": pid, "ref_chars": nr, "ro_cer": round(e_ro / max(nr, 1), 4), "of_cer": round(e_of / max(nr, 1), 4), + "n_hyp_lines": len(r["hyp_lines"]), "n_ref_lines": len(r["ref_lines"]), "stopped": r["stopped"], + "n_new": r["n_new"], "seconds": r["seconds"]} + A = routeA.get(s, {}).get(pid) + if A is not None and "hyp_lines" in A: + x_ro, x_of, _ = page_cers(A["hyp_lines"], r["ref_lines"]) + aro, aof, an = aro + x_ro, aof + x_of, an + nr + row["routeA_ro_cer"] = round(x_ro / max(nr, 1), 4) + row["routeA_of_cer"] = round(x_of / max(nr, 1), 4) + per.append(row) + res["cells"].append({"set": s, "prompt": pr, "pages": len(pages), "ref_chars": n, + "B1_reading_order_cer": round(ro / max(n, 1), 4), "B1_order_free_cer": round(of / max(n, 1), 4), + "routeA_same_pages_reading_order_cer": round(aro / an, 4) if an else None, + "routeA_same_pages_order_free_cer": round(aof / an, 4) if an else None, + "per_page": per}) +json.dump(res, open(a.out, "w", encoding="utf-8"), ensure_ascii=False, indent=1) +for c in res["cells"]: + print(c["set"], c["prompt"], "pages", c["pages"], "B1 ro/of", c["B1_reading_order_cer"], c["B1_order_free_cer"], + "routeA ro/of", c["routeA_same_pages_reading_order_cer"], c["routeA_same_pages_order_free_cer"]) diff --git a/scripts/b1_page_check/b1_page_score.sbatch b/scripts/b1_page_check/b1_page_score.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..3c864efb9d092db638f039e171f43b49945590d8 --- /dev/null +++ b/scripts/b1_page_check/b1_page_score.sbatch @@ -0,0 +1,13 @@ +#!/bin/bash +#SBATCH --job-name=b1_page_score +#SBATCH --partition=ZEN4 +#SBATCH --cpus-per-task=2 +#SBATCH --mem=8G +#SBATCH --time=00:10:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +set -u +CODE=/path/to/TURKIC_OCR_CODE +D=/path/to/TURKIC_OCR_DATA +$CODE/.venv_kraken/bin/python -I $CODE/scripts/b1_page_check/b1_page_score.py --dir $D/outputs/r5/b1_page_check \ + --routeA_dir $D/outputs/r5/linedet/det_eval --out $D/outputs/r5/b1_page_check/score.json +echo "=== exit $? $(date -u)" diff --git a/scripts/b1_page_check/base_page_check.sbatch b/scripts/b1_page_check/base_page_check.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..143671483b714b365ec1335100f0d7deb3b2e57a --- /dev/null +++ b/scripts/b1_page_check/base_page_check.sbatch @@ -0,0 +1,25 @@ +#!/bin/bash +#SBATCH --job-name=base_page_check +#SBATCH --partition=ZEN4 +#SBATCH --cpus-per-task=16 +#SBATCH --mem=48G +#SBATCH --time=00:40:00 +#SBATCH --array=0-5 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%A_%a.out +# The original PaddleOCR-VL 1.6 (the pinned copy B1 was fine-tuned from) on the same pages as b1_page_check. +# Task t: prompt = spot (t<4) or ocr (t>=4, generated pages only); set = gen (t%4<2) or school; chunk = t%2. +set -u +CODE=/path/to/TURKIC_OCR_CODE +D=/path/to/TURKIC_OCR_DATA +P=$D/data/processed/r5_linedet_det +OUT=$D/outputs/r5/b1_page_check +mkdir -p $OUT +t=$SLURM_ARRAY_TASK_ID +if [ $t -lt 4 ]; then PR=spot; else PR=ocr; fi +if [ $((t % 4)) -lt 2 ]; then S=gen; PAGES=$P/gen/pages_gen_val.tsv; STRIDE=30; else S=school; PAGES=$P/school2/pages_school_val.tsv; STRIDE=15; fi +C=$((t % 2)) +export HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 OMP_NUM_THREADS=16 +hostname; date -u +$CODE/.venv_vlm/bin/python -I $CODE/scripts/b1_page_check/b1_page_check.py --model $D/hf_cache/j2_models/paddleocr_vl_1_6 \ + --pages $PAGES --stride $STRIDE --n 10 --chunk $C --chunks 2 --prompt $PR --out $OUT/${S}_base${PR}_c${C}.jsonl --stop_utc 03:42 --threads 16 +echo "=== exit $? $(date -u)" diff --git a/scripts/b1_page_check/detb1_page_check.py b/scripts/b1_page_check/detb1_page_check.py new file mode 100644 index 0000000000000000000000000000000000000000..36cd2db1eafdd072877c3b00d031e8703e1aa07c --- /dev/null +++ b/scripts/b1_page_check/detb1_page_check.py @@ -0,0 +1,99 @@ +"""Line detector + B1 on the same sampled validation pages as b1_page_check.py. + +The detector boxes are the stored YOLO11s stage-2 boxes from the route A run (det_eval e2e_yolo_s2_*_A1_long_pages.jsonl), +so detection is identical to route A and only the reader changes (A1 -> B1). Reading order, crop margins and the school +full-resolution lookup are copied from linedet.det_eval. B1 reads each crop with its training instruction, greedy, bf16 on +CPU, at most 192 new tokens per line (vlm_common.MAXNEW['line']). + +usage: detb1_page_check.py --set gen|school --pages TSV --stride K --n 10 --chunk C --chunks 2 --routeA JSONL --out JSONL +""" +import argparse +import json +import os +import sys +import time +import unicodedata + +ap = argparse.ArgumentParser() +ap.add_argument("--set", required=True) +ap.add_argument("--pages", required=True) +ap.add_argument("--stride", type=int, required=True) +ap.add_argument("--n", type=int, default=10) +ap.add_argument("--chunk", type=int, default=0) +ap.add_argument("--chunks", type=int, default=1) +ap.add_argument("--routeA", required=True) +ap.add_argument("--model", required=True) +ap.add_argument("--out", required=True) +ap.add_argument("--threads", type=int, default=16) +ap.add_argument("--vlma", default="/path/to/TURKIC_OCR_CODE/scripts/r5_vlma") +a = ap.parse_args() +assert "test" not in os.path.basename(a.pages).lower() + +sys.path.insert(0, a.vlma) +import torch # noqa: E402 +from PIL import Image # noqa: E402 + +import vlm_common as vc # noqa: E402 + +torch.set_num_threads(a.threads) +SCHOOL = "/path/to/TURKIC_OCR_DATA/data/raw/school_notebooks_ru" + + +def school_orig(pid): + sp, num = pid.split("_")[1], int(pid.split("_")[2]) + d = json.load(open("%s/annotations_%s.json" % (SCHOOL, sp), encoding="utf-8")) + fn = {im["id"]: im["file_name"] for im in d["images"]}[num] + return "%s/val_test_images/%s/%s" % (SCHOOL, sp, fn) + + +with open(a.pages, encoding="utf-8") as f: + hdr = f.readline().rstrip("\n").split("\t") + pages = [dict(zip(hdr, ln.rstrip("\n").split("\t"))) for ln in f] +pages = pages[::a.stride][:a.n][a.chunk::a.chunks] +det = {} +for ln in open(a.routeA, encoding="utf-8"): + r = json.loads(ln) + det[r["id"]] = r["boxes"] + +proc, tok = vc.load_processor("paddleocr_vl_1_6", a.model) +tok.padding_side = "left" +model = vc.load_model("paddleocr_vl_1_6", a.model, torch.bfloat16) +model.eval() +gc, stops, stop_set = vc.gen_setup(model, tok) +tmpl_kw = vc.template_kwargs(proc, tok) +dev = torch.device("cpu") + +with open(a.out, "a", encoding="utf-8") as fo: + for pg in pages: + t1 = time.time() + boxes = det[pg["id"]] + if pg["id"].startswith("school_"): + big = Image.open(school_orig(pg["id"])).convert("RGB") + sc = 1.0 / float(pg["scale"]) + else: + big, sc = Image.open(pg["image"]).convert("RGB"), 1.0 + W, H = big.size + # M28 reading order, as det_eval: (centre_y // 15, centre_x) in the 1280 px page + order = sorted(range(len(boxes)), key=lambda i: (int(((boxes[i][1] + boxes[i][3]) / 2) // 15), (boxes[i][0] + boxes[i][2]) / 2)) + crops = [] + for i in order: + x0, y0, x1, y1 = boxes[i] + hh = y1 - y0 + x0, x1 = x0 - 0.01 * (x1 - x0) - 2, x1 + 0.01 * (x1 - x0) + 2 + y0, y1 = y0 - 0.1 * hh - 1, y1 + 0.1 * hh + 1 + X0, Y0, X1, Y1 = [int(round(v * sc)) for v in (max(x0, 0), max(y0, 0), x1, y1)] + X0, Y0, X1, Y1 = max(X0, 0), max(Y0, 0), min(X1, W), min(Y1, H) + if X1 - X0 < 4 or Y1 - Y0 < 4: + continue + crops.append(big.crop((X0, Y0, X1, Y1))) + hyp = [] + for s0 in range(0, len(crops), 16): + recs = vc.generate_batch("paddleocr_vl_1_6", model, proc, tok, crops[s0:s0 + 16], vc.MAXNEW["line"], tmpl_kw, gc, stop_set, dev) + hyp += [" ".join(unicodedata.normalize("NFC", r["raw"]).split()) for r in recs] + rec = {"id": pg["id"], "prompt": "detB1", "n_boxes": len(boxes), "n_new": 0, "stopped": True, + "seconds": round(time.time() - t1, 1), "hyp_lines": [h for h in hyp if h], + "ref_lines": json.loads(pg["ref_lines_json"]) if pg.get("ref_lines_json") else []} + fo.write(json.dumps(rec, ensure_ascii=False) + "\n") + fo.flush() + print(pg["id"], "boxes", len(boxes), "%.1f s" % rec["seconds"], flush=True) +print("done", flush=True) diff --git a/scripts/b1_page_check/detb1_page_check.sbatch b/scripts/b1_page_check/detb1_page_check.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..28ffbf646c82b0e05bf94a7b23539be8f88e151f --- /dev/null +++ b/scripts/b1_page_check/detb1_page_check.sbatch @@ -0,0 +1,24 @@ +#!/bin/bash +#SBATCH --job-name=detb1_page_check +#SBATCH --partition=ZEN4 +#SBATCH --cpus-per-task=16 +#SBATCH --mem=48G +#SBATCH --time=00:35:00 +#SBATCH --array=0-7 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%A_%a.out +# Task t: set = gen (t<4) or school; chunk = t%4 of 4 (2-3 pages each). +set -u +CODE=/path/to/TURKIC_OCR_CODE +D=/path/to/TURKIC_OCR_DATA +P=$D/data/processed/r5_linedet_det +E=$D/outputs/r5/linedet/det_eval +OUT=$D/outputs/r5/b1_page_check +t=$SLURM_ARRAY_TASK_ID +if [ $t -lt 4 ]; then S=gen; PAGES=$P/gen/pages_gen_val.tsv; STRIDE=30; else S=school; PAGES=$P/school2/pages_school_val.tsv; STRIDE=15; fi +C=$((t % 4)) +export HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 OMP_NUM_THREADS=16 +hostname; date -u +$CODE/.venv_vlm/bin/python -I $CODE/scripts/b1_page_check/detb1_page_check.py --set $S --pages $PAGES --stride $STRIDE --n 10 \ + --chunk $C --chunks 4 --routeA $E/e2e_yolo_s2_${S}_val_A1_long_pages.jsonl --model $D/checkpoints/r5/paddleocr_vl_1_6/leader \ + --out $OUT/${S}_detB1_c${C}.jsonl --threads 16 +echo "=== exit $? $(date -u)" diff --git a/scripts/j2/build_screen_set.py b/scripts/j2/build_screen_set.py new file mode 100644 index 0000000000000000000000000000000000000000..35d8d8234b2c902f56f541b2c5ddd10b18520a5a --- /dev/null +++ b/scripts/j2/build_screen_set.py @@ -0,0 +1,38 @@ +"""Build screen_set_v1.tsv by screen_rule_v1.txt. Reads only validation.tsv. + +usage: build_screen_set.py VALIDATION_TSV OUT_TSV +""" +import collections +import hashlib +import sys + +val_path, out_path = sys.argv[1], sys.argv[2] +assert val_path.endswith("kohtd_split_v1/validation.tsv"), "only the validation split may be read" + +rows = [] +with open(val_path, encoding="utf-8", newline="") as f: + hdr = f.readline().rstrip("\n").split("\t") + assert hdr == ["crop_file", "form_id", "label", "key_type"], hdr + for line in f: + parts = line.rstrip("\n").split("\t") + assert len(parts) == 4, repr(line) + rows.append(parts) + +by_form = collections.defaultdict(list) +for crop_file, form_id, label, key_type in rows: + h = hashlib.sha256(("J11-screen-v1:" + crop_file).encode("utf-8")).hexdigest() + by_form[form_id].append((h, crop_file, label)) + +out = [] +for form_id in sorted(by_form, key=lambda x: int(x)): + items = sorted(by_form[form_id]) # ascending hex digest as text + for h, crop_file, label in items[:15]: + out.append((crop_file, form_id, label)) + +with open(out_path, "w", encoding="utf-8", newline="") as f: + f.write("crop_file\tform_id\tlabel\n") + for crop_file, form_id, label in out: + f.write(f"{crop_file}\t{form_id}\t{label}\n") + +print("forms", len(by_form), "crops in list", len(out)) +print("forms with fewer than 15 crops", sum(1 for v in by_form.values() if len(v) < 15)) diff --git a/scripts/j2/check_images_kwargs.py b/scripts/j2/check_images_kwargs.py new file mode 100644 index 0000000000000000000000000000000000000000..c63ca9133cd7bfc044a36b473f6e1368c2f2bf56 --- /dev/null +++ b/scripts/j2/check_images_kwargs.py @@ -0,0 +1,26 @@ +"""Does images_kwargs (size) reach the image processor in apply_chat_template? Processor only, one crop, no model. +usage: check_images_kwargs.py MODELS_DIR PROMPTS_JSON IMG_DIR CROP_FILE short [short ...]""" +import json +import os +import sys + +os.environ["HF_HUB_OFFLINE"] = "1" +import transformers +from PIL import Image + +models_dir, prompts_json, img_dir, crop = sys.argv[1:5] +P = json.load(open(prompts_json, encoding="utf-8")) +im = Image.open(os.path.join(img_dir, crop)).convert("RGB") +print("crop size", im.size) +for short in sys.argv[5:]: + proc = transformers.AutoProcessor.from_pretrained(os.path.join(models_dir, short), trust_remote_code=False) + ik = P[short].get("images_kwargs") + if ik and ik["size"]["shortest_edge"] == "MIN_PIXELS_FROM_PROCESSOR": + sz = proc.image_processor.size + ik["size"]["shortest_edge"] = int(sz["shortest_edge"] if isinstance(sz, dict) else sz.shortest_edge) + txt = [{"type": "text", "text": P[short]["prompt"]}] if P[short]["prompt"] else [] + conv = [[{"role": "user", "content": [{"type": "image", "image": im}] + txt}]] + for label, kw in (("without images_kwargs", {}), ("with images_kwargs", {"images_kwargs": ik} if ik else {})): + out = proc.apply_chat_template(conv, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", padding=True, **kw) + grid = out.get("image_grid_thw") + print(short, label, "input_ids", tuple(out["input_ids"].shape), "image_grid_thw", None if grid is None else grid.tolist(), "ik", ik) diff --git a/scripts/j2/codec_238.json b/scripts/j2/codec_238.json new file mode 100644 index 0000000000000000000000000000000000000000..4029465d3f57672b5e3d2f8d1f2523acd5babae7 --- /dev/null +++ b/scripts/j2/codec_238.json @@ -0,0 +1,244 @@ +{ +"source": "project records R3/O1_golden_middle/work/codec_count.json, key designed_codepoints (own count of 18-19 Nov, O1; listed in docs/research_artifacts/round_2026-11-19/O1_golden_middle/variants.json planning_number as 238 output symbols, NFC form)", +"count": 238, +"codepoints": [ +"U+0020", +"U+0021", +"U+0022", +"U+0023", +"U+0024", +"U+0025", +"U+0026", +"U+0027", +"U+0028", +"U+0029", +"U+002A", +"U+002B", +"U+002C", +"U+002D", +"U+002E", +"U+002F", +"U+0030", +"U+0031", +"U+0032", +"U+0033", +"U+0034", +"U+0035", +"U+0036", +"U+0037", +"U+0038", +"U+0039", +"U+003A", +"U+003B", +"U+003C", +"U+003D", +"U+003E", +"U+003F", +"U+0040", +"U+0041", +"U+0042", +"U+0043", +"U+0044", +"U+0045", +"U+0046", +"U+0047", +"U+0048", +"U+0049", +"U+004A", +"U+004B", +"U+004C", +"U+004D", +"U+004E", +"U+004F", +"U+0050", +"U+0051", +"U+0052", +"U+0053", +"U+0054", +"U+0055", +"U+0056", +"U+0057", +"U+0058", +"U+0059", +"U+005A", +"U+005B", +"U+005C", +"U+005D", +"U+005E", +"U+005F", +"U+0060", +"U+0061", +"U+0062", +"U+0063", +"U+0064", +"U+0065", +"U+0066", +"U+0067", +"U+0068", +"U+0069", +"U+006A", +"U+006B", +"U+006C", +"U+006D", +"U+006E", +"U+006F", +"U+0070", +"U+0071", +"U+0072", +"U+0073", +"U+0074", +"U+0075", +"U+0076", +"U+0077", +"U+0078", +"U+0079", +"U+007A", +"U+007B", +"U+007C", +"U+007D", +"U+007E", +"U+00A7", +"U+00AB", +"U+00B0", +"U+00BB", +"U+00C4", +"U+00C7", +"U+00D6", +"U+00DC", +"U+00DD", +"U+00E4", +"U+00E7", +"U+00F6", +"U+00FC", +"U+00FD", +"U+011E", +"U+011F", +"U+0130", +"U+0131", +"U+0147", +"U+0148", +"U+015E", +"U+015F", +"U+017D", +"U+017E", +"U+018F", +"U+0259", +"U+02BB", +"U+02BC", +"U+0401", +"U+0404", +"U+0406", +"U+0407", +"U+040E", +"U+0410", +"U+0411", +"U+0412", +"U+0413", +"U+0414", +"U+0415", +"U+0416", +"U+0417", +"U+0418", +"U+0419", +"U+041A", +"U+041B", +"U+041C", +"U+041D", +"U+041E", +"U+041F", +"U+0420", +"U+0421", +"U+0422", +"U+0423", +"U+0424", +"U+0425", +"U+0426", +"U+0427", +"U+0428", +"U+0429", +"U+042A", +"U+042B", +"U+042C", +"U+042D", +"U+042E", +"U+042F", +"U+0430", +"U+0431", +"U+0432", +"U+0433", +"U+0434", +"U+0435", +"U+0436", +"U+0437", +"U+0438", +"U+0439", +"U+043A", +"U+043B", +"U+043C", +"U+043D", +"U+043E", +"U+043F", +"U+0440", +"U+0441", +"U+0442", +"U+0443", +"U+0444", +"U+0445", +"U+0446", +"U+0447", +"U+0448", +"U+0449", +"U+044A", +"U+044B", +"U+044C", +"U+044D", +"U+044E", +"U+044F", +"U+0451", +"U+0454", +"U+0456", +"U+0457", +"U+045E", +"U+0490", +"U+0491", +"U+0492", +"U+0493", +"U+0494", +"U+0495", +"U+0496", +"U+0497", +"U+0498", +"U+0499", +"U+049A", +"U+049B", +"U+04A0", +"U+04A1", +"U+04A2", +"U+04A3", +"U+04A4", +"U+04A5", +"U+04AA", +"U+04AB", +"U+04AE", +"U+04AF", +"U+04B0", +"U+04B1", +"U+04B2", +"U+04B3", +"U+04BA", +"U+04BB", +"U+04D8", +"U+04D9", +"U+04E8", +"U+04E9", +"U+2013", +"U+2014", +"U+2018", +"U+2019", +"U+201C", +"U+201D", +"U+201E", +"U+2026", +"U+2116" +] +} \ No newline at end of file diff --git a/scripts/j2/collect.py b/scripts/j2/collect.py new file mode 100644 index 0000000000000000000000000000000000000000..a834ec2e8939121d8a3109f38a2e586b0d10770c --- /dev/null +++ b/scripts/j2/collect.py @@ -0,0 +1,152 @@ +"""Turn finished (or partly finished) J2 outputs into results.tsv. Run on the cluster (the per-crop files hold labels and stay there). + +usage: collect.py OUT_ROOT SCREEN_SET_TSV SCORELIB_PY RESULTS_TSV [model ...] +OUT_ROOT = DATA/outputs/j11_stage1_kohtd (model folders s1/ s2/ s3/ with preds.jsonl, timing.jsonl, meta.json). +Robust to a job killed by its time limit: a half-written last line of preds.jsonl or timing.jsonl is skipped and counted +(bad_lines); if meta.json was never written the row is filled from timing.jsonl, the screen set and loadtest/.json. +Every speed and memory column carries the suffix _H100_not_5090: all figures come from one H100, not from an RTX 5090. +A row is complete when crops_done == crops_in_list; the column complete says so. +""" +import importlib.util +import json +import os +import sys + +out_root, screen_set, scorelib_py, results_tsv = sys.argv[1:5] +only = set(sys.argv[5:]) +assert "screen_set_v1.tsv" in screen_set +spec = importlib.util.spec_from_file_location("scorelib", scorelib_py) +sl = importlib.util.module_from_spec(spec) +spec.loader.exec_module(sl) + +labels = {} +with open(screen_set, encoding="utf-8", newline="") as f: + f.readline() + for line in f: + c, form, lab = line.rstrip("\n").split("\t") + labels[c] = lab + +prompts_path = os.path.join(os.path.dirname(os.path.abspath(scorelib_py)), "prompts.json") +prompts = json.load(open(prompts_path, encoding="utf-8")) if os.path.exists(prompts_path) else {} + + +def prompt_source(model): + note = (prompts.get(model) or {}).get("note", "") + if not note: + return "unknown" + if note.startswith("NOT FROM THE CARD"): + return "J2 departure (not from the card)" + if "closest documented" in note or "nearest" in note: + return "nearest documented (page prompt)" + return "card" + + +def read_jsonl(path): + recs, bad = [], 0 + if os.path.exists(path): + for line in open(path, encoding="utf-8"): + if not line.strip(): + continue + try: + recs.append(json.loads(line)) + except Exception: # noqa: BLE001 (half-written line of a killed job) + bad += 1 + return recs, bad + + +COLS = ["model", "scale", "complete", "prompt_source", "version_revision", "params_unique", "gpu", "crops_done", "crops_in_list", + "cer_pooled", "cer_mean", "cer_mean_cap1", "exact_match", "hr2_ins_per_ref_char", "hr3_share_refs_ge5", "hr4_loop_share", + "empty_share", "other_script_share", "ref_other_script_share", "cer_pooled_casefold", "exact_casefold", "hit_cap_share", + "mean_image_tokens", "crops_per_s_H100_not_5090", "crops_per_s_excl_first_batch_H100_not_5090", + "crops_per_s_median_full_batch_H100_not_5090", "new_tokens_per_s_H100_not_5090", "disk_read_s_per_crop", + "peak_gpu_mem_GiB_H100_not_5090", "batch_size", "job_ids", "errors", "bad_lines", "best_of_scales_pooled_cer", "scales_finished"] +rows = [] +by_model = {} +for model in sorted(os.listdir(out_root)): + mdir = os.path.join(out_root, model) + if only and model not in only: + continue + if not os.path.isdir(os.path.join(mdir, "s1")) or model in ("eligibility", "loadtest", "keyaudit"): + continue + lt_path = os.path.join(out_root, "loadtest", model + ".json") + lt = json.load(open(lt_path)) if os.path.exists(lt_path) else {} + for scale in (1, 2, 3): + d = os.path.join(mdir, f"s{scale}") + if not os.path.exists(os.path.join(d, "preds.jsonl")): + continue + meta = json.load(open(os.path.join(d, "meta.json"))) if os.path.exists(os.path.join(d, "meta.json")) else {} + pred_recs, bad1 = read_jsonl(os.path.join(d, "preds.jsonl")) + tim, bad2 = read_jsonl(os.path.join(d, "timing.jsonl")) + preds = {} + for r in pred_recs: # keep the last record per crop + if r.get("crop_file") in labels: + preds[r["crop_file"]] = r + scored, det = [], [] + for c, r in preds.items(): + s = sl.score_crop(labels[c], r["raw"]) + scored.append(s) + det.append((c, s, r)) + agg = sl.aggregate(scored) + batch_size = meta.get("batch_size") or (max((t["n"] for t in tim), default=None)) + job_ids = meta.get("job_ids") or sorted({t["job_id"] for t in tim if t.get("job_id")}) + tot_n = sum(t["n"] for t in tim) + tot_t = sum(t["t_pre"] + t["t_gen"] for t in tim) + tim2 = tim[1:] + tot_n2 = sum(t["n"] for t in tim2) + tot_t2 = sum(t["t_pre"] + t["t_gen"] for t in tim2) + gen_t = sum(t["t_gen"] for t in tim) + full = sorted(t["n"] / (t["t_pre"] + t["t_gen"]) for t in tim if t["n"] == batch_size and (t["t_pre"] + t["t_gen"]) > 0) + median_full = full[len(full) // 2] if full else None # steady speed: no warm-up batch, no odd last batch + n_list = meta.get("crops_in_list") or len(labels) + row = { + "model": model, "scale": scale, "complete": "yes" if len(preds) == n_list else "no (partial)", + "prompt_source": prompt_source(model), + "version_revision": meta.get("repo_revision") or lt.get("revision"), + "params_unique": meta.get("params_unique") or lt.get("model_params_unique"), + "gpu": meta.get("gpu") or "unknown (no meta.json: run was cut off)", "crops_done": len(preds), "crops_in_list": n_list, + "cer_pooled": agg.get("cer_pooled"), "cer_mean": agg.get("cer_mean"), "cer_mean_cap1": agg.get("cer_mean_cap1"), + "exact_match": agg.get("exact"), "hr2_ins_per_ref_char": agg.get("hr2_ins_per_ref_char"), + "hr3_share_refs_ge5": agg.get("hr3_share_refs_ge5"), "hr4_loop_share": agg.get("hr4_loop_share"), + "empty_share": agg.get("empty_share"), "other_script_share": agg.get("other_script_share"), + "ref_other_script_share": agg.get("ref_other_script_share"), "cer_pooled_casefold": agg.get("cer_pooled_casefold"), + "exact_casefold": agg.get("exact_casefold"), + "hit_cap_share": sum(1 for r in preds.values() if r.get("hit_cap")) / max(1, len(preds)), + "mean_image_tokens": (sum(r["n_img_tokens"] for r in preds.values() if r.get("n_img_tokens", -1) >= 0) / + max(1, sum(1 for r in preds.values() if r.get("n_img_tokens", -1) >= 0))), + "crops_per_s_H100_not_5090": (tot_n / tot_t) if tot_t else None, + "crops_per_s_excl_first_batch_H100_not_5090": (tot_n2 / tot_t2) if tot_t2 else None, + "crops_per_s_median_full_batch_H100_not_5090": median_full, + "new_tokens_per_s_H100_not_5090": (sum(t["new_tokens"] for t in tim) / gen_t) if gen_t else None, + "disk_read_s_per_crop": (sum(t.get("t_img", 0) for t in tim) / tot_n) if tot_n else None, + "peak_gpu_mem_GiB_H100_not_5090": (meta.get("peak_gpu_mem_allocated_bytes", 0) / 2 ** 30) if meta.get("peak_gpu_mem_allocated_bytes") else None, + "batch_size": batch_size, "job_ids": ",".join(job_ids), "errors": meta.get("errors"), "bad_lines": bad1 + bad2, + } + rows.append(row) + by_model.setdefault(model, {})[scale] = row + with open(os.path.join(d, "scored.tsv"), "w", encoding="utf-8") as f: # stays on the cluster (holds labels) + f.write("crop_file\tref\tout\tdist\tcer\texact\tloop\thr3\tempty\tn_new\thit_cap\tn_img_tokens\n") + for c, s, r in det: + f.write("\t".join(str(x) for x in [c, s["ref"], s["hyp"], s["dist"], round(s["cer"], 4), int(s["exact"]), int(s["loop"]), + int(s["hr3"]), int(s["empty"]), r["n_new"], int(r["hit_cap"]), r["n_img_tokens"]]) + "\n") + +for model, sc in by_model.items(): + full_rows = [r for r in sc.values() if r["complete"] == "yes"] + best = min((r["cer_pooled"] for r in full_rows), default=None) + for r in sc.values(): + r["best_of_scales_pooled_cer"] = best # minimum over the finished scales of this model + r["scales_finished"] = ",".join(str(s) for s, x in sorted(sc.items()) if x in full_rows) + + +def fmt(v): + if v is None: + return "" + if isinstance(v, float): + return f"{v:.4f}" + return str(v) + + +with open(results_tsv, "w", encoding="utf-8") as f: + f.write("\t".join(COLS) + "\n") + for r in rows: + f.write("\t".join(fmt(r.get(c)) for c in COLS) + "\n") +print("rows", len(rows), "complete", sum(1 for r in rows if r["complete"] == "yes"), "->", results_tsv) diff --git a/scripts/j2/contrast_stretch.py b/scripts/j2/contrast_stretch.py new file mode 100644 index 0000000000000000000000000000000000000000..49cf7a55019282dd5e0cb4ea6342374501415c73 --- /dev/null +++ b/scripts/j2/contrast_stretch.py @@ -0,0 +1,18 @@ +"""Per-crop contrast stretch for the J2 contrast control. One function; it changes the grey levels and nothing else. + +contrast_stretch(img): the 1st and 99th percentile of the crop's grey (PIL 'L' conversion) are mapped to 0 and 255; the same +linear map is applied to the three colour channels, so colour relations are kept; values are clipped to 0..255. Size and mode +(RGB) do not change. A crop with a grey range below 1 level is returned unchanged (as RGB). +""" +import numpy as np +from PIL import Image + + +def contrast_stretch(img): + rgb = np.asarray(img.convert("RGB"), dtype=np.float64) + grey = np.asarray(img.convert("L"), dtype=np.float64) + lo, hi = np.percentile(grey, 1), np.percentile(grey, 99) + if hi - lo < 1.0: + return img.convert("RGB") + out = np.clip((rgb - lo) * (255.0 / (hi - lo)), 0.0, 255.0) + return Image.fromarray(np.rint(out).astype(np.uint8)) diff --git a/scripts/j2/control_report.py b/scripts/j2/control_report.py new file mode 100644 index 0000000000000000000000000000000000000000..e760df29809b58be6091e2273c2b04ce042cfacb --- /dev/null +++ b/scripts/j2/control_report.py @@ -0,0 +1,56 @@ +"""Score the positive control with the screen's scorelib (same post-processing, same CER) and write positive_control.tsv. +usage: control_report.py CONTROL_LIST SCORELIB_PY OUT_TSV label=OUT_ROOT [label=OUT_ROOT ...] +label is cpu or gpu; OUT_ROOT holds /s1/preds.jsonl. +""" +import importlib.util +import json +import os +import sys + +control_list, scorelib_py, out_tsv = sys.argv[1:4] +roots = [a.split("=", 1) for a in sys.argv[4:]] +spec = importlib.util.spec_from_file_location("scorelib", scorelib_py) +sl = importlib.util.module_from_spec(spec) +spec.loader.exec_module(sl) + +rows = [] +with open(control_list, encoding="utf-8", newline="") as f: + f.readline() + for line in f: + c, i, lab = line.rstrip("\n").split("\t") + rows.append((c, lab)) +label = dict(rows) +order = [c for c, _ in rows] +sample_idx = {40: [order[i] for i in (0, 1, 100, 101, 102)], 80: [order[i] for i in (200, 201, 300, 301, 302)]} # 2 kk + 3 ky... see below +# five fixed crops per height: kk 1, kk 2, ky 1, ky 2, ky 3 (list order: h40 kk, h40 ky, h80 kk, h80 ky) +out = ["model\tdevice\theight_px\tcrops_scored\tcer_pooled\texact_match\tcer_pooled_kk\tcer_pooled_ky\thr4_loop_share\tempty_share\tfive_raw_outputs (reference => raw output)"] +for dev, root in roots: + for model in sorted(os.listdir(root)): + pp = os.path.join(root, model, "s1", "preds.jsonl") + if not os.path.exists(pp): + continue + preds = {} + for line in open(pp, encoding="utf-8"): + try: + r = json.loads(line) + except Exception: # noqa: BLE001 + continue + preds[r["crop_file"]] = r + for H in (40, 80): + sc, by_lang = [], {"kk": [], "ky": []} + for c in order: + if f"_h{H}_" in c and c in preds: + s = sl.score_crop(label[c], preds[c]["raw"]) + sc.append(s) + by_lang[c[:2]].append(s) + if not sc: + continue + a = sl.aggregate(sc) + ak = sl.aggregate(by_lang["kk"]) if by_lang["kk"] else {} + ay = sl.aggregate(by_lang["ky"]) if by_lang["ky"] else {} + five = " | ".join(f"{label[c]} => {preds[c]['raw']!r}" for c in sample_idx[H] if c in preds) + out.append("\t".join([model, dev, str(H), str(len(sc)), f"{a['cer_pooled']:.4f}", f"{a['exact']:.4f}", + f"{ak.get('cer_pooled', float('nan')):.4f}", f"{ay.get('cer_pooled', float('nan')):.4f}", + f"{a['hr4_loop_share']:.4f}", f"{a['empty_share']:.4f}", five])) +open(out_tsv, "w", encoding="utf-8").write("\n".join(out) + "\n") +print("rows", len(out) - 1) diff --git a/scripts/j2/control_run_cpu.sbatch b/scripts/j2/control_run_cpu.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..31e5a1726be837d9b3a17fad61de794051ba5653 --- /dev/null +++ b/scripts/j2/control_run_cpu.sbatch @@ -0,0 +1,24 @@ +#!/bin/bash +#SBATCH --job-name=j2_ctl_cpu +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=16 +#SBATCH --mem=64G +#SBATCH --time=06:00:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# J2 positive control on ZEN4 CPU: the SAME run_screen.py, prompts, batch size 16, 1x, bf16, greedy, 48 new tokens, on the 400 +# printed control images. Output folder: DATA/outputs/j11_positive_control/out_cpu. usage: sbatch control_run_cpu.sbatch short [short ...] +set -u +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +export HF_HUB_OFFLINE=1 +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN || true +CT=$DATA/outputs/j11_positive_control +mkdir -p $CT/out_cpu +for M in "$@"; do + echo "=== $M $(date -u +%H:%M:%S)" + $CODE/.venv_vlm/bin/python -I $CODE/scripts/j2/run_screen.py $M $DATA/hf_cache/j2_models $CODE/scripts/j2/prompts.json \ + $CT/positive_control_screen_set_v1.tsv $CT/img $CT/out_cpu --device cpu --threads 16 --batch-size 16 --max-new-tokens 48 --scales 1 2>&1 | grep -v -E "Loading weights|^\s*$" | tail -6 +done +echo "[j2_ctl_cpu] done $(date -u +%H:%M:%S)" diff --git a/scripts/j2/control_run_gpu.sbatch b/scripts/j2/control_run_gpu.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..a4942c0550278ef21ed87bb19f23e55da5cde11d --- /dev/null +++ b/scripts/j2/control_run_gpu.sbatch @@ -0,0 +1,26 @@ +#!/bin/bash +#SBATCH --job-name=j2_ctl_gpu +#SBATCH --partition=H100 +#SBATCH --qos=nu-h100 +#SBATCH --gres=gpu:h100:1 +#SBATCH --cpus-per-task=16 +#SBATCH --mem=96G +#SBATCH --time=01:30:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# J2 positive control on one H100: the SAME run_screen.py, prompts, batch size 16, 1x, bf16, greedy, 48 new tokens, on the 400 +# printed control images. Output folder: DATA/outputs/j11_positive_control/out_gpu. usage: sbatch control_run_gpu.sbatch short [short ...] +set -u +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +export HF_HUB_OFFLINE=1 +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN || true +CT=$DATA/outputs/j11_positive_control +mkdir -p $CT/out_gpu +echo "job $SLURM_JOB_ID on $(hostname)" +nvidia-smi --query-gpu=name,driver_version,memory.total --format=csv +for M in "$@"; do + echo "=== $M $(date -u +%H:%M:%S)" + $CODE/.venv_vlm/bin/python -I $CODE/scripts/j2/run_screen.py $M $DATA/hf_cache/j2_models $CODE/scripts/j2/prompts.json \ + $CT/positive_control_screen_set_v1.tsv $CT/img $CT/out_gpu --device cuda --batch-size 16 --max-new-tokens 48 --scales 1 2>&1 | grep -v -E "Loading weights|^\s*$" | tail -6 +done +echo "[j2_ctl_gpu] done $(date -u +%H:%M:%S)" diff --git a/scripts/j2/controls2_report.py b/scripts/j2/controls2_report.py new file mode 100644 index 0000000000000000000000000000000000000000..f1cf3ea6925eebccf23fdbbf95ea63e2eb2a61f8 --- /dev/null +++ b/scripts/j2/controls2_report.py @@ -0,0 +1,96 @@ +"""Score the two small controls (contrast, handwriting fonts) with the screen's scorelib and write controls_2.tsv. +A printed-text row (PT Sans, 40 px, from the first positive control) is scored with the same code for comparison. + +usage: controls2_report.py C2_DIR PRINTED_LIST PRINTED_OUT_ROOT SCORELIB_PY OUT_TSV +C2_DIR holds contrast_stored_/contrast_stretch_/fonts_screen_set_v1.tsv and out_stored/ out_stretch/ out_fonts/. +""" +import importlib.util +import json +import os +import sys + +c2, printed_list, printed_root, scorelib_py, out_tsv = sys.argv[1:6] +spec = importlib.util.spec_from_file_location("scorelib", scorelib_py) +sl = importlib.util.module_from_spec(spec) +spec.loader.exec_module(sl) + + +def read_list(path): + rows = [] + with open(path, encoding="utf-8", newline="") as f: + f.readline() + for line in f: + c, i, lab = line.rstrip("\n").split("\t") + rows.append((c, lab)) + return rows + + +def read_preds(path): + preds = {} + if os.path.exists(path): + for line in open(path, encoding="utf-8"): + try: + r = json.loads(line) + except Exception: # noqa: BLE001 + continue + preds[r["crop_file"]] = r + return preds + + +def is_lang(c, k): + return c.startswith(k + "_") or f"_{k}_" in c + + +def block(name, model, rows, preds, pick): + sc, lang = [], {"kk": [], "ky": []} + for c, lab in rows: + if c in preds: + s = sl.score_crop(lab, preds[c]["raw"]) + sc.append(s) + for k in lang: + if is_lang(c, k): + lang[k].append(s) + if not sc: + return None + a = sl.aggregate(sc) + ak = sl.aggregate(lang["kk"]) if lang["kk"] else {} + ay = sl.aggregate(lang["ky"]) if lang["ky"] else {} + lab = dict(rows) + five = " | ".join(f"{lab[c]} => {preds[c]['raw']!r}" for c in pick if c in preds) + fmt = lambda d, k: f"{d[k]:.4f}" if k in d else "" # noqa: E731 + return "\t".join([name, model, str(len(sc)), f"{a['cer_pooled']:.4f}", f"{a['cer_mean_cap1']:.4f}", f"{a['exact']:.4f}", + fmt(ak, "cer_pooled"), fmt(ay, "cer_pooled"), f"{a['hr4_loop_share']:.4f}", f"{a['empty_share']:.4f}", + f"{a['other_script_share']:.4f}", five]) + + +def pick5(rows): + names = [c for c, _ in rows] + kk = [c for c in names if is_lang(c, "kk")][:2] + ky = [c for c in names if is_lang(c, "ky")][:3] + return kk + ky + + +out = ["control\tmodel\tcrops_scored\tcer_pooled\tcer_capped_mean\texact_match\tcer_pooled_kk\tcer_pooled_ky\thr4_loop_share\tempty_share\tother_script_share\tfive_raw_outputs (reference => raw output)"] +models = ["paddleocr_vl_1_6", "qwen3_vl_2b"] +stored, stretch, fonts = (read_list(os.path.join(c2, n)) for n in + ("contrast_stored_screen_set_v1.tsv", "contrast_stretch_screen_set_v1.tsv", "fonts_screen_set_v1.tsv")) +printed40 = [(c, l) for c, l in read_list(printed_list) if "_h40_" in c] +for m in models: + first5 = lambda rows: [c for c, _ in rows[:5]] # noqa: E731 + for name, rows, root in (("A1 KOHTD first 300 crops, as stored", stored, "out_stored"), + ("A2 KOHTD first 300 crops, contrast stretch p1-p99", stretch, "out_stretch")): + r = block(name, m, rows, read_preds(os.path.join(c2, root, m, "s1", "preds.jsonl")), first5(rows)) + if r: + out.append(r) + fp = read_preds(os.path.join(c2, "out_fonts", m, "s1", "preds.jsonl")) + for font, name in (("caveat", "B1 printed words in Caveat (40 px)"), ("badscript", "B2 printed words in Bad Script (40 px)")): + rows = [(c, l) for c, l in fonts if c.startswith(font + "_")] + r = block(name, m, rows, fp, pick5(rows)) + if r: + out.append(r) + r = block("C printed PT Sans 40 px (first positive control)", m, printed40, + read_preds(os.path.join(printed_root, m, "s1", "preds.jsonl")), pick5(printed40)) + if r: + out.append(r) +open(out_tsv, "w", encoding="utf-8").write("\n".join(out) + "\n") +print("rows", len(out) - 1) diff --git a/scripts/j2/controls2_run_cpu.sbatch b/scripts/j2/controls2_run_cpu.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..f93fd8d1a81ef94f72a83857ee63fd8840e1ea8d --- /dev/null +++ b/scripts/j2/controls2_run_cpu.sbatch @@ -0,0 +1,31 @@ +#!/bin/bash +#SBATCH --job-name=j2_c2_run +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=16 +#SBATCH --mem=64G +#SBATCH --time=04:00:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# J2 controls 2 on ZEN4 CPU: the SAME run_screen.py, prompts, batch size 16, 1x, bf16, greedy, 48 new tokens. +# usage: sbatch controls2_run_cpu.sbatch SET:MODEL [SET:MODEL ...] with SET = stored | stretch | fonts +set -u +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +export HF_HUB_OFFLINE=1 +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN || true +C2=$DATA/outputs/j11_controls_2 +KIMG=$DATA/data/processed/kohtd_words_raw/KOHTD_dataset/HK_dataset/img +for PAIR in "$@"; do + SET=${PAIR%%:*}; M=${PAIR##*:} + case $SET in + stored) LIST=$C2/contrast_stored_screen_set_v1.tsv; IMG=$KIMG ;; + stretch) LIST=$C2/contrast_stretch_screen_set_v1.tsv; IMG=$C2/img_stretch ;; + fonts) LIST=$C2/fonts_screen_set_v1.tsv; IMG=$C2/img_fonts ;; + esac + mkdir -p $C2/out_$SET + echo "=== $SET $M $(date -u +%H:%M:%S)" + $CODE/.venv_vlm/bin/python -I $CODE/scripts/j2/run_screen.py $M $DATA/hf_cache/j2_models $CODE/scripts/j2/prompts.json \ + $LIST $IMG $C2/out_$SET --device cpu --threads 16 --batch-size 16 --max-new-tokens 48 --scales 1 2>&1 | grep -v -E "Loading weights|^\s*$" | tail -4 +done +echo "[j2_c2_run] done $(date -u +%H:%M:%S)" diff --git a/scripts/j2/eligibility.py b/scripts/j2/eligibility.py new file mode 100644 index 0000000000000000000000000000000000000000..7d7fddb71d4bea6c6c281d53122d9146188cd54d --- /dev/null +++ b/scripts/j2/eligibility.py @@ -0,0 +1,252 @@ +"""J2 step 2: eligibility facts for the 20 models of screen.list_S. Runs on a ZEN4 node with .venv_vlm. + +Downloads (no token, no .py file) only config, tokenizer, processor, chat template and README files and +reads the file list with sizes from the Hub API. Then, with the pinned transformers release only: + - checks that model_type and architecture are native classes (trust_remote_code is never set), + - builds the native model class on the meta device (no weights) and counts parameters, + - loads the tokenizer and the processor with trust_remote_code=False, + - round-trips the 238 project symbols and all validation labels through the tokenizer (E3). + +usage: eligibility.py MODELS_TSV CODEC_JSON VALIDATION_TSV MODELS_DIR OUT_DIR [only_short ...] +""" +import collections +import json +import os +import sys +import traceback +import unicodedata + +os.environ.setdefault("HF_HUB_DISABLE_TELEMETRY", "1") +for k in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"): + os.environ.pop(k, None) + +models_tsv, codec_json, val_tsv, models_dir, out_dir = sys.argv[1:6] +only = set(sys.argv[6:]) +os.makedirs(out_dir, exist_ok=True) + +import huggingface_hub +import torch +import transformers +from huggingface_hub import HfApi, snapshot_download + +ALLOW = [ + "config.json", "generation_config.json", "preprocessor_config.json", "processor_config.json", + "video_preprocessor_config.json", "tokenizer*", "special_tokens_map.json", "added_tokens.json", + "vocab*", "merges.txt", "chat_template*", "*.jinja", "README.md", "*.safetensors.index.json", +] +WEIGHT_EXT_PICKLE = (".bin", ".pt", ".pth", ".pdparams", ".ckpt", ".pkl", ".msgpack", ".h5", ".onnx", ".gguf") + +codec = json.load(open(codec_json, encoding="utf-8")) +symbols = [chr(int(c[2:], 16)) for c in codec["codepoints"]] +assert len(symbols) == 238 + +labels = [] +with open(val_tsv, encoding="utf-8", newline="") as f: + f.readline() + for line in f: + parts = line.rstrip("\n").split("\t") + labels.append(unicodedata.normalize("NFC", parts[2])) +labels = sorted(set(labels)) + +api = HfApi(token=False) + + +def roundtrip(tok, texts, kind): + """kind 'hf' (transformers tokenizer) or 'raw' (tokenizers.Tokenizer).""" + bad, unk = [], 0 + unk_id = getattr(tok, "unk_token_id", None) if kind == "hf" else None + for t in texts: + if kind == "hf": + ids = tok.encode(t, add_special_tokens=False) + back = tok.decode(ids, skip_special_tokens=True, clean_up_tokenization_spaces=False) + else: + enc = tok.encode(t, add_special_tokens=False) + ids = enc.ids + back = tok.decode(ids, skip_special_tokens=True) + if unk_id is not None: + unk += sum(1 for i in ids if i == unk_id) + if back != t: + bad.append((t, back)) + return bad, unk + + +def native_info(cfg_dict): + from transformers.models.auto import configuration_auto, modeling_auto + info = {} + mt = cfg_dict.get("model_type") + info["model_type"] = mt + info["config_native"] = mt in configuration_auto.CONFIG_MAPPING_NAMES + for sub in ("text_config", "vision_config", "llm_config", "language_config"): + if isinstance(cfg_dict.get(sub), dict) and cfg_dict[sub].get("model_type"): + smt = cfg_dict[sub]["model_type"] + info[sub + "_type"] = smt + info[sub + "_native"] = smt in configuration_auto.CONFIG_MAPPING_NAMES + maps = {} + for name in ("MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES", "MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES", + "MODEL_FOR_CAUSAL_LM_MAPPING_NAMES", "MODEL_MAPPING_NAMES"): + m = getattr(modeling_auto, name, None) + if m is not None and mt in m: + maps[name.replace("MODEL_FOR_", "").replace("_MAPPING_NAMES", "").replace("MODEL_MAPPING_NAMES", "BASE")] = m[mt] + info["auto_model_mappings"] = maps + return info + + +rows = [] +with open(models_tsv, encoding="utf-8") as f: + f.readline() + for line in f: + short, repo, dp, sc = line.rstrip("\n").split("\t") + if only and short not in only: + continue + rows.append((short, repo, int(dp), sc)) + +for short, repo, design_params, size_class in rows: + rec = {"short": short, "repo": repo, "design_unique_params": design_params, "size_class_design": size_class, + "transformers": transformers.__version__, "errors": []} + try: + info = api.model_info(repo, files_metadata=True, token=False) + rec["revision"] = info.sha + rec["gated"] = info.gated + rec["license_tag"] = (info.card_data.get("license") if info.card_data else None) + rec["last_modified"] = str(info.last_modified) + files = [(s.rfilename, s.size) for s in (info.siblings or [])] + rec["n_files"] = len(files) + st = [(n, s) for n, s in files if n.endswith(".safetensors")] + pk = [(n, s) for n, s in files if n.endswith(WEIGHT_EXT_PICKLE)] + rec["safetensors_files"] = len(st) + rec["safetensors_bytes"] = sum(s or 0 for n, s in st) + rec["other_weight_files"] = [f"{n}:{s}" for n, s in pk][:20] + rec["other_weight_bytes"] = sum(s or 0 for n, s in pk) + rec["py_files_in_repo_not_downloaded"] = [n for n, s in files if n.endswith(".py")] + rec["weight_format"] = ("safetensors" if st and not pk else "safetensors+other" if st and pk + else "pickle/other only" if pk else "none found") + if info.gated: + rec["errors"].append("repo is gated: " + str(info.gated)) + local = os.path.join(models_dir, short) + os.makedirs(local, exist_ok=True) + snapshot_download(repo, revision=info.sha, local_dir=local, allow_patterns=ALLOW, token=False) + got = [] + for root, _, fs in os.walk(local): + for fn in fs: + got.append(os.path.relpath(os.path.join(root, fn), local)) + rec["downloaded_files"] = sorted(g for g in got if not g.startswith(".cache")) + assert not any(g.endswith(".py") for g in got), "a .py file was downloaded" + except Exception as e: # noqa: BLE001 + rec["errors"].append("fetch: " + repr(e)[:300]) + json.dump(rec, open(os.path.join(out_dir, short + ".json"), "w"), indent=1) + print(short, "FETCH ERROR", repr(e)[:200], flush=True) + continue + + local = os.path.join(models_dir, short) + cfg_path = os.path.join(local, "config.json") + try: + cfg_dict = json.load(open(cfg_path, encoding="utf-8")) + rec["architectures"] = cfg_dict.get("architectures") + rec["auto_map"] = cfg_dict.get("auto_map") + rec.update(native_info(cfg_dict)) + archs = cfg_dict.get("architectures") or [] + rec["arch_class_in_transformers"] = [bool(getattr(transformers, a, None)) for a in archs] + except Exception as e: # noqa: BLE001 + rec["errors"].append("config read: " + repr(e)[:300]) + cfg_dict = {} + + # native config load, trust_remote_code=False + cfg = None + try: + cfg = transformers.AutoConfig.from_pretrained(local, trust_remote_code=False) + rec["autoconfig_class"] = type(cfg).__module__ + "." + type(cfg).__name__ + rec["autoconfig_native"] = type(cfg).__module__.startswith("transformers.") + except Exception as e: # noqa: BLE001 + rec["autoconfig_native"] = False + rec["errors"].append("AutoConfig: " + repr(e)[:300]) + + # meta-device construction of the native class (no weights, no code of the vendor) + try: + if cfg is not None and rec.get("autoconfig_native"): + archs = cfg_dict.get("architectures") or [] + cls = None + for a in archs: + cls = getattr(transformers, a, None) + if cls is not None: + rec["native_model_class"] = a + break + if cls is None: + from transformers import AutoModelForImageTextToText + cls = AutoModelForImageTextToText + rec["native_model_class"] = "AutoModelForImageTextToText(fallback)" + with torch.device("meta"): + if hasattr(cls, "_from_config"): + m = cls._from_config(cfg, dtype=torch.bfloat16) + else: + m = cls.from_config(cfg, trust_remote_code=False) + n = 0 + seen = set() + for p in m.parameters(): + if id(p) in seen: + continue + seen.add(id(p)) + n += p.numel() + rec["meta_params_unique"] = n + rec["meta_construct_ok"] = True + del m + except Exception as e: # noqa: BLE001 + rec["meta_construct_ok"] = False + rec["errors"].append("meta construct: " + repr(e)[:300]) + + # tokenizer, trust_remote_code=False + tok, kind = None, None + try: + tok = transformers.AutoTokenizer.from_pretrained(local, trust_remote_code=False) + kind = "hf" + rec["tokenizer_class"] = type(tok).__module__ + "." + type(tok).__name__ + rec["tokenizer_native"] = type(tok).__module__.startswith("transformers.") + except Exception as e: # noqa: BLE001 + rec["errors"].append("AutoTokenizer: " + repr(e)[:300]) + tj = os.path.join(local, "tokenizer.json") + if os.path.exists(tj): + try: + from tokenizers import Tokenizer + tok = Tokenizer.from_file(tj) + kind = "raw" + rec["tokenizer_class"] = "tokenizers.Tokenizer(from tokenizer.json, data only)" + rec["tokenizer_native"] = True + except Exception as e2: # noqa: BLE001 + rec["errors"].append("tokenizers.from_file: " + repr(e2)[:300]) + rec["tokenizer_kind"] = kind + if tok is not None: + try: + nonspace = [s for s in symbols if s != " "] + bad_s, unk_s = roundtrip(tok, nonspace, kind) + bad_sp, _ = roundtrip(tok, ["а б"], kind) + joined = "".join(nonspace) + bad_j, _ = roundtrip(tok, [joined], kind) + bad_l, unk_l = roundtrip(tok, labels, kind) + rec["e3_symbols_tested"] = len(nonspace) + rec["e3_symbols_bad"] = len(bad_s) + rec["e3_symbols_bad_examples"] = [[a, b] for a, b in bad_s[:12]] + rec["e3_space_in_context_ok"] = not bad_sp + rec["e3_joined_string_ok"] = not bad_j + rec["e3_unk_ids_symbols"] = unk_s + rec["e3_labels_tested"] = len(labels) + rec["e3_labels_bad"] = len(bad_l) + rec["e3_labels_bad_examples"] = [[a, b] for a, b in bad_l[:12]] + rec["e3_labels_bad_strip_equal"] = sum(1 for a, b in bad_l if a.strip() == b.strip()) + rec["e3_unk_ids_labels"] = unk_l + except Exception as e: # noqa: BLE001 + rec["errors"].append("roundtrip: " + repr(e)[:300] + traceback.format_exc()[-300:]) + + # processor, trust_remote_code=False + try: + proc = transformers.AutoProcessor.from_pretrained(local, trust_remote_code=False) + rec["processor_class"] = type(proc).__module__ + "." + type(proc).__name__ + rec["processor_native"] = type(proc).__module__.startswith("transformers.") + tmpl = getattr(proc, "chat_template", None) + rec["chat_template_present"] = bool(tmpl) or bool(getattr(getattr(proc, "tokenizer", None), "chat_template", None)) + except Exception as e: # noqa: BLE001 + rec["processor_native"] = False + rec["errors"].append("AutoProcessor: " + repr(e)[:300]) + + json.dump(rec, open(os.path.join(out_dir, short + ".json"), "w"), indent=1, ensure_ascii=False) + print(short, rec.get("model_type"), rec.get("weight_format"), "native_cfg", rec.get("autoconfig_native"), + "meta", rec.get("meta_construct_ok"), "tok_sym_bad", rec.get("e3_symbols_bad"), "labels_bad", + rec.get("e3_labels_bad"), "proc", rec.get("processor_native"), "errors", len(rec["errors"]), flush=True) diff --git a/scripts/j2/eligibility.sbatch b/scripts/j2/eligibility.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..96c449d7303ce73a1f6452d56d0ef95cb566edf5 --- /dev/null +++ b/scripts/j2/eligibility.sbatch @@ -0,0 +1,24 @@ +#!/bin/bash +#SBATCH --job-name=j2_elig +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=4 +#SBATCH --mem=24G +#SBATCH --time=02:00:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# J2 step 2: eligibility facts. Downloads only config/tokenizer/processor/template/README files (no .py, no weights), no token. +set -eu +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +export HF_HOME=$DATA/hf_cache/j2_home +export HF_HUB_CACHE=$DATA/hf_cache/j2_hub +export TRANSFORMERS_NO_ADVISORY_WARNINGS=1 +export HF_HUB_DISABLE_IMPLICIT_TOKEN=1 +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN || true +mkdir -p $HF_HOME $HF_HUB_CACHE $DATA/outputs/j11_stage1_kohtd/eligibility +$CODE/.venv_vlm/bin/python -I $CODE/scripts/j2/eligibility.py \ + $CODE/scripts/j2/models.tsv $CODE/scripts/j2/codec_238.json \ + $DATA/data/processed/kohtd_split_v1/validation.tsv \ + $DATA/hf_cache/j2_models $DATA/outputs/j11_stage1_kohtd/eligibility "$@" +echo "[j2_elig] done" diff --git a/scripts/j2/fetch_weights_loadtest.py b/scripts/j2/fetch_weights_loadtest.py new file mode 100644 index 0000000000000000000000000000000000000000..881e85a06a421a79a307c96479ce665969f88141 --- /dev/null +++ b/scripts/j2/fetch_weights_loadtest.py @@ -0,0 +1,136 @@ +"""J2 step 2b: fetch root-level safetensors weights of the run candidates and test the native weight load on CPU. + +No token, no .py file, trust_remote_code is never set. A model passes the load gate only if from_pretrained with the +native class reports no missing key and no mismatched key; unexpected keys are listed for reading. + +usage: fetch_weights_loadtest.py MODELS_DIR OUT_DIR short [short ...] +""" +import json +import os +import struct +import sys +import time + +os.environ.setdefault("HF_HUB_DISABLE_TELEMETRY", "1") +for k in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"): + os.environ.pop(k, None) + +models_dir, out_dir = sys.argv[1:3] +shorts = sys.argv[3:] +os.makedirs(out_dir, exist_ok=True) + +import torch +import transformers +from huggingface_hub import HfApi, snapshot_download + +CFG = [ + "config.json", "generation_config.json", "preprocessor_config.json", "processor_config.json", + "video_preprocessor_config.json", "tokenizer*", "special_tokens_map.json", "added_tokens.json", + "vocab*", "merges.txt", "chat_template*", "README.md", +] +REPO = {} +for line in open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "models.tsv"), encoding="utf-8").read().splitlines()[1:]: + s, r, _, _ = line.split("\t") + REPO[s] = r + +# class used for loading: the one the card names, else the auto class that maps the config's model_type +CARD_CLASS = { + "lightonocr_3_0_8b": "Qwen3_5ForConditionalGeneration", + "lightonocr_3_1b": "LightOnOcrForConditionalGeneration", +} + + +def header_params(path): + """Total elements and tensor count from a safetensors header (data only).""" + with open(path, "rb") as f: + n = struct.unpack(" " + type(model).__module__ + "." + type(model).__name__ + rec["missing_keys"] = sorted(li.get("missing_keys", []))[:50] + rec["n_missing_keys"] = len(li.get("missing_keys", [])) + rec["unexpected_keys"] = sorted(li.get("unexpected_keys", []))[:50] + rec["n_unexpected_keys"] = len(li.get("unexpected_keys", [])) + rec["mismatched_keys"] = [str(x)[:200] for x in li.get("mismatched_keys", [])][:50] + rec["n_mismatched_keys"] = len(li.get("mismatched_keys", [])) + rec["error_msgs"] = [str(x)[:300] for x in li.get("error_msgs", [])][:20] + seen, n = set(), 0 + for p in model.parameters(): + if id(p) in seen: + continue + seen.add(id(p)) + n += p.numel() + rec["model_params_unique"] = n + rec["tied_weights_note"] = "checkpoint header total minus model unique params = %d" % (ck_params - n) + rec["generation_config"] = model.generation_config.to_dict() if getattr(model, "generation_config", None) else None + rec["load_gate"] = ("PASS" if rec["n_missing_keys"] == 0 and rec["n_mismatched_keys"] == 0 and not rec["error_msgs"] + else "FAIL") + rec["load_seconds"] = round(time.time() - t1, 1) + del model + except Exception as e: # noqa: BLE001 + rec["load_gate"] = "FAIL" + rec["errors"].append("load: " + repr(e)[:500]) + json.dump(rec, open(os.path.join(out_dir, short + ".json"), "w"), indent=1, ensure_ascii=False, default=str) + print(short, "gate", rec.get("load_gate"), "missing", rec.get("n_missing_keys"), "unexpected", rec.get("n_unexpected_keys"), + "mismatched", rec.get("n_mismatched_keys"), "ckpt_params", rec.get("ckpt_params_header"), "model_params", rec.get("model_params_unique"), + "errors", len(rec["errors"]), flush=True) diff --git a/scripts/j2/fetch_weights_loadtest.sbatch b/scripts/j2/fetch_weights_loadtest.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..0793413519fd6a0373d55ea27082f008246970b7 --- /dev/null +++ b/scripts/j2/fetch_weights_loadtest.sbatch @@ -0,0 +1,21 @@ +#!/bin/bash +#SBATCH --job-name=j2_weights +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=8 +#SBATCH --mem=64G +#SBATCH --time=03:00:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# J2 step 2b: root-level safetensors download (no token, no .py) and native weight-load gate on CPU. +set -eu +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +export HF_HOME=$DATA/hf_cache/j2_home +export HF_HUB_CACHE=$DATA/hf_cache/j2_hub +export HF_HUB_DISABLE_IMPLICIT_TOKEN=1 +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN || true +mkdir -p $DATA/outputs/j11_stage1_kohtd/loadtest +$CODE/.venv_vlm/bin/python -I $CODE/scripts/j2/fetch_weights_loadtest.py $DATA/hf_cache/j2_models $DATA/outputs/j11_stage1_kohtd/loadtest \ + paddleocr_vl_1_6 granite_docling_258m ovisocr2 lightonocr_3_0_8b lightonocr_3_1b hunyuanocr glm_ocr minicpm_ocr_1_0 qwen3_vl_2b +echo "[j2_weights] done" diff --git a/scripts/j2/finalize.sbatch b/scripts/j2/finalize.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..a12a1cfcc4d7d92c3de09d0c8b41114c9d0714a7 --- /dev/null +++ b/scripts/j2/finalize.sbatch @@ -0,0 +1,25 @@ +#!/bin/bash +#SBATCH --job-name=j2_finalize +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=2 +#SBATCH --mem=16G +#SBATCH --time=00:30:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# J2: gather everything that has finished (CPU only, no model): results.tsv, raw_samples.tsv, positive_control.tsv (cpu and gpu roots), +# controls_2.tsv. Safe to run again at any time. +set -u +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +PY=$CODE/.venv/bin/python +S=$CODE/scripts/j2 +DS=$DATA/outputs/j11_stage1_kohtd +DC=$DATA/outputs/j11_positive_control +$PY -I $S/collect.py $DS $DS/screen_set_v1.tsv $S/scorelib.py $DS/results.tsv +$PY -I $S/raw_samples.py $DS $DS/screen_set_v1.tsv $S/scorelib.py $DS/raw_samples.tsv +ARGS="cpu=$DC/out_cpu" +[ -d $DC/out_gpu ] && ARGS="$ARGS gpu=$DC/out_gpu" +$PY -I $S/control_report.py $DC/positive_control_screen_set_v1.tsv $S/scorelib.py $DC/positive_control.tsv $ARGS +$PY -I $S/controls2_report.py $DATA/outputs/j11_controls_2 $DC/positive_control_screen_set_v1.tsv $DC/out_cpu $S/scorelib.py $DATA/outputs/j11_controls_2/controls_2.tsv +echo "[j2_finalize] done" diff --git a/scripts/j2/harness_audit.py b/scripts/j2/harness_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..5a185afd3c4b2bb1939fd13827bffa3fcb001df1 --- /dev/null +++ b/scripts/j2/harness_audit.py @@ -0,0 +1,98 @@ +"""J2 harness audit: what exactly goes into each model for 5 KOHTD validation crops and 5 positive-control images. +Processor only (no model weights), CPU. The input is built the same way as run_screen.py (build_inputs, batch of one). +Text and numbers only; no image data is printed. + +usage: harness_audit.py MODELS_DIR PROMPTS_JSON SCREEN_SET KOHTD_IMG_DIR CONTROL_LIST CONTROL_IMG_DIR OUT_TXT short [short ...] +""" +import copy +import json +import os +import re +import sys + +os.environ["HF_HUB_OFFLINE"] = "1" +import torch +import transformers +from PIL import Image + +models_dir, prompts_json, screen_set, kohtd_dir, control_list, control_dir, out_txt = sys.argv[1:8] +shorts = sys.argv[8:] +P = json.load(open(prompts_json, encoding="utf-8")) +CARD_PROC = {"lightonocr_3_1b": "LightOnOcrProcessor"} +TWO_STEP = {"granite_docling_258m"} + + +def read_list(path): + rows = [] + with open(path, encoding="utf-8", newline="") as f: + f.readline() + for line in f: + rows.append(line.rstrip("\n").split("\t")[0]) + return rows + + +kohtd = read_list(screen_set)[:5] +ctl_all = read_list(control_list) +ctl = [ctl_all[i] for i in (0, 1, 100, 200, 300)] # kk h40, kk h40, ky h40, kk h80, ky h80 +items = [("KOHTD validation crop", kohtd_dir, c) for c in kohtd] + [("positive-control image", control_dir, c) for c in ctl] +RUN = re.compile(r"((?:<\|[^>]*\|>|<[^>\s]{1,40}>))\1{2,}") + + +def collapse(s): + return RUN.sub(lambda m: f"{m.group(1)}x{len(m.group(0)) // len(m.group(1))}", s) + + +out = [] +for short in shorts: + pcls = getattr(transformers, CARD_PROC.get(short, ""), None) or transformers.AutoProcessor + proc = pcls.from_pretrained(os.path.join(models_dir, short), trust_remote_code=False) + tok = getattr(proc, "tokenizer", proc) + tok.padding_side = "left" + prompt = P[short]["prompt"] + ik = copy.deepcopy(P[short].get("images_kwargs")) + if ik and ik.get("size", {}).get("shortest_edge") == "MIN_PIXELS_FROM_PROCESSOR": + sz = proc.image_processor.size + ik["size"]["shortest_edge"] = int(sz["shortest_edge"] if isinstance(sz, dict) else sz.shortest_edge) + tk = {"enable_thinking": False} if P[short].get("enable_thinking_false") else {} + out.append("=" * 100) + out.append(f"MODEL {short} processor {type(proc).__module__}.{type(proc).__name__}") + out.append(f" prompt (frozen in prompts.json) = {prompt!r}") + out.append(f" images_kwargs = {ik} chat-template kwargs = {tk} two-step path = {short in TWO_STEP}") + ip = getattr(proc, "image_processor", None) + if ip is not None: + out.append(f" image processor: {type(ip).__name__}; size = {getattr(ip, 'size', None)}; do_convert_rgb = {getattr(ip, 'do_convert_rgb', None)}; " + f"mean = {getattr(ip, 'image_mean', None)}; std = {getattr(ip, 'image_std', None)}; do_rescale = {getattr(ip, 'do_rescale', None)}; " + f"rescale_factor = {getattr(ip, 'rescale_factor', None)}") + for kind, d, c in items: + raw = Image.open(os.path.join(d, c)) + rmode, rsize, rfmt = raw.mode, raw.size, raw.format + im = raw.convert("RGB") + content_text = [{"type": "text", "text": prompt}] if prompt else [] + if short in TWO_STEP: + conv = [{"role": "user", "content": [{"type": "image"}] + content_text}] + templ = proc.apply_chat_template(conv, add_generation_prompt=True) + inputs = proc(text=[templ], images=[[im]], return_tensors="pt", padding=True) + else: + conv = [{"role": "user", "content": [{"type": "image", "image": im}] + content_text}] + templ = proc.apply_chat_template([conv][0], add_generation_prompt=True, tokenize=False, **tk) + kw = dict(tk) + if ik: + kw["images_kwargs"] = ik + inputs = proc.apply_chat_template([conv], add_generation_prompt=True, tokenize=True, return_dict=True, + return_tensors="pt", padding=True, **kw) + pv = inputs.get("pixel_values") + pvs = "none" + if pv is not None: + pvf = pv.float() + pvs = (f"shape {tuple(pv.shape)} dtype {pv.dtype} min {pvf.min().item():.3f} max {pvf.max().item():.3f} " + f"mean {pvf.mean().item():.3f}") + grid = inputs.get("image_grid_thw") + ids = inputs["input_ids"][0] + decoded = collapse(tok.decode(ids, skip_special_tokens=False)).replace("\n", "\\n") + out.append(f" [{kind}] {c}: PIL as loaded: mode {rmode}, size {rsize[0]}x{rsize[1]} (w x h), format {rfmt}; after convert('RGB'): {im.mode} {im.size[0]}x{im.size[1]}") + out.append(f" pixel_values: {pvs}; image_grid_thw: {None if grid is None else grid.tolist()}; input_ids length {ids.shape[0]}") + out.append(f" template string (before expansion): {templ[:400]!r}") + out.append(f" decoded input_ids (image placeholder runs collapsed): {decoded[:700]}") + print(short, "done", flush=True) +open(out_txt, "w", encoding="utf-8").write("\n".join(out) + "\n") +print("written", out_txt) diff --git a/scripts/j2/harness_audit.sbatch b/scripts/j2/harness_audit.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..3efb9c7d2b4a22947c9de63acd93b71b19c5ad3d --- /dev/null +++ b/scripts/j2/harness_audit.sbatch @@ -0,0 +1,21 @@ +#!/bin/bash +#SBATCH --job-name=j2_audit +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=4 +#SBATCH --mem=24G +#SBATCH --time=01:00:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# J2 harness audit (processor only, CPU, offline). Writes DATA/outputs/j11_positive_control/harness_audit.txt (text and numbers only). +set -u +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +export HF_HUB_OFFLINE=1 +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN || true +CT=$DATA/outputs/j11_positive_control +$CODE/.venv_vlm/bin/python -I $CODE/scripts/j2/harness_audit.py $DATA/hf_cache/j2_models $CODE/scripts/j2/prompts.json \ + $DATA/outputs/j11_stage1_kohtd/screen_set_v1.tsv $DATA/data/processed/kohtd_words_raw/KOHTD_dataset/HK_dataset/img \ + $CT/positive_control_screen_set_v1.tsv $CT/img $CT/harness_audit.txt \ + paddleocr_vl_1_6 granite_docling_258m ovisocr2 lightonocr_3_0_8b lightonocr_3_1b hunyuanocr glm_ocr minicpm_ocr_1_0 qwen3_vl_2b +echo "[j2_audit] done" diff --git a/scripts/j2/keyaudit.py b/scripts/j2/keyaudit.py new file mode 100644 index 0000000000000000000000000000000000000000..9da41e772108b72749befdba67004e8b96ef54cd --- /dev/null +++ b/scripts/j2/keyaudit.py @@ -0,0 +1,78 @@ +"""J2: which checkpoint tensors does the native class not use, and which model tensors are not from the checkpoint? + +Exact match by (shape, sha1 of the bf16 bytes), so renamed keys still match. Checkpoint tensors with no matching model +tensor were dropped by the loader (not instantiated or ignored on load); model tensors with no matching checkpoint +tensor were created or changed by the loader (random init, fused, split or tied differently). +usage: keyaudit.py MODELS_DIR OUT_DIR short [short ...] +""" +import hashlib +import json +import os +import sys + +os.environ["HF_HUB_OFFLINE"] = "1" +import torch +import transformers +from safetensors import safe_open + +models_dir, out_dir = sys.argv[1:3] +shorts = sys.argv[3:] +os.makedirs(out_dir, exist_ok=True) +CARD_CLASS = {"lightonocr_3_0_8b": "Qwen3_5ForConditionalGeneration", "lightonocr_3_1b": "LightOnOcrForConditionalGeneration"} + + +def fp(t): + t = t.detach().contiguous().cpu() + if t.dtype == torch.bfloat16: + raw = t.view(torch.int16).numpy().tobytes() + else: + raw = t.numpy().tobytes() + return (tuple(t.shape), str(t.dtype), hashlib.sha1(raw).hexdigest()) + + +def group(names_numel): + g = {} + for n, k in names_numel: + key = ".".join(n.split(".")[:3]) + a = g.setdefault(key, [0, 0]) + a[0] += 1 + a[1] += k + return {k: v for k, v in sorted(g.items(), key=lambda kv: -kv[1][1])} + + +for short in shorts: + path = os.path.join(models_dir, short) + rec = {"short": short} + cls = getattr(transformers, CARD_CLASS.get(short, ""), None) or transformers.AutoModelForImageTextToText + model = cls.from_pretrained(path, dtype=torch.bfloat16, trust_remote_code=False, use_safetensors=True) + mfp = {} + for n, p in model.named_parameters(): + mfp.setdefault(fp(p), []).append(n) + ck = [] + cfp = set() + for fn in sorted(os.listdir(path)): + if fn.endswith(".safetensors"): + with safe_open(os.path.join(path, fn), "pt") as f: + for k in f.keys(): + t = f.get_tensor(k) + h = fp(t) + cfp.add(h) + ck.append((k, t.numel(), h)) + dropped = [(k, n) for k, n, h in ck if h not in mfp] + created = [(names[0], int(torch.tensor(h[0]).prod())) for h, names in mfp.items() if h not in cfp] + rec["ckpt_tensors"] = len(ck) + rec["ckpt_params"] = sum(n for _, n, _ in ck) + rec["model_unique_param_tensors"] = len(mfp) + rec["ckpt_tensors_not_in_model_count"] = len(dropped) + rec["ckpt_tensors_not_in_model_params"] = sum(n for _, n in dropped) + rec["ckpt_not_in_model_groups"] = group(dropped) + rec["ckpt_not_in_model_examples"] = [k for k, _ in dropped[:15]] + rec["model_tensors_not_in_ckpt_count"] = len(created) + rec["model_tensors_not_in_ckpt_params"] = sum(n for _, n in created) + rec["model_not_in_ckpt_groups"] = group(created) + rec["model_not_in_ckpt_examples"] = [k for k, _ in created[:15]] + rec["tie_word_embeddings_config"] = getattr(model.config, "tie_word_embeddings", None) + json.dump(rec, open(os.path.join(out_dir, short + ".json"), "w"), indent=1) + print(short, "ckpt params", rec["ckpt_params"], "dropped tensors", len(dropped), "params", rec["ckpt_tensors_not_in_model_params"], + "| model tensors not from ckpt", len(created), "params", rec["model_tensors_not_in_ckpt_params"], flush=True) + del model diff --git a/scripts/j2/keyaudit.sbatch b/scripts/j2/keyaudit.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..d4ee8f025582c909bc0a787273f80a9f6feedf76 --- /dev/null +++ b/scripts/j2/keyaudit.sbatch @@ -0,0 +1,19 @@ +#!/bin/bash +#SBATCH --job-name=j2_keyaudit +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=8 +#SBATCH --mem=64G +#SBATCH --time=01:30:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# J2: checkpoint-versus-model tensor audit (CPU, offline). +set -eu +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +export HF_HUB_OFFLINE=1 +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN || true +mkdir -p $DATA/outputs/j11_stage1_kohtd/keyaudit +$CODE/.venv_vlm/bin/python -I $CODE/scripts/j2/keyaudit.py $DATA/hf_cache/j2_models $DATA/outputs/j11_stage1_kohtd/keyaudit \ + paddleocr_vl_1_6 hunyuanocr glm_ocr lightonocr_3_1b granite_docling_258m ovisocr2 lightonocr_3_0_8b minicpm_ocr_1_0 qwen3_vl_2b +echo "[j2_keyaudit] done" diff --git a/scripts/j2/make_control_set.py b/scripts/j2/make_control_set.py new file mode 100644 index 0000000000000000000000000000000000000000..47efda7234ea957c959f9474955374fcee5868bf --- /dev/null +++ b/scripts/j2/make_control_set.py @@ -0,0 +1,91 @@ +"""J2 positive control: 200 printed words (100 Kazakh + 100 Kyrgyz, Cyrillic) rendered in PT Sans (OFL 1.1), black on white, at +heights 40 px and 80 px = 400 images. Words come from the DISPLAY sentence banks that pagesynth uses. +(There is no Russian bank in pagesynth_text; the plan allows Kazakh + Kyrgyz then.) + +Word choice: whitespace tokens of the display sentences with punctuation stripped from both ends; keep tokens that are +all letters, 3 to 12 characters, every letter in the Cyrillic block, every glyph in the font; ascending sha256 of +"J2-control-v1::"; first 100 per language. Writes the list in the screen-set format +(positive_control_screen_set_v1.tsv: crop_file, form_id, label) and the images. + +usage: make_control_set.py BANK_KK BANK_KY FONT_TTF OUT_DIR +""" +import hashlib +import os +import sys +import unicodedata + +from fontTools.ttLib import TTFont +from PIL import Image, ImageDraw, ImageFont + +bank = {"kk": sys.argv[1], "ky": sys.argv[2]} +font_path, out_dir = sys.argv[3], sys.argv[4] +os.makedirs(os.path.join(out_dir, "img"), exist_ok=True) +cmap = TTFont(font_path).getBestCmap() +STRIP = "\"'«»„“”‘’.,;:!?()[]{}-–—…/\\" + + +def ok_word(w): + if not (3 <= len(w) <= 12): + return False + for ch in w: + if not ch.isalpha() or not ("Ѐ" <= ch <= "ӿ") or ord(ch) not in cmap: + return False + return True + + +words = {} +for lang, path in bank.items(): + seen = {} + with open(path, encoding="utf-8") as f: + for line in f: + parts = line.rstrip("\n").split("\t") + if len(parts) < 2: + continue + sid, sent = parts[0], parts[1] + for tok in sent.split(): + w = unicodedata.normalize("NFC", tok.strip(STRIP)) + if ok_word(w) and w not in seen: + seen[w] = sid + ranked = sorted(seen, key=lambda w: hashlib.sha256(f"J2-control-v1:{lang}:{w}".encode("utf-8")).hexdigest()) + words[lang] = [(w, seen[w]) for w in ranked[:100]] + print(lang, "candidate words", len(seen), "chosen", len(words[lang])) + + +def render(word, H): + size = int(round(0.62 * H)) + font = ImageFont.truetype(font_path, size) + asc, desc = font.getmetrics() + l, t, r, b = font.getbbox(word) + pad = int(round(0.25 * H)) + W = (r - l) + 2 * pad + im = Image.new("RGB", (W, H), (255, 255, 255)) + d = ImageDraw.Draw(im) + y = (H - (asc + desc)) // 2 + d.text((pad - l, y), word, font=font, fill=(0, 0, 0)) + return im + + +rows, sizes = [], [] +idx = 0 +for H in (40, 80): + for lang in ("kk", "ky"): + for i, (w, sid) in enumerate(words[lang], 1): + name = f"{lang}_h{H}_{i:03d}.png" + im = render(w, H) + assert im.height == H and im.mode == "RGB" + im.save(os.path.join(out_dir, "img", name)) + rows.append((name, str(idx), w, lang, H, sid)) + sizes.append((H, im.width)) + idx += 1 +with open(os.path.join(out_dir, "positive_control_screen_set_v1.tsv"), "w", encoding="utf-8", newline="") as f: + f.write("crop_file\tform_id\tlabel\n") + for name, i, w, lang, H, sid in rows: + f.write(f"{name}\t{i}\t{w}\n") +with open(os.path.join(out_dir, "control_words.tsv"), "w", encoding="utf-8", newline="") as f: + f.write("crop_file\tlang\theight\tword\tsource_sentence_id\n") + for name, i, w, lang, H, sid in rows: + f.write(f"{name}\t{lang}\t{H}\t{w}\t{sid}\n") +for H in (40, 80): + ws = [w for h, w in sizes if h == H] + print("height", H, "images", len(ws), "width min/mean/max", min(ws), sum(ws) / len(ws), max(ws)) +print("font", os.path.basename(font_path), "images", len(rows)) diff --git a/scripts/j2/make_control_set.sbatch b/scripts/j2/make_control_set.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..4f77cf2350796c9f9388c3e63ae03cfa6b5c7ce5 --- /dev/null +++ b/scripts/j2/make_control_set.sbatch @@ -0,0 +1,18 @@ +#!/bin/bash +#SBATCH --job-name=j2_ctl_make +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=2 +#SBATCH --mem=16G +#SBATCH --time=00:30:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# J2 positive control: render 400 printed word images (CPU). +set -eu +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +$CODE/.venv/bin/python -I $CODE/scripts/j2/make_control_set.py $DATA/data/processed/pagesynth_text/kk/sentences_display.tsv \ + $DATA/data/processed/pagesynth_text/ky/sentences_display.tsv $DATA/outputs/j11_positive_control/PTSans-Regular.ttf \ + $DATA/outputs/j11_positive_control +sha256sum $DATA/outputs/j11_positive_control/positive_control_screen_set_v1.tsv +echo "[j2_ctl_make] done" diff --git a/scripts/j2/make_controls2_set.py b/scripts/j2/make_controls2_set.py new file mode 100644 index 0000000000000000000000000000000000000000..ca2335cda6efcdaae3802eb842e0e785b69a7d98 --- /dev/null +++ b/scripts/j2/make_controls2_set.py @@ -0,0 +1,107 @@ +"""J2 second follow-up controls: build the image sets. + +A. Contrast: the first 300 crops of screen_set_v1.tsv (file order). List "stored" = the crops as stored (names unchanged, images are + read from the KOHTD folder). List "stretch" = the same crops after contrast_stretch (own PNG copies; PNG so no new JPEG loss). + The KOHTD images stay on the cluster. +B. Handwriting fonts, no real ink: the same 200 Kazakh and Kyrgyz control words (the 40 px rows of control_words.tsv) rendered at + height 40 px in Caveat and Bad Script (OFL), black on white. A word with a letter the font lacks is left out for that font + and listed. + +usage: make_controls2_set.py SCREEN_SET KOHTD_IMG_DIR CONTROL_WORDS_TSV CONTRAST_STRETCH_PY FONT_CAVEAT FONT_BADSCRIPT OUT_DIR +""" +import importlib.util +import os +import sys + +import numpy as np +from fontTools.ttLib import TTFont +from PIL import Image, ImageDraw, ImageFont + +screen_set, kohtd_dir, words_tsv, cs_py, font_caveat, font_bad, out_dir = sys.argv[1:8] +assert "screen_set_v1.tsv" in screen_set +spec = importlib.util.spec_from_file_location("cs", cs_py) +cs = importlib.util.module_from_spec(spec) +spec.loader.exec_module(cs) +os.makedirs(os.path.join(out_dir, "img_stretch"), exist_ok=True) +os.makedirs(os.path.join(out_dir, "img_fonts"), exist_ok=True) + +# ---- A: contrast +rows = [] +with open(screen_set, encoding="utf-8", newline="") as f: + f.readline() + for line in f: + rows.append(line.rstrip("\n").split("\t")) + if len(rows) == 300: + break +assert len(rows) == 300 +with open(os.path.join(out_dir, "contrast_stored_screen_set_v1.tsv"), "w", encoding="utf-8", newline="") as f: + f.write("crop_file\tform_id\tlabel\n") + for c, form, lab in rows: + f.write(f"{c}\t{form}\t{lab}\n") +p1b, p99b, p1a, p99a = [], [], [], [] +with open(os.path.join(out_dir, "contrast_stretch_screen_set_v1.tsv"), "w", encoding="utf-8", newline="") as f: + f.write("crop_file\tform_id\tlabel\n") + for c, form, lab in rows: + im = Image.open(os.path.join(kohtd_dir, c)).convert("RGB") + out = cs.contrast_stretch(im) + assert out.size == im.size and out.mode == "RGB" + g0 = np.asarray(im.convert("L"), dtype=float) + g1 = np.asarray(out.convert("L"), dtype=float) + p1b.append(np.percentile(g0, 1)) + p99b.append(np.percentile(g0, 99)) + p1a.append(np.percentile(g1, 1)) + p99a.append(np.percentile(g1, 99)) + name = os.path.splitext(c)[0] + ".png" + out.save(os.path.join(out_dir, "img_stretch", name)) + f.write(f"{name}\t{form}\t{lab}\n") +print("A: 300 crops; grey 1st/99th percentile mean before %.1f / %.1f, after %.1f / %.1f" % ( + np.mean(p1b), np.mean(p99b), np.mean(p1a), np.mean(p99a))) +print("A: crops whose 1st percentile was already below 30: %d; whose 99th was above 225: %d" % ( + sum(1 for v in p1b if v < 30), sum(1 for v in p99b if v > 225))) + +# ---- B: handwriting fonts +words = [] +with open(words_tsv, encoding="utf-8", newline="") as f: + f.readline() + for line in f: + crop, lang, h, word, sid = line.rstrip("\n").split("\t") + if h == "40": + words.append((crop, lang, word)) +assert len(words) == 200 +H = 40 +FONTS = {"caveat": font_caveat, "badscript": font_bad} + + +def render(word, path): + size = int(round(0.62 * H)) + font = ImageFont.truetype(path, size) + l, t, r, b = font.getbbox(word) + while (b - t) > H - 4 and size > 8: + size -= 1 + font = ImageFont.truetype(path, size) + l, t, r, b = font.getbbox(word) + pad = int(round(0.25 * H)) + im = Image.new("RGB", ((r - l) + 2 * pad, H), (255, 255, 255)) + ImageDraw.Draw(im).text((pad - l, (H - (b - t)) // 2 - t), word, font=font, fill=(0, 0, 0)) + return im, size + + +n = 0 +with open(os.path.join(out_dir, "fonts_screen_set_v1.tsv"), "w", encoding="utf-8", newline="") as f: + f.write("crop_file\tform_id\tlabel\n") + for fname, path in FONTS.items(): + cmap = TTFont(path).getBestCmap() + left_out, widths = [], [] + for crop, lang, word in words: + if any(ord(ch) not in cmap for ch in word): + left_out.append(word) + continue + im, size = render(word, path) + name = f"{fname}_{os.path.splitext(crop)[0]}.png" + im.save(os.path.join(out_dir, "img_fonts", name)) + f.write(f"{name}\t{n}\t{word}\n") + n += 1 + widths.append(im.width) + print(f"B: {fname}: rendered {len(widths)} of 200 words, left out for missing glyphs: {len(left_out)} {left_out[:10]}; width min/mean/max " + f"{min(widths)}/{np.mean(widths):.0f}/{max(widths)}") +print("B: total images", n) diff --git a/scripts/j2/make_controls2_set.sbatch b/scripts/j2/make_controls2_set.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..24fe6b0d390c377d46d90d1600b039fe861caeef --- /dev/null +++ b/scripts/j2/make_controls2_set.sbatch @@ -0,0 +1,20 @@ +#!/bin/bash +#SBATCH --job-name=j2_c2_make +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=2 +#SBATCH --mem=16G +#SBATCH --time=00:30:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# J2 controls 2: contrast-stretched copies of the first 300 screen crops, and the 200 control words in two OFL handwriting fonts (CPU). +set -eu +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +OUT=$DATA/outputs/j11_controls_2 +mkdir -p $OUT +$CODE/.venv/bin/python -I $CODE/scripts/j2/make_controls2_set.py $DATA/outputs/j11_stage1_kohtd/screen_set_v1.tsv \ + $DATA/data/processed/kohtd_words_raw/KOHTD_dataset/HK_dataset/img $DATA/outputs/j11_positive_control/control_words.tsv \ + $CODE/scripts/j2/contrast_stretch.py "$DATA/data/raw/fonts/Caveat/Caveat[wght].ttf" $DATA/data/raw/fonts/BadScript/BadScript-Regular.ttf $OUT +sha256sum $OUT/contrast_stored_screen_set_v1.tsv $OUT/contrast_stretch_screen_set_v1.tsv $OUT/fonts_screen_set_v1.tsv +echo "[j2_c2_make] done" diff --git a/scripts/j2/models.tsv b/scripts/j2/models.tsv new file mode 100644 index 0000000000000000000000000000000000000000..07adee5b540cbb3589a6a0741cc696c9a264b666 --- /dev/null +++ b/scripts/j2/models.tsv @@ -0,0 +1,21 @@ +short repo design_unique_params size_class +paddleocr_vl_1_6 PaddlePaddle/PaddleOCR-VL-1.6 958588736 middle +falcon_ocr tiiuae/Falcon-OCR 269944416 small +granite_docling_258m ibm-granite/granite-docling-258M 257517120 small +surya_ocr_2_5 datalab-to/surya-ocr-2.5 689356864 middle +ovisocr2 ATH-MaaS/OvisOCR2 852985920 middle +lightonocr_3_0_8b lightonai/LightOnOCR-3-0.8B 852985920 middle +lightonocr_3_1b lightonai/LightOnOCR-3-1B 1005647872 middle +hunyuanocr tencent/HunyuanOCR 996208112 middle +glm_ocr zai-org/GLM-OCR 1142806016 middle +mineru2_5_pro opendatalab/MinerU2.5-Pro-2605-1.2B 1156026624 middle +teleocr XingChen-AGI/TeleOCR 1259490304 middle +minicpm_ocr_1_0 openbmb/MiniCPM-OCR-1.0 1300434160 middle +oxr_1_0 SoMarkAI/OXR-1.0 1378795752 middle +qwen3_vl_2b Qwen/Qwen3-VL-2B-Instruct 2127532032 large +firered_ocr FireRedTeam/FireRed-OCR 2127532032 large +youtu_parsing tencent/Youtu-Parsing 2515984240 large +dots_mocr rednote-hilab/dots.mocr 3039179264 large +unlimited_ocr_2 baidu/Unlimited-OCR-2 3343978240 large +jina_ocr_v1 jinaai/jina-ocr-v1 3372238080 large +deepseek_ocr_2 deepseek-ai/DeepSeek-OCR-2 3389119360 large diff --git a/scripts/j2/prompts.json b/scripts/j2/prompts.json new file mode 100644 index 0000000000000000000000000000000000000000..a7459d9899988d1c2042adee28394b40de571bc0 --- /dev/null +++ b/scripts/j2/prompts.json @@ -0,0 +1,84 @@ +{ + "paddleocr_vl_1_6": { + "prompt": "OCR:", + "readme_line_no": 198, + "readme_line_text": "\"ocr\": \"OCR:\",", + "note": "card task table, transformers example; text prompt PROMPTS[task] with task='ocr'", + "enable_thinking_false": false, + "images_kwargs": { + "size": { + "shortest_edge": "MIN_PIXELS_FROM_PROCESSOR", + "longest_edge": 1003520 + } + } + }, + "granite_docling_258m": { + "prompt": "Convert this page to docling.", + "readme_line_no": 167, + "readme_line_text": "{\"type\": \"text\", \"text\": \"Convert this page to docling.\"}", + "note": "closest documented: card documents no plain-text prompt; this is the card's transformers example (page to DocTags); tags removed by the common post-processing", + "enable_thinking_false": false, + "images_kwargs": null + }, + "ovisocr2": { + "prompt": "\nExtract all readable content from the image in natural human reading order and output the result as a single Markdown document. For charts or images, represent them using an HTML image tag: , where left, top, right, bottom are bounding box coordinates scaled to [0, 1000). Format formulas as LaTeX. Format tables as HTML: ...
. Transcribe all other text as standard Markdown. Preserve the original text without translation or paraphrasing.", + "readme_line_no": 72, + "readme_line_text": "prompt = '\\nExtract all readable content from the image in natural human reading order and output the result as a single Markdown document. For charts or images, represent them using an HTML image tag: <' + 'img src=\"images/bbox_{left}_{top}_{right}_{bottom}.jpg\" />, where left, top, right, bottom are bounding box coordinates scaled to [0, 1000). Format formulas as LaTeX. Format tables as HTML: ...
. Transcribe all other text as standard Markdown. Preserve the original text without translation or paraphrasing.'", + "note": "card's page-parsing prompt (vLLM example), including its leading newline; closest documented, no plain-text prompt exists", + "enable_thinking_false": true, + "images_kwargs": { + "size": { + "shortest_edge": 200704, + "longest_edge": 8294400 + } + } + }, + "lightonocr_3_0_8b": { + "prompt": "", + "readme_line_no": 61, + "readme_line_text": "The models can be used as before in a **transcription-only mode**: called with an empty prompt (`\"\"`; the image only), they output all textual elements of the page as markdown. If you are currently using our previous models, switching to LightOnOCR-3 requires no change, as this is the default behavior.", + "note": "transcription mode = empty prompt, image only (no text part)", + "enable_thinking_false": true, + "images_kwargs": null + }, + "lightonocr_3_1b": { + "prompt": "", + "readme_line_no": 58, + "readme_line_text": "The models can be used as before in a **transcription-only mode**: called with an empty prompt (`\"\"`; the image only), they output all textual elements of the page as markdown. If you are currently using our previous models, switching to LightOnOCR-3 requires no change, as this is the default behavior.", + "note": "transcription mode = empty prompt, image only (no text part)", + "enable_thinking_false": false, + "images_kwargs": null + }, + "hunyuanocr": { + "prompt": "请提取图片中的文字内容。", + "readme_line_no": 201, + "readme_line_text": "{\"type\": \"text\", \"text\": \"请提取图片中的文字内容。\"},", + "note": "plain text extraction prompt in the card's OpenAI-SDK example; the card's default markdown page-parse prompt is not used", + "enable_thinking_false": false, + "images_kwargs": null + }, + "glm_ocr": { + "prompt": "Text Recognition:", + "readme_line_no": 91, + "readme_line_text": "\"text\": \"Text Recognition:\",", + "note": "card 'Prompt Limited' list, document parsing task 'text'", + "enable_thinking_false": false, + "images_kwargs": null + }, + "minicpm_ocr_1_0": { + "prompt": "Text Recognition:", + "readme_line_no": 326, + "readme_line_text": "Text Recognition:", + "note": "card 'Recognition guide' table, row 'Text block / Paragraph / Title / Page' -> plain text", + "enable_thinking_false": false, + "images_kwargs": null + }, + "qwen3_vl_2b": { + "prompt": "Read the text in the image. Output only the text.", + "readme_line_no": 107, + "readme_line_text": "{\"type\": \"text\", \"text\": \"Describe this image.\"},", + "note": "NOT FROM THE CARD (departure by J2): the card documents only 'Describe this image.', which is not text reading; this plain instruction was frozen before any output existed", + "enable_thinking_false": false, + "images_kwargs": null + } +} \ No newline at end of file diff --git a/scripts/j2/raw_samples.py b/scripts/j2/raw_samples.py new file mode 100644 index 0000000000000000000000000000000000000000..bc590945ea82054906c165945220a5572ae64ab5 --- /dev/null +++ b/scripts/j2/raw_samples.py @@ -0,0 +1,44 @@ +"""20 raw outputs per model and enlargement next to their references (for manual inspection only, never for a page). +Same 20 crops for every model and scale: ascending sha256 of "J2-raw-sample-v1:" + crop_file over the screen set. +Only crops that are already done are listed (a partial run shows fewer than 20 rows; the column crops_of_sample_done says so). +usage: raw_samples.py OUT_ROOT SCREEN_SET_TSV SCORELIB_PY OUT_TSV +""" +import hashlib +import importlib.util +import json +import os +import sys + +out_root, screen_set, scorelib_py, out_tsv = sys.argv[1:5] +assert "screen_set_v1.tsv" in screen_set +spec = importlib.util.spec_from_file_location("scorelib", scorelib_py) +sl = importlib.util.module_from_spec(spec) +spec.loader.exec_module(sl) +labels = {} +with open(screen_set, encoding="utf-8", newline="") as f: + f.readline() + for line in f: + c, form, lab = line.rstrip("\n").split("\t") + labels[c] = lab +sample = sorted(labels, key=lambda c: hashlib.sha256(("J2-raw-sample-v1:" + c).encode("utf-8")).hexdigest())[:20] +rows = ["model\tscale\tcrop_file\treference\traw_output\tafter_wrapper_removal\tcer\tn_new_tokens\thit_cap\timage_tokens\tcrops_of_sample_done"] +for model in sorted(os.listdir(out_root)): + for scale in (1, 2, 3): + pp = os.path.join(out_root, model, f"s{scale}", "preds.jsonl") + if not os.path.exists(pp): + continue + preds = {} + for line in open(pp, encoding="utf-8"): + try: + r = json.loads(line) + except Exception: # noqa: BLE001 + continue + preds[r["crop_file"]] = r + done = [c for c in sample if c in preds] + for c in done: + r = preds[c] + s = sl.score_crop(labels[c], r["raw"]) + rows.append("\t".join([model, f"{scale}x", c, labels[c].replace("\t", " "), repr(r["raw"])[1:-1], s["hyp"].replace("\n", "\\n"), + f"{s['cer']:.3f}", str(r["n_new"]), str(int(r["hit_cap"])), str(r["n_img_tokens"]), f"{len(done)}/20"])) +open(out_tsv, "w", encoding="utf-8").write("\n".join(rows) + "\n") +print("rows", len(rows) - 1) diff --git a/scripts/j2/run_gpu_job.sbatch b/scripts/j2/run_gpu_job.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..99460a0fee7f15f204efcaa4a081ec16b319402a --- /dev/null +++ b/scripts/j2/run_gpu_job.sbatch @@ -0,0 +1,30 @@ +#!/bin/bash +#SBATCH --job-name=j2_gpu +#SBATCH --partition=H100 +#SBATCH --qos=nu-h100 +#SBATCH --gres=gpu:h100:1 +#SBATCH --cpus-per-task=16 +#SBATCH --mem=96G +#SBATCH --time=02:00:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# J2 step 6: zero-shot screen of 2-4 models on the KOHTD validation word crops, one model after another, offline. +# Order: enlargement 1x for every model of the job first, then 2x, then 3x, so that a timeout still leaves 1x for all. +# Every model writes JSONL after each batch and resumes from it: a job that ran out of time is simply submitted again. +# usage: sbatch --job-name=j2_gpuA run_gpu_job.sbatch short [short ...] +set -u +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +export HF_HUB_OFFLINE=1 +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN || true +OUT=$DATA/outputs/j11_stage1_kohtd +echo "job $SLURM_JOB_ID on $(hostname) models: $*" +nvidia-smi --query-gpu=name,driver_version,memory.total --format=csv +for SCALE in 1 2 3; do + for M in "$@"; do + echo "=== $M scale $SCALE $(date -u +%H:%M:%S)" + $CODE/.venv_vlm/bin/python -I $CODE/scripts/j2/run_screen.py $M $DATA/hf_cache/j2_models $CODE/scripts/j2/prompts.json \ + $OUT/screen_set_v1.tsv $DATA/data/processed/kohtd_words_raw/KOHTD_dataset/HK_dataset/img $OUT \ + --device cuda --batch-size 16 --max-new-tokens 48 --scales $SCALE 2>&1 | grep -v -E "Loading weights|^\s*$" | tail -15 + done +done +echo "[j2_gpu] done $(date -u +%H:%M:%S)" diff --git a/scripts/j2/run_screen.py b/scripts/j2/run_screen.py new file mode 100644 index 0000000000000000000000000000000000000000..73aa0b8e0635f577dc65577c2f9c5d749f7d180b --- /dev/null +++ b/scripts/j2/run_screen.py @@ -0,0 +1,290 @@ +"""J2 screen: zero-shot reading of KOHTD validation word crops with one stock-transformers model. + +Native transformers classes only (trust_remote_code is never set), safetensors only, greedy, bf16, sdpa. +This script never reads labels and never opens train.tsv or test.tsv: it reads crop_file from screen_set_v1.tsv only. +Writes after every batch and resumes from preds.jsonl. + +usage: run_screen.py SHORT MODELS_DIR PROMPTS_JSON SCREEN_SET_TSV IMG_DIR OUT_ROOT + [--batch-size 16] [--max-new-tokens 48] [--scales 1,2,3] [--limit N] [--device cuda|cpu] + [--threads N] [--check-batch-equal] +""" +import argparse +import copy +import json +import os +import sys +import time +from datetime import datetime, timezone + +os.environ.setdefault("HF_HUB_OFFLINE", "1") +for k in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"): + os.environ.pop(k, None) + +ap = argparse.ArgumentParser() +ap.add_argument("short") +ap.add_argument("models_dir") +ap.add_argument("prompts_json") +ap.add_argument("screen_set") +ap.add_argument("img_dir") +ap.add_argument("out_root") +ap.add_argument("--batch-size", type=int, default=16) +ap.add_argument("--max-new-tokens", type=int, default=48) +ap.add_argument("--scales", default="1,2,3") +ap.add_argument("--limit", type=int, default=0) +ap.add_argument("--device", default="cuda") +ap.add_argument("--threads", type=int, default=0) +ap.add_argument("--check-batch-equal", action="store_true") +args = ap.parse_args() + +assert "screen_set_v1.tsv" in args.screen_set +import torch +import transformers +from PIL import Image + +if args.threads: + torch.set_num_threads(args.threads) +dev = args.device +use_cuda = dev == "cuda" +assert (not use_cuda) or torch.cuda.is_available(), "cuda requested but not available" + +CARD_CLASS = {"lightonocr_3_0_8b": "Qwen3_5ForConditionalGeneration", "lightonocr_3_1b": "LightOnOcrForConditionalGeneration"} +CARD_PROC = {"lightonocr_3_1b": "LightOnOcrProcessor"} +TWO_STEP = {"granite_docling_258m"} # card: apply_chat_template(text) then processor(text, images) + +P = json.load(open(args.prompts_json, encoding="utf-8"))[args.short] +prompt = P["prompt"] +model_path = os.path.join(args.models_dir, args.short) +assert not any(f.endswith(".py") for f in os.listdir(model_path)), "a .py file in the model folder" + +crops = [] +with open(args.screen_set, encoding="utf-8", newline="") as f: + hdr = f.readline().rstrip("\n").split("\t") + assert hdr == ["crop_file", "form_id", "label"] + for line in f: + crops.append(line.rstrip("\n").split("\t")[0]) +if args.limit: + crops = crops[: args.limit] +print(f"[{args.short}] crops {len(crops)} device {dev} batch {args.batch_size} scales {args.scales}", flush=True) + +t_load = time.time() +cls = None +if args.short in CARD_CLASS: + cls = getattr(transformers, CARD_CLASS[args.short], None) +if cls is None: + cls = transformers.AutoModelForImageTextToText +pcls = getattr(transformers, CARD_PROC.get(args.short, ""), None) or transformers.AutoProcessor +processor = pcls.from_pretrained(model_path, trust_remote_code=False) +model = cls.from_pretrained(model_path, dtype=torch.bfloat16, trust_remote_code=False, use_safetensors=True, + attn_implementation="sdpa") +model = model.to(dev).eval() +load_seconds = time.time() - t_load +tok = getattr(processor, "tokenizer", processor) +tok.padding_side = "left" +if getattr(tok, "pad_token_id", None) is None: + tok.pad_token = tok.eos_token + +seen_p, n_params = set(), 0 +for p in model.parameters(): + if id(p) not in seen_p: + seen_p.add(id(p)) + n_params += p.numel() + +gc = copy.deepcopy(model.generation_config) +gc.max_new_tokens = args.max_new_tokens +gc.do_sample = False +gc.num_beams = 1 +gc.repetition_penalty = 1.0 +gc.no_repeat_ngram_size = 0 +gc.temperature = None +gc.top_p = None +gc.top_k = None +if gc.pad_token_id is None: + gc.pad_token_id = tok.pad_token_id +eos_ids = set() +for e in (gc.eos_token_id, getattr(tok, "eos_token_id", None)): + if isinstance(e, (list, tuple)): + eos_ids.update(e) + elif e is not None: + eos_ids.add(e) +# stop on the generation config's end ids AND the tokenizer's end token (the chat turn end, e.g. <|im_end|>), as +# the serving stacks of the cards do; without this OvisOCR2 ran on after its turn end in the smoke test +gc.eos_token_id = sorted(eos_ids) +stop_ids_used = sorted(eos_ids) +if gc.pad_token_id is not None: + eos_ids.add(gc.pad_token_id) + +img_tok_id = getattr(model.config, "image_token_id", None) +if img_tok_id is None: + img_tok_id = getattr(processor, "image_token_id", None) +if img_tok_id is None and getattr(processor, "image_token", None): + img_tok_id = tok.convert_tokens_to_ids(processor.image_token) + +images_kwargs = copy.deepcopy(P.get("images_kwargs")) +if images_kwargs and images_kwargs.get("size", {}).get("shortest_edge") == "MIN_PIXELS_FROM_PROCESSOR": + # card: processor.image_processor.min_pixels; the native processor keeps it as size["shortest_edge"] + _ip = processor.image_processor + _mp = getattr(_ip, "min_pixels", None) + if _mp is None: + _sz = _ip.size + _mp = _sz["shortest_edge"] if isinstance(_sz, dict) else getattr(_sz, "shortest_edge") + images_kwargs["size"]["shortest_edge"] = int(_mp) +tmpl_kwargs = {"enable_thinking": False} if P.get("enable_thinking_false") else {} + +if use_cuda: + torch.cuda.synchronize() + mem_after_load = torch.cuda.memory_allocated() + torch.cuda.reset_peak_memory_stats() +else: + mem_after_load = 0 +job_id = os.environ.get("SLURM_JOB_ID", "") +revision = None +try: + lt = json.load(open(os.path.join(os.path.dirname(os.path.abspath(args.out_root)), "j11_stage1_kohtd", "loadtest", args.short + ".json"))) + revision = lt.get("revision") +except Exception: # noqa: BLE001 + pass + + +def load_image(crop_file, scale): + im = Image.open(os.path.join(args.img_dir, crop_file)).convert("RGB") + if scale != 1: + im = im.resize((im.width * scale, im.height * scale), Image.Resampling.LANCZOS) + return im + + +def build_inputs(imgs): + content_text = [{"type": "text", "text": prompt}] if prompt else [] + if args.short in TWO_STEP: + convs = [[{"role": "user", "content": [{"type": "image"}] + content_text}] for _ in imgs] + texts = [processor.apply_chat_template(c, add_generation_prompt=True) for c in convs] + inputs = processor(text=texts, images=[[im] for im in imgs], return_tensors="pt", padding=True) + else: + convs = [[{"role": "user", "content": [{"type": "image", "image": im}] + content_text}] for im in imgs] + kw = dict(tmpl_kwargs) + if images_kwargs: + kw["images_kwargs"] = images_kwargs + inputs = processor.apply_chat_template(convs, add_generation_prompt=True, tokenize=True, return_dict=True, + return_tensors="pt", padding=True, **kw) + return inputs + + +def generate_batch(imgs): + t0 = time.time() + inputs = build_inputs(imgs) + am = inputs["attention_mask"] + assert bool(am[:, -1].all()), "padding is not on the left" + inputs = inputs.to(dev, dtype=torch.bfloat16) + t1 = time.time() + if use_cuda: + torch.cuda.synchronize() + t1 = time.time() + with torch.inference_mode(): + out = model.generate(**inputs, generation_config=gc) + if use_cuda: + torch.cuda.synchronize() + t2 = time.time() + in_len = inputs["input_ids"].shape[1] + new = out[:, in_len:] + try: + texts = processor.batch_decode(new, skip_special_tokens=True, clean_up_tokenization_spaces=False) + except Exception: # noqa: BLE001 + texts = tok.batch_decode(new, skip_special_tokens=True, clean_up_tokenization_spaces=False) + recs = [] + for r in range(new.shape[0]): + row = new[r].tolist() + n_new, hit_eos = len(row), False + for j, t in enumerate(row): + if t in eos_ids: + n_new, hit_eos = j + 1, True + break + n_img = int((inputs["input_ids"][r] == img_tok_id).sum()) if img_tok_id is not None else -1 + recs.append({"raw": texts[r], "n_new": n_new, "hit_cap": (not hit_eos) and n_new >= args.max_new_tokens, + "n_img_tokens": n_img, "in_len": int(am[r].sum())}) + return recs, t1 - t0, t2 - t1 + + +def run_scale(scale, out_dir, bs, list_crops): + os.makedirs(out_dir, exist_ok=True) + pred_path = os.path.join(out_dir, "preds.jsonl") + time_path = os.path.join(out_dir, "timing.jsonl") + done = set() + if os.path.exists(pred_path): + for line in open(pred_path, encoding="utf-8"): + try: + done.add(json.loads(line)["crop_file"]) + except Exception: # noqa: BLE001 + pass + todo = [c for c in list_crops if c not in done] + print(f"[{args.short}] scale {scale}x: done {len(done)}, to do {len(todo)}", flush=True) + meta_path = os.path.join(out_dir, "meta.json") + prev = json.load(open(meta_path)) if os.path.exists(meta_path) else {} + peak = prev.get("peak_gpu_mem_allocated_bytes", 0) + sessions = prev.get("job_ids", []) + if job_id and job_id not in sessions: + sessions.append(job_id) + errors = prev.get("errors", 0) + with open(pred_path, "a", encoding="utf-8") as fp, open(time_path, "a", encoding="utf-8") as ft: + for b in range(0, len(todo), bs): + batch = todo[b: b + bs] + t_img = 0.0 + try: + ti = time.time() + imgs = [load_image(c, scale) for c in batch] + t_img = time.time() - ti + recs, t_pre, t_gen = generate_batch(imgs) + except Exception as e: # noqa: BLE001 + print(f"[{args.short}] batch failed ({repr(e)[:200]}); one crop at a time", flush=True) + if use_cuda: + torch.cuda.empty_cache() + recs, t_pre, t_gen = [], 0.0, 0.0 + for c in batch: + try: + r1, a, g = generate_batch([load_image(c, scale)]) + recs.append(r1[0]) + t_pre += a + t_gen += g + except Exception as e2: # noqa: BLE001 + errors += 1 + recs.append({"raw": "", "n_new": 0, "hit_cap": False, "n_img_tokens": -1, "in_len": -1, + "error": repr(e2)[:300]}) + for c, r in zip(batch, recs): + r.update({"crop_file": c, "scale": scale, "batch_size": bs}) + fp.write(json.dumps(r, ensure_ascii=False) + "\n") + fp.flush() + os.fsync(fp.fileno()) + pk = torch.cuda.max_memory_allocated() if use_cuda else 0 + peak = max(peak, pk) + ft.write(json.dumps({"n": len(batch), "t_img": round(t_img, 4), "t_pre": round(t_pre, 4), "t_gen": round(t_gen, 4), + "new_tokens": sum(r["n_new"] for r in recs), "job_id": job_id, + "batch_first_crop": batch[0]}) + "\n") + ft.flush() + meta = { + "short": args.short, "repo_revision": revision, "scale": scale, "prompt": prompt, "prompt_note": P["note"], + "transformers": transformers.__version__, "torch": torch.__version__, "device": dev, + "gpu": torch.cuda.get_device_name(0) if use_cuda else "cpu", "dtype": "bfloat16", + "attn_implementation": getattr(model.config, "_attn_implementation", None), "batch_size": bs, + "max_new_tokens": args.max_new_tokens, "model_class": type(model).__module__ + "." + type(model).__name__, + "processor_class": type(processor).__module__ + "." + type(processor).__name__, + "params_unique": n_params, "generation_config_used": {k: v for k, v in gc.to_dict().items() if v is not None}, + "stop_token_ids": stop_ids_used, "images_kwargs": images_kwargs, "chat_template_kwargs": tmpl_kwargs, "two_step_processor": args.short in TWO_STEP, + "load_seconds": round(load_seconds, 1), "mem_after_load_bytes": mem_after_load, + "peak_gpu_mem_allocated_bytes": peak, "peak_note": "H100, not the RTX 5090; torch.cuda.max_memory_allocated after weights were loaded and the peak counter reset" if use_cuda else "cpu run: no GPU memory figure", + "job_ids": sessions, "errors": errors, "updated_utc": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + "screen_set": os.path.basename(args.screen_set), "crops_in_list": len(list_crops), + } + json.dump(meta, open(meta_path, "w"), indent=1, ensure_ascii=False) + return meta + + +model_dir_out = os.path.join(args.out_root, args.short) +for s in [int(x) for x in args.scales.split(",")]: + meta = run_scale(s, os.path.join(model_dir_out, f"s{s}"), args.batch_size, crops) + print(f"[{args.short}] scale {s}x finished; peak GPU mem {meta['peak_gpu_mem_allocated_bytes']/2**30:.2f} GiB", flush=True) + +if args.check_batch_equal: + a = [json.loads(l)["raw"] for l in open(os.path.join(model_dir_out, "s1", "preds.jsonl"), encoding="utf-8")] + run_scale(1, os.path.join(model_dir_out, "s1_batch1_check"), 1, crops) + b = [json.loads(l)["raw"] for l in open(os.path.join(model_dir_out, "s1_batch1_check", "preds.jsonl"), encoding="utf-8")] + res = {"crops": len(a), "identical": sum(1 for x, y in zip(a, b) if x == y), "batch_N": a, "batch_1": b} + json.dump(res, open(os.path.join(model_dir_out, "batch_equal_check.json"), "w"), indent=1, ensure_ascii=False) + print(f"[{args.short}] batch-N vs batch-1 identical outputs: {res['identical']} of {res['crops']}", flush=True) diff --git a/scripts/j2/scorelib.py b/scripts/j2/scorelib.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a695ecf2004318b4de812a1f51bb84eb5c89e7 --- /dev/null +++ b/scripts/j2/scorelib.py @@ -0,0 +1,149 @@ +"""Scoring library for the J2 screen. Frozen before any model output exists (sha256 in scoring.txt). + +Own edit-distance code (no package): the design's HR2 needs an alignment with a stated tie-break, which +no package gives. Tested in test_scorelib.py. +Design keys followed: decision_rule_v3.txt rule 0.3 (strip, remove wrappers, NFC, CER definition), section 1 +(CER = summed edit distances / summed reference lengths), section 2 (HR1-HR4), j11_v3_design.json +screen.stage_1_zero_shot (Z cut off at 1.0). +""" +import re +import unicodedata + +_WS = re.compile(r"\s+") +_TAG = re.compile(r"") # , , ,
+_SPECIAL = re.compile(r"<\|[^>|]*\|>") # <|im_end|> style leftovers +_FENCE = re.compile(r"^```[a-zA-Z0-9_-]*\s*$", re.M) # markdown code fence lines +_LOOP = re.compile(r"(.{4,}?)\1{2,}", re.S) +_HEADING = re.compile(r"^[ \t]*#{1,6}[ \t]+", re.M) # markdown heading marker at a line start +_LATEX_TEXT = re.compile(r"\$\\text\{([^{}]*)\}\$") # $\text{word}$ -> word +_CJK_PREAMBLE = re.compile(r"^\s*[一-鿿][^\n::]{0,60}[::]") # chat preamble such as "图片中的文本内容是:" + + +def strip_wrappers(text): + """The one post-processing step for model output (identical for all models). + Amendment 2026-11-20 (before the screen, after the 5-crop smoke test): heading markers and a leading CJK + preamble clause ending in a colon are also removed (seen in the smoke outputs of OvisOCR2 and HunyuanOCR), and a + whole-text $\\text{...}$ unwrapping (LightOnOCR-3-0.8B smoke output). Only markup without content of its own.""" + t = _FENCE.sub("", text) + t = _SPECIAL.sub("", t) + t = _TAG.sub("", t) + t = _CJK_PREAMBLE.sub("", t) + t = _HEADING.sub("", t) + t = _LATEX_TEXT.sub(r"\1", t) + return t + + +def norm(text): + """NFC, whitespace runs (incl. newlines) to one space, strip. Case is kept.""" + return _WS.sub(" ", unicodedata.normalize("NFC", text)).strip() + + +def prep_output(raw): + return norm(strip_wrappers(raw)) + + +def prep_ref(label): + return norm(label) + + +def align(ref, hyp): + """Edit distance and operation counts. Backtrace from the end; at a tie the order of preference is + substitution (or match), then deletion (a reference character missing), then insertion.""" + n, m = len(ref), len(hyp) + prev = list(range(m + 1)) + rows = [prev] + for i in range(1, n + 1): + cur = [i] + [0] * m + ri = ref[i - 1] + for j in range(1, m + 1): + cost = 0 if ri == hyp[j - 1] else 1 + cur[j] = min(prev[j - 1] + cost, prev[j] + 1, cur[j - 1] + 1) + rows.append(cur) + prev = cur + dist = rows[n][m] + i, j = n, m + sub = dele = ins = 0 + while i > 0 or j > 0: + if i > 0 and j > 0 and rows[i][j] == rows[i - 1][j - 1] + (0 if ref[i - 1] == hyp[j - 1] else 1): + if ref[i - 1] != hyp[j - 1]: + sub += 1 + i -= 1 + j -= 1 + elif i > 0 and rows[i][j] == rows[i - 1][j] + 1: + dele += 1 + i -= 1 + else: + ins += 1 + j -= 1 + assert sub + dele + ins == dist + return dist, sub, dele, ins + + +def has_loop(ref, hyp): + """HR4: a block of 4 or more characters repeated 3 or more times in a row that the reference does not contain. + Reading: the whole repeated run (block x repeats) must not occur in the reference.""" + for m in _LOOP.finditer(hyp): + if m.group(0) not in ref: + return True + return False + + +def scripts_of(text): + out = set() + for ch in text: + if unicodedata.category(ch).startswith("L"): + try: + out.add(unicodedata.name(ch).split()[0]) + except ValueError: + out.add("UNKNOWN") + return out + + +def other_script(text): + """Not in the design: output has a letter that is neither Cyrillic nor Latin.""" + return bool(scripts_of(text) - {"CYRILLIC", "LATIN"}) + + +def score_crop(ref_raw, out_raw): + ref = prep_ref(ref_raw) + hyp = prep_output(out_raw) + dist, sub, dele, ins = align(ref, hyp) + rl = len(ref) + cer = dist / rl if rl else float(len(hyp) > 0) + dist_cf, _, _, _ = align(ref.casefold(), hyp.casefold()) + return { + "ref": ref, "hyp": hyp, "ref_len": rl, "hyp_len": len(hyp), "dist": dist, "sub": sub, "del": dele, + "ins": ins, "cer": cer, "dist_cf": dist_cf, "exact": hyp == ref, "exact_cf": hyp.casefold() == ref.casefold(), + "empty": hyp == "", "loop": has_loop(ref, hyp), "other_script": other_script(hyp), + "ref_other_script": other_script(ref), + "hr3": (rl >= 5) and ((len(hyp) > rl + max(4, 0.5 * rl)) or cer > 1.0), + "ref_ge5": rl >= 5, + } + + +def aggregate(scored): + n = len(scored) + if n == 0: + return {} + tot_ref = sum(s["ref_len"] for s in scored) + pooled = sum(s["dist"] for s in scored) / tot_ref + ge5 = [s for s in scored if s["ref_ge5"]] + return { + "crops": n, + "cer_mean": sum(s["cer"] for s in scored) / n, + "cer_mean_cap1": sum(min(s["cer"], 1.0) for s in scored) / n, + "cer_pooled": pooled, + "z_term_pooled_cap1": min(pooled, 1.0), + "cer_pooled_casefold": sum(s["dist_cf"] for s in scored) / tot_ref, + "exact": sum(s["exact"] for s in scored) / n, + "exact_casefold": sum(s["exact_cf"] for s in scored) / n, + "hr2_ins_per_ref_char": sum(s["ins"] for s in scored) / tot_ref, + "sub_per_ref_char": sum(s["sub"] for s in scored) / tot_ref, + "del_per_ref_char": sum(s["del"] for s in scored) / tot_ref, + "hr3_share_refs_ge5": (sum(s["hr3"] for s in ge5) / len(ge5)) if ge5 else float("nan"), + "refs_ge5": len(ge5), + "hr4_loop_share": sum(s["loop"] for s in scored) / n, + "empty_share": sum(s["empty"] for s in scored) / n, + "other_script_share": sum(s["other_script"] for s in scored) / n, + "ref_other_script_share": sum(s["ref_other_script"] for s in scored) / n, + } diff --git a/scripts/j2/setup_env_vlm.sbatch b/scripts/j2/setup_env_vlm.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..ed5f3601d19f3df1cf04e3a2f6843de7b6c66a32 --- /dev/null +++ b/scripts/j2/setup_env_vlm.sbatch @@ -0,0 +1,21 @@ +#!/bin/bash +#SBATCH --job-name=j2_env +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=4 +#SBATCH --mem=16G +#SBATCH --time=01:00:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# J2 step 1: new uv environment .venv_vlm (torch CUDA 12.8 build for H100, newest stable transformers, no vendor OCR packages). +set -eu +UV=$HOME/.local/bin/uv +VENV=/path/to/TURKIC_OCR_CODE/.venv_vlm +export UV_CACHE_DIR=/path/to/TURKIC_OCR_DATA/tmp/uv_cache +mkdir -p $UV_CACHE_DIR +$UV venv $VENV --python 3.12 +$UV pip install --python $VENV/bin/python --index-url https://download.pytorch.org/whl/cu128 torch torchvision +# stable releases only (uv skips pre-releases by default) +$UV pip install --python $VENV/bin/python transformers accelerate pillow huggingface_hub tokenizers safetensors sentencepiece protobuf numpy +$UV pip list --python $VENV/bin/python | grep -i -E "^(torch|torchvision|transformers|accelerate|pillow|huggingface[-_]hub|tokenizers|safetensors|sentencepiece|protobuf|numpy) " +echo "[j2_env] done" diff --git a/scripts/j2/smoke_cpu.sbatch b/scripts/j2/smoke_cpu.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..9c7e70e00fe4ffb1a4802ce257f2bb25e74781dd --- /dev/null +++ b/scripts/j2/smoke_cpu.sbatch @@ -0,0 +1,25 @@ +#!/bin/bash +#SBATCH --job-name=j2_smoke +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=16 +#SBATCH --mem=64G +#SBATCH --time=03:00:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# J2 step 6: smoke test, 5 crops per model on ZEN4 CPU, offline. Output goes to a separate folder (not the production one). +# usage: sbatch smoke_cpu.sbatch short [short ...] +set -u +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +export HF_HUB_OFFLINE=1 +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN || true +OUT=$DATA/outputs/j11_smoke2 +mkdir -p $OUT +for M in "$@"; do + echo "=== $M" + $CODE/.venv_vlm/bin/python -I $CODE/scripts/j2/run_screen.py $M $DATA/hf_cache/j2_models $CODE/scripts/j2/prompts.json \ + $DATA/outputs/j11_stage1_kohtd/screen_set_v1.tsv $DATA/data/processed/kohtd_words_raw/KOHTD_dataset/HK_dataset/img $OUT \ + --device cpu --threads 16 --batch-size 5 --scales 1 --limit 5 --check-batch-equal 2>&1 | grep -v -E "Loading weights|^\s*$" | tail -25 +done +echo "[j2_smoke] done" diff --git a/scripts/j2/smoke_gpu.sbatch b/scripts/j2/smoke_gpu.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..e31d0e4f233c5aacdb5821bc359362ee852dc72d --- /dev/null +++ b/scripts/j2/smoke_gpu.sbatch @@ -0,0 +1,27 @@ +#!/bin/bash +#SBATCH --job-name=j2_gpusmoke +#SBATCH --partition=H100 +#SBATCH --qos=nu-h100 +#SBATCH --gres=gpu:h100:1 +#SBATCH --cpus-per-task=16 +#SBATCH --mem=96G +#SBATCH --time=00:30:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# J2 step 6, GPU part: 16 crops per model at 1x and 2x on one H100 (checks the CUDA code path, memory counter and speed +# bookkeeping), offline, separate output folder. usage: sbatch smoke_gpu.sbatch short [short ...] +set -u +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +export HF_HUB_OFFLINE=1 +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN || true +OUT=$DATA/outputs/j11_smoke_gpu +mkdir -p $OUT +echo "job $SLURM_JOB_ID on $(hostname)" +nvidia-smi --query-gpu=name,driver_version,memory.total --format=csv +for M in "$@"; do + echo "=== $M $(date -u +%H:%M:%S)" + $CODE/.venv_vlm/bin/python -I $CODE/scripts/j2/run_screen.py $M $DATA/hf_cache/j2_models $CODE/scripts/j2/prompts.json \ + $DATA/outputs/j11_stage1_kohtd/screen_set_v1.tsv $DATA/data/processed/kohtd_words_raw/KOHTD_dataset/HK_dataset/img $OUT \ + --device cuda --batch-size 16 --scales 1,2 --limit 16 2>&1 | grep -v -E "Loading weights|^\s*$" | tail -12 +done +echo "[j2_gpusmoke] done $(date -u +%H:%M:%S)" diff --git a/scripts/j2/test_collect.py b/scripts/j2/test_collect.py new file mode 100644 index 0000000000000000000000000000000000000000..02e3feb1ade38bfd0833a3ab467e0ea1701de7bb --- /dev/null +++ b/scripts/j2/test_collect.py @@ -0,0 +1,31 @@ +"""Test collect.py on synthetic outputs with a half-written last line and no meta.json. +usage: test_collect.py SCRIPTS_DIR WORK_DIR""" +import json +import os +import subprocess +import sys + +scripts, work = sys.argv[1:3] +root = os.path.join(work, "out") +os.makedirs(os.path.join(root, "toymodel", "s1"), exist_ok=True) +os.makedirs(os.path.join(root, "loadtest"), exist_ok=True) +with open(os.path.join(root, "screen_set_v1.tsv"), "w", encoding="utf-8") as f: + f.write("crop_file\tform_id\tlabel\n0_001_001.jpg\t0\tсалық\n0_001_002.jpg\t0\t1\n0_001_003.jpg\t0\tәке\n") +with open(os.path.join(root, "toymodel", "s1", "preds.jsonl"), "w", encoding="utf-8") as f: + f.write(json.dumps({"crop_file": "0_001_001.jpg", "raw": "салық", "n_new": 3, "hit_cap": False, "n_img_tokens": 10}) + "\n") + f.write(json.dumps({"crop_file": "0_001_002.jpg", "raw": "## 1", "n_new": 2, "hit_cap": False, "n_img_tokens": 9}) + "\n") + f.write('{"crop_file": "0_001_003.jpg", "raw": "ә') # killed in the middle of a line +with open(os.path.join(root, "toymodel", "s1", "timing.jsonl"), "w", encoding="utf-8") as f: + f.write(json.dumps({"n": 2, "t_img": 0.01, "t_pre": 0.1, "t_gen": 0.4, "new_tokens": 5, "job_id": "1", "batch_first_crop": "a"}) + "\n") + f.write('{"n": 16, "t_im') +json.dump({"revision": "abc", "model_params_unique": 123}, open(os.path.join(root, "loadtest", "toymodel.json"), "w")) +res = os.path.join(work, "results_test.tsv") +subprocess.run([sys.executable, "-I", os.path.join(scripts, "collect.py"), root, os.path.join(root, "screen_set_v1.tsv"), + os.path.join(scripts, "scorelib.py"), res], check=True) +rows = [l.rstrip("\n").split("\t") for l in open(res, encoding="utf-8")] +hdr, row = rows[0], dict(zip(rows[0], rows[1])) +assert row["crops_done"] == "2" and row["crops_in_list"] == "3" and row["complete"].startswith("no"), row +assert row["bad_lines"] == "2" and row["version_revision"] == "abc" and row["params_unique"] == "123", row +assert row["cer_pooled"] == "0.0000" and row["exact_match"] == "1.0000", row # '## 1' -> '1' after the wrapper step +assert row["batch_size"] == "2" and row["job_ids"] == "1", row +print("collect.py robustness test passed") diff --git a/scripts/j2/test_contrast_stretch.py b/scripts/j2/test_contrast_stretch.py new file mode 100644 index 0000000000000000000000000000000000000000..926d1918f74862cf5b51615e5785198e620bd1b7 --- /dev/null +++ b/scripts/j2/test_contrast_stretch.py @@ -0,0 +1,45 @@ +"""Unit test of contrast_stretch. usage: test_contrast_stretch.py PATH_TO_contrast_stretch.py""" +import importlib.util +import sys + +import numpy as np +from PIL import Image + +spec = importlib.util.spec_from_file_location("cs", sys.argv[1]) +cs = importlib.util.module_from_spec(spec) +spec.loader.exec_module(cs) + +rng = np.random.default_rng(0) +base = rng.integers(100, 201, size=(61, 242, 1)).astype(np.uint8) # grey 100..200 +arr = np.repeat(base, 3, axis=2) +arr[..., 2] = np.clip(arr[..., 2].astype(int) - 20, 0, 255).astype(np.uint8) # slightly yellow tint +im = Image.fromarray(arr) +out = cs.contrast_stretch(im) +assert out.size == im.size and out.mode == "RGB" +g = np.asarray(out.convert("L"), dtype=float) +g0 = np.asarray(im.convert("L"), dtype=float) +lo, hi = np.percentile(g0, 1), np.percentile(g0, 99) +# the percentile pixels land at (about) 0 and 255 after the stretch +assert abs(np.percentile(g, 1)) < 8 and abs(np.percentile(g, 99) - 255) < 8, (np.percentile(g, 1), np.percentile(g, 99)) +# order of grey levels is kept (monotone map) +idx = np.argsort(g0.ravel(), kind="stable") +assert np.all(np.diff(np.asarray(out.convert("L"), dtype=float).ravel()[idx]) >= -1.0) +# colour relation kept: the tint (R - B difference) is kept up to the map's scale +o3 = np.asarray(out, dtype=float) +# same map for all channels: the red channel is a monotone function of the input red channel, blue likewise +assert np.all(np.diff(o3[..., 0].ravel()[np.argsort(arr[..., 0].ravel(), kind="stable")]) >= -1.0) +assert np.all(np.diff(o3[..., 2].ravel()[np.argsort(arr[..., 2].ravel(), kind="stable")]) >= -1.0) +# a flat image is returned unchanged +flat = Image.new("RGB", (30, 20), (120, 120, 120)) +assert np.array_equal(np.asarray(cs.contrast_stretch(flat)), np.asarray(flat)) +# an image already spanning 0..255 stays almost unchanged +gfull = rng.integers(0, 256, size=(40, 90, 1)).astype(np.uint8) +full = Image.fromarray(np.repeat(gfull, 3, axis=2)) +d = np.abs(np.asarray(cs.contrast_stretch(full), dtype=float) - np.asarray(full, dtype=float)).mean() +assert d < 8, d +# a grey input comes back as RGB with three equal channels +gi = Image.fromarray(rng.integers(50, 150, size=(20, 40)).astype(np.uint8), "L") +o = cs.contrast_stretch(gi) +a = np.asarray(o) +assert o.mode == "RGB" and np.array_equal(a[..., 0], a[..., 1]) and np.array_equal(a[..., 1], a[..., 2]) +print("contrast_stretch tests passed") diff --git a/scripts/j2/test_controls2_report.py b/scripts/j2/test_controls2_report.py new file mode 100644 index 0000000000000000000000000000000000000000..fbce9c314451801a1bdf1e07989aa5ca09782789 --- /dev/null +++ b/scripts/j2/test_controls2_report.py @@ -0,0 +1,60 @@ +"""Synthetic test of controls2_report.py. usage: test_controls2_report.py SCRIPTS_DIR WORK_DIR""" +import json +import os +import subprocess +import sys + +scripts, work = sys.argv[1:3] +c2 = os.path.join(work, "c2") +pr = os.path.join(work, "printed") + + +def wlist(path, rows): + with open(path, "w", encoding="utf-8", newline="") as f: + f.write("crop_file\tform_id\tlabel\n") + for i, (c, lab) in enumerate(rows): + f.write(f"{c}\t{i}\t{lab}\n") + + +def wpreds(root, model, pairs): + d = os.path.join(root, model, "s1") + os.makedirs(d, exist_ok=True) + with open(os.path.join(d, "preds.jsonl"), "w", encoding="utf-8") as f: + for c, raw in pairs: + f.write(json.dumps({"crop_file": c, "raw": raw}) + "\n") + + +os.makedirs(c2, exist_ok=True) +stored = [("0_001_001.jpg", "салық"), ("0_001_002.jpg", "1")] +stretch = [("0_001_001.png", "салық"), ("0_001_002.png", "1")] +fonts = [("caveat_kk_h40_001.png", "ашаршылық"), ("caveat_ky_h40_001.png", "кийим"), ("badscript_kk_h40_001.png", "ашаршылық")] +wlist(os.path.join(c2, "contrast_stored_screen_set_v1.tsv"), stored) +wlist(os.path.join(c2, "contrast_stretch_screen_set_v1.tsv"), stretch) +wlist(os.path.join(c2, "fonts_screen_set_v1.tsv"), fonts) +printed = [("kk_h40_001.png", "ашаршылық"), ("ky_h40_001.png", "кийим"), ("kk_h80_001.png", "ашаршылық")] +wlist(os.path.join(work, "printed_list_screen_set_v1.tsv"), printed) +m = "toy" +wpreds(os.path.join(c2, "out_stored"), m, [("0_001_001.jpg", "## салык"), ("0_001_002.jpg", "1")]) +wpreds(os.path.join(c2, "out_stretch"), m, [("0_001_001.png", "салық"), ("0_001_002.png", "I")]) +wpreds(os.path.join(c2, "out_fonts"), m, [(c, "ашаршылық" if "kk" in c else "кийим") for c, _ in fonts]) +wpreds(pr, m, [("kk_h40_001.png", "ашаршылык"), ("ky_h40_001.png", "кийим"), ("kk_h80_001.png", "x")]) +# the real script loops over two fixed model names; run it with those names by copying the toy folders +for root in (os.path.join(c2, "out_stored"), os.path.join(c2, "out_stretch"), os.path.join(c2, "out_fonts"), pr): + for name in ("paddleocr_vl_1_6", "qwen3_vl_2b"): + src = os.path.join(root, m, "s1", "preds.jsonl") + d = os.path.join(root, name, "s1") + os.makedirs(d, exist_ok=True) + open(os.path.join(d, "preds.jsonl"), "w", encoding="utf-8").write(open(src, encoding="utf-8").read()) +res = os.path.join(work, "controls_2.tsv") +subprocess.run([sys.executable, "-I", os.path.join(scripts, "controls2_report.py"), c2, os.path.join(work, "printed_list_screen_set_v1.tsv"), + pr, os.path.join(scripts, "scorelib.py"), res], check=True) +rows = [l.rstrip("\n").split("\t") for l in open(res, encoding="utf-8")] +hdr = rows[0] +d = {(r[0][:2], r[1]): dict(zip(hdr, r)) for r in rows[1:]} +assert d[("A1", "qwen3_vl_2b")]["cer_pooled"] == "0.1429" or d[("A1", "qwen3_vl_2b")]["cer_pooled"] == "0.1667", d[("A1", "qwen3_vl_2b")] +assert d[("A2", "qwen3_vl_2b")]["exact_match"] == "0.5000" +assert d[("B1", "qwen3_vl_2b")]["crops_scored"] == "2" and d[("B2", "qwen3_vl_2b")]["crops_scored"] == "1" +assert d[("B1", "qwen3_vl_2b")]["cer_pooled_kk"] == "0.0000" and d[("B1", "qwen3_vl_2b")]["cer_pooled_ky"] == "0.0000" +assert d[("C ", "qwen3_vl_2b")]["crops_scored"] == "2" # only the h40 rows +assert len(rows) - 1 == 10, len(rows) +print("controls2_report test passed") diff --git a/scripts/j2/test_scorelib.py b/scripts/j2/test_scorelib.py new file mode 100644 index 0000000000000000000000000000000000000000..f8a758c4fc300edfbc300c81a10a747f8070742e --- /dev/null +++ b/scripts/j2/test_scorelib.py @@ -0,0 +1,81 @@ +"""Unit tests for scorelib.py. usage: python -I test_scorelib.py PATH_TO_SCORELIB_PY""" +import importlib.util +import random +import sys + +spec = importlib.util.spec_from_file_location("scorelib", sys.argv[1]) +sl = importlib.util.module_from_spec(spec) +spec.loader.exec_module(sl) + + +def lev_full(a, b): + """Independent full-matrix Levenshtein (memoised recursion over indices).""" + import functools + sys.setrecursionlimit(10000) + + @functools.lru_cache(maxsize=None) + def f(i, j): + if i == 0: + return j + if j == 0: + return i + return min(f(i - 1, j) + 1, f(i, j - 1) + 1, f(i - 1, j - 1) + (a[i - 1] != b[j - 1])) + return f(len(a), len(b)) + + +assert sl.align("kitten", "sitting")[0] == 3 +assert sl.align("", "abc") == (3, 0, 0, 3) +assert sl.align("abc", "") == (3, 0, 3, 0) +assert sl.align("abc", "abc") == (0, 0, 0, 0) +d, s, dl, ins = sl.align("қазақ", "казак") +assert d == 2 and s == 2 and dl == 0 and ins == 0, (d, s, dl, ins) +# tie-break: ref "ab" hyp "b" -> one deletion; ref "b" hyp "ab" -> one insertion +assert sl.align("ab", "b") == (1, 0, 1, 0) +assert sl.align("b", "ab") == (1, 0, 0, 1) +# substitution preferred over delete+insert: "ab" vs "ba" costs 2 either way (2 subs vs del+ins) +assert sl.align("ab", "ba") == (2, 2, 0, 0), sl.align("ab", "ba") +random.seed(1) +alphabet = "аәбвгғдеёжзийкқлмнңоөпрстуұүфхһцчшщъыіьэюяabc 1" +for _ in range(3000): + a = "".join(random.choice(alphabet) for _ in range(random.randint(0, 12))) + b = "".join(random.choice(alphabet) for _ in range(random.randint(0, 16))) + d, s, dl, ins = sl.align(a, b) + assert d == lev_full(a, b), (a, b) + assert s + dl + ins == d + # lengths: len(b) - len(a) = ins - del + assert len(b) - len(a) == ins - dl, (a, b, s, dl, ins) + +# wrappers and normalisation +assert sl.prep_output("```text\nсалықты\n```") == "салықты" +assert sl.prep_output("Еңбек") == "Еңбек" +assert sl.prep_output(" а\n б ") == "а б" +assert sl.prep_output("слово<|im_end|>") == "слово" +assert sl.prep_output("## Office announcement") == "Office announcement" +assert sl.prep_output("# 1") == "1" +assert sl.prep_output("слово # 5") == "слово # 5" # a # inside the line is text +assert sl.prep_output("图片中的文本内容是:Kreinopen") == "Kreinopen" +assert sl.prep_output("图片中的文本内容是: 1") == "1" +assert sl.prep_output("$\\text{Клеин орн.}$") == "Клеин орн." +assert sl.prep_output("$\\mathcal{H}$") == "$\\mathcal{H}$" # other LaTeX is not touched +assert sl.prep_output("字词") == "字词" # no colon: kept, counts as an error and as other script +assert sl.prep_ref(" й ") == "й" # NFC: и + breve -> й +# loop +assert sl.has_loop("abc", "abcdabcdabcdabcd") is True +assert sl.has_loop("abcdabcdabcd", "abcdabcdabcd") is False # run occurs in the reference +assert sl.has_loop("abc", "aaaa") is False # block of 1 repeated, not 4+ +assert sl.has_loop("abc", "aaaaaaaaaaaa") is True # block "aaaa" x 3 +assert sl.has_loop("x", "слово слово слово слово") is True +assert sl.has_loop("x", "ab ab ab") is False # block "ab " is 3 chars +# scripts +assert sl.other_script("слово") is False and sl.other_script("word1") is False +assert sl.other_script("слово字") is True and sl.other_script("كلمة") is True +# crop score and HR3 +r = sl.score_crop("слово", "слово слово слово слово слово") +assert r["hr3"] is True and r["loop"] is True and r["ref_ge5"] is True +r = sl.score_crop("1", "11") +assert r["hr3"] is False and r["cer"] == 1.0 +r = sl.score_crop("слово", "") +assert r["empty"] is True and r["cer"] == 1.0 and r["dist"] == 5 +agg = sl.aggregate([sl.score_crop("слово", "слово"), sl.score_crop("ab", "abc")]) +assert abs(agg["cer_pooled"] - 1 / 7) < 1e-12 and agg["exact"] == 0.5 and abs(agg["hr2_ins_per_ref_char"] - 1 / 7) < 1e-12 +print("all scorelib tests passed") diff --git a/scripts/j2/valcheck.py b/scripts/j2/valcheck.py new file mode 100644 index 0000000000000000000000000000000000000000..b7f2b0865a28f05363f154772960f8deb02b94c1 --- /dev/null +++ b/scripts/j2/valcheck.py @@ -0,0 +1,27 @@ +import csv, collections, sys, unicodedata +p = "/path/to/TURKIC_OCR_DATA/data/processed/kohtd_split_v1/validation.tsv" +rows = [] +bad = 0 +with open(p, encoding="utf-8", newline="") as f: + hdr = f.readline().rstrip("\n").split("\t") + print("header", hdr) + for line in f: + parts = line.rstrip("\n").split("\t") + if len(parts) != 4: + bad += 1 + print("BAD", repr(line)[:200]) + continue + rows.append(parts) +print("rows", len(rows), "bad", bad) +forms = collections.Counter(r[1] for r in rows) +print("forms", len(forms), "min crops", min(forms.values()), "max", max(forms.values())) +print("forms<15", sum(1 for v in forms.values() if v < 15)) +print("sum min(15,n)", sum(min(15, v) for v in forms.values())) +print("empty labels", sum(1 for r in rows if r[2].strip() == "")) +print("labels with leading/trailing space", sum(1 for r in rows if r[2] != r[2].strip())) +print("labels with double space", sum(1 for r in rows if " " in r[2])) +print("labels with <", sum(1 for r in rows if "<" in r[2])) +print("labels not NFC", sum(1 for r in rows if unicodedata.normalize("NFC", r[2]) != r[2])) +print("key types", collections.Counter(r[3] for r in rows)) +lens = [len(r[2]) for r in rows] +print("label len mean", sum(lens) / len(lens), "max", max(lens), "<=2", sum(1 for x in lens if x <= 2), ">=5", sum(1 for x in lens if x >= 5)) diff --git a/scripts/k1_build_split.py b/scripts/k1_build_split.py new file mode 100644 index 0000000000000000000000000000000000000000..4f0b3b23962e9bb1f4e8deee1796eff8e49b4777 --- /dev/null +++ b/scripts/k1_build_split.py @@ -0,0 +1,120 @@ +# K1 (runs on the cluster): build the KOHTD form-disjoint split exactly as OUT/split_spec_v1.txt says. +# usage: python k1_build_split.py +# scan_map.tsv: header, then "stemsheet" for scan-named crops shown to be cuts of a sheet (their split = that sheet's form's split) +# Text only: no image is read. +import collections +import hashlib +import os +import re +import sys + +labels_path, out_dir, chk_path, key_mode, scan_map_path = sys.argv[1:6] +PREFIX = "KOHTD-split-v1-2026-11-20:" +KAZ = "әғқңөұүһі" +KAZ_UP = "ӘҒҚҢӨҰҮҺІ" + + +def bucket(key): + h = hashlib.sha256((PREFIX + str(key)).encode("utf-8")).hexdigest()[:8] + v = int(h, 16) % 100 + return "train" if v < 70 else ("validation" if v < 85 else "test") + + +num = re.compile(r"^(\d+)_(\d+)_(\d+)$") +scan = re.compile(r"^word_croped_(.+)_(-?\d+)_(\d+)$") +rows = [] +with open(labels_path, encoding="utf-8") as f: + next(f) + for line in f: + stem, _, lab = line.rstrip("\n").partition("\t") + rows.append((stem, lab)) +forms = set() +for stem, lab in rows: + m = num.match(stem) + if m: + forms.add(int(m.group(1))) +scan_map = {} +if scan_map_path != "none": + with open(scan_map_path, encoding="utf-8") as f: + next(f) + for line in f: + a = line.rstrip("\n").split("\t") + scan_map[a[0]] = int(a[1]) + + +def split_of_form(fid): + key = fid if key_mode == "form" else fid // 10 + return bucket(key) + + +os.makedirs(out_dir, exist_ok=True) +outs = {s: open(os.path.join(out_dir, s + ".tsv"), "w", encoding="utf-8") for s in ("train", "validation", "test")} +for o in outs.values(): + o.write("crop_file\tform_id\tlabel\tkey_type\n") +crops = collections.Counter() +form_set = collections.defaultdict(set) +chars = collections.defaultdict(collections.Counter) +nchars = collections.Counter() +scan_info = collections.Counter() +for stem, lab in rows: + m = num.match(stem) + if m: + fid = int(m.group(1)) + sp = split_of_form(fid) + outs[sp].write("%s.jpg\t%d\t%s\tnumbered\n" % (stem, fid, lab)) + form_set[sp].add(fid) + key_type = "numbered" + else: + m2 = scan.match(stem) + if not m2: + continue + if stem in scan_map and scan_map[stem] in forms: + fid = scan_map[stem] + sp = split_of_form(fid) + outs[sp].write("%s.jpg\t%d\t%s\tscan_named_cut_of_sheet\n" % (stem, fid, lab)) + scan_info["scan crops placed with their sheet's form"] += 1 + else: + sp = "train" + outs[sp].write("%s.jpg\tNA\t%s\tscan_named_train_only\n" % (stem, lab)) + scan_info["scan crops train only"] += 1 + key_type = "scan" + crops[(sp, key_type)] += 1 + for ch in lab: + if ch in KAZ or ch in KAZ_UP: + chars[sp][ch] += 1 + nchars[sp] += len(lab) +for o in outs.values(): + o.close() +# excluded sheets: sheet ids 0..1925 without numbered crops +with open(os.path.join(out_dir, "excluded_sheets.tsv"), "w", encoding="utf-8") as f: + f.write("sheet\tsheet_file\treason\n") + for i in range(1926): + if i not in forms: + f.write("%d\t%d.jpg\tno numbered crops (unlabelled page)\n" % (i, i)) +with open(os.path.join(out_dir, "split_stats.tsv"), "w", encoding="utf-8") as f: + f.write("split\tforms\tnumbered_crops\tscan_named_crops\ttotal_crops\tlabel_characters\n") + tot_num = sum(v for (s, k), v in crops.items() if k == "numbered") + for sp in ("train", "validation", "test"): + n_num = crops[(sp, "numbered")] + n_scan = crops[(sp, "scan")] + f.write("%s\t%d\t%d\t%d\t%d\t%d\n" % (sp, len(form_set[sp]), n_num, n_scan, n_num + n_scan, nchars[sp])) + f.write("\nlanguage-specific letters (counts in the labels of each split)\nletter\ttrain\tvalidation\ttest\n") + for ch in KAZ + KAZ_UP: + f.write("%s\t%d\t%d\t%d\n" % (ch, chars["train"][ch], chars["validation"][ch], chars["test"][ch])) + f.write("all_9_letters_lower\t%d\t%d\t%d\n" % tuple(sum(chars[sp][c] for c in KAZ) for sp in ("train", "validation", "test"))) + f.write("all_9_letters_upper\t%d\t%d\t%d\n" % tuple(sum(chars[sp][c] for c in KAZ_UP) for sp in ("train", "validation", "test"))) + f.write("all_18\t%d\t%d\t%d\n" % tuple(sum(chars[sp][c] for c in KAZ + KAZ_UP) for sp in ("train", "validation", "test"))) + f.write("\nscan-named crops: %s\n" % dict(scan_info)) + f.write("key mode: %s; forms with numbered crops: %d; excluded sheets: %d\n" % (key_mode, len(forms), 1926 - len(forms))) +# checksums +with open(chk_path, "w") as c: + for name in ("train.tsv", "validation.tsv", "test.tsv", "excluded_sheets.tsv", "split_stats.tsv", "split_spec_v1.txt"): + p = os.path.join(out_dir, name) + if not os.path.exists(p): + continue + h = hashlib.sha256() + with open(p, "rb") as g: + for chunk in iter(lambda: g.read(1 << 20), b""): + h.update(chunk) + c.write("%s %s\n" % (h.hexdigest(), p)) +print(open(os.path.join(out_dir, "split_stats.tsv"), encoding="utf-8").read()) diff --git a/scripts/k1_labels_all.py b/scripts/k1_labels_all.py new file mode 100644 index 0000000000000000000000000000000000000000..b33344334b1bb6bce5b9d0e46e0e4426e310459a --- /dev/null +++ b/scripts/k1_labels_all.py @@ -0,0 +1,25 @@ +# K1 (runs on the cluster, ZEN4): read every KOHTD ann file (JSON with the label) and write one TSV: file stem, label. +# Text only; no image is read. usage: python k1_labels_all.py +import json +import os +import sys +from concurrent.futures import ThreadPoolExecutor + +ann, out = sys.argv[1], sys.argv[2] +names = sorted(e.name for e in os.scandir(ann) if e.name.endswith(".json")) +print("ann files:", len(names), flush=True) + + +def read(n): + with open(os.path.join(ann, n), encoding="utf-8") as f: + d = json.load(f) + return n[:-5], str(d.get("description", "")).replace("\t", " ").replace("\n", " ") + + +with ThreadPoolExecutor(32) as ex, open(out, "w", encoding="utf-8") as f: + f.write("stem\tlabel\n") + for i, (stem, lab) in enumerate(ex.map(read, names, chunksize=64)): + f.write(stem + "\t" + lab + "\n") + if i % 20000 == 0: + print(i, flush=True) +print("done") diff --git a/scripts/kohtd_leak_numbered.py b/scripts/kohtd_leak_numbered.py new file mode 100644 index 0000000000000000000000000000000000000000..265e4b2435ce3a3c954e39c3f1303b490b0e4481 --- /dev/null +++ b/scripts/kohtd_leak_numbered.py @@ -0,0 +1,110 @@ +# Check 1 from review: are NUMBERED train crops duplicated in validation/test (same ink under two form ids)? Images only, no label file. +# All valid numbered train crops (80,512) against validation+test (34,853), reuse of cached features and the helpers of kohtd_leak_scan.py. +# usage: python -I kohtd_leak_numbered.py +import collections +import importlib.util +import json +import os +import re +import sys +import time + +import numpy as np + +t0 = time.time() +spec = importlib.util.spec_from_file_location("leak", "/path/to/TURKIC_OCR_CODE/scripts/kohtd_leak_scan.py") +leak = importlib.util.module_from_spec(spec) +sys.modules["leak"] = leak +spec.loader.exec_module(leak) +OUT, WORKERS = sys.argv[1], int(sys.argv[2]) +NAMES = sorted(n for n in os.listdir(leak.IMG) if n.endswith(".jpg")) +leak.NAMES = NAMES +num = re.compile(r"^(\d+)_(\d+)_(\d+)\.jpg$") +grp = np.full(len(NAMES), -1) +form = np.full(len(NAMES), -1) +for i, n in enumerate(NAMES): + m = num.match(n) + if m: + form[i] = int(m.group(1)) + grp[i] = leak.split_of_form(form[i]) + else: + grp[i] = leak.G_S +z = np.load(os.path.join(OUT, "features.npz"), allow_pickle=True) +W, H, STD, DH, PH, BAD = [z[k] for k in ("W", "H", "STD", "DH", "PH", "BAD")] +AR = (W / np.maximum(H, 1)).astype(np.float32) +valid = (~BAD) & (STD > leak.STD_MIN) +iN = np.where((grp == leak.G_N) & valid)[0] +iV = np.where((grp == leak.G_V) & valid)[0] +iT = np.where((grp == leak.G_T) & valid)[0] +DBi = np.concatenate([iV, iT]) +segs = [(0, len(iV)), (len(iV), len(DBi))] +bd, bi, _ = leak.nn(DH[iN], PH[iN], AR[iN], DH[DBi], PH[DBi], AR[DBi], segs) +best_seg = np.where(bd[:, 0] <= bd[:, 1], 0, 1) +d = bd.min(1) +dbk = np.where(best_seg == 0, bi[:, 0], bi[:, 1]) +print("matching done", round(time.time() - t0), flush=True) +TE, TH = 0.2091, 0.3751 +cand = np.where(d <= TH)[0] +pairs = [(NAMES[DBi[dbk[q]]], NAMES[iN[q]]) for q in cand] +from multiprocessing import Pool +with Pool(WORKERS) as pool: + ncc = np.array(pool.map(leak.ncc_paths, pairs, chunksize=64)) +print("ncc done", len(cand), round(time.time() - t0), flush=True) +res = {"queries_numbered_train_crops": len(iN), "database_val_plus_test": len(DBi), "pairs_hash_le_tau_hard": int(len(cand)), "pairs_hash_le_tau_easy": int((d <= TE).sum()), + "pairs_hash_le_tau_hard_and_ncc_ge_0.9": int((ncc >= 0.9).sum()), "pairs_hash_le_tau_hard_and_ncc_ge_0.85": int((ncc >= 0.85).sum()), "pairs_hash_le_tau_hard_and_ncc_ge_0.8": int((ncc >= 0.8).sum())} +sel = [k for k in range(len(cand)) if d[cand[k]] <= TE or ncc[k] >= 0.9] +rows = [] +for k in sel: + q = cand[k] + a, b = NAMES[iN[q]], NAMES[DBi[dbk[q]]] + rows.append({"train_crop": a, "train_form": int(form[iN[q]]), "train_wxh": [int(W[iN[q]]), int(H[iN[q]])], "vt_crop": b, "vt_form": int(form[DBi[dbk[q]]]), "vt_split": "validation" if best_seg[q] == 0 else "test", + "vt_wxh": [int(W[DBi[dbk[q]]]), int(H[DBi[dbk[q]]])], "hash_distance": round(float(d[q]), 4), "ncc": round(float(ncc[k]), 4)}) +res["pairs_listed_hash_le_easy_or_ncc_ge_0.9"] = len(rows) +res["of_those_hash_le_easy_and_ncc_ge_0.9"] = int(sum(1 for r in rows if r["hash_distance"] <= TE and r["ncc"] >= 0.9)) +gp = collections.Counter((r["train_form"], r["vt_form"]) for r in rows) +res["form_pairs_with_pairs"] = len(gp) +res["max_pairs_on_one_form_pair"] = max(gp.values()) if gp else 0 +res["form_pairs_top10"] = [{"train_form": a, "vt_form": b, "n": c} for (a, b), c in gp.most_common(10)] +tf = collections.Counter(r["train_form"] for r in rows) +vf = collections.Counter(r["vt_form"] for r in rows) +res["max_pairs_per_train_form"] = max(tf.values()) if tf else 0 +res["max_pairs_per_vt_form"] = max(vf.values()) if vf else 0 +res["distinct_train_forms"] = len(tf) +res["distinct_vt_forms"] = len(vf) +ar = np.array([r["train_wxh"][0] * r["train_wxh"][1] for r in rows]) if rows else np.array([0]) +res["median_area_px_of_listed_train_crops"] = float(np.median(ar)) +res["median_area_px_all_train_crops"] = float(np.median((W[iN] * H[iN]).astype(np.float64))) +rows.sort(key=lambda r: (-(r["ncc"] >= 0.9), r["hash_distance"])) +res["pairs_listed"] = rows +# side by side images, 20 pairs in two panels +from PIL import Image, ImageDraw, ImageFont +font = ImageFont.truetype(leak.FONT, 13) +sh = rows[:20] +for pi in range(2): + chunk = sh[pi * 10:(pi + 1) * 10] + if not chunk: + continue + panels = [] + for r in chunk: + _, ga = leak.load(os.path.join(leak.IMG, r["train_crop"])) + _, gb = leak.load(os.path.join(leak.IMG, r["vt_crop"])) + hh = 70 + A = Image.fromarray(ga).resize((max(1, int(ga.shape[1] * hh / ga.shape[0])), hh)) + B = Image.fromarray(gb).resize((max(1, int(gb.shape[1] * hh / gb.shape[0])), hh)) + c = Image.new("L", (A.width + B.width + 50, hh + 22), 255) + c.paste(A, (5, 20)) + c.paste(B, (A.width + 40, 20)) + ImageDraw.Draw(c).text((5, 2), "train %s | %s %s | d %.3f ncc %.3f" % (r["train_crop"], r["vt_split"], r["vt_crop"], r["hash_distance"], r["ncc"]), font=font, fill=0) + panels.append(c) + Wp = max(p.width for p in panels) + img = Image.new("L", (Wp, sum(p.height + 6 for p in panels)), 255) + y = 0 + for p in panels: + img.paste(p, (0, y)) + y += p.height + 6 + img.save(os.path.join(OUT, "numbered_pairs_panel_%d.png" % (pi + 1))) +res["job_id"] = os.environ.get("SLURM_JOB_ID", "none") +res["runtime_seconds"] = round(time.time() - t0) +with open(os.path.join(OUT, "result_numbered.json"), "w", encoding="utf-8") as f: + json.dump(res, f, ensure_ascii=False, indent=1) +print("DONE", round(time.time() - t0), flush=True) diff --git a/scripts/kohtd_leak_numbered.sbatch b/scripts/kohtd_leak_numbered.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..d049e97d002501a1796641bc6cfca9cddb4587b2 --- /dev/null +++ b/scripts/kohtd_leak_numbered.sbatch @@ -0,0 +1,14 @@ +#!/bin/bash +#SBATCH --job-name=kohtd_leak_num +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=16 +#SBATCH --mem=48G +#SBATCH --time=00:40:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +C=/path/to/TURKIC_OCR_CODE +D=/path/to/TURKIC_OCR_DATA +echo "== start $(date) job $SLURM_JOB_ID" +$C/.venv/bin/python -I $C/scripts/kohtd_leak_numbered.py $D/outputs/r5/leak_kohtd_scan 16 +echo "== end $(date)" diff --git a/scripts/kohtd_leak_scan.py b/scripts/kohtd_leak_scan.py new file mode 100644 index 0000000000000000000000000000000000000000..1867b0550ea8fcf2bba46f237212ba00ad9f7aa8 --- /dev/null +++ b/scripts/kohtd_leak_scan.py @@ -0,0 +1,507 @@ +# Leakage check: do the 24,989 scan-named KOHTD training crops come from forms in the validation or test split? +# IMAGES ONLY. No label file is read. Split membership is rebuilt from the crop file names with the pre-registered hash rule +# (DATA/data/processed/kohtd_split_v1/split_spec_v1.txt, rule (b)) and checked against the published counts. +# usage: python -I kohtd_leak_scan.py +import collections +import hashlib +import json +import math +import os +import random +import re +import sys +import time + +import cv2 +import numpy as np + +cv2.setNumThreads(1) +IMG = "/path/to/TURKIC_OCR_DATA/data/processed/kohtd_words_raw/KOHTD_dataset/HK_dataset/img" +OUT = sys.argv[1] +WORKERS = int(sys.argv[2]) +SEED = 20261125 +PREFIX = "KOHTD-split-v1-2026-11-20:" +STD_MIN = 5.0 # near-blank filter, as in K1 +ASPECT_LOG = math.log(1.15) # aspect-ratio gate: within 15 percent +EXPECT = {"train_numbered": 80513, "validation": 16238, "test": 18615, "scan": 24989} +FONT = "/path/to/TURKIC_OCR_CODE/.venv/lib/python3.12/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans.ttf" +NAMES = [] +G_S, G_N, G_V, G_T = 0, 1, 2, 3 # groups: scan-named, numbered train, numbered validation, numbered test + + +def split_of_form(fid): + v = int(hashlib.sha256((PREFIX + str(fid)).encode("utf-8")).hexdigest()[:8], 16) % 100 + return G_N if v < 70 else (G_V if v < 85 else G_T) + + +def ink_map(g): + bg = float(np.percentile(g, 70)) + ink = np.clip(bg - g.astype(np.float32), 0, None) + ink[ink < 25] = 0 + return ink / 255.0 + + +def hashes(g): + ink = ink_map(g) + t = cv2.resize(ink, (17, 16), interpolation=cv2.INTER_AREA) + a, b = t[:, 1:], t[:, :-1] + bits = np.concatenate([(a > b + 0.01).ravel(), (a < b - 0.01).ravel()]).astype(np.uint8) # 512 bits: rise, fall + dh = np.packbits(bits).view(np.uint64) + t32 = cv2.resize(ink, (32, 32), interpolation=cv2.INTER_AREA).astype(np.float32) + d = cv2.dct(t32)[:8, :8].ravel() + ph = np.packbits((d > np.median(d[1:])).astype(np.uint8)).view(np.uint64) # 64 bits + return dh, ph + + +def load(path): + with open(path, "rb") as f: + b = f.read() + return b, cv2.imdecode(np.frombuffer(b, np.uint8), cv2.IMREAD_GRAYSCALE) + + +def work(i): + try: + b, g = load(os.path.join(IMG, NAMES[i])) + except Exception: + return i, None + if g is None: + return i, None + h, w = g.shape + dh, ph = hashes(g) + return i, (hashlib.sha256(b).hexdigest(), hashlib.sha256(g.tobytes() + str(g.shape).encode()).hexdigest(), w, h, float(g.std()), dh, ph) + + +def ncc_arrays(a, b): + """a: DB crop (gray), b: scan crop (gray). Resize b to a's size, blur, shift +-4 px, return max TM_CCOEFF_NORMED.""" + ia, ib = ink_map(a), ink_map(b) + h, w = ia.shape + ib = cv2.resize(ib, (w, h), interpolation=cv2.INTER_AREA) + if ia.std() < 1e-6 or ib.std() < 1e-6: + return -1.0 + ia = cv2.GaussianBlur(ia, (0, 0), 1.0) + ib = cv2.GaussianBlur(ib, (0, 0), 1.0) + ia = cv2.copyMakeBorder(ia, 4, 4, 4, 4, cv2.BORDER_CONSTANT, value=0) + r = cv2.matchTemplate(ia, ib, cv2.TM_CCOEFF_NORMED) + return float(np.nanmax(r)) + + +def ncc_paths(pair): + try: + _, a = load(os.path.join(IMG, pair[0])) + _, b = load(os.path.join(IMG, pair[1])) + return ncc_arrays(a, b) + except Exception: + return -2.0 + + +def pack_feats(gs): + dh = np.zeros((len(gs), 8), np.uint64) + ph = np.zeros((len(gs), 1), np.uint64) + ar = np.zeros(len(gs), np.float32) + for k, g in enumerate(gs): + dh[k], ph[k] = hashes(g) + ar[k] = g.shape[1] / g.shape[0] + return dh, ph, ar + + +def nn(Qdh, Qph, Qar, Ddh, Dph, Dar, segs, exclude=None, chunk=64): + """Nearest neighbour by combined distance d = dHash512/512 + pHash64/64 (0..2), aspect-gated. + segs: list of (lo, hi) in the DB; returns best dist and global index per segment (nq, nseg), plus best-other dist if exclude given.""" + DT = np.ascontiguousarray(Ddh.T) + PT = np.ascontiguousarray(Dph.T) + nq, n = len(Qdh), len(Ddh) + bd = np.full((nq, len(segs)), 9.0, np.float32) + bi = np.full((nq, len(segs)), -1, np.int64) + other = np.full(nq, 9.0, np.float32) + lar = np.log(Dar)[None, :] + for s in range(0, nq, chunk): + e = min(nq, s + chunk) + dh = np.zeros((e - s, n), np.uint16) + for k in range(8): + dh += np.bitwise_count(Qdh[s:e, k, None] ^ DT[k][None, :]) + ph = np.bitwise_count(Qph[s:e, 0, None] ^ PT[0][None, :]).astype(np.uint16) + dist = dh.astype(np.float32) / 512.0 + ph.astype(np.float32) / 64.0 + dist[np.abs(np.log(Qar[s:e])[:, None] - lar) > ASPECT_LOG] = 9.0 + if exclude is not None: + ex = exclude[s:e] + sel = ex >= 0 + tmp = dist[np.arange(e - s)[sel], ex[sel]].copy() + dist[np.arange(e - s)[sel], ex[sel]] = 9.0 + other[s:e] = dist.min(1) + dist[np.arange(e - s)[sel], ex[sel]] = tmp + for j, (lo, hi) in enumerate(segs): + k = dist[:, lo:hi].argmin(1) + bi[s:e, j] = lo + k + bd[s:e, j] = dist[np.arange(e - s), lo + k] + return bd, bi, other + + +def degrade(g, rng, hard, f=1.78): + h, w = g.shape + up = cv2.resize(g, None, fx=f, fy=f, interpolation=cv2.INTER_LINEAR if f >= 1 else cv2.INTER_AREA) + hh, ww = up.shape + m = (0.02, 0.04) if hard else (0.01, 0.02) + t, bt, l, r = [int(round(rng.uniform(*m) * (hh if k < 2 else ww))) for k in range(4)] + up = up[t:hh - bt, l:ww - r] + x = up.astype(np.float32) + if hard: + ang = rng.uniform(-1.0, 1.0) + H, W = x.shape + M = cv2.getRotationMatrix2D((W / 2, H / 2), ang, 1.0) + x = cv2.warpAffine(x, M, (W, H), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT, borderValue=255) + x = x * 0.88 + 8.0 + x = x + np.random.RandomState(rng.randint(0, 2 ** 31 - 1)).normal(0, 4.0, x.shape) + x = np.clip(x, 0, 255).astype(np.uint8) + ok, buf = cv2.imencode(".jpg", x, [cv2.IMWRITE_JPEG_QUALITY, 75 if hard else 85]) + return cv2.imdecode(buf, cv2.IMREAD_GRAYSCALE) + + +def qs(a, ps=(0, 0.1, 1, 5, 25, 50, 75, 95, 99, 100)): + a = np.asarray(a, dtype=np.float64) + return {str(p): round(float(np.percentile(a, p)), 4) for p in ps} if len(a) else {} + + +def main(): + global NAMES + t0 = time.time() + os.makedirs(OUT, exist_ok=True) + job = os.environ.get("SLURM_JOB_ID", "none") + res = {"job_id": job, "seed": SEED} + NAMES = sorted(n for n in os.listdir(IMG) if n.endswith(".jpg")) + num = re.compile(r"^(\d+)_(\d+)_(\d+)\.jpg$") + scan = re.compile(r"^word_croped_(.+)_(-?\d+)_(\d+)\.jpg$") + grp, form, sname, srow = [], [], [], [] + other = [] + for n in NAMES: + m = num.match(n) + if m: + fid = int(m.group(1)) + grp.append(split_of_form(fid)) + form.append(fid) + sname.append("") + srow.append(0) + continue + m = scan.match(n) + if m: + grp.append(G_S) + form.append(-1) + sname.append(m.group(1)) + srow.append(int(m.group(2))) + else: + other.append(n) + grp.append(-1) + form.append(-1) + sname.append("") + srow.append(0) + grp, form, srow = np.array(grp), np.array(form), np.array(srow) + counts = {"files": len(NAMES), "unparsed": len(other), "scan": int((grp == G_S).sum()), "train_numbered": int((grp == G_N).sum()), + "validation": int((grp == G_V).sum()), "test": int((grp == G_T).sum())} + counts["matches_published_split_stats"] = all(counts[k] == v for k, v in EXPECT.items()) + res["membership_rebuilt_from_file_names"] = counts + print("counts", counts, flush=True) + + # ---- features for all crops (cached) ---- + cache = os.path.join(OUT, "features.npz") + if os.path.exists(cache): + z = np.load(cache, allow_pickle=True) + sha, pix, W, H, STD, DH, PH, BAD = [z[k] for k in ("sha", "pix", "W", "H", "STD", "DH", "PH", "BAD")] + else: + from multiprocessing import Pool + n = len(NAMES) + sha, pix = np.empty(n, dtype=object), np.empty(n, dtype=object) + W, H, STD = np.zeros(n, np.int32), np.zeros(n, np.int32), np.zeros(n, np.float32) + DH, PH, BAD = np.zeros((n, 8), np.uint64), np.zeros((n, 1), np.uint64), np.zeros(n, bool) + with Pool(WORKERS) as pool: + for k, (i, r) in enumerate(pool.imap_unordered(work, range(n), chunksize=256)): + if r is None: + BAD[i] = True + continue + sha[i], pix[i], W[i], H[i], STD[i], DH[i], PH[i] = r + if k % 20000 == 0: + print("features", k, round(time.time() - t0), "s", flush=True) + np.savez(cache, sha=sha, pix=pix, W=W, H=H, STD=STD, DH=DH, PH=PH, BAD=BAD) + print("features done", round(time.time() - t0), "s", flush=True) + res["unreadable_files"] = int(BAD.sum()) + valid = (~BAD) & (STD > STD_MIN) + res["near_blank_dropped_std_le_5"] = {g: int(((grp == c) & ~BAD & (STD <= STD_MIN)).sum()) for g, c in (("scan", G_S), ("train_numbered", G_N), ("validation", G_V), ("test", G_T))} + AR = (W / np.maximum(H, 1)).astype(np.float32) + + # ---- exact duplicates ---- + def dup_report(key, label): + by = collections.defaultdict(list) + for i in range(len(NAMES)): + if not BAD[i]: + by[key[i]].append(i) + groups = [v for v in by.values() if len(v) > 1] + cross = {"scan_with_validation": 0, "scan_with_test": 0, "scan_with_train_numbered": 0, "scan_with_scan": 0} + for v in groups: + gs = set(int(grp[i]) for i in v) + if G_S in gs and G_V in gs: + cross["scan_with_validation"] += 1 + if G_S in gs and G_T in gs: + cross["scan_with_test"] += 1 + if G_S in gs and G_N in gs: + cross["scan_with_train_numbered"] += 1 + if sum(1 for i in v if grp[i] == G_S) > 1: + cross["scan_with_scan"] += 1 + return {"duplicate_groups": len(groups), "files_in_groups": sum(len(v) for v in groups), "groups_by_kind": cross, "label": label} + res["exact_duplicates_file_sha256"] = dup_report(sha, "sha256 of the file bytes") + res["exact_duplicates_decoded_pixels"] = dup_report(pix, "sha256 of the decoded grayscale pixels") + print("exact dup", res["exact_duplicates_file_sha256"], res["exact_duplicates_decoded_pixels"], flush=True) + + # ---- sets ---- + iS = np.where((grp == G_S) & valid)[0] + iN = np.where((grp == G_N) & valid)[0] + iV = np.where((grp == G_V) & valid)[0] + iT = np.where((grp == G_T) & valid)[0] + DBi = np.concatenate([iV, iT, iN]) # DB order: V, T, N + segs = [(0, len(iV)), (len(iV), len(iV) + len(iT)), (len(iV) + len(iT), len(DBi))] + Ddh, Dph, Dar = DH[DBi], PH[DBi], AR[DBi] + res["valid_crops_used"] = {"scan": len(iS), "train_numbered": len(iN), "validation": len(iV), "test": len(iT)} + + # ---- positive controls ---- + rng = random.Random(SEED) + ctrl_src = rng.sample(list(iN), 600) + pos_in_db = {int(d): k for k, d in enumerate(DBi)} + ctrl = {} + dbidx = np.array([pos_in_db[int(i)] for i in ctrl_src]) + for hard in (False, True): + gs, orig = [], [] + for i in ctrl_src: + _, g = load(os.path.join(IMG, NAMES[i])) + gs.append((g, degrade(g, rng, hard))) + dh, ph, ar = pack_feats([x[1] for x in gs]) + bd, bi, oth = nn(dh, ph, ar, Ddh, Dph, Dar, [(0, len(DBi))], exclude=dbidx) + top1_ok = (bi[:, 0] == dbidx) + # true-pair distance: recompute through nn with exclude trick: distance to original = need explicit + true_d = [] + for k in range(len(gs)): + a = np.bitwise_count(dh[k] ^ Ddh[dbidx[k]]).sum() / 512.0 + np.bitwise_count(ph[k] ^ Dph[dbidx[k]]).sum() / 64.0 + true_d.append(float(a)) + nccs = [ncc_arrays(gs[k][0], gs[k][1]) for k in range(len(gs))] + name = "hard" if hard else "easy" + ctrl[name] = {"n": len(gs), "top1_recall_all_numbered_db": float(top1_ok.mean()), "true_pair_dist": qs(true_d), "best_other_dist": qs(oth), + "true_pair_ncc": qs(nccs), "description": ("scale x1.78 + JPEG q75 + crop margins 2-4% + rotation +-1 deg + contrast 0.88x+8 + gaussian noise sd 4" if hard else "scale x1.78 + JPEG q85 + crop margins 1-2%")} + ctrl[name]["true_pair_ncc_fraction_ge"] = {str(t): round(float(np.mean(np.array(nccs) >= t)), 3) for t in (0.6, 0.7, 0.8, 0.85, 0.9)} + ctrl[name]["_p95_true"] = float(np.percentile(true_d, 95)) + ctrl[name]["_ncc_p5"] = float(np.percentile(nccs, 5)) + tau_easy, tau_hard = ctrl["easy"].pop("_p95_true"), ctrl["hard"].pop("_p95_true") + ctrl["easy"].pop("_ncc_p5"), ctrl["hard"].pop("_ncc_p5") + res["positive_controls"] = ctrl + # reverse control in the scan domain: 600 scan crops shrunk by 1/1.78 (numbered-crop size) and matched against the scan crops themselves + rev = {} + rs = random.Random(SEED + 5) + src = rs.sample(list(iS), 600) + pos_s = {int(d): k for k, d in enumerate(iS)} + exs = np.array([pos_s[int(i)] for i in src]) + for hard in (False, True): + gs = [] + for i in src: + _, g = load(os.path.join(IMG, NAMES[i])) + gs.append((g, degrade(g, rs, hard, f=1 / 1.78))) + dh, ph, ar = pack_feats([x[1] for x in gs]) + bd2, bi2, oth2 = nn(dh, ph, ar, DH[iS], PH[iS], AR[iS], [(0, len(iS))], exclude=exs) + td = [float(np.bitwise_count(dh[k] ^ DH[iS][exs[k]]).sum() / 512.0 + np.bitwise_count(ph[k] ^ PH[iS][exs[k]]).sum() / 64.0) for k in range(len(gs))] + nc2 = [ncc_arrays(gs[k][0], gs[k][1]) for k in range(len(gs))] + rev["hard" if hard else "easy"] = {"n": len(gs), "top1_recall_among_scan_crops": float((bi2[:, 0] == exs).mean()), "true_pair_dist": qs(td), "best_other_dist": qs(oth2), "true_pair_ncc": qs(nc2), + "fraction_true_pairs_within_tau_hard_0.3751": round(float(np.mean(np.array(td) <= 0.3751)), 3), + "description": "scan-named crop shrunk to 1/1.78 (numbered-crop size), same distortions as the forward control"} + res["reverse_controls_scan_domain"] = rev + res["thresholds"] = {"hash_distance": "d = dHash512/512 + pHash64/64 on the ink map (0 = identical, 2 = opposite); aspect-ratio gate within 15 percent", + "tau_easy_p95_of_true_pairs": round(tau_easy, 4), "tau_hard_p95_of_true_pairs": round(tau_hard, 4)} + print("controls", json.dumps(ctrl)[:1500], flush=True) + + # ---- real query: scan-named crops against V, T, N ---- + bdS, biS, _ = nn(DH[iS], PH[iS], AR[iS], Ddh, Dph, Dar, segs) + # ---- null query: a random sample of numbered TRAIN crops, same size, against V and T only (form-disjoint by construction) ---- + nrng = np.random.RandomState(SEED) + sampN = nrng.choice(iN, len(iS), replace=False) + VT = (0, len(iV) + len(iT)) + DdhVT, DphVT, DarVT = Ddh[:VT[1]], Dph[:VT[1]], Dar[:VT[1]] + bdN, biN, _ = nn(DH[sampN], PH[sampN], AR[sampN], DdhVT, DphVT, DarVT, [(0, len(iV)), (len(iV), VT[1])]) + print("matching done", round(time.time() - t0), "s", flush=True) + + realVT = np.minimum(bdS[:, 0], bdS[:, 1]) + nullVT = np.minimum(bdN[:, 0], bdN[:, 1]) + ladder = [round(tau_easy, 4), round(tau_hard, 4), 0.10, 0.20, 0.30, 0.40, 0.50, 0.60] + lad = {} + for t in ladder: + lad[str(t)] = {"scan_to_validation": int((bdS[:, 0] <= t).sum()), "scan_to_test": int((bdS[:, 1] <= t).sum()), "scan_to_train_numbered": int((bdS[:, 2] <= t).sum()), + "scan_to_val_or_test": int((realVT <= t).sum()), "NULL_trainnumbered_sample_to_val_or_test": int((nullVT <= t).sum())} + res["hash_counts_by_threshold_crops"] = lad + res["nearest_distance_quantiles"] = {"scan_to_val_or_test": qs(realVT), "NULL_trainnumbered_to_val_or_test": qs(nullVT), "scan_to_train_numbered": qs(bdS[:, 2]), "scan_to_all_numbered": qs(bdS.min(1))} + res["nearest_distance_note"] = "NULL = 24,989 random numbered TRAIN crops matched against validation+test crops; train forms differ from val/test forms by construction (checked by the hash rule), so every NULL neighbour is a different page." + + # ---- NCC second check on the closest pairs ---- + from multiprocessing import Pool + best_seg = np.where(bdS[:, 0] <= bdS[:, 1], 0, 1) + real_idx = np.where(best_seg == 0, biS[:, 0], biS[:, 1]) # DB index + null_best_seg = np.where(bdN[:, 0] <= bdN[:, 1], 0, 1) + null_idx = np.where(null_best_seg == 0, biN[:, 0], biN[:, 1]) + K = int(max(300, min(3000, (realVT <= tau_hard).sum()))) + ordR = np.argsort(realVT)[:K] + ordN = np.argsort(nullVT)[:K] + pairsR = [(NAMES[DBi[real_idx[q]]], NAMES[iS[q]]) for q in ordR] + pairsN = [(NAMES[DBi[null_idx[q]]], NAMES[sampN[q]]) for q in ordN] + rand_q = nrng.choice(len(iS), 2000, replace=False) + pairsN_rand = [(NAMES[DBi[null_idx[q]]], NAMES[sampN[q]]) for q in rand_q] + with Pool(WORKERS) as pool: + nccR = np.array(pool.map(ncc_paths, pairsR, chunksize=32)) + nccN = np.array(pool.map(ncc_paths, pairsN, chunksize=32)) + nccNr = np.array(pool.map(ncc_paths, pairsN_rand, chunksize=32)) + thr_ncc = 0.85 # fixed in advance (reviewer advice before the first result was seen) + res["ncc_second_check"] = {"K_closest_pairs_checked": K, "method": "scan crop resized to the val/test crop size, ink map, gaussian blur 1 px, max TM_CCOEFF_NORMED over +-4 px shifts", + "real_closest_K_ncc": qs(nccR), "NULL_closest_K_ncc": qs(nccN), "NULL_random_top1_ncc": qs(nccNr), "threshold_ncc_fixed_in_advance": thr_ncc, "ncc_ladder_real_closest_K_count_ge": {str(t): int((nccR >= t).sum()) for t in (0.6, 0.7, 0.8, 0.85, 0.9)}, "ncc_ladder_NULL_closest_K_count_ge": {str(t): int((nccN >= t).sum()) for t in (0.6, 0.7, 0.8, 0.85, 0.9)}, + "hard_control_ncc_p5": ctrl["hard"]["true_pair_ncc"].get("5"), "easy_control_ncc_p5": ctrl["easy"]["true_pair_ncc"].get("5")} + conf_mask = (realVT[ordR] <= tau_hard) & (nccR >= thr_ncc) + conf_null = (nullVT[ordN] <= tau_hard) & (nccN >= thr_ncc) + conf_q = ordR[conf_mask] + res["confirmed_near_duplicates"] = {"rule": "hash distance <= tau_hard AND NCC >= threshold_ncc", "crops": int(conf_mask.sum()), "NULL_expected_false_positives_same_rule": int(conf_null.sum()), + "in_validation": int((best_seg[conf_q] == 0).sum()), "in_test": int((best_seg[conf_q] == 1).sum())} + + # ---- vote per scan name ---- + snames = np.array([re.match(scan, NAMES[i]).group(1) for i in iS]) + allbest = bdS.argmin(1) + best_dist = bdS.min(1) + best_db = biS[np.arange(len(iS)), allbest] + best_form = form[DBi[best_db]] + best_grp = grp[DBi[best_db]] + by_name = collections.defaultdict(list) + for q in range(len(iS)): + by_name[snames[q]].append(q) + names3 = [k for k, v in by_name.items() if len(v) >= 3] + + def maxvotes(forms_arr): + out = {} + for k in names3: + c = collections.Counter(int(forms_arr[q]) for q in by_name[k] if forms_arr[q] >= 0) + out[k] = c.most_common(1)[0] if c else (-1, 0) + return out + + def vote_summary(forms_arr, label): + real = maxvotes(forms_arr) + rv = np.array([v[1] for v in real.values()]) + prng = np.random.RandomState(SEED + 1) + perm_counts = {k: [] for k in (2, 3, 4, 5)} + for _ in range(200): + fa = prng.permutation(forms_arr) + pv = np.array([v[1] for v in maxvotes(fa).values()]) + for k in perm_counts: + perm_counts[k].append(int((pv >= k).sum())) + return {"label": label, "scan_names_with_3plus_valid_crops": len(names3), + "names_with_max_votes_ge": {str(k): int((rv >= k).sum()) for k in perm_counts}, + "PERMUTATION_NULL_mean_names_ge": {str(k): round(float(np.mean(v)), 2) for k, v in perm_counts.items()}, + "PERMUTATION_NULL_max_names_ge": {str(k): int(np.max(v)) for k, v in perm_counts.items()}}, real + allforms = best_form.copy() + s_all, real_all = vote_summary(allforms, "every crop votes for the form of its nearest numbered crop (aspect-gated), no distance limit") + close_forms = np.where(best_dist <= tau_hard, best_form, -1) + s_close, real_close = vote_summary(close_forms, "only crops whose nearest numbered crop is within tau_hard vote") + res["vote_per_scan_name"] = {"all_crops": s_all, "close_crops_only": s_close, + "crops_whose_nearest_numbered_crop_is_within_tau_hard": int((best_dist <= tau_hard).sum()), + "their_split": {"validation": int(((best_dist <= tau_hard) & (best_grp == G_V)).sum()), "test": int(((best_dist <= tau_hard) & (best_grp == G_T)).sum()), + "train_numbered": int(((best_dist <= tau_hard) & (best_grp == G_N)).sum())}} + # NCC of voting pairs in names that pile up on a val/test form + vp = [] + for k, (fid, c) in real_all.items(): + if c >= 3 and fid >= 0 and split_of_form(fid) in (G_V, G_T): + for q in by_name[k]: + if best_form[q] == fid: + vp.append((NAMES[DBi[best_db[q]]], NAMES[iS[q]], k, fid, float(best_dist[q]))) + vp = vp[:1500] + with Pool(WORKERS) as pool: + nv = np.array(pool.map(ncc_paths, [(a, b) for a, b, _, _, _ in vp], chunksize=32)) if vp else np.array([]) + res["vote_per_scan_name"]["names_piling_on_a_val_or_test_form_3plus"] = len(set(v[2] for v in vp)) + res["vote_per_scan_name"]["their_voting_pairs_ncc"] = qs(nv) + res["vote_per_scan_name"]["their_voting_pairs_ncc_ge_threshold"] = int((nv >= thr_ncc).sum()) if len(nv) else 0 + res["vote_per_scan_name"]["linked_names_vote3_and_ncc_ge_threshold"] = None + linked = collections.defaultdict(int) + for (a, b, k, fid, d), v in zip(vp, nv): + if v >= thr_ncc: + linked[(k, fid)] += 1 + ln = [(k, fid, c) for (k, fid), c in linked.items() if c >= 3] + res["vote_per_scan_name"]["linked_names_vote3_and_ncc_ge_threshold"] = {"count": len(ln), "details": [{"scan_name": k, "form": fid, "split": ["train", "validation", "test"][split_of_form(fid) - 1], "crops_voting_and_confirmed": c} for k, fid, c in ln[:20]], + "crops_of_linked_names": int(sum(len(by_name[k]) for k, _, _ in ln))} + + # ---- examples: five closest scan-to-val/test pairs by NCC among the K closest by hash ---- + order_ex = np.argsort(-nccR)[:5] + ex = [] + from PIL import Image, ImageDraw, ImageFont + font = ImageFont.truetype(FONT, 14) + panels = [] + for r, o in enumerate(order_ex): + q = ordR[o] + sa, db = NAMES[iS[q]], NAMES[DBi[real_idx[q]]] + d = float(realVT[q]) + nc = float(nccR[o]) + confirmed = bool(d <= tau_hard and nc >= thr_ncc) + fid = int(form[DBi[real_idx[q]]]) + spl = "validation" if best_seg[q] == 0 else "test" + ex.append({"rank": r + 1, "scan_named_crop": sa, "val_or_test_crop": db, "form_id": fid, "split": spl, "hash_distance": round(d, 4), "ncc": round(nc, 4), "confirmed_duplicate": confirmed}) + _, ga = load(os.path.join(IMG, sa)) + _, gb = load(os.path.join(IMG, db)) + hh = 130 + A = Image.fromarray(ga).resize((max(1, int(ga.shape[1] * hh / ga.shape[0])), hh)) + B = Image.fromarray(gb).resize((max(1, int(gb.shape[1] * hh / gb.shape[0])), hh)) + canvas = Image.new("L", (A.width + B.width + 60, hh + 50), 255) + canvas.paste(A, (10, 40)) + canvas.paste(B, (A.width + 50, 40)) + dr = ImageDraw.Draw(canvas) + dr.text((10, 4), "%d scan-named: %s" % (r + 1, sa[:60]), font=font, fill=0) + dr.text((10, 22), "%s form %d (%s) hash dist %.3f NCC %.3f %s" % (db, fid, spl, d, nc, "CONFIRMED" if confirmed else "closest, not a confirmed duplicate"), font=font, fill=0) + canvas.save(os.path.join(OUT, "pair_%d.png" % (r + 1))) + panels.append(canvas) + Wp = max(p.width for p in panels) + panel = Image.new("L", (Wp, sum(p.height + 10 for p in panels)), 255) + y = 0 + for p in panels: + panel.paste(p, (0, y)) + y += p.height + 10 + panel.save(os.path.join(OUT, "examples_panel.png")) + res["examples_five_closest_scan_to_val_or_test"] = ex + + # ---- step 4: name structure and image traits ---- + snm = re.compile(r"^Скан_(\d{8})(?:_(\d+))?(?: \((\d+)\))?$") + names_all = sorted(set(sname[i] for i in range(len(NAMES)) if grp[i] == G_S)) + per_date = collections.defaultdict(lambda: {"names": 0, "crops": 0, "n_values": set(), "heights": []}) + unparsed = 0 + name_date = {} + for s in names_all: + m = snm.match(s) + if not m: + unparsed += 1 + continue + name_date[s] = m.group(1) + per_date[m.group(1)]["names"] += 1 + if m.group(2): + per_date[m.group(1)]["n_values"].add(int(m.group(2))) + for i in range(len(NAMES)): + if grp[i] == G_S and not BAD[i] and sname[i] in name_date: + per_date[name_date[sname[i]]]["crops"] += 1 + per_date[name_date[sname[i]]]["heights"].append(int(H[i])) + res["scan_name_structure"] = {"names": len(names_all), "unparsed": unparsed, "crops_with_row_minus1": int(((grp == G_S) & (srow == -1)).sum()), + "pattern": "Скан_YYYYMMDD[_n][ (k)] = scanner export file name (date, batch number n, copy number k); the meaning of n and k is NOT documented (unknown)", + "per_date": {d: {"names": v["names"], "crops": v["crops"], "n_range": [min(v["n_values"]), max(v["n_values"])] if v["n_values"] else None, "median_crop_height": float(np.median(v["heights"])) if v["heights"] else None} for d, v in sorted(per_date.items())}, + "note": "The sheet archive folder is named 20200929_Examination_sheets_cleaned; 500 scan names carry the date 20200929. Flagged as a coincidence, not evidence of a link."} + ms, mn = (np.median(W[iS]), np.median(H[iS])), (np.median(W[iN]), np.median(H[iN])) + res["crop_size_median_wxh"] = {"scan": [float(ms[0]), float(ms[1])], "train_numbered": [float(mn[0]), float(mn[1])], "ratio_h": round(float(ms[1] / mn[1]), 3)} + from PIL import Image as PI + meta = {} + srng = random.Random(SEED + 2) + for lab, pool_i in (("scan", iS), ("numbered", iN)): + fp = collections.Counter() + dpis = collections.Counter() + for i in srng.sample(list(pool_i), 300): + with PI.open(os.path.join(IMG, NAMES[i])) as im: + q = getattr(im, "quantization", None) + fp[hashlib.md5(repr(q).encode()).hexdigest()[:8]] += 1 + dpis[str(im.info.get("dpi"))] += 1 + meta[lab] = {"jpeg_quant_table_fingerprints_in_300": dict(fp), "dpi_values_in_300": dict(dpis)} + res["jpeg_metadata_sample"] = meta + res["runtime_seconds"] = round(time.time() - t0) + with open(os.path.join(OUT, "result.json"), "w", encoding="utf-8") as f: + json.dump(res, f, ensure_ascii=False, indent=1, default=lambda o: o.item() if hasattr(o, "item") else str(o)) + print("DONE", round(time.time() - t0), "s", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/kohtd_leak_scan.sbatch b/scripts/kohtd_leak_scan.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..05037e9d6ecd93c01af9562b5d23fbfbcfbb7e09 --- /dev/null +++ b/scripts/kohtd_leak_scan.sbatch @@ -0,0 +1,15 @@ +#!/bin/bash +#SBATCH --job-name=kohtd_leak_scan +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=16 +#SBATCH --mem=48G +#SBATCH --time=01:30:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# Leakage check on KOHTD: scan-named training crops versus validation/test crops, images only (no label file is read). +C=/path/to/TURKIC_OCR_CODE +D=/path/to/TURKIC_OCR_DATA +echo "== start $(date) job $SLURM_JOB_ID" +$C/.venv/bin/python -I $C/scripts/kohtd_leak_scan.py $D/outputs/r5/leak_kohtd_scan 16 +echo "== end $(date)" diff --git a/scripts/kohtd_leak_singles.py b/scripts/kohtd_leak_singles.py new file mode 100644 index 0000000000000000000000000000000000000000..517175e293ec9b1e4407705fec6eb3580dd6ba37 --- /dev/null +++ b/scripts/kohtd_leak_singles.py @@ -0,0 +1,39 @@ +# Render the 23 other numbered-train vs val/test pairs (not form pair 1695/501) side by side. Images only. +import importlib.util +import json +import os +import sys + +from PIL import Image, ImageDraw, ImageFont + +spec = importlib.util.spec_from_file_location("leak", "/path/to/TURKIC_OCR_CODE/scripts/kohtd_leak_scan.py") +leak = importlib.util.module_from_spec(spec) +sys.modules["leak"] = leak +spec.loader.exec_module(leak) +OUT = sys.argv[1] +r = json.load(open(os.path.join(OUT, "result_numbered.json"), encoding="utf-8")) +rows = [x for x in r["pairs_listed"] if not (x["train_form"] == 1695 and x["vt_form"] == 501)] +font = ImageFont.truetype(leak.FONT, 13) +panels = [] +for x in rows: + _, ga = leak.load(os.path.join(leak.IMG, x["train_crop"])) + _, gb = leak.load(os.path.join(leak.IMG, x["vt_crop"])) + hh = 60 + A = Image.fromarray(ga).resize((max(1, int(ga.shape[1] * hh / ga.shape[0])), hh)) + B = Image.fromarray(gb).resize((max(1, int(gb.shape[1] * hh / gb.shape[0])), hh)) + c = Image.new("L", (A.width + B.width + 50, hh + 20), 255) + c.paste(A, (5, 18)) + c.paste(B, (A.width + 40, 18)) + ImageDraw.Draw(c).text((5, 1), "train %s | %s %s | d %.3f ncc %.3f" % (x["train_crop"], x["vt_split"], x["vt_crop"], x["hash_distance"], x["ncc"]), font=font, fill=0) + panels.append(c) +for pi in range(2): + ch = panels[pi * 12:(pi + 1) * 12] + if not ch: + continue + img = Image.new("L", (max(p.width for p in ch), sum(p.height + 4 for p in ch)), 255) + y = 0 + for p in ch: + img.paste(p, (0, y)) + y += p.height + 4 + img.save(os.path.join(OUT, "numbered_singles_panel_%d.png" % (pi + 1))) +print("done", len(rows)) diff --git a/scripts/kohtd_leak_valtest.py b/scripts/kohtd_leak_valtest.py new file mode 100644 index 0000000000000000000000000000000000000000..60b607cd9823847e2e5a4256dee0ea49d6eba781 --- /dev/null +++ b/scripts/kohtd_leak_valtest.py @@ -0,0 +1,77 @@ +# Is any validation form a duplicate of a test form (same ink under two form ids)? Images only, cached features. +import collections +import importlib.util +import json +import os +import re +import sys +import time + +import numpy as np + +t0 = time.time() +spec = importlib.util.spec_from_file_location("leak", "/path/to/TURKIC_OCR_CODE/scripts/kohtd_leak_scan.py") +leak = importlib.util.module_from_spec(spec) +sys.modules["leak"] = leak +spec.loader.exec_module(leak) +OUT, WORKERS = sys.argv[1], int(sys.argv[2]) +NAMES = sorted(n for n in os.listdir(leak.IMG) if n.endswith(".jpg")) +leak.NAMES = NAMES +num = re.compile(r"^(\d+)_(\d+)_(\d+)\.jpg$") +grp = np.full(len(NAMES), -1) +form = np.full(len(NAMES), -1) +for i, n in enumerate(NAMES): + m = num.match(n) + if m: + form[i] = int(m.group(1)) + grp[i] = leak.split_of_form(form[i]) +z = np.load(os.path.join(OUT, "features.npz"), allow_pickle=True) +W, H, STD, DH, PH, BAD = [z[k] for k in ("W", "H", "STD", "DH", "PH", "BAD")] +AR = (W / np.maximum(H, 1)).astype(np.float32) +valid = (~BAD) & (STD > leak.STD_MIN) +iV = np.where((grp == leak.G_V) & valid)[0] +iT = np.where((grp == leak.G_T) & valid)[0] +bd, bi, _ = leak.nn(DH[iV], PH[iV], AR[iV], DH[iT], PH[iT], AR[iT], [(0, len(iT))]) +d = bd[:, 0] +cand = np.where(d <= 0.3751)[0] +pairs = [(NAMES[iT[bi[q, 0]]], NAMES[iV[q]]) for q in cand] +from multiprocessing import Pool +with Pool(WORKERS) as pool: + ncc = np.array(pool.map(leak.ncc_paths, pairs, chunksize=64)) +sel = [k for k in range(len(cand)) if d[cand[k]] <= 0.2091 or ncc[k] >= 0.9] +gp = collections.Counter((int(form[iV[cand[k]]]), int(form[iT[bi[cand[k], 0]]])) for k in sel) +res = {"queries_validation": len(iV), "database_test": len(iT), "pairs_hash_le_tau_hard": int(len(cand)), "pairs_hash_le_tau_easy": int((d <= 0.2091).sum()), + "pairs_ncc_ge_0.9_among_hash_le_tau_hard": int((ncc >= 0.9).sum()), "listed": len(sel), "form_pairs": len(gp), "max_pairs_on_one_form_pair": max(gp.values()) if gp else 0, + "top_form_pairs_val_test": [{"val_form": a, "test_form": b, "n": c} for (a, b), c in gp.most_common(5)], "job_id": os.environ.get("SLURM_JOB_ID", "none"), "runtime_seconds": round(time.time() - t0)} +json.dump(res, open(os.path.join(OUT, "result_valtest.json"), "w"), indent=1) +print(json.dumps(res)) + +# list and draw the pairs of the top form pair +from PIL import Image, ImageDraw, ImageFont +top = gp.most_common(1)[0][0] if gp else None +rows = [] +for k in sel: + q = cand[k] + a, b = int(form[iV[q]]), int(form[iT[bi[q, 0]]]) + rows.append({"val_crop": NAMES[iV[q]], "test_crop": NAMES[iT[bi[q, 0]]], "val_form": a, "test_form": b, "hash_distance": round(float(d[q]), 4), "ncc": round(float(ncc[k]), 4), "val_wxh": [int(W[iV[q]]), int(H[iV[q]])], "test_wxh": [int(W[iT[bi[q, 0]]]), int(H[iT[bi[q, 0]]])]}) +rows.sort(key=lambda r: (r["val_form"], r["val_crop"])) +json.dump(rows, open(os.path.join(OUT, "result_valtest_pairs.json"), "w"), indent=1) +font = ImageFont.truetype(leak.FONT, 13) +panels = [] +for r in rows: + _, ga = leak.load(os.path.join(leak.IMG, r["val_crop"])) + _, gb = leak.load(os.path.join(leak.IMG, r["test_crop"])) + hh = 60 + A = Image.fromarray(ga).resize((max(1, int(ga.shape[1] * hh / ga.shape[0])), hh)) + B = Image.fromarray(gb).resize((max(1, int(gb.shape[1] * hh / gb.shape[0])), hh)) + c = Image.new("L", (A.width + B.width + 50, hh + 20), 255) + c.paste(A, (5, 18)) + c.paste(B, (A.width + 40, 18)) + ImageDraw.Draw(c).text((5, 1), "val %s | test %s | d %.3f ncc %.3f" % (r["val_crop"], r["test_crop"], r["hash_distance"], r["ncc"]), font=font, fill=0) + panels.append(c) +img = Image.new("L", (max(p.width for p in panels), sum(p.height + 4 for p in panels)), 255) +y = 0 +for p in panels: + img.paste(p, (0, y)) + y += p.height + 4 +img.save(os.path.join(OUT, "valtest_pairs_panel.png")) diff --git a/scripts/kohtd_leak_valtest.sbatch b/scripts/kohtd_leak_valtest.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..4d42b90b2eb6691dc943812aa53c687844a33c22 --- /dev/null +++ b/scripts/kohtd_leak_valtest.sbatch @@ -0,0 +1,14 @@ +#!/bin/bash +#SBATCH --job-name=kohtd_leak_vt +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=16 +#SBATCH --mem=48G +#SBATCH --time=00:40:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +C=/path/to/TURKIC_OCR_CODE +D=/path/to/TURKIC_OCR_DATA +echo "== start $(date) job $SLURM_JOB_ID" +$C/.venv/bin/python -I $C/scripts/kohtd_leak_valtest.py $D/outputs/r5/leak_kohtd_scan 16 +echo "== end $(date)" diff --git a/scripts/r5/r5_after_gen.sbatch b/scripts/r5/r5_after_gen.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..539c31b05fefe33126e5faa12223010b76883048 --- /dev/null +++ b/scripts/r5/r5_after_gen.sbatch @@ -0,0 +1,18 @@ +#!/bin/bash +#SBATCH --job-name=r5_after_gen +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=8 +#SBATCH --mem=24G +#SBATCH --time=02:00:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# R5 DATA: run this ONCE GEN's synthetic manifests (synth_{hand,typed,clutter,pages}_{train,val,test}.tsv) are written and no longer change. +# 1 hash GEN's images, 2 report-only duplicate check over all manifests (rewrites nothing), 3 validate every manifest, 4 recut the unseen-word slice P2 with the +# synthetic train labels, 5 rewrite manifest_stats.json, evalsets.json and mix_v1_shares.json (placeholders become ready sets). +PY=/path/to/TURKIC_OCR_CODE/.venv/bin/python +S=/path/to/TURKIC_OCR_CODE/scripts/r5 +$PY -I $S/r5_build_real.py hash_synth dedupe_all --force +$PY -I $S/r5_validate_manifests.py +$PY -I $S/r5_p2_slice.py +$PY -I $S/r5_registry.py diff --git a/scripts/r5/r5_build_A.sbatch b/scripts/r5/r5_build_A.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..a868adc7b70ae217f24e7486ed74d0b3ce0a8d1b --- /dev/null +++ b/scripts/r5/r5_build_A.sbatch @@ -0,0 +1,14 @@ +#!/bin/bash +#SBATCH --job-name=r5_build_A +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=4 +#SBATCH --mem=16G +#SBATCH --time=02:00:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# R5 DATA: real-data manifests, part A (see r5_build_real.py) +PY=/path/to/TURKIC_OCR_CODE/.venv/bin/python +S=/path/to/TURKIC_OCR_CODE/scripts/r5/r5_build_real.py +$PY -I $S kohtd --force +$PY -I $S hkr chd rukopys diff --git a/scripts/r5/r5_build_B.sbatch b/scripts/r5/r5_build_B.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..832d7a78fdfe53a898f597a20f4e5d9439d51064 --- /dev/null +++ b/scripts/r5/r5_build_B.sbatch @@ -0,0 +1,13 @@ +#!/bin/bash +#SBATCH --job-name=r5_build_B +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=12 +#SBATCH --mem=32G +#SBATCH --time=03:00:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# R5 DATA: real-data manifests, part B (see r5_build_real.py) +PY=/path/to/TURKIC_OCR_CODE/.venv/bin/python +S=/path/to/TURKIC_OCR_CODE/scripts/r5/r5_build_real.py +$PY -I $S school diff --git a/scripts/r5/r5_build_C.sbatch b/scripts/r5/r5_build_C.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..214c2671604e87d449e9ebc068afedbae4261a39 --- /dev/null +++ b/scripts/r5/r5_build_C.sbatch @@ -0,0 +1,13 @@ +#!/bin/bash +#SBATCH --job-name=r5_build_C +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=12 +#SBATCH --mem=32G +#SBATCH --time=02:00:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# R5 DATA: real-data manifests, part C (see r5_build_real.py) +PY=/path/to/TURKIC_OCR_CODE/.venv/bin/python +S=/path/to/TURKIC_OCR_CODE/scripts/r5/r5_build_real.py +$PY -I $S hash dedupe diff --git a/scripts/r5/r5_build_real.py b/scripts/r5/r5_build_real.py new file mode 100644 index 0000000000000000000000000000000000000000..a847404073aec80905a1853a8f05dd5d7c4493e9 --- /dev/null +++ b/scripts/r5/r5_build_real.py @@ -0,0 +1,832 @@ +"""R5 DATA: build the real-data manifests of round R5 (shared TSV format of the R5 common specification). + +Stages (run in this order; each stage writes its outputs and a stage log, and is skipped if its log exists, unless --force): + kohtd K1 split -> kohtd_{train,val,test}, kohtd_screen_v1 (V1, unchanged), kohtd_lmtune (500 validation crops not in V1, seed 20261121) + hkr HKR words (Kaggle mirror zip): extract jpg, official split (train / val / test1 / test2) from the project's HKR audit manifest + chd Cyrillic Handwriting Dataset (CHD): extract png; official train / test; validation carved from train by word type + school school_notebooks_ru: word crops from pupil_text polygons, page split kept + rukopys RUKOPYS test: handwritten, legible, Ukrainian line crops from the boxes (test only) + hash sha256 + perceptual hash (64-bit pHash) of every image in every manifest + dedupe drop train images that are byte-identical or near-identical (pHash distance <= 4) to a val or test image of any source + +Raw manifests (before dedupe) go to DATA/data/processed/r5/manifests_pre_dedupe/, final ones to .../r5/manifests/. +Nothing here trains or scores a model. Test images are read only to cut line crops (rukopys, school) and to hash them for the duplicate check; none is shown or scored. +""" +import argparse +import collections +import csv +import gzip +import hashlib +import io +import json +import multiprocessing as mp +import os +import sys +import time +import unicodedata +import zipfile +from pathlib import Path + +import cv2 +import numpy as np +from PIL import Image + +DATA = Path("/path/to/TURKIC_OCR_DATA") +RAW = DATA / "data/raw" +PROC = DATA / "data/processed" +R5 = PROC / "r5" +PRE = R5 / "manifests_pre_dedupe" +MAN = R5 / "manifests" +IMG = R5 / "images" +LOGS = R5 / "build_logs" +HDR = ["id", "image", "text", "lang", "script", "kind", "source", "split", "group", "unit"] +KK_LETTERS = set("әғқңөұүһіӘҒҚҢӨҰҮҺІ") +KOHTD_IMG = PROC / "kohtd_words_raw/KOHTD_dataset/HK_dataset/img" +K1 = PROC / "kohtd_split_v1" +V1_PATH = DATA / "outputs/j11_stage1_kohtd/screen_set_v1.tsv" +V1_SHA = "aca23aed02629f884cd533761ca2553951eb91cc9b15120a25c88071f54198ec" +HKR_MANIFEST = R5 / "inputs/hkr_manifest.tsv.gz" +CRC = cv2.IMWRITE_PNG_COMPRESSION +NPROC = int(os.environ.get("SLURM_CPUS_PER_TASK", "4")) + + +def nfc(s): + return unicodedata.normalize("NFC", s) + + +def clean(s): + """NFC, tabs and line breaks to one space, strip the ends.""" + s = nfc(s) + for ch in ("\t", "\r", "\n"): + s = s.replace(ch, " ") + return s.strip() + + +def write_manifest(path, rows): + path.parent.mkdir(parents=True, exist_ok=True) + with open(path, "w", encoding="utf-8", newline="") as f: + f.write("\t".join(HDR) + "\n") + for r in rows: + f.write("\t".join(str(r[k]) for k in HDR) + "\n") + + +def read_manifest(path): + rows = [] + with open(path, encoding="utf-8", newline="") as f: + header = f.readline().rstrip("\n").split("\t") + assert header == HDR, (path, header) + for line in f: + parts = line.rstrip("\n").split("\t") + assert len(parts) == len(HDR), (path, parts) + rows.append(dict(zip(HDR, parts))) + return rows + + +def sha256_file(p): + h = hashlib.sha256() + with open(p, "rb") as f: + for chunk in iter(lambda: f.read(1 << 20), b""): + h.update(chunk) + return h.hexdigest() + + +def stage_log(name, info): + LOGS.mkdir(parents=True, exist_ok=True) + info["finished_utc"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) + with open(LOGS / f"stage_{name}.json", "w", encoding="utf-8") as f: + json.dump(info, f, ensure_ascii=False, indent=1) + + +def row(id_, image, text, lang, script, kind, source, split, group, unit): + return dict(id=id_, image=str(image), text=text, lang=lang, script=script, kind=kind, + source=source, split=split, group=group, unit=unit) + + +# ----------------------------------------------------------------------------- KOHTD +def read_k1(path): + out = [] + with open(path, encoding="utf-8", newline="") as f: + header = f.readline().rstrip("\n").split("\t") + assert header[:3] == ["crop_file", "form_id", "label"], header + for line in f: + parts = line.rstrip("\n").split("\t") + # label is the third column; key_type (last) never contains a tab + crop_file, form_id = parts[0], parts[1] + key_type = parts[-1] if len(header) == 4 else "" + label = "\t".join(parts[2:-1]) if len(header) == 4 else "\t".join(parts[2:]) + out.append((crop_file, form_id, label, key_type)) + return out + + +def stage_kohtd(): + info = {"stage": "kohtd"} + sets = {} + altered = collections.Counter() + for sp, fn in (("train", "train.tsv"), ("val", "validation.tsv"), ("test", "test.tsv")): + rows = [] + for crop_file, form_id, label, key_type in read_k1(K1 / fn): + t = clean(label) + if t != label: + altered[sp] += 1 + if key_type == "numbered": + grp = "kohtd_form_" + form_id + else: # scan-named crop: the unit is the scan file name (split_spec_v1, K1 report) + grp = "kohtd_scan_" + crop_file[:-4].replace("word_croped_", "", 1).rsplit("_", 2)[0] + rows.append(row("kohtd:" + crop_file[:-4], KOHTD_IMG / crop_file, t, "kk", "Cyrl", "hand_real", + "kohtd", "val" if sp == "val" else sp, grp, "word")) + sets[sp] = rows + # does every image exist? + missing = collections.Counter() + for sp, rows in sets.items(): + for r in rows: + if not Path(r["image"]).exists(): + missing[sp] += 1 + info["missing_images"] = dict(missing) + info["labels_changed_by_cleaning"] = dict(altered) + info["empty_labels"] = {sp: sum(1 for r in rows if r["text"] == "") for sp, rows in sets.items()} + # train: empty labels are not usable targets; they are listed and dropped from TRAIN only + train_rows = [r for r in sets["train"] if r["text"] != ""] + info["train_empty_label_rows_dropped"] = len(sets["train"]) - len(train_rows) + write_manifest(PRE / "kohtd_train.tsv", train_rows) + write_manifest(PRE / "kohtd_val.tsv", sets["val"]) + write_manifest(PRE / "kohtd_test.tsv", sets["test"]) + # V1 screen set, unchanged + v1_sha = sha256_file(V1_PATH) + assert v1_sha == V1_SHA, v1_sha + val_by_file = {r["id"]: r for r in sets["val"]} + v1_rows = [] + with open(V1_PATH, encoding="utf-8", newline="") as f: + header = f.readline().rstrip("\n").split("\t") + assert header == ["crop_file", "form_id", "label"], header + for line in f: + crop_file, form_id, label = line.rstrip("\n").split("\t")[:3] + rid = "kohtd:" + crop_file[:-4] + base = val_by_file[rid] + assert base["text"] == clean(label), (rid, base["text"], label) + v1_rows.append(dict(base)) + write_manifest(PRE / "kohtd_screen_v1.tsv", v1_rows) + v1_ids = {r["id"] for r in v1_rows} + cand = [r for r in sets["val"] if r["id"] not in v1_ids] + rng = np.random.default_rng(20261121) + pick = np.sort(rng.choice(len(cand), size=500, replace=False)) + lm_rows = [dict(cand[i]) for i in pick] + write_manifest(PRE / "kohtd_lmtune.tsv", lm_rows) + info.update(v1_sha256=v1_sha, v1_rows=len(v1_rows), lmtune_candidates=len(cand), lmtune_rows=len(lm_rows), + lmtune_method="numpy.random.default_rng(20261121).choice(len(candidates), 500, replace=False), sorted by index; " + "candidates = rows of kohtd_val.tsv (K1 validation.tsv order) whose crop is not in V1", + numpy=np.__version__, + counts={sp: len(rows) for sp, rows in sets.items()}, + forms={sp: len({r["group"] for r in rows}) for sp, rows in sets.items()}) + # sidecar: language evidence per label (Kazakh-specific letter or not) + ev = collections.Counter() + side = PRE / "kohtd_label_lang_evidence.tsv" + with open(side, "w", encoding="utf-8") as f: + f.write("id\tsplit\tevidence\n") + for sp, rows in (("train", train_rows), ("val", sets["val"]), ("test", sets["test"])): + for r in rows: + t = r["text"] + if any(c in KK_LETTERS for c in t): + e = "kk_specific_letter" + elif any("Ѐ" <= c <= "ӿ" for c in t): + e = "cyrillic_no_specific_letter" + else: + e = "no_cyrillic_letter" + ev[(sp, e)] += 1 + f.write(f"{r['id']}\t{sp}\t{e}\n") + info["label_lang_evidence"] = {f"{k[0]}:{k[1]}": v for k, v in sorted(ev.items())} + stage_log("kohtd", info) + print(json.dumps(info, ensure_ascii=False)[:2000]) + + +# ----------------------------------------------------------------------------- HKR +HKR_PREFIX = "HKR_Dataset_Words_Public/20200923_Dataset_Words_Public/" + + +def stage_hkr(): + info = {"stage": "hkr"} + with gzip.open(HKR_MANIFEST, "rt", encoding="utf-8") as f: + rd = csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE) + man = {r["id"]: r for r in rd} + info["manifest_rows"] = len(man) + z = zipfile.ZipFile(RAW / "hkr_words_kaggle_scispecai/hkr_dat.zip") + names = set(z.namelist()) + out_dir = IMG / "hkr" + out_dir.mkdir(parents=True, exist_ok=True) + ann_keys = collections.Counter() + rows = {"train": [], "val": [], "test1": [], "test2": []} + n_text_diff = 0 + n_missing_in_manifest = 0 + for mid in sorted(man): + jn = HKR_PREFIX + "ann/" + mid + ".json" + jp = HKR_PREFIX + "img/" + mid + ".jpg" + if jn not in names or jp not in names: + info.setdefault("missing_in_zip", []).append(mid) + continue + ann = json.loads(z.read(jn).decode("utf-8")) + ann_keys.update(ann.keys()) + text = clean(ann["description"]) + if text != clean(man[mid]["text"]): + n_text_diff += 1 + dst = out_dir / (mid + ".jpg") + if not dst.exists(): + dst.write_bytes(z.read(jp)) + parts = mid.split("_") + group = "hkr_t%s_i%s" % (parts[0], parts[2]) # template, filled-form instance (project inference, N9d / H1-10) + lang = "kk" if any(c in KK_LETTERS for c in text) else "ru" + sp = man[mid]["split"] + rows[sp].append(row("hkr:" + mid, dst, text, lang, "Cyrl", "hand_real", "hkr_words", + "train" if sp == "train" else "val" if sp == "val" else "test", group, "word")) + # zip entries not in manifest + zip_ids = {n[len(HKR_PREFIX + "img/"):-4] for n in names if n.startswith(HKR_PREFIX + "img/") and n.endswith(".jpg")} + n_missing_in_manifest = len(zip_ids - set(man)) + info.update(ann_keys=dict(ann_keys), text_differs_from_manifest=n_text_diff, zip_ids_not_in_manifest=n_missing_in_manifest, + counts={k: len(v) for k, v in rows.items()}, + kk_labelled={k: sum(1 for r in v if r["lang"] == "kk") for k, v in rows.items()}, + groups={k: len({r["group"] for r in v}) for k, v in rows.items()}) + # empty labels + for k in rows: + info.setdefault("empty_labels", {})[k] = sum(1 for r in rows[k] if r["text"] == "") + rows["train"] = [r for r in rows["train"] if r["text"] != ""] + write_manifest(PRE / "hkr_train.tsv", rows["train"]) + write_manifest(PRE / "hkr_val.tsv", rows["val"]) + write_manifest(PRE / "hkr_test1.tsv", rows["test1"]) + write_manifest(PRE / "hkr_test2.tsv", rows["test2"]) + info["manifest_sha256"] = sha256_file(HKR_MANIFEST) + stage_log("hkr", info) + print(json.dumps(info, ensure_ascii=False)[:2000]) + + +# ----------------------------------------------------------------------------- CHD +def stage_chd(): + info = {"stage": "chd"} + z = zipfile.ZipFile(RAW / "chd/archive.zip") + out_dir = IMG / "chd" + (out_dir / "train").mkdir(parents=True, exist_ok=True) + (out_dir / "test").mkdir(parents=True, exist_ok=True) + rows = {"train": [], "val": [], "test": []} + names = set(z.namelist()) + carve = collections.Counter() + for sp in ("train", "test"): + raw = z.read(sp + ".tsv").decode("utf-8") + for line in raw.split("\n"): + line = line.rstrip("\r") + if not line.strip(): + continue + fn, _, label = line.partition("\t") + text = clean(label) + member = sp + "/" + fn + if member not in names: + info.setdefault("missing_in_zip", []).append(member) + continue + dst = out_dir / sp / fn + if not dst.exists(): + dst.write_bytes(z.read(member)) + stem = fn[:-4] + # group = word type (CHD has no writer or page id): sha1 of the NFC label + gid = "chd_w" + hashlib.sha1(text.encode("utf-8")).hexdigest()[:10] + target = sp + if sp == "train": + h = int(hashlib.sha256(("R5-chd-val-v1:" + text).encode("utf-8")).hexdigest()[:8], 16) % 100 + if h < 5: + target = "val" + rows[target].append(row("chd:" + sp + "_" + stem, dst, text, "ru", "Cyrl", "hand_real", "chd", + "val" if target == "val" else target, gid, "word")) + carve[target] += 1 + info.update(counts={k: len(v) for k, v in rows.items()}, + empty_labels={k: sum(1 for r in v if r["text"] == "") for k, v in rows.items()}, + distinct_words={k: len({r["text"] for r in v}) for k, v in rows.items()}, + val_rule="validation = train rows whose label word type has sha256('R5-chd-val-v1:'+label)[:8] mod 100 < 5, " + "so a word type is never in train and validation; official test unchanged") + for k in rows: + rows[k] = [r for r in rows[k] if r["text"] != ""] if k == "train" else rows[k] + write_manifest(PRE / "chd_train.tsv", rows["train"]) + write_manifest(PRE / "chd_val.tsv", rows["val"]) + write_manifest(PRE / "chd_test.tsv", rows["test"]) + # overlap of word types between train and official test + tr = {r["text"] for r in rows["train"]} + te = [r["text"] for r in rows["test"]] + info["official_test_rows_whose_word_is_in_train"] = sum(1 for t in te if t in tr) + stage_log("chd", info) + print(json.dumps(info, ensure_ascii=False)[:2000]) + + +# ----------------------------------------------------------------------------- school notebooks +def poly_pts(seg): + flat = seg[0] if seg and isinstance(seg[0], list) else seg + pts = np.array(flat, dtype=np.float32).reshape(-1, 2) + return pts + + +def cut_word(page, pts, pad=3): + """Cut one word: axis-aligned patch around the polygon, levelled by the long edge of its minimum-area rectangle when tilted.""" + H, W = page.shape[:2] + x, y, w, h = cv2.boundingRect(pts.astype(np.int32)) + if w < 6 or h < 6: + return None + rect = cv2.minAreaRect(pts) + box = cv2.boxPoints(rect) + e0, e1 = box[1] - box[0], box[2] - box[1] + d = e0 if np.linalg.norm(e0) >= np.linalg.norm(e1) else e1 + long_len, short_len = max(np.linalg.norm(e0), np.linalg.norm(e1)), min(np.linalg.norm(e0), np.linalg.norm(e1)) + theta = float(np.degrees(np.arctan2(d[1], d[0]))) + if theta > 90: + theta -= 180 + if theta <= -90: + theta += 180 + if abs(theta) < 2.0 or abs(theta) > 30 or long_len < 1.2 * short_len: + x0, y0, x1, y1 = max(0, x - pad), max(0, y - pad), min(W, x + w + pad), min(H, y + h + pad) + c = page[y0:y1, x0:x1] + return c if c.shape[0] >= 6 and c.shape[1] >= 6 else None + r = int(np.hypot(w, h)) + pad + 4 + px0, py0, px1, py1 = max(0, x - r), max(0, y - r), min(W, x + w + r), min(H, y + h + r) + patch = page[py0:py1, px0:px1] + cx, cy = rect[0][0] - px0, rect[0][1] - py0 + M = cv2.getRotationMatrix2D((cx, cy), theta, 1.0) + rot = cv2.warpAffine(patch, M, (patch.shape[1], patch.shape[0]), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE) + p2 = cv2.transform((pts - np.array([px0, py0], dtype=np.float32)).reshape(-1, 1, 2), M).reshape(-1, 2) + x2, y2, w2, h2 = cv2.boundingRect(p2.astype(np.int32)) + x0, y0 = max(0, x2 - pad), max(0, y2 - pad) + x1, y1 = min(rot.shape[1], x2 + w2 + pad), min(rot.shape[0], y2 + h2 + pad) + c = rot[y0:y1, x0:x1] + return c if c.shape[0] >= 6 and c.shape[1] >= 6 else None + + +def school_page_job(args): + split, page_info, words, src = args # words: list of (ann_index, text, seg) + fn = page_info["file_name"] + W, H = page_info["width"], page_info["height"] + stem = fn.rsplit(".", 1)[0] + out_dir = IMG / "school" / split / stem + out_dir.mkdir(parents=True, exist_ok=True) + try: + if src[0] == "zip": + with zipfile.ZipFile(src[1]) as z: + data = z.read("images/" + fn) + im = Image.open(io.BytesIO(data)) + else: + im = Image.open(src[1] + "/" + fn) + im.load() + size_note = "ok" + if im.size != (W, H): + if im.size == (H, W): + from PIL import ImageOps + im = ImageOps.exif_transpose(im) + size_note = "exif_transposed" + if im.size != (W, H): + return fn, [], {"error": "size_mismatch", "got": im.size, "want": (W, H)} + page = cv2.cvtColor(np.array(im.convert("RGB")), cv2.COLOR_RGB2BGR) + except Exception as e: # noqa + return fn, [], {"error": repr(e)} + out_rows = [] + skipped = collections.Counter() + for ai, text, seg in words: + try: + pts = poly_pts(seg) + c = cut_word(page, pts) + except Exception: + c = None + if c is None: + skipped["bad_polygon_or_tiny"] += 1 + continue + dst = out_dir / f"{ai}.png" + cv2.imwrite(str(dst), c, [CRC, 1]) + out_rows.append((ai, text, str(dst))) + return fn, out_rows, {"skipped": dict(skipped), "size_note": size_note} + + +def stage_school(): + info = {"stage": "school"} + base = RAW / "school_notebooks_ru" + zip_path = str(base / "images.zip") + jobs = [] + for sp in ("train", "val", "test"): + d = json.load(open(base / f"annotations_{sp}.json", encoding="utf-8")) + pages = {i["id"]: i for i in d["images"]} + words = collections.defaultdict(list) + n_empty = 0 + for ai, a in enumerate(d["annotations"]): + if a["category_id"] != 0: + continue + t = clean((a.get("attributes") or {}).get("translation") or "") + if t == "": + n_empty += 1 + continue + words[a["image_id"]].append((ai, t, a["segmentation"])) + info.setdefault("empty_translation_skipped", {})[sp] = n_empty + src = ("zip", zip_path) if sp == "train" else ("dir", str(base / "val_test_images" / sp)) + for iid, w in words.items(): + jobs.append((sp, pages[iid], w, src)) + info["pages_with_words"] = collections.Counter(j[0] for j in jobs) + t0 = time.time() + rows = {"train": [], "val": [], "test": []} + errors = {} + skipped = collections.Counter() + with mp.Pool(NPROC) as pool: + for k, (sp_job, res) in enumerate(zip(jobs, pool.imap(school_page_job, jobs, chunksize=4))): + sp = sp_job[0] + fn, out_rows, meta = res + if "error" in meta: + errors[fn] = meta + for kk, v in meta.get("skipped", {}).items(): + skipped[kk] += v + stem = fn.rsplit(".", 1)[0] + for ai, text, dst in out_rows: + rows[sp].append(row(f"school:{sp}_{stem}_{ai}", dst, text, "ru", "Cyrl", "hand_real", "school_notebooks_ru", + sp, "school_page_" + stem, "word")) + if k % 200 == 0: + print("school pages", k, "of", len(jobs), "elapsed", round(time.time() - t0), flush=True) + info.update(counts={k: len(v) for k, v in rows.items()}, page_errors=errors, skipped=dict(skipped), + pages={k: len({r["group"] for r in v}) for k, v in rows.items()}, + crop_rule="category pupil_text (id 0) with a non-empty translation; axis-aligned patch of the polygon with 3 px padding, " + "levelled by the long edge of the polygon's minimum-area rectangle when the tilt is between 2 and 30 degrees; no masking", + pages_total=len(jobs)) + write_manifest(PRE / "school_train.tsv", rows["train"]) + write_manifest(PRE / "school_val.tsv", rows["val"]) + write_manifest(PRE / "school_test.tsv", rows["test"]) + stage_log("school", info) + print(json.dumps(info, ensure_ascii=False, default=str)[:2000]) + + +# ----------------------------------------------------------------------------- RUKOPYS test +def stage_rukopys(): + info = {"stage": "rukopys"} + base = RAW / "rukopys_test/test" + recs = [json.loads(l) for l in open(base / "metadata.jsonl", encoding="utf-8")] + rows = [] + skip = collections.Counter() + for rec in recs: + stem = rec["file_name"].split("/")[-1].rsplit(".", 1)[0] + page = cv2.imread(str(base / rec["file_name"]), cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION) + if page is None: + skip["page_unreadable"] += 1 + continue + H, W = page.shape[:2] + if (W, H) != (rec["image_width"], rec["image_height"]): + skip["size_mismatch_page"] += 1 + continue + out_dir = IMG / "rukopys" / stem + out_dir.mkdir(parents=True, exist_ok=True) + for ri, reg in enumerate(rec["regions"]): + if reg["type"] != "handwritten": + continue + if reg["language"] != "uk" or reg["legibility"] != "legible": + skip["handwritten_not_uk_or_illegible"] += 1 + continue + t = clean(reg["text"]) + if t == "" or "[illegible]" in t or "~~" in t: + skip["empty_or_marked_text"] += 1 + continue + x1, y1, x2, y2 = [int(v) for v in reg["bbox"]] + x1, y1, x2, y2 = max(0, x1 - 4), max(0, y1 - 4), min(W, x2 + 4), min(H, y2 + 4) + if x2 - x1 < 8 or y2 - y1 < 8: + skip["tiny_box"] += 1 + continue + dst = out_dir / f"{ri}.png" + cv2.imwrite(str(dst), page[y1:y2, x1:x2], [CRC, 1]) + rows.append(row(f"rukopys:{stem}_{ri}", dst, t, "other", "Cyrl", "hand_real", "rukopys_test", "test", + "rukopys_page_" + stem, "line")) + info.update(counts={"test": len(rows)}, pages=len({r["group"] for r in rows}), skipped=dict(skip), + rule="regions of type handwritten, language uk, legibility legible, no ~~ or [illegible] markers; bbox plus 4 px; " + "orientation as stored (README v2.4: boxes agree with pixels)") + write_manifest(PRE / "rukopys_test.tsv", rows) + stage_log("rukopys", info) + print(json.dumps(info, ensure_ascii=False)[:2000]) + + +# ----------------------------------------------------------------------------- hashing +def phash64(gray): + small = cv2.resize(gray, (32, 32), interpolation=cv2.INTER_AREA).astype(np.float32) + dct = cv2.dct(small) + low = dct[:8, :8] + med = np.median(low) + bits = (low > med).flatten() + return int.from_bytes(np.packbits(bits).tobytes(), "big") + + +def hash_job(item): + rid, path = item + try: + data = open(path, "rb").read() + sha = hashlib.sha256(data).hexdigest() + arr = cv2.imdecode(np.frombuffer(data, np.uint8), cv2.IMREAD_GRAYSCALE | cv2.IMREAD_IGNORE_ORIENTATION) + if arr is None: + return rid, sha, "", 0, 0 + return rid, sha, "%016x" % phash64(arr), arr.shape[1], arr.shape[0] + except Exception: + return rid, "", "", 0, 0 + + +ALL_MANIFESTS = ["kohtd_train", "kohtd_val", "kohtd_test", "hkr_train", "hkr_val", "hkr_test1", "hkr_test2", + "chd_train", "chd_val", "chd_test", "school_train", "school_val", "school_test", "rukopys_test"] + + +def stage_hash(): + info = {"stage": "hash"} + items = [] + for m in ALL_MANIFESTS: + for r in read_manifest(PRE / (m + ".tsv")): + items.append((r["id"], r["image"])) + # val rows that are also in V1 / lmtune are the same ids: nothing to add + print("hashing", len(items), flush=True) + t0 = time.time() + out = LOGS / "hashes.tsv" + n_fail = 0 + with open(out, "w", encoding="utf-8") as f, mp.Pool(NPROC) as pool: + f.write("id\tsha256\tphash\twidth\theight\n") + for k, res in enumerate(pool.imap(hash_job, items, chunksize=400)): + if res[1] == "" or res[2] == "": + n_fail += 1 + f.write("%s\t%s\t%s\t%d\t%d\n" % res) + if k % 50000 == 0: + print("hashed", k, round(time.time() - t0), flush=True) + info.update(images=len(items), failed=n_fail, seconds=round(time.time() - t0), + hash="64-bit pHash of the grey image: 32x32 INTER_AREA, DCT, low 8x8, bit = coefficient > median (imagehash-style); distance = Hamming") + stage_log("hash", info) + print(info) + + +# ----------------------------------------------------------------------------- dedupe +def stage_dedupe(): + info = {"stage": "dedupe"} + hashes = {} + with open(LOGS / "hashes.tsv", encoding="utf-8") as f: + f.readline() + for line in f: + rid, sha, ph, w, h = line.rstrip("\n").split("\t") + hashes[rid] = (sha, int(ph, 16) if ph else None, int(w), int(h)) + man = {m: read_manifest(PRE / (m + ".tsv")) for m in ALL_MANIFESTS} + meta = [] # (id, source, split, text, manifest) + for m, rows in man.items(): + for r in rows: + meta.append((r["id"], r["source"], r["split"], r["text"], m)) + idx = {t[0]: i for i, t in enumerate(meta)} + ids = [t[0] for t in meta] + ph = np.array([hashes[i][1] if hashes[i][1] is not None else 0 for i in ids], dtype=np.uint64) + ok = np.array([hashes[i][1] is not None for i in ids]) + sha = [hashes[i][0] for i in ids] + split = np.array([t[2] for t in meta]) + is_train = split == "train" + is_ref = (split == "val") | (split == "test") + info["images_hashed"] = len(ids) + info["images_without_hash"] = int((~ok).sum()) + + # exact duplicates: sha256 groups with a train member and a val/test member + bysha = collections.defaultdict(list) + for i, s in enumerate(sha): + if s: + bysha[s].append(i) + drop = {} # train index -> (reason, partner index) + n_exact_groups = 0 + for s, members in bysha.items(): + if len(members) < 2: + continue + trn = [i for i in members if is_train[i]] + ref = [i for i in members if is_ref[i]] + if trn and ref: + n_exact_groups += 1 + for i in trn: + drop[i] = ("byte_identical", ref[0]) + info["exact_groups_train_vs_valtest"] = n_exact_groups + info["train_dropped_exact"] = len(drop) + + # near duplicates (distance <= 4) with multi-index hashing: 5 chunks of the 64 bits + def near_pairs(a_idx, b_idx, maxd=4): + """best partner (b, distance) for every a with Hamming(ph[a], ph[b]) <= maxd. Exact: five 13/12-bit chunks; + a pair at distance <= 4 differs in at most 4 chunks, so it shares at least one chunk.""" + a_idx = np.array(a_idx) + b_idx = np.array(b_idx) + pa, pb = ph[a_idx], ph[b_idx] + best = {} + for s0, wd in zip([0, 13, 26, 39, 52], [13, 13, 13, 13, 12]): + mask = np.uint64((1 << wd) - 1) + ka = (pa >> np.uint64(s0)) & mask + kb = (pb >> np.uint64(s0)) & mask + order_b = np.argsort(kb, kind="stable") + kb_sorted = kb[order_b] + order_a = np.argsort(ka, kind="stable") + ka_sorted = ka[order_a] + keys, starts = np.unique(ka_sorted, return_index=True) + ends = np.append(starts[1:], len(ka_sorted)) + for key, e_lo, e_hi in zip(keys, starts, ends): + lo = np.searchsorted(kb_sorted, key, "left") + hi = np.searchsorted(kb_sorted, key, "right") + if hi == lo: + continue + aa = order_a[e_lo:e_hi] + bb = order_b[lo:hi] + blk = max(1, int(2e7 // len(bb))) + for j in range(0, len(aa), blk): + sub = aa[j:j + blk] + d = np.bitwise_count(pa[sub][:, None] ^ pb[bb][None, :]).astype(np.int16) + dm = np.where(d <= maxd, d, 99) + am = dm.argmin(axis=1) + mv = dm[np.arange(len(sub)), am] + for u in np.nonzero(mv <= maxd)[0]: + ai, bi, dv = int(a_idx[sub[u]]), int(b_idx[bb[am[u]]]), int(mv[u]) + if ai not in best or dv < best[ai][1]: + best[ai] = (bi, dv) + return best + + tr_idx = [i for i in range(len(ids)) if is_train[i] and ok[i]] + ref_idx = [i for i in range(len(ids)) if is_ref[i] and ok[i]] + t0 = time.time() + near_train = near_pairs(tr_idx, ref_idx) + info["near_pair_search_seconds"] = round(time.time() - t0) + info["train_images_with_a_near_partner_in_valtest"] = len(near_train) + n_near_only = 0 + for a, (b, d) in near_train.items(): + if a not in drop: + drop[a] = ("near_phash_d%d" % d, b) + n_near_only += 1 + info["train_dropped_near_only"] = n_near_only + info["train_dropped_total"] = len(drop) + + # HKR vs KOHTD: any split of KOHTD (the owner's extra check); HKR train rows overlapping any KOHTD image are dropped + hk_all = [i for i, t in enumerate(meta) if t[1] == "hkr_words" and ok[i]] + ko_all = [i for i, t in enumerate(meta) if t[1] == "kohtd" and ok[i]] + ko_sha = collections.defaultdict(list) + for i in ko_all: + ko_sha[sha[i]].append(i) + hk_exact = [i for i in hk_all if sha[i] in ko_sha] + hk_near_a = near_pairs(hk_all, ko_all) + n_hk_extra = 0 + for i in set(hk_exact) | set(hk_near_a): + if is_train[i] and i not in drop: + if i in hk_near_a: + b, d = hk_near_a[i] + drop[i] = ("hkr_vs_kohtd_near_d%d" % d, b) + else: + drop[i] = ("hkr_vs_kohtd_byte_identical", ko_sha[sha[i]][0]) + n_hk_extra += 1 + info["hkr_vs_kohtd"] = { + "hkr_images_checked": len(hk_all), "kohtd_images_checked": len(ko_all), + "hkr_byte_identical_to_a_kohtd_image": len(hk_exact), + "hkr_with_near_phash_partner_in_kohtd": len(hk_near_a), + "hkr_train_rows_additionally_dropped": n_hk_extra, + } + + # diagnostics: of the dropped, how many pairs share the same label (true duplicates) and which partner split / source + why = collections.Counter() + same_label = collections.Counter() + pair_src = collections.Counter() + for a, (reason, b) in drop.items(): + key = reason.split("_d")[0] if reason.startswith("near") else reason + why[key] += 1 + same_label[(key, meta[a][3] == meta[b][3])] += 1 + pair_src[(meta[a][1], meta[b][1], meta[b][2])] += 1 + info["dropped_by_reason"] = dict(why) + info["dropped_pairs_label_same_vs_different"] = {f"{k[0]}|same_label={k[1]}": v for k, v in same_label.items()} + info["dropped_train_source_vs_partner_source_split"] = {f"{k[0]} <- {k[1]}:{k[2]}": v for k, v in sorted(pair_src.items())} + + # diagnostics only: val vs test near-duplicates across sets (not acted on) + v_idx = [i for i in range(len(ids)) if split[i] == "val" and ok[i]] + t_idx = [i for i in range(len(ids)) if split[i] == "test" and ok[i]] + vt = near_pairs(v_idx, t_idx) + info["diagnostic_val_images_with_a_near_partner_in_test"] = len(vt) + info["diagnostic_val_vs_test_by_source"] = dict(collections.Counter(f"{meta[a][1]}:val ~ {meta[b][0].split(':')[0]}:test" for a, (b, d) in vt.items())) + + # rewrite train manifests, write the dropped list + per = {} + drop_ids = {ids[a]: (reason, ids[b]) for a, (reason, b) in drop.items()} + for m, rows in man.items(): + if not m.endswith("_train"): + write_manifest(MAN / (m + ".tsv"), rows) + continue + keep = [r for r in rows if r["id"] not in drop_ids] + per[m] = {"before": len(rows), "after": len(keep), "dropped": len(rows) - len(keep)} + write_manifest(MAN / (m + ".tsv"), keep) + # subsets of validation (V1, lmtune) copied unchanged + for m in ("kohtd_screen_v1", "kohtd_lmtune"): + write_manifest(MAN / (m + ".tsv"), read_manifest(PRE / (m + ".tsv"))) + info["train_manifests"] = per + with open(LOGS / "dedupe_dropped.tsv", "w", encoding="utf-8") as f: + f.write("dropped_train_id\treason\tpartner_id\tpartner_split\tdropped_label\tpartner_label\n") + for a, (reason, b) in sorted(drop.items(), key=lambda kv: ids[kv[0]]): + f.write("\t".join([ids[a], reason, ids[b], meta[b][2], meta[a][3], meta[b][3]]) + "\n") + stage_log("dedupe", info) + print(json.dumps(info, ensure_ascii=False)[:3500]) + + + +# ----------------------------------------------------------------------------- synthetic manifests of GEN: hash and report-only duplicate check +def synth_manifest_names(): + return sorted(q.stem for pat in ("synth_*.tsv", "az_localdoc_*.tsv") for q in MAN.glob(pat) if q.stem.rsplit("_", 1)[-1] in ("train", "val", "test")) + + +def stage_hash_synth(): + """Hash the images of GEN's synthetic manifests (synth_*_{train,val,test}), clutter and page images included, and of the extra Azerbaijani test manifest.""" + info = {"stage": "hash_synth"} + items = [] + names = synth_manifest_names() + for m in names: + for r in read_manifest(MAN / (m + ".tsv")): + items.append((r["id"], r["image"])) + print("hashing synthetic", len(items), "images from", names, flush=True) + t0 = time.time() + n_fail = 0 + with open(LOGS / "hashes_synth.tsv", "w", encoding="utf-8") as f, mp.Pool(NPROC) as pool: + f.write("id\tsha256\tphash\twidth\theight\n") + for k, res in enumerate(pool.imap(hash_job, items, chunksize=400)): + if res[1] == "" or res[2] == "": + n_fail += 1 + f.write("%s\t%s\t%s\t%d\t%d\n" % res) + info.update(manifests=names, images=len(items), failed=n_fail, seconds=round(time.time() - t0)) + stage_log("hash_synth", info) + print(info) + + +def near_best(ph, a_idx, b_idx, maxd=4): + a_idx, b_idx = np.array(a_idx), np.array(b_idx) + pa, pb = ph[a_idx], ph[b_idx] + best = {} + for s0, wd in zip([0, 13, 26, 39, 52], [13, 13, 13, 13, 12]): + mask = np.uint64((1 << wd) - 1) + ka = (pa >> np.uint64(s0)) & mask + kb = (pb >> np.uint64(s0)) & mask + order_b = np.argsort(kb, kind="stable") + kb_sorted = kb[order_b] + order_a = np.argsort(ka, kind="stable") + ka_sorted = ka[order_a] + keys, starts = np.unique(ka_sorted, return_index=True) + ends = np.append(starts[1:], len(ka_sorted)) + for key, e_lo, e_hi in zip(keys, starts, ends): + lo, hi = np.searchsorted(kb_sorted, key, "left"), np.searchsorted(kb_sorted, key, "right") + if hi == lo: + continue + aa, bb = order_a[e_lo:e_hi], order_b[lo:hi] + blk = max(1, int(2e7 // len(bb))) + for j in range(0, len(aa), blk): + sub = aa[j:j + blk] + d = np.bitwise_count(pa[sub][:, None] ^ pb[bb][None, :]).astype(np.int16) + dm = np.where(d <= maxd, d, 99) + am = dm.argmin(axis=1) + mv = dm[np.arange(len(sub)), am] + for u in np.nonzero(mv <= maxd)[0]: + ai, bi, dv = int(a_idx[sub[u]]), int(b_idx[bb[am[u]]]), int(mv[u]) + if ai not in best or dv < best[ai][1]: + best[ai] = (bi, dv) + return best + + +def stage_dedupe_all(): + """Report-only duplicate check over ALL manifests in the folder (real and synthetic). Rewrites nothing. + Writes build_logs/dedupe_all.json and dedupe_all_dropped.tsv: the train images that WOULD be dropped, with reason and partner.""" + info = {"stage": "dedupe_all", "mode": "report only: no manifest is rewritten"} + hashes = {} + for fn in ("hashes.tsv", "hashes_synth.tsv"): + if not (LOGS / fn).exists(): + continue + with open(LOGS / fn, encoding="utf-8") as f: + f.readline() + for line in f: + rid, sha, ph_, w, h = line.rstrip("\n").split("\t") + hashes[rid] = (sha, int(ph_, 16) if ph_ else None) + names = [q.stem for q in sorted(MAN.glob("*.tsv")) if not q.name.endswith(".meta.tsv") and q.stem not in ("kohtd_screen_v1", "kohtd_lmtune", "kohtd_test_p2", "kohtd_test_p2b", "hkr_val_s2000", "chd_val_s2000", "school_val_s2000")] + meta = [] + for m in names: + for r in read_manifest(MAN / (m + ".tsv")): + if r["id"] in hashes: + meta.append((r["id"], r["source"], r["split"], r["text"], m, r["kind"])) + ids = [t[0] for t in meta] + ph = np.array([hashes[i][1] if hashes[i][1] is not None else 0 for i in ids], dtype=np.uint64) + ok = np.array([hashes[i][1] is not None for i in ids]) + split = np.array([t[2] for t in meta]) + tr = [i for i in range(len(ids)) if split[i] == "train" and ok[i]] + rf = [i for i in range(len(ids)) if split[i] in ("val", "test") and ok[i]] + bysha = collections.defaultdict(list) + for i in rf: + bysha[hashes[ids[i]][0]].append(i) + drop = {} + for i in tr: + s_ = hashes[ids[i]][0] + if s_ in bysha: + drop[i] = ("byte_identical", bysha[s_][0]) + near = near_best(ph, tr, rf) + for a, (b, d) in near.items(): + if a not in drop: + drop[a] = ("near_phash_d%d" % d, b) + by = collections.Counter((meta[a][4], r_.split("_d")[0] if r_.startswith("near") else r_, meta[a][5]) for a, (r_, b) in drop.items()) + info.update(manifests_checked=names, images=len(ids), train_images=len(tr), valtest_images=len(rf), would_drop_total=len(drop), + would_drop_by_manifest_and_reason={f"{k[0]} | {k[1]} | kind {k[2]}": v for k, v in sorted(by.items())}) + with open(LOGS / "dedupe_all_dropped.tsv", "w", encoding="utf-8") as f: + f.write("train_id\tmanifest\tkind\treason\tpartner_id\tpartner_manifest\tsame_label\n") + for a, (r_, b) in sorted(drop.items(), key=lambda kv: ids[kv[0]]): + f.write("\t".join([ids[a], meta[a][4], meta[a][5], r_, ids[b], meta[b][4], str(meta[a][3] == meta[b][3])]) + "\n") + stage_log("dedupe_all", info) + print(json.dumps(info, ensure_ascii=False)[:3000]) + +STAGES = {"kohtd": stage_kohtd, "hkr": stage_hkr, "chd": stage_chd, "school": stage_school, + "rukopys": stage_rukopys, "hash": stage_hash, "dedupe": stage_dedupe, + "hash_synth": stage_hash_synth, "dedupe_all": stage_dedupe_all} + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("stages", nargs="+") + ap.add_argument("--force", action="store_true") + a = ap.parse_args() + for s in a.stages: + if (LOGS / f"stage_{s}.json").exists() and not a.force: + print("skip (log exists):", s) + continue + print("=== stage", s, flush=True) + STAGES[s]() diff --git a/scripts/r5/r5_disk_counts.py b/scripts/r5/r5_disk_counts.py new file mode 100644 index 0000000000000000000000000000000000000000..449c11ac794f6ba7e8a298c8833135d33ae1813a --- /dev/null +++ b/scripts/r5/r5_disk_counts.py @@ -0,0 +1,160 @@ +"""R5 DATA: count what is on disk for every data source held on the cluster. +Writes DATA/outputs/r5/disk_counts.json: for each source the counts and the exact files or folders that were counted. +Read-only. Usage: python -I r5_disk_counts.py +""" +import collections +import json +import os +import time +import zipfile +from pathlib import Path + +import pyarrow.parquet as pq + +DATA = Path("/path/to/TURKIC_OCR_DATA") +RAW = DATA / "data/raw" +PROC = DATA / "data/processed" +OUT = DATA / "outputs/r5/disk_counts.json" +res = {} + + +def zip_count(zp, skip_macosx=True): + z = zipfile.ZipFile(zp) + names = [i for i in z.infolist() if not i.is_dir()] + if skip_macosx: + names = [i for i in names if not i.filename.startswith("__MACOSX")] + ext = collections.Counter(os.path.splitext(i.filename)[1].lower() for i in names) + return {"files": len(names), "by_extension": dict(ext), "uncompressed_bytes": sum(i.file_size for i in names), + "zip_bytes": os.path.getsize(zp), "counted_file": str(zp)} + + +def n_files(d, pattern_ext=None): + n = 0 + total = 0 + for e in os.scandir(d): + if e.is_file() and (pattern_ext is None or e.name.lower().endswith(pattern_ext)): + n += 1 + total += e.stat().st_size + return n, total + + +def lines(p): + n = 0 + b = 0 + with open(p, "rb") as f: + for line in f: + n += 1 + b += len(line) + return n, b + + +# KOHTD +img_dir = PROC / "kohtd_words_raw/KOHTD_dataset/HK_dataset/img" +ann_dir = PROC / "kohtd_words_raw/KOHTD_dataset/HK_dataset/ann" +ni, bi = n_files(img_dir, ".jpg") +na, _ = n_files(ann_dir, ".json") +res["kohtd_words"] = {"word_crop_images": ni, "annotation_files": na, "bytes_images": bi, "counted_folder": str(img_dir)} +sheets = RAW / "kohtd/forms_sheets_extracted/20200929_Examination_sheets_cleaned" +ns, bs = n_files(sheets, ".jpg") +res["kohtd_sheets"] = {"sheet_scans": ns, "bytes": bs, "counted_folder": str(sheets)} +sp = {} +for name in ("train", "validation", "test"): + n, _ = lines(PROC / f"kohtd_split_v1/{name}.tsv") + sp[name] = n - 1 +res["kohtd_split_v1_rows"] = {"rows": sp, "counted_folder": str(PROC / "kohtd_split_v1")} + +# HKR +res["hkr_words"] = zip_count(RAW / "hkr_words_kaggle_scispecai/hkr_dat.zip") +# CHD +chd = zip_count(RAW / "chd/archive.zip") +z = zipfile.ZipFile(RAW / "chd/archive.zip") +chd["train_tsv_rows"] = sum(1 for l in z.read("train.tsv").decode("utf-8").split("\n") if l.strip()) +chd["test_tsv_rows"] = sum(1 for l in z.read("test.tsv").decode("utf-8").split("\n") if l.strip()) +res["chd"] = chd +# Sheriyeva isolated letters +sh = {} +for s in ("train", "val", "test"): + c = zip_count(RAW / f"sheriyeva/{s}.zip") + sh[s] = c +res["sheriyeva_letters"] = sh +# Turkish and Azerbaijani character sets +for key, zp, member in (("yasiradoan_hw_tr_en_hu", "yasiradoan_hw_tr_en_hu/yasiradoan_hw_tr_en_hu.zip", "version7.csv"), + ("yasiradoan_tr_csv", "yasiradoan_tr_csv/yasiradoan_tr_csv.zip", "Turkish_special_characters_2.csv"), + ("azemnist", "azemnist/azemnist.zip", "AzEMNIST.csv")): + zf = zipfile.ZipFile(RAW / zp) + n = 0 + classes = collections.Counter() + with zf.open(member) as f: + for line in f: + n += 1 + # label is the last column for yasiradoan files and the first column for AzEMNIST + parts = line.decode("utf-8", "replace").rstrip("\r\n").split(",") + classes[parts[0] if key == "azemnist" else parts[-1]] += 1 + res[key] = {"rows": n, "distinct_label_values": len(classes), "counted_file": str(RAW / zp) + "::" + member} +res["muhammeterem_tr_en_chars"] = zip_count(RAW / "muhammeterem_tr_en_chars/muhammeterem_tr_en_chars.zip") +# school notebooks +base = RAW / "school_notebooks_ru" +sn = {} +for s in ("train", "val", "test"): + d = json.load(open(base / f"annotations_{s}.json", encoding="utf-8")) + cats = collections.Counter(a["category_id"] for a in d["annotations"]) + withtext = collections.Counter(a["category_id"] for a in d["annotations"] if ((a.get("attributes") or {}).get("translation") or "").strip()) + sn[s] = {"pages": len(d["images"]), "annotations_by_category_id": dict(cats), "annotations_with_text_by_category_id": dict(withtext), + "counted_file": str(base / f"annotations_{s}.json")} +sn["category_names"] = {"0": "pupil_text (word polygons with text)", "1": "pupil_comment", "2": "teacher_comment", "3": "paper", "4": "text_line (polygon, no text)"} +res["school_notebooks_ru"] = sn +# RUKOPYS test +rows = [json.loads(l) for l in open(RAW / "rukopys_test/test/metadata.jsonl", encoding="utf-8")] +types = collections.Counter(r2["type"] for r in rows for r2 in r["regions"]) +res["rukopys_test"] = {"pages": len(rows), "regions_by_type": dict(types), + "handwritten_uk_legible": sum(1 for r in rows for r2 in r["regions"] if r2["type"] == "handwritten" and r2["language"] == "uk" and r2["legibility"] == "legible"), + "pages_by_source": dict(collections.Counter(r["source"] for r in rows)), + "counted_file": str(RAW / "rukopys_test/test/metadata.jsonl")} +# TurkishOCR-Bench +rows = [json.loads(l) for l in open(RAW / "turkishocr_bench/metadata.jsonl", encoding="utf-8")] +res["turkishocr_bench"] = {"pages": len(rows), "by_category": dict(collections.Counter(r["kategori"] for r in rows)), + "by_licence_field": dict(collections.Counter(r.get("lisans", "") for r in rows)), + "counted_file": str(RAW / "turkishocr_bench/metadata.jsonl")} +# NAF +naf = RAW / "naf/extracted_images" +nn, _ = n_files(naf) +res["naf"] = {"extracted_files": nn, "counted_folder": str(naf), + "note": "findings record NEW_NAF: 863 labelled form images (train 708, valid 78, test 77)"} +# DocLayNet v1.2 test parquet +tot = 0 +files = sorted((RAW / "doclaynet_v1_2_test/data").glob("*.parquet")) +for f in files: + tot += pq.ParquetFile(f).metadata.num_rows +res["doclaynet_v1_2_test"] = {"pages": tot, "parquet_files": len(files), "counted_folder": str(RAW / "doclaynet_v1_2_test/data")} +# ailabykt Sakha monolingual corpus +sak = RAW / "ailabykt_sakha_mono/data" +cnt = collections.Counter() +tot = 0 +for f in sorted(sak.glob("*.parquet")): + pf = pq.ParquetFile(f) + tot += pf.metadata.num_rows + if "source" in pf.schema_arrow.names: + col = pf.read(columns=["source"]).column(0).to_pylist() + cnt.update(col) +res["ailabykt_sakha_mono"] = {"documents": tot, "documents_by_source": dict(cnt), "counted_folder": str(sak)} +# generator text per language +pt = {} +for lang in ("kk", "ky", "uz_cyrl", "uz_latn", "tr", "az", "tt", "ba", "tk", "sah"): + p = PROC / f"pagesynth_text/{lang}/sentences.tsv" + n, b = lines(p) + lw = json.load(open(PROC / f"pagesynth_text/{lang}/label_words.json", encoding="utf-8")) + pt[lang] = {"sentences_file_lines": n, "bytes": b, "label_words": ({k: len(v) for k, v in lw.items() if isinstance(v, list)} if isinstance(lw, dict) else len(lw)), "counted_file": str(p)} +res["pagesynth_text"] = pt +# fonts: raw folder and generator assets +fonts = {} +for d in sorted(os.scandir(RAW / "fonts"), key=lambda e: e.name): + if d.is_dir(): + fonts[d.name] = sorted(x.name for x in os.scandir(d.path)) +res["fonts_raw_folder"] = {"families": len(fonts), "files_by_family": fonts, "counted_folder": str(RAW / "fonts")} +ga = Path("/path/to/TURKIC_OCR_CODE/src/pagesynth/assets/fonts") +res["fonts_generator_assets"] = {"files": sorted(x.name for x in os.scandir(ga) if x.is_file()), "counted_folder": str(ga), + "licence_files": sorted(x.name for x in os.scandir(ga / "licences"))} +res["generated_utc"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) +OUT.parent.mkdir(parents=True, exist_ok=True) +json.dump(res, open(OUT, "w", encoding="utf-8"), ensure_ascii=False, indent=1) +print("written", OUT) diff --git a/scripts/r5/r5_fetch_az_htr.py b/scripts/r5/r5_fetch_az_htr.py new file mode 100644 index 0000000000000000000000000000000000000000..e24f7bbfd766c4c8883f0f0d235b70085324af99 --- /dev/null +++ b/scripts/r5/r5_fetch_az_htr.py @@ -0,0 +1,86 @@ +"""R5 DATA (extra, beyond the plan): fetch the open Azerbaijani handwriting benchmark LocalDoc/azerbaijani-htr-benchmark +(CC BY 4.0, 442 human-annotated line crops from 29 pages, test-sized) and write a test-only manifest. +Plain public downloads, no login, no token, no special headers. The files are untrusted data: parquet is read with pyarrow only, nothing is executed. +Run on a ZEN4 node: python -I r5_fetch_az_htr.py fetch | manifest +""" +import hashlib +import io +import json +import sys +import time +import urllib.request +from pathlib import Path + +DATA = Path("/path/to/TURKIC_OCR_DATA") +RAW = DATA / "data/raw/localdoc_az_htr" +R5 = DATA / "data/processed/r5" +REPO = "LocalDoc/azerbaijani-htr-benchmark" +API = f"https://huggingface.co/api/datasets/{REPO}" +HDR = ["id", "image", "text", "lang", "script", "kind", "source", "split", "group", "unit"] + + +def sha256_file(p): + h = hashlib.sha256() + with open(p, "rb") as f: + for c in iter(lambda: f.read(1 << 20), b""): + h.update(c) + return h.hexdigest() + + +def fetch(): + RAW.mkdir(parents=True, exist_ok=True) + meta = json.load(urllib.request.urlopen(API, timeout=60)) + json.dump(meta, open(RAW / "api_record.json", "w", encoding="utf-8"), ensure_ascii=False, indent=1) + sib = [s["rfilename"] for s in meta.get("siblings", [])] + log = {"repo": REPO, "licence_field": (meta.get("cardData") or {}).get("license"), "files": {}, "fetched_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())} + for name in sib: + if name.endswith(".parquet") or name == "README.md" or name == ".gitattributes": + dst = RAW / name + dst.parent.mkdir(parents=True, exist_ok=True) + url = f"https://huggingface.co/datasets/{REPO}/resolve/main/{name}" + data = urllib.request.urlopen(url, timeout=300).read() + dst.write_bytes(data) + log["files"][name] = {"bytes": len(data), "sha256": sha256_file(dst)} + json.dump(log, open(RAW / "fetch_log.json", "w", encoding="utf-8"), indent=1) + print(json.dumps(log)[:1500]) + + +def manifest(): + import unicodedata + + import pyarrow.parquet as pq + cands = sorted(RAW.rglob("*.parquet")) + print("parquet files:", [str(c.relative_to(RAW)) for c in cands]) + lines = [c for c in cands if "line" in str(c).lower()] + assert lines, "no lines parquet found" + pf = pq.ParquetFile(lines[0]) + print("schema:", pf.schema_arrow) + tbl = pf.read() + cols = tbl.column_names + img_col = next(c for c in cols if "image" in c.lower()) + txt_col = next(c for c in cols if c.lower() in ("text", "label", "transcription", "ground_truth", "gt")) + page_col = next((c for c in cols if "page" in c.lower() or "source" in c.lower()), None) + out_dir = R5 / "images/az_localdoc_htr" + out_dir.mkdir(parents=True, exist_ok=True) + rows = [] + for i in range(tbl.num_rows): + im = tbl.column(img_col)[i].as_py() + data = im["bytes"] if isinstance(im, dict) else im + text = unicodedata.normalize("NFC", str(tbl.column(txt_col)[i].as_py())).strip() + for ch in ("\t", "\r", "\n"): + text = text.replace(ch, " ") + dst = out_dir / f"{i:04d}.png" + from PIL import Image + Image.open(io.BytesIO(data)).convert("RGB").save(dst) + grp = "az_page_" + str(tbl.column(page_col)[i].as_py()) if page_col else "az_page_unknown" + rows.append([f"az_localdoc:{i:04d}", str(dst), text, "az", "Latn", "hand_real", "localdoc_az_htr", "test", grp, "line"]) + mp = R5 / "manifests/az_localdoc_test.tsv" + with open(mp, "w", encoding="utf-8", newline="") as f: + f.write("\t".join(HDR) + "\n") + for r in rows: + f.write("\t".join(r) + "\n") + print("wrote", mp, len(rows), "columns", cols) + + +if __name__ == "__main__": + {"fetch": fetch, "manifest": manifest}[sys.argv[1]]() diff --git a/scripts/r5/r5_finalize.sbatch b/scripts/r5/r5_finalize.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..7a867cce97fa31b0210beae4c4f13a27cb479149 --- /dev/null +++ b/scripts/r5/r5_finalize.sbatch @@ -0,0 +1,15 @@ +#!/bin/bash +#SBATCH --job-name=r5_finalize +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=2 +#SBATCH --mem=8G +#SBATCH --time=00:40:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# R5 DATA: after the duplicate check: validate the manifests, cut the P2 slice, write manifest statistics, the registry and the effective mix shares. +PY=/path/to/TURKIC_OCR_CODE/.venv/bin/python +S=/path/to/TURKIC_OCR_CODE/scripts/r5 +$PY -I $S/r5_validate_manifests.py +$PY -I $S/r5_p2_slice.py +$PY -I $S/r5_registry.py diff --git a/scripts/r5/r5_kohtd_check.py b/scripts/r5/r5_kohtd_check.py new file mode 100644 index 0000000000000000000000000000000000000000..75e83759efa64e1c1c9405cc2b28d2be72920388 --- /dev/null +++ b/scripts/r5/r5_kohtd_check.py @@ -0,0 +1,36 @@ +"""R5 DATA: what does cleaning change in KOHTD labels, and what is the form_id of scan-named crops.""" +import collections +import unicodedata +from pathlib import Path + +K1 = Path("/path/to/TURKIC_OCR_DATA/data/processed/kohtd_split_v1") +for fn in ("train.tsv", "validation.tsv", "test.tsv"): + kinds = collections.Counter() + changes = collections.Counter() + ex = [] + scan_forms = collections.Counter() + with open(K1 / fn, encoding="utf-8", newline="") as f: + f.readline() + for line in f: + p = line.rstrip("\n").split("\t") + kinds[p[-1]] += 1 + if p[-1] != "numbered": + scan_forms[p[1][:20]] += 1 + lab = "\t".join(p[2:-1]) + nf = unicodedata.normalize("NFC", lab) + st = nf.strip() + if nf != lab: + changes["nfc_changed"] += 1 + if len(ex) < 4: + ex.append((p[0], [hex(ord(c)) for c in lab if unicodedata.normalize("NFC", c) != c][:4], lab)) + if st != nf: + changes["strip_changed"] += 1 + if len(ex) < 8: + ex.append((p[0], "strip", repr(lab))) + if lab != lab.replace("\r", " ").replace("\n", " "): + changes["has_newline"] += 1 + if "\t" in lab: + changes["has_tab"] += 1 + print(fn, dict(kinds), dict(changes), "scan-form-ids", len(scan_forms), list(scan_forms.items())[:3]) + for e in ex: + print(" ", e) diff --git a/scripts/r5/r5_p2_slice.py b/scripts/r5/r5_p2_slice.py new file mode 100644 index 0000000000000000000000000000000000000000..7464a8edefe1575a07134a007f128c863fc8d4b8 --- /dev/null +++ b/scripts/r5/r5_p2_slice.py @@ -0,0 +1,89 @@ +"""R5 DATA: the unseen-word slice P2 (and P2b) of the KOHTD test, by version 3 section 1. + +P2 = KOHTD test crops whose normalised label does not occur among the normalised labels of any handwriting training crop + (real handwriting train manifests plus hand_synth train manifests when they exist). +P2b = P2 crops whose normalised label also equals no whitespace token of any training label of any kind + (typed_synth, hand_synth, clutter excluded because empty). Reported only. +Normalisation: NFC, lower case, keep only letters and digits (Unicode categories L* and N*). +A test crop whose normalised label is empty (for example "-" or ".") belongs to neither slice. +Reads only label text and manifests; opens no image. Writes kohtd_test_p2.tsv, kohtd_test_p2b.tsv and p2_slice_info.json. +Run again when GEN's synthetic train manifests are frozen. Usage: python -I r5_p2_slice.py +""" +import json +import time +import unicodedata +from pathlib import Path + +MAN = Path("/path/to/TURKIC_OCR_DATA/data/processed/r5/manifests") +INFO = MAN.parent / "p2_slice_info.json" +HDR = ["id", "image", "text", "lang", "script", "kind", "source", "split", "group", "unit"] +HAND_TRAIN = ["kohtd_train", "hkr_train", "chd_train", "school_train", "synth_hand_train"] +OTHER_TRAIN = ["synth_typed_train"] + + +def norm(s): + s = unicodedata.normalize("NFC", s).lower() + return "".join(c for c in s if unicodedata.category(c)[0] in ("L", "N")) + + +def read(p): + rows = [] + with open(p, encoding="utf-8", newline="") as f: + assert f.readline().rstrip("\n").split("\t") == HDR + for line in f: + rows.append(line.rstrip("\n").split("\t")) + return rows + + +def write(p, rows): + with open(p, "w", encoding="utf-8", newline="") as f: + f.write("\t".join(HDR) + "\n") + for r in rows: + f.write("\t".join(r) + "\n") + + +used, missing = {}, [] +hand_labels = set() +tokens = set() +for name in HAND_TRAIN + OTHER_TRAIN: + p = MAN / (name + ".tsv") + if not p.exists(): + missing.append(name) + continue + rows = read(p) + used[name] = len(rows) + for r in rows: + n = norm(r[2]) + if name in HAND_TRAIN and n: + hand_labels.add(n) + for tok in r[2].split(): + t = norm(tok) + if t: + tokens.add(t) + if n: + tokens.add(n) +test = read(MAN / "kohtd_test.tsv") +p2, p2b, empty = [], [], 0 +for r in test: + n = norm(r[2]) + if not n: + empty += 1 + continue + if n not in hand_labels: + p2.append(r) + if n not in tokens: + p2b.append(r) +write(MAN / "kohtd_test_p2.tsv", p2) +write(MAN / "kohtd_test_p2b.tsv", p2b) +info = { + "generated_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "test_crops": len(test), "test_crops_with_empty_normalised_label": empty, + "p2_crops": len(p2), "p2b_crops": len(p2b), + "p2_forms": len({r[8] for r in p2}), "p2b_forms": len({r[8] for r in p2b}), + "train_manifests_used_rows": used, "train_manifests_missing_at_run_time": missing, + "distinct_normalised_handwriting_train_labels": len(hand_labels), + "final": len(missing) == 0, + "note": "P2 is provisional while any train manifest is missing: rerun after GEN's synth_hand_train.tsv and synth_typed_train.tsv exist.", +} +json.dump(info, open(INFO, "w", encoding="utf-8"), ensure_ascii=False, indent=1) +print(json.dumps(info, ensure_ascii=False)) diff --git a/scripts/r5/r5_registry.py b/scripts/r5/r5_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..75ddc6e2314342077afcd5e66dcbbe7968e91754 --- /dev/null +++ b/scripts/r5/r5_registry.py @@ -0,0 +1,192 @@ +"""R5 DATA: manifest statistics, the evaluation registry (evalsets.json) and the effective mix_v1 shares. +Reads only the manifests (text columns); opens no image. Run on a cluster compute node after dedupe (and again when GEN's manifests appear). +Writes DATA/data/processed/r5/manifest_stats.json, DATA/data/processed/r5/evalsets.json, DATA/outputs/r5/mix_v1_shares.json. +""" +import collections +import hashlib +import json +import time +from pathlib import Path + +R5 = Path("/path/to/TURKIC_OCR_DATA/data/processed/r5") +MAN = R5 / "manifests" +OUTD = Path("/path/to/TURKIC_OCR_DATA/outputs/r5") +HDR = ["id", "image", "text", "lang", "script", "kind", "source", "split", "group", "unit"] +NOW = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) + + +def sha256_file(p): + h = hashlib.sha256() + with open(p, "rb") as f: + for c in iter(lambda: f.read(1 << 20), b""): + h.update(c) + return h.hexdigest() + + +def stats(p): + rows = [] + with open(p, encoding="utf-8", newline="") as f: + assert f.readline().rstrip("\n").split("\t") == HDR, p + for line in f: + rows.append(line.rstrip("\n").split("\t")) + return { + "rows": len(rows), + "groups": len({r[8] for r in rows}), + "chars": sum(len(r[2]) for r in rows), + "by_lang": dict(collections.Counter(r[3] for r in rows)), + "by_script": dict(collections.Counter(r[4] for r in rows)), + "by_kind": dict(collections.Counter(r[5] for r in rows)), + "by_source": dict(collections.Counter(r[6] for r in rows)), + "by_split": dict(collections.Counter(r[7] for r in rows)), + "by_unit": dict(collections.Counter(r[9] for r in rows)), + "empty_labels": sum(1 for r in rows if r[2] == ""), + "sha256": sha256_file(p), + "path": str(p), + } + + +mstats = {} +for p in sorted(MAN.glob("*.tsv")): + if p.name.endswith(".meta.tsv"): # FREEZE 21 Nov: GEN's per-row sidecars are not manifests (extra columns) + continue + mstats[p.stem] = stats(p) +json.dump({"generated_utc": NOW, "manifests": mstats}, open(R5 / "manifest_stats.json", "w", encoding="utf-8"), ensure_ascii=False, indent=1) + + +def entry(name, manifest, split, purpose, locked, **kw): + path = MAN / (manifest + ".tsv") + e = {"name": name, "manifest": str(path), "split": split, "purpose": purpose, "locked": locked} + if manifest in mstats: + s = mstats[manifest] + e.update(status="ready", n_rows=s["rows"], n_groups=s["groups"], manifest_sha256=s["sha256"], langs=s["by_lang"], unit=list(s["by_unit"])[0] if s["by_unit"] else None) + else: + e.update(status="placeholder: manifest not written yet (planned path)", n_rows=None, n_groups=None, manifest_sha256=None) + e.update(kw) + assert " " not in name and "(" not in name, "evalset names are used in file paths" + return e + + +p2info = json.load(open(R5 / "p2_slice_info.json")) if (R5 / "p2_slice_info.json").exists() else {} +p2_final = bool(p2info.get("final")) + +sets = [ + # ---- validation sets (selection only; never used for the final claim) + entry("V1", "kohtd_screen_v1", "val", + "KOHTD validation screen set of the zero-shot screen: at most 15 crops per validation form, 3,678 crops (screen rule v1). Selection of B1 and B2 by amendment 3.2 C6 uses CER on this set.", False, + group_unit="KOHTD form", source_of_list="records/R4/J2_screen/screen_set_v1.tsv, sha256 aca23aed02629f884cd533761ca2553951eb91cc9b15120a25c88071f54198ec (matches the cluster copy), used unchanged", + split_rule="form-disjoint from KOHTD train and test (K1 split v1)"), + entry("V1lm", "kohtd_lmtune", "val", + "500 KOHTD validation crops that are not in V1 (numpy default_rng(20261121)). Only for tuning the weights of post-processing (language model, fixed script).", False, + group_unit="KOHTD form", split_rule="subset of KOHTD validation, disjoint from V1"), + entry("kohtd_val", "kohtd_val", "val", "All 16,238 KOHTD validation crops (258 forms); superset of V1 and V1lm. Reported as the wider validation figure; selection uses V1.", False, + group_unit="KOHTD form", split_rule="K1 split v1: sha256 of 'KOHTD-split-v1-2026-11-20:'+form id, first 8 hex digits mod 100 in 70..84"), + entry("hkr_val", "hkr_val", "val", "HKR words, validation part of the audit-recorded official split (Russian and Kazakh handwriting words). Cyrillic handwriting check.", False, + group_unit="HKR template and filled-form instance (project inference)", split_rule="the split recorded in the project audit manifest (described there as the official CSV split; not re-read from the CSV in R5); NOT form-disjoint", + caution="the HKR split puts crops of the same filled forms in train, val and test; sizes differ from the 5,057-per-part figures of one published paper; use it for rough comparison, not as proof of generalisation to new writers"), + entry("chd_val", "chd_val", "val", "Cyrillic Handwriting Dataset (Russian words): 5% of train word types held out for validation (the dataset ships no validation part).", False, + group_unit="word type (the dataset has no writer or page id)", split_rule="word type with sha256('R5-chd-val-v1:'+label) first 8 hex digits mod 100 below 5; a word type never sits in both train and val", + caution="writer identity is unknown, so the same hand may appear in train and val"), + entry("school_val", "school_val", "val", "School notebooks (Russian), word crops of the 150 official validation pages.", False, + group_unit="notebook page", split_rule="official page split of the dataset kept (train 1,557 / val 150 / test 150 pages, no page in two parts)"), + entry("hkr_val_s2000", "hkr_val_s2000", "val", "OPTIONAL small version of hkr_val: 2,000 rows drawn with seed 20261121 (default_rng.choice), for cheap validation passes.", False, subset_of="hkr_val", group_unit="HKR template and filled-form instance"), + entry("chd_val_s2000", "chd_val_s2000", "val", "OPTIONAL small version of chd_val: 2,000 rows drawn with seed 20261121.", False, subset_of="chd_val", group_unit="word type"), + entry("school_val_s2000", "school_val_s2000", "val", "OPTIONAL small version of school_val: 2,000 rows drawn with seed 20261121 over the 150 validation pages.", False, subset_of="school_val", group_unit="notebook page"), + entry("synth_hand_val", "synth_hand_val", "val", "Synthetic handwriting line crops (10 language-scripts, 1,000 each planned), with two held-out fonts per script (unseen-font check).", False, group_unit="composed page", owner="GEN"), + entry("synth_typed_val", "synth_typed_val", "val", "Synthetic typed line crops (500 per language-script planned).", False, group_unit="source document", owner="GEN"), + entry("synth_clutter_val", "synth_clutter_val", "val", "Clutter crops with no text; the target is the empty string (500 planned). Measures hallucination.", False, owner="GEN"), + entry("synth_pages_val", "synth_pages_val", "val", "Composed pages with line boxes and polygons (300 planned), for detector validation.", False, owner="GEN"), + # ---- test sets (locked) + entry("kohtd_test", "kohtd_test", "test", "Primary endpoint P1: CER on all 18,615 KOHTD test crops of 305 forms.", True, + group_unit="KOHTD form", endpoint="P1", split_rule="K1 split v1, share 85..99 of the form hash", + caution="form-disjoint, not writer-disjoint (writer ids do not exist); labels are crowd labels (two volunteers agreeing)"), + entry("kohtd_test_p2", "kohtd_test_p2", "test", + "Primary endpoint P2: KOHTD test crops whose normalised label (NFC, lower case, letters and digits only) is in no handwriting training label (version 3 section 1).", True, + group_unit="KOHTD form", split_rule="slice of kohtd_test by label, computed by scripts/r5_p2_slice.py from the final train manifests", + endpoint="P2", provisional=not p2_final, p2_info=p2info, + note="provisional until GEN's synthetic train manifests exist; rerun r5_p2_slice.py then (it records which train manifests it used)"), + entry("kohtd_test_p2b", "kohtd_test_p2b", "test", + "Reported only: P2 crops whose normalised label equals no whitespace token of any training label of any kind (real, synthetic handwriting, synthetic typed).", True, + group_unit="KOHTD form", endpoint="P2b (reported only)", split_rule="slice of P2", provisional=not p2_final), + entry("hkr_test1", "hkr_test1", "test", "HKR words, test1 part of the audit-recorded official split (rough comparison with published figures).", True, + group_unit="HKR template and filled-form instance", split_rule="project audit record of the official split, kept", caution="not form-disjoint from train; 4,966 rows against 5,057 in one published paper"), + entry("hkr_test2", "hkr_test2", "test", "HKR words, test2 part of the audit-recorded official split (rough comparison with published figures).", True, + group_unit="HKR template and filled-form instance", split_rule="project audit record of the official split, kept", caution="not form-disjoint from train; 5,043 rows against 5,057 in one published paper"), + entry("chd_test", "chd_test", "test", "Cyrillic Handwriting Dataset, official test part (1,544 Russian word crops).", True, + group_unit="word type", split_rule="official train/test split of the dataset kept", + caution="615 of 1,544 test crops carry a word that also occurs in CHD train; writers unknown"), + entry("school_test", "school_test", "test", "School notebooks (Russian), word crops of the 150 official test pages.", True, + group_unit="notebook page", split_rule="official page split of the dataset kept"), + entry("rukopys_test", "rukopys_test", "test", + "RUKOPYS test split (Ukrainian handwriting; 385 pages; lines cut from the handwritten, legible, Ukrainian boxes, human-annotated). Cyrillic handwriting on photos and scans; lang is 'other'.", True, + group_unit="page", split_rule="official test split of the dataset; no training data of RUKOPYS is used in R5 (only the test split is on the cluster)"), + entry("az_localdoc_test", "az_localdoc_test", "test", + "EXTRA (added by stage DATA beyond the plan): 442 real Azerbaijani (Latin) handwriting lines from 29 phone-photographed pages, annotated by hand in Label Studio with exact transcriptions (LocalDoc/azerbaijani-htr-benchmark, CC BY 4.0). The only real handwriting of a Latin-script target language that could be obtained openly; unknown writers (at least 3 hands). lang az.", True, + group_unit="source page", split_rule="the dataset ships one test split only; used as a test set only, never for training", + added_beyond_plan=True, caution="test-sized (442 lines) and few writers; intervals will be wide"), + entry("synth_hand_test", "synth_hand_test", "test", "Synthetic handwriting line crops, held-out text and held-out fonts (1,000 per language-script planned).", True, owner="GEN"), + entry("synth_typed_test", "synth_typed_test", "test", "Synthetic typed line crops from held-out text (500 per language-script planned).", True, owner="GEN"), + entry("synth_clutter_test", "synth_clutter_test", "test", "Clutter crops, empty target (500 planned).", True, owner="GEN"), + entry("synth_pages_test", "synth_pages_test", "test", "Composed test pages with line polygons (300 planned) for Level P if a detector exists.", True, owner="GEN"), +] +listed = [{ + "name": "TurkishOCR-Bench (moganai)", "manifest": None, "split": "test", "locked": True, + "purpose": "488 Turkish pages in 10 categories, 50 of them handwritten phone photos (the only real Turkish handwriting held).", + "status": "listed, not used in R5", + "reason": "its licence is an open owner question: the pages carry mixed per-page licences (by-nc, by, by-sa, FSEK, and 'no licence stated' for the 50 handwritten pages)", + "held_at": "/path/to/TURKIC_OCR_DATA/data/raw/turkishocr_bench"}] +reg = { + "registry_version": "r5-evalsets-1", "generated_utc": NOW, + "format": "manifest TSV columns: id, image, text, lang, script, kind, source, split, group, unit (R5 common specification). Every test set is locked: no process opens its images or runs a model on it before the single scoring pass after 22 Nov 2026 19:00 UTC.", + "sets": sets, "listed_not_used": listed, + "hash_note": "images were hashed (sha256 and 64-bit pHash) for the duplicate check; no test image was shown or scored", +} +json.dump(reg, open(R5 / "evalsets.json", "w", encoding="utf-8"), ensure_ascii=False, indent=1) + +# ---- effective mix_v1 shares +n_train = {k: mstats[k]["rows"] for k in ("kohtd_train", "hkr_train", "chd_train", "school_train") if k in mstats} +latin_items = 0 # no Turkish (or other Latin-script) handwriting word or line set is held: the Turkish sets are single characters +latin_cap_share = min(0.05, 5 * latin_items / 1e6) +other_cyr = {} +for k in ("hkr_train", "chd_train", "school_train"): + n = n_train.get(k, 0) + want = round(0.15 / 3 * 1e6) # samples per 1M + cap = 3 * n + other_cyr[k] = {"train_items": n, "requested_samples_per_1M": want, "cap_3_passes_samples_per_1M": cap, + "passes_at_request_per_1M": round(want / n, 3) if n else None, "cap_binds": want > cap} +moved = round(0.05 - latin_cap_share, 6) +latin = ["uz_latn", "tr", "az", "tk"] +cyr = ["kk", "ky", "uz_cyrl", "tt", "ba", "sah"] +hand_synth_each = {l: 0.30 / 10 for l in cyr + latin} +for l in latin: + hand_synth_each[l] += moved / len(latin) +mix = { + "set_by": "the R5 DATA plan; the shares below are written unchanged", + "shares_as_set": { + "hand_real_kk (KOHTD train)": 0.35, + "hand_real_other_cyrillic (HKR train, CHD train, school_notebooks train; equal by source; at most 3 passes of a source per 1M samples)": 0.15, + "hand_real_latin (Turkish handwriting train)": 0.05, + "hand_synth (equal across the 10 language-scripts)": 0.30, + "typed_synth (equal across the 10 language-scripts)": 0.12, + "clutter (empty string target)": 0.03, + }, + "clause_applied_hand_real_latin": { + "rule": "if fewer than 5,000 items, the share drops to what 5 repeats per 1M samples allow, and the rest moves to hand_synth Latin", + "items_available": latin_items, + "why_zero": "no Latin-script handwriting set of words or lines that can be used for TRAINING is on the cluster (the only real Latin-script lines held are the 442 Azerbaijani test-only lines, which must never be trained on): the Turkish and Azerbaijani handwriting sets held are single characters (T-H-E copies, Turkish special characters, AzEMNIST, a set of 835,750 character images); TurkishOCR-Bench handwriting is 50 pages and is listed, not used", + "allowed_share": latin_cap_share, "moved_to_hand_synth_latin": moved, + }, + "other_cyrillic_sources_check": other_cyr, + "kohtd_train_passes_per_1M_samples": round(0.35 * 1e6 / n_train["kohtd_train"], 3) if n_train.get("kohtd_train") else None, + "effective_shares": { + "hand_real_kk": 0.35, "hand_real_other_cyrillic": 0.15, "hand_real_latin": latin_cap_share, + "hand_synth": round(0.30 + moved, 6), "typed_synth": 0.12, "clutter": 0.03, + "sum": round(0.35 + 0.15 + latin_cap_share + 0.30 + moved + 0.12 + 0.03, 6)}, + "hand_synth_share_per_language_script": {k: round(v, 6) for k, v in hand_synth_each.items()}, + "assumption_flag": "the 5 points moved to hand_synth Latin are split equally over the four Latin-script language-scripts (uz_latn, tr, az, tk); this is DATA's reading of the clause, another split may be chosen", + "typed_synth_share_per_language_script": {k: 0.012 for k in cyr + latin}, + "train_items_after_dedupe": n_train, + "generated_utc": NOW, +} +OUTD.mkdir(parents=True, exist_ok=True) +json.dump(mix, open(OUTD / "mix_v1_shares.json", "w", encoding="utf-8"), ensure_ascii=False, indent=1) +print("written: manifest_stats.json, evalsets.json, mix_v1_shares.json;", len(mstats), "manifests;", sum(1 for s in sets if s["status"] == "ready"), "sets ready") diff --git a/scripts/r5/r5_val_subsets.py b/scripts/r5/r5_val_subsets.py new file mode 100644 index 0000000000000000000000000000000000000000..87e5fd1627b48fef31d13e1dbc2998a3a510eb16 --- /dev/null +++ b/scripts/r5/r5_val_subsets.py @@ -0,0 +1,19 @@ +"""R5 DATA (optional helper): fixed 2,000-row random subsets of the three large Russian validation manifests (hkr_val, chd_val, school_val), +so that a validation pass over many checkpoints stays cheap. The full validation manifests stay as they are. +Draw: numpy.random.default_rng(20261121).choice(n, 2000, replace=False), rows kept in manifest order. Opens no image. +Usage: python -I r5_val_subsets.py +""" +import numpy as np +from pathlib import Path + +MAN = Path("/path/to/TURKIC_OCR_DATA/data/processed/r5/manifests") +for name in ("hkr_val", "chd_val", "school_val"): + lines = open(MAN / f"{name}.tsv", encoding="utf-8", newline="").read().split("\n") + header, rows = lines[0], [l for l in lines[1:] if l] + rng = np.random.default_rng(20261121) + pick = np.sort(rng.choice(len(rows), size=2000, replace=False)) + with open(MAN / f"{name}_s2000.tsv", "w", encoding="utf-8", newline="") as f: + f.write(header + "\n") + for i in pick: + f.write(rows[i] + "\n") + print(name, len(rows), "->", len(pick)) diff --git a/scripts/r5/r5_validate_manifests.py b/scripts/r5/r5_validate_manifests.py new file mode 100644 index 0000000000000000000000000000000000000000..6a7ec40b4311621ff969cdf507cdd87f1e67a5bc --- /dev/null +++ b/scripts/r5/r5_validate_manifests.py @@ -0,0 +1,74 @@ +"""R5 DATA: check every manifest in DATA/data/processed/r5/manifests against the shared format. +Checks: header; allowed values of lang, script, kind, split, unit; text is NFC and has no tab or line break; ids unique across all manifests of the folder +(except the named subsets V1 and lmtune, which repeat validation ids on purpose); image path is absolute and exists; train/val/test value agrees with the file name. +Writes DATA/outputs/r5/manifest_validation.json. Usage: python -I r5_validate_manifests.py [manifest names to check only; then the output file is manifest_validation_partial.json] +""" +import collections +import json +import os +import sys +import unicodedata +from pathlib import Path + +MAN = Path("/path/to/TURKIC_OCR_DATA/data/processed/r5/manifests") +HDR = ["id", "image", "text", "lang", "script", "kind", "source", "split", "group", "unit"] +LANG = {"kk", "ky", "uz_cyrl", "uz_latn", "tr", "az", "tt", "ba", "tk", "sah", "ru", "other"} +SCRIPT = {"Cyrl", "Latn"} +KIND = {"hand_real", "hand_synth", "typed_real", "typed_synth", "clutter"} +SPLIT = {"train", "val", "test"} +UNIT = {"word", "line", "page"} +SUBSETS = {"kohtd_screen_v1", "kohtd_lmtune", "kohtd_test_p2", "kohtd_test_p2b", "hkr_val_s2000", "chd_val_s2000", "school_val_s2000"} +res = {} +seen = {} +dups = collections.Counter() +ONLY = set(sys.argv[1:]) +for p in sorted(MAN.glob("*.tsv")): + if p.name.endswith(".meta.tsv"): # FREEZE 21 Nov: GEN's per-row sidecars are not manifests (extra columns) + continue + name = p.stem + if ONLY and name not in ONLY: + continue + bad = collections.Counter() + n = 0 + with open(p, encoding="utf-8", newline="") as f: + if f.readline().rstrip("\n").split("\t") != HDR: + bad["bad_header"] += 1 + for line in f: + parts = line.rstrip("\n").split("\t") + n += 1 + if len(parts) != 10: + bad["wrong_column_count"] += 1 + continue + id_, img, text, lang, script, kind, source, split, group, unit = parts + if unicodedata.normalize("NFC", text) != text: + bad["text_not_nfc"] += 1 + if lang not in LANG: + bad["bad_lang"] += 1 + if script not in SCRIPT: + bad["bad_script"] += 1 + if kind not in KIND: + bad["bad_kind"] += 1 + if split not in SPLIT: + bad["bad_split"] += 1 + if unit not in UNIT: + bad["bad_unit"] += 1 + if not img.startswith("/"): + bad["image_not_absolute"] += 1 + elif not os.path.exists(img): + bad["image_missing"] += 1 + for sfx, sp in (("_train", "train"), ("_val", "val"), ("_test", "test"), ("_test1", "test"), ("_test2", "test")): + if name.endswith(sfx) and split != sp: + bad["split_value_vs_file_name"] += 1 + if name in ("kohtd_screen_v1", "kohtd_lmtune", "hkr_val_s2000", "chd_val_s2000", "school_val_s2000"): + if split != "val": + bad["subset_not_val"] += 1 + if name not in SUBSETS: + if id_ in seen: + dups[(name, seen[id_])] += 1 + else: + seen[id_] = name + res[name] = {"rows": n, "problems": dict(bad)} +out = {"manifests": res, "duplicate_ids_across_manifests": {f"{a} ~ {b}": v for (a, b), v in dups.items()}, + "all_clean": all(not v["problems"] for v in res.values()) and not dups} +Path("/path/to/TURKIC_OCR_DATA/outputs/r5/" + ("manifest_validation_partial.json" if ONLY else "manifest_validation.json")).write_text(json.dumps(out, ensure_ascii=False, indent=1), encoding="utf-8") +print(json.dumps(out, ensure_ascii=False)[:3000]) diff --git a/scripts/r5_curve_set.sbatch b/scripts/r5_curve_set.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..0b5bd0c1f890337c471fed8d58ca4a529e2a95d2 --- /dev/null +++ b/scripts/r5_curve_set.sbatch @@ -0,0 +1,13 @@ +#!/bin/bash +#SBATCH --job-name=r5_curve_set +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=2 +#SBATCH --mem=8G +#SBATCH --time=00:20:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# R5 EVALCODE: (re)builds the fixed learning-curve set curve_v1 from the validation manifests that exist and registers it in evalsets.json. +# Re-run when GEN's or PRINT's validation manifests appear; use "--register-only" after DATA's r5_registry.py rewrote evalsets.json. +C=/path/to/TURKIC_OCR_CODE +$C/.venv_kraken/bin/python -I $C/scripts/r5eval/build_curve_set.py "$@" diff --git a/scripts/r5_erran/erran_analysis.py b/scripts/r5_erran/erran_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..d0af4fe68e9454e8982af1c2b0355230917a811a --- /dev/null +++ b/scripts/r5_erran/erran_analysis.py @@ -0,0 +1,1042 @@ +"""ERRAN (R5): descriptive error analysis of every arm on VALIDATION data only. + +Tasks (ERRAN plan): + 1 error taxonomy on V1 (KOHTD validation screen set) and on hkr/chd/school _val_s2000, with form-bootstrap intervals, + top-20 confusion pairs and per-letter error rates of the Kazakh special letters; + 3 overlap of error-crop sets between arms (Jaccard) and the crops every arm gets wrong; + 4 attribute breakdown on synth_hand_val, synth_typed_val, print_real_val and synth_clutter_val from the generator side files; + 6 learning curves on curve_v1 (25/50/75/100% of P_short). +Scoring conventions are those of the frozen R5 scorer (CODE/src/r5eval): reference = manifest text joined on id after N0, +output = N0 of the TSV hyp, alignment = r5eval.align.align_ops (J2 tie-break), bootstrap = r5eval.stats weights (seed 20261121, +B = 10,000, clusters = the manifest 'group' column: forms for KOHTD, form instances for HKR, pages, source documents). +Locked (test) sets are never opened: every manifest path is taken from a registry entry whose split is 'val' and locked is false. + +Private outputs (reference and output strings of real persons' handwriting) are written only under OUT/private/ on the cluster. +The public JSON files contain counts, rates and single characters only. +""" +import argparse +import collections +import json +import os +import sys +import time +import unicodedata + +import numpy as np + +sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src") +from r5eval import stats # noqa: E402 +from r5eval.align import align_ops, lev_fast # noqa: E402 +from r5eval.analyse import COLLAPSE, LETTERS, LEN_EDGES, length_bucket # noqa: E402 +from r5eval.ioutil import read_manifest, read_preds, read_meta_tsv, sha256_file, write_json_atomic # noqa: E402 +from r5eval.lookalike import PARTNER, repair_label # noqa: E402 +from r5eval.textnorm import fold_lower, char_script_set, norm # noqa: E402 + +D = "/path/to/TURKIC_OCR_DATA" +PREDS = D + "/outputs/r5/preds" +SCORES = D + "/outputs/r5/scores" +REG = D + "/data/processed/r5/evalsets.json" +B = stats.B_DEFAULT +SEED = stats.SEED_BASE +P_SHORT = 150000 + +VLM_ARMS = ["hunyuanocr", "minicpm_ocr_1_0", "paddleocr_vl_1_6", "qwen3_vl_2b", "lightonocr_3_0_8b", "glm_ocr", "teleocr", + "ovisocr2", "ovisocr3", "lightonocr_3_1b", "granite_docling_258m"] +LINE_ARMS = [("A1", "long"), ("A1", "long_lm_gated"), ("A2", "long_lm_gated"), ("A3", "long")] +TAX_SETS = ["V1", "hkr_val_s2000", "chd_val_s2000", "school_val_s2000"] +ATTR_SETS = ["synth_hand_val", "synth_typed_val", "print_real_val", "synth_clutter_val"] +CURVE_ARMS = ["hunyuanocr", "minicpm_ocr_1_0", "paddleocr_vl_1_6", "qwen3_vl_2b", "lightonocr_3_0_8b", "glm_ocr", "teleocr", + "ovisocr2", "ovisocr3", "lightonocr_3_1b", "granite_docling_258m", "firered_ocr", "oxr_1_0", "surya_ocr_2_5", + "mineru2_5_pro", "A1", "A2", "A3", "A1s", "A4"] +MIN_ROWS = 30 + +# Kazakh special letter -> Russian look-alike (frozen scorer table, lower case; analyse._PARTNER_LOWER['kk'] via COLLAPSE) +KK_PAIRS_LOWER = {k: v for k, v in COLLAPSE["kk"].items() if k == k.lower()} +KK_SPECIAL_LOWER = set(KK_PAIRS_LOWER) +KK_PLAIN_TO_SPECIAL = collections.defaultdict(set) +for _s, _p in KK_PAIRS_LOWER.items(): + KK_PLAIN_TO_SPECIAL[_p].add(_s) +KK_ALL_SPECIAL = set(LETTERS["kk"]) + +FINE_TO_COARSE = { + "kk_collapse_to_russian": "kazakh_letter_vs_russian_lookalike", + "kk_overgeneration": "kazakh_letter_vs_russian_lookalike", + "kk_letter_swapped_for_another_kk_letter": "kazakh_letter_vs_another_kazakh_letter", + "wrong_script_in_output": "wrong_script_lookalike", + "offscript_letter_in_reference": "reference_has_offscript_letter", + "case_only": "case_only", + "space_words_merged": "space_words_merged_or_split", + "space_word_split": "space_words_merged_or_split", + "space_substituted": "space_words_merged_or_split", + "space_next_to_punctuation": "space_next_to_punctuation", + "punctuation_or_symbol": "punctuation_or_symbol", + "digit": "digit", + "other_substitution": "other_substitution", + "other_deletion": "other_deletion", + "other_insertion": "other_insertion", +} +CROP_LEVEL = ["empty_output", "truncation", "extra_text_after_correct_reading", "unrelated_cer_above_0_8"] +FINE = list(FINE_TO_COARSE) +COARSE = [] +for _c in FINE_TO_COARSE.values(): + if _c not in COARSE: + COARSE.append(_c) +CHAR_CLASSES = CROP_LEVEL + FINE +CROP_CLASSES = CROP_LEVEL + COARSE + ["mixed"] + +PLAIN_NAMES = { + "empty_output": "the model gave no text at all", + "truncation": "the output is a proper prefix of the reference (reading stopped early)", + "extra_text_after_correct_reading": "the reference is a proper prefix of the output (correct reading, then extra text)", + "unrelated_cer_above_0_8": "output unrelated to the reference: crop CER above 0.8 and a reference of at least 3 characters (and not one of the three cases above); shorter references are classified by their edit operations", + "kk_collapse_to_russian": "a Kazakh letter (Ә Ғ Қ Ң Ө Ұ Ү Һ І) read as its Russian look-alike (А Г К Н О У У Х И), either case", + "kk_overgeneration": "a Russian letter (А Г К Н О У Х И) read as a Kazakh letter that looks like it", + "kk_letter_swapped_for_another_kk_letter": "one Kazakh letter read as another Kazakh letter (for example Ң read as Қ, Ү as Ұ), either case", + "wrong_script_in_output": "a letter replaced by a letter of the other script (Latin instead of Cyrillic or the reverse) where the reference letter is in the row's own script", + "offscript_letter_in_reference": "the REFERENCE letter is in the other script (for example Latin i inside a Cyrillic word) and the output differs: a labelling artefact, not a reading fault", + "case_only": "right letter, wrong case", + "space_words_merged": "a space of the reference is missing (two words merged)", + "space_word_split": "a space is added (one word split)", + "space_substituted": "a space replaced by another character or the reverse", + "space_next_to_punctuation": "a space missing or added directly next to a punctuation mark (a spacing convention, for example 'word .' read as 'word.')", + "punctuation_or_symbol": "a punctuation mark or symbol missed, added or replaced (Unicode categories P* and S*)", + "digit": "a digit missed, added or replaced", + "other_substitution": "any other letter replaced by another letter", + "other_deletion": "any other letter missing", + "other_insertion": "any other letter added", + "mixed": "the crop's errors fall into two or more of the classes", +} + + +def log(*a): + print(time.strftime("%H:%M:%S"), *a, flush=True) + + +def registry(): + reg = json.load(open(REG, encoding="utf-8")) + sets = reg["sets"] if isinstance(reg, dict) else reg + out = {} + for s in sets: + if s.get("locked") or str(s.get("split", "")).lower() != "val": + continue + out[s["name"]] = s + return out + + +def is_punct_or_symbol(c): + cat = unicodedata.category(c) + return cat[0] in ("P", "S") + + +def is_digit(c): + return unicodedata.category(c) == "Nd" + + +def letter_script(c): + """'Latin', 'Cyrillic' or None (not a letter of exactly one of the two scripts).""" + if not unicodedata.category(c).startswith("L"): + return None + s = char_script_set(c) + if not s: + return None + if "Latin" in s and "Cyrillic" not in s: + return "Latin" + if "Cyrillic" in s and "Latin" not in s: + return "Cyrillic" + return None + + +def space_next_to_punct(s, k): + for x in (k - 1, k + 1): + if 0 <= x < len(s) and is_punct_or_symbol(s[x]): + return True + return False + + +def op_class(op, i, j, ref, hyp, row_script): + if op == "S": + rc, hc = ref[i], hyp[j] + rl, hl = rc.lower(), hc.lower() + if rl in KK_SPECIAL_LOWER and KK_PAIRS_LOWER[rl] == hl: + return "kk_collapse_to_russian" + if hl in KK_SPECIAL_LOWER and KK_PAIRS_LOWER[hl] == rl: + return "kk_overgeneration" + if rl in KK_SPECIAL_LOWER and hl in KK_SPECIAL_LOWER and rl != hl: + return "kk_letter_swapped_for_another_kk_letter" + rs, hs = letter_script(rc), letter_script(hc) + if rs and hs and rs != hs: + own = "Cyrillic" if row_script == "Cyrl" else "Latin" + return "offscript_letter_in_reference" if rs != own else "wrong_script_in_output" + if fold_lower(rc) == fold_lower(hc): + return "case_only" + if rc == " " or hc == " ": + if (rc == " " and space_next_to_punct(ref, i)) or (hc == " " and space_next_to_punct(hyp, j)): + return "space_next_to_punctuation" + return "space_substituted" + if is_punct_or_symbol(rc) or is_punct_or_symbol(hc): + return "punctuation_or_symbol" + if is_digit(rc) or is_digit(hc): + return "digit" + return "other_substitution" + if op == "D": + rc = ref[i] + if rc == " ": + return "space_next_to_punctuation" if space_next_to_punct(ref, i) else "space_words_merged" + if is_punct_or_symbol(rc): + return "punctuation_or_symbol" + if is_digit(rc): + return "digit" + return "other_deletion" + hc = hyp[j] + if hc == " ": + return "space_next_to_punctuation" if space_next_to_punct(hyp, j) else "space_word_split" + if is_punct_or_symbol(hc): + return "punctuation_or_symbol" + if is_digit(hc): + return "digit" + return "other_insertion" + + +def classify_crop(ref, hyp, row_script): + """Returns dict: dist, S, D, I, crop_class, char_counts (partition of dist over CHAR_CLASSES), contains (set of coarse + classes and crop-level flags), pairs (Counter of (ref char, out char)).""" + dist, ops = align_ops(ref, hyp) + s = sum(1 for o in ops if o[0] == "S") + d = sum(1 for o in ops if o[0] == "D") + ins = sum(1 for o in ops if o[0] == "I") + res = {"dist": dist, "S": s, "D": d, "I": ins, "ops": ops} + if dist == 0: + res["crop_class"] = None + return res + fine = collections.Counter() + pairs = collections.Counter() + for op, i, j in ops: + if op == "M": + continue + fine[op_class(op, i, j, ref, hyp, row_script)] += 1 + pairs[(ref[i] if i >= 0 else "", hyp[j] if j >= 0 else "")] += 1 + cer = dist / len(ref) + if hyp == "": + cc = "empty_output" + elif ref.startswith(hyp): + cc = "truncation" + elif hyp.startswith(ref): + cc = "extra_text_after_correct_reading" + elif cer > 0.8 and len(ref) >= 3: + # a 1-2 character reference reaches CER 1 with one wrong letter (for example a case error on a one-letter word); such crops are + # classified by their edit operations instead + cc = "unrelated_cer_above_0_8" + else: + cc = None + contains = set(FINE_TO_COARSE[f] for f in fine) + if cc is not None: + charc = {cc: dist} + contains.add(cc) + crop_class = cc + else: + charc = dict(fine) + coarse = set(FINE_TO_COARSE[f] for f in fine) + crop_class = next(iter(coarse)) if len(coarse) == 1 else "mixed" + res.update({"crop_class": crop_class, "char_counts": charc, "fine_counts": dict(fine), "contains": contains, "pairs": pairs, + "cer": cer}) + return res + + +# ------------------------------------------------------------------------------------------------ bootstrap helpers +class Boot: + """Cluster bootstrap over a fixed sorted cluster list (the scorer's S01: multinomial cluster counts, ratio of sums).""" + + def __init__(self, cluster_ids): + self.clusters = sorted(set(cluster_ids)) + self.index = {c: k for k, c in enumerate(self.clusters)} + self.K = len(self.clusters) + W = stats.weights_full(self.K, B, SEED) + if W is None: + W = np.concatenate([w for _, w in stats.weight_chunks(self.K, B, SEED)]) + self.W = np.asarray(W, dtype=np.float64) + + def sums(self, row_clusters, values): + """values: (n_rows, c) -> per-cluster sums (K, c).""" + idx = np.array([self.index[c] for c in row_clusters], dtype=np.int64) + M = np.zeros((self.K, values.shape[1]), dtype=np.float64) + np.add.at(M, idx, values) + return M + + def ratio_ci(self, num_k, den_k): + """num_k: (K, c) per-cluster numerators; den_k: (K,) or (K, c) denominators. Returns lists lo, hi (95% percentile).""" + Wn = self.W @ num_k + dd = den_k if den_k.ndim == 2 else den_k[:, None] + Wd = self.W @ dd + with np.errstate(divide="ignore", invalid="ignore"): + R = Wn / Wd + lo, hi = [], [] + for c in range(R.shape[1]): + r = R[:, c] + r = r[np.isfinite(r)] + if len(r) < 20: + lo.append(None) + hi.append(None) + else: + a, b = np.percentile(r, [2.5, 97.5]) + lo.append(float(a)) + hi.append(float(b)) + return lo, hi + + def diff_ci(self, num_a, den_a, num_b, den_b): + """CER_a - CER_b per resample (same resamples, so paired by cluster). Inputs per-cluster (K,) arrays.""" + W = self.W + with np.errstate(divide="ignore", invalid="ignore"): + ra = (W @ num_a) / (W @ den_a) + rb = (W @ num_b) / (W @ den_b) + d = ra - rb + d = d[np.isfinite(d)] + if len(d) < 20: + return None, None + a, b = np.percentile(d, [2.5, 97.5]) + return float(a), float(b) + + +def rate(num, den, lo=None, hi=None, n_rows=None): + out = {"value": (num / den) if den else None, "num": float(num), "den": float(den)} + if lo is not None: + out["lo"], out["hi"] = lo, hi + if n_rows is not None: + out["n_rows"] = int(n_rows) + if n_rows < MIN_ROWS: + out["fewer_than_30_rows"] = True + return out + + +# ------------------------------------------------------------------------------------------------ loading +def arm_list(): + arms = [(a, "short", a) for a in VLM_ARMS] + [(a, ck, "%s %s" % (a, ck)) for a, ck in LINE_ARMS] + return arms + + +def load_pairs(reg, set_name, arm, ck): + """Rows of the set that the arm predicted: list of dicts (id, ref, hyp, lang, script, kind, group, unit). None if no file.""" + entry = reg.get(set_name) + if entry is None: + return None, "set not in registry as an unlocked validation set" + p = os.path.join(PREDS, arm, ck, set_name + ".tsv") + if not os.path.exists(p): + return None, "no prediction file" + preds, header, ragged, dup = read_preds(p) + man = read_manifest(entry["manifest"]) + rows = [] + missing = 0 + for r in man: + q = preds.get(r["id"]) + if q is None: + missing += 1 + continue + rows.append({"id": r["id"], "ref": norm(r["text"]), "hyp": norm(q["hyp"]), "lang": r["lang"], "script": r["script"], + "kind": r["kind"], "group": r["group"], "unit": r["unit"]}) + info = {"pred_path": p, "pred_sha256": sha256_file(p), "manifest_path": entry["manifest"], "manifest_rows": len(man), + "rows_scored": len(rows), "manifest_rows_without_prediction": missing, "ragged_pred_rows": ragged, "duplicate_pred_ids": dup} + return rows, info + + +def score_file_counts(arm, ck, set_name): + p = os.path.join(SCORES, arm, ck, set_name + ".json") + if not os.path.exists(p): + return None + try: + sc = json.load(open(p, encoding="utf-8")) + g = sc["profiles"]["plain"]["groups"]["all"]["metrics"] + return {"path": p, "dist": g["cer"]["num"], "ref_chars": g["cer"]["den"], "S": g["sub_rate"]["num"], + "D": g["del_rate"]["num"], "I": g["ins_rate"]["num"], "cer": g["cer"]["value"], + "homoglyph_sub": (g.get("homoglyph_sub_rate") or {}).get("num"), + "case_err": (g.get("case_error_rate") or {}).get("num"), + "kk_letters": {k: v for k, v in g.items() if k.startswith(("sl|kk|", "slg|kk|"))}} + except (KeyError, ValueError, TypeError) as e: + return {"path": p, "error": repr(e)} + + +# ------------------------------------------------------------------------------------------------ task 1 (+ data for 3 and 2) +def taxonomy_one(rows, arm_label, set_name, sc_counts, priv): + scored = [r for r in rows if r["ref"] != ""] + boot = Boot([r["group"] for r in scored]) + res = [classify_crop(r["ref"], r["hyp"], r["script"]) for r in scored] + n = len(scored) + ref_chars = sum(len(r["ref"]) for r in scored) + tot = {"dist": sum(x["dist"] for x in res), "S": sum(x["S"] for x in res), "D": sum(x["D"] for x in res), + "I": sum(x["I"] for x in res)} + err_idx = [k for k in range(n) if res[k]["dist"] > 0] + groups = [scored[k]["group"] for k in range(n)] + # character partition + ci = {c: k for k, c in enumerate(CHAR_CLASSES)} + Mc = np.zeros((n, len(CHAR_CLASSES))) + for k in err_idx: + for c, v in res[k]["char_counts"].items(): + Mc[k, ci[c]] += v + dist_rows = np.array([x["dist"] for x in res], dtype=np.float64) + ref_rows = np.array([len(r["ref"]) for r in scored], dtype=np.float64) + Mk = boot.sums(groups, Mc) + distk = boot.sums(groups, dist_rows[:, None])[:, 0] + refk = boot.sums(groups, ref_rows[:, None])[:, 0] + lo, hi = boot.ratio_ci(Mk, distk) + lo2, hi2 = boot.ratio_ci(Mk, refk) + char_share = {} + for c in CHAR_CLASSES: + k = ci[c] + num = float(Mc[:, k].sum()) + char_share[c] = {"error_chars": num, "share_of_error_chars": rate(num, tot["dist"], lo[k], hi[k]), + "per_reference_char": rate(num, ref_chars, lo2[k], hi2[k])} + # coarse char shares (sum of fine) + coarse_share = {} + for cc in CROP_LEVEL + COARSE: + members = [cc] if cc in CROP_LEVEL else [f for f in FINE if FINE_TO_COARSE[f] == cc] + cols = [ci[m] for m in members] + num_k = Mk[:, cols].sum(axis=1, keepdims=True) + l1, h1 = boot.ratio_ci(num_k, distk) + l2, h2 = boot.ratio_ci(num_k, refk) + num = float(Mc[:, cols].sum()) + coarse_share[cc] = {"error_chars": num, "share_of_error_chars": rate(num, tot["dist"], l1[0], h1[0]), + "per_reference_char": rate(num, ref_chars, l2[0], h2[0])} + # crop classes (exclusive) and 'contains' + cri = {c: k for k, c in enumerate(CROP_CLASSES)} + Mx = np.zeros((n, len(CROP_CLASSES))) + contain_names = CROP_LEVEL + COARSE + cti = {c: k for k, c in enumerate(contain_names)} + Mt = np.zeros((n, len(contain_names))) + is_err = np.zeros(n) + for k in err_idx: + Mx[k, cri[res[k]["crop_class"]]] = 1 + for c in res[k]["contains"]: + Mt[k, cti[c]] = 1 + is_err[k] = 1 + errk = boot.sums(groups, is_err[:, None])[:, 0] + Mxk, Mtk = boot.sums(groups, Mx), boot.sums(groups, Mt) + lx, hx = boot.ratio_ci(Mxk, errk) + lt, ht = boot.ratio_ci(Mtk, errk) + n_err = len(err_idx) + crop_excl = {c: rate(float(Mx[:, cri[c]].sum()), n_err, lx[cri[c]], hx[cri[c]]) for c in CROP_CLASSES} + crop_contains = {c: rate(float(Mt[:, cti[c]].sum()), n_err, lt[cti[c]], ht[cti[c]]) for c in contain_names} + # confusion pairs + pairs = collections.Counter() + pair_cls = {} + for k in err_idx: + pairs.update(res[k]["pairs"]) + top_all = [] + for (rc, hc), cnt in pairs.most_common(20): + top_all.append({"reference_char": rc, "output_char": hc, "count": cnt, "share_of_error_chars": cnt / tot["dist"] if tot["dist"] else None, + "op": "substitution" if rc and hc else ("deletion" if rc else "insertion"), + "U+ref": ("U+%04X" % ord(rc)) if rc else "", "U+out": ("U+%04X" % ord(hc)) if hc else ""}) + subs = collections.Counter({p: c for p, c in pairs.items() if p[0] and p[1]}) + top_sub = [{"reference_char": rc, "output_char": hc, "count": cnt, "U+ref": "U+%04X" % ord(rc), "U+out": "U+%04X" % ord(hc)} + for (rc, hc), cnt in subs.most_common(20)] + # Kazakh special letters: per letter (case-sensitive) and merged case + kk = kk_letter_stats(scored, res, boot, groups) + # Kazakh letters produced on rows whose language is not kk (over-generation on Russian sets) + kk_out_on_ru = 0 + ru_ref_chars = 0 + for r, x in zip(scored, res): + if r["lang"] != "kk": + ru_ref_chars += len(r["ref"]) + hm = ["I"] * len(r["hyp"]) + for op, i, j in x["ops"]: + if j >= 0: + hm[j] = op + kk_out_on_ru += sum(1 for j, c in enumerate(r["hyp"]) if c in KK_ALL_SPECIAL and hm[j] != "M") + # reconciliation with the scorer + recon = {"mine": {"error_chars": tot["dist"], "S": tot["S"], "D": tot["D"], "I": tot["I"], "ref_chars": ref_chars}, + "score_file": None, "match": None} + if sc_counts and "error" not in sc_counts: + recon["score_file"] = {k: sc_counts[k] for k in ("path", "dist", "ref_chars", "S", "D", "I", "cer")} + recon["match"] = (abs(sc_counts["dist"] - tot["dist"]) < 1e-9 and abs(sc_counts["ref_chars"] - ref_chars) < 1e-9 and + abs(sc_counts["S"] - tot["S"]) < 1e-9 and abs(sc_counts["D"] - tot["D"]) < 1e-9 and + abs(sc_counts["I"] - tot["I"]) < 1e-9) + hs = sc_counts.get("homoglyph_sub") + mine_h = sum(1 for k in err_idx for (op, i, j) in res[k]["ops"] + if op == "S" and PARTNER.get(scored[k]["ref"][i]) == scored[k]["hyp"][j]) + recon["homoglyph_sub"] = {"mine_table_pairs": mine_h, "score_file": hs, "match": (hs is not None and abs(hs - mine_h) < 1e-9)} + elif sc_counts: + recon["score_file"] = sc_counts + # repaired references (frozen look-alike table): how the shares move + rep = repaired_view(scored) + # private per-crop rows (cluster only) + for k in range(n): + r, x = scored[k], res[k] + priv.append((set_name, arm_label, r["id"], r["group"], len(r["ref"]), x["dist"], x["crop_class"] or "", r["ref"], r["hyp"])) + def sp_punct(t): + return any(t[k] == " " and (is_punct_or_symbol(t[k + 1]) or (k > 0 and is_punct_or_symbol(t[k - 1]))) + for k in range(len(t) - 1)) + spacing = {"references_with_a_space_next_to_punctuation": sum(1 for r in scored if sp_punct(r["ref"])), + "outputs_with_a_space_next_to_punctuation": sum(1 for r in scored if sp_punct(r["hyp"]))} + out = {"rows": n, "ref_chars": ref_chars, "clusters": boot.K, "error_crops": n_err, "error_chars": tot["dist"], + "spacing_convention_counts": spacing, + "cer": rate(tot["dist"], ref_chars), "S": tot["S"], "D": tot["D"], "I": tot["I"], + "char_partition_fine": char_share, "char_partition_coarse": coarse_share, + "crop_primary_class": crop_excl, "crop_contains_class": crop_contains, + "top20_pairs_all_ops": top_all, "top20_substitution_pairs": top_sub, "kazakh_special_letters": kk, + "kazakh_letters_written_in_non_kk_rows": {"count": kk_out_on_ru, "non_kk_reference_chars": ru_ref_chars, + "per_1000_reference_chars": (1000.0 * kk_out_on_ru / ru_ref_chars) if ru_ref_chars else None}, + "reconciliation_with_scorer": recon, "repaired_reference_view": rep} + return out, res, scored + + +def kk_letter_stats(scored, res, boot, groups): + n = len(scored) + letters = LETTERS["kk"] + merged = sorted(set(c.lower() for c in letters), key=lambda c: letters.index(c.upper()) if c.upper() in letters else 0) + keys = [] + for c in letters: + keys += [("case", c)] + for c in merged: + keys += [("both", c)] + kix = {k: q for q, k in enumerate(keys)} + refc = np.zeros((n, len(keys))) + miss = np.zeros((n, len(keys))) + coll = np.zeros((n, len(keys))) + coll_ci = np.zeros((n, len(keys))) + fa = np.zeros((n, len(keys))) + became = {k: collections.Counter() for k in keys} + for q, (r, x) in enumerate(zip(scored, res)): + if r["lang"] != "kk": + continue + ref, hyp = r["ref"], r["hyp"] + rmap = ["D"] * len(ref) + r2h = [-1] * len(ref) + hmap = ["I"] * len(hyp) + for op, i, j in x["ops"]: + if i >= 0: + rmap[i] = op + r2h[i] = j + if j >= 0: + hmap[j] = op + for i, c in enumerate(ref): + if c in KK_ALL_SPECIAL: + for key in (("case", c), ("both", c.lower())): + t = kix[key] + refc[q, t] += 1 + if rmap[i] != "M": + miss[q, t] += 1 + became[key][hyp[r2h[i]] if rmap[i] == "S" else ""] += 1 + p = COLLAPSE["kk"].get(c) + if rmap[i] == "S" and p is not None and hyp[r2h[i]] == p: + coll[q, t] += 1 + if rmap[i] == "S" and hyp[r2h[i]].lower() == KK_PAIRS_LOWER[c.lower()]: + coll_ci[q, t] += 1 + for j, c in enumerate(hyp): + if c in KK_ALL_SPECIAL and hmap[j] != "M": + for key in (("case", c), ("both", c.lower())): + fa[q, kix[key]] += 1 + R = boot.sums(groups, refc) + lo_m, hi_m = boot.ratio_ci(boot.sums(groups, miss), R) + lo_c, hi_c = boot.ratio_ci(boot.sums(groups, coll_ci), R) + lo_f, hi_f = boot.ratio_ci(boot.sums(groups, fa), R) + out = {} + for key, t in kix.items(): + nref = float(refc[:, t].sum()) + name = key[1] if key[0] == "case" else key[1] + " (both cases)" + if nref == 0 and fa[:, t].sum() == 0: + continue + e = {"reference_occurrences": nref, "missed": float(miss[:, t].sum()), "read_as_russian_partner_exact_case": float(coll[:, t].sum()), + "read_as_russian_partner_any_case": float(coll_ci[:, t].sum()), "false_alarms": float(fa[:, t].sum()), + "most_common_misreadings": [{"output_char": h, "count": cnt} for h, cnt in became[key].most_common(5)]} + if nref >= MIN_ROWS: + e["miss_rate"] = {"value": e["missed"] / nref, "lo": lo_m[t], "hi": hi_m[t]} + e["collapse_rate_any_case"] = {"value": e["read_as_russian_partner_any_case"] / nref, "lo": lo_c[t], "hi": hi_c[t]} + e["false_alarm_rate"] = {"value": e["false_alarms"] / nref, "lo": lo_f[t], "hi": hi_f[t]} + else: + e["note"] = "fewer than 30 reference occurrences: counts only" + out[name] = e + return out + + +def repaired_view(scored): + changed = 0 + tot = collections.Counter() + for r in scored: + new, ch = repair_label(r["ref"], r["script"]) + if ch: + changed += 1 + x = classify_crop(new, r["hyp"], r["script"]) + if x["dist"] > 0: + for c, v in x["char_counts"].items(): + tot[c] += v + tot["_dist"] += x["dist"] + tot["_ref"] += len(new) + d = tot.pop("_dist") + rf = tot.pop("_ref") + return {"references_changed_by_lookalike_repair": changed, "error_chars": d, "cer": d / rf if rf else None, + "char_partition_fine_share": {c: (tot[c] / d if d else None) for c in CHAR_CLASSES}, + "note": "references repaired with the frozen look-alike table (r5eval.lookalike.repair_label); outputs unchanged; no interval"} + + +# ------------------------------------------------------------------------------------------------ task 3 +def overlap(err_sets, all_ids, arms): + out = {"arms": arms, "n_crops": len(all_ids), "pairs": []} + for a_i in range(len(arms)): + for b_i in range(a_i + 1, len(arms)): + a, b = arms[a_i], arms[b_i] + A, Bs = err_sets[a], err_sets[b] + u = len(A | Bs) + out["pairs"].append({"a": a, "b": b, "errors_a": len(A), "errors_b": len(Bs), "both": len(A & Bs), "union": u, + "jaccard": (len(A & Bs) / u) if u else None}) + cnt = collections.Counter() + for i in all_ids: + cnt[sum(1 for a in arms if i in err_sets[a])] += 1 + out["crops_by_number_of_arms_wrong"] = {str(k): cnt[k] for k in sorted(cnt)} + allw = set(all_ids) + for a in arms: + allw &= err_sets[a] + out["wrong_for_every_arm"] = {"count": len(allw), "share_of_crops": len(allw) / len(all_ids) if all_ids else None} + nonew = set(all_ids) + for a in arms: + nonew -= err_sets[a] + out["right_for_every_arm"] = {"count": len(nonew), "share_of_crops": len(nonew) / len(all_ids) if all_ids else None} + return out, allw + + +# ------------------------------------------------------------------------------------------------ task 4 +def attr_rows(rows, side): + """Attach side-file attributes and the length bucket.""" + for r in rows: + m = side.get(r["id"]) if side else None + r["len_bucket"] = length_bucket(len(r["ref"])) if r["ref"] else None + r["m"] = m or {} + return rows + + +def cell_table(rows, dist, refl, boot, cells, min_rows=MIN_ROWS, with_contrast=False): + """cells: list of (name, mask). CER with CI per cell; with_contrast: CER with vs without and the paired difference.""" + groups = [r["group"] for r in rows] + distk_rows = np.asarray(dist, dtype=np.float64) + refl_rows = np.asarray(refl, dtype=np.float64) + out = {} + if not cells: + return out + masks = np.array([m for _, m in cells], dtype=np.float64).T # (n, c) + num = boot.sums(groups, masks * distk_rows[:, None]) + den = boot.sums(groups, masks * refl_rows[:, None]) + lo, hi = boot.ratio_ci(num, den) + tot_num = boot.sums(groups, distk_rows[:, None])[:, 0] + tot_den = boot.sums(groups, refl_rows[:, None])[:, 0] + for c, (name, m) in enumerate(cells): + nr = int(np.asarray(m).sum()) + e = rate(float(num[:, c].sum()), float(den[:, c].sum()), lo[c], hi[c], n_rows=nr) + if with_contrast: + if nr == len(rows): + e["contrast"] = "no contrast possible: present in every row" + elif nr == 0: + e["contrast"] = "absent from every row" + else: + wn, wd = tot_num - num[:, c], tot_den - den[:, c] + e["cer_without"] = rate(float(wn.sum()), float(wd.sum()), n_rows=len(rows) - nr) + dl, dh = boot.diff_ci(num[:, c], den[:, c], wn, wd) + if e["value"] is not None and e["cer_without"]["value"] is not None: + e["difference_with_minus_without"] = {"value": e["value"] - e["cer_without"]["value"], "lo": dl, "hi": dh, + "note": "descriptive: effects co-occur on a page, so this is not the effect's own cause"} + out[name] = e + return out + + +def attributes_one(rows, set_name): + text_rows = [r for r in rows if r["ref"] != ""] + out = {} + if set_name == "synth_clutter_val": + boot = Boot([r["group"] for r in rows]) + groups = [r["group"] for r in rows] + nonempty = np.array([1.0 if r["hyp"] != "" else 0.0 for r in rows]) + olen = np.array([float(len(r["hyp"])) for r in rows]) + ones = np.ones(len(rows)) + res = {} + cols = [("all", ones)] + for col in ("crop_mode", "page_type", "paper_kind", "geo_mode", "strength"): + vals = sorted(set(r["m"].get(col, "") for r in rows)) + for v in vals: + cols.append(("%s=%s" % (col, v), np.array([1.0 if r["m"].get(col, "") == v else 0.0 for r in rows]))) + toks = collections.Counter() + for r in rows: + for t in (r["m"].get("effects_all") or "").split("|"): + if t: + toks[t] += 1 + for t in sorted(toks): + cols.append(("effect=%s" % t, np.array([1.0 if t in (r["m"].get("effects_all") or "").split("|") else 0.0 for r in rows]))) + M = np.array([m for _, m in cols]).T + num = boot.sums(groups, M * nonempty[:, None]) + den = boot.sums(groups, M) + lo, hi = boot.ratio_ci(num, den) + for c, (name, m) in enumerate(cols): + nr = int(m.sum()) + e = rate(float(num[:, c].sum()), float(den[:, c].sum()), lo[c], hi[c], n_rows=nr) + e["mean_output_chars_when_nonempty"] = (float((olen * m * nonempty).sum()) / float((m * nonempty).sum())) if (m * nonempty).sum() else None + if nr == len(rows) and name != "all": + e["contrast"] = "no contrast possible: present in every row" + res[name] = e + out["HR1_text_on_empty_images"] = res + return out + if not text_rows: + return out + dist = [lev_fast(r["ref"], r["hyp"]) for r in text_rows] + refl = [len(r["ref"]) for r in text_rows] + bt = Boot([r["group"] for r in text_rows]) + n = len(text_rows) + + def mask(f): + return [1.0 if f(r) else 0.0 for r in text_rows] + out["all"] = cell_table(text_rows, dist, refl, bt, [("all", [1.0] * n)])["all"] + langs = sorted(set(r["lang"] for r in text_rows)) + out["by_language_script"] = cell_table(text_rows, dist, refl, bt, [(l, mask(lambda r, l=l: r["lang"] == l)) for l in langs]) + vals = [v for v in out["by_language_script"].values() if v["value"] is not None] + out["macro_over_language_scripts"] = (sum(v["value"] for v in vals) / len(vals)) if vals else None + out["by_length_bucket"] = cell_table(text_rows, dist, refl, bt, [(name, mask(lambda r, name=name: r["len_bucket"] == name)) for _, _, name in LEN_EDGES]) + if set_name in ("synth_hand_val", "synth_typed_val"): + fg = sorted(set(r["m"].get("font_group", "") for r in text_rows)) + cells = [("font_group=%s" % v, mask(lambda r, v=v: r["m"].get("font_group", "") == v)) for v in fg] + for sc in ("Cyrl", "Latn"): + for v in fg: + cells.append(("font_group=%s|%s" % (v, sc), mask(lambda r, v=v, sc=sc: r["m"].get("font_group", "") == v and r["script"] == sc))) + out["by_font_group"] = cell_table(text_rows, dist, refl, bt, cells) + if len(fg) == 2 and "seen" in fg and "unseen" in fg: + groups = [r["group"] for r in text_rows] + d_ = np.asarray(dist, dtype=np.float64) + l_ = np.asarray(refl, dtype=np.float64) + mu = np.asarray(mask(lambda r: r["m"].get("font_group") == "unseen")) + ms = 1.0 - mu + nu, du = bt.sums(groups, (mu * d_)[:, None])[:, 0], bt.sums(groups, (mu * l_)[:, None])[:, 0] + ns, ds = bt.sums(groups, (ms * d_)[:, None])[:, 0], bt.sums(groups, (ms * l_)[:, None])[:, 0] + lo, hi = bt.diff_ci(nu, du, ns, ds) + out["unseen_minus_seen_font"] = {"value": nu.sum() / du.sum() - ns.sum() / ds.sum(), "lo": lo, "hi": hi} + fonts = collections.Counter(r["m"].get("font_id", "") for r in text_rows) + out["by_font_id"] = cell_table(text_rows, dist, refl, bt, [("%s (%s)" % (f, next((r["m"].get("font_group", "") for r in text_rows if r["m"].get("font_id", "") == f), "")), + mask(lambda r, f=f: r["m"].get("font_id", "") == f)) for f in sorted(fonts)]) + for col in ("paper_kind", "geo_mode", "page_type", "strength", "ink", "region_class", "crop_mode", "overlaps", "mixed"): + vals = sorted(set(r["m"].get(col, "") for r in text_rows)) + out["by_" + col] = cell_table(text_rows, dist, refl, bt, [("%s=%s" % (col, v if v else "(none)"), mask(lambda r, v=v, col=col: r["m"].get(col, "") == v)) for v in vals]) + toks = collections.Counter() + for r in text_rows: + for t in (r["m"].get("effects_all") or "").split("|"): + if t: + toks[t] += 1 + cells = [(t, mask(lambda r, t=t: t in (r["m"].get("effects_all") or "").split("|"))) for t in sorted(toks)] + out["by_effect_with_vs_without"] = cell_table(text_rows, dist, refl, bt, cells, with_contrast=True) + same = collections.defaultdict(list) + for t, m in cells: + same[tuple(k for k, x in enumerate(m) if x)].append(t) + out["effect_tokens_always_together"] = [{"tokens": v, "n_rows": len(k), "note": "these tokens occur on exactly the same rows: their " + "contrasts are identical and cannot be told apart"} for k, v in same.items() if len(v) > 1] + n_all = len(text_rows) + keyset = {k: v for k, v in same.items()} + comp = [] + for k, v in keyset.items(): + ks = set(k) + ck = tuple(i for i in range(n_all) if i not in ks) + if ck in keyset and k < ck: + comp.append({"tokens_present": v, "rows_present": len(k), "complement_tokens": keyset[ck], "rows_complement": len(ck), + "note": "the second group is present exactly where the first is absent: its 'with vs without' contrast is the first " + "group's contrast reversed"}) + out["effect_tokens_exact_complements"] = comp + out["effect_contrasts_within_strata"] = stratified_contrasts(text_rows, dist, refl, bt) + out["by_effect_with_vs_without:note"] = ("tokens of the side-file column effects_all (every effect the generator applied, a superset of the " + "column 'effects'); CER of rows with the token, of rows without it, and the difference with a " + "paired page-bootstrap interval") + return out + + +STRAT_TOKENS = ["overlaps=stamp", "stamp", "stains", "creases", "staple", "binder_holes", "pattern:dots", "pattern:faint_table", "pattern:guilloche", + "pattern:stripes", "pattern:tint", "pattern:watermark", "mark:arrow", "mark:brace", "mark:circle", "mark:cross", "mark:highlight", + "mark:scribble", "mark:strike", "mark:tick", "mark:underline", "paper:ruled", "object:map", "blur:>=1.0", "noise:>=5", "fx:ink_dropout"] + + +def _has_token(r, t): + if t.startswith("overlaps="): + return r["m"].get("overlaps", "") == t.split("=", 1)[1] + return t in (r["m"].get("effects_all") or "").split("|") + + +def stratified_contrasts(rows, dist, refl, bt): + """CER with minus without a token, computed inside strata of capture mode x degradation strength (geo_mode x strength, the two + page-level settings that bundle most other effects) and averaged with weights = rows with the token in each stratum. The interval + comes from the same page bootstrap (resampled per-stratum ratios, fixed weights). Descriptive: other co-occurring effects remain.""" + groups = [r["group"] for r in rows] + d = np.asarray(dist, dtype=np.float64) + l = np.asarray(refl, dtype=np.float64) + skey = [(r["m"].get("geo_mode", ""), r["m"].get("strength", "")) for r in rows] + svals = sorted(set(skey)) + out = {"strata": "geo_mode x strength (%d cells)" % len(svals), "weighting": "rows with the token per stratum", + "note": "descriptive: removes the capture-mode and strength bundles only; tokens that define a stratum cannot be contrasted", "tokens": {}} + for t in STRAT_TOKENS: + has = np.array([1.0 if _has_token(r, t) else 0.0 for r in rows]) + if has.sum() == 0: + continue + cols, wts = [], [] + for v in svals: + s = np.array([1.0 if k == v else 0.0 for k in skey]) + nw, nwo = float((s * has).sum()), float((s * (1 - has)).sum()) + if nw == 0 or nwo == 0: + continue + cols += [s * has * d, s * has * l, s * (1 - has) * d, s * (1 - has) * l] + wts.append(nw) + raw_w = (has * d).sum() / (has * l).sum() if (has * l).sum() else None + raw_wo = ((1 - has) * d).sum() / ((1 - has) * l).sum() if ((1 - has) * l).sum() else None + e = {"n_rows_with": int(has.sum()), "raw_difference": (raw_w - raw_wo) if (raw_w is not None and raw_wo is not None) else None} + if not wts: + e["stratified_difference"] = "not evaluable: no stratum has rows both with and without the token" + out["tokens"][t] = e + continue + M = np.array(cols).T + Mk = bt.sums(groups, M) + w = np.array(wts) / sum(wts) + S = len(wts) + pt = 0.0 + for i in range(S): + pt += w[i] * (Mk[:, 4 * i].sum() / Mk[:, 4 * i + 1].sum() - Mk[:, 4 * i + 2].sum() / Mk[:, 4 * i + 3].sum()) + R = bt.W @ Mk + with np.errstate(divide="ignore", invalid="ignore"): + reps = sum(w[i] * (R[:, 4 * i] / R[:, 4 * i + 1] - R[:, 4 * i + 2] / R[:, 4 * i + 3]) for i in range(S)) + reps = reps[np.isfinite(reps)] + e["stratified_difference"] = {"value": float(pt), "lo": float(np.percentile(reps, 2.5)) if len(reps) >= 20 else None, + "hi": float(np.percentile(reps, 97.5)) if len(reps) >= 20 else None, "strata_used": S, + "valid_replicates": int(len(reps))} + if has.sum() < MIN_ROWS: + e["fewer_than_30_rows"] = True + out["tokens"][t] = e + return out + + +# ------------------------------------------------------------------------------------------------ task 6 +def curves(reg): + entry = reg.get("curve_v1") + man = read_manifest(entry["manifest"]) + mrows = {r["id"]: r for r in man} + out = {} + for arm in CURVE_ARMS: + ad = os.path.join(PREDS, arm) + if not os.path.isdir(ad): + continue + pts = [] + for ck in sorted(os.listdir(ad)): + if not ck.startswith("curve_"): + continue + p = os.path.join(ad, ck, "curve_v1.tsv") + if not os.path.exists(p): + continue + meta = {} + mp = os.path.join(ad, ck, "meta.json") + if os.path.exists(mp): + try: + meta = json.load(open(mp, encoding="utf-8")) + except ValueError: + meta = {} + preds, _, _, _ = read_preds(p) + per = {} + for r in man: + q = preds.get(r["id"]) + if q is None: + continue + ref, hyp = norm(r["text"]), norm(q["hyp"]) + per[r["id"]] = (ref, hyp) + ss = meta.get("samples_seen") + try: + ss = int(ss) + except (TypeError, ValueError): + ss = None + if ss is None: + digits = "".join(ch for ch in ck.split("_")[1] if ch.isdigit()) + ss = int(digits) if digits else None + pts.append({"checkpoint": ck, "samples_seen": ss, "per": per, "pred_path": p, "pred_sha256": sha256_file(p), + "killed_or_crashed": ("killed" in ck or "crash" in ck)}) + if not pts: + continue + kr_ids = [i for i, r in mrows.items() if r["kind"] == "hand_real"] + bt = Boot([mrows[i]["group"] for i in kr_ids]) + res_pts = [] + cl = {} + for pt in sorted(pts, key=lambda x: (x["samples_seen"] or 0, x["checkpoint"])): + per = pt["per"] + ids = [i for i in kr_ids if i in per] + d = np.array([lev_fast(per[i][0], per[i][1]) for i in ids], dtype=np.float64) + l = np.array([len(per[i][0]) for i in ids], dtype=np.float64) + g = [mrows[i]["group"] for i in ids] + nk, dk = bt.sums(g, d[:, None])[:, 0], bt.sums(g, l[:, None])[:, 0] + lo, hi = bt.ratio_ci(nk[:, None], dk) + kinds = {} + for kind in ("hand_synth", "typed_synth", "typed_real"): + kid = [i for i, r in mrows.items() if r["kind"] == kind and i in per and per[i][0]] + dd = sum(lev_fast(per[i][0], per[i][1]) for i in kid) + ll = sum(len(per[i][0]) for i in kid) + kinds[kind] = {"cer": dd / ll if ll else None, "rows": len(kid)} + clut = [i for i, r in mrows.items() if r["kind"] == "clutter" and i in per] + kinds["clutter_HR1"] = {"value": (sum(1 for i in clut if per[i][1] != "") / len(clut)) if clut else None, "rows": len(clut)} + res_pts.append({"checkpoint": pt["checkpoint"], "samples_seen": pt["samples_seen"], + "fraction_of_P_short": (pt["samples_seen"] / P_SHORT) if pt["samples_seen"] else None, + "killed_or_crashed_run": pt["killed_or_crashed"], "kohtd_part_rows": len(ids), + "cer_kohtd_part": {"value": float(nk.sum() / dk.sum()) if dk.sum() else None, "lo": lo[0], "hi": hi[0], + "num": float(nk.sum()), "den": float(dk.sum())}, + "other_parts": kinds, "pred_path": pt["pred_path"], "pred_sha256": pt["pred_sha256"]}) + cl[pt["checkpoint"]] = (nk, dk) + # flag per r5_descriptive_labels.txt: 75% vs 100% points of P_short + valid = [p for p in res_pts if not p["killed_or_crashed_run"] and p["samples_seen"]] + p75 = [p for p in valid if abs(p["samples_seen"] - 0.75 * P_SHORT) <= 0.1 * P_SHORT] + p100 = [p for p in valid if abs(p["samples_seen"] - P_SHORT) <= 0.1 * P_SHORT] + flag, fig = None, None + if p75 and p100: + a, b = p75[0], p100[0] + va, vb = a["cer_kohtd_part"]["value"], b["cer_kohtd_part"]["value"] + fell = (va - vb) / va if va else None + flag = "still improving" if (fell is not None and fell > 0.10) else "plateaued" + na, da = cl[a["checkpoint"]] + nb, db = cl[b["checkpoint"]] + W = bt.W + with np.errstate(divide="ignore", invalid="ignore"): + ra, rb = (W @ na) / (W @ da), (W @ nb) / (W @ db) + rel = (ra - rb) / ra + rel = rel[np.isfinite(rel)] + fig = {"cer_75": va, "cer_100": vb, "relative_drop": fell, "relative_drop_ci95_paired_form_bootstrap": + [float(np.percentile(rel, 2.5)), float(np.percentile(rel, 97.5))] if len(rel) >= 20 else None, + "share_of_resamples_with_drop_above_10pct": float(np.mean(rel > 0.10)) if len(rel) else None, + "checkpoints": [a["checkpoint"], b["checkpoint"]]} + flag_note = None + if flag is None: + last = max((p["samples_seen"] for p in valid), default=None) + flag_note = ("not evaluable: the rule needs points within 10%% of 75%% and of 100%% of P_short; the last usable checkpoint is at %s samples " + "(%s of P_short)%s" % (last, ("%.0f%%" % (100.0 * last / P_SHORT)) if last else "n/a", + "; checkpoints of killed or crashed runs are not used" if any(p["killed_or_crashed_run"] for p in res_pts) else "")) + status = "complete" if (p75 and p100 and len(valid) >= 4) else "incomplete" + if any(p["killed_or_crashed_run"] for p in res_pts): + status += " (some checkpoints come from a killed or crashed run and are not used for the flag)" + out[arm] = {"points": res_pts, "flag_rule_r5_descriptive_labels": flag, "flag_figures": fig, "curve_status": status} + if flag_note: + out[arm]["flag_note"] = flag_note + return out + + +# ------------------------------------------------------------------------------------------------ main +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", required=True) + ap.add_argument("--tasks", default="1,3,4,6") + ap.add_argument("--limit-arms", default="") + ap.add_argument("--extra-vlm-arms", default="", help="VLM arms that finished after the task-2 sample was drawn (checkpoint 'short')") + args = ap.parse_args() + tasks = set(args.tasks.split(",")) + os.makedirs(os.path.join(args.out, "private"), exist_ok=True) + reg = registry() + arms = arm_list() + extra_labels = [a for a in args.extra_vlm_arms.split(",") if a] + arms = arms[:len(VLM_ARMS)] + [(a, "short", a) for a in extra_labels] + arms[len(VLM_ARMS):] + if args.limit_arms: + keep = set(args.limit_arms.split(",")) + arms = [a for a in arms if a[2] in keep] + meta = {"generated_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "script": os.path.abspath(__file__), + "script_sha256": sha256_file(os.path.abspath(__file__)), "bootstrap": {"B": B, "seed": SEED, "level": "95% percentile", + "clusters": "manifest column 'group' (KOHTD forms, HKR form instances, school pages, CHD groups, synthetic source pages, real-print documents)"}, + "normalisation": "N0 (r5eval.textnorm.norm) on manifest text and TSV hyp; alignment r5eval.align.align_ops", "validation_only": True} + if "1" in tasks or "3" in tasks: + tax = {"meta": dict(meta), "class_definitions": PLAIN_NAMES, + "partition_rule": ("Character shares are a partition of all error characters (edit operations) of the set: a crop whose output is empty, " + "a proper prefix of the reference, has the reference as a proper prefix, or has CER above 0.8 with a reference of 3+ characters puts all its error characters " + "into that crop-level class (checked in this order); every other crop's operations are classified one by one in the order " + "Kazakh letter vs Russian partner (either direction), Kazakh letter vs another Kazakh letter, other script, case, space " + "(next to punctuation, else merged/split/substituted), punctuation or symbol, digit, other. Crop shares: 'primary' gives each erroneous " + "crop one class (crop-level class, else its single coarse class, else 'mixed'); 'contains' counts crops with at least one " + "operation of the class (overlapping)."), + "sets": {}, "arms": [a[2] for a in arms]} + priv = [] + err_sets = collections.defaultdict(dict) + crop_info = collections.defaultdict(dict) + ids_by_set = {} + for s in TAX_SETS: + tax["sets"][s] = {} + for arm, ck, label in arms: + rows, info = load_pairs(reg, s, arm, ck) + if rows is None: + tax["sets"][s][label] = {"status": info} + continue + sc = score_file_counts(arm, ck, s) + log("taxonomy", s, label, len(rows)) + o, res, scored = taxonomy_one(rows, label, s, sc, priv) + o["inputs"] = info + tax["sets"][s][label] = o + err_sets[s][label] = set(r["id"] for r, x in zip(scored, res) if x["dist"] > 0) + crop_info[s][label] = {r["id"]: (x["dist"], x["crop_class"]) for r, x in zip(scored, res) if x["dist"] > 0} + ids_by_set.setdefault(s, set(r["id"] for r in scored)) + write_json_atomic(os.path.join(args.out, "error_taxonomy.json"), tax) + with open(os.path.join(args.out, "private", "per_crop_errors.tsv"), "w", encoding="utf-8") as f: + f.write("set\tarm\tid\tgroup\tref_len\tdist\tcrop_class\tref\thyp\n") + for t in priv: + f.write("\t".join(str(x).replace("\t", " ") for x in t) + "\n") + ov = {"meta": dict(meta), "sets": {}} + for s in TAX_SETS: + labels = [a[2] for a in arms if a[2] in err_sets[s]] + if not labels: + continue + full, allw = overlap(err_sets[s], sorted(ids_by_set[s]), labels) + base = [l for l in labels if l not in extra_labels] + if extra_labels: + # the 15-arm list fixed when the task-2 sample was drawn stays the definition of "every arm" for task 2 + base_ov, allw = overlap(err_sets[s], sorted(ids_by_set[s]), base) + full["task1_base_15_arms"] = {k: v for k, v in base_ov.items() if k != "pairs"} + full["late_arms_added"] = extra_labels + vlm = [l for l in labels if " " not in l] + vlm_ov, vlm_allw = overlap(err_sets[s], sorted(ids_by_set[s]), vlm) + four = [l for l in ("hunyuanocr", "minicpm_ocr_1_0", "paddleocr_vl_1_6", "A1 long_lm_gated") if l in labels] + four_ov, four_allw = overlap(err_sets[s], sorted(ids_by_set[s]), four) + ov["sets"][s] = {"all_arms": full, "vlm_arms_only": {k: v for k, v in vlm_ov.items() if k != "pairs"}, + "four_sampled_arms": {k: v for k, v in four_ov.items() if k != "pairs"}} + mass = {} + for l in labels: + ci = crop_info[s][l] + tot = sum(dd for dd, _ in ci.values()) + unr = sum(dd for dd, c in ci.values() if c == "unrelated_cer_above_0_8") + tot_in = sum(dd for i, (dd, _) in ci.items() if i in allw) + unr_in = sum(dd for i, (dd, c) in ci.items() if i in allw and c == "unrelated_cer_above_0_8") + mass[l] = {"error_chars": tot, "error_chars_in_every_arm_wrong_crops": tot_in, + "share_of_error_chars_in_every_arm_wrong_crops": (tot_in / tot) if tot else None, + "unrelated_error_chars": unr, "unrelated_error_chars_in_every_arm_wrong_crops": unr_in, + "share_of_unrelated_in_every_arm_wrong_crops": (unr_in / unr) if unr else None} + ov["sets"][s]["error_mass_in_every_arm_wrong_crops"] = {"every_arm_definition": "the 15 arms of the task-1 list fixed when the task-2 sample was drawn", + "n_crops": len(allw), "arms": mass} + with open(os.path.join(args.out, "private", "wrong_for_every_arm_%s.txt" % s), "w", encoding="utf-8") as f: + for i in sorted(allw): + f.write(i + "\n") + with open(os.path.join(args.out, "private", "error_sets_%s.json" % s), "w", encoding="utf-8") as f: + json.dump({k: sorted(v) for k, v in err_sets[s].items()}, f) + write_json_atomic(os.path.join(args.out, "overlap.json"), ov) + if "4" in tasks: + att = {"meta": dict(meta), "sets": {}, "note_common_rows": ("The line arms with LM-gated decoding were scored on 4,000-row subsets of " + "synth_hand_val, synth_typed_val and print_real_val. 'all_rows' uses every row an arm has; 'common_rows' uses only the ids every " + "listed arm has, which is the figure to compare across arms.")} + side_dir = D + "/data/processed/r5/frozen_eval_v1" + for s in ATTR_SETS: + side_p = os.path.join(side_dir, s + ".meta.tsv") + side = read_meta_tsv(side_p) if os.path.exists(side_p) else {} + loaded = {} + for arm, ck, label in arms: + rows, info = load_pairs(reg, s, arm, ck) + if rows is None: + continue + loaded[label] = (rows, info) + if not loaded: + continue + common = None + for label, (rows, info) in loaded.items(): + ids = set(r["id"] for r in rows) + common = ids if common is None else (common & ids) + att["sets"][s] = {"side_file": side_p if side else None, "side_file_sha256": sha256_file(side_p) if side else None, + "common_row_count": len(common), "arms": {}} + for label, (rows, info) in loaded.items(): + log("attributes", s, label, len(rows)) + attr_rows(rows, side) + e = {"inputs": info} + e["all_rows"] = attributes_one(rows, s) + if len(common) < len(rows): + crow = [r for r in rows if r["id"] in common] + e["common_rows"] = attributes_one(crow, s) + else: + e["common_rows"] = "identical to all_rows" + att["sets"][s]["arms"][label] = e + write_json_atomic(os.path.join(args.out, "attributes.json"), att) + if "6" in tasks: + cv = {"meta": dict(meta), "rule": "records/R5/RULE/r5_descriptive_labels.txt (sha256 0eaf7801...): 'still improving' when V1-curve CER fell by " + "more than 10% (relative) between the 75% and the 100% points of P_short, 'plateaued' otherwise. V1-curve CER is read, as in the " + "report cards, as the CER on the KOHTD part of curve_v1 (500 V1lm crops, hand_real rows).", "arms": curves(reg)} + write_json_atomic(os.path.join(args.out, "curves.json"), cv) + log("done") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/r5_erran/erran_inventory.py b/scripts/r5_erran/erran_inventory.py new file mode 100644 index 0000000000000000000000000000000000000000..7157837cd4b8da0a1ff4ef883347baa028750bb6 --- /dev/null +++ b/scripts/r5_erran/erran_inventory.py @@ -0,0 +1,104 @@ +"""ERRAN (R5) inventory: which prediction files exist, row counts, registry entries of the validation sets used, and the +distinct values of the generator side-file columns. Validation sets only; locked (test) entries are listed by name only and never opened.""" +import collections +import json +import os +import sys + +D = "/path/to/TURKIC_OCR_DATA" +PREDS = D + "/outputs/r5/preds" +REG = D + "/data/processed/r5/evalsets.json" +SETS = ["V1", "hkr_val_s2000", "chd_val_s2000", "school_val_s2000", "synth_hand_val", "synth_typed_val", "print_real_val", + "synth_clutter_val", "curve_v1"] + + +def nrows(p): + with open(p, encoding="utf-8") as f: + return sum(1 for _ in f) - 1 + + +def main(): + reg = json.load(open(REG, encoding="utf-8")) + sets = reg["sets"] if isinstance(reg, dict) else reg + print("REGISTRY entries (validation ones in full, locked ones name only):") + for s in sets: + locked = bool(s.get("locked")) or str(s.get("split", "")).lower() == "test" + if locked: + print(" LOCKED", s.get("name")) + else: + print(" ", json.dumps({k: s.get(k) for k in ("name", "manifest", "split", "purpose")}, ensure_ascii=False)[:400]) + print("\nPRED FILES (arm/ckpt/set rows):") + for arm in sorted(os.listdir(PREDS)): + for ck in sorted(os.listdir(os.path.join(PREDS, arm))): + dd = os.path.join(PREDS, arm, ck) + if not os.path.isdir(dd): + continue + row = [] + for s in SETS: + p = os.path.join(dd, s + ".tsv") + if os.path.exists(p): + row.append("%s=%d" % (s, nrows(p))) + hdr = "" + p = os.path.join(dd, "V1.tsv") + if os.path.exists(p): + hdr = open(p, encoding="utf-8").readline().strip().replace("\t", ",") + print(" %s/%s: %s [V1 header: %s]" % (arm, ck, " ".join(row), hdr)) + side_dir = D + "/data/processed/r5/frozen_eval_v1" + for nm in ("synth_hand_val", "synth_typed_val", "synth_clutter_val"): + p = os.path.join(side_dir, nm + ".meta.tsv") + with open(p, encoding="utf-8") as f: + hdr = f.readline().rstrip("\n").split("\t") + cnt = {c: collections.Counter() for c in hdr} + eff = collections.Counter() + effa = collections.Counter() + n = 0 + for line in f: + parts = line.rstrip("\n").split("\t") + if len(parts) != len(hdr): + continue + n += 1 + r = dict(zip(hdr, parts)) + for c in ("lang", "script", "kind", "page_type", "strength", "geo_mode", "paper_kind", "region_class", "font_id", + "font_group", "heldout_font", "ink", "crop_mode", "licence_class", "font_licence_class", "mixed", "overlaps", + "source_doc_confidence", "unit"): + if c in r: + cnt[c][r[c]] += 1 + for t in r.get("effects", "").split("|"): + if t: + eff[t] += 1 + for t in r.get("effects_all", "").split("|"): + if t: + effa[t] += 1 + groups = cnt.setdefault("_groups", collections.Counter()) + groups[r.get("group", "")] += 1 + print("\nSIDECAR", nm, "rows", n, "distinct groups", len(cnt["_groups"])) + for c, k in cnt.items(): + if c == "_groups" or not k: + continue + print(" ", c, dict(k.most_common(30))) + print(" effects:", dict(eff.most_common(60))) + print(" effects_all:", dict(effa.most_common(120))) + for nm in ("kohtd_screen_v1", "hkr_val_s2000", "chd_val_s2000", "school_val_s2000", "print_real_val", "curve_v1"): + p = D + "/data/processed/r5/manifests/" + nm + ".tsv" + if not os.path.exists(p): + print("missing", p) + continue + with open(p, encoding="utf-8") as f: + hdr = f.readline().rstrip("\n").split("\t") + c = collections.Counter() + g = set() + k = collections.Counter() + u = collections.Counter() + n = 0 + for line in f: + r = dict(zip(hdr, line.rstrip("\n").split("\t"))) + n += 1 + c[r.get("lang")] += 1 + g.add(r.get("group")) + k[r.get("kind")] += 1 + u[r.get("unit")] += 1 + print("\nMANIFEST", nm, "rows", n, "groups", len(g), "lang", dict(c), "kind", dict(k), "unit", dict(u), "cols", hdr) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/r5_erran/erran_sample.py b/scripts/r5_erran/erran_sample.py new file mode 100644 index 0000000000000000000000000000000000000000..62b14409ba175076eae54c617647e6ceb2b8bdeb --- /dev/null +++ b/scripts/r5_erran/erran_sample.py @@ -0,0 +1,113 @@ +"""ERRAN (R5) task 2: draw the V1 error crops to view, and build contact sheets for viewing. + +Design (fixed before viewing, ERRAN plan task 2): + - one random order of all V1 crop ids: numpy default_rng(20261122).permutation(sorted ids); + - for each of the four arms (hunyuanocr, minicpm_ocr_1_0, paddleocr_vl_1_6, A1 long_lm_gated) the first 120 of ITS error crops + in that order: a uniform random sample of that arm's error crops (the shared order only makes the samples overlap); + - a separate stratum: the crops every arm of the task-1 list gets wrong (all of them if at most 80, else the first 80 in the order). +Contact sheets show the crop images with a running number only (no text drawn); the references and outputs go to a separate index +file. Everything is written under OUT/private/ on the cluster (real students' handwriting: never copied into page files). +""" +import argparse +import json +import os +import sys + +import numpy as np +from PIL import Image, ImageDraw, ImageFont + +sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src") +from r5eval.ioutil import read_manifest # noqa: E402 + +SEED = 20261122 +N_PER_ARM = 120 +N_ALLWRONG = 80 +ARMS = ["hunyuanocr", "minicpm_ocr_1_0", "paddleocr_vl_1_6", "A1 long_lm_gated"] +V1_MANIFEST = "/path/to/TURKIC_OCR_DATA/data/processed/r5/manifests/kohtd_screen_v1.tsv" +H = 120 +MAXW = 1000 +PER_SHEET = 8 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", required=True) + args = ap.parse_args() + priv = os.path.join(args.out, "private") + err = json.load(open(os.path.join(priv, "error_sets_V1.json"), encoding="utf-8")) + allwrong = [l.strip() for l in open(os.path.join(priv, "wrong_for_every_arm_V1.txt"), encoding="utf-8") if l.strip()] + man = read_manifest(V1_MANIFEST) + mrow = {r["id"]: r for r in man} + ids = sorted(mrow) + order = np.random.default_rng(SEED).permutation(len(ids)) + rank = {ids[k]: int(pos) for pos, k in enumerate(order)} + samples = {} + for a in ARMS: + e = sorted(err[a], key=lambda i: rank[i]) + samples[a] = e[:N_PER_ARM] + aw = sorted(allwrong, key=lambda i: rank[i]) + stratum = aw if len(aw) <= N_ALLWRONG else aw[:N_ALLWRONG] + union = sorted(set(stratum).union(*[set(v) for v in samples.values()]), key=lambda i: rank[i]) + # outputs of every arm for the index file + hyp = {} + ref = {} + nwrong = {} + with open(os.path.join(priv, "per_crop_errors.tsv"), encoding="utf-8") as f: + hdr = f.readline().rstrip("\n").split("\t") + for line in f: + p = dict(zip(hdr, line.rstrip("\n").split("\t"))) + if p["set"] != "V1": + continue + hyp[(p["arm"], p["id"])] = p["hyp"] + ref[p["id"]] = p["ref"] + if int(p["dist"]) > 0: + nwrong[p["id"]] = nwrong.get(p["id"], 0) + 1 + n_arms = len(err) + sheets = os.path.join(priv, "sheets") + os.makedirs(sheets, exist_ok=True) + try: + font = ImageFont.load_default(size=28) + except TypeError: + font = ImageFont.load_default() + idx_rows = [] + for s0 in range(0, len(union), PER_SHEET): + chunk = union[s0:s0 + PER_SHEET] + tiles = [] + for k, cid in enumerate(chunk): + n = s0 + k + 1 + im = Image.open(mrow[cid]["image"]).convert("RGB") + w0, h0 = im.size + sc = H / float(h0) + w = int(round(w0 * sc)) + if w > MAXW: + sc = MAXW / float(w0) + w = MAXW + im2 = im.resize((max(1, w), max(1, int(round(h0 * sc)))), Image.LANCZOS) + tiles.append((n, im2, w0, h0)) + idx_rows.append({"n": n, "id": cid, "orig_w": w0, "orig_h": h0, "sheet": s0 // PER_SHEET + 1, + "in_sample_of": [a for a in ARMS if cid in samples[a]], "in_allwrong_stratum": cid in stratum, + "arms_wrong_of_%d" % n_arms: nwrong.get(cid, 0), "ref": ref.get(cid), + "out": {a: hyp.get((a, cid)) for a in ARMS}}) + Wd = 90 + max(t[1].size[0] for t in tiles) + 10 + Ht = sum(t[1].size[1] + 16 for t in tiles) + 8 + sheet = Image.new("RGB", (Wd, Ht), (255, 255, 255)) + dr = ImageDraw.Draw(sheet) + y = 8 + for n, im2, w0, h0 in tiles: + dr.text((4, y + im2.size[1] // 2 - 14), "%d" % n, fill=(200, 0, 0), font=font) + sheet.paste(im2, (90, y)) + dr.rectangle([89, y - 1, 90 + im2.size[0], y + im2.size[1]], outline=(160, 160, 160)) + y += im2.size[1] + 16 + sheet.save(os.path.join(sheets, "sheet_%03d.png" % (s0 // PER_SHEET + 1))) + with open(os.path.join(sheets, "index.jsonl"), "w", encoding="utf-8") as f: + for r in idx_rows: + f.write(json.dumps(r, ensure_ascii=False) + "\n") + design = {"seed": SEED, "n_per_arm": N_PER_ARM, "arms": ARMS, "error_crops_per_arm": {a: len(err[a]) for a in ARMS}, + "sample_sizes": {a: len(samples[a]) for a in ARMS}, "allwrong_total": len(aw), "allwrong_stratum": len(stratum), + "union_crops_to_view": len(union), "sheets": (len(union) + PER_SHEET - 1) // PER_SHEET, "arms_in_every_arm_definition": sorted(err)} + json.dump(design, open(os.path.join(priv, "sample_design.json"), "w"), indent=1) + print(json.dumps(design)) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/r5_erran/erran_visual.py b/scripts/r5_erran/erran_visual.py new file mode 100644 index 0000000000000000000000000000000000000000..d3922ae7fd5f740b31a20bcff1474b53a4345fc5 --- /dev/null +++ b/scripts/r5_erran/erran_visual.py @@ -0,0 +1,127 @@ +"""ERRAN (R5) task 2: shares of the visual causes per arm, with Wilson 95% intervals, from the viewer's judgements. + +Input (cluster only, OUT/private/): sheets/index.jsonl (crop number -> id, which arm samples hold it, stratum flag) and +visual_judgements.tsv with columns n, cause, overrides (arm=cause;...), written by the viewer after looking at each crop next to +its reference and the outputs. One primary cause per (crop, arm): the crop's cause unless an override names the arm. +Output: OUT/visual_causes_counts.json with counts and shares only (no ids, no text). +""" +import argparse +import collections +import json +import math +import os +import sys +import time + +CAUSES = { + "a": "the reference label looks wrong or incomplete", + "b": "the crop cuts off letters, or holds parts of other words", + "c": "handwriting genuinely ambiguous or illegible to a careful reader", + "d": "a correction or strike-through in the ink", + "e": "ruled lines, stains or noise over the ink", + "f": "an unusual letter form for a known letter", + "g": "a clear, legible image that the model misread (model fault)", + "h": "other", +} +ARMS = ["hunyuanocr", "minicpm_ocr_1_0", "paddleocr_vl_1_6", "A1 long_lm_gated"] + + +def wilson(k, n, z=1.959964): + if n == 0: + return None, None + p = k / n + den = 1 + z * z / n + c = (p + z * z / (2 * n)) / den + h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / den + return max(0.0, c - h), min(1.0, c + h) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", required=True) + args = ap.parse_args() + priv = os.path.join(args.out, "private") + idx = {} + with open(os.path.join(priv, "sheets", "index.jsonl"), encoding="utf-8") as f: + for line in f: + r = json.loads(line) + idx[r["n"]] = r + jud = {} + notes = {} + with open(os.path.join(priv, "visual_judgements.tsv"), encoding="utf-8") as f: + hdr = f.readline().rstrip("\n").split("\t") + for line in f: + p = dict(zip(hdr, line.rstrip("\n").split("\t"))) + if not p.get("n"): + continue + ov = {} + for t in (p.get("overrides") or "").split(";"): + if "=" in t: + a, c = t.split("=", 1) + ov[a.strip()] = c.strip() + jud[int(p["n"])] = (p["cause"].strip(), ov) + alias = {"punct": "punct-missing-in-ref", "space": "space-missing-in-ref"} + notes[int(p["n"])] = [alias.get(t.strip(), t.strip()) for t in (p.get("note") or "").replace("+", ";").split(";") if t.strip()] + missing = sorted(n for n in idx if n not in jud) + bad = sorted(n for n, (c, ov) in jud.items() if c not in CAUSES or any(v not in CAUSES for v in ov.values())) + per_arm = {} + for a in ARMS: + cnt = collections.Counter() + n = 0 + for k, r in idx.items(): + if a in r["in_sample_of"] and k in jud: + c, ov = jud[k] + cnt[ov.get(a, c)] += 1 + n += 1 + per_arm[a] = {"n_viewed": n, "causes": {}} + for c in CAUSES: + lo, hi = wilson(cnt[c], n) + per_arm[a]["causes"][c] = {"cause": CAUSES[c], "count": cnt[c], "share": cnt[c] / n if n else None, "wilson95": [lo, hi]} + sub = collections.Counter() + for k, r in idx.items(): + if a in r["in_sample_of"] and k in jud: + c, ov = jud[k] + if a in ov: + sub["%s|arm-specific-override" % ov[a]] += 1 + continue + for t in notes.get(k, []): + sub["%s|%s" % (c, t)] += 1 + per_arm[a]["viewer_tags_within_causes"] = dict(sorted(sub.items())) + # every-arm-wrong stratum: crop-level cause (overrides ignored), and per-arm for those in it + cnt = collections.Counter() + n = 0 + for k, r in idx.items(): + if r["in_allwrong_stratum"] and k in jud: + cnt[jud[k][0]] += 1 + n += 1 + strat = {"n_viewed": n, "causes": {c: {"cause": CAUSES[c], "count": cnt[c], "share": cnt[c] / n if n else None, + "wilson95": list(wilson(cnt[c], n))} for c in CAUSES}} + sub = collections.Counter() + for k, r in idx.items(): + if r["in_allwrong_stratum"] and k in jud: + for t in notes.get(k, []): + sub["%s|%s" % (jud[k][0], t)] += 1 + strat["viewer_tags_within_causes"] = dict(sorted(sub.items())) + strat["note"] = "crop-level cause (per-arm overrides ignored); these crops are wrong for all 15 arms of the task-1 list" + n_override = sum(1 for c, ov in jud.values() if ov) + design = json.load(open(os.path.join(priv, "sample_design.json"), encoding="utf-8")) + out = {"generated_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "validation_only": True, "set": "V1 (KOHTD validation screen set)", + "design": design, "causes": CAUSES, "per_arm_uniform_sample": per_arm, "every_arm_wrong_stratum": strat, + "crops_viewed": len(jud), "crops_in_index": len(idx), "crops_not_judged": len(missing), "invalid_codes": len(bad), + "crops_with_arm_specific_override": n_override, + "viewer_tags": {"case": "case-only mismatch between reference and what the image shows", + "punct-missing-in-ref": "a punctuation mark visible in the image is missing from the reference", + "space-conv": "spacing next to punctuation differs between reference and image (KOHTD labels often put a space before , . : ) -)", + "language-prior": "the output replaced what is written with a more frequent real word or spelling", + "spelling-normalised-in-ref": "the writer misspelled, the reference gives the correct spelling", + "wrong-script-output": "the output uses letters of the other script", + "other tags": "short free-text notes of the viewer (faint, lowres, cut-right, neighbour-comma, strike, ...)"}, + "viewer": "stage ERRAN, one viewer, no second rater: agreement unknown", + "judgement_file_on_cluster": os.path.join(priv, "visual_judgements.tsv"), + "privacy": "counts and categories only; crop ids, images and label text stay on the cluster under OUT/private/"} + json.dump(out, open(os.path.join(args.out, "visual_causes_counts.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1) + print(json.dumps({"missing": len(missing), "bad": len(bad), "n": len(jud)})) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/r5_erran/r5_erran.sbatch b/scripts/r5_erran/r5_erran.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..e40ad66b1f7b60be46f0573780b8021c81b9bb48 --- /dev/null +++ b/scripts/r5_erran/r5_erran.sbatch @@ -0,0 +1,15 @@ +#!/bin/bash +#SBATCH --job-name=r5_erran +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=16 +#SBATCH --mem=32G +#SBATCH --time=02:00:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# R5 ERRAN: descriptive error analysis on validation data only. Arguments pass through to erran_analysis.py +# (for example: --out DATA/outputs/r5/erran --tasks 1,3,4,6 [--limit-arms hunyuanocr]). +C=/path/to/TURKIC_OCR_CODE +export OMP_NUM_THREADS=16 +export OPENBLAS_NUM_THREADS=16 +$C/.venv_kraken/bin/python -I $C/scripts/r5_erran/erran_analysis.py "$@" diff --git a/scripts/r5_erran/r5_erran_py.sbatch b/scripts/r5_erran/r5_erran_py.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..f1f4916a1c8e398d0eb25a43a3b87bcfade9ed78 --- /dev/null +++ b/scripts/r5_erran/r5_erran_py.sbatch @@ -0,0 +1,15 @@ +#!/bin/bash +#SBATCH --job-name=r5_erran_py +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=4 +#SBATCH --mem=16G +#SBATCH --time=00:30:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# R5 ERRAN: run one ERRAN script from CODE/scripts/r5_erran with its arguments, e.g. +# sbatch r5_erran_py.sbatch erran_sample.py --out DATA/outputs/r5/erran +C=/path/to/TURKIC_OCR_CODE +S=$1 +shift +$C/.venv_kraken/bin/python -I $C/scripts/r5_erran/$S "$@" diff --git a/scripts/r5_freeze/build_seq2.sbatch b/scripts/r5_freeze/build_seq2.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..5d6b7e266861db64dccfa6b146ac11f74f0b7724 --- /dev/null +++ b/scripts/r5_freeze/build_seq2.sbatch @@ -0,0 +1,27 @@ +#!/bin/bash +#SBATCH --job-name=r5_freeze_seq2 +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=4 +#SBATCH --mem=32G +#SBATCH --time=01:30:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# R5 stage FREEZE, part B step 5: the seed-2 sample sequence for the leader runs (amendment 3.3 D2), built with VLMA's own builder +# from the frozen mix_v1.yaml, data-order seed 20261122, 6,000,000 rows (the builder's default), beside seed 1's sequence. +# leader_runner.py (ensure_seq) uses it as is when .done exists. +set -u +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN +C=/path/to/TURKIC_OCR_CODE +D=/path/to/TURKIC_OCR_DATA +R5=$D/data/processed/r5 +OUT=$R5/seq/mix_v1_seq_s20261122.tsv +echo "start $(date -u +%FT%TZ) on $(hostname)" +sha256sum $R5/mix_v1.yaml +if [ -e $OUT.done ]; then echo "already built"; cat $OUT.done; exit 0; fi +$C/.venv_vlm/bin/python -I $C/scripts/r5_vlma/build_sequence.py $R5/mix_v1.yaml $OUT --seed 20261122 +RC=$? +echo "exit $RC" +[ -e $OUT.done ] && cat $OUT.done && sha256sum $OUT $OUT.summary.json +echo "end $(date -u +%FT%TZ)" +exit $RC diff --git a/scripts/r5_freeze/check_curve.py b/scripts/r5_freeze/check_curve.py new file mode 100644 index 0000000000000000000000000000000000000000..a3b7ca6f29ba39349f564949ca4d9e2b387292de --- /dev/null +++ b/scripts/r5_freeze/check_curve.py @@ -0,0 +1,38 @@ +"""R5 FREEZE: after r5_freeze_curve.sh, check that every part of curve_v1 was drawn from the expected version of its source manifest +(GEN production_done.json stage 1 for the synthetic val sets, PRINT's sha256 for print_real_val, the registry for kohtd_lmtune), that no +part is missing, and that the registry entry matches the frozen file. +usage: python -I check_curve.py CURVE_INFO_JSON CURVE_FROZEN_JSON PRODUCTION_DONE_JSON EVALSETS_JSON OUT_JSON +""" +import json +import sys + +info_p, frozen_p, pd_p, reg_p, out = sys.argv[1:6] +info = json.load(open(info_p, encoding="utf-8")) +fz = json.load(open(frozen_p, encoding="utf-8")) +pd = json.load(open(pd_p, encoding="utf-8")) +reg = json.load(open(reg_p, encoding="utf-8")) +sets = {s["name"]: s for s in reg["sets"]} +expect = {"synth_hand_val": pd["manifests"]["synth_hand_val.tsv"]["sha256"], + "synth_typed_val": pd["manifests"]["synth_typed_val.tsv"]["sha256"], + "synth_clutter_val": pd["manifests"]["synth_clutter_val.tsv"]["sha256"], + "print_real_val": "36235ee1806f32b8f30f4bfbbd5ced306a98eb1201fe768f257393241588e82e", + "V1lm": sets["V1lm"]["manifest_sha256"]} +res = {"problems": [], "parts": []} +for p in info["parts"]: + e = expect.get(p["part"]) + ok = p.get("manifest_sha256") == e + res["parts"].append({"part": p["part"], "rows_drawn": p.get("rows_drawn"), "short_languages": p.get("short_languages"), + "source_sha256": p.get("manifest_sha256"), "expected": e, "match": ok}) + if not ok: + res["problems"].append("%s drawn from sha256 %s, expected %s" % (p["part"], p.get("manifest_sha256"), e)) + if p.get("short_languages"): + res["problems"].append("%s short in %s" % (p["part"], p["short_languages"])) +if info.get("missing_parts"): + res["problems"].append("missing parts " + str(info["missing_parts"])) +c = sets.get("curve_v1") +if not c or c.get("manifest_sha256") != fz["manifest_sha256"] or c.get("n_rows") != fz["rows"]: + res["problems"].append("registry curve_v1 entry missing or differs from curve_v1_frozen.json") +res["frozen"] = fz +res["status"] = "PASS" if not res["problems"] else "FAIL" +json.dump(res, open(out, "w", encoding="utf-8"), indent=1, ensure_ascii=False) +print(res["status"], res["problems"], fz.get("manifest_sha256"), fz.get("rows"), fz.get("rows_by_part")) diff --git a/scripts/r5_freeze/compare_parsers.py b/scripts/r5_freeze/compare_parsers.py new file mode 100644 index 0000000000000000000000000000000000000000..de67aed07b9114f71c2506a651af2d85f5c67d84 --- /dev/null +++ b/scripts/r5_freeze/compare_parsers.py @@ -0,0 +1,64 @@ +"""R5 FREEZE: do all consumers of mix_v1.yaml read the same leaves and shares? (audit part 1, CAN'T TELL item on the two parsers) + +Reads the yaml with the consumers' OWN code (imported, not copied): + - LINEDET: linedet.data.load_mix (CODE/src/linedet/data.py), also used by make_codec, train_arm and lm_prep; + - REF: load_mix of CODE/scripts/r5_ref/ref_make_mix_lists.py (its stated verbatim copy of LINEDET's); + - EVALCODE: r5eval.ktrain.read_mix_leaves (leaves and filters only; K_train uses no shares); + - VLMA: build_sequence.py's per-stratum target_share, taken from the summary JSON that build_sequence.py wrote for this yaml + (its walk is module-level code, so it is run, not imported; the summary's mix_yaml_sha256 must equal the yaml's sha256); + - the generator's own exact shares (gen report JSON). +A leaf is identified by (manifest path, lang filter). PASS when every reader has the same leaf set and every share agrees within 1e-9. +usage: python -I compare_parsers.py YAML VLMA_SUMMARY_JSON GEN_REPORT_JSON OUT_JSON +""" +import hashlib +import json +import sys + +CODE = "/path/to/TURKIC_OCR_CODE" +sys.path.insert(0, CODE + "/src") +sys.path.insert(0, CODE + "/scripts/r5_ref") + +yml, vsum, grep_, out = sys.argv[1:5] +ysha = hashlib.sha256(open(yml, "rb").read()).hexdigest() +res = {"yaml": yml, "yaml_sha256": ysha, "readers": {}, "problems": []} + + +def key(manifest, flt): + lang = (flt or {}).get("lang") + if isinstance(lang, list): + lang = ",".join(map(str, lang)) + other = sorted((k, str(v)) for k, v in (flt or {}).items() if k != "lang") + return "%s|lang=%s%s" % (manifest, lang, ("|" + str(other)) if other else "") + + +readers = {} +from linedet.data import load_mix as ld_load # noqa: E402 +readers["LINEDET linedet.data.load_mix"] = {key(c["manifest"], c["filter"]): (c["share"], c["name"]) for c in ld_load(yml)} +import ref_make_mix_lists as REF # noqa: E402 +readers["REF ref_make_mix_lists.load_mix"] = {key(c["manifest"], c["filter"]): (c["share"], c["name"]) for c in REF.load_mix(yml)} +from r5eval.ktrain import read_mix_leaves # noqa: E402 +kt = read_mix_leaves(yml) +readers["EVALCODE r5eval.ktrain.read_mix_leaves (no shares)"] = {key(c["manifest"], c["filter"]): (None, c["name"]) for c in kt} +s = json.load(open(vsum, encoding="utf-8")) +if s.get("mix_yaml_sha256") != ysha: + res["problems"].append("VLMA summary was written for another yaml (%s)" % s.get("mix_yaml_sha256")) +readers["VLMA build_sequence.py summary target_share"] = {key(st["manifest"], st["filter"]): (st["target_share"], st["name"]) for st in s["strata"]} +g = json.load(open(grep_, encoding="utf-8")) +readers["generator exact shares"] = {key(lf["manifest"], {"lang": lf["filter_lang"]} if lf["filter_lang"] else None): (lf["share"], lf["name"]) for lf in g["leaves"]} +ref = readers["generator exact shares"] +for nm, r in readers.items(): + info = {"n_leaves": len(r), "sum_of_shares": (sum(v[0] for v in r.values()) if all(v[0] is not None for v in r.values()) else None)} + missing = sorted(set(ref) - set(r)) + extra = sorted(set(r) - set(ref)) + if missing or extra: + res["problems"].append("%s: leaf sets differ: missing %s extra %s" % (nm, missing, extra)) + diffs = {k: abs(r[k][0] - ref[k][0]) for k in set(r) & set(ref) if r[k][0] is not None} + info["max_abs_share_diff_vs_generator"] = max(diffs.values()) if diffs else None + if diffs and max(diffs.values()) > 1e-9: + res["problems"].append("%s: share differs by %g" % (nm, max(diffs.values()))) + res["readers"][nm] = info +res["leaf_shares"] = {k: {nm: r.get(k, (None,))[0] for nm, r in readers.items()} for k in sorted(ref)} +res["status"] = "PASS" if not res["problems"] else "FAIL" +json.dump(res, open(out, "w", encoding="utf-8"), indent=1, ensure_ascii=False) +print(res["status"], json.dumps({k: v for k, v in res.items() if k in ("readers", "problems")}, ensure_ascii=False)) +sys.exit(0 if res["status"] == "PASS" else 3) diff --git a/scripts/r5_freeze/dedupe_verdict.py b/scripts/r5_freeze/dedupe_verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..c3904b7767d9cd9cb0d45bf537524dfd7d7cddae --- /dev/null +++ b/scripts/r5_freeze/dedupe_verdict.py @@ -0,0 +1,91 @@ +"""R5 FREEZE: reads DATA's report-only duplicate check (build_logs/dedupe_all.json + dedupe_all_dropped.tsv) and applies the +freeze rule written in records/R5/FREEZE/status.json BEFORE the report existed: + - pairs where the train side is kohtd_rand_train or the partner is kohtd_rand_val / kohtd_rand_test are the deliberate + replication overlap (amendment 3.3 D5 (ii), clarification H1): left out, counted; + - any pair whose partner is kohtd_test: STOP (H1 guarantee and the form split); + - any other byte-identical pair: STOP; + - near-pHash pairs with the same non-empty label: STOP for manual review; + - near-pHash pairs with different labels or empty (clutter) labels: reported, not a stop. +Also counts, per manifest, how many row ids have an image hash in hashes.tsv / hashes_synth.tsv (rows without a hash are silently +skipped by dedupe_all: they are 'not checked', not 'clean'). Reads ids only from the manifests (no text of test rows, no image). +Also checks whether kohtd_rand_train / kohtd_rand_val ids are KOHTD ids (overlap with kohtd_train / kohtd_val ids). +usage: python -I dedupe_verdict.py OUT_JSON +""" +import collections +import csv +import json +import os +import sys + +csv.field_size_limit(10 ** 9) +R5 = "/path/to/TURKIC_OCR_DATA/data/processed/r5" +LOGS = R5 + "/build_logs" +MAN = R5 + "/manifests" +out = sys.argv[1] +info = json.load(open(LOGS + "/stage_dedupe_all.json", encoding="utf-8")) +hs = json.load(open(LOGS + "/stage_hash_synth.json", encoding="utf-8")) +RAND_TRAIN = {"kohtd_rand_train"} +RAND_EVAL = {"kohtd_rand_val", "kohtd_rand_test"} +cnt = collections.Counter() +stop = [] +near_report = collections.Counter() +same_label_near = [] +with open(LOGS + "/dedupe_all_dropped.tsv", encoding="utf-8", newline="") as f: + rd = csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE) + for r in rd: + byte = r["reason"] == "byte_identical" + k = (r["manifest"], r["partner_manifest"], "byte" if byte else "near", r["same_label"]) + cnt[k] += 1 + if r["partner_manifest"] == "kohtd_test": + stop.append(("partner is kohtd_test",) + k) + continue + if r["manifest"] in RAND_TRAIN or r["partner_manifest"] in RAND_EVAL: + continue + if byte: + stop.append(("byte-identical",) + k) + elif r["same_label"] == "True" and r["kind"] != "clutter": + same_label_near.append([r["train_id"], r["manifest"], r["partner_id"], r["partner_manifest"], r["reason"]]) + else: + near_report[k] += 1 + + +def ids_of(name): + p = os.path.join(MAN, name + ".tsv") + with open(p, encoding="utf-8", newline="") as f: + rd = csv.reader(f, delimiter="\t", quoting=csv.QUOTE_NONE) + h = next(rd) + i = h.index("id") + return [r[i] for r in rd if r] + + +hashed = set() +for fn in ("hashes.tsv", "hashes_synth.tsv"): + with open(os.path.join(LOGS, fn), encoding="utf-8") as f: + f.readline() + for line in f: + q = line.split("\t", 3) + if len(q) >= 3 and q[2]: + hashed.add(q[0]) +cover = {} +for fn in sorted(os.listdir(MAN)): + if not fn.endswith(".tsv") or fn.endswith(".meta.tsv"): + continue + nm = fn[:-4] + ids = ids_of(nm) + n_h = sum(1 for i in ids if i in hashed) + cover[nm] = {"rows": len(ids), "rows_with_hash": n_h, + "duplicate_check": "checked" if n_h == len(ids) else ("NOT CHECKED" if n_h == 0 else "partly checked")} +kt, kv = set(ids_of("kohtd_train")), set(ids_of("kohtd_val")) +rt, rv = ids_of("kohtd_rand_train"), ids_of("kohtd_rand_val") +rand_ids = {"kohtd_rand_train_rows": len(rt), "in_kohtd_train": sum(1 for i in rt if i in kt), "in_kohtd_val": sum(1 for i in rt if i in kv), + "kohtd_rand_val_rows": len(rv), "rand_val_in_kohtd_train": sum(1 for i in rv if i in kt), "rand_val_in_kohtd_val": sum(1 for i in rv if i in kv)} +res = {"dedupe_all_finished_utc": info.get("finished_utc"), "hash_synth": hs, "would_drop_total": info.get("would_drop_total"), + "pairs_by_manifest_partner_reason_samelabel": {" | ".join(k): v for k, v in sorted(cnt.items())}, + "STOP_pairs": [" | ".join(x) for x in stop][:200], "n_STOP_pairs": len(stop), + "same_label_near_nonclutter": same_label_near[:200], "n_same_label_near_nonclutter": len(same_label_near), + "near_reported_not_stop": {" | ".join(k): v for k, v in near_report.items()}, + "hash_coverage_by_manifest": cover, "rand_ids_are_kohtd_ids": rand_ids} +res["verdict"] = "STOP" if stop else ("NEEDS MANUAL REVIEW (same-label near duplicates)" if same_label_near else "PASS") +json.dump(res, open(out, "w", encoding="utf-8"), indent=1, ensure_ascii=False) +print(res["verdict"], "stop pairs", len(stop), "same-label near", len(same_label_near), + "not checked:", [k for k, v in cover.items() if v["duplicate_check"] != "checked"]) diff --git a/scripts/r5_freeze/drop_rows.py b/scripts/r5_freeze/drop_rows.py new file mode 100644 index 0000000000000000000000000000000000000000..dfc8375d1aec7afbcb46c1c00a20e1c68fa30a3f --- /dev/null +++ b/scripts/r5_freeze/drop_rows.py @@ -0,0 +1,115 @@ +"""R5 FREEZE: decision of 21 Nov 2026 ~02:05 UTC (option B extended). From the FROZEN synthetic train copies only, drop + (a) near_dup_same_label: the synthetic train rows that DATA's duplicate check (build_logs/dedupe_all_dropped.tsv, run 01:58:30 UTC) + pairs with a synthetic val/test row by near pHash (distance <= 4) AND the same non-empty label; + (b) text_leak_ge20: every synthetic train row whose label equals the label of a synthetic val/test LINE of at least 20 characters + (same definition as AUDIT's data_audit.py lines 278-286: unit == line, len(text) >= 20, whitespace collapsed). +Val/test labels are read from the read-only copies in frozen_eval_v1/ and are never printed or written; outputs hold ids only. +Non-synthetic train rows that match (b) are counted and listed (ids), not dropped (the decision covers synthetic rows only). +Writes into OUT_DIR: synth_hand_train.tsv, synth_typed_train.tsv and their .meta.tsv sidecars without the dropped rows (raw lines +copied byte for byte), dropped_rows.tsv (id, manifest, reason, matched_valtest_id, matched_valtest_manifest, detail), drop_report.json. +usage: python -I drop_rows.py FROZEN_TRAIN_DIR FROZEN_EVAL_DIR DEDUPE_DROPPED_TSV OUT_DIR PREDROP_DIR +(the two synthetic train manifests and their sidecars are read from PREDROP_DIR, the copies made before any drop) +""" +import collections +import csv +import hashlib +import json +import os +import sys + +csv.field_size_limit(10 ** 9) +fz, fe, ddt, out, pre = sys.argv[1:6] +os.makedirs(out, exist_ok=True) +SYN = ["synth_hand_train", "synth_typed_train"] +TRAIN = ["kohtd_train", "hkr_train", "chd_train", "school_train", "synth_hand_train", "synth_typed_train", "print_real_train", "synth_clutter_train"] +VALTEST = ["synth_hand_val", "synth_hand_test", "synth_typed_val", "synth_typed_test", "synth_clutter_val", "synth_clutter_test", + "synth_pages_val", "synth_pages_test"] + + +def norm(t): + return " ".join(t.split()) + + +def sha(p): + h = hashlib.sha256() + with open(p, "rb") as f: + for b in iter(lambda: f.read(1 << 20), b""): + h.update(b) + return h.hexdigest() + + +def rows(p): + with open(p, encoding="utf-8", newline="") as f: + return list(csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE)) + + +drops = [] # (id, manifest, reason, matched id, matched manifest, detail) +# (a) +with open(ddt, encoding="utf-8", newline="") as f: + for r in csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE): + if r["manifest"] in SYN and r["partner_manifest"] in VALTEST and r["same_label"] == "True" and r["kind"] != "clutter": + drops.append((r["train_id"], r["manifest"], "near_dup_same_label", r["partner_id"], r["partner_manifest"], r["reason"])) +n_a = len(drops) +# (b) +vt = collections.defaultdict(list) +vt_n = {} +for m in VALTEST: + n = 0 + for r in rows(os.path.join(fe, m + ".tsv")): + if r["unit"] == "line" and len(r["text"]) >= 20: + vt[norm(r["text"])].append((r["id"], m)) + n += 1 + vt_n[m] = n +matched_vt = set() +nonsyn = collections.Counter() +nonsyn_ids = [] +train_rows = {} +for m in TRAIN: + rs = rows(os.path.join(pre if m in SYN else fz, m + ".tsv")) + train_rows[m] = len(rs) + for r in rs: + k = norm(r["text"]) + if k in vt: + for vid, vm in vt[k]: + matched_vt.add((vid, vm)) + if m in SYN: + drops.append((r["id"], m, "text_leak_ge20", vid, vm, "exact label of a val/test line >= 20 chars")) + else: + nonsyn[m] += 1 + nonsyn_ids.append([r["id"], m, vid, vm]) +drop_ids = {m: {d[0] for d in drops if d[1] == m} for m in SYN} +# filtered copies (raw lines, byte for byte) +written = {} +for m in SYN: + for fn in (m + ".tsv", m + ".meta.tsv"): + src, dst = os.path.join(pre, fn), os.path.join(out, fn) + kept = dropped = 0 + with open(src, "rb") as fi, open(dst, "wb") as fo: + fo.write(fi.readline()) + for line in fi: + rid = line.split(b"\t", 1)[0].decode("utf-8") + if rid in drop_ids[m]: + dropped += 1 + continue + fo.write(line) + kept += 1 + written[fn] = {"source": src, "source_sha256": sha(src), "out": dst, "out_sha256": sha(dst), "rows_kept": kept, "rows_dropped": dropped} + if dropped != len(drop_ids[m]): + raise SystemExit("%s: dropped %d lines but %d ids are listed" % (fn, dropped, len(drop_ids[m]))) +with open(os.path.join(out, "dropped_rows.tsv"), "w", encoding="utf-8", newline="") as f: + f.write("id\tmanifest\treason\tmatched_valtest_id\tmatched_valtest_manifest\tdetail\n") + for d in sorted(drops): + f.write("\t".join(d) + "\n") +rep = {"decision": "decision of 21 Nov 2026 ~02:05 UTC, option B extended (near-duplicate same-label rows + text leak of val/test lines >= 20 chars), synthetic train rows only, frozen copies only; manifests/ unchanged", + "pairs_a_near_dup_same_label": n_a, + "pairs_b_text_leak": len(drops) - n_a, + "unique_rows_dropped": {m: len(v) for m, v in drop_ids.items()}, + "unique_rows_dropped_total": sum(len(v) for v in drop_ids.values()), + "unique_rows_dropped_by_reason": {r: len({(d[0], d[1]) for d in drops if d[2] == r}) for r in ("near_dup_same_label", "text_leak_ge20")}, + "rows_in_both_reasons": len({(d[0], d[1]) for d in drops if d[2] == "near_dup_same_label"} & {(d[0], d[1]) for d in drops if d[2] == "text_leak_ge20"}), + "valtest_lines_ge20": vt_n, "valtest_lines_ge20_matched_by_any_train_row": len(matched_vt), + "valtest_lines_ge20_matched_by_manifest": dict(collections.Counter(vm for _, vm in matched_vt)), + "nonsynthetic_train_rows_matching_b_not_dropped": dict(nonsyn), "nonsynthetic_matches": nonsyn_ids[:200], + "train_rows_before": train_rows, "files": written} +json.dump(rep, open(os.path.join(out, "drop_report.json"), "w", encoding="utf-8"), indent=1) +print(json.dumps({k: v for k, v in rep.items() if k not in ("files", "nonsynthetic_matches")}, indent=1)) diff --git a/scripts/r5_freeze/freeze_drop.sbatch b/scripts/r5_freeze/freeze_drop.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..7c216a1ef869fddc2bffd6395e6b415cfcd99774 --- /dev/null +++ b/scripts/r5_freeze/freeze_drop.sbatch @@ -0,0 +1,114 @@ +#!/bin/bash +#SBATCH --job-name=r5_freeze_drop +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=01:00:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# R5 stage FREEZE, decision of 21 Nov ~02:05 UTC (option B extended). Never creates mix_v1.yaml. Steps: +# 1 keep the pre-drop synthetic train copies (outputs/r5/freeze/predrop/, read-only); drop_rows.py -> filtered copies + dropped_rows.tsv +# 2 replace synth_hand_train / synth_typed_train (+ .meta.tsv) in frozen_mix_v1 (atomic mv), read-only again, new sha256 list +# 3 gen_mix_v1.py --dropped -> mix_v1.yaml.tmp (frozen = pre-drop minus exactly the listed ids; pre-drop = production_done) +# 4 repoint_evalsets.py: synth_*_val/test registry entries -> read-only copies in frozen_eval_v1/ +# 5 AUDIT's data audit (reads manifests/): only if no GEN finalize job runs or may begin within 5 minutes (it takes ~80 s and +# GEN's finalize reads its parts for ~4 minutes before it writes); otherwise skipped and noted +# 6 VLMA check_mix, LINEDET make_codec, parser comparison on the tmp yaml +set -u +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN +C=/path/to/TURKIC_OCR_CODE +D=/path/to/TURKIC_OCR_DATA +R5=$D/data/processed/r5 +M=$R5/manifests +FZ=$R5/frozen_mix_v1 +FE=$R5/frozen_eval_v1 +W=$D/outputs/r5/freeze +F=$C/scripts/r5_freeze +TMPY=$R5/mix_v1.yaml.tmp +PYK=$C/.venv_kraken/bin/python +PYD=$C/.venv/bin/python +PRE=$W/predrop +DS=$W/drop_stage +echo "start $(date -u +%FT%TZ) on $(hostname), job $SLURM_JOB_ID" +if [ -e $R5/mix_v1.yaml ]; then echo "STOP: mix_v1.yaml exists already"; exit 9; fi + +echo "== step 1 drop list $(date -u +%T)" +if [ ! -e $PRE/synth_typed_train.meta.tsv ]; then + mkdir -p $PRE + cp -p $FZ/synth_hand_train.tsv $FZ/synth_hand_train.meta.tsv $FZ/synth_typed_train.tsv $FZ/synth_typed_train.meta.tsv $PRE/ + chmod a-w $PRE/*.tsv +fi +(cd $PRE && sha256sum *.tsv) +mkdir -p $DS +cp -p $R5/build_logs/dedupe_all_dropped.tsv $W/dedupe_all_dropped_used.tsv +$PYD -I $F/drop_rows.py $FZ $FE $W/dedupe_all_dropped_used.tsv $DS $PRE +RC1=$? +echo "step1 exit $RC1" +if [ $RC1 -ne 0 ]; then echo "STOP: drop_rows failed"; exit 2; fi +cp $DS/dropped_rows.tsv $DS/drop_report.json $W/ + +echo "== step 2 replace in frozen_mix_v1 $(date -u +%T)" +chmod u+w $FZ +cp $DS/synth_hand_train.tsv $FZ/synth_hand_train.tsv.new && mv -f $FZ/synth_hand_train.tsv.new $FZ/synth_hand_train.tsv +cp $DS/synth_hand_train.meta.tsv $FZ/synth_hand_train.meta.tsv.new && mv -f $FZ/synth_hand_train.meta.tsv.new $FZ/synth_hand_train.meta.tsv +cp $DS/synth_typed_train.tsv $FZ/synth_typed_train.tsv.new && mv -f $FZ/synth_typed_train.tsv.new $FZ/synth_typed_train.tsv +cp $DS/synth_typed_train.meta.tsv $FZ/synth_typed_train.meta.tsv.new && mv -f $FZ/synth_typed_train.meta.tsv.new $FZ/synth_typed_train.meta.tsv +chmod a-w $FZ/*.tsv +ls -la $FZ +(cd $FZ && sha256sum *.tsv) > $W/frozen_mix_v1.sha256 +cat $W/frozen_mix_v1.sha256 + +echo "== step 3 generator $(date -u +%T)" +$PYK -I $F/gen_mix_v1.py --frozen-dir $FZ --source-dir $M --out $TMPY --report $W/gen_report.json --dropped $W/dropped_rows.tsv --predrop-dir $PRE +RC3=$? +echo "step3 exit $RC3" +chmod a-w $FZ +if [ $RC3 -ne 0 ]; then echo "STOP: generator failed"; exit 3; fi +cp $W/frozen_mix_v1.sha256 $D/checksums/r5_frozen_mix_v1.sha256 +sha256sum $TMPY + +echo "== step 4 registry: synthetic val/test -> frozen_eval_v1 $(date -u +%T)" +cp -p $R5/evalsets.json $W/evalsets_before_repoint.json +$PYD -I $F/repoint_evalsets.py $R5/evalsets.json $FE $W/repoint_evalsets.json +RC4=$? +echo "step4 exit $RC4" + +echo "== step 5 data audit $(date -u +%T)" +RC5=skipped +OK5=1 +NOWS=$(date +%s) +for J in 51065 51066; do + ST=$(squeue -h -j $J -o %T 2>/dev/null) + if [ "$ST" = "RUNNING" ]; then OK5=0; echo "GEN finalize $J is running"; fi + if [ "$ST" = "PENDING" ]; then + BS=$(date -d "$(squeue -h -j $J -o %S)" +%s 2>/dev/null || echo 0) + if [ $((BS - NOWS)) -lt 300 ]; then OK5=0; echo "GEN finalize $J may begin within 5 min"; fi + fi +done +if [ $OK5 -eq 1 ]; then + bash $D/outputs/r5/audit/data_audit.sbatch > $W/data_audit2.log 2>&1 + RC5=$? + cp -p $D/outputs/r5/audit/data_audit.json $W/data_audit2.json + tail -c 600 $W/data_audit2.log + echo "GEN finalize running after the audit: [$(squeue -h -u $USER -n r5_gen_final -t R -o %i)]" +else + echo "data audit SKIPPED (GEN finalize window); rerun later" +fi +echo "step5 $RC5" + +echo "== step 6 check_mix, make_codec, compare $(date -u +%T)" +bash $C/scripts/r5_vlma/check_mix.sbatch $TMPY > $W/check_mix2.log 2>&1 +O=$D/outputs/r5/vlma/check_mix +if [ -e $O/trial_seq.tsv.done ]; then RC6A=0; else RC6A=1; fi +cp $O/trial_seq.tsv.summary.json $W/check_mix_summary2.json +head -c 600 $W/check_mix2.log +$PYK -I -m linedet.make_codec --mix $TMPY --out $D/tmp/codec_check/codec_union.json > $W/make_codec2.log 2>&1 +RC6B=$? +head -1 $W/make_codec2.log +$PYK -I $F/compare_parsers.py $TMPY $W/check_mix_summary2.json $W/gen_report.json $W/compare_parsers2.json +RC6C=$? +sha256sum $TMPY +echo "{\"job\": $SLURM_JOB_ID, \"end_utc\": \"$(date -u +%FT%TZ)\", \"rc\": {\"drop\": $RC1, \"gen\": $RC3, \"repoint\": $RC4, \"data_audit\": \"$RC5\", \"check_mix_done_missing\": $RC6A, \"make_codec\": $RC6B, \"compare\": $RC6C}}" > $W/freeze_drop_rc.json +cat $W/freeze_drop_rc.json +echo "end $(date -u +%FT%TZ)" diff --git a/scripts/r5_freeze/freeze_post.sbatch b/scripts/r5_freeze/freeze_post.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..7c37ceaf11ca37dcfe8627827698af427d38b25f --- /dev/null +++ b/scripts/r5_freeze/freeze_post.sbatch @@ -0,0 +1,74 @@ +#!/bin/bash +#SBATCH --job-name=r5_freeze_post +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=01:30:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# R5 stage FREEZE, job 2 of 2. Every step reads manifests/, which GEN finalize jobs 51065/51066 rewrite in place: the guard +# below stops the job (exit 4) if one of them runs or may begin within 20 minutes; then resubmit with +# --dependency=afterany:51065:51066. Steps: +# 6 DATA's r5_after_gen.sbatch, run with bash inside this job (hash GEN images, report-only dedupe of all manifests, validate, +# P2 slice, registry) +# 6b dedupe_verdict.py: the freeze rule on the dedupe report + per-manifest hash coverage +# 7 merge_evalsets.py: put back the sets r5_registry.py drops (PRINT's 3, REF's kohtd_rand_test, curve_v1 if present) +# 8 AUDIT's data_audit.sbatch, run with bash inside this job (stat() of every image path of every manifest; no image opened) +set -u +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN +C=/path/to/TURKIC_OCR_CODE +D=/path/to/TURKIC_OCR_DATA +R5=$D/data/processed/r5 +W=$D/outputs/r5/freeze +F=$C/scripts/r5_freeze +PYD=$C/.venv/bin/python +mkdir -p $W +echo "start $(date -u +%FT%TZ) on $(hostname), job $SLURM_JOB_ID, cpus $SLURM_CPUS_PER_TASK" +echo "GEN finalize jobs running now: [$(squeue -h -u $USER -n r5_gen_final -t R -o %i)]" +# guard: GEN finalize jobs 51065/51066 rewrite manifests/synth_* in place. Stop (exit 4) if one runs now or may begin within +# 20 minutes (its begin time is read from squeue in cluster local time and compared with the node clock). No waiting. +guard() { + NOWS=$(date +%s) + for J in 51065 51066; do + ST=$(squeue -h -j $J -o %T 2>/dev/null) + if [ "$ST" = "RUNNING" ]; then echo "GUARD STOP before $1: GEN finalize $J is running"; exit 4; fi + if [ "$ST" = "PENDING" ]; then + BS=$(date -d "$(squeue -h -j $J -o %S)" +%s 2>/dev/null || echo 0) + if [ $((BS - NOWS)) -lt 1200 ]; then echo "GUARD STOP before $1: GEN finalize $J may begin within 20 min (begin $(squeue -h -j $J -o %S) local)"; exit 4; fi + fi + echo "guard $1: $J state [$ST] ok" + done +} +guard step6 + +echo "== step 6 DATA after_gen $(date -u +%T)" +cp -p $R5/evalsets.json $W/evalsets_before_aftergen.json +bash $C/scripts/r5/r5_after_gen.sbatch > $W/after_gen.log 2>&1 +RC6=$? +tail -c 5000 $W/after_gen.log +echo "step6 exit $RC6" + +echo "== step 6b dedupe verdict $(date -u +%T)" +$PYD -I $F/dedupe_verdict.py $W/dedupe_verdict.json +RC6B=$? +cp -p $R5/build_logs/stage_dedupe_all.json $R5/build_logs/dedupe_all_dropped.tsv $R5/build_logs/stage_hash_synth.json $R5/p2_slice_info.json $W/ +echo "step6b exit $RC6B" + +echo "== step 7 registry merge $(date -u +%T)" +$PYD -I $F/merge_evalsets.py $W/evalsets_before_aftergen.json $R5/evalsets.json $R5/evalsets_extra_print.json $D/outputs/r5/mix_v1_shares.json $W/merge_evalsets.json +RC7=$? +cp -p $R5/evalsets.json $W/evalsets_after_merge.json +echo "step7 exit $RC7" + +guard step8 +echo "== step 8 data audit (stat only) $(date -u +%T)" +bash $D/outputs/r5/audit/data_audit.sbatch > $W/data_audit.log 2>&1 +RC8=$? +cp -p $D/outputs/r5/audit/data_audit.json $W/data_audit.json +tail -c 1500 $W/data_audit.log +echo "step8 exit $RC8" +echo "GEN finalize jobs running at the end: [$(squeue -h -u $USER -n r5_gen_final -t R -o %i)]" +echo "{\"job\": $SLURM_JOB_ID, \"end_utc\": \"$(date -u +%FT%TZ)\", \"rc\": {\"after_gen\": $RC6, \"dedupe_verdict\": $RC6B, \"merge\": $RC7, \"data_audit\": $RC8}}" > $W/freeze_post_rc.json +cat $W/freeze_post_rc.json +echo "end $(date -u +%FT%TZ)" diff --git a/scripts/r5_freeze/freeze_post2.sbatch b/scripts/r5_freeze/freeze_post2.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..39230587b6eb64e16f394b6c5ada81ce4a790e30 --- /dev/null +++ b/scripts/r5_freeze/freeze_post2.sbatch @@ -0,0 +1,48 @@ +#!/bin/bash +#SBATCH --job-name=r5_freeze_post2 +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=01:00:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# R5 stage FREEZE: rerun of the two DATA steps that failed in job 51293 on GEN's .meta.tsv sidecars (fixed: they are skipped now, +# diff records/R5/FREEZE/data_scripts_meta_fix.diff): the report-only duplicate check over all manifests (dedupe_all, using the +# hashes_synth.tsv written by 51293 at 01:52:29 UTC) and the manifest validator; then dedupe_verdict.py. Same guard as freeze_post. +set -u +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN +C=/path/to/TURKIC_OCR_CODE +D=/path/to/TURKIC_OCR_DATA +R5=$D/data/processed/r5 +W=$D/outputs/r5/freeze +PY=$C/.venv/bin/python +S=$C/scripts/r5 +echo "start $(date -u +%FT%TZ) on $(hostname), job $SLURM_JOB_ID, cpus $SLURM_CPUS_PER_TASK" +guard() { + NOWS=$(date +%s) + for J in 51065 51066; do + ST=$(squeue -h -j $J -o %T 2>/dev/null) + if [ "$ST" = "RUNNING" ]; then echo "GUARD STOP before $1: GEN finalize $J is running"; exit 4; fi + if [ "$ST" = "PENDING" ]; then + BS=$(date -d "$(squeue -h -j $J -o %S)" +%s 2>/dev/null || echo 0) + if [ $((BS - NOWS)) -lt 1200 ]; then echo "GUARD STOP before $1: GEN finalize $J may begin within 20 min"; exit 4; fi + fi + echo "guard $1: $J state [$ST] ok" + done +} +guard dedupe +sha256sum $S/r5_build_real.py $S/r5_validate_manifests.py +$PY -I $S/r5_build_real.py dedupe_all --force > $W/dedupe_all_rerun.log 2>&1 +RC1=$? +tail -c 3000 $W/dedupe_all_rerun.log +echo "dedupe_all exit $RC1" +$PY -I $C/scripts/r5_freeze/dedupe_verdict.py $W/dedupe_verdict.json +RC2=$? +cp -p $R5/build_logs/stage_dedupe_all.json $R5/build_logs/dedupe_all_dropped.tsv $R5/build_logs/stage_hash_synth.json $W/ +guard validate +$PY -I $S/r5_validate_manifests.py > $W/validate_rerun.log 2>&1 +RC3=$? +tail -c 2000 $W/validate_rerun.log +echo "{\"job\": $SLURM_JOB_ID, \"end_utc\": \"$(date -u +%FT%TZ)\", \"rc\": {\"dedupe_all\": $RC1, \"dedupe_verdict\": $RC2, \"validate\": $RC3}}" > $W/freeze_post2_rc.json +cat $W/freeze_post2_rc.json diff --git a/scripts/r5_freeze/freeze_prep.sbatch b/scripts/r5_freeze/freeze_prep.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..8912ae9b38f51425eca124123de25ee3df3e9dbb --- /dev/null +++ b/scripts/r5_freeze/freeze_prep.sbatch @@ -0,0 +1,84 @@ +#!/bin/bash +#SBATCH --job-name=r5_freeze_prep +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=01:00:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# R5 stage FREEZE, job 1 of 2 (part A plus the checks of part B step 3). It never creates mix_v1.yaml (the file that starts +# the GPU jobs). Reads manifests/ only in step 1 (the copy), and refuses to copy while a GEN finalize job (r5_gen_final) runs, +# because that job rewrites manifests/synth_* in place. Steps: +# 1 copies of the 8 train manifests + 3 GEN sidecars into DATA/data/processed/r5/frozen_mix_v1/, files chmod a-w +# 2 gen_mix_v1.py -> DATA/data/processed/r5/mix_v1.yaml.tmp (+ gen_report.json); fails closed on any sha256 or row problem; +# only then the folder itself is made read-only +# 3 VLMA's check_mix.sbatch, run with bash inside this job (build_sequence.py, 200,000 rows, every train image checked) +# 4 LINEDET's make_codec on the tmp yaml (--out DATA/tmp/codec_check/codec_union.json) +# 5 compare_parsers.py: LINEDET, REF, EVALCODE and VLMA parsers read the same leaves and shares +# Outputs in DATA/outputs/r5/freeze/. +set -u +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN +C=/path/to/TURKIC_OCR_CODE +D=/path/to/TURKIC_OCR_DATA +R5=$D/data/processed/r5 +M=$R5/manifests +FZ=$R5/frozen_mix_v1 +W=$D/outputs/r5/freeze +F=$C/scripts/r5_freeze +TMPY=$R5/mix_v1.yaml.tmp +PYK=$C/.venv_kraken/bin/python +mkdir -p $W $D/tmp/codec_check +echo "start $(date -u +%FT%TZ) on $(hostname), job $SLURM_JOB_ID, cpus $SLURM_CPUS_PER_TASK" +if [ -e $R5/mix_v1.yaml ]; then echo "STOP: mix_v1.yaml exists already"; exit 9; fi + +echo "== step 1 frozen copies $(date -u +%T)" +RUNNING=$(squeue -h -u $USER -n r5_gen_final -t R -o %i) +echo "GEN finalize jobs running now: [$RUNNING]" +if [ -w $FZ ] || [ ! -e $FZ ]; then + if [ -n "$RUNNING" ]; then echo "STOP: a GEN finalize job is rewriting manifests/synth_* now; resubmit later"; exit 4; fi + mkdir -p $FZ + for f in kohtd_train hkr_train chd_train school_train synth_hand_train synth_typed_train print_real_train synth_clutter_train; do + [ -e $FZ/$f.tsv ] || cp -p $M/$f.tsv $FZ/$f.tsv + done + for f in synth_hand_train synth_typed_train synth_clutter_train; do + [ -e $FZ/$f.meta.tsv ] || cp -p $M/$f.meta.tsv $FZ/$f.meta.tsv + done + chmod a-w $FZ/*.tsv +fi +echo "GEN finalize jobs running after the copy: [$(squeue -h -u $USER -n r5_gen_final -t R -o %i)]" +ls -la $FZ +(cd $FZ && sha256sum *.tsv) > $W/frozen_mix_v1.sha256 +cat $W/frozen_mix_v1.sha256 + +echo "== step 2 generator $(date -u +%T)" +$PYK -I $F/gen_mix_v1.py --frozen-dir $FZ --source-dir $M --out $TMPY --report $W/gen_report.json +RC2=$? +echo "step2 exit $RC2" +if [ $RC2 -ne 0 ]; then echo "STOP: generator failed; the frozen folder stays writable so a bad copy can be replaced"; exit 2; fi +chmod a-w $FZ +cp $W/frozen_mix_v1.sha256 $D/checksums/r5_frozen_mix_v1.sha256 +sha256sum $TMPY + +echo "== step 3 check_mix (VLMA build_sequence, 200,000 rows) $(date -u +%T)" +bash $C/scripts/r5_vlma/check_mix.sbatch $TMPY > $W/check_mix.log 2>&1 +O=$D/outputs/r5/vlma/check_mix +if [ -e $O/trial_seq.tsv.done ]; then RC3=0; else RC3=1; fi +cp $O/trial_seq.tsv.summary.json $W/check_mix_summary.json +tail -c 1500 $W/check_mix.log +echo "step3 done-file present: $RC3 (0 = yes)" + +echo "== step 4 make_codec (LINEDET) $(date -u +%T)" +$PYK -I -m linedet.make_codec --mix $TMPY --out $D/tmp/codec_check/codec_union.json > $W/make_codec.log 2>&1 +RC4=$? +head -c 3000 $W/make_codec.log +echo "step4 exit $RC4" + +echo "== step 5 parser comparison $(date -u +%T)" +$PYK -I $F/compare_parsers.py $TMPY $W/check_mix_summary.json $W/gen_report.json $W/compare_parsers.json +RC5=$? +echo "step5 exit $RC5" +sha256sum $TMPY +echo "{\"job\": $SLURM_JOB_ID, \"end_utc\": \"$(date -u +%FT%TZ)\", \"rc\": {\"gen\": $RC2, \"check_mix_done_missing\": $RC3, \"make_codec\": $RC4, \"compare\": $RC5}}" > $W/freeze_prep_rc.json +cat $W/freeze_prep_rc.json +echo "end $(date -u +%FT%TZ)" diff --git a/scripts/r5_freeze/gen_finalize_stage2.sbatch b/scripts/r5_freeze/gen_finalize_stage2.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..00ed641d53beb94cc32ca281609b8a9d860e11d6 --- /dev/null +++ b/scripts/r5_freeze/gen_finalize_stage2.sbatch @@ -0,0 +1,28 @@ +#!/bin/bash +#SBATCH --job-name=r5_gen_final +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=2 +#SBATCH --mem=24G +#SBATCH --time=00:40:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# R5 GEN: merge the production parts into the manifests and write counts, realised statistics and production_done.json. +# usage: sbatch [--dependency=...] [--begin=...] r5_finalize.sbatch PLAN_JSON STAGE +# Safe to run again at any time (reads _parts, rewrites manifests; --keep-extra: no image is deleted). Stage 2 first copies the stage 1 manifests to manifests/stage1/. +CODE=/path/to/TURKIC_OCR_CODE/src/pagesynth +D=/path/to/TURKIC_OCR_DATA +PLAN=${1:-$D/tmp/r5_plan_stage1.json} +STAGE=${2:-1} +# Stage FREEZE, 21 Nov 2026: copy of src/pagesynth/scripts/r5_finalize.sbatch with ONE change: stage 2 writes its manifests to +# manifests_stage2/ instead of rewriting manifests/ (the frozen mix_v1 and the registry point to the stage-1 files there). +# Stage-2 lines are extra data for the leaders only (amendment 3.3 D2). Reports keep their stage-2 names (counts_stage2.json, +# realised_stats_stage2.json, production_done_stage2.json), so stage-1 reports are not overwritten. +M=$D/data/processed/r5/manifests_stage2 +mkdir -p $D/outputs/r5/gen_reports $M +if [ "$STAGE" != "1" ] && [ ! -d $M/stage1 ]; then + mkdir -p $M/stage1 + cp $M/synth_* $M/stage1/ 2>/dev/null +fi +/path/to/TURKIC_OCR_CODE/.venv_gen/bin/python $CODE/scripts/r5_finalize.py --out-root $D/data/processed/r5/synth --manifest-dir $M \ + --plan $PLAN --report-dir $D/outputs/r5/gen_reports --stage $STAGE --keep-extra diff --git a/scripts/r5_freeze/gen_mix_v1.py b/scripts/r5_freeze/gen_mix_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..9d2461148d95d7239fc7de4566065ddda47aa079 --- /dev/null +++ b/scripts/r5_freeze/gen_mix_v1.py @@ -0,0 +1,345 @@ +"""R5 FREEZE: writes mix_v1.yaml, the frozen training mix of round R5, from the recorded mix decision. + +Source of the shares: the project decision log key "mix_v1_decision", restated in the freeze plan, part A step 2: + hand_real kk 35; hand_real other Cyrillic 15 (HKR, CHD, school equally, at most 3 passes of a source per 1M samples); + hand_synth 35 = 30 equally over the 10 language-scripts + the 5 points of the empty hand_real Latin, split equally over + uz_latn, tr, az, tk; typed_synth 6 and typed_real 6, equal over the 10 language-scripts (a language-script without + print_real_train rows gives its typed_real part to its typed_synth); clutter 3. NOT from DATA's mix_v1_shares.json + (that file has typed_synth 12 and no typed_real; superseded). + +Every leaf points to a READ-ONLY copy in --frozen-dir (made by freeze_prep.sbatch before this script runs). The script checks: + - each frozen copy is byte-identical to its source in --source-dir and to the expected sha256 (GEN's production_done.json + for synth_*, PRINT's stated sha256 for print_real_train, DATA's manifest_stats.json for the real handwriting sets); + - each frozen copy and sidecar has no write bit; + - header = the 10 shared columns; every row has split train; every leaf has train rows after its filter; + - shares are exact fractions that sum to exactly 1; the 3-pass cap does not bind. +YAML layout (read by four parsers; see records/R5/FREEZE/schema.json): top-level key "components" (a list); a component is either +a LEAF (name, share, manifest, sha256, optional filter {lang: x}) or a GROUP (name, share, members = list of leaves with +ABSOLUTE shares that sum to the group's share). No top-level key may be one of mix, members, sources, manifests, items, +children, parts, strata, groups, entries, streams, shares, manifest, path, file, tsv. + +usage: python -I gen_mix_v1.py --frozen-dir DIR --source-dir DIR --out YAML --report JSON +Exit 0 = yaml written and re-read; any failed check: exit 2 and no yaml. +""" +import argparse +import csv +import hashlib +import json +import os +import stat +import sys +import time +from fractions import Fraction as F + +import yaml + +csv.field_size_limit(10 ** 9) +DATA = "/path/to/TURKIC_OCR_DATA" +R5 = DATA + "/data/processed/r5" +HDR = ["id", "image", "text", "lang", "script", "kind", "source", "split", "group", "unit"] +CYR = ["kk", "ky", "uz_cyrl", "tt", "ba", "sah"] +LAT = ["uz_latn", "tr", "az", "tk"] +LANGS = CYR + LAT +P_SHORT = 150000 +PRINT_TRAIN_SHA = "6fe8df2acc693637009150d00947153ab3a22b32c5dc1be1332c8e52b70d1f14" # PRINT final (01:45 UTC), re-hashed 01:35 UTC +MANIFESTS = ["kohtd_train", "hkr_train", "chd_train", "school_train", "synth_hand_train", "synth_typed_train", + "print_real_train", "synth_clutter_train"] +SIDECARS = {"synth_hand_train": "synth_hand_train.meta.tsv", "synth_typed_train": "synth_typed_train.meta.tsv", + "synth_clutter_train": "synth_clutter_train.meta.tsv"} +FORBIDDEN_TOP = {"mix", "members", "sources", "manifests", "items", "children", "parts", "strata", "groups", "entries", + "streams", "shares", "manifest", "path", "file", "tsv"} + + +def sha256(p): + h = hashlib.sha256() + with open(p, "rb") as f: + for b in iter(lambda: f.read(1 << 20), b""): + h.update(b) + return h.hexdigest() + + +def count_lines(p): + n = 0 + with open(p, "rb") as f: + for _ in f: + n += 1 + return n + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--frozen-dir", default=R5 + "/frozen_mix_v1") + ap.add_argument("--source-dir", default=R5 + "/manifests") + ap.add_argument("--out", required=True) + ap.add_argument("--report", required=True) + ap.add_argument("--data-root", default=DATA, help="tests only: replaces the DATA root for production_done.json and manifest_stats.json") + ap.add_argument("--print-sha", default=PRINT_TRAIN_SHA, help="tests only") + ap.add_argument("--dropped", default=None, help="dropped_rows.tsv of drop_rows.py (decision of 21 Nov, option B extended)") + ap.add_argument("--predrop-dir", default=None, help="copies of the frozen files as they were before the drop") + a = ap.parse_args() + problems = [] + expected = {} + drop_ids = {} + if a.dropped: + with open(a.dropped, encoding="utf-8", newline="") as f: + for r in csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE): + drop_ids.setdefault(r["manifest"], set()).add(r["id"]) + + def filtered_sha(path, ids): + h = hashlib.sha256() + with open(path, "rb") as fi: + h.update(fi.readline()) + for line in fi: + if line.split(b"\t", 1)[0].decode("utf-8") not in ids: + h.update(line) + return h.hexdigest() + pd = json.load(open(a.data_root + "/outputs/r5/gen_reports/production_done.json", encoding="utf-8")) + for k, v in pd["manifests"].items(): + expected[k[:-4]] = ("GEN production_done.json (stage 1, written %s)" % pd.get("written"), v["sha256"]) + ms = json.load(open(a.data_root + "/data/processed/r5/manifest_stats.json", encoding="utf-8")) + for k in ("kohtd_train", "hkr_train", "chd_train", "school_train"): + expected[k] = ("DATA manifest_stats.json (generated %s)" % ms.get("generated_utc"), ms["manifests"][k]["sha256"]) + expected["print_real_train"] = ("PRINT final, message of 21 Nov 01:45 UTC (6fe8df2a...)", a.print_sha) + + files = {} + for m in MANIFESTS: + fz = os.path.join(a.frozen_dir, m + ".tsv") + src = os.path.join(a.source_dir, m + ".tsv") + rec = {"frozen": fz, "source": src} + if not os.path.exists(fz): + problems.append("frozen copy missing: " + fz) + files[m] = rec + continue + rec["sha256"] = sha256(fz) + rec["source_sha256_now"] = sha256(src) if os.path.exists(src) else None + rec["expected_from"], rec["expected_sha256"] = expected.get(m, (None, None)) + rec["writable_bits"] = oct(os.stat(fz).st_mode & 0o222) + rec["source_now_equal (report only: GEN jobs may rewrite manifests/)"] = rec["sha256"] == rec["source_sha256_now"] + if m in drop_ids: + pre = os.path.join(a.predrop_dir, m + ".tsv") + rec["predrop"] = pre + rec["predrop_sha256"] = sha256(pre) + rec["rows_dropped"] = len(drop_ids[m]) + rec["expected_after_drop_sha256"] = filtered_sha(pre, drop_ids[m]) + if rec["predrop_sha256"] != rec["expected_sha256"]: + problems.append("%s: pre-drop copy sha256 %s differs from the expected %s (%s)" % (m, rec["predrop_sha256"], rec["expected_sha256"], rec["expected_from"])) + if rec["sha256"] != rec["expected_after_drop_sha256"]: + problems.append("%s: frozen copy is not the pre-drop copy minus exactly the %d listed ids" % (m, len(drop_ids[m]))) + elif rec["sha256"] != rec["expected_sha256"]: + problems.append("%s: frozen copy sha256 %s differs from the expected %s (%s)" % (m, rec["sha256"], rec["expected_sha256"], rec["expected_from"])) + if os.stat(fz).st_mode & 0o222: + problems.append("%s: frozen copy is writable" % m) + if m in SIDECARS: + sc = os.path.join(a.frozen_dir, SIDECARS[m]) + if not os.path.exists(sc): + problems.append("frozen sidecar missing: " + sc) + else: + rec["sidecar"] = sc + rec["sidecar_sha256"] = sha256(sc) + ssrc = os.path.join(a.source_dir, SIDECARS[m]) + rec["sidecar_source_sha256_now"] = sha256(ssrc) if os.path.exists(ssrc) else None + if m in drop_ids: + rec["sidecar_expected_after_drop_sha256"] = filtered_sha(os.path.join(a.predrop_dir, SIDECARS[m]), drop_ids[m]) + if rec["sidecar_sha256"] != rec["sidecar_expected_after_drop_sha256"]: + problems.append("%s: frozen sidecar is not the pre-drop sidecar minus the listed ids" % m) + else: + rec["sidecar_source_now_equal (report only)"] = rec["sidecar_sha256"] == rec["sidecar_source_sha256_now"] + if os.stat(sc).st_mode & 0o222: + problems.append("%s: frozen sidecar is writable" % m) + if count_lines(sc) != count_lines(fz): + problems.append("%s: sidecar line count differs from the manifest" % m) + # rows + by_lang, by_split, by_kind, page_rows, empty_nonclutter, bad_fields = {}, {}, {}, 0, 0, 0 + with open(fz, encoding="utf-8", newline="") as f: + rd = csv.reader(f, delimiter="\t", quoting=csv.QUOTE_NONE) + hdr = next(rd) + if hdr != HDR: + problems.append("%s: header %s is not the shared 10 columns" % (m, hdr)) + for r in rd: + if len(r) != len(HDR): + bad_fields += 1 + continue + d = dict(zip(HDR, r)) + by_split[d["split"]] = by_split.get(d["split"], 0) + 1 + by_kind[d["kind"]] = by_kind.get(d["kind"], 0) + 1 + if d["split"] == "train": + by_lang[d["lang"]] = by_lang.get(d["lang"], 0) + 1 + if d["unit"] == "page": + page_rows += 1 + if d["text"].strip() == "" and d["kind"] != "clutter": + empty_nonclutter += 1 + rec.update(train_rows_by_lang=by_lang, rows_by_split=by_split, rows_by_kind=by_kind, unit_page_rows=page_rows, + empty_text_nonclutter_rows=empty_nonclutter, rows_with_wrong_field_count=bad_fields) + if set(by_split) - {"train"}: + problems.append("%s: rows with split other than train: %s" % (m, by_split)) + if bad_fields: + problems.append("%s: %d rows with a wrong field count" % (m, bad_fields)) + if page_rows or empty_nonclutter: + problems.append("%s: %d page rows and %d empty non-clutter texts (the line parser would drop them, the VLM parser not)" % (m, page_rows, empty_nonclutter)) + files[m] = rec + if problems: + json.dump({"status": "FAIL", "problems": problems, "files": files}, open(a.report, "w", encoding="utf-8"), indent=1, ensure_ascii=False) + print("FAIL", *problems, sep="\n ") + sys.exit(2) + + def n_train(m, lang=None): + bl = files[m]["train_rows_by_lang"] + return sum(bl.values()) if lang is None else bl.get(lang, 0) + + # ------------------------------------------------------------------ shares (exact fractions) + notes = [] + comps = [] + comps.append({"name": "hand_real_kk", "stream": "hand_real", "share": F(35, 100), "leaf": ("kohtd_train", None), + "description": "KOHTD train word crops (Kazakh handwriting, form split K1 v1, after DATA's dedupe)"}) + other = [] + for m, desc in (("hkr_train", "HKR train words (Russian and Kazakh handwriting)"), + ("chd_train", "Cyrillic Handwriting Dataset train words (Russian)"), + ("school_train", "School notebooks train word crops (Russian)")): + s = F(15, 100) / 3 + cap = F(3 * n_train(m), 10 ** 6) + if s > cap: + problems.append("3-pass cap binds for %s (%d rows): share %s > cap %s; the decision does not say where the rest goes" % (m, n_train(m), float(s), float(cap))) + other.append({"name": m, "share": s, "leaf": (m, None), "description": desc, + "cap_3_passes_per_1M_share": float(cap), "cap_binds": s > cap}) + comps.append({"name": "hand_real_other_cyrillic", "stream": "hand_real", "share": F(15, 100), "members": other, + "description": "real Cyrillic handwriting other than KOHTD: HKR, CHD and school notebooks equally"}) + hs = [] + for lang in LANGS: + s = F(30, 100) / 10 + (F(5, 100) / 4 if lang in LAT else 0) + if n_train("synth_hand_train", lang) == 0: + problems.append("synth_hand_train has no train rows for " + lang) + hs.append({"name": "hand_synth_" + lang, "share": s, "leaf": ("synth_hand_train", lang), + "description": "synthetic handwriting lines, %s%s" % (lang, " (3 points + 1.25 moved from the empty hand_real Latin)" if lang in LAT else "")}) + comps.append({"name": "hand_synth", "stream": "hand_synth", "share": sum(x["share"] for x in hs), "members": hs, + "description": "synthetic handwriting lines (GEN generator 0.3.0, stage 1): 30 points equally over the 10 language-scripts plus the 5 points of the empty hand_real Latin split equally over uz_latn, tr, az, tk"}) + ts, tr_ = [], [] + for lang in LANGS: + s_syn, s_real = F(6, 1000), F(6, 1000) + if n_train("synth_typed_train", lang) == 0: + problems.append("synth_typed_train has no train rows for " + lang) + if n_train("print_real_train", lang) == 0: + notes.append("print_real_train has no train rows for %s: its typed_real 0.006 moves to typed_synth %s" % (lang, lang)) + s_syn, s_real = s_syn + s_real, F(0) + ts.append({"name": "typed_synth_" + lang, "share": s_syn, "leaf": ("synth_typed_train", lang), + "description": "synthetic typed lines, " + lang}) + if s_real > 0: + tr_.append({"name": "typed_real_" + lang, "share": s_real, "leaf": ("print_real_train", lang), + "description": "real printed lines from born-digital PDFs (exact text layer), " + lang}) + comps.append({"name": "typed_synth", "stream": "typed_synth", "share": sum(x["share"] for x in ts), "members": ts, + "description": "synthetic typed lines, equal over the 10 language-scripts"}) + if tr_: + comps.append({"name": "typed_real", "stream": "typed_real", "share": sum(x["share"] for x in tr_), "members": tr_, + "description": "real printed lines (stage PRINT's print_real_train), equal over the language-scripts that have them"}) + comps.append({"name": "clutter", "stream": "clutter", "share": F(3, 100), "leaf": ("synth_clutter_train", None), + "description": "clutter crops with no text (diagrams, stamps, ruling); the target is the empty string"}) + total = sum(c["share"] for c in comps) + if total != 1: + problems.append("shares sum to %s, not 1" % total) + for c in comps: + if "members" in c and sum(x["share"] for x in c["members"]) != c["share"]: + problems.append("group %s: members do not sum to the group share" % c["name"]) + if problems: + json.dump({"status": "FAIL", "problems": problems, "files": files}, open(a.report, "w", encoding="utf-8"), indent=1, ensure_ascii=False) + print("FAIL", *problems, sep="\n ") + sys.exit(2) + + # ------------------------------------------------------------------ yaml text + def fnum(x): + v = float(x) + if F(repr(v)) != x: + raise SystemExit("share %s is not exactly representable as a short decimal" % x) + return repr(v) + + def leaf_lines(ind, node): + m, lang = node["leaf"] + r = files[m] + out = ["%sshare: %s" % (ind, fnum(node["share"])), + "%smanifest: %s" % (ind, r["frozen"]), + "%ssha256: %s" % (ind, r["sha256"])] + if lang: + out += ["%sfilter:" % ind, "%s lang: \"%s\"" % (ind, lang)] + out.append("%strain_rows: %d" % (ind, n_train(m, lang))) + if "sidecar" in r: + out += ["%smeta_sidecar: %s" % (ind, r["sidecar"]), "%smeta_sidecar_sha256: %s" % (ind, r["sidecar_sha256"])] + out.append("%sdescription: \"%s\"" % (ind, node["description"])) + return out + + now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) + L = ["# mix_v1: the frozen training mix of round R5 (written by stage FREEZE with CODE/scripts/r5_freeze/gen_mix_v1.py).", + "# Shares are fractions of all training samples; a group's members carry ABSOLUTE shares that sum to the group's share.", + "# Every manifest is a read-only copy in the frozen folder; sha256 values are checked by build_sequence.py and build_ktrain.py.", + "# Only rows with split = train are used. Filter {lang: x} keeps the rows of one language-script.", + "mix_name: mix_v1", + "written_utc: \"%s\"" % now, + "decision: \"the project decision log key mix_v1_decision: hand_real kk 35, hand_real other Cyrillic 15, hand_synth 35 (30 + 5 from the empty hand_real Latin to uz_latn/tr/az/tk), typed_synth 6, typed_real 6, clutter 3\"", + "frozen_dir: %s" % a.frozen_dir] + if drop_ids: + L.append("dropped_rows: \"%s; list %s\"" % (", ".join("%s -%d rows" % (m, len(v)) for m, v in sorted(drop_ids.items())), os.path.abspath(a.dropped))) + L.append("dropped_rule: \"decision of 21 Nov 2026: synthetic train rows that are near-duplicate images of synthetic val/test rows with the same label, or whose label equals a synthetic val/test line of at least 20 characters, are removed from the frozen copies only\"") + L.append("components:") + for c in comps: + L.append(" - name: %s" % c["name"]) + L.append(" stream: %s" % c["stream"]) + if "members" in c: + L.append(" share: %s" % fnum(c["share"])) + L.append(" description: \"%s\"" % c["description"]) + L.append(" members:") + for x in c["members"]: + L.append(" - name: %s" % x["name"]) + L += leaf_lines(" ", x) + else: + L += leaf_lines(" ", c) + text = "\n".join(L) + "\n" + doc = yaml.safe_load(text) + if set(doc) & FORBIDDEN_TOP: + raise SystemExit("forbidden top-level key") + # re-read check: walk the parsed yaml and compare with the exact shares + got = {} + for c in doc["components"]: + if "members" in c: + for x in c["members"]: + got[x["name"]] = (x["share"], x["manifest"], x.get("filter")) + else: + got[c["name"]] = (c["share"], c["manifest"], c.get("filter")) + want = {} + for c in comps: + for x in (c["members"] if "members" in c else [c]): + want[x["name"]] = x + assert set(got) == set(want), (set(got) ^ set(want)) + for k, x in want.items(): + assert F(repr(got[k][0])) == x["share"], k + assert got[k][1] == files[x["leaf"][0]]["frozen"], k + assert (got[k][2] or {}).get("lang") == x["leaf"][1], k + assert isinstance((got[k][2] or {}).get("lang", ""), str), k + os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True) + tmp = a.out + ".part%d" % os.getpid() + with open(tmp, "w", encoding="utf-8") as f: + f.write(text) + os.replace(tmp, a.out) + + leaves = [] + for c in comps: + for x in (c["members"] if "members" in c else [c]): + m, lang = x["leaf"] + n = n_train(m, lang) + leaves.append({"name": x["name"], "stream": c["stream"], "group": c["name"], "share": float(x["share"]), + "share_exact": str(x["share"]), "manifest": files[m]["frozen"], "filter_lang": lang, "train_rows": n, + "samples_per_1M": round(float(x["share"]) * 1e6), "passes_per_1M_samples": round(float(x["share"]) * 1e6 / n, 3), + "samples_in_P_short_150000": round(float(x["share"]) * P_SHORT, 1), + "passes_in_P_short": round(float(x["share"]) * P_SHORT / n, 4)}) + streams = {} + for lf in leaves: + streams[lf["stream"]] = streams.get(lf["stream"], F(0)) + F(lf["share_exact"]) + rep = {"status": "OK", "written_utc": now, "yaml": os.path.abspath(a.out), "yaml_sha256": sha256(a.out), + "share_source": "the project decision log key mix_v1_decision (not records/R5/DATA/mix_v1_shares.json, which is superseded)", + "per_stream_fractions": {k: float(v) for k, v in streams.items()}, + "per_stream_exact": {k: str(v) for k, v in streams.items()}, + "sum_exact": str(sum(streams.values())), "sum_is_exactly_1": sum(streams.values()) == 1, + "per_component": {c["name"]: float(c["share"]) for c in comps}, "leaves": leaves, "n_leaves": len(leaves), + "notes": notes, "dropped_rows_by_manifest": {m: len(v) for m, v in drop_ids.items()}, "dropped_list": a.dropped, "files": files} + json.dump(rep, open(a.report, "w", encoding="utf-8"), indent=1, ensure_ascii=False) + print("OK", a.out, rep["yaml_sha256"], json.dumps(rep["per_stream_fractions"]), "sum", rep["sum_exact"], "leaves", len(leaves)) + + +if __name__ == "__main__": + main() diff --git a/scripts/r5_freeze/make_endpoints.py b/scripts/r5_freeze/make_endpoints.py new file mode 100644 index 0000000000000000000000000000000000000000..917286795e4c55d387c9516008826f574fbf9405 --- /dev/null +++ b/scripts/r5_freeze/make_endpoints.py @@ -0,0 +1,32 @@ +"""R5 FREEZE: endpoints.json for the scorer = EVALCODE's endpoints_proposal.json with three settings filled (freeze plan part B step 7): + T2.audited_languages = the language-scripts of PRINT's audit with at least 49 of 50 test lines matching, label 'checked by machine viewing'; + reader_only_counts_as_pipeline = true (clarification H6 of amendment 3.3); + confirmed = true. +Nothing else is changed. usage: python -I make_endpoints.py PROPOSAL_JSON PRINT_AUDIT_JSON OUT_JSON +""" +import json +import sys +import time + +prop_p, audit_p, out_p = sys.argv[1:4] +e = json.load(open(prop_p, encoding="utf-8")) +au = json.load(open(audit_p, encoding="utf-8")) +now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) +langs, detail = [], {} +for lang, v in sorted(au["languages"].items()): + fin = v["final"] + ok = bool(fin.get("audited")) and fin["matches"] >= 49 and fin["sample_size"] == 50 + detail[lang] = "%d/%d%s" % (fin["matches"], fin["sample_size"], "" if ok else " (not audited)") + if ok: + langs.append(lang) +e["T2"]["audited_languages"] = langs +e["T2"]["audited_languages_label"] = "checked by machine viewing (the PRINT stage compared 50 test crops per language-script with their labels), not by a human" +e["T2"]["audited_languages_source"] = "records/R5/PRINT/audit.json key languages..final (threshold: at least 49 of 50 exact): " + ", ".join("%s %s" % kv for kv in detail.items()) +e["reader_only_counts_as_pipeline"] = True +e["reader_only_counts_as_pipeline_source"] = "clarification H6 of amendment 3.3 (records/R5/RULE/j11_v3_3_clarifications_2.txt): if no full pipeline memory is measured, gate G uses reader peak memory plus the detector chosen on validation; if the detector figure is missing, the reader figure alone is used and labelled 'reader only; detector not added'" +e["confirmed"] = True +e["confirmed_by"] = "stage FREEZE (freeze plan part B step 7)" +e["confirmed_utc"] = now +e["status"] = "CONFIRMED %s before any arm trained on mix_v1 (audited languages fixed before training, version 3); proposal by EVALCODE" % now +json.dump(e, open(out_p, "w", encoding="utf-8"), indent=2, ensure_ascii=False) +print("audited", langs, detail) diff --git a/scripts/r5_freeze/merge_evalsets.py b/scripts/r5_freeze/merge_evalsets.py new file mode 100644 index 0000000000000000000000000000000000000000..483d99f38504dffbcc0ca36fdef380bf82f5e5fc --- /dev/null +++ b/scripts/r5_freeze/merge_evalsets.py @@ -0,0 +1,97 @@ +"""R5 FREEZE: after DATA's r5_registry.py rewrote evalsets.json from its own list, put back the sets it dropped. + +Dropped by design (r5_registry.py writes a fixed list): PRINT's print_real_val / print_real_test / more_real_print +(evalsets_extra_print.json), REF's kohtd_rand_test, and curve_v1 if it was registered. Every set that was in the registry before +the rewrite (BEFORE) and is missing now is added back unchanged, except that n_rows and manifest_sha256 are re-measured from the +manifest; a difference is logged (and the measured values are written, so the registry matches the file on disk). +PRINT's entries are taken from evalsets_extra_print.json when present there. Checks: every split=test set is locked; every set +locked BEFORE is still locked; no duplicate names. Also marks DATA's mix_v1_shares.json as superseded (key added, nothing removed). +usage: python -I merge_evalsets.py BEFORE_JSON REGISTRY_JSON EXTRA_PRINT_JSON SHARES_JSON LOG_JSON +""" +import hashlib +import json +import os +import sys +import time + +before_p, reg_p, extra_p, shares_p, log_p = sys.argv[1:6] + + +def sha(p): + h = hashlib.sha256() + with open(p, "rb") as f: + for b in iter(lambda: f.read(1 << 20), b""): + h.update(b) + return h.hexdigest() + + +def nrows(p): + with open(p, "rb") as f: + return sum(1 for _ in f) - 1 + + +now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) +before = json.load(open(before_p, encoding="utf-8")) +reg = json.load(open(reg_p, encoding="utf-8")) +extra = json.load(open(extra_p, encoding="utf-8")) if os.path.exists(extra_p) else {"sets": []} +extra_by = {s["name"]: s for s in extra.get("sets", [])} +log = {"written_utc": now, "registry": reg_p, "registry_sha256_from_r5_registry": sha(reg_p), "before": before_p, + "added_back": [], "measured_differs": [], "problems": []} +names = [s["name"] for s in reg["sets"]] +if len(names) != len(set(names)): + log["problems"].append("duplicate names in the rewritten registry") +have = set(names) +for s in before["sets"]: + if s["name"] in have: + continue + e = dict(extra_by.get(s["name"], s)) + src = "evalsets_extra_print.json" if s["name"] in extra_by else "registry before the rewrite" + m = e.get("manifest") + if m and os.path.exists(m): + got_sha, got_n = sha(m), nrows(m) + if got_sha != e.get("manifest_sha256") or got_n != e.get("n_rows"): + log["measured_differs"].append({"name": e["name"], "entry_sha256": e.get("manifest_sha256"), "file_sha256": got_sha, + "entry_rows": e.get("n_rows"), "file_rows": got_n}) + e["manifest_sha256"], e["n_rows"] = got_sha, got_n + e["remeasured_by_freeze_utc"] = now + elif m: + log["problems"].append("manifest of %s is missing: %s" % (e["name"], m)) + if s.get("locked"): + e["locked"] = True + reg["sets"].append(e) + have.add(e["name"]) + log["added_back"].append({"name": e["name"], "from": src, "locked": e.get("locked"), "split": e.get("split")}) +for nm in extra_by: + if nm not in have: + reg["sets"].append(extra_by[nm]) + have.add(nm) + log["added_back"].append({"name": nm, "from": "evalsets_extra_print.json (not in the registry before)", "locked": extra_by[nm].get("locked")}) +locked_before = {s["name"] for s in before["sets"] if s.get("locked")} +for s in reg["sets"]: + if s.get("split") == "test" and not s.get("locked"): + log["problems"].append("test set not locked: " + s["name"]) + if s["name"] in locked_before and not s.get("locked"): + log["problems"].append("set was locked before and is not now: " + s["name"]) +log["sets_now"] = [{"name": s["name"], "split": s.get("split"), "locked": s.get("locked"), "status": s.get("status", "")[:30], + "n_rows": s.get("n_rows"), "manifest_sha256": s.get("manifest_sha256")} for s in reg["sets"]] +log["dropped_for_good"] = sorted({s["name"] for s in before["sets"]} - have) +reg["merged_by_freeze_utc"] = now +reg["merge_note"] = "stage FREEZE re-added sets dropped by r5_registry.py: " + ", ".join(x["name"] for x in log["added_back"]) +tmp = reg_p + ".tmp%d" % os.getpid() +with open(tmp, "w", encoding="utf-8") as f: + json.dump(reg, f, ensure_ascii=False, indent=1) +os.replace(tmp, reg_p) +log["registry_sha256_after_merge"] = sha(reg_p) +if os.path.exists(shares_p): + sh = json.load(open(shares_p, encoding="utf-8")) + sh["SUPERSEDED"] = ("superseded on %s by the mix_v1_decision (the project decision log): typed_synth 0.06 + typed_real 0.06 " + "(print_real_train) instead of typed_synth 0.12; the frozen shares are in DATA/data/processed/r5/mix_v1.yaml and " + "records/R5/FREEZE/gen_report.json" % now) + tmp = shares_p + ".tmp%d" % os.getpid() + with open(tmp, "w", encoding="utf-8") as f: + json.dump(sh, f, ensure_ascii=False, indent=1) + os.replace(tmp, shares_p) + log["shares_marked_superseded"] = shares_p +json.dump(log, open(log_p, "w", encoding="utf-8"), ensure_ascii=False, indent=1) +print("merge", "OK" if not log["problems"] else "PROBLEMS", json.dumps({k: log[k] for k in ("added_back", "measured_differs", "problems", "dropped_for_good")}, ensure_ascii=False)) +sys.exit(0 if not log["problems"] else 3) diff --git a/scripts/r5_freeze/repoint_evalsets.py b/scripts/r5_freeze/repoint_evalsets.py new file mode 100644 index 0000000000000000000000000000000000000000..91fd93a184b43a527fc1b4a4b938b2d7a01ca6d6 --- /dev/null +++ b/scripts/r5_freeze/repoint_evalsets.py @@ -0,0 +1,58 @@ +"""R5 FREEZE: point the registry entries synth_{hand,typed,clutter,pages}_{val,test} at their read-only copies in frozen_eval_v1/ +(decision 4, 21 Nov 2026), so evaluation sets cannot change when GEN jobs rewrite manifests/. A path is changed only if +the copy's sha256 equals the entry's manifest_sha256; the old path is kept in 'manifest_original'. Every other entry is unchanged. +Note: DATA's r5_registry.py rewrites evalsets.json from manifests/; if it is ever run again, run this script and merge_evalsets.py again. +usage: python -I repoint_evalsets.py REGISTRY_JSON FROZEN_EVAL_DIR LOG_JSON +""" +import hashlib +import json +import os +import sys +import time + +reg_p, fe, log_p = sys.argv[1:4] +NAMES = ["synth_%s_%s" % (k, s) for k in ("hand", "typed", "clutter", "pages") for s in ("val", "test")] + + +def sha(p): + h = hashlib.sha256() + with open(p, "rb") as f: + for b in iter(lambda: f.read(1 << 20), b""): + h.update(b) + return h.hexdigest() + + +now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) +reg = json.load(open(reg_p, encoding="utf-8")) +log = {"written_utc": now, "registry": reg_p, "registry_sha256_before": sha(reg_p), "changed": [], "problems": []} +by = {s["name"]: s for s in reg["sets"]} +for n in NAMES: + s = by.get(n) + cp = os.path.join(fe, n + ".tsv") + if s is None: + log["problems"].append("registry has no " + n) + continue + h = sha(cp) + if h != s.get("manifest_sha256"): + log["problems"].append("%s: copy sha256 %s differs from the registry %s" % (n, h, s.get("manifest_sha256"))) + continue + if os.stat(cp).st_mode & 0o222: + log["problems"].append(n + ": copy is writable") + continue + if s["manifest"] != cp: + s["manifest_original"] = s["manifest"] + s["manifest"] = cp + s["frozen_copy"] = "read-only copy made by stage FREEZE %s; equal to GEN production_done.json stage 1" % now + log["changed"].append({"name": n, "manifest": cp, "sha256": h, "locked": s.get("locked")}) +if log["problems"]: + json.dump(log, open(log_p, "w", encoding="utf-8"), indent=1) + print("PROBLEMS", log["problems"]) + sys.exit(3) +reg["frozen_eval_note"] = "synth_*_val/test entries point to read-only copies in %s (stage FREEZE, %s)" % (fe, now) +tmp = reg_p + ".tmp%d" % os.getpid() +with open(tmp, "w", encoding="utf-8") as f: + json.dump(reg, f, ensure_ascii=False, indent=1) +os.replace(tmp, reg_p) +log["registry_sha256_after"] = sha(reg_p) +json.dump(log, open(log_p, "w", encoding="utf-8"), indent=1) +print("OK", len(log["changed"]), "entries repointed", log["registry_sha256_after"]) diff --git a/scripts/r5_freeze_curve.sh b/scripts/r5_freeze_curve.sh new file mode 100644 index 0000000000000000000000000000000000000000..46ddebc1edae0d02c6852e801c0353f11ea976ad --- /dev/null +++ b/scripts/r5_freeze_curve.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# R5 EVALCODE: the FINAL, complete build of the fixed learning-curve set curve_v1 (rule: build it once by 05:45 UTC on 21 Nov from the parts that exist, +# freeze it at the mix freeze, never rebuild it after the first run starts; a part missing now is left out for good). +# It reads three small validation manifests (about 1 second), so it is run directly, not queued behind the ZEN4 backlog. Prints the sha256 and the row counts by part. +# Writes DATA/data/processed/r5/manifests/curve_v1.tsv, curve_v1_info.json, curve_v1_frozen.json and registers curve_v1 in evalsets.json. +# After DATA's r5_registry.py rewrote evalsets.json, run: CODE/.venv_kraken/bin/python -I CODE/scripts/r5eval/build_curve_set.py --register-only +C=/path/to/TURKIC_OCR_CODE +D=/path/to/TURKIC_OCR_DATA +$C/.venv_kraken/bin/python -I $C/scripts/r5eval/build_curve_set.py --final && cat $D/data/processed/r5/curve_v1_frozen.json diff --git a/scripts/r5_gate/gate_backup.sbatch b/scripts/r5_gate/gate_backup.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..5b467f40e747729f63f7ae3968af12983699e1ab --- /dev/null +++ b/scripts/r5_gate/gate_backup.sbatch @@ -0,0 +1,47 @@ +#!/bin/bash +#SBATCH --job-name=r5_gate_backup +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=1 +#SBATCH --mem=1G +#SBATCH --time=00:10:00 +#SBATCH --begin=2026-11-24T17:00:05 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# R5 backup writer of the test-pass gate file (clarification J10, records/R5/RULE/j12_v3_4_clarifications_3.txt). +# --begin is cluster local time (+05): 17:00:05 there is 12:00:05 UTC on 24 Nov 2026. +# eval_vlm_test.py, score.py, LINEDET and REF only check that the gate file exists, so this script checks the clock +# itself and never writes before 12:00:00 UTC, whenever Slurm happens to start it. +# Exclusive create (noclobber): a gate file already written by hand is left alone, because +# eval_vlm_test.py records the gate file's sha256 in every meta and a rewrite would break those records. +# GATE_TEST_DIR and GATE_OPEN_UTC exist only for the dry tests in DATA/tmp; the real jobs set neither. +# GATE_MAX_WAIT (seconds, default 120): the second real copy is submitted hours early without --begin and sleeps +# until 12:00:00 UTC, so that a full ZEN4 queue at noon cannot delay the gate. +set -u +D=${GATE_TEST_DIR:-/path/to/TURKIC_OCR_DATA/outputs/r5} +OPEN=$(date -u -d "${GATE_OPEN_UTC:-2026-11-24T12:00:00Z}" +%s) || { echo "bad open time; nothing written"; exit 2; } +NOW=$(date -u +%s) +if [ "$NOW" -lt "$OPEN" ]; then + W=$((OPEN - NOW)) + if [ "$W" -gt "${GATE_MAX_WAIT:-120}" ]; then + echo "$(date -u +%FT%TZ) refused: $W s before the opening time; nothing written" + exit 1 + fi + sleep $((W + 1)) +fi +if [ "$(date -u +%s)" -lt "$OPEN" ]; then + echo "$(date -u +%FT%TZ) refused: clock still before the opening time; nothing written" + exit 1 +fi +T=$(date -u +%FT%TZ) +set -o noclobber +for P in "$D/RULE/test_pass_started.txt" "$D/linedet/test_pass_started.txt" "$D/ref/test_pass_started.txt"; do + if [ -e "$P" ]; then + echo "$T exists, left alone: $P :: $(head -c 300 "$P")" + elif printf 'R5 test pass started %s (UTC). Written by the backup gate job %s on %s (clarification J10, records/R5/RULE/j12_v3_4_clarifications_3.txt; gate of J9, records/R5/RULE/j11_v3_4_clarifications_2.txt).\n' \ + "$T" "${SLURM_JOB_ID:-none}" "$(hostname -s)" > "$P"; then + echo "$T written: $P sha256 $(sha256sum "$P" | cut -c1-64)" + else + echo "$T not written (created by another writer at the same moment): $P" + fi +done diff --git a/scripts/r5_gate/select_dryrun.sbatch b/scripts/r5_gate/select_dryrun.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..760f91de084d31d6840bd63259516de7f9b87cbf --- /dev/null +++ b/scripts/r5_gate/select_dryrun.sbatch @@ -0,0 +1,21 @@ +#!/bin/bash +#SBATCH --job-name=r5_select_dryrun +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=4 +#SBATCH --mem=48G +#SBATCH --time=00:30:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# Dry run of select_b1b2.py on the validation scores present now, with the same arguments as +# r5_select_verdict.sbatch select. It writes to DATA/tmp, never to DATA/outputs/r5/selection.json, which the +# test-pass runner reads. Validation only, not hashed into records/R5/RULE; it is not the J7 selection. +C=/path/to/TURKIC_OCR_CODE +D=/path/to/TURKIC_OCR_DATA +TSV=$C/scripts/r5_vlma/models_r5.tsv,$C/scripts/r5_vlmb/models_r5_vlmb.tsv +AI="" +if [ -f $D/outputs/r5/arms_info.json ]; then AI="--arms-info $D/outputs/r5/arms_info.json"; fi +O=$D/tmp/selection_dryrun_$(date -u +%Y%m%dT%H%MZ).json +$C/.venv_kraken/bin/python -I $C/scripts/r5eval/select_b1b2.py --scores $D/outputs/r5/scores --preds $D/outputs/r5/preds --out $O \ + --models-tsv $TSV --vlm-arms "${VLM_EXTRA:-}" $AI +echo "out $O" diff --git a/scripts/r5_ktrain.sbatch b/scripts/r5_ktrain.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..22ee059638c7fe5c269726b7a6ad2f7a63d47a44 --- /dev/null +++ b/scripts/r5_ktrain.sbatch @@ -0,0 +1,14 @@ +#!/bin/bash +#SBATCH --job-name=r5_ktrain +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=4 +#SBATCH --mem=48G +#SBATCH --time=01:00:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# R5 EVALCODE: builds and hashes K_train (clarification G3) from the train manifests of the FROZEN mix_v1.yaml and the generator's train text. +# Run once, after the freeze. Reads training text only. Output: DATA/data/processed/r5/p2/ktrain_manifest.json and three key files. +C=/path/to/TURKIC_OCR_CODE +D=/path/to/TURKIC_OCR_DATA +$C/.venv_kraken/bin/python -I $C/scripts/r5eval/build_ktrain.py --mix $D/data/processed/r5/mix_v1.yaml --out $D/data/processed/r5/p2 diff --git a/scripts/r5_ktrain_scratch.sbatch b/scripts/r5_ktrain_scratch.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..ae220957ab4a274a0570dbf5d304ebe854a3d4c6 --- /dev/null +++ b/scripts/r5_ktrain_scratch.sbatch @@ -0,0 +1,19 @@ +#!/bin/bash +#SBATCH --job-name=r5_ktrain_scratch +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=4 +#SBATCH --mem=48G +#SBATCH --time=01:00:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# R5 EVALCODE: time and size check of build_ktrain.py on the real TRAIN manifests (scratch mix, not mix_v1) and the generator's train text. +# Reads training text only. Output under DATA/tmp/evalcode_ktrain_scratch; then loads it back and prints sizes, time and a slice-flag example. +C=/path/to/TURKIC_OCR_CODE +D=/path/to/TURKIC_OCR_DATA +S=$C/.venv_kraken/bin/python +date -u +$S -I $C/scripts/r5eval/build_ktrain.py --mix $C/config_r5eval/mix_scratch.yaml --out $D/tmp/evalcode_ktrain_scratch +date -u +ls -la $D/tmp/evalcode_ktrain_scratch +sacct -j $SLURM_JOB_ID --format=JobID,Elapsed,MaxRSS,State diff --git a/scripts/r5_linedet/blla_stage2.sh b/scripts/r5_linedet/blla_stage2.sh new file mode 100644 index 0000000000000000000000000000000000000000..03495f1a364cf774751f03dee45b4a36a4db07ee --- /dev/null +++ b/scripts/r5_linedet/blla_stage2.sh @@ -0,0 +1,17 @@ +#!/bin/bash +# kraken BLLA stage 2: continue from the best stage-1 weights on school + generator pages. +set -eu +DATA=/path/to/TURKIC_OCR_DATA +CK=$DATA/checkpoints/r5/linedet +DP=$DATA/data/processed/r5_linedet_det +KET=/path/to/TURKIC_OCR_CODE/.venv_kraken/bin/ketos +export PYTHONNOUSERSITE=1 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True +BEST=$(ls -t $CK/blla_s1/model/best_*.safetensors 2>/dev/null | head -1 || true) +if [ -z "$BEST" ]; then BEST=$(ls -t $CK/blla_s1/model/checkpoint_*.ckpt | head -1); fi +echo "stage-1 weights: $BEST" +mkdir -p $CK/blla_s2 +$KET -d cuda:0 --workers 6 --precision bf16-mixed segtrain -f page \ + -t $DP/xml2/school_train/list.txt -t $DP/xml2/gen_train/list.txt \ + -e $DP/xml2/school_val/list.txt -e $DP/xml2/gen_val/list.txt \ + -i $BEST --resize union -q fixed -N ${BLLA_EPOCHS:-3} -r 5e-5 --schedule cosine --cos-max ${BLLA_EPOCHS:-3} --cos-min-lr 1e-6 --warmup 50 --augment \ + -o $CK/blla_s2/model diff --git a/scripts/r5_linedet/curve_post.sbatch b/scripts/r5_linedet/curve_post.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..9e2ba90ec015dacf01c509e43c2e76198b27c781 --- /dev/null +++ b/scripts/r5_linedet/curve_post.sbatch @@ -0,0 +1,16 @@ +#!/bin/bash +#SBATCH --job-name=r5_ld_curvepost +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=16 +#SBATCH --mem=32G +#SBATCH --time=03:00:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# After the GPU job: greedy scoring of every learning-curve checkpoint that has no curve_v1.tsv yet (CPU). +CODE=/path/to/TURKIC_OCR_CODE +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN +export OMP_NUM_THREADS=8 MKL_NUM_THREADS=8 +for ARM in A1 A2 A3 A4 A1s; do + $CODE/.venv_kraken/bin/python -I -m linedet.curve_score --arm $ARM --device cpu --workers 6 +done diff --git a/scripts/r5_linedet/det_prep_school.sbatch b/scripts/r5_linedet/det_prep_school.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..a53354a1de3b9cd7dd798bed3d8a633b885de8c9 --- /dev/null +++ b/scripts/r5_linedet/det_prep_school.sbatch @@ -0,0 +1,12 @@ +#!/bin/bash +#SBATCH --job-name=r5_ld_detprep +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=12 +#SBATCH --mem=32G +#SBATCH --time=01:30:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +CODE=/path/to/TURKIC_OCR_CODE +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN +$CODE/.venv_kraken/bin/python -I -m linedet.det_prep school --workers 12 diff --git a/scripts/r5_linedet/env_setup.sbatch b/scripts/r5_linedet/env_setup.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..95c84b784f0703a7d5dd10d3395027d7f91db710 --- /dev/null +++ b/scripts/r5_linedet/env_setup.sbatch @@ -0,0 +1,10 @@ +#!/bin/bash +#SBATCH --job-name=r5_ld_env +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=8 +#SBATCH --mem=24G +#SBATCH --time=01:00:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +bash /path/to/TURKIC_OCR_CODE/scripts/r5_linedet/env_setup.sh diff --git a/scripts/r5_linedet/env_setup.sh b/scripts/r5_linedet/env_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..a477e31d752abf4edba5c331653eee70fcd02dcd --- /dev/null +++ b/scripts/r5_linedet/env_setup.sh @@ -0,0 +1,19 @@ +#!/bin/bash +# R5 LINEDET: create the kraken + ultralytics uv environment (plain shell). Run on a compute node (CPU job). +set -eu +UV=$HOME/.local/bin/uv +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +VENV=$CODE/.venv_kraken +export UV_CACHE_DIR=$DATA/tmp/uv_cache +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN +mkdir -p $UV_CACHE_DIR $DATA/outputs/r5/linedet +$UV venv $VENV --python 3.12 +# torch 2.11.0 cu128 build: same as the working .venv and .venv_vlm on the H100 nodes +$UV pip install --python $VENV/bin/python --index-url https://download.pytorch.org/whl/cu128 torch==2.11.0 torchvision==0.26.0 +$UV pip install --python $VENV/bin/python kraken==7.2 +$UV pip install --python $VENV/bin/python ultralytics pyyaml +$UV pip install --python $VENV/bin/python kenlm 2>&1 | tail -5 || echo "kenlm module did not build" +$UV pip freeze --python $VENV/bin/python > $DATA/outputs/r5/linedet/pip_freeze_kraken_env.txt +$UV pip list --python $VENV/bin/python | grep -i -E "^(torch|torchvision|kraken|ultralytics|lightning|pytorch-lightning|numpy|pillow|kenlm|safetensors|opencv|shapely|scikit-image) " +echo "[env] done" diff --git a/scripts/r5_linedet/ext_selftest.sh b/scripts/r5_linedet/ext_selftest.sh new file mode 100644 index 0000000000000000000000000000000000000000..11351a8f336ac4f438454842cd26e4539709132a --- /dev/null +++ b/scripts/r5_linedet/ext_selftest.sh @@ -0,0 +1,20 @@ +#!/bin/bash +# Self-test of the extension mode (amendment 3.4 E5) on the KOHTD smoke data with arm A3 on CPU: (1) the sample target comes first, (2) the time budget comes first. +set -u +DATA=/path/to/TURKIC_OCR_DATA +LD=$DATA/outputs/r5/linedet +PY=/path/to/TURKIC_OCR_CODE/.venv_kraken/bin/python +SM=$DATA/data/processed/r5_linedet_smoke +T=$DATA/tmp/extselftest +rm -rf $T; mkdir -p $T +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN +for CASE in samples time; do + if [ $CASE = samples ]; then TGT=8320; MS=600; else TGT=1000000; MS=100; fi + echo "== case $CASE (extend_to $TGT, max_seconds $MS)" + $PY -I -m linedet.train_arm --arm A3 --mix $SM/smoke_mix.yaml --codec $LD/smoke/codec_union.json --seed 1 --workers 2 --device cpu --log_every 5 \ + --resume_from $LD/smoke_gpu3/ckpt/A3/resume.pt --extend_to $TGT --ext_peak_lr 5e-4 --max_seconds $MS --ckpt_dir $T/$CASE --log_dir $T/$CASE/logs 2>&1 | grep -a -E "extension|\"saved\"|resumed|Error|Traceback" | cut -c1-260 + ls $T/$CASE/A3 + grep -a "\"event\": \"step\"" $T/$CASE/logs/A3.jsonl | /usr/bin/head -3 | cut -c1-120 + grep -a "\"event\": \"step\"" $T/$CASE/logs/A3.jsonl | /usr/bin/tail -2 | cut -c1-120 +done +echo "== source resume.pt untouched:"; ls -la $LD/smoke_gpu3/ckpt/A3/resume.pt | cut -c25-90 diff --git a/scripts/r5_linedet/fetch_weights.sbatch b/scripts/r5_linedet/fetch_weights.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..3733256e4016b4b70459860989ef4a57e7fe5ab6 --- /dev/null +++ b/scripts/r5_linedet/fetch_weights.sbatch @@ -0,0 +1,10 @@ +#!/bin/bash +#SBATCH --job-name=r5_ld_weights +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=2 +#SBATCH --mem=4G +#SBATCH --time=00:20:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +bash /path/to/TURKIC_OCR_CODE/scripts/r5_linedet/fetch_weights.sh diff --git a/scripts/r5_linedet/fetch_weights.sh b/scripts/r5_linedet/fetch_weights.sh new file mode 100644 index 0000000000000000000000000000000000000000..1b4878298e73e99b39a1aa000685c944c4f6fba2 --- /dev/null +++ b/scripts/r5_linedet/fetch_weights.sh @@ -0,0 +1,14 @@ +#!/bin/bash +# Download the two kraken PP-OCRv6 weight files from Zenodo (records 21788410 medium, 21788405 small), verify md5. +set -eu +DATA=/path/to/TURKIC_OCR_DATA +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN +M=$DATA/data/raw/zenodo_ppocrv6_medium_21788410; S=$DATA/data/raw/zenodo_ppocrv6_small_21788405 +mkdir -p $M $S +curl -sSfL -o $M/medium.safetensors https://zenodo.org/records/21788410/files/medium.safetensors +curl -sSfL -o $M/README.md https://zenodo.org/records/21788410/files/README.md +curl -sSfL -o $S/small.safetensors https://zenodo.org/records/21788405/files/small.safetensors +curl -sSfL -o $S/README.md https://zenodo.org/records/21788405/files/README.md +md5sum $M/medium.safetensors $S/small.safetensors +sha256sum $M/medium.safetensors $S/small.safetensors $M/README.md $S/README.md | tee $DATA/checksums/r5_ppocrv6_weights.sha256 +echo "expected md5 medium e3411a453ce3b9e9efae3f8631d85762 small 07279cd68cd4402807542799f12d0f4a" diff --git a/scripts/r5_linedet/gate_unittest.py b/scripts/r5_linedet/gate_unittest.py new file mode 100644 index 0000000000000000000000000000000000000000..c60273d4d033db83e7bf8892c8557a4a0f294d57 --- /dev/null +++ b/scripts/r5_linedet/gate_unittest.py @@ -0,0 +1,21 @@ +"""Unit test of linedet.lm_gate on a toy folder (no real prediction file): plain outputs '' , ' ', ' ', 'a', and LM outputs with text. Expect the gated output empty for the first three.""" +import csv, os, sys, tempfile +sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src") +import importlib +gate_one = importlib.import_module("linedet." + (sys.argv[1] if len(sys.argv) > 1 else "lm_gate")).gate_one +cols = ["id", "ref", "hyp", "conf", "conf_min", "hit_cap"] +def w(path, rows): + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w", newline="", encoding="utf-8") as f: + f.write("\t".join(cols) + "\n") + for r in rows: + f.write("\t".join(str(x) for x in r) + "\n") +T = tempfile.mkdtemp(dir="/path/to/TURKIC_OCR_DATA/tmp") +w(T + "/X/ck/toy.tsv", [("1", "", "", 0.9, 0.9, 0), ("2", "", " ", 0.2, 0.2, 0), ("3", "", " ", 0.2, 0.2, 0), ("4", "ab", "a", 0.9, 0.9, 0), ("5", "", " ", 0.1, 0.1, 0)]) +w(T + "/X/ck_lm/toy.tsv", [("1", "", "na", -3, -3, 0), ("2", "", "na", -3, -3, 0), ("3", "", "na", -3, -3, 0), ("4", "ab", "ab", -1, -1, 0), ("5", "", "na", -3, -3, 0)]) +print("sets gated:", gate_one(T, "X", "ck")) +rows = list(csv.DictReader(open(T + "/X/ck_lm_gated/toy.tsv", encoding="utf-8"), delimiter="\t", quoting=csv.QUOTE_NONE)) +print([(r["id"], r["hyp"]) for r in rows]) +assert [r["hyp"] for r in rows] == ["", "", "", "ab", ""], "gate still lets text through" +print("UNIT TEST PASSED") +import shutil; shutil.rmtree(T) diff --git a/scripts/r5_linedet/gpu_driver.sbatch b/scripts/r5_linedet/gpu_driver.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..f3a9a642f0d94cb101b34b6fca8912dfb1482fe8 --- /dev/null +++ b/scripts/r5_linedet/gpu_driver.sbatch @@ -0,0 +1,22 @@ +#!/bin/bash +#SBATCH --job-name=r5_linedet_gpu +#SBATCH --partition=H100 +#SBATCH --qos=nu-h100 +#SBATCH --gres=gpu:h100:1 +#SBATCH --cpus-per-task=32 +#SBATCH --mem=160G +#SBATCH --time=16:00:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# Stage LINEDET, round R5: the one GPU job of slot L. A task driver runs, as separate processes: timing at batch 1, the five +# line recognizers (A1, A2, A3, A4, A1s) concurrently on mix_v1, their validation predictions, and the detectors. The task list +# (LD_OUT/tasks.json) is re-read while the job runs. Stop time is inside the file (stop_utc). +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN +LD=$DATA/outputs/r5/linedet +mkdir -p $LD/driver_logs +echo "job $SLURM_JOB_ID on $(hostname) started $(date -u)" +nvidia-smi --query-gpu=name,memory.total,memory.used --format=csv +export OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 PYTHONUNBUFFERED=1 +$CODE/.venv_kraken/bin/python -I -m linedet.driver --tasks $LD/tasks.json --status $LD/driver_status.json --logdir $LD/driver_logs +echo "driver ended $(date -u)" diff --git a/scripts/r5_linedet/h10_selftest.sh b/scripts/r5_linedet/h10_selftest.sh new file mode 100644 index 0000000000000000000000000000000000000000..dab72f9e809d993f8563c55bea4e418de6db9d4c --- /dev/null +++ b/scripts/r5_linedet/h10_selftest.sh @@ -0,0 +1,24 @@ +#!/bin/bash +# Self-test of the test-pass code path (clarification H10) on SMOKE data only: 100 KOHTD validation crops relabelled as a fake locked "test" set, a fake gate file +# in a scratch folder. Checks: predict --test_pass and lm_decode --test_pass run without a cap, write meta_test_pass.json and leave meta.json alone, +# lm_gate gates the new set. No real test file is opened. +set -u +DATA=/path/to/TURKIC_OCR_DATA +LD=$DATA/outputs/r5/linedet +PY=/path/to/TURKIC_OCR_CODE/.venv_kraken/bin/python +T=$DATA/tmp/h10selftest +rm -rf $T; mkdir -p $T/preds/A1/long_lm $T/topk +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN +$PY -I -m linedet.h10_fake $DATA/data/processed/r5_linedet_smoke/kohtd_val_smoke.tsv $T/man_test.tsv +echo '{"sets": [{"name": "fake_test", "manifest": "'$T'/man_test.tsv", "split": "test", "locked": true}]}' > $T/evalsets.json +echo fake > $T/gate.txt +# validation meta of the LM folder with the tuned alpha and beta (from the earlier smoke LM test) +cp $LD/smoke_gpu/preds/A1/long_lm/meta.json $T/preds/A1/long_lm/meta.json +echo "== predict --test_pass" +$PY -I -m linedet.predict --arm A1 --ckpt long --ckpt_dir $LD/smoke_gpu3/ckpt --evalsets $T/evalsets.json --test_pass --gate_file $T/gate.txt --device cpu --workers 2 --pred_dir $T/preds --logit_dir $T/topk 2>&1 | grep -a -E "fake_test|REFUSED|Error|Traceback" +ls $T/preds/A1/long +echo "== lm_decode --test_pass (no cap)" +$PY -I -m linedet.lm_decode --arm A1 --ckpt long --test_pass --gate_file $T/gate.txt --lm $LD/lmtest/char6.klm --codec $LD/smoke/codec_union.json --workers 4 --pred_dir $T/preds --logit_dir $T/topk 2>&1 | grep -a -E "fake_test|REFUSED|Error|Traceback|lm_gate" +ls $T/preds/A1/long_lm $T/preds/A1/long_lm_gated 2>&1 +wc -l $T/preds/A1/long/fake_test.tsv $T/preds/A1/long_lm/fake_test.tsv $T/preds/A1/long_lm_gated/fake_test.tsv +echo "== done" diff --git a/scripts/r5_linedet/inspect_models.sbatch b/scripts/r5_linedet/inspect_models.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..7e8f66df7ba95bae3c36a2aee42c372c597d38cb --- /dev/null +++ b/scripts/r5_linedet/inspect_models.sbatch @@ -0,0 +1,24 @@ +#!/bin/bash +#SBATCH --job-name=r5_ld_inspect +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=4 +#SBATCH --mem=16G +#SBATCH --time=00:30:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN +export UV_CACHE_DIR=$DATA/tmp/uv_cache +$HOME/.local/bin/uv pip install --python $CODE/.venv_kraken/bin/python rapidfuzz +$HOME/.local/bin/uv pip freeze --python $CODE/.venv_kraken/bin/python > $DATA/outputs/r5/linedet/pip_freeze_kraken_env.txt +OUT=$DATA/outputs/r5/linedet/base_models +mkdir -p $OUT +SITE=$CODE/.venv_kraken/lib/python3.12/site-packages +# rule 0.11: sha256 of every .py file of the maker packages that can run +find $SITE/kraken $SITE/ultralytics -name '*.py' | sort | xargs sha256sum > $DATA/outputs/r5/linedet/maker_py_sha256.txt +wc -l $DATA/outputs/r5/linedet/maker_py_sha256.txt +cd $CODE +$CODE/.venv_kraken/bin/python -I $CODE/src/linedet/inspect_models.py $DATA/data/raw/zenodo_ppocrv6_medium_21788410/medium.safetensors medium $OUT +$CODE/.venv_kraken/bin/python -I $CODE/src/linedet/inspect_models.py $DATA/data/raw/zenodo_ppocrv6_small_21788405/small.safetensors small $OUT diff --git a/scripts/r5_linedet/kenlm_build.sbatch b/scripts/r5_linedet/kenlm_build.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..d38ec7742ebec0322ba8beebbb53a4b51f7df40b --- /dev/null +++ b/scripts/r5_linedet/kenlm_build.sbatch @@ -0,0 +1,27 @@ +#!/bin/bash +#SBATCH --job-name=r5_ld_kenlm +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=8 +#SBATCH --mem=16G +#SBATCH --time=00:40:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# Build lmplz and build_binary from the kenlm 0.3.0 PyPI source (sha256 pinned). No credentials in the environment. +DATA=/path/to/TURKIC_OCR_DATA +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN +export UV_CACHE_DIR=$DATA/tmp/uv_cache +W=$DATA/tmp/kenlm_build +mkdir -p $W && cd $W +echo "node tools:"; which cmake gcc g++ make; ls /usr/include/boost 2>&1 | head -2; ls /usr/lib64 | grep -c boost +$HOME/.local/bin/uv venv $W/venv --python 3.12 +$HOME/.local/bin/uv pip install --python $W/venv/bin/python cmake +export PATH=$W/venv/bin:$PATH +which cmake; cmake --version | head -1 +echo "c4628bb9fb63c8a6f9240035b8b037385cfc404cb72e933cf48878291edac1e8 $DATA/data/raw/kenlm_0_3_0_sdist/kenlm-0.3.0.tar.gz" | sha256sum -c - +rm -rf src build && mkdir src && tar -xzf $DATA/data/raw/kenlm_0_3_0_sdist/kenlm-0.3.0.tar.gz -C src +find src \( -name '*.cc' -o -name '*.hh' -o -name '*.h' -o -name 'CMakeLists.txt' \) | sort | xargs sha256sum > $DATA/outputs/r5/linedet/kenlm_src_sha256.txt +mkdir -p build && cd build +cmake ../src/kenlm-0.3.0 -DCMAKE_BUILD_TYPE=Release -DKENLM_MAX_ORDER=6 2>&1 | tail -30 +make -j8 lmplz build_binary 2>&1 | tail -30 +ls -la bin 2>&1 diff --git a/scripts/r5_linedet/lb_smoke.sh b/scripts/r5_linedet/lb_smoke.sh new file mode 100644 index 0000000000000000000000000000000000000000..ec7b4f2a9408b137e73e7e48a95d574360ec490f --- /dev/null +++ b/scripts/r5_linedet/lb_smoke.sh @@ -0,0 +1,25 @@ +#!/bin/bash +# Miniature of the line block on the KOHTD smoke data (own folders): seed 2 of A1 in two phases with a plan file, predictions with arm_label, +# seed voting against the seed-1 smoke run, and one H06 run with its report. Not arm results. +set -u +DATA=/path/to/TURKIC_OCR_DATA +LD=$DATA/outputs/r5/linedet +PY=/path/to/TURKIC_OCR_CODE/.venv_kraken/bin/python +SM=$DATA/data/processed/r5_linedet_smoke +T=$LD/lbsmoke +rm -rf $T; mkdir -p $T +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN +export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True +echo "== h06 prep"; $PY -I -m linedet.h06 prep 2>&1 | tail -2 +echo "== seed 2 A1" +$PY -I -m linedet.train_arm --arm A1 --mix $SM/smoke_mix.yaml --codec $LD/smoke/codec_union.json --seed 20261122 --p_short 3200 --p_long_file $LD/smoke3_plan.json --workers 3 --ckpt_dir $T/ck2 --log_dir $T/logs --log_every 50 2>&1 | grep -a -E "saved|Error|Traceback" +echo "== predictions seed 2 and seed 1 (same 100 lines)" +$PY -I -m linedet.predict --arm A1 --arm_label A1_s2 --ckpt long --ckpt_dir $T/ck2 --evalsets $SM/evalsets_smoke.json --limit 100 --pred_dir $T/preds --logit_dir $T/topk --workers 3 2>&1 | grep -a -E "kohtd_val_smoke|Error|Traceback" | cut -c1-200 +echo "== vote" +$PY -I -m linedet.seed_vote --label_a A1 --label_b A1_s2 --ckpt long --pred_dir_a $LD/smoke_gpu3/preds --logit_dir_a $LD/smoke_gpu3/topk --pred_dir_b $T/preds --logit_dir_b $T/topk --codec $LD/smoke/codec_union.json --out $T/vote.json --vote_pred_dir $T/votepreds 2>&1 | tail -3 | cut -c1-600 +echo "== h06 run base10 (tiny)" +$PY -I -m linedet.train_arm --arm A1 --mix $LD/h06/h06_10.yaml --codec $LD/smoke/codec_union.json --p_short 3200 --stop_after_phase1 --workers 3 --ckpt_dir $T/h06/base10 --log_dir $T/h06logs --log_every 50 2>&1 | grep -a -E "saved|Error|Traceback" | cut -c1-160 +$PY -I -m linedet.predict --arm A1 --arm_label h06_base10 --ckpt short --ckpt_dir $T/h06/base10 --only V1,kohtd_val --limit 300 --pred_dir $T/h06preds --logit_dir $T/h06topk --workers 3 2>&1 | grep -a -E "V1 |kohtd_val |Error|Traceback" | cut -c1-200 +echo "== h06 report" +$PY -I -m linedet.h06 report 2>&1 | head -12 | cut -c1-200 +echo "== done" diff --git a/scripts/r5_linedet/line_block.sbatch b/scripts/r5_linedet/line_block.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..f5d1b25c81d021e74a6d0662ccddd24093fa5ad1 --- /dev/null +++ b/scripts/r5_linedet/line_block.sbatch @@ -0,0 +1,21 @@ +#!/bin/bash +#SBATCH --job-name=r5_line_block +#SBATCH --partition=H100 +#SBATCH --qos=nu-h100 +#SBATCH --gres=gpu:h100:1 +#SBATCH --cpus-per-task=32 +#SBATCH --mem=160G +#SBATCH --time=06:30:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# Stage LINEDET, round R5, amendment 3.3: the line block (D3 second seed of A1 and A2, D6 SR1-H06) and the four reference runs of stage REF +# (clarification H2), as concurrent processes of one driver. Stop: the earlier of 23 Nov 18:20 UTC (file) and the job start plus 6 h 10 min. +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN +LD=$DATA/outputs/r5/linedet +mkdir -p $LD/driver_logs_line_block +echo "job $SLURM_JOB_ID on $(hostname) started $(date -u)" +export OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 PYTHONUNBUFFERED=1 +$CODE/.venv_kraken/bin/python -I -m linedet.driver --tasks $LD/tasks_line_block.json --status $LD/driver_status_line_block.json \ + --logdir $LD/driver_logs_line_block --max_seconds 22200 +echo "driver ended $(date -u)" diff --git a/scripts/r5_linedet/line_ext.sbatch b/scripts/r5_linedet/line_ext.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..cc29a70168140be6e244a90d650e69566a1bc17b --- /dev/null +++ b/scripts/r5_linedet/line_ext.sbatch @@ -0,0 +1,22 @@ +#!/bin/bash +#SBATCH --job-name=r5_line_ext_L +#SBATCH --partition=H100 +#SBATCH --qos=nu-h100 +#SBATCH --gres=gpu:h100:1 +#SBATCH --cpus-per-task=32 +#SBATCH --mem=160G +#SBATCH --time=03:00:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# Amendment 3.4 E5: A1 and A2 (seed 1) continue from their P_long checkpoints to 2 x P_long = 3,168,768 samples (frozen seed-1 sample stream, warm restart with a +# time-aware cosine, peak 2.5e-4, see status.json), then validation predictions, LM decoding and gating for the checkpoint long2x. If the target is not reached in +# the time of this job the training anneals by the clock and stops with a saved checkpoint; the samples reached are in the log and in the checkpoint file. +# Slot L chain: 50971 -> 51128 -> 52050 -> this job -> 51277. +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN +LD=$DATA/outputs/r5/linedet +mkdir -p $LD/ext_driver_logs +echo "job $SLURM_JOB_ID on $(hostname) started $(date -u)" +export OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 PYTHONUNBUFFERED=1 +$CODE/.venv_kraken/bin/python -I -m linedet.driver --tasks $LD/tasks_line_ext.json --status $LD/driver_status_line_ext.json --logdir $LD/ext_driver_logs --max_seconds 10200 --grace 300 +echo "driver ended $(date -u)" diff --git a/scripts/r5_linedet/lineblock_post.sbatch b/scripts/r5_linedet/lineblock_post.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..088b32fefdc3a9cb3afcccac2ee2afe2848100bb --- /dev/null +++ b/scripts/r5_linedet/lineblock_post.sbatch @@ -0,0 +1,27 @@ +#!/bin/bash +#SBATCH --job-name=r5_ld_lbpost +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=02:00:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# After the line block: seed voting of A1 and A2 (D7, descriptive) and the SR1-H06 report (D6, descriptive). Validation sets only. +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN +PY=$CODE/.venv_kraken/bin/python +LD=$DATA/outputs/r5/linedet +PRED=$DATA/outputs/r5/preds +export OMP_NUM_THREADS=2 +for ARM in A1 A2; do + for CK in short long partial; do + if [ -f $PRED/$ARM/$CK/meta.json ] && [ -f $PRED/${ARM}_s2/$CK/meta.json ]; then + echo "=== vote $ARM $CK $(date)" + $PY -I -m linedet.seed_vote --label_a $ARM --label_b ${ARM}_s2 --ckpt $CK --out $LD/vote_${ARM}_${CK}.json --vote_pred_dir $LD/vote_preds + fi + done +done +$PY -I -m linedet.h06 report +echo "=== done $(date)" diff --git a/scripts/r5_linedet/lineblock_vote.sbatch b/scripts/r5_linedet/lineblock_vote.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..47d5c1d4312696ab77ed378649532b5fff0ebb97 --- /dev/null +++ b/scripts/r5_linedet/lineblock_vote.sbatch @@ -0,0 +1,27 @@ +#!/bin/bash +#SBATCH --job-name=r5_ld_vote2 +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=4 +#SBATCH --mem=24G +#SBATCH --time=02:00:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# Rerun of the seed voting of job 51129 (which died of out-of-memory in linedet.seed_vote, see the fix in load_npz). Validation sets only; the H06 report of 51129 had finished. +# The same commands can run as a step inside a running job: srun --jobid= --overlap -c 2 --mem=12G bash lineblock_vote.sbatch +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN +PY=$CODE/.venv_kraken/bin/python +LD=$DATA/outputs/r5/linedet +PRED=$DATA/outputs/r5/preds +export OMP_NUM_THREADS=2 +for ARM in A1 A2; do + for CK in short long partial; do + if [ -f $PRED/$ARM/$CK/meta.json ] && [ -f $PRED/${ARM}_s2/$CK/meta.json ]; then + echo "=== vote $ARM $CK $(date)" + $PY -I -m linedet.seed_vote --label_a $ARM --label_b ${ARM}_s2 --ckpt $CK --out $LD/vote_${ARM}_${CK}.json --vote_pred_dir $LD/vote_preds + fi + done +done +echo "=== done $(date)" diff --git a/scripts/r5_linedet/lm_build.sh b/scripts/r5_linedet/lm_build.sh new file mode 100644 index 0000000000000000000000000000000000000000..0f0d19902a37967d15974542e7e6abeaf5bdec45 --- /dev/null +++ b/scripts/r5_linedet/lm_build.sh @@ -0,0 +1,18 @@ +#!/bin/bash +# Character 6-gram, modified Kneser-Ney, built with kenlm lmplz (kenlm 0.3.0 PyPI source, sha256 c4628bb9...; static-boost build on the login node). +# Usage: lm_build.sh [folder with train_text.txt] (default DATA/outputs/r5/linedet/lm) +set -eu +DATA=/path/to/TURKIC_OCR_DATA +LM=${1:-$DATA/outputs/r5/linedet/lm} +BIN=$DATA/tmp/kenlm_build/build_static/bin +TMP=$DATA/tmp/lmplz_tmp_$$ +mkdir -p $LM $TMP +cd $LM +ls -la train_text.txt +nice -n 5 $BIN/lmplz -o 6 -S 16G -T $TMP --discount_fallback < train_text.txt > char6.arpa +ls -la char6.arpa +$BIN/build_binary -q 8 -b 8 trie char6.arpa char6.klm +ls -la char6.klm +sha256sum char6.klm train_text.txt > char6.sha256 +head -12 char6.arpa +rm -rf $TMP diff --git a/scripts/r5_linedet/lm_extra.sbatch b/scripts/r5_linedet/lm_extra.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..447f140aed49dac460f5ece3f8cd64cfe6a3ae7e --- /dev/null +++ b/scripts/r5_linedet/lm_extra.sbatch @@ -0,0 +1,26 @@ +#!/bin/bash +#SBATCH --job-name=r5_ld_lmextra +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=16 +#SBATCH --mem=48G +#SBATCH --time=04:00:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# After the line block: character-LM decoding (and, through the hook in lm_decode, the gated copy of clarification H9) for the seed-2 runs and A4b. +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN +PY=$CODE/.venv_kraken/bin/python +PRED=$DATA/outputs/r5/preds +export OMP_NUM_THREADS=1 +for LAB in A1_s2 A2_s2 A4b; do + for CK in short long partial; do + if [ -f $PRED/$LAB/$CK/meta.json ] && [ ! -f $PRED/$LAB/${CK}_lm/meta.json ]; then + echo "=== lm_decode $LAB $CK $(date)" + $PY -I -m linedet.lm_decode --arm $LAB --ckpt $CK --tune_set V1lm --workers 14 --max_lines 4000 + fi + done +done +$PY -I -m linedet.lm_gate +echo "=== done $(date)" diff --git a/scripts/r5_linedet/post_chain.sbatch b/scripts/r5_linedet/post_chain.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..4710d22eff3ae2e6df98d1cd84a780ee02f3d1e6 --- /dev/null +++ b/scripts/r5_linedet/post_chain.sbatch @@ -0,0 +1,33 @@ +#!/bin/bash +#SBATCH --job-name=r5_ld_post +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=16 +#SBATCH --mem=48G +#SBATCH --time=04:00:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# After the GPU job: language-model decoding of every prediction set that the GPU job did not finish, then results.json and arch.json. +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN +PY=$CODE/.venv_kraken/bin/python +LD=$DATA/outputs/r5/linedet +PRED=$DATA/outputs/r5/preds +export OMP_NUM_THREADS=1 +if [ ! -f $LD/lm/char6.klm ] && [ -f $LD/lm/train_text_stats.json ]; then + bash $CODE/scripts/r5_linedet/lm_build.sh +fi +if [ -f $LD/lm/char6.klm ]; then + for ARM in A1 A2 A3 A4 A1s; do + for CK in short long partial; do + if [ -f $PRED/$ARM/$CK/meta.json ] && [ ! -f $PRED/$ARM/${CK}_lm/meta.json ]; then + echo "=== lm_decode $ARM $CK $(date)" + $PY -I -m linedet.lm_decode --arm $ARM --ckpt $CK --tune_set V1lm --workers 16 --max_lines 4000 + fi + done + done +fi +[ -f $LD/arch.json ] || $PY -I -m linedet.arch_json +$PY -I -m linedet.collect +echo "=== post chain done $(date)" diff --git a/scripts/r5_linedet/r2_cmdtest.sh b/scripts/r5_linedet/r2_cmdtest.sh new file mode 100644 index 0000000000000000000000000000000000000000..f5b301f9cda38827204d11e9057e91ab0874deef --- /dev/null +++ b/scripts/r5_linedet/r2_cmdtest.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Validation-only test of the edited R2 prediction command (22 Nov): the new ref_ppocr_predict.py.new with --weights /model/latest, 200 crops of a validation set, +# predictions written to a scratch folder (--pred_root), never to preds/. No locked set is named. +C=/path/to/TURKIC_OCR_CODE +D=/path/to/TURKIC_OCR_DATA +S=$C/scripts/r5_ref +M=$D/data/processed/r5/manifests +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN +export FLAGS_allocator_strategy=auto_growth OMP_NUM_THREADS=2 +rm -rf $D/tmp/r2_cmdtest +$C/.venv_ref_paddle/bin/python -I $S/ref_ppocr_predict.py.new --run i --sets "kohtd_val=$M/kohtd_val.tsv" --weights $D/checkpoints/r5/ref/R2_i/model/latest --pred_root $D/tmp/r2_cmdtest --limit 200 --threads 2 2>&1 | grep -a -v "Warning\|WARNING\|ccache\|OMP\|PLEASE\|^W1" | tail -3 +$C/.venv_ref_paddle/bin/python -I $S/ref_ppocr_predict.py.new --run ii --sets "kohtd_rand_val=$M/kohtd_rand_val.tsv" --weights $D/checkpoints/r5/ref/R2_ii/model/latest --pred_root $D/tmp/r2_cmdtest --limit 200 --threads 2 2>&1 | grep -a -v "Warning\|WARNING\|ccache\|OMP\|PLEASE\|^W1" | tail -3 +for r in ours rand; do echo "== $r"; grep -a '"samples_seen"\|"epochs_done"\|"counts_from"\|"train_summary_samples_seen"\|"weights"\|"checkpoint"\|"rows"' $D/tmp/r2_cmdtest/R2/$r/meta.json | cut -c1-260; done +ls $D/tmp/r2_cmdtest/R2/* +cat $D/checkpoints/r5/ref/R2_i/progress.json $D/checkpoints/r5/ref/R2_ii/progress.json; echo diff --git a/scripts/r5_linedet/ref_finish.sbatch b/scripts/r5_linedet/ref_finish.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..6fc8bca375b3e51da8f42f9ab6e432af62ed4133 --- /dev/null +++ b/scripts/r5_linedet/ref_finish.sbatch @@ -0,0 +1,28 @@ +#!/bin/bash +#SBATCH --job-name=r5_ref_finish_L +#SBATCH --partition=H100 +#SBATCH --qos=nu-h100 +#SBATCH --gres=gpu:h100:1 +#SBATCH --cpus-per-task=32 +#SBATCH --mem=160G +#SBATCH --time=03:00:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# Clarification H12: resume the reference runs (stage REF) that were cut short or never started in the line block 51128, from REF's saved state, up to the +# paper's stopping rule or the 3 h limit of this job. Exits at once when every reference run reached its stopping rule. Slot L chain: +# 50971 -> 51128 (line block) -> this job -> 51277 (leader job on slot L). +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN +LD=$DATA/outputs/r5/linedet +PY=$CODE/.venv_kraken/bin/python +mkdir -p $LD/ref_finish/driver_logs +echo "job $SLURM_JOB_ID on $(hostname) started $(date -u)" +$PY -I -m linedet.ref_finish_make --out $LD/ref_finish/tasks_ref_finish.json --count_file $LD/ref_finish/n_unfinished.txt --job_seconds 10200 --reserve_s 2400 +N=$(cat $LD/ref_finish/n_unfinished.txt) +if [ "$N" = "0" ]; then + echo "every reference run reached its stopping rule in the line block: nothing to do, exiting at $(date -u)" + exit 0 +fi +export OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 PYTHONUNBUFFERED=1 +$PY -I -m linedet.driver --tasks $LD/ref_finish/tasks_ref_finish.json --status $LD/ref_finish/driver_status.json --logdir $LD/ref_finish/driver_logs --max_seconds 10200 +echo "driver ended $(date -u)" diff --git a/scripts/r5_linedet/ref_val_figs.sh b/scripts/r5_linedet/ref_val_figs.sh new file mode 100644 index 0000000000000000000000000000000000000000..5c5c2f3e585d0f1c8ada907a7b0497924b9d70f1 --- /dev/null +++ b/scripts/r5_linedet/ref_val_figs.sh @@ -0,0 +1,23 @@ +#!/bin/bash +# Validation-only figures of the replication split (clarification H12): R2(ii) predictions on kohtd_rand_val (the 15 % validation part of the replication split) with the +# final-epoch weights (model/latest: the compressed 3-epoch run never reached the 2000-iteration evaluation, so PaddleOCR saved no best_accuracy), then the paper metrics for +# R1(ii) (existing predictions) and R2(ii). Runs as a small step inside job 52050 (srun --jobid=52050 --overlap). No locked set is read. +CODE=/path/to/TURKIC_OCR_CODE +D=/path/to/TURKIC_OCR_DATA +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN +S=$CODE/scripts/r5_ref +MAN=$D/data/processed/r5/manifests +mkdir -p $D/outputs/r5/ref/metrics +export FLAGS_allocator_strategy=auto_growth OMP_NUM_THREADS=2 MKL_NUM_THREADS=2 OPENBLAS_NUM_THREADS=2 TF_CPP_MIN_LOG_LEVEL=2 +echo "=== R2(ii) predictions on kohtd_rand_val $(date -u)" +$CODE/.venv_ref_paddle/bin/python -I $S/ref_ppocr_predict.py --run ii --sets kohtd_rand_val=$MAN/kohtd_rand_val.tsv --train_dir $D/checkpoints/r5/ref/R2_ii --weights $D/checkpoints/r5/ref/R2_ii/model/latest --threads 2 +RC=$? +if [ $RC -eq 3 ]; then + echo "no GPU in this step; CPU run" + $CODE/.venv_ref_paddle/bin/python -I $S/ref_ppocr_predict.py --run ii --sets kohtd_rand_val=$MAN/kohtd_rand_val.tsv --train_dir $D/checkpoints/r5/ref/R2_ii --weights $D/checkpoints/r5/ref/R2_ii/model/latest --threads 2 --cpu +fi +for R in R1 R2; do + echo "=== metrics $R(ii) $(date -u)" + $CODE/.venv_ref_tf/bin/python -I $S/ref_paper_metrics.py $D/outputs/r5/preds/$R/rand/kohtd_rand_val.tsv $D/outputs/r5/ref/metrics/${R}_rand_kohtd_rand_val.json | head -60 +done +echo "=== done $(date -u)" diff --git a/scripts/r5_linedet/school_stats.sbatch b/scripts/r5_linedet/school_stats.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..b398aa5e02d86080d3f9528d2b07b93a593e6d24 --- /dev/null +++ b/scripts/r5_linedet/school_stats.sbatch @@ -0,0 +1,12 @@ +#!/bin/bash +#SBATCH --job-name=r5_ld_school +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=4 +#SBATCH --mem=16G +#SBATCH --time=00:30:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +CODE=/path/to/TURKIC_OCR_CODE +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN +$CODE/.venv_kraken/bin/python -I -m linedet.det_school_stats diff --git a/scripts/r5_linedet/smoke_cpu.sbatch b/scripts/r5_linedet/smoke_cpu.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..6ce268bea3f119d29b4b1d02ba9d5049cfc2acb9 --- /dev/null +++ b/scripts/r5_linedet/smoke_cpu.sbatch @@ -0,0 +1,33 @@ +#!/bin/bash +#SBATCH --job-name=r5_ld_smoke +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=16 +#SBATCH --mem=48G +#SBATCH --time=01:30:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# Smoke test on CPU: every arm trains a few steps on KOHTD train crops (kohtd_split_v1), saves, resumes-free predict on 64 validation crops. +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN +PY=$CODE/.venv_kraken/bin/python +SITE=$CODE/.venv_kraken/lib/python3.12/site-packages +echo $CODE/src > $SITE/linedet.pth +export OMP_NUM_THREADS=14 MKL_NUM_THREADS=14 +SM=$DATA/data/processed/r5_linedet_smoke +SO=$DATA/outputs/r5/linedet/smoke +mkdir -p $SO +$PY -I -m linedet.make_smoke +$PY -I -m linedet.make_codec --mix $SM/smoke_mix.yaml --out $SO/codec_union.json +for ARM in A3 A2 A1 A1s A4; do + echo "=== $ARM $(date)" + PS=384; PL=768; if [ $ARM = A4 ]; then PS=128; PL=256; fi + $PY -I -m linedet.train_arm --arm $ARM --mix $SM/smoke_mix.yaml --codec $SO/codec_union.json --p_short $PS --p_long $PL \ + --workers 4 --device cpu --ckpt_dir $SO/ckpt --log_dir $SO/logs --log_every 1 --seed 1 + for CK in short long; do + $PY -I -m linedet.predict --arm $ARM --ckpt $CK --ckpt_dir $SO/ckpt --evalsets $SM/evalsets_smoke.json --limit 64 --bs 16 --workers 4 \ + --device cpu --pred_dir $SO/preds --logit_dir $SO/topk + done +done +echo "=== done $(date)" diff --git a/scripts/r5_linedet/test_pass_commands.sh b/scripts/r5_linedet/test_pass_commands.sh new file mode 100644 index 0000000000000000000000000000000000000000..206ad307bebb0dc6c967d470abf44ee29db998cd --- /dev/null +++ b/scripts/r5_linedet/test_pass_commands.sh @@ -0,0 +1,42 @@ +#!/bin/bash +# R5 LINEDET: test-set predictions of the line arms, to be run on a compute node ONLY in the scoring pass. NO CAP of any kind (clarification H10): +# every crop of every locked set, greedy and then the character-LM beam search (alpha and beta taken from each checkpoint's validation tuning) and its gated copy. +# +# Order of use: +# 1. copy records/R5/RULE/test_pass_started.txt to the cluster as /path/to/TURKIC_OCR_DATA/outputs/r5/linedet/test_pass_started.txt +# (predict.py and lm_decode.py REFUSE the test pass while that file does not exist, and refuse --limit and --max_lines). +# 2. run this script in a job, for example (GPU for the predictions; the LM decoding uses CPU workers): +# sbatch --partition=H100 --qos=nu-h100 --gres=gpu:h100:1 --cpus-per-task=32 --mem=96G --time=03:00:00 --job-name=r5_ld_testpass \ +# --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out --wrap "bash /path/to/TURKIC_OCR_CODE/scripts/r5_linedet/test_pass_commands.sh" +# (LINEDET_DEVICE=cpu runs it on CPU.) +# Writes DATA/outputs/r5/preds/
(design sequence_length_cap) +MAX_NEW_CEILING = 6144 +LOC_RE = re.compile(r"<\|LOC_(\d{1,4})\|>") +SPECIAL_RE = re.compile(r"<\|[A-Za-z_]+\|>||") # as records/R5/PAGECHK/b1_page_check.py lines_from +_WS = re.compile(r"\s+") + + +def norm_line(s): + """NFC, every run of whitespace (newlines included) to one space, outer spaces stripped.""" + return _WS.sub(" ", unicodedata.normalize("NFC", s or "")).strip() + + +def spot_size(w, h, max_pixels=SPOT_MAX_PIXELS, factor=FACTOR): + """(W, H) of the resized page: both sides multiples of `factor`, area <= max_pixels, scaled up or down so that the + area is as large as the flooring allows. For an image already of that form and under the cap the processor's + smart_resize leaves it unchanged (round(h/28)*28 == h, area <= max_pixels).""" + beta = math.sqrt((w * h) / float(max_pixels)) + hb = max(factor, int(math.floor(h / beta / factor)) * factor) + wb = max(factor, int(math.floor(w / beta / factor)) * factor) + while hb * wb > max_pixels: # guard against float rounding at an exact boundary + if hb >= wb: + hb -= factor + else: + wb -= factor + return wb, hb + + +def fit_size(w, h, max_pixels=SPOT_MAX_PIXELS, factor=FACTOR): + """size used for an image that is already a page image of the build (sides multiples of 28): unchanged if it is under + the cap, else spot_size (down). Training jitter u < 1 and evaluation (u = 1) both go through this.""" + if w % factor == 0 and h % factor == 0 and w * h <= max_pixels: + return w, h + return spot_size(w, h, max_pixels, factor) + + +def loc(v, size): + n = int(math.floor(1000.0 * float(v) / float(size) + 0.5)) + return min(1000, max(0, n)) + + +def quad_of_box(box, W, H): + """axis-aligned box (x0, y0, x1, y1) in a W x H frame -> 8 ints TL, TR, BR, BL in 0..1000""" + x0, y0, x1, y1 = box + a, b, c, d = loc(x0, W), loc(y0, H), loc(x1, W), loc(y1, H) + return [a, b, c, b, c, d, a, d] + + +def loc_tokens(q): + return "".join("<|LOC_%d|>" % n for n in q) + + +def build_target(texts, boxes, W, H, order): + """texts, boxes: reference lines (det_eval page file order); order: target order (list of indices). + Returns (target string, kept indices in target order, quads of the kept lines, counts).""" + parts, kept, quads = [], [], [] + cnt = {"empty_text_lines_left_out": 0, "lines_with_special_like_text": 0} + for i in order: + t = norm_line(texts[i]) + if not t: + cnt["empty_text_lines_left_out"] += 1 + continue + if "<|" in t or "" in t: + cnt["lines_with_special_like_text"] += 1 + q = quad_of_box(boxes[i], W, H) + parts.append(t + loc_tokens(q)) + kept.append(i) + quads.append(q) + return "\n".join(parts), kept, quads, cnt + + +def parse_output(raw): + """Spotting output (special tokens kept) -> list of instances {text, locs, box (x0, y0, x1, y1 in 0..1000) or None, + malformed}. Blank output lines are skipped. box = bounds of the LAST 8 location tokens of the line; a line with fewer + than 8 has no box; malformed = the number of location tokens is not exactly 8.""" + out = [] + for ln in (raw or "").split("\n"): + locs = [int(m) for m in LOC_RE.findall(ln)] + text = norm_line(SPECIAL_RE.sub("", LOC_RE.sub("", ln))) + if not text and not locs: + continue + box = None + if len(locs) >= 8: + q = locs[-8:] + xs, ys = q[0::2], q[1::2] + box = (min(xs), min(ys), max(xs), max(ys)) + out.append({"text": text, "locs": locs, "box": box, "malformed": len(locs) != 8}) + return out + + +def page_lines(instances): + """page text lines = non-empty instance texts in output order""" + return [x["text"] for x in instances if x["text"]] + + +def boxes_to_frame(instances, W, H): + """boxes of the instances that have one, mapped from 0..1000 to a W x H frame""" + return [[b[0] / 1000.0 * W, b[1] / 1000.0 * H, b[2] / 1000.0 * W, b[3] / 1000.0 * H] + for b in (x["box"] for x in instances) if b is not None] + + +# ------------------------------------------------------------------------------------------------ reading order +def gutter_x(boxes, W, lo=0.35, hi=0.65, tol=0.03, max_cross=0.10, min_side=0.15): + """R_SCHOOL step 1-2. boxes: axis-aligned line boxes in a frame of width W. Returns (gutter x or None, info).""" + n = len(boxes) + if n < 4: + return None, {"n": n} + d = tol * W + best, xs = None, [] + for x in range(int(lo * W), int(hi * W) + 1): + c = 0 + for b in boxes: + if b[0] < x - d and b[2] > x + d: + c += 1 + if best is None or c < best: + best, xs = c, [x] + elif c == best: + xs.append(x) + runs, cur = [], [xs[0]] + for x in xs[1:]: + if x == cur[-1] + 1: + cur.append(x) + else: + runs.append(cur) + cur = [x] + runs.append(cur) + run = max(runs, key=len) # first longest run on ties + xg = (run[0] + run[-1]) / 2.0 + left = sum(1 for b in boxes if (b[0] + b[2]) / 2.0 < xg) + ok = best <= max_cross * n and min(left, n - left) >= min_side * n + return (xg if ok else None), {"n": n, "min_cross": best, "left": left, "xg": xg, "two_columns": ok} + + +def partition_by_gutter(order, boxes, xg): + """R_SCHOOL step 3: stable partition of `order` into the lines left of the gutter, then the lines right of it.""" + if xg is None: + return list(order) + left = [i for i in order if (boxes[i][0] + boxes[i][2]) / 2.0 < xg] + right = [i for i in order if (boxes[i][0] + boxes[i][2]) / 2.0 >= xg] + return left + right + + +def school_order(boxes, W): + """reference / target order of a School page: stored order (indices 0..n-1, det_prep's baseline-y sort), partitioned + by the gutter. Returns (order, gutter info).""" + xg, info = gutter_x(boxes, W) + return partition_by_gutter(list(range(len(boxes))), boxes, xg), info + + +def det_order(boxes): + """det_eval / detb1_page_check reading order of detected boxes: (centre_y // 15, centre_x) in the 1280 px page""" + return sorted(range(len(boxes)), key=lambda i: (int(((boxes[i][1] + boxes[i][3]) / 2) // 15), (boxes[i][0] + boxes[i][2]) / 2)) + + +def det_order_columns(boxes, W): + """baseline order of the decision: det_order, stably partitioned by the R_SCHOOL gutter of the detected boxes""" + xg, info = gutter_x(boxes, W) + return partition_by_gutter(det_order(boxes), boxes, xg), info + + +def guard_not_test(path): + import os + b = os.path.basename(str(path)).lower() + for w in ("test", "kohtd_rand", "rukopys", "turkishocr", "more_real_print"): + if w in b: + raise SystemExit("REFUSED: %s looks like a locked set (%s)" % (path, w)) diff --git a/scripts/r5_onemodel/om_train.py b/scripts/r5_onemodel/om_train.py new file mode 100644 index 0000000000000000000000000000000000000000..6858333bfec742237f0f84fd4b6770957a2019d0 --- /dev/null +++ b/scripts/r5_onemodel/om_train.py @@ -0,0 +1,510 @@ +"""ONEMODEL pilot (design ONEMODEL-pilot-1): fine-tune the R5 leader on whole pages in the spotting format, mixed 1:1 with its +own crop samples. Adapted from CODE/scripts/r5_vlma/train_vlm.py (same precision, optimiser, schedule, state files, export). + +- Start: the leader folder (DATA/checkpoints/r5/paddleocr_vl_1_6/leader); native class, trust_remote_code never set. +- Step k uses page rows 16k..16k+15 of seq/page_seq.tsv and crop rows 16k..16k+15 of seq/crop_seq.tsv (mix_v1_seq rows from + 1,310,592). Page micro-batches of 4, one crop micro-batch of 16 (on CUDA out-of-memory, or a cuBLAS allocation failure, + the failed micro-batch's graph is freed and only the failing stream's micro-batch is halved, down to 1; then exit 98; a + resume whose fp32-master fingerprint does not match exits 96); pages and crops never share + a micro-batch. Loss = page token-mean + crop token-mean (each over the step's target tokens of its stream). +- Pages: record image (pre-resized to <= 1,605,632 px) resized to spot_size(u x 1,605,632) with Lanczos (u from page_seq); + prompt 'Spotting:' with the page processor size; target ids from the record (they end with ). Crops: vlm_common's own + training batch (instruction 'Transcribe the text in this image exactly.', default processor size) - the leader's path. +- bf16 weights and compute, fp32 master weights and AdamW moments (0.9, 0.999, 1e-8, wd 0), clip 1.0, warm-up 3% then cosine to 0, + gradient checkpointing (non-reentrant). +- State (master.pt, optim.pt, sched.pt, state.json) saved atomically every --save-every-min minutes, at --export-at steps, and + when --max-seconds (process wall time) is reached or on SIGTERM/SIGUSR1; the process then exits 99 (the sbatch resubmits). + Exports (bf16 HF folder + r5_export.json that eval_vlm.py reads) at --export-at steps, named ck_; the last is + also linked as 'final'. Exit 0 when all steps are done and the final export exists. +- --smoke: CPU code-path test (tiny page pixel cap, small batches, label-mask report, per-stream timing); --stop-after-steps N + saves and exits 0 after step N (resume test). + +usage: om_train.py --run pilot [--device cuda] [--max-seconds S] ... +""" +import argparse +import csv +import json +import math +import os +import shutil +import signal +import sys +import time +from datetime import datetime, timezone + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import om_common as C # noqa: E402 +import om_text as T # noqa: E402 + +import torch # noqa: E402 +import transformers # noqa: E402 +from PIL import Image # noqa: E402 + +vc = C.vc +csv.field_size_limit(10 ** 9) + +ap = argparse.ArgumentParser() +ap.add_argument("--run", required=True) +ap.add_argument("--model-dir", default=C.LEADER) +ap.add_argument("--data-root", default=C.DATA + "/data/processed/r6_onemodel") +ap.add_argument("--ckpt-root", default=C.DATA + "/checkpoints/r6_onemodel") +ap.add_argument("--out-root", default=C.DATA + "/outputs/r6_onemodel/train") +ap.add_argument("--page-batch", type=int, default=16) +ap.add_argument("--crop-batch", type=int, default=16) +ap.add_argument("--page-mb", type=int, default=4) +ap.add_argument("--crop-mb", type=int, default=16) +ap.add_argument("--page-samples", type=int, default=30000) +ap.add_argument("--lr", type=float, default=1e-5) +ap.add_argument("--warmup-frac", type=float, default=0.03) +ap.add_argument("--save-every-min", type=float, default=30.0) +ap.add_argument("--max-seconds", type=float, default=0.0) +ap.add_argument("--export-at", default="469,938,1407,1875") +ap.add_argument("--device", default="cuda") +ap.add_argument("--threads", type=int, default=0) +ap.add_argument("--workers", type=int, default=6, help="loader workers per stream") +ap.add_argument("--check-labels", type=int, default=4) +ap.add_argument("--smoke", action="store_true") +ap.add_argument("--smoke-max-pixels", type=int, default=200704, help="smoke only: page pixel cap (256 visual tokens)") +ap.add_argument("--stop-after-steps", type=int, default=0) +ap.add_argument("--state-dir", default="") +ap.add_argument("--no-export", action="store_true") +ap.add_argument("--seed", type=int, default=20261125) +args = ap.parse_args() + +dev = args.device +use_cuda = dev == "cuda" +if args.threads: + torch.set_num_threads(args.threads) +elif use_cuda: + torch.set_num_threads(4) +torch.manual_seed(args.seed) +total_steps = math.ceil(args.page_samples / args.page_batch) +warmup = round(args.warmup_frac * total_steps) +export_at = sorted(int(x) for x in args.export_at.split(",") if x) +run_dir = os.path.join(args.out_root, args.run) +state_dir = args.state_dir or os.path.join(args.ckpt_root, args.run, "state") +os.makedirs(run_dir, exist_ok=True) +log_path = os.path.join(run_dir, "train_log.jsonl") +job_id = os.environ.get("SLURM_JOB_ID", "") +STOP = {"flag": False, "why": ""} +T_PROC = time.time() + + +def _sig(signum, frame): # noqa: ARG001 + STOP["flag"] = True + STOP["why"] = "signal %d" % signum + + +signal.signal(signal.SIGTERM, _sig) +signal.signal(signal.SIGINT, _sig) +signal.signal(signal.SIGUSR1, _sig) + + +def utc(): + return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def log(rec): + rec["utc"] = utc() + with open(log_path, "a", encoding="utf-8") as f: + f.write(json.dumps(rec, ensure_ascii=False) + "\n") + + +def say(*a): + print("[om %s %s]" % (args.run, utc()), *a, flush=True) + + +# ---------------- data ---------------- +def read_tsv(p): + T.guard_not_test(p) + with open(p, encoding="utf-8", newline="") as f: + return list(csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE)) + + +pages = {} +for s in ("gen_train", "school_train"): + p = os.path.join(args.data_root, "records", s + ".jsonl") + T.guard_not_test(p) + with open(p, encoding="utf-8") as f: + for line in f: + r = json.loads(line) + assert r["id"].startswith(("pg_train_", "school_train_")) and r["split"] == "train", r["id"] + pages[r["id"]] = {"image": r["image"], "target_ids": r["target_ids"], "over_cap": r["over_cap"]} +page_rows = read_tsv(os.path.join(args.data_root, "seq", "page_seq.tsv")) +crop_rows = read_tsv(os.path.join(args.data_root, "seq", "crop_seq.tsv")) +need_p, need_c = total_steps * args.page_batch, total_steps * args.crop_batch +assert len(page_rows) >= need_p and len(crop_rows) >= need_c, "sequence files too short" +assert not any(pages[r["page_id"]]["over_cap"] for r in page_rows[:need_p]), "over-cap page in the sequence" + +# ---------------- model ---------------- +t_load = time.time() +proc, tok, model = C.load(args.model_dir) +tmpl_kw = vc.template_kwargs(proc, tok) +suffix_ids, suffix_how, suffix_text = vc.answer_suffix(C.SHORT, proc, tok, model.generation_config, tmpl_kw) +assert suffix_ids == [2], "answer suffix %s" % suffix_ids +assert vc.INSTR == T.CROP_INSTRUCTION, "crop instruction changed" +model.to(dev) +model.config.use_cache = False +model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False}) +for p_ in model.parameters(): + p_.requires_grad_(True) +model.train() +named = list(model.named_parameters()) +names = [n for n, _ in named] +params = [p_ for _, p_ in named] +master = [torch.nn.Parameter(p_.detach().float().clone(), requires_grad=True) for p_ in params] +opt = torch.optim.AdamW(master, lr=args.lr, betas=(0.9, 0.999), eps=1e-8, weight_decay=0.0, fused=use_cuda) +sched = transformers.get_cosine_schedule_with_warmup(opt, warmup, total_steps) +load_seconds = time.time() - t_load + + +def fingerprint(): + with torch.no_grad(): + return float(sum(m.double().sum().item() for m in master[:: max(1, len(master) // 16)])) + + +st = {"step": 0, "page_mb": args.page_mb, "crop_mb": args.crop_mb, "saves": 0, "oom_events": [], "job_ids": [], "resumed_from_step": [], + "fingerprint_at_save": None, "train_seconds": 0.0, "exports": []} + + +def save_state(d, extra=None): + t0 = time.time() + tmp, old = d + ".tmp", d + ".old" + shutil.rmtree(tmp, ignore_errors=True) + os.makedirs(tmp, exist_ok=True) + torch.save({n: m.detach() for n, m in zip(names, master)}, os.path.join(tmp, "master.pt")) + torch.save(opt.state_dict(), os.path.join(tmp, "optim.pt")) + torch.save(sched.state_dict(), os.path.join(tmp, "sched.pt")) + st["saves"] += 1 + st["fingerprint_at_save"] = fingerprint() + rec = dict(st) + if extra: + rec.update(extra) + json.dump(rec, open(os.path.join(tmp, "state.json"), "w"), indent=1) + if os.path.isdir(d): + os.rename(d, old) + os.rename(tmp, d) + shutil.rmtree(old, ignore_errors=True) + return time.time() - t0 + + +def load_state(d): + sd = torch.load(os.path.join(d, "master.pt"), map_location="cpu", weights_only=True) + with torch.no_grad(): + for n, m, p_ in zip(names, master, params): + m.copy_(sd[n].to(m.device)) + p_.copy_(m) + del sd + opt.load_state_dict(torch.load(os.path.join(d, "optim.pt"), map_location=dev, weights_only=True)) + sched.load_state_dict(torch.load(os.path.join(d, "sched.pt"), weights_only=True)) + st.update(json.load(open(os.path.join(d, "state.json")))) + + +shutil.rmtree(state_dir + ".tmp", ignore_errors=True) +if not os.path.isdir(state_dir) and os.path.isdir(state_dir + ".old"): + os.rename(state_dir + ".old", state_dir) +resumed = False +if os.path.isdir(state_dir): + load_state(state_dir) + fp = fingerprint() + st["resumed_from_step"].append(st["step"]) + st["resume_fingerprint_match"] = st["fingerprint_at_save"] == fp + resumed = True + say("resumed at step %d; fingerprint saved %r now %r" % (st["step"], st["fingerprint_at_save"], fp)) + if not st["resume_fingerprint_match"]: + say("REFUSED: the fp32 master weights loaded from %s do not match the fingerprint saved with them; exit 96" % state_dir) + sys.exit(96) +if job_id and job_id not in st["job_ids"]: + st["job_ids"].append(job_id) +meta = {"design": T.DESIGN_ID, "run": args.run, "model_dir": args.model_dir, "model_class": type(model).__name__, + "processor_class": type(proc).__name__, "image_processor_class": type(proc.image_processor).__name__, + "params_unique": vc.unique_params(model), "lr": args.lr, "total_steps": total_steps, "warmup_steps": warmup, + "page_batch": args.page_batch, "crop_batch": args.crop_batch, "page_mb": st["page_mb"], "crop_mb": args.crop_mb, + "page_samples": total_steps * args.page_batch, "crop_samples": total_steps * args.crop_batch, + "loss": "page token-mean + crop token-mean", "export_at": export_at, "answer_suffix_ids": suffix_ids, + "answer_suffix_how": suffix_how, "chat_template_kwargs": tmpl_kw, "page_prompt": T.SPOT_PROMPT, "crop_instruction": vc.INSTR, + "page_processor_kwargs": C.PAGE_PROC_KW, "smoke": args.smoke, "smoke_max_pixels": args.smoke_max_pixels if args.smoke else None, + "transformers": transformers.__version__, "torch": torch.__version__, "device": dev, + "gpu": torch.cuda.get_device_name(0) if use_cuda else "cpu", "job_id": job_id, "resumed": resumed, + "load_seconds": round(load_seconds, 1), "started_utc": utc(), "attention": vc.SDPA_NOTE} +json.dump(meta, open(os.path.join(run_dir, "run_meta_%s.json" % (job_id or "local_%d" % int(time.time()))), "w"), indent=1, ensure_ascii=False) +log({"event": "start", "step": st["step"], "resumed": resumed, "lr": args.lr, "total_steps": total_steps}) +say("start: step %d of %d (warm-up %d), lr %g, params %d, resumed %s" % (st["step"], total_steps, warmup, args.lr, meta["params_unique"], resumed)) + + +class PageDS(torch.utils.data.Dataset): + def __len__(self): + return len(page_rows) + + def __getitem__(self, i): + r = page_rows[i] + rec = pages[r["page_id"]] + im = Image.open(rec["image"]).convert("RGB") + cap = args.smoke_max_pixels if args.smoke else float(r["u"]) * T.SPOT_MAX_PIXELS + w, h = T.fit_size(im.size[0], im.size[1], cap) + if (w, h) != im.size: + im = im.resize((w, h), Image.LANCZOS) + return im, rec["target_ids"], r["page_id"] + + +class CropDS(torch.utils.data.Dataset): + def __len__(self): + return len(crop_rows) + + def __getitem__(self, i): + r = crop_rows[i] # rows of the frozen train mix (build job copies mix_v1_seq rows 1,310,592 ...) + return Image.open(r["image"]).convert("RGB"), r["text"], r["id"] + + +def collate_page(batch): + imgs, tg, ids = [b[0] for b in batch], [b[1] for b in batch], [b[2] for b in batch] + inp, lab = C.page_train_batch(proc, tok, imgs, tg, tmpl_kw) + return inp, lab, sum(len(t) for t in tg), tg, ids + + +def collate_crop(batch): + imgs, labs, ids = [b[0] for b in batch], [b[1] for b in batch], [b[2] for b in batch] + inp, lab, ntok = vc.build_train_batch(C.SHORT, proc, tok, imgs, labs, suffix_ids, tmpl_kw) + tg = [vc.target_ids(tok, l_, suffix_ids) for l_ in labs] + return inp, lab, ntok, tg, ids + + +PARENT = os.getpid() + + +def _wi(_): + try: + import ctypes + ctypes.CDLL("libc.so.6", use_errno=True).prctl(1, signal.SIGKILL, 0, 0, 0) + if os.getppid() != PARENT: + os._exit(0) + except Exception: # noqa: BLE001 + pass + try: + os.nice(10) + except Exception: # noqa: BLE001 + pass + torch.set_num_threads(1) + + +def make_loader(ds, first, mb, collate): + sub = torch.utils.data.Subset(ds, range(first, len(ds))) + kw = dict(batch_size=mb, shuffle=False, collate_fn=collate, num_workers=args.workers, drop_last=False) + if args.workers > 0: + kw.update(prefetch_factor=2, persistent_workers=False, pin_memory=False, worker_init_fn=_wi) + return iter(torch.utils.data.DataLoader(sub, **kw)) + + +def export(name): + t0 = time.time() + d = os.path.join(args.ckpt_root, args.run, name) + tmp = d + ".tmp" + shutil.rmtree(tmp, ignore_errors=True) + model.config.use_cache = True + model.save_pretrained(tmp, safe_serialization=True, save_original_format=False) + model.config.use_cache = False + proc.save_pretrained(tmp) + miss, unexp = vc.export_key_check(model, tmp) + if miss or unexp: + shutil.rmtree(tmp, ignore_errors=True) + log({"event": "export_key_check_failed", "missing": miss[:20], "unexpected": unexp[:20]}) + say("EXPORT KEY CHECK FAILED", len(miss), len(unexp)) + raise SystemExit(3) + json.dump({"design": T.DESIGN_ID, "arm": "onemodel", "short": C.SHORT, "run": args.run, "phase": name, + "repo": "PaddlePaddle/PaddleOCR-VL-1.6", "base_revision": "132c45f52c0a26ed5a6b2f6bd8e3985794cc27dd", + "start_weights": args.model_dir, "steps": st["step"], "samples_seen": st["step"] * args.page_batch, + "page_samples_seen": st["step"] * args.page_batch, "crop_samples_seen": st["step"] * args.crop_batch, + "samples_total": st["step"] * args.page_batch, "lr": args.lr, "flag": "complete" if st["step"] >= total_steps else "partial", + "train_seconds": st["train_seconds"], "answer_suffix_ids": suffix_ids, "chat_template_kwargs": tmpl_kw, + "instruction": vc.INSTR, "spotting_prompt": T.SPOT_PROMPT, "page_max_pixels": T.SPOT_MAX_PIXELS, + "data_order_seed": args.seed, "seed_index": 1, "exported_utc": utc(), "smoke": args.smoke}, + open(os.path.join(tmp, "r5_export.json"), "w"), indent=1) + shutil.rmtree(d, ignore_errors=True) + os.rename(tmp, d) + st["exports"].append({"name": name, "step": st["step"], "utc": utc()}) + log({"event": "export", "name": name, "step": st["step"], "seconds": round(time.time() - t0, 1), "dir": d}) + say("exported %s at step %d in %.0fs" % (name, st["step"], time.time() - t0)) + return d + + +def micro(inp, lab): + out = model(**C.to_dev(inp, dev), use_cache=False) + ls, nt = vc.target_loss_sum(out.logits, lab) + return out, ls, nt + + +def accumulate(): + for p_, m in zip(params, master): + if p_.grad is not None: + if m.grad is None: + m.grad = p_.grad.detach().float() + else: + m.grad.add_(p_.grad.detach()) + p_.grad = None + + +def is_oom(e): + """CUDA out-of-memory and allocation failures that arrive as RuntimeError (cuBLAS / cuDNN) are handled alike""" + if isinstance(e, torch.cuda.OutOfMemoryError): + return True + t = str(e) + return isinstance(e, RuntimeError) and ("CUBLAS_STATUS_ALLOC_FAILED" in t or "out of memory" in t) + + +checked = {"page": 0, "crop": 0} +smoke_rep = {"label_checks": [], "timing": []} +page_loader = make_loader(PageDS(), st["step"] * args.page_batch, st["page_mb"], collate_page) +crop_loader = make_loader(CropDS(), st["step"] * args.crop_batch, st["crop_mb"], collate_crop) +last_save = time.time() +exit_code = 0 +if use_cuda: + torch.cuda.reset_peak_memory_stats() +while st["step"] < total_steps: + if STOP["flag"] or (args.max_seconds and time.time() - T_PROC > args.max_seconds): + why = STOP["why"] or "max_seconds" + s_ = save_state(state_dir, {"stopped_for": why}) + log({"event": "stopped_for_time", "step": st["step"], "why": why, "save_seconds": round(s_, 1)}) + say("stopped (%s) at step %d; state saved in %.0fs; exit 99" % (why, st["step"], s_)) + exit_code = 99 + break + t_step = time.time() + n_pmb = math.ceil(args.page_batch / st["page_mb"]) + n_cmb = math.ceil(args.crop_batch / st["crop_mb"]) + cur = "data" + out = ls = None + try: + t0 = time.time() + pmbs = [next(page_loader) for _ in range(n_pmb)] + cmbs = [next(crop_loader) for _ in range(n_cmb)] + t_data = time.time() - t0 + n_ptok = sum(x[2] for x in pmbs) + n_ctok = sum(x[2] for x in cmbs) + lp = lc = 0.0 + tim = {"page_fwd_bwd": 0.0, "crop_fwd_bwd": 0.0} + for stream, mbs, ntot in (("page", pmbs, n_ptok), ("crop", cmbs, n_ctok)): + for inp, lab, ntok, tg, ids in mbs: + cur = stream + tp = time.time() + out, ls, nt = micro(inp, lab) + assert nt == ntok, "target tokens %d != %d" % (nt, ntok) + if checked[stream] < args.check_labels: + rep = C.label_mask_report(lab, tg, inp["input_ids"]) + for r_, x in enumerate(rep): + lv = lab[r_][lab[r_] != -100].tolist() + x.update({"stream": stream, "id": ids[r_], "step": st["step"] + 1, + "decoded_head": tok.decode(lv[:16], skip_special_tokens=False), + "decoded_tail": tok.decode(lv[-12:], skip_special_tokens=False), + "last_label_is_end_token": lv[-1:] == suffix_ids}) + if stream == "page": + x["grid"] = inp["image_grid_thw"][r_].tolist() + log({"event": "label_check", **x}) + smoke_rep["label_checks"].append(x) + checked[stream] += 1 + (ls / ntot).backward() + if stream == "page": + lp += float(ls.detach()) + else: + lc += float(ls.detach()) + out = ls = None + accumulate() + if use_cuda: + torch.cuda.synchronize() + tim[stream + "_fwd_bwd"] += time.time() - tp + cur = "optimizer" + tp = time.time() + gnorm = float(torch.nn.utils.clip_grad_norm_(master, 1.0)) + opt.step() + sched.step() + with torch.no_grad(): + for p_, m in zip(params, master): + p_.copy_(m) + opt.zero_grad(set_to_none=True) + if use_cuda: + torch.cuda.synchronize() + tim["opt"] = time.time() - tp + except (torch.cuda.OutOfMemoryError, RuntimeError) as e: + if not is_oom(e): + raise + # free the failed micro-batch's graph and every partial gradient before the retry (the step is redone from its start; + # the fp32 masters were not touched unless the optimiser itself failed, which is fatal below) + out = ls = None + pmbs = cmbs = None + import gc as _gc + _gc.collect() + for p_ in params: + p_.grad = None + opt.zero_grad(set_to_none=True) + if use_cuda: + torch.cuda.empty_cache() + key = {"page": "page_mb", "crop": "crop_mb"}.get(cur) + if key is None or st[key] == 1: + if key is not None: # failed inside a micro-batch: the masters are untouched, the state is safe to save + save_state(state_dir, {"stopped_for": "out of memory in %s (micro-batch 1)" % cur}) + log({"event": "oom_fatal", "step": st["step"], "where": cur, "error": repr(e)[:300]}) + say("OUT OF MEMORY in %s (%s); exit 98" % (cur, "state saved" if key else "state not saved, last periodic save kept")) + exit_code = 98 + break + st["oom_events"].append({"step": st["step"], "stream": cur, key: st[key], "utc": utc(), "error": repr(e)[:200]}) + st[key] //= 2 + say("out of memory in the %s stream (step %d): %s halved to %d; %s" % (cur, st["step"], key, st[key], repr(e)[:120])) + page_loader = make_loader(PageDS(), st["step"] * args.page_batch, st["page_mb"], collate_page) + crop_loader = make_loader(CropDS(), st["step"] * args.crop_batch, st["crop_mb"], collate_crop) + continue + dt = time.time() - t_step + st["step"] += 1 + st["train_seconds"] += dt + loss_p, loss_c = lp / max(n_ptok, 1), lc / max(n_ctok, 1) + rec = {"step": st["step"], "loss": loss_p + loss_c, "loss_page": loss_p, "loss_crop": loss_c, "page_tokens": n_ptok, + "crop_tokens": n_ctok, "lr": sched.get_last_lr()[0], "grad_norm": gnorm, "step_s": round(dt, 3), + "data_wait_s": round(t_data, 3), "page_mb": st["page_mb"], "crop_mb": st["crop_mb"], + "timing_s": {k: round(v, 3) for k, v in tim.items()}} + if use_cuda: + rec["max_mem_GiB"] = round(torch.cuda.max_memory_allocated() / 2 ** 30, 2) + rec["max_mem_reserved_GiB"] = round(torch.cuda.max_memory_reserved() / 2 ** 30, 2) + log(rec) + smoke_rep["timing"].append(rec) + if st["step"] <= 3 or st["step"] % 25 == 0: + say("step %d/%d loss %.4f (page %.4f crop %.4f) lr %.2e %.2fs (data %.2fs) mb %d" % ( + st["step"], total_steps, rec["loss"], loss_p, loss_c, rec["lr"], dt, t_data, st["page_mb"])) + if not math.isfinite(rec["loss"]): + s_ = save_state(state_dir, {"stopped_for": "non-finite loss"}) + say("non-finite loss; exit 97") + exit_code = 97 + break + if st["step"] in export_at and not args.no_export: + export("ck_%d" % (st["step"] * args.page_batch)) + save_state(state_dir) + last_save = time.time() + if args.stop_after_steps and st["step"] >= args.stop_after_steps and st["step"] < total_steps: + s_ = save_state(state_dir, {"stopped_for": "stop_after_steps"}) + log({"event": "stopped_after_steps", "step": st["step"], "save_seconds": round(s_, 1)}) + say("stopped after %d steps (resume test); state saved" % st["step"]) + break + if time.time() - last_save >= args.save_every_min * 60: + s_ = save_state(state_dir) + last_save = time.time() + log({"event": "save", "step": st["step"], "save_seconds": round(s_, 1)}) + +done = st["step"] >= total_steps +if done and exit_code == 0: + if not args.no_export: + final_name = "ck_%d" % (st["step"] * args.page_batch) + d = os.path.join(args.ckpt_root, args.run, final_name) + if not os.path.isdir(d): + export(final_name) + link = os.path.join(args.ckpt_root, args.run, "final") + if not os.path.islink(link): + os.symlink(final_name, link) + save_state(state_dir, {"finished_utc": utc()}) + json.dump({"design": T.DESIGN_ID, "run": args.run, "steps": st["step"], "train_seconds": st["train_seconds"], + "exports": st["exports"], "oom_events": st["oom_events"], "job_ids": st["job_ids"], + "resumed_from_step": st["resumed_from_step"], "finished_utc": utc()}, + open(os.path.join(run_dir, "train.done.json"), "w"), indent=1) + say("training complete") +if args.smoke: + smoke_rep.update({"steps_done": st["step"], "resumed": resumed, "resume_fingerprint_match": st.get("resume_fingerprint_match"), + "load_seconds": round(load_seconds, 1)}) + json.dump(smoke_rep, open(os.path.join(run_dir, "smoke_train_%s.json" % ("resumed" if resumed else "fresh")), "w"), + indent=1, ensure_ascii=False) +sys.exit(exit_code) diff --git a/scripts/r5_onemodel/onemodel_gate.sbatch b/scripts/r5_onemodel/onemodel_gate.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..541f861861fb5015f1e591bda4b6c357d29e9d16 --- /dev/null +++ b/scripts/r5_onemodel/onemodel_gate.sbatch @@ -0,0 +1,35 @@ +#!/bin/bash +#SBATCH --job-name=onemodel_run +#SBATCH --partition=H100 +#SBATCH --qos=nu-h100 +#SBATCH --gres=gpu:h100:1 +#SBATCH --cpus-per-task=16 +#SBATCH --mem=96G +#SBATCH --time=04:00:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +#SBATCH --dependency=singleton +# Single-model page training (route C), queued early at the owner's request on 25 Nov 2026 so it holds a place in the +# H100 queue while the code is still being reviewed. It runs only reviewed code: READY lists the sha256 of every file the +# review approved, and the job refuses to start if READY is missing or any listed file changed since the review. +# Self-resubmission by the training code must submit THIS file again, so every segment passes the same check. +set -u +C=/path/to/TURKIC_OCR_CODE +D=/path/to/TURKIC_OCR_DATA +READY=$D/outputs/r5/onemodel/READY +RUN=${1:-seed1} +hostname; date -u; nvidia-smi --query-gpu=name,memory.total --format=csv,noheader +if [ ! -f "$READY" ]; then + echo "NOT STARTED: no READY file (code review not finished); exit 3" + exit 3 +fi +cd "$C" || exit 3 +if ! sha256sum -c --quiet "$READY"; then + echo "NOT STARTED: a reviewed file changed after the review; exit 3" + exit 3 +fi +if [ ! -f "$C/scripts/r5_onemodel/run_gpu.sh" ]; then + echo "NOT STARTED: scripts/r5_onemodel/run_gpu.sh missing; exit 3" + exit 3 +fi +echo "review check passed; starting run $RUN" +exec bash "$C/scripts/r5_onemodel/run_gpu.sh" "$RUN" diff --git a/scripts/r5_onemodel/run_gpu.sh b/scripts/r5_onemodel/run_gpu.sh new file mode 100644 index 0000000000000000000000000000000000000000..f9558f963609d57ad638e4ad16dbe01f61655eb2 --- /dev/null +++ b/scripts/r5_onemodel/run_gpu.sh @@ -0,0 +1,146 @@ +#!/bin/bash +# ONEMODEL pilot (records/R5/ONEMODEL/design.json, ONEMODEL-pilot-1): the single GPU entry point. +# Runs INSIDE an existing one-H100 allocation started by CODE/scripts/r5_onemodel/onemodel_gate.sbatch (submitted by hand, +# which checks the reviewed sha256 list READY and then execs: bash run_gpu.sh ). No #SBATCH lines are needed here. +# Usage (by the gate only): bash run_gpu.sh seed1 +# Validation data only. Stages, each resumable. A stage is resubmitted ONLY when it stopped on the time budget (exit 99, or for +# eval_vlm.py its deadline passed); any other failure exits non-zero with no resubmission. Before a stage starts with less than +# 60 s of budget, the script resubmits instead of starting it. Resubmission = THE GATE again (sbatch --test-only first, then +# sbatch onemodel_gate.sbatch ), at most 12 times (logic of CODE/scripts/r5_hymt/hymt_run.sbatch). +# 0 baseline detector + leader on all 300 generated + 150 School val pages on this GPU (the comparator), scored alone +# 1 om_train.py: 1,875 steps, exports ck_7504, ck_15008, ck_22512, ck_30000 (= final) +# 2 final export: 450 val pages in spotting mode; V1 (3,678 crops) and synth_clutter_val (500) in crop mode (eval_vlm.py) +# 3 R5 scorer on the crop predictions, om_score.py -> DATA/outputs/r6_onemodel/page_scores/page_scores__final.json (gates) +# 4 descriptive: the 500 clutter images in spotting mode (final export and leader, at most 256 new tokens), re-scored +# 5 learning curve (descriptive): the three earlier exports, pages + V1 + clutter, then re-scored +# Guard: DATA/outputs/r5/onemodel/train//RUNNING holds the job id of the running segment; a second segment of the same run +# exits 3 while that job is still running. The file is removed at the normal end and before each resubmission. +# Dry-run switches (environment; all unset in the real job, so it runs exactly as described above): OM_DEVICE (cuda), +# OM_OUT, OM_CKPT_ROOT (output and checkpoint roots), OM_LIMIT (14280), OM_X_TRAIN, OM_X_EVAL, OM_X_BASE, OM_X_CROP (extra options +# appended to om_train / om_eval_pages / om_baseline / eval_vlm), OM_CKS (learning-curve export names), OM_TEST_ONLY (resubmission +# stops after the test-only check). Used only by om_dryrun.sbatch on ZEN4. +set -uo pipefail +RUN=${1:?usage: run_gpu.sh RUN} +C=/path/to/TURKIC_OCR_CODE +D=/path/to/TURKIC_OCR_DATA +S=$C/scripts/r5_onemodel +GATE=$C/scripts/r5_onemodel/onemodel_gate.sbatch +PY=$C/.venv_vlm/bin/python +PK=$C/.venv_kraken/bin/python +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN +export HF_HOME=$D/hf_cache/r5_vlmb_home HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 TOKENIZERS_PARALLELISM=false PYTHONDONTWRITEBYTECODE=1 +export OMP_NUM_THREADS=16 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True +DEV=${OM_DEVICE:-cuda} +O=${OM_OUT:-$D/outputs/r6_onemodel} +CKR=${OM_CKPT_ROOT:-$D/checkpoints/r6_onemodel} +LIMIT=${OM_LIMIT:-14280} # the gate's 04:00:00 allocation minus 120 s for the gate's own checks before exec +XT=${OM_X_TRAIN:-} +XE=${OM_X_EVAL:-} +XB=${OM_X_BASE:-} +XC=${OM_X_CROP:-} +CKS=${OM_CKS:-ck_7504 ck_15008 ck_22512} +N=${OM_RESUBMIT:-0} +CK=$CKR/$RUN +LEADER=$D/checkpoints/r5/paddleocr_vl_1_6/leader +GUARD=$D/outputs/r5/onemodel/train/$RUN/RUNNING +need() { grep -q "$2" "$1" 2>/dev/null || { echo "REFUSED: precondition $1 ($2) not met"; exit 3; }; } +need $D/data/processed/r6_onemodel/build_report.json '"passed": true' +need $D/outputs/r6_onemodel/smoke/smoke_check.json '"smoke_passed": true' +[ -n "${SLURM_JOB_ID:-}" ] || { echo "REFUSED: not inside a Slurm allocation"; exit 3; } +if [ -f $GUARD ]; then + OTHER=$(head -n 1 $GUARD) + if [ -n "$OTHER" ] && [ "$OTHER" != "$SLURM_JOB_ID" ] && [ -n "$(squeue -h -j $OTHER -t R -o %i 2>/dev/null)" ]; then + echo "REFUSED: segment $OTHER of run $RUN is still running ($GUARD); exit 3" + exit 3 + fi +fi +mkdir -p $(dirname $GUARD) +echo $SLURM_JOB_ID > $GUARD +resubmit() { + rm -f $GUARD + if [ "$N" -ge 12 ]; then echo "resubmission limit reached ($N)"; exit 1; fi + sbatch --test-only --export=ALL,OM_RESUBMIT=$((N + 1)) $GATE $RUN \ + || { echo "RESUBMISSION FAILED (test-only refused); the chain stops here"; exit 1; } + if [ -n "${OM_TEST_ONLY:-}" ]; then echo "DRY RUN: test-only passed, real sbatch skipped; exit 0"; exit 0; fi + sbatch --export=ALL,OM_RESUBMIT=$((N + 1)) $GATE $RUN \ + || { echo "RESUBMISSION FAILED (sbatch refused); the chain stops here"; exit 1; } + exit 0 +} +left() { echo $((LIMIT - SECONDS - $1)); } +budget() { # margin: resubmit before a stage that would start with under 60 s; never pass --max-seconds 0 (= unlimited) + if [ $(left $1) -lt 60 ]; then echo "budget below 60 s before a stage; resubmitting"; resubmit; fi +} +stage_rc() { # rc, what: 99 = stopped on the time budget -> resubmit; any other non-zero -> fail visibly, no resubmission + if [ $1 -eq 99 ]; then resubmit; fi + if [ $1 -ne 0 ]; then echo "FAILED: $2 (exit $1); no resubmission"; exit $1; fi +} +evalpages() { # model dir, name, sets [extra options] + budget 600 + echo "=== pages $2 ($3) $(date -u +%FT%TZ)" + $PY -I $S/om_eval_pages.py --model-dir $1 --name $2 --sets $3 --device $DEV --out-root $O/page_preds --max-seconds $(left 600) ${4:-} $XE + stage_rc $? "page evaluation $2 $3" +} +cropsdone() { grep -q '"complete": true' $O/preds/onemodel/$1/V1.score.json 2>/dev/null && grep -q '"complete": true' $O/preds/onemodel/$1/synth_clutter_val.score.json 2>/dev/null; } +evalcrops() { # model dir, name + if cropsdone $2; then return 0; fi + budget 600 + echo "=== crops $2 $(date -u +%FT%TZ)" + DLS=$(( $(date -u +%s) + $(left 600) )) + DL=$(date -u -d "@$DLS" +%Y-%m-%dT%H:%M:%SZ) + $PY -I $C/scripts/r5_vlma/eval_vlm.py --short paddleocr_vl_1_6 --arm onemodel --ckpt $2 --model-dir $1 \ + --registry $C/scripts/r5_vlma/models_r5.tsv --evalsets $D/data/processed/r5/evalsets.json --preds-root $O/preds \ + --sets V1,synth_clutter_val --device $DEV --batch 16 --deadline-utc $DL $XC + RC=$? + if [ $RC -ne 0 ]; then echo "FAILED: crop evaluation $2 (exit $RC); no resubmission"; exit $RC; fi + if cropsdone $2; then return 0; fi + # eval_vlm.py stops at its deadline with exit 0 and an incomplete score file: resubmit only if the deadline has passed + if [ $(date -u +%s) -ge $DLS ]; then echo "crop evaluation $2 stopped at its deadline"; resubmit; fi + echo "FAILED: crop evaluation $2 incomplete before its deadline (a set refused or skipped?); no resubmission" + exit 1 +} +baseline() { # set + if [ -f $O/baseline/gpu/$1.done ]; then return 0; fi + budget 600 + echo "=== baseline $1 $(date -u +%FT%TZ)" + $PY -I $S/om_baseline.py --set $1 --device $DEV --out $O/baseline/gpu/$1.jsonl --max-seconds $(left 600) $XB + stage_rc $? "baseline $1" + touch $O/baseline/gpu/$1.done +} +SCORE_PATHS="--page-preds $O/page_preds --baseline-dir $O/baseline/gpu --crop-scores $O/scores --out $O/page_scores" +score() { + echo "=== score $(date -u +%FT%TZ)" + OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=1 $PK -I $C/scripts/r5eval/score.py --preds $O/preds \ + --registry $D/data/processed/r5/evalsets.json --out $O/scores --workers 8 --page-preds "" --settle 0 + echo "r5 scorer rc $?" + for name in "$@"; do $PK -I $S/om_score.py --name $name $SCORE_PATHS; echo "om_score $name rc $?"; done +} +hostname; nvidia-smi --query-gpu=name,memory.total --format=csv,noheader 2>/dev/null || echo "no GPU visible (device $DEV)"; date -u +%FT%TZ +echo "run $RUN, job $SLURM_JOB_ID, resubmission $N, device $DEV, out $O, limit $LIMIT" +baseline gen_val +baseline school_val +if [ ! -f $O/page_scores/page_scores_baseline_gpu.json ]; then + $PK -I $S/om_score.py --baseline-only $SCORE_PATHS; echo "baseline score rc $?" +fi +if [ ! -f $O/train/$RUN/train.done.json ]; then + budget 1500 + echo "=== train $(date -u +%FT%TZ)" + $PY -I $S/om_train.py --run $RUN --device $DEV --ckpt-root $CKR --out-root $O/train --max-seconds $(left 1500) $XT + stage_rc $? "training" +fi +F=${RUN}_final +evalpages $CK/final $F gen_val,school_val +evalcrops $CK/final $F +if [ ! -f $O/page_scores/page_scores_$F.json ]; then score $F; fi +evalpages $CK/final $F clutter_spot "--max-new 256" +evalpages $LEADER leader clutter_spot "--max-new 256" +score $F +NAMES="" +for ck in $CKS; do + evalpages $CK/$ck ${RUN}_$ck gen_val,school_val + evalcrops $CK/$ck ${RUN}_$ck + NAMES="$NAMES ${RUN}_$ck" +done +score $F $NAMES +touch $O/train/$RUN/run_gpu.done +rm -f $GUARD +echo "=== all done $(date -u +%FT%TZ)" diff --git a/scripts/r5_perf.sbatch b/scripts/r5_perf.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..23420548d40a46ee23e8c019cfaf54aa58647af1 --- /dev/null +++ b/scripts/r5_perf.sbatch @@ -0,0 +1,13 @@ +#!/bin/bash +#SBATCH --job-name=r5_eval_perf +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=4 +#SBATCH --mem=24G +#SBATCH --time=00:40:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# R5 EVALCODE: scale and timing check of the scorer on the real V1 and kohtd_val manifests (validation labels only) with synthetic predictions. +C=/path/to/TURKIC_OCR_CODE +D=/path/to/TURKIC_OCR_DATA +$C/.venv_kraken/bin/python -I $C/tests_r5eval/perf_real_manifest.py $D/data/processed/r5/manifests $D/tmp/evalcode_perf diff --git a/scripts/r5_print/r5_print_after_rerun.sh b/scripts/r5_print/r5_print_after_rerun.sh new file mode 100644 index 0000000000000000000000000000000000000000..5ded56ed599a84c34efc0c117d16509019365824 --- /dev/null +++ b/scripts/r5_print/r5_print_after_rerun.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# assemble manifests, validate them, build the audit montages for the given languages +CODE=/path/to/TURKIC_OCR_CODE +D=/path/to/TURKIC_OCR_DATA +PY=$CODE/.venv_print/bin/python +nice -n 19 $PY -I $CODE/scripts/r5_print/r5_print_assemble.py $D/outputs/r5/print_real_out 2>&1 | tail -1 | cut -c1-500 +nice -n 19 $PY -I $CODE/scripts/r5_print/r5_print_validate.py $D/outputs/r5/print_real_out/validation_print.json 2>&1 | cut -c1-1200 +rm -rf $D/outputs/r5/print_audit +bash $CODE/scripts/r5_print/r5_print_audit_prep.sh "$@" diff --git a/scripts/r5_print/r5_print_all.sbatch b/scripts/r5_print/r5_print_all.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..3e090f716947284d84b06f90dcdc2b129c4720ea --- /dev/null +++ b/scripts/r5_print/r5_print_all.sbatch @@ -0,0 +1,21 @@ +#!/bin/bash +#SBATCH --job-name=r5_print_all +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=8 +#SBATCH --mem=24G +#SBATCH --time=01:30:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# All ten language-scripts one after the other (thin ones first); a language already taken by a per-language job is skipped. +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN +hostname; date -u +for L in tk ba sah tt ky uz_cyrl uz_latn az kk tr; do + echo "=== $L $(date -u)" + $CODE/.venv_print/bin/python -I $CODE/scripts/r5_print/r5_print_process.py --lang $L \ + --raw $DATA/data/raw/r5_print --out $DATA/data/processed/r5/print_real \ + --corpus $DATA/data/processed/r5/pagesynth_text_split --workers 8 || echo "FAILED $L" +done +date -u diff --git a/scripts/r5_print/r5_print_assemble.py b/scripts/r5_print/r5_print_assemble.py new file mode 100644 index 0000000000000000000000000000000000000000..a087d65767b95c4cfbb2ff27f4d4c6277fc62cd4 --- /dev/null +++ b/scripts/r5_print/r5_print_assemble.py @@ -0,0 +1,178 @@ +#!/usr/bin/env python3 +"""R5 PRINT stage E: sidecars -> manifests, duplicate check by crop sha256, counts.json, evalsets.json. + +Reads DATA/data/processed/r5/print_real/_sidecars/.jsonl (one per language-script) and more.jsonl. +Writes print_real_{train,val,test}.tsv and more_real_print.tsv into DATA/data/processed/r5/manifests/, +adds three entries to evalsets.json (re-read right before the atomic replace), writes counts.json. +Usage: python -I r5_print_assemble.py OUT_JSON_DIR +""" +import collections +import concurrent.futures as cf +import hashlib +import json +import os +import sys +import time +import unicodedata + +D = "/path/to/TURKIC_OCR_DATA/data/processed/r5" +PR = D + "/print_real" +MAN = D + "/manifests" +OUTDIR = sys.argv[1] +MORE_ONLY = len(sys.argv) > 2 and sys.argv[2] == "more_only" +HDR = ["id", "image", "text", "lang", "script", "kind", "source", "split", "group", "unit"] +LANGS = ["kk", "ky", "uz_cyrl", "uz_latn", "tr", "az", "tt", "ba", "tk", "sah"] +NOW = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) + + +def sha256_file(p): + h = hashlib.sha256() + with open(p, "rb") as f: + for c in iter(lambda: f.read(1 << 20), b""): + h.update(c) + return h.hexdigest() + + +def read_jsonl(p): + if not os.path.exists(p): + return [] + return [json.loads(x) for x in open(p, encoding="utf-8")] + + +def write_manifest(path, rows): + tmp = path + ".part" + with open(tmp, "w", encoding="utf-8", newline="") as f: + f.write("\t".join(HDR) + "\n") + for r in rows: + t = unicodedata.normalize("NFC", r["text"]) + assert "\t" not in t and "\n" not in t and "\r" not in t + f.write("\t".join([r["id"], r["image"], t, r["lang"], r["script"], r["kind"], r["source"], r["split"], r["group"], r["unit"]]) + "\n") + os.replace(tmp, path) + + +# hashes of every crop of the other manifests (stage DATA's table of 20 Nov) and of GEN's images so far +other = set() +other_files = [] +for hp in (D + "/build_logs/hashes.tsv", D + "/build_logs/hashes_synth.tsv"): + if os.path.exists(hp): + other_files.append(hp) + with open(hp, encoding="utf-8") as f: + next(f) + for line in f: + other.add(line.split("\t", 2)[1]) +print("other-manifest sha256 values", len(other), other_files, flush=True) + +def opens(path): + """True if the file exists and PIL can read it as an image (header and checksums).""" + try: + from PIL import Image + with Image.open(path) as im: + im.verify() + return True + except Exception: + return False + + +rows = [] +dropped = collections.Counter() +for lg in LANGS: + for r in read_jsonl(f"{PR}/_sidecars/{lg}.jsonl"): + if r["sha256"] in other: + dropped["crop_sha256_in_other_manifest"] += 1 + continue + if not os.path.exists(r["image"]): + dropped["image_missing"] += 1 + continue + rows.append(r) +# every image must exist and open (added after a draft pointed to rewritten crops) +with cf.ThreadPoolExecutor(16) as ex: + flags = list(ex.map(opens, [r["image"] for r in rows], chunksize=256)) +n_checked = len(rows) +rows = [r for r, ok in zip(rows, flags) if ok] +dropped["image_unreadable"] += n_checked - len(rows) +# duplicate crops across languages +seen = set() +final = [] +for r in sorted(rows, key=lambda r: r["id"]): + if r["sha256"] in seen: + dropped["crop_sha256_duplicate_in_print_real"] += 1 + continue + seen.add(r["sha256"]) + final.append(r) +by_split = {sp: [r for r in final if r["split"] == sp] for sp in ("train", "val", "test")} +if not MORE_ONLY: + for sp, rs in by_split.items(): + write_manifest(f"{MAN}/print_real_{sp}.tsv", rs) + +# MORE +more = [r for r in read_jsonl(f"{PR}/_sidecars/more.jsonl") if r["sha256"] not in other] +with cf.ThreadPoolExecutor(16) as ex: + mflags = list(ex.map(opens, [r["image"] for r in more])) +dropped["more_image_unreadable"] += sum(1 for f in mflags if not f) +more = [r for r, ok in zip(more, mflags) if ok] +write_manifest(f"{MAN}/more_real_print.tsv", sorted(more, key=lambda r: r["id"])) + +# counts +counts = {"generated_utc": NOW, "dropped_in_assembly": dict(dropped), + "image_check": {"rows_checked_exists_and_opens": n_checked, "rows_kept": len(final), + "rows_dropped_missing_file": int(dropped.get("image_missing", 0)), + "rows_dropped_unreadable": int(dropped.get("image_unreadable", 0)), + "more_rows_dropped_unreadable": int(dropped.get("more_image_unreadable", 0))}, + "per_language": {}, "totals": {}} +for lg in LANGS: + st = {} + sp_path = f"{PR}/_stats/{lg}.json" + if os.path.exists(sp_path): + st = json.load(open(sp_path, encoding="utf-8")) + ent = {"script": "Latn" if lg in ("tr", "az", "tk", "uz_latn") else "Cyrl", "documents_on_disk": st.get("documents_on_disk"), + "documents_accepted": st.get("documents_accepted"), "document_rejects": st.get("doc_rejects"), + "hosts_accepted": st.get("hosts_accepted"), "splits": {}} + for sp in ("train", "val", "test"): + rs = [r for r in by_split[sp] if r["lang"] == lg] + ent["splits"][sp] = {"documents": len({r["group"] for r in rs}), "pages": len({(r["group"], r["page"]) for r in rs}), "lines": len(rs), + "characters": sum(len(r["text"]) for r in rs)} + ent["sources"] = dict(collections.Counter(r["source"] for r in final if r["lang"] == lg).most_common(8)) + counts["per_language"][lg] = ent +counts["totals"] = {sp: {"documents": len({r["group"] for r in by_split[sp]}), "lines": len(by_split[sp])} for sp in by_split} +mc = collections.Counter(r["lang"] for r in more) +counts["more_real_print"] = {"paragraphs": len(more), "by_lang": dict(mc), "pages": len({(r["group"]) for r in more}), + "characters": sum(len(r["text"]) for r in more)} +os.makedirs(OUTDIR, exist_ok=True) +json.dump(counts, open(os.path.join(OUTDIR, "counts_more_only.json" if MORE_ONLY else "counts.json"), "w", encoding="utf-8"), indent=1, ensure_ascii=False) + +# evalsets.json: three entries, atomic replace after a fresh read +sha = {n: sha256_file(f"{MAN}/{n}.tsv") for n in (("more_real_print",) if MORE_ONLY else ("print_real_val", "print_real_test", "more_real_print"))} +def langs_of(rs): + return dict(collections.Counter(r["lang"] for r in rs)) +entries = [ + {"name": "print_real_val", "manifest": f"{MAN}/print_real_val.tsv", "split": "val", "locked": False, "status": "ready", + "purpose": "Validation lines cut from real born-digital PDFs (exact text layer), 10 language-scripts, documents disjoint from the training and test documents. For selection only.", + "n_rows": len(by_split["val"]), "n_groups": len({r["group"] for r in by_split["val"]}), "manifest_sha256": sha.get("print_real_val"), + "langs": langs_of(by_split["val"]), "unit": "line", "group_unit": "source document", + "split_rule": "documents split by seeded shuffle (seed 20261121) per language-script, about 80/5/15; exact line texts that occur in a training document are removed from val and test", + "owner": "PRINT"}, + {"name": "print_real_test", "manifest": f"{MAN}/print_real_test.tsv", "split": "test", "locked": True, "status": "ready", + "purpose": "Typed endpoint N (version 3 section 1): lines cut from real born-digital PDFs with an exact text layer, per language-script, documents disjoint from train and val. The machine audit of 50 random lines per language-script is in OUT/audit.json (checked by machine viewing, not by a human).", + "n_rows": len(by_split["test"]), "n_groups": len({r["group"] for r in by_split["test"]}), "manifest_sha256": sha.get("print_real_test"), + "langs": langs_of(by_split["test"]), "unit": "line", "group_unit": "source document", "endpoint": "N", + "split_rule": "as print_real_val", "owner": "PRINT", + "caution": "document counts per language-script are small for the thin languages; see counts.json; the text is the PDF's own text layer, not a human transcript"}, + {"name": "more_real_print", "manifest": f"{MAN}/more_real_print.tsv", "split": "test", "locked": True, "status": "ready", + "purpose": "MORE benchmark (zimoqingfeng/MORE), paragraph part, in-scope languages: text blocks cut from real PDF pages; labels are model-assisted and human-refined per the README. Paragraph level (unit paragraph), never cut into lines.", + "n_rows": len(more), "n_groups": len({r["group"] for r in more}), "manifest_sha256": sha.get("more_real_print"), + "langs": dict(mc), "unit": "paragraph", "group_unit": "source page", "owner": "PRINT", + "licence_note": "the README carries an Apache-2.0 badge in its metadata; the repository has no licence file", + "caution": "unit paragraph is not in the shared unit list (word, line, page); the manifest validator of stage DATA will flag it; newlines inside a block were replaced by one space"}, +] +ev_path = D + "/evalsets.json" +reg = json.load(open(ev_path, encoding="utf-8")) +if MORE_ONLY: + entries = [e for e in entries if e["name"] == "more_real_print"] +names = {e["name"] for e in entries} +reg["sets"] = [e for e in reg["sets"] if e.get("name") not in names] + entries +tmp = ev_path + ".print.part" +json.dump(reg, open(tmp, "w", encoding="utf-8"), ensure_ascii=False, indent=1) +os.replace(tmp, ev_path) +json.dump({"note": "entries added by stage PRINT; r5_registry.py rewrites evalsets.json from its own list and would drop them, so merge this file there", "sets": entries}, + open(D + "/evalsets_extra_print.json", "w", encoding="utf-8"), ensure_ascii=False, indent=1) +print(json.dumps(counts["totals"]), json.dumps(counts["more_real_print"]), dict(dropped)) diff --git a/scripts/r5_print/r5_print_audit_prep.sh b/scripts/r5_print/r5_print_audit_prep.sh new file mode 100644 index 0000000000000000000000000000000000000000..469db244deb8b876325dcf1fc6eac9903819f5c7 --- /dev/null +++ b/scripts/r5_print/r5_print_audit_prep.sh @@ -0,0 +1,10 @@ +#!/bin/bash +# Audit helper: 50 random test lines per language-script as numbered montage sheets (10 lines per sheet) + label text. +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +OUT=$DATA/outputs/r5/print_audit +mkdir -p $OUT +for L in "$@"; do + $CODE/.venv_print/bin/python -I $CODE/scripts/r5_print/r5_print_montage.py $DATA/data/processed/r5/print_real/_sidecars/$L.jsonl test 50 20261121 $OUT/$L > $OUT/${L}_labels.txt + echo $L $(ls $OUT/${L}_*.png | wc -l) +done diff --git a/scripts/r5_print/r5_print_dupcheck.py b/scripts/r5_print/r5_print_dupcheck.py new file mode 100644 index 0000000000000000000000000000000000000000..5513921dbf43668ece35b234da481eecff913662 --- /dev/null +++ b/scripts/r5_print/r5_print_dupcheck.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python3 +"""Final leakage checks on the sidecars: (1) the same PDF (doc_sha256) under two document ids or in two splits; +(2) a val/test line text that also occurs in a train line text of the same language-script; (3) val vs test text overlap.""" +import collections +import json +import os + +base = "/path/to/TURKIC_OCR_DATA/data/processed/r5/print_real/_sidecars" +LANGS = ["kk", "ky", "uz_cyrl", "uz_latn", "tr", "az", "tt", "ba", "tk", "sah"] +hash_docs = collections.defaultdict(set) +res = {"same_pdf_two_docids": [], "same_pdf_two_splits": [], "text_val_or_test_in_train": {}, "text_val_in_test": {}} +for lg in LANGS: + rows = [json.loads(x) for x in open(os.path.join(base, lg + ".jsonl"), encoding="utf-8")] + splits_of = collections.defaultdict(set) + texts = {"train": set(), "val": set(), "test": set()} + for r in rows: + hash_docs[r["doc_sha256"]].add((r["group"], r["split"])) + texts[r["split"]].add(r["text"]) + res["text_val_or_test_in_train"][lg] = len((texts["val"] | texts["test"]) & texts["train"]) + res["text_val_in_test"][lg] = len(texts["val"] & texts["test"]) +for h, s in hash_docs.items(): + docs = {d for d, _ in s} + spl = {sp for _, sp in s} + if len(docs) > 1: + res["same_pdf_two_docids"].append([h[:12], sorted(s)]) + if len(spl) > 1: + res["same_pdf_two_splits"].append([h[:12], sorted(s)]) +print(json.dumps(res, ensure_ascii=False)[:3000]) +json.dump(res, open("/path/to/TURKIC_OCR_DATA/outputs/r5/print_real_out/dupcheck.json", "w"), ensure_ascii=False, indent=1) diff --git a/scripts/r5_print/r5_print_fetch.py b/scripts/r5_print/r5_print_fetch.py new file mode 100644 index 0000000000000000000000000000000000000000..f0f56bfd6b589de93bd8ec5733bce09016e43544 --- /dev/null +++ b/scripts/r5_print/r5_print_fetch.py @@ -0,0 +1,238 @@ +#!/usr/bin/env python3 +"""R5 PRINT stage A2: fetch the original PDFs of the candidate list (download only, no parsing). + +Each document goes into its own folder RAW///doc.pdf with meta.json beside it. +Downloaded files are untrusted data and are never executed or opened here (only the first bytes are +checked for the %PDF magic). A host that answers 401/403/429/451 is dropped for the rest of the run +(no bypass); a host with 3 connection failures is dropped too. At most one request per host per second. + +Usage: + python -I r5_print_fetch.py cand CANDIDATE_DIR RAW_DIR CFG TARGET + python -I r5_print_fetch.py tbmm RAW_DIR TERMS(comma list) PER_TERM_YEAR SEED +""" +import hashlib +import json +import os +import random +import re +import sys +import threading +import time +import concurrent.futures as cf +from urllib.parse import urlparse + +import requests + +MAX_BYTES = 80 * 1024 * 1024 +DEADLINE_S = 100 +HOST_LOCK = {} +HOST_LAST = {} +HOST_FAIL = {} +BLOCKED = set() +G = threading.Lock() +COUNT = {"ok": 0} + + +def host_lock(h): + with G: + if h not in HOST_LOCK: + HOST_LOCK[h] = threading.Lock() + HOST_LAST[h] = 0.0 + return HOST_LOCK[h] + + +def fetch(url, dest_pdf, host, timeout=(8, 25)): + """returns (status, reason, nbytes, sha256)""" + lk = host_lock(host) + with lk: + if host in BLOCKED: + return ("skipped", "host blocked earlier", 0, "") + wait = 1.0 - (time.time() - HOST_LAST[host]) + if wait > 0: + time.sleep(wait) + t0 = time.time() + try: + r = requests.get(url, stream=True, timeout=timeout, allow_redirects=True, + headers={"Accept": "application/pdf,*/*;q=0.5"}) + except Exception as e: # connection problems, TLS errors, timeouts + HOST_LAST[host] = time.time() + with G: + HOST_FAIL[host] = HOST_FAIL.get(host, 0) + 1 + if HOST_FAIL[host] >= 3: + BLOCKED.add(host) + return ("error", type(e).__name__, 0, "") + HOST_LAST[host] = time.time() + if r.status_code in (401, 403, 429, 451): + with G: + BLOCKED.add(host) + r.close() + return (str(r.status_code), "refused; host dropped", 0, "") + if r.status_code != 200: + r.close() + return (str(r.status_code), "not 200", 0, "") + h = hashlib.sha256() + n = 0 + first = b"" + tmp = dest_pdf + ".part" + os.makedirs(os.path.dirname(dest_pdf), exist_ok=True) + try: + with open(tmp, "wb") as fo: + for chunk in r.iter_content(chunk_size=1 << 16): + if not chunk: + continue + if not first: + first = chunk[:1024] + if b"%PDF" not in first: + r.close() + fo.close() + os.remove(tmp) + return ("notpdf", "no %PDF magic in first 1 KB", 0, "") + n += len(chunk) + if n > MAX_BYTES: + r.close() + fo.close() + os.remove(tmp) + return ("toolarge", f">{MAX_BYTES} bytes", n, "") + if time.time() - t0 > DEADLINE_S: + r.close() + fo.close() + os.remove(tmp) + return ("slow", f">{DEADLINE_S}s", n, "") + h.update(chunk) + fo.write(chunk) + except Exception as e: + try: + os.remove(tmp) + except OSError: + pass + return ("error", "stream " + type(e).__name__, n, "") + if n < 1000: + os.remove(tmp) + return ("tiny", "under 1000 bytes", n, "") + os.replace(tmp, dest_pdf) + return ("ok", "", n, h.hexdigest()) + + +def do_candidate(c, raw, target, logf): + if COUNT["ok"] >= target: + return None + docid = c["lang"] + "_" + hashlib.sha1(c["url"].encode()).hexdigest()[:10] + d = os.path.join(raw, c["lang"], docid) + if os.path.exists(os.path.join(d, "meta.json")): + return "exists" + st, why, n, sha = fetch(c["url"], os.path.join(d, "doc.pdf"), c["host"]) + rec = {"docid": docid, "url": c["url"], "host": c["host"], "status": st, "why": why, + "bytes": n, "sha256": sha, "t": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())} + with G: + logf.write(json.dumps(rec, ensure_ascii=False) + "\n") + logf.flush() + if st == "ok": + COUNT["ok"] += 1 + if st == "ok": + meta = {"docid": docid, "lang": c["lang"], "url": c["url"], "host": c["host"], "bytes": n, + "sha256": sha, "source": "finepdfs", "finepdfs_id": c.get("id"), "finepdfs_cfg": c.get("cfg"), + "finepdfs_dump": c.get("dump"), "finepdfs_pages": c.get("pages"), + "fetched_utc": rec["t"]} + with open(os.path.join(d, "meta.json"), "w", encoding="utf-8") as fm: + json.dump(meta, fm, ensure_ascii=False) + return st + + +def run_cand(cand_dir, raw, cfg, target): + cands = [json.loads(x) for x in open(os.path.join(cand_dir, f"candidates_{cfg}.jsonl"), encoding="utf-8")] + lang = cands[0]["lang"] + os.makedirs(os.path.join(raw, "_fetch"), exist_ok=True) + # count what already exists (resume) + ld = os.path.join(raw, lang) + if os.path.isdir(ld): + COUNT["ok"] = sum(1 for x in os.listdir(ld) if os.path.exists(os.path.join(ld, x, "meta.json"))) + print(cfg, "candidates", len(cands), "already", COUNT["ok"], "target", target, flush=True) + with open(os.path.join(raw, "_fetch", f"fetch_log_{cfg}.jsonl"), "a", encoding="utf-8") as logf: + with cf.ThreadPoolExecutor(max_workers=12) as ex: + futs = [ex.submit(do_candidate, c, raw, target, logf) for c in cands] + stats = {} + for f in cf.as_completed(futs): + try: + r = f.result() + except Exception as e: + r = "exc:" + type(e).__name__ + if r is not None: + stats[r] = stats.get(r, 0) + 1 + print(cfg, "done", json.dumps(stats), "ok_total", COUNT["ok"], "blocked_hosts", len(BLOCKED), flush=True) + with open(os.path.join(raw, "_fetch", f"fetch_summary_{cfg}.json"), "w") as fo: + json.dump({"cfg": cfg, "lang": lang, "candidates": len(cands), "stats": stats, + "ok_total": COUNT["ok"], "blocked_hosts": sorted(BLOCKED)}, fo, indent=1) + + +def get_text(url, timeout=(8, 30)): + host = urlparse(url).netloc + lk = host_lock(host) + with lk: + wait = 1.0 - (time.time() - HOST_LAST[host]) + if wait > 0: + time.sleep(wait) + r = requests.get(url, timeout=timeout) + HOST_LAST[host] = time.time() + if r.status_code != 200: + raise RuntimeError(f"{r.status_code} {url}") + return r.text + + +def run_tbmm(raw, terms, per, seed): + """TBMM minutes: sitting list pages -> sitting page -> 'Basilmis' (printed) PDF on cdn.tbmm.gov.tr.""" + rng = random.Random(int(seed)) + os.makedirs(os.path.join(raw, "_fetch"), exist_ok=True) + logf = open(os.path.join(raw, "_fetch", "fetch_log_tbmm.jsonl"), "a", encoding="utf-8") + base = "https://www.tbmm.gov.tr" + for term in [int(t) for t in terms.split(",")]: + for year in range(1, 6): + try: + html = get_text(f"{base}/Tutanaklar/DoneminTutanakMetinleri?Donem={term}&YasamaYili={year}") + except Exception as e: + print("list fail", term, year, e, flush=True) + continue + ids = sorted(set(re.findall(r"/Tutanaklar/Tutanak\?Id=([0-9a-fA-F-]{36})", html))) + if not ids: + continue + rng.shuffle(ids) + got = 0 + for tid in ids: + if got >= per: + break + try: + page = get_text(f"{base}/Tutanaklar/Tutanak?Id={tid}") + except Exception as e: + print("sitting fail", tid, e, flush=True) + continue + m = re.search(r"https://cdn\.tbmm\.gov\.tr/TbmmWeb/Tutanak/(\d+)/(\d+)/(\d+)/Basilmis/[0-9a-fA-F-]{36}\.pdf", page) + if not m: + continue + url = m.group(0) + docid = f"tr_tbmm_d{m.group(1)}y{m.group(2)}b{m.group(3)}" + d = os.path.join(raw, "tr", docid) + if os.path.exists(os.path.join(d, "meta.json")): + got += 1 + continue + st, why, n, sha = fetch(url, os.path.join(d, "doc.pdf"), "cdn.tbmm.gov.tr", timeout=(10, 60)) + rec = {"docid": docid, "url": url, "host": "cdn.tbmm.gov.tr", "status": st, "why": why, + "bytes": n, "sha256": sha, "t": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())} + logf.write(json.dumps(rec) + "\n") + logf.flush() + print(docid, st, n, flush=True) + if st == "ok": + got += 1 + with open(os.path.join(d, "meta.json"), "w", encoding="utf-8") as fm: + json.dump({"docid": docid, "lang": "tr", "url": url, "host": "cdn.tbmm.gov.tr", + "bytes": n, "sha256": sha, "source": "tbmm_minutes", + "term": int(m.group(1)), "legislative_year": int(m.group(2)), + "sitting": int(m.group(3)), "fetched_utc": rec["t"]}, fm) + + +if __name__ == "__main__": + mode = sys.argv[1] + if mode == "cand": + run_cand(sys.argv[2], sys.argv[3], sys.argv[4], int(sys.argv[5])) + elif mode == "tbmm": + run_tbmm(sys.argv[2], sys.argv[3], int(sys.argv[4]), sys.argv[5]) + else: + raise SystemExit("mode?") diff --git a/scripts/r5_print/r5_print_fetch_all.sh b/scripts/r5_print/r5_print_fetch_all.sh new file mode 100644 index 0000000000000000000000000000000000000000..8f5f4399241b1002c42079f9d321ac2f45e4ea09 --- /dev/null +++ b/scripts/r5_print/r5_print_fetch_all.sh @@ -0,0 +1,13 @@ +#!/bin/bash +# Download-only driver (login node, nice'd). Three language groups in parallel; each group sequential. +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +RAW=$DATA/data/raw/r5_print +CAND=$RAW/_select +PY=$CODE/.venv_print/bin/python +run() { for cfg in "$@"; do nice -n 10 env -u HF_TOKEN -u HUGGING_FACE_HUB_TOKEN $PY -I $CODE/scripts/r5_print/r5_print_fetch.py cand $CAND $RAW $cfg 100; done; } +run sah_Cyrl bak_Cyrl tuk_Latn & +run tat_Cyrl kir_Cyrl uzn_Cyrl & +nice -n 10 $PY -I $CODE/scripts/r5_print/r5_print_fetch.py tbmm $RAW 28,27,26,25,24 2 20261121 & +wait +echo fetch_all_done diff --git a/scripts/r5_print/r5_print_fetch_all2.sh b/scripts/r5_print/r5_print_fetch_all2.sh new file mode 100644 index 0000000000000000000000000000000000000000..c7955c227a52ff2950bb2c37106c1b7eb2425a9c --- /dev/null +++ b/scripts/r5_print/r5_print_fetch_all2.sh @@ -0,0 +1,14 @@ +#!/bin/bash +# Download-only driver, second batch (login node, nice'd). +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +RAW=$DATA/data/raw/r5_print +CAND=$RAW/_select +PY=$CODE/.venv_print/bin/python +f() { nice -n 10 env -u HF_TOKEN -u HUGGING_FACE_HUB_TOKEN $PY -I $CODE/scripts/r5_print/r5_print_fetch.py cand $CAND $RAW $1 $2; } +f kaz_Cyrl 100 & +f uzn_Latn 100 & +f azj_Latn 100 & +f tur_Latn 60 & +wait +echo fetch_all2_done diff --git a/scripts/r5_print/r5_print_fetch_all3.sh b/scripts/r5_print/r5_print_fetch_all3.sh new file mode 100644 index 0000000000000000000000000000000000000000..6c6999ba1ac8e557d91b3a24ee371171c3e813d6 --- /dev/null +++ b/scripts/r5_print/r5_print_fetch_all3.sh @@ -0,0 +1,14 @@ +#!/bin/bash +# Download-only driver, round 3: more candidates per language (login node, nice'd), resumes from existing meta.json files. +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +RAW=$DATA/data/raw/r5_print +CAND=$RAW/_select +PY=$CODE/.venv_print/bin/python +f() { nice -n 10 env -u HF_TOKEN -u HUGGING_FACE_HUB_TOKEN $PY -I $CODE/scripts/r5_print/r5_print_fetch.py cand $CAND $RAW $1 $2; } +( f sah_Cyrl 180; f bak_Cyrl 180; f tuk_Latn 180 ) & +( f tat_Cyrl 180; f kir_Cyrl 180; f uzn_Cyrl 180 ) & +( f kaz_Cyrl 160; f uzn_Latn 160 ) & +( f azj_Latn 160; f tur_Latn 120 ) & +wait +echo fetch_all3_done diff --git a/scripts/r5_print/r5_print_fetch_all4.sh b/scripts/r5_print/r5_print_fetch_all4.sh new file mode 100644 index 0000000000000000000000000000000000000000..d63e4be47256286af6e1acba886f4e42ec621cbf --- /dev/null +++ b/scripts/r5_print/r5_print_fetch_all4.sh @@ -0,0 +1,14 @@ +#!/bin/bash +# Download-only driver, round 4: stricter candidate lists (_select2) for the thin languages (login node, nice'd). +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +RAW=$DATA/data/raw/r5_print +CAND=$RAW/_select2 +PY=$CODE/.venv_print/bin/python +f() { nice -n 10 env -u HF_TOKEN -u HUGGING_FACE_HUB_TOKEN $PY -I $CODE/scripts/r5_print/r5_print_fetch.py cand $CAND $RAW $1 $2; } +( f tuk_Latn 400 ) & +( f bak_Cyrl 400; f sah_Cyrl 400 ) & +( f tat_Cyrl 260 ) & +( f kir_Cyrl 260 ) & +wait +echo fetch_all4_done diff --git a/scripts/r5_print/r5_print_fetch_all5.sh b/scripts/r5_print/r5_print_fetch_all5.sh new file mode 100644 index 0000000000000000000000000000000000000000..99a9b458c56f91687c700a56aa654bea21b2b080 --- /dev/null +++ b/scripts/r5_print/r5_print_fetch_all5.sh @@ -0,0 +1,14 @@ +#!/bin/bash +# Download-only driver, round 5: larger candidate lists (_select3) for tr, uz_latn, az (login node, nice'd). +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +RAW=$DATA/data/raw/r5_print +PY=$CODE/.venv_print/bin/python +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN +nice -n 10 $PY -I $CODE/scripts/r5_print/r5_print_select3.py $RAW/_select3 tur_Latn uzn_Latn azj_Latn +f() { nice -n 10 $PY -I $CODE/scripts/r5_print/r5_print_fetch.py cand $RAW/_select3 $RAW $1 $2; } +f tur_Latn 230 & +f uzn_Latn 190 & +f azj_Latn 190 & +wait +echo fetch_all5_done diff --git a/scripts/r5_print/r5_print_login_all.sh b/scripts/r5_print/r5_print_login_all.sh new file mode 100644 index 0000000000000000000000000000000000000000..5dfef4db129abadd3262366d51f8499a1e165677 --- /dev/null +++ b/scripts/r5_print/r5_print_login_all.sh @@ -0,0 +1,3 @@ +#!/bin/bash +CODE=/path/to/TURKIC_OCR_CODE +for L in "$@"; do bash $CODE/scripts/r5_print/r5_print_login_run.sh $L; done diff --git a/scripts/r5_print/r5_print_login_run.sh b/scripts/r5_print/r5_print_login_run.sh new file mode 100644 index 0000000000000000000000000000000000000000..b12a7b7288fbb7e46724fcc1fc044df98859c708 --- /dev/null +++ b/scripts/r5_print/r5_print_login_run.sh @@ -0,0 +1,11 @@ +#!/bin/bash +# Login-node run of r5_print_process.py for ONE language at nice 19 with 4 workers, with CPU time report. +# (deviation from the ZEN4 rule, justified in the report: ZEN4 start estimate was after 03:45 UTC) +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN +L=$1 +TIMEFORMAT="$L cpu_user_s=%U cpu_sys_s=%S wall_s=%R" +time nice -n 19 $CODE/.venv_print/bin/python -I $CODE/scripts/r5_print/r5_print_process.py --lang $L \ + --raw $DATA/data/raw/r5_print --out $DATA/data/processed/r5/print_real \ + --corpus $DATA/data/processed/r5/pagesynth_text_split --workers 4 --maxpages 40 --exclude $DATA/data/processed/r5/print_real/_excluded_docs.txt 2>&1 | grep -E "lexicon|documents|parsed|split|render jobs|DONE|Traceback|Error" diff --git a/scripts/r5_print/r5_print_more_build.py b/scripts/r5_print/r5_print_more_build.py new file mode 100644 index 0000000000000000000000000000000000000000..ba164536975c0d8ae7766ddac6b7954e54e3be82 --- /dev/null +++ b/scripts/r5_print/r5_print_more_build.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python3 +"""Build the locked test set more_real_print from zimoqingfeng/MORE (paragraph part). + +One row per annotated text block (unit paragraph) of the in-scope languages. The repository already ships +one cropped image per block (paragraph/images/_.jpg); those files are used in place +(only their bytes are read, to hash them; nothing is decoded or shown). Nothing is cut at line level. Labels are the MORE annotations (model-assisted, +human-refined, per the dataset README); newlines inside a block become one space. +Usage: python -I r5_print_more_build.py RAWMORE OUTROOT CORPUS_DIR MODULE_PATH +""" +import hashlib +import importlib.util +import io +import json +import os +import re +import sys +import unicodedata +from collections import Counter + + +raw, out, corpus, modpath = sys.argv[1:5] +spec = importlib.util.spec_from_file_location("rpp", modpath) +rpp = importlib.util.module_from_spec(spec) +spec.loader.exec_module(rpp) + +PAGE_LANG = {"kk": "kk", "ky": "ky", "uz": "uz", "tr": "tr", "az": "az", "tt": "tt", "ba": "ba", "tk": "tk", "sah": "sah"} +data = json.load(open(os.path.join(raw, "paragraph", "MORE_paragraph.json"), encoding="utf-8")) +lex = {} +rows = [] +stats = Counter() +cyr = re.compile("[Ѐ-ӿ]") +lat = re.compile("[A-Za-zÀ-ɏ]") +for it in data: + code = it["page_info"].get("page_attribute", {}).get("language") + if code not in PAGE_LANG: + continue + imgname = it["page_info"]["image_path"] + stem = os.path.splitext(imgname)[0] + for ld in it["layout_dets"]: + stats[code + "_blocks_total"] += 1 + if ld.get("category_type") != "text_block": + stats["not_text_block"] += 1 + continue + if (ld.get("attribute") or {}).get("text_rotate", "normal") != "normal": + stats["rotated"] += 1 + continue + txt = ld.get("text") or "" + if re.search(r"[$\\<>|]", txt) or "{" in txt: + stats["markup_like"] += 1 + continue + txt = unicodedata.normalize("NFC", re.sub(r"\s+", " ", txt)).strip() + if len(txt) < 3: + stats["too_short"] += 1 + continue + nc, nl = len(cyr.findall(txt)), len(lat.findall(txt)) + script = "Cyrl" if nc > nl else "Latn" + lang = code + if code == "uz": + lang = "uz_cyrl" if script == "Cyrl" else "uz_latn" + full = os.path.join(raw, "paragraph", "images", f"{stem}_{ld.get('anno_id')}.jpg") + if not os.path.exists(full): + stats["paragraph_crop_missing"] += 1 + continue + with open(full, "rb") as fi: + sha = hashlib.sha256(fi.read()).hexdigest() + lid = f"more:{lang}:{stem}:{ld.get('anno_id')}" + if lang not in lex: + lex[lang] = rpp.build_lexicon(corpus, lang)[0] + toks = rpp.tokens(txt, lang) + sh = rpp.share(toks, lex[lang]) if len(toks) >= 8 else None + bad_chars = sorted({c for c in txt if c not in rpp.PUNCT and c.lower() not in set(rpp.PROFILES[lang]["letters"]) | set("abcdefghijklmnopqrstuvwxyz")}) + rows.append({"id": lid, "image": full, "text": txt, "lang": lang, "script": script, "kind": "typed_real", + "source": "MORE:zimoqingfeng/MORE paragraph (page language code %s)" % code, "split": "test", + "group": stem, "unit": "paragraph", "sha256": sha, "lexicon_share": sh, + "chars_outside_alphabet": bad_chars, "chars": len(txt)}) + stats["kept_" + lang] += 1 +with open(os.path.join(out, "_sidecars", "more.jsonl"), "w", encoding="utf-8") as fo: + for r in rows: + fo.write(json.dumps(r, ensure_ascii=False) + "\n") +summary = {"kept": len(rows), "stats": dict(stats), + "pages_by_lang": dict(Counter(r["lang"] for r in {(r["group"], r["lang"]): r for r in rows}.values())), + "chars_total": sum(r["chars"] for r in rows), + "low_lexicon_share_blocks(<0.2, >=8 tokens)": [(r["id"], round(r["lexicon_share"], 2)) for r in rows if r["lexicon_share"] is not None and r["lexicon_share"] < 0.2], + "blocks_with_chars_outside_alphabet": sum(1 for r in rows if r["chars_outside_alphabet"])} +json.dump(summary, open(os.path.join(out, "_stats", "more.json"), "w"), indent=1, ensure_ascii=False) +print(json.dumps(summary, ensure_ascii=False)[:3000]) diff --git a/scripts/r5_print/r5_print_more_fetch.py b/scripts/r5_print/r5_print_more_fetch.py new file mode 100644 index 0000000000000000000000000000000000000000..f2078003b5b1e4fae673b292f523cd3b60b152ef --- /dev/null +++ b/scripts/r5_print/r5_print_more_fetch.py @@ -0,0 +1,6 @@ +import sys +from huggingface_hub import snapshot_download +dest = sys.argv[1] +pats = ["README.md", "paragraph/MORE_paragraph.json"] + [f"paragraph/images/{c}_*" for c in ("kk", "ky", "uz", "tr", "az", "tt", "ba", "tk", "sah")] +p = snapshot_download(repo_id="zimoqingfeng/MORE", repo_type="dataset", local_dir=dest, allow_patterns=pats) +print(p) diff --git a/scripts/r5_print/r5_print_process.py b/scripts/r5_print/r5_print_process.py new file mode 100644 index 0000000000000000000000000000000000000000..e099a65b83bc9e0344540be045a7b2ac8fb70e09 --- /dev/null +++ b/scripts/r5_print/r5_print_process.py @@ -0,0 +1,937 @@ +#!/usr/bin/env python3 +"""R5 PRINT stage B: PDF text layer -> line crops for ONE language-script (ZEN4 job). + +Steps (per language): + 1. parse every PDF in RAW///doc.pdf with PyMuPDF (never executes anything inside it): + page and line gates, text normalisation, character allow-list, script-mixing check, language gate + (share of tokens in the top words of the project's own reference text for that language). + 2. document gate, split by document (stratified, seeded), exact-text leakage filter for val/test. + 3. line sampling (water-filling over documents), page render at a random 150-300 dpi, crops with + 2-6 px padding, sha256 of every crop, sidecar JSONL (id, image, text, page, dpi, bbox, sha256, ...). +Run: python -I r5_print_process.py --lang kk --raw RAW --out OUT --corpus CORPUS_DIR --workers 8 +""" +import argparse +import hashlib +import io +import json +import math +import os +import random +import re +import signal +import sys +import time +import unicodedata +import collections +from collections import Counter + +import numpy as np +import pymupdf +from PIL import Image + +SEED = 20261121 +RU = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя" +PROFILES = { + "kk": dict(script="Cyrl", letters=RU + "әғқңөұүһі"), + "ky": dict(script="Cyrl", letters=RU + "ңөү"), + "uz_cyrl": dict(script="Cyrl", letters=RU + "ўқғҳ"), + "tt": dict(script="Cyrl", letters=RU + "әөүҗңһ"), + "ba": dict(script="Cyrl", letters=RU + "әөүғҡңҙҫһ"), + "sah": dict(script="Cyrl", letters=RU + "ҕҥөүһ"), + "tr": dict(script="Latn", letters="abcçdefgğhıijklmnoöprsştuüvyzqwxâîû"), + "az": dict(script="Latn", letters="abcçdeəfgğhxıijkqlmnoöprsştuüvyzwâ"), + "tk": dict(script="Latn", letters="abcçdefghijklmnoprstuvwyzäöüýňşž"), + "uz_latn": dict(script="Latn", letters="abcdefghijklmnopqrstuvxyz" + "ʻʼ"), +} +APOS = "ʻʼ'’‘`´" +# letters that Russian or English text never has (used to keep Russian and English lines out of a language) +# letters whose printed form has a tail below the baseline; if the text layer says one of them but the pixels show no tail, +# the font printed the plain letter (k, x, n, s) and the label is wrong +TAIL = set("қҚҳҲңҢҫҪ") # not the Sakha letter ҥ: it carries a hook at the top right, no tail +SPEC = {"kk": "әғқңөұүһі", "ky": "ңөү", "uz_cyrl": "ўқғҳ", "tt": "әөүҗңһ", "ba": "әөүғҡңҙҫһ", "sah": "ҕҥөүһ", + "tr": "çğıöşü", "az": "əçğıöşü", "tk": "äçöüýňşž", "uz_latn": "ʻʼ"} +PUNCT = set(" .,:;!?-–—‑−_'\"’‘“”«»„‚()[]{}/\\%№§°+=<>*&#@$€£|~^…·•ʻʼ`´" + "0123456789") +CYR = re.compile("[Ѐ-ӿ]") +LAT = re.compile("[A-Za-zÀ-ɏ]") +LIG = {"ff": "ff", "fi": "fi", "fl": "fl", "ffi": "ffi", "ffl": "ffl", "ſt": "st", "st": "st"} +SPACES = dict.fromkeys([0xA0, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, + 0x202F, 0x205F, 0x3000], " ") +DROPCH = {0xAD: None, 0x200B: None, 0x200C: None, 0x200D: None, 0x2060: None, 0xFEFF: None, 0x200E: None, 0x200F: None} + + +class Timeout(Exception): + pass + + +def _alarm(signum, frame): + raise Timeout() + + +def lower_key(s, lang): + if lang in ("tr", "az"): + s = s.replace("İ", "i").replace("I", "ı") + s = s.lower() + if lang == "uz_latn": + for a in APOS: + s = s.replace(a, "ʻ") + return s + + +TOK = re.compile(r"[^\W\d_]+(?:ʻ[^\W\d_]+)*", re.U) + + +def tokens(s, lang): + return TOK.findall(lower_key(s, lang)) + + +EXCLUDE = set() # documents left out after the audit found that their text layer disagrees with the visible glyphs +KNOWN = set() # words seen at least twice in the reference text of the language (filled by build_lexicon) + + +def build_lexicon(corpus_dir, lang, nsent=250000, topk=4000): + global KNOWN + p = os.path.join(corpus_dir, "train", lang, "sentences.tsv") + c = Counter() + n = 0 + with open(p, encoding="utf-8") as f: + for line in f: + parts = line.rstrip("\n").split("\t", 1) + if len(parts) < 2: + continue + c.update(tokens(parts[1], lang)) + n += 1 + if n >= nsent: + break + KNOWN = {w for w, k in c.items() if k >= 2} + return {w for w, _ in c.most_common(topk)}, n + + +def share(toks, lex): + if not toks: + return None + return sum(1 for t in toks if t in lex) / len(toks) + + +def normalise(raw): + r0 = raw.rstrip() + if r0.endswith("\u00ad"): + raw = r0[:-1] + "-" # a soft hyphen at the end of a line is printed as a hyphen + s = raw.translate(DROPCH) + for k, v in LIG.items(): + s = s.replace(k, v) + s = s.translate(SPACES) + s = re.sub(r"\s+", " ", s).strip() + return unicodedata.normalize("NFC", s) + + +def line_ok(s, lang): + """returns (ok, reason)""" + prof = PROFILES[lang] + if len(s) < 3 or len(s) > 160: + return False, "length" + letters = set(prof["letters"]) | set(prof["letters"].upper()) + if lang in ("tr", "az"): + letters |= {"İ"} + allowed_lat = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") + nlet = 0 + for ch in s: + if ch in PUNCT: + continue + if ch in letters: + nlet += 1 + continue + if prof["script"] == "Cyrl" and ch in allowed_lat: + nlet += 1 + continue + if prof["script"] == "Latn" and ch in allowed_lat: + nlet += 1 + continue + return False, "charset" + if lang == "uz_latn" and ("\u201e" in s or "\u201a" in s): + return False, "odd_apostrophe" # low quotes stand in for the okina in some fonts; the glyph and the code disagree + if prof["script"] == "Latn" and CYR.search(s): + return False, "cyrillic_in_latin" + if nlet < 2 or nlet < 0.5 * len(s.replace(" ", "")): + return False, "few_letters" + if re.search(r"[^\W\d_]\d+[^\W\d_]", s): + return False, "digit_inside_word" + # script mixing inside one word (homoglyph risk) + for w in re.split(r"[\s\-–—/.,;:!?()\[\]«»“”\"]+", s): + if w and CYR.search(w) and LAT.search(w): + return False, "mixed_script_word" + if prof["script"] == "Cyrl": + nl = len(LAT.findall(s)) + if nl > 0.3 * max(1, nlet): + return False, "too_latin" + return True, "" + + +def order_blocks(blocks, W): + """column ordering: full-width blocks split bands; inside a band, columns left to right.""" + blocks = sorted(blocks, key=lambda b: (b["bbox"][1], b["bbox"][0])) + out, band = [], [] + + def flush(): + cols = [] + for b in sorted(band, key=lambda b: b["bbox"][0]): + x0, x1 = b["bbox"][0], b["bbox"][2] + placed = False + for c in cols: + ov = min(x1, c["x1"]) - max(x0, c["x0"]) + if ov > 0.3 * min(x1 - x0, c["x1"] - c["x0"]): + c["items"].append(b) + c["x0"], c["x1"] = min(c["x0"], x0), max(c["x1"], x1) + placed = True + break + if not placed: + cols.append({"x0": x0, "x1": x1, "items": [b]}) + for c in sorted(cols, key=lambda c: c["x0"]): + out.extend(sorted(c["items"], key=lambda b: b["bbox"][1])) + band.clear() + + for b in blocks: + if b["bbox"][2] - b["bbox"][0] > 0.6 * W: + flush() + out.append(b) + else: + band.append(b) + flush() + return out + + +def rect_overlap(a, b): + x0, y0 = max(a[0], b[0]), max(a[1], b[1]) + x1, y1 = min(a[2], b[2]), min(a[3], b[3]) + if x1 <= x0 or y1 <= y0: + return 0.0 + return (x1 - x0) * (y1 - y0) + + +def parse_page(page, lang, lex): + W, H = page.rect.width, page.rect.height + st = {"lines_seen": 0} + if page.rotation != 0: + return None, "rotated_page", st + if W > 1500 or H > 1500 or W < 100 or H < 100: + return None, "odd_page_size", st + try: + tt = page.get_texttrace() + except Exception: + tt = [] + gmap = {} + for sp in tt: + if sp.get("type") == 3 or sp.get("opacity", 1) == 0: + return None, "invisible_text", st + f_ = sp.get("font") + for c_ in sp.get("chars", ()): + ch_ = chr(c_[0]) + if ch_.isalpha(): + gmap.setdefault(f"{f_}|{c_[1]}", set()).add(ch_.lower()) + try: + infos = page.get_image_info() + except Exception: + infos = [] + irects = [] + for im in infos: + bb = im.get("bbox") + if bb: + irects.append(tuple(bb)) + if (bb[2] - bb[0]) * (bb[3] - bb[1]) > 0.5 * W * H: + return None, "fullpage_image", st + d = page.get_text("dict", flags=pymupdf.TEXTFLAGS_DICT & ~pymupdf.TEXT_PRESERVE_IMAGES) + allchars = 0 + bad = 0 + blocks = [] + for b in d["blocks"]: + if b.get("type") != 0: + continue + lines = [] + for ln in b["lines"]: + sp = ln["spans"] + if not sp: + continue + txt = "".join(s["text"] for s in sp) + allchars += len(txt) + bad += sum(1 for ch in txt if 0xE000 <= ord(ch) <= 0xF8FF or ch == "�" or ord(ch) < 32) + lines.append({"bbox": tuple(ln["bbox"]), "dir": ln["dir"], "spans": sp, "raw": txt}) + if lines: + blocks.append({"bbox": tuple(b["bbox"]), "lines": lines}) + if allchars < 40: + return None, "little_text", st + if bad / max(1, allchars) > 0.005: + return None, "broken_tounicode", st + blocks = order_blocks(blocks, W) + alllines = [ln["bbox"] for b in blocks for ln in b["lines"] if abs(ln["dir"][1]) <= 0.05 and ln["dir"][0] > 0] + page_tokens = [] + cand = [] + for bi, b in enumerate(blocks): + btoks = [] + blines = [] + for ln in b["lines"]: + st["lines_seen"] += 1 + if abs(ln["dir"][1]) > 0.05 or ln["dir"][0] <= 0: + continue + s = normalise(ln["raw"]) + ok, why = line_ok(s, lang) + if not ok: + st["rej_" + why] = st.get("rej_" + why, 0) + 1 + continue + sp = ln["spans"] + size = max(x["size"] for x in sp) + if size < 6.5 or max(x["size"] for x in sp) > 2.2 * min(x["size"] for x in sp): + st["rej_size"] = st.get("rej_size", 0) + 1 + continue + gap_bad = False + for a, c in zip(sp, sp[1:]): + if c["bbox"][0] - a["bbox"][2] > 1.6 * size: + gap_bad = True + if gap_bad: + st["rej_gap"] = st.get("rej_gap", 0) + 1 + continue + bb = ln["bbox"] + area = max(1e-6, (bb[2] - bb[0]) * (bb[3] - bb[1])) + if any(rect_overlap(bb, r) > 0.05 * area for r in irects): + st["rej_image_overlap"] = st.get("rej_image_overlap", 0) + 1 + continue + tk = tokens(s, lang) + if len(tk) >= 5 and sum(1 for t in tk if t not in KNOWN) > 0.5 * len(tk): + st["rej_oov"] = st.get("rej_oov", 0) + 1 + continue + btoks.extend(tk) + blines.append({"bbox": bb, "text": s, "size": size, "block": bi, "ntok": len(tk), "share": share(tk, lex), + "base": sp[0]["origin"][1]}) + page_tokens.extend(btoks) + bsh = share(btoks, lex) if len(btoks) >= 8 else None + for ln in blines: + ln["block_share"] = bsh + cand.extend(blines) + # where the box of a neighbouring line overlaps this line's box, cut in the middle of the overlap + for a_ in cand: + ab = a_["bbox"] + acy = (ab[1] + ab[3]) / 2 + ct, cb = None, None + for c_ in alllines: + if c_ == ab: + continue + if min(ab[2], c_[2]) - max(ab[0], c_[0]) <= 0: + continue + ccy = (c_[1] + c_[3]) / 2 + if ccy < acy and c_[3] > ab[1]: + m = (ab[1] + c_[3]) / 2 + ct = m if ct is None else max(ct, m) + elif ccy > acy and c_[1] < ab[3]: + m = (ab[3] + c_[1]) / 2 + cb = m if cb is None else min(cb, m) + base_, size_ = a_["base"], a_["size"] + if ct is not None: + ct = min(ct, base_ - 0.95 * size_) + if cb is not None: + cb = max(cb, base_ + 0.30 * size_) + a_["cut_top"], a_["cut_bot"] = ct, cb + # overlap between lines (superimposed text) + keep = [] + for i, a in enumerate(cand): + area = max(1e-6, (a["bbox"][2] - a["bbox"][0]) * (a["bbox"][3] - a["bbox"][1])) + clash = False + for j, c in enumerate(cand): + if i != j and rect_overlap(a["bbox"], c["bbox"]) > 0.3 * min( + area, (c["bbox"][2] - c["bbox"][0]) * (c["bbox"][3] - c["bbox"][1])): + clash = True + break + if clash: + st["rej_line_overlap"] = st.get("rej_line_overlap", 0) + 1 + else: + keep.append(a) + psh = share(page_tokens, lex) if len(page_tokens) >= 15 else None + st["page_share"] = psh + st["page_tokens"] = len(page_tokens) + return {"lines": keep, "page_share": psh, "ntok": len(page_tokens), "gmap": gmap}, "", st + + +def parse_doc(job): + docdir, lang, lexlist, maxpages = job + lex = set(lexlist) + docid = os.path.basename(docdir) + res = {"docid": docid, "status": "ok", "pages_total": 0, "pages_sampled": 0, "page_reject": {}, "pages": {}} + signal.signal(signal.SIGALRM, _alarm) + signal.alarm(150) + try: + doc = pymupdf.open(os.path.join(docdir, "doc.pdf")) + if doc.needs_pass or doc.is_encrypted: + res["status"] = "encrypted" + return res + n = doc.page_count + res["pages_total"] = n + rng = random.Random(f"{SEED}-{docid}") + idx = list(range(n)) + if n > maxpages: + idx = sorted(rng.sample(idx, maxpages)) + res["pages_sampled"] = len(idx) + shares = [] + docmap = {} # (font, glyph id) -> letters the text layer assigns to that glyph + agg = Counter() + for pno in idx: + try: + page = doc.load_page(pno) + out, why, st = parse_page(page, lang, lex) + except Timeout: + raise + except Exception as e: + res["page_reject"]["exc_" + type(e).__name__] = res["page_reject"].get("exc_" + type(e).__name__, 0) + 1 + continue + for k, v in st.items(): + if isinstance(v, int): + agg[k] += v + if out is None: + res["page_reject"][why] = res["page_reject"].get(why, 0) + 1 + continue + for k_, v_ in out.pop("gmap").items(): + docmap.setdefault(k_, set()).update(v_) + if out["page_share"] is not None: + shares.append(out["page_share"]) + res["pages"][str(pno)] = out + # one glyph that the text layer reads as two different letters (a hooked letter shown as the plain one) + res["ambiguous_glyphs"] = sorted(f"{k_}={''.join(sorted(v_))}" for k_, v_ in docmap.items() if len(v_) >= 2)[:8] + res["n_ambiguous_glyphs"] = sum(1 for v_ in docmap.values() if len(v_) >= 2) + res["line_stats"] = dict(agg) + res["median_page_share"] = float(np.median(shares)) if shares else None + res["pages_with_share"] = len(shares) + except Timeout: + res["status"] = "timeout" + except Exception as e: + res["status"] = "error:" + type(e).__name__ + ":" + str(e)[:80] + finally: + signal.alarm(0) + return res + + +def render_job(job): + docdir, lang, docid, split, outdir, pages = job + # pages: {pno: [ {idx, text, bbox, ...}, ...]} + recs = [] + nchk = nbad = 0 + signal.signal(signal.SIGALRM, _alarm) + signal.alarm(240) + try: + doc = pymupdf.open(os.path.join(docdir, "doc.pdf")) + for pno_s, lines in pages.items(): + pno = int(pno_s) + rng = random.Random(f"{SEED}-{docid}-{pno}") + dpi = rng.randint(150, 300) + page = doc.load_page(pno) + pix = page.get_pixmap(matrix=pymupdf.Matrix(dpi / 72, dpi / 72), colorspace=pymupdf.csRGB, alpha=False) + img = Image.frombytes("RGB", (pix.width, pix.height), pix.samples) + sc = dpi / 72.0 + gpage = np.asarray(img.convert("L"), dtype=np.int16) + try: + rd = page.get_text("rawdict", flags=pymupdf.TEXTFLAGS_RAWDICT & ~pymupdf.TEXT_PRESERVE_IMAGES) + except Exception: + rd = {"blocks": []} + chars_by_line = {} + for b_ in rd["blocks"]: + if b_.get("type") != 0: + continue + for l_ in b_["lines"]: + chars_by_line[tuple(round(v, 1) for v in l_["bbox"])] = [c_ for s_ in l_["spans"] for c_ in s_["chars"]] + for ln in lines: + chs = chars_by_line.get(tuple(round(v, 1) for v in ln["bbox"])) + if chs is None: + for k_, v_ in chars_by_line.items(): + if max(abs(k_[i_] - ln["bbox"][i_]) for i_ in range(4)) < 0.2: + chs = v_ + break + if chs is not None: + tail_bad = False + for c_ in chs: + if c_["c"] not in TAIL: + continue + bx0, by0, bx1, by1 = c_["bbox"] + w_ = bx1 - bx0 + base_ = c_["origin"][1] + ya, yb = int((base_ + 0.04 * ln["size"]) * sc), int((base_ + 0.28 * ln["size"]) * sc) + xa, xb = int((bx0 - 0.05 * w_) * sc), int((bx1 + 0.12 * w_) * sc) + if yb - ya < 2 or xb - xa < 2: + continue + full_ = gpage[max(0, int(by0 * sc)):int(by1 * sc), max(0, xa):xb] + reg = gpage[max(0, ya):yb, max(0, xa):xb] + if full_.size == 0 or reg.size == 0: + continue + nchk += 1 + if int((np.abs(reg - np.median(full_)) > 60).sum()) < 2: + nbad += 1 + tail_bad = True + if tail_bad: + recs.append({"id": ln["id"], "drop": "tail_letter_without_tail"}) + continue + # (1) a hole between two characters: a glyph without a text-layer code was left out; + # (2) a letter or digit whose box shows no ink: hidden, clipped or covered + size_ = ln["size"] + miss_bad = False + lx0, ly0, lx1, ly1 = ln["bbox"] + band_ = gpage[max(0, int(ly0 * sc)):int(ly1 * sc), max(0, int(lx0 * sc)):int(lx1 * sc)] + if band_.size: + bgm = float(np.median(band_)) + # (1) ink inside a gap between two characters that the text layer does not account for + for a_c, b_c in zip(chs, chs[1:]): + if (b_c["bbox"][0] - a_c["bbox"][2]) > 0.15 * size_: + gx0, gx1 = int((a_c["bbox"][2] + 0.04 * size_) * sc), int((b_c["bbox"][0] - 0.04 * size_) * sc) + gy0 = int((a_c["bbox"][1] + 0.3 * (a_c["bbox"][3] - a_c["bbox"][1])) * sc) + gy1 = int((a_c["bbox"][3] - 0.3 * (a_c["bbox"][3] - a_c["bbox"][1])) * sc) + if gx1 - gx0 >= 2 and gy1 - gy0 >= 2: + greg = gpage[max(0, gy0):gy1, max(0, gx0):gx1] + if greg.size and int((np.abs(greg - bgm) > 60).sum()) >= 4: + miss_bad = True + break + if not miss_bad: + for c_ in chs: + if not c_["c"].isalnum(): + continue + bx0, by0, bx1, by1 = c_["bbox"] + w_ = bx1 - bx0 + xa, xb = int((bx0 + 0.1 * w_) * sc), int((bx1 - 0.1 * w_) * sc) + ya, yb = int(by0 * sc), int(by1 * sc) + if xb - xa < 1 or yb - ya < 2: + continue + reg = gpage[max(0, ya):yb, max(0, xa):xb] + if reg.size and int((np.abs(reg - bgm) > 60).sum()) < 2: + miss_bad = True + break + if miss_bad: + recs.append({"id": ln["id"], "drop": "missing_or_hidden_glyph"}) + continue + bad_space = False + for c_ in chs: + if not c_["c"].isspace(): + continue + bx0, by0, bx1, by1 = c_["bbox"] + w_ = bx1 - bx0 + xa, xb = int((bx0 + 0.2 * w_) * sc), int((bx1 - 0.2 * w_) * sc) + ya, yb = int(by0 * sc), int(by1 * sc) + if xb - xa < 2 or yb - ya < 6: + continue + reg = gpage[max(0, ya):yb, max(0, xa):xb] + if reg.size == 0: + continue + rmed = np.median(gpage[max(0, ya):yb, max(0, xa - 3 * (xb - xa)):xb + 3 * (xb - xa)]) + rows = (np.abs(reg - rmed) > 80).any(axis=1).mean() + if rows >= 0.35 and w_ * sc > 3: + bad_space = True + break + if bad_space: + recs.append({"id": ln["id"], "drop": "space_over_ink"}) + continue + else: + pass + lines_ok = True + pad = rng.randint(2, 6) + x0, y0, x1, y1 = ln["bbox"] + box = (max(0, int(math.floor(x0 * sc)) - pad), max(0, int(math.floor(y0 * sc)) - pad), + min(img.width, int(math.ceil(x1 * sc)) + pad), min(img.height, int(math.ceil(y1 * sc)) + pad)) + if ln.get("cut_top") is not None: + box = (box[0], max(box[1], int(math.ceil(ln["cut_top"] * sc))), box[2], box[3]) + if ln.get("cut_bot") is not None: + box = (box[0], box[1], box[2], min(box[3], int(math.floor(ln["cut_bot"] * sc)))) + w, h = box[2] - box[0], box[3] - box[1] + if h < 14 or w < 30 or w / h > 120: + recs.append({"id": ln["id"], "drop": "geometry"}) + continue + crop = img.crop(box) + g = np.asarray(crop.convert("L"), dtype=np.int16) + med = np.median(g) + mask = np.abs(g - med) > 60 + cols = np.flatnonzero(mask.any(axis=0)) + if len(cols) == 0: + recs.append({"id": ln["id"], "drop": "ink"}) + continue + # ink touching the left or right border of the crop (middle rows): a neighbouring glyph or word is cut off + r0 = int(0.25 * mask.shape[0]) + band = mask[r0:max(int(0.75 * mask.shape[0]), r0 + 1), :] + if int(band[:, 0].sum()) >= 2 or int(band[:, -1].sum()) >= 2: + recs.append({"id": ln["id"], "drop": "edge_clipped"}) + continue + # trim blank space left and right of the ink (spaces, tabs), keep the padding + l_, r_ = max(0, int(cols[0]) - pad), min(crop.width, int(cols[-1]) + 1 + pad) + if r_ - l_ < 30: + recs.append({"id": ln["id"], "drop": "geometry"}) + continue + if l_ > 0 or r_ < crop.width: + crop = crop.crop((l_, 0, r_, crop.height)) + g = g[:, l_:r_] + mask = mask[:, l_:r_] + w = crop.width + dark = float(mask.mean()) + if dark < 0.012 or dark > 0.6: + recs.append({"id": ln["id"], "drop": "ink"}) + continue + bio = io.BytesIO() + crop.save(bio, format="PNG", compress_level=4) + data = bio.getvalue() + sha = hashlib.sha256(data).hexdigest() + rel = os.path.join(split, docid, f"{ln['id'].split(':')[-1]}.png") + full = os.path.join(outdir, rel) + os.makedirs(os.path.dirname(full), exist_ok=True) + with open(full, "wb") as fo: + fo.write(data) + recs.append({"id": ln["id"], "image": full, "sha256": sha, "dpi": dpi, "pad": pad, + "w": w, "h": h, "ink": round(dark, 4)}) + recs.append({"docstat": [docid, nchk, nbad]}) + except Timeout: + recs.append({"drop": "timeout_job", "docid": docid}) + except Exception as e: + recs.append({"drop": "error:" + type(e).__name__ + ":" + str(e)[:60], "docid": docid}) + finally: + signal.alarm(0) + return recs + + +def waterfill(avail, total, per_doc_max): + """avail: {doc: n}; returns {doc: quota} spreading `total` as evenly as the caps allow.""" + quota = {d: 0 for d in avail} + rem = total + docs = sorted(avail, key=lambda d: avail[d]) + left = len(docs) + for d in docs: + share_ = rem // left if left else 0 + q = min(avail[d], per_doc_max, max(share_, 1) if rem > 0 else 0) + quota[d] = q + rem -= q + left -= 1 + # one more pass to hand out the remainder to docs that still have room + if rem > 0: + for d in sorted(avail, key=lambda d: -avail[d]): + room = min(avail[d], per_doc_max) - quota[d] + add = min(room, rem) + quota[d] += add + rem -= add + if rem <= 0: + break + return quota + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--lang", required=True) + ap.add_argument("--raw", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--corpus", required=True) + ap.add_argument("--workers", type=int, default=8) + ap.add_argument("--maxpages", type=int, default=60) + ap.add_argument("--calibrate", action="store_true") + ap.add_argument("--exclude", default="", help="file with one document id per line to leave out of every split") + ap.add_argument("--tr_tbmm_max_share", type=float, default=0.3) + a = ap.parse_args() + lang = a.lang + t_start = time.time() + global EXCLUDE + if a.exclude and os.path.exists(a.exclude): + EXCLUDE = {x.strip() for x in open(a.exclude, encoding="utf-8") if x.strip()} + if not a.calibrate: + # one worker per language: whichever job starts first takes the lock (mkdir is atomic) + os.makedirs(os.path.join(a.out, "_locks"), exist_ok=True) + try: + os.mkdir(os.path.join(a.out, "_locks", lang)) + except FileExistsError: + print(lang, "already taken by another job or finished; nothing to do", flush=True) + return + lex, nsent = build_lexicon(a.corpus, lang) + print(lang, "lexicon", len(lex), "from sentences", nsent, flush=True) + os.makedirs(os.path.join(a.out, "_stats"), exist_ok=True) + os.makedirs(os.path.join(a.out, "_sidecars"), exist_ok=True) + if a.calibrate: + sh = [] + rng = random.Random(SEED) + sents = [] + with open(os.path.join(a.corpus, "val", lang, "sentences.tsv"), encoding="utf-8") as f: + for i, line in enumerate(f): + parts = line.rstrip("\n").split("\t", 1) + if len(parts) == 2: + sents.append(parts[1]) + if i > 60000: + break + for _ in range(500): + txt = " ".join(rng.sample(sents, 12)) + sh.append(share(tokens(txt, lang), lex)) + print("pseudo-page share (12 held-out sentences): min %.3f p5 %.3f median %.3f" % (min(sh), np.percentile(sh, 5), np.median(sh))) + cross = {} + for ol in PROFILES: + if ol == lang: + continue + osn = [] + with open(os.path.join(a.corpus, "val", ol, "sentences.tsv"), encoding="utf-8") as f: + for i, line in enumerate(f): + parts = line.rstrip("\n").split("\t", 1) + if len(parts) == 2: + osn.append(parts[1]) + if i > 6000: + break + xs = [share(tokens(" ".join(rng.sample(osn, 12)), lang), lex) for _ in range(100)] + cross[ol] = (round(float(np.median(xs)), 3), round(float(np.max(xs)), 3)) + print("other languages vs this lexicon (median, max):", cross) + return + rawlang = os.path.join(a.raw, lang) + docs = sorted(d for d in os.listdir(rawlang) if os.path.exists(os.path.join(rawlang, d, "meta.json"))) + print(lang, "documents on disk", len(docs), flush=True) + import multiprocessing as mp + ctx = mp.get_context("fork") + lexlist = sorted(lex) + jobs = [(os.path.join(rawlang, d), lang, lexlist, a.maxpages) for d in docs] + parsed = {} + with ctx.Pool(a.workers, maxtasksperchild=20) as pool: + for r in pool.imap_unordered(parse_doc, jobs, chunksize=1): + parsed[r["docid"]] = r + print(lang, "parsed", len(parsed), "in", round(time.time() - t_start), "s", flush=True) + + # document gate + T_PAGE, T_DOC = 0.33, 0.38 + good, rej = {}, Counter() + doc_rows = [] + for docid, r in parsed.items(): + meta = json.load(open(os.path.join(rawlang, docid, "meta.json"), encoding="utf-8")) + info = {"docid": docid, "host": meta.get("host"), "url": meta.get("url"), "source": meta.get("source"), + "pages_total": r["pages_total"], "pages_sampled": r["pages_sampled"], "status": r["status"], + "page_reject": r["page_reject"], "median_page_share": r.get("median_page_share")} + if r["status"] != "ok": + rej[r["status"].split(":")[0]] += 1 + info["verdict"] = "reject:" + r["status"][:40] + doc_rows.append(info) + continue + if docid in EXCLUDE: + rej["excluded_after_audit"] += 1 + info["verdict"] = "reject:excluded_after_audit (text layer and visible glyphs disagree)" + doc_rows.append(info) + continue + keep_pages = {} + for pno, p in r["pages"].items(): + ps = p["page_share"] + lines = [] + for ln in p["lines"]: + bs = ln.get("block_share") + ref = bs if bs is not None else ps + if ref is None: + ref = r.get("median_page_share") + if ref is None or ref < T_PAGE: + continue + if ln["ntok"] >= 5 and ln["share"] is not None and ln["share"] < 0.2: + continue + if not any(ch in SPEC[lang] for ch in lower_key(ln["text"], lang)): + # no letter of the language's own: keep only lines with at least 3 words that match its vocabulary well + if ln["ntok"] < 3 or ln["share"] is None or ln["share"] < 0.6: + continue + lines.append(ln) + if lines: + keep_pages[pno] = lines + nl = sum(len(v) for v in keep_pages.values()) + info["eligible_lines"] = nl + msh = r.get("median_page_share") + if msh is None or msh < T_DOC: + rej["language_gate"] += 1 + info["verdict"] = "reject:language_gate" + doc_rows.append(info) + continue + if nl < 30: + rej["few_lines"] += 1 + info["verdict"] = "reject:few_lines" + doc_rows.append(info) + continue + info["verdict"] = "accepted" + doc_rows.append(info) + good[docid] = {"meta": meta, "pages": keep_pages} + tbmm_dropped = 0 + if lang == "tr": + tb = sorted(d for d in good if good[d]["meta"].get("source") == "tbmm_minutes") + others = len(good) - len(tb) + tb_max = int(math.floor(a.tr_tbmm_max_share / (1 - a.tr_tbmm_max_share) * others)) + if len(tb) > tb_max: + random.Random(f"{SEED}-tbmmcap").shuffle(tb) + for d in tb[tb_max:]: + del good[d] + tbmm_dropped += 1 + print(lang, "documents accepted", len(good), "rejected", dict(rej), "tbmm_dropped_for_share", tbmm_dropped, flush=True) + + # per-document exact duplicates of text (headers repeated on every page) + for docid, g in good.items(): + seen = set() + for pno in sorted(g["pages"], key=int): + new = [] + for ln in g["pages"][pno]: + if ln["text"] in seen: + continue + seen.add(ln["text"]) + new.append(ln) + g["pages"][pno] = new + + # split by document + ids = sorted(good) + rng = random.Random(f"{SEED}-{lang}") + rng.shuffle(ids) + n = len(ids) + if n >= 20: + nv, nt = max(3, round(0.05 * n)), max(5, round(0.15 * n)) + elif n >= 12: + nv, nt = 2, max(3, round(0.15 * n)) + elif n >= 6: + nv, nt = 1, 2 + elif n >= 3: + nv, nt = 0, 1 + else: + nv, nt = 0, 0 + split_of = {d: "train" for d in ids} + # held-out documents are drawn (in the seeded shuffled order) among documents with at least 40 eligible lines, + # so that val and test can reach their line targets; documents with fewer lines stay in train + avail0 = {d: sum(len(v) for v in good[d]["pages"].values()) for d in ids} + cands = [d for d in ids if avail0[d] >= 40] + for i, d in enumerate(cands): + if i < nt: + split_of[d] = "test" + elif i < nt + nv: + split_of[d] = "val" + print(lang, "split docs", Counter(split_of.values()), flush=True) + + # TBMM share cap for tr (train only: keep test/val diverse by simply capping documents) + train_text = set() + for d in ids: + if split_of[d] == "train": + for p in good[d]["pages"].values(): + for ln in p: + train_text.add(ln["text"]) + test_text = set() + leak = Counter() + for sp in ("test", "val"): + for d in ids: + if split_of[d] != sp: + continue + for pno in list(good[d]["pages"]): + new = [] + for ln in good[d]["pages"][pno]: + if ln["text"] in train_text: + leak[sp + "_text_in_train"] += 1 + continue + if sp == "val" and ln["text"] in test_text: + leak["val_text_in_test"] += 1 + continue + new.append(ln) + if sp == "test": + test_text.add(ln["text"]) + good[d]["pages"][pno] = new + + targets = {"train": 7500, "val": 520, "test": 850} + permax = {"train": 900, "val": 300, "test": 300} + perpage = {"train": 60, "val": 14, "test": 14} + sel = {} # docid -> {pno: [lines]} + quota_info = {} + for sp in ("train", "val", "test"): + dl = [d for d in ids if split_of[d] == sp] + if not dl: + continue + avail = {d: sum(len(v) for v in good[d]["pages"].values()) for d in dl} + quota = waterfill(avail, targets[sp], permax[sp]) + quota_info[sp] = {"docs": len(dl), "available": sum(avail.values()), "quota": sum(quota.values())} + for d in dl: + r2 = random.Random(f"{SEED}-{lang}-{d}-sel") + pnos = sorted(good[d]["pages"], key=int) + r2.shuffle(pnos) + left = quota[d] + chosen = {} + rounds = 0 + while left > 0 and rounds < 10: + progressed = False + for pno in pnos: + if left <= 0: + break + have = chosen.setdefault(pno, []) + pool = [ln for ln in good[d]["pages"][pno] if ln not in have] + k = min(left, perpage[sp] * (rounds + 1) - len(have), len(pool)) + if k <= 0: + continue + have.extend(r2.sample(pool, k)) + left -= k + progressed = True + rounds += 1 + if not progressed: + break + sel[d] = {p: v for p, v in chosen.items() if v} + # ids: sort lines of every page by their position (stable order) and number them + outdir = a.out + rjobs = [] + meta_of = {} + for d, pages in sel.items(): + sp = split_of[d] + pg = {} + for pno, lines in pages.items(): + lines = sorted(lines, key=lambda x: (x["block"], x["bbox"][1], x["bbox"][0])) + lst = [] + for k, ln in enumerate(lines): + lid = f"printreal:{lang}:{d}:p{int(pno):04d}l{k:03d}" + lst.append({"id": lid, "bbox": ln["bbox"], "text": ln["text"], "size": ln["size"], + "cut_top": ln.get("cut_top"), "cut_bot": ln.get("cut_bot")}) + meta_of[lid] = {"docid": d, "split": sp, "page": int(pno), "text": ln["text"], "bbox": ln["bbox"], + "size_pt": round(ln["size"], 2)} + pg[pno] = lst + rjobs.append((os.path.join(rawlang, d), lang, d, sp, os.path.join(outdir, lang), pg)) + print(lang, "render jobs", len(rjobs), "lines", len(meta_of), flush=True) + drops = Counter() + tail_stat = collections.defaultdict(lambda: [0, 0]) + rows = [] + with ctx.Pool(a.workers, maxtasksperchild=10) as pool: + for recs in pool.imap_unordered(render_job, rjobs, chunksize=1): + for rc in recs: + if "docstat" in rc: + d_, a_, b_ = rc["docstat"] + tail_stat[d_][0] += a_ + tail_stat[d_][1] += b_ + continue + if "drop" in rc: + drops[rc["drop"]] += 1 + continue + m = meta_of[rc["id"]] + dmeta = good[m["docid"]]["meta"] + rows.append({"id": rc["id"], "image": rc["image"], "text": m["text"], "lang": lang, + "script": PROFILES[lang]["script"], "kind": "typed_real", + "source": ("tbmm_minutes" if dmeta.get("source") == "tbmm_minutes" else "finepdfs:" + dmeta.get("host", "")), + "split": m["split"], "group": m["docid"], "unit": "line", + "page": m["page"], "dpi": rc["dpi"], "pad": rc["pad"], "w": rc["w"], "h": rc["h"], + "ink": rc["ink"], "bbox_pt": [round(x, 2) for x in m["bbox"]], "size_pt": m["size_pt"], + "sha256": rc["sha256"], "url": dmeta.get("url"), "doc_sha256": dmeta.get("sha256")}) + suspect = sorted(d for d, (a_, b_) in tail_stat.items() if a_ >= 10 and b_ / a_ >= 0.05) + if suspect: + rows = [r for r in rows if r["group"] not in set(suspect)] + # crop-level dedupe by sha256 (identical crops, e.g. repeated headings) + seen, final = set(), [] + dupc = 0 + for r in sorted(rows, key=lambda r: r["id"]): + if r["sha256"] in seen: + dupc += 1 + try: + os.remove(r["image"]) + except OSError: + pass + continue + seen.add(r["sha256"]) + final.append(r) + sidecar = os.path.join(a.out, "_sidecars", f"{lang}.jsonl") + with open(sidecar, "w", encoding="utf-8") as fo: + for r in final: + fo.write(json.dumps(r, ensure_ascii=False) + "\n") + cnt = {} + for sp in ("train", "val", "test"): + rs = [r for r in final if r["split"] == sp] + cnt[sp] = {"lines": len(rs), "documents": len({r["group"] for r in rs}), + "pages": len({(r["group"], r["page"]) for r in rs})} + stats = {"lang": lang, "documents_on_disk": len(docs), "documents_accepted": len(good), "doc_rejects": dict(rej), "tbmm_dropped_for_share": tbmm_dropped, + "split_docs": dict(Counter(split_of.values())), "leakage_removed": dict(leak), "quota": quota_info, + "render_drops": dict(drops), "suspect_docs_tail_check": suspect, + "tail_check": {d: v for d, v in tail_stat.items() if v[1] > 0}, "crop_dup_dropped": dupc, "counts": cnt, + "hosts_accepted": len({good[d]["meta"].get("host") for d in good}), "seconds": round(time.time() - t_start), + "thresholds": {"T_PAGE_block_or_page_share": T_PAGE, "T_DOC_median_page_share": T_DOC, + "lexicon_words": len(lex), "lexicon_sentences": nsent}} + with open(os.path.join(a.out, "_stats", f"{lang}.json"), "w") as fo: + json.dump(stats, fo, indent=1, ensure_ascii=False) + with open(os.path.join(a.out, "_stats", f"{lang}_docs.jsonl"), "w", encoding="utf-8") as fo: + for r in doc_rows: + r["split"] = split_of.get(r["docid"]) + fo.write(json.dumps(r, ensure_ascii=False) + "\n") + print(lang, "DONE", json.dumps(cnt), "drops", dict(drops), flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/r5_print/r5_print_process.sbatch b/scripts/r5_print/r5_print_process.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..9c4fc6e527b4cfd035c858cfc7b739a9e052e8c3 --- /dev/null +++ b/scripts/r5_print/r5_print_process.sbatch @@ -0,0 +1,17 @@ +#!/bin/bash +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=8 +#SBATCH --mem=16G +#SBATCH --time=01:00:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# usage: sbatch --job-name=r5_print_ r5_print_process.sbatch +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN +hostname; date -u +$CODE/.venv_print/bin/python -I $CODE/scripts/r5_print/r5_print_process.py --lang "$1" \ + --raw $DATA/data/raw/r5_print --out $DATA/data/processed/r5/print_real \ + --corpus $DATA/data/processed/r5/pagesynth_text_split --workers 8 +date -u diff --git a/scripts/r5_print/r5_print_rerun.sh b/scripts/r5_print/r5_print_rerun.sh new file mode 100644 index 0000000000000000000000000000000000000000..0c5088f9292acc24314aab0c92d06374a5631f3f --- /dev/null +++ b/scripts/r5_print/r5_print_rerun.sh @@ -0,0 +1,8 @@ +#!/bin/bash +# remove the previous output of a language (crops, sidecar, stats, lock) and run it again on the login node +CODE=/path/to/TURKIC_OCR_CODE +OUT=/path/to/TURKIC_OCR_DATA/data/processed/r5/print_real +for L in "$@"; do + rm -rf $OUT/$L $OUT/_locks/$L $OUT/_sidecars/$L.jsonl $OUT/_stats/$L.json $OUT/_stats/${L}_docs.jsonl + bash $CODE/scripts/r5_print/r5_print_login_run.sh $L +done diff --git a/scripts/r5_print/r5_print_rerun_loop.sh b/scripts/r5_print/r5_print_rerun_loop.sh new file mode 100644 index 0000000000000000000000000000000000000000..99263feb036576d00b534457ea8de1858836cc18 --- /dev/null +++ b/scripts/r5_print/r5_print_rerun_loop.sh @@ -0,0 +1,11 @@ +#!/bin/bash +# run a language, add the documents flagged by the tail-letter check to the exclusion file, rerun (at most 3 times in total) +CODE=/path/to/TURKIC_OCR_CODE +for L in "$@"; do + for i in 1 2 3; do + bash $CODE/scripts/r5_print/r5_print_rerun.sh $L | grep -E "DONE|accepted" + n=$($CODE/.venv_print/bin/python -I $CODE/scripts/r5_print/r5_print_suspects.py $L) + echo "$L round $i new suspect documents: $n" + if [ "$n" = "0" ]; then break; fi + done +done diff --git a/scripts/r5_print/r5_print_schema.py b/scripts/r5_print/r5_print_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..d0a2376fdaa37701439923915c31755dba8e401a --- /dev/null +++ b/scripts/r5_print/r5_print_schema.py @@ -0,0 +1,13 @@ +import sys +import pyarrow.parquet as pq +from huggingface_hub import HfFileSystem +fs = HfFileSystem() +p = sys.argv[1] +with fs.open(p, "rb") as f: + pf = pq.ParquetFile(f) + print(pf.schema_arrow) + print("row groups", pf.num_row_groups, "rows", pf.metadata.num_rows) + tb = pf.read_row_group(0, columns=[n for n in pf.schema_arrow.names if n != "text"]) + d = tb.slice(0, 2).to_pydict() + for k, v in d.items(): + print(k, str(v)[:200]) diff --git a/scripts/r5_print/r5_print_select.py b/scripts/r5_print/r5_print_select.py new file mode 100644 index 0000000000000000000000000000000000000000..aa61d15ee6b7012533af7b9fdf6fbd5327b4b30a --- /dev/null +++ b/scripts/r5_print/r5_print_select.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python3 +"""R5 PRINT stage A1: pick candidate PDF URLs from HuggingFaceFW/finepdfs. + +Reads ONLY metadata columns (never the text column) through range requests, keeps documents whose +`extractor` field is "docling" (finepdfs: text taken from the PDF's own text layer; the field is a +classifier guess from PDF metadata, so the text-layer check on the fetched PDF still decides later), +caps the number of documents per host, and writes candidates_.jsonl. + +No credentials are used (anonymous access). Run: python -I r5_print_select.py OUTDIR config1 config2 ... +""" +import json +import os +import random +import sys +import time +from urllib.parse import urlparse + +import pyarrow.parquet as pq +from huggingface_hub import HfFileSystem + +SEED = 20261121 +REPO = "datasets/HuggingFaceFW/finepdfs/data" +COLS = ["id", "url", "extractor", "is_truncated", "language", "full_doc_lid", + "per_page_languages", "page_ends", "token_count", "dump"] +# hosts whose terms forbid reuse or that are known to be out of bounds +BLOCK_HOSTS = ("adebiportal.kz",) +# config -> (lang code of this project, shard list, max candidates, host cap) +CONF = { + "kaz_Cyrl": ("kk", ["000_00000.parquet"], 320, 5), + "kir_Cyrl": ("ky", ["000_00000.parquet"], 320, 6), + "uzn_Cyrl": ("uz_cyrl", ["000_00000.parquet"], 320, 6), + "uzn_Latn": ("uz_latn", ["000_00000.parquet"], 320, 6), + "tur_Latn": ("tr", ["000_00000.parquet"], 360, 3), + "azj_Latn": ("az", ["000_00000.parquet"], 320, 6), + "tat_Cyrl": ("tt", ["000_00000.parquet"], 400, 10), + "bak_Cyrl": ("ba", ["000_00000.parquet"], 400, 10), + "tuk_Latn": ("tk", ["000_00000.parquet"], 400, 10), + "sah_Cyrl": ("sah", ["000_00000.parquet"], 400, 10), +} + + +def host_of(url): + try: + h = urlparse(url).netloc.lower() + except Exception: + return "" + if h.startswith("www."): + h = h[4:] + return h + + +def main(): + outdir = sys.argv[1] + configs = sys.argv[2:] or list(CONF) + os.makedirs(outdir, exist_ok=True) + fs = HfFileSystem() + rng = random.Random(SEED) + summary = {} + for cfg in configs: + lang, shards, maxc, hostcap = CONF[cfg] + t0 = time.time() + rows = [] + n_all = 0 + n_dock = 0 + for sh in shards: + path = f"{REPO}/{cfg}/train/{sh}" + with fs.open(path, "rb") as f: + pf = pq.ParquetFile(f, pre_buffer=True) + nrg = pf.num_row_groups + for rg in range(nrg): + tb = pf.read_row_group(rg, columns=COLS) + d = tb.to_pydict() + for i in range(tb.num_rows): + n_all += 1 + if d["extractor"][i] != "docling": + continue + n_dock += 1 + pe = d["page_ends"][i] or [] + npg = len(pe) + if npg < 1 or npg > 1500: + continue + ppl = d["per_page_languages"][i] or [] + n_lang_pages = sum(1 for x in ppl if x == cfg) + if d["full_doc_lid"][i] != cfg and d["language"][i] != cfg: + continue + if n_lang_pages < 1: + continue + url = d["url"][i] + h = host_of(url) + if not h or any(h.endswith(b) for b in BLOCK_HOSTS): + continue + if not url.lower().startswith(("http://", "https://")): + continue + rows.append({"id": d["id"][i], "url": url, "host": h, "dump": d["dump"][i], + "pages": npg, "lang_pages": n_lang_pages, + "tokens": d["token_count"][i], "cfg": cfg, "lang": lang}) + # dedupe by url, cap per host, shuffle + seen = set() + uniq = [] + for r in rows: + if r["url"] in seen: + continue + seen.add(r["url"]) + uniq.append(r) + rng.shuffle(uniq) + per_host = {} + picked = [] + for r in uniq: + c = per_host.get(r["host"], 0) + if c >= hostcap: + continue + per_host[r["host"]] = c + 1 + picked.append(r) + if len(picked) >= maxc: + break + with open(os.path.join(outdir, f"candidates_{cfg}.jsonl"), "w", encoding="utf-8") as fo: + for r in picked: + fo.write(json.dumps(r, ensure_ascii=False) + "\n") + hosts_total = len({r["host"] for r in uniq}) + summary[cfg] = {"lang": lang, "rows_read": n_all, "docling_rows": n_dock, + "after_filters_unique_urls": len(uniq), "hosts_after_filters": hosts_total, + "picked": len(picked), "picked_hosts": len(per_host and {r['host'] for r in picked}), + "host_cap": hostcap, "seconds": round(time.time() - t0, 1)} + print(cfg, json.dumps(summary[cfg]), flush=True) + with open(os.path.join(outdir, "select_summary_" + "_".join(configs)[:80] + ".json"), "w") as fs_: + json.dump(summary, fs_, indent=1) + + +if __name__ == "__main__": + main() diff --git a/scripts/r5_print/r5_print_select2.py b/scripts/r5_print/r5_print_select2.py new file mode 100644 index 0000000000000000000000000000000000000000..395304127db52d789d50e4deca2bd7519f3bed81 --- /dev/null +++ b/scripts/r5_print/r5_print_select2.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python3 +"""R5 PRINT stage A1b (second pass for thin languages): like r5_print_select.py, but keeps only documents where at least +60% of the pages carry the language label (per_page_languages) and ranks by that share, host cap 4. + +R5 PRINT stage A1: pick candidate PDF URLs from HuggingFaceFW/finepdfs. + +Reads ONLY metadata columns (never the text column) through range requests, keeps documents whose +`extractor` field is "docling" (finepdfs: text taken from the PDF's own text layer; the field is a +classifier guess from PDF metadata, so the text-layer check on the fetched PDF still decides later), +caps the number of documents per host, and writes candidates_.jsonl. + +No credentials are used (anonymous access). Run: python -I r5_print_select.py OUTDIR config1 config2 ... +""" +import json +import os +import random +import sys +import time +from urllib.parse import urlparse + +import pyarrow.parquet as pq +from huggingface_hub import HfFileSystem + +SEED = 20261121 +REPO = "datasets/HuggingFaceFW/finepdfs/data" +COLS = ["id", "url", "extractor", "is_truncated", "language", "full_doc_lid", + "per_page_languages", "page_ends", "token_count", "dump"] +# hosts whose terms forbid reuse or that are known to be out of bounds +BLOCK_HOSTS = ("adebiportal.kz",) +# config -> (lang code of this project, shard list, max candidates, host cap) +CONF = { + "tuk_Latn": ("tk", ["000_00000.parquet"], 600, 4), + "bak_Cyrl": ("ba", ["000_00000.parquet"], 600, 4), + "sah_Cyrl": ("sah", ["000_00000.parquet"], 600, 4), + "tat_Cyrl": ("tt", ["000_00000.parquet"], 600, 4), + "kir_Cyrl": ("ky", ["000_00000.parquet"], 500, 4), +} + + +def host_of(url): + try: + h = urlparse(url).netloc.lower() + except Exception: + return "" + if h.startswith("www."): + h = h[4:] + return h + + +def main(): + outdir = sys.argv[1] + configs = sys.argv[2:] or list(CONF) + os.makedirs(outdir, exist_ok=True) + fs = HfFileSystem() + rng = random.Random(SEED) + summary = {} + for cfg in configs: + lang, shards, maxc, hostcap = CONF[cfg] + t0 = time.time() + rows = [] + n_all = 0 + n_dock = 0 + for sh in shards: + path = f"{REPO}/{cfg}/train/{sh}" + with fs.open(path, "rb") as f: + pf = pq.ParquetFile(f, pre_buffer=True) + nrg = pf.num_row_groups + for rg in range(nrg): + tb = pf.read_row_group(rg, columns=COLS) + d = tb.to_pydict() + for i in range(tb.num_rows): + n_all += 1 + if d["extractor"][i] != "docling": + continue + n_dock += 1 + pe = d["page_ends"][i] or [] + npg = len(pe) + if npg < 1 or npg > 1500: + continue + ppl = d["per_page_languages"][i] or [] + n_lang_pages = sum(1 for x in ppl if x == cfg) + if d["full_doc_lid"][i] != cfg and d["language"][i] != cfg: + continue + if n_lang_pages < min(2, npg) or n_lang_pages < 0.6 * npg: + continue + url = d["url"][i] + h = host_of(url) + if not h or any(h.endswith(b) for b in BLOCK_HOSTS): + continue + if not url.lower().startswith(("http://", "https://")): + continue + rows.append({"id": d["id"][i], "url": url, "host": h, "dump": d["dump"][i], + "pages": npg, "lang_pages": n_lang_pages, + "tokens": d["token_count"][i], "cfg": cfg, "lang": lang, + "lang_frac": round(n_lang_pages / npg, 3)}) + # dedupe by url, cap per host, shuffle + seen = set() + uniq = [] + for r in rows: + if r["url"] in seen: + continue + seen.add(r["url"]) + uniq.append(r) + rng.shuffle(uniq) + uniq.sort(key=lambda r: 0 if r["lang_frac"] >= 0.9 else (1 if r["lang_frac"] >= 0.75 else 2)) + per_host = {} + picked = [] + for r in uniq: + c = per_host.get(r["host"], 0) + if c >= hostcap: + continue + per_host[r["host"]] = c + 1 + picked.append(r) + if len(picked) >= maxc: + break + with open(os.path.join(outdir, f"candidates_{cfg}.jsonl"), "w", encoding="utf-8") as fo: + for r in picked: + fo.write(json.dumps(r, ensure_ascii=False) + "\n") + hosts_total = len({r["host"] for r in uniq}) + summary[cfg] = {"lang": lang, "rows_read": n_all, "docling_rows": n_dock, + "after_filters_unique_urls": len(uniq), "hosts_after_filters": hosts_total, + "picked": len(picked), "picked_hosts": len(per_host and {r['host'] for r in picked}), + "host_cap": hostcap, "seconds": round(time.time() - t0, 1)} + print(cfg, json.dumps(summary[cfg]), flush=True) + with open(os.path.join(outdir, "select_summary_" + "_".join(configs)[:80] + ".json"), "w") as fs_: + json.dump(summary, fs_, indent=1) + + +if __name__ == "__main__": + main() diff --git a/scripts/r5_print/r5_print_select3.py b/scripts/r5_print/r5_print_select3.py new file mode 100644 index 0000000000000000000000000000000000000000..ae5a428d80b1ac8374907ea7dec08b38004841f3 --- /dev/null +++ b/scripts/r5_print/r5_print_select3.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python3 +"""R5 PRINT stage A1c (larger lists for tr, uz_latn, az; same rules as r5_print_select.py). + +R5 PRINT stage A1: pick candidate PDF URLs from HuggingFaceFW/finepdfs. + +Reads ONLY metadata columns (never the text column) through range requests, keeps documents whose +`extractor` field is "docling" (finepdfs: text taken from the PDF's own text layer; the field is a +classifier guess from PDF metadata, so the text-layer check on the fetched PDF still decides later), +caps the number of documents per host, and writes candidates_.jsonl. + +No credentials are used (anonymous access). Run: python -I r5_print_select.py OUTDIR config1 config2 ... +""" +import json +import os +import random +import sys +import time +from urllib.parse import urlparse + +import pyarrow.parquet as pq +from huggingface_hub import HfFileSystem + +SEED = 20261121 +REPO = "datasets/HuggingFaceFW/finepdfs/data" +COLS = ["id", "url", "extractor", "is_truncated", "language", "full_doc_lid", + "per_page_languages", "page_ends", "token_count", "dump"] +# hosts whose terms forbid reuse or that are known to be out of bounds +BLOCK_HOSTS = ("adebiportal.kz",) +# config -> (lang code of this project, shard list, max candidates, host cap) +CONF = { + "tur_Latn": ("tr", ["000_00000.parquet"], 1200, 4), + "uzn_Latn": ("uz_latn", ["000_00000.parquet"], 1000, 6), + "azj_Latn": ("az", ["000_00000.parquet"], 900, 6), +} + + +def host_of(url): + try: + h = urlparse(url).netloc.lower() + except Exception: + return "" + if h.startswith("www."): + h = h[4:] + return h + + +def main(): + outdir = sys.argv[1] + configs = sys.argv[2:] or list(CONF) + os.makedirs(outdir, exist_ok=True) + fs = HfFileSystem() + rng = random.Random(SEED) + summary = {} + for cfg in configs: + lang, shards, maxc, hostcap = CONF[cfg] + t0 = time.time() + rows = [] + n_all = 0 + n_dock = 0 + for sh in shards: + path = f"{REPO}/{cfg}/train/{sh}" + with fs.open(path, "rb") as f: + pf = pq.ParquetFile(f, pre_buffer=True) + nrg = pf.num_row_groups + for rg in range(nrg): + tb = pf.read_row_group(rg, columns=COLS) + d = tb.to_pydict() + for i in range(tb.num_rows): + n_all += 1 + if d["extractor"][i] != "docling": + continue + n_dock += 1 + pe = d["page_ends"][i] or [] + npg = len(pe) + if npg < 1 or npg > 1500: + continue + ppl = d["per_page_languages"][i] or [] + n_lang_pages = sum(1 for x in ppl if x == cfg) + if d["full_doc_lid"][i] != cfg and d["language"][i] != cfg: + continue + if n_lang_pages < 1: + continue + url = d["url"][i] + h = host_of(url) + if not h or any(h.endswith(b) for b in BLOCK_HOSTS): + continue + if not url.lower().startswith(("http://", "https://")): + continue + rows.append({"id": d["id"][i], "url": url, "host": h, "dump": d["dump"][i], + "pages": npg, "lang_pages": n_lang_pages, + "tokens": d["token_count"][i], "cfg": cfg, "lang": lang}) + # dedupe by url, cap per host, shuffle + seen = set() + uniq = [] + for r in rows: + if r["url"] in seen: + continue + seen.add(r["url"]) + uniq.append(r) + rng.shuffle(uniq) + per_host = {} + picked = [] + for r in uniq: + c = per_host.get(r["host"], 0) + if c >= hostcap: + continue + per_host[r["host"]] = c + 1 + picked.append(r) + if len(picked) >= maxc: + break + with open(os.path.join(outdir, f"candidates_{cfg}.jsonl"), "w", encoding="utf-8") as fo: + for r in picked: + fo.write(json.dumps(r, ensure_ascii=False) + "\n") + hosts_total = len({r["host"] for r in uniq}) + summary[cfg] = {"lang": lang, "rows_read": n_all, "docling_rows": n_dock, + "after_filters_unique_urls": len(uniq), "hosts_after_filters": hosts_total, + "picked": len(picked), "picked_hosts": len(per_host and {r['host'] for r in picked}), + "host_cap": hostcap, "seconds": round(time.time() - t0, 1)} + print(cfg, json.dumps(summary[cfg]), flush=True) + with open(os.path.join(outdir, "select_summary_" + "_".join(configs)[:80] + ".json"), "w") as fs_: + json.dump(summary, fs_, indent=1) + + +if __name__ == "__main__": + main() diff --git a/scripts/r5_print/r5_print_smoke_all.sh b/scripts/r5_print/r5_print_smoke_all.sh new file mode 100644 index 0000000000000000000000000000000000000000..c39e07c7abd57cf65819b49233a2a7372028071a --- /dev/null +++ b/scripts/r5_print/r5_print_smoke_all.sh @@ -0,0 +1,10 @@ +#!/bin/bash +# smoke test of r5_print_process.py on N documents per language (login node, small). usage: N lang... +CODE=/path/to/TURKIC_OCR_CODE +DATA=/path/to/TURKIC_OCR_DATA +N=$1; shift +for L in "$@"; do + bash $CODE/scripts/r5_print/r5_print_smoke_setup.sh $L $N > /dev/null + nice -n 10 $CODE/.venv_print/bin/python -I $CODE/scripts/r5_print/r5_print_process.py --lang $L \ + --raw $DATA/tmp/print_smoke_$L/raw --out $DATA/tmp/print_smoke_$L/out --corpus $DATA/data/processed/r5/pagesynth_text_split --workers 3 --maxpages 10 2>&1 | grep -E "accepted|DONE|Error|Traceback" +done diff --git a/scripts/r5_print/r5_print_smoke_setup.sh b/scripts/r5_print/r5_print_smoke_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..31284adc0c51afe457f338b36dde60ad684c8673 --- /dev/null +++ b/scripts/r5_print/r5_print_smoke_setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +# smoke-test helper: link N downloaded documents of a language (optional name pattern) into a scratch RAW tree +DATA=/path/to/TURKIC_OCR_DATA +L=$1; N=$2; PAT=${3:-.} +SM=$DATA/tmp/print_smoke_$L +rm -rf $SM; mkdir -p $SM/raw/$L +for d in $(ls $DATA/data/raw/r5_print/$L | grep -E "$PAT" | head -$N); do ln -s $DATA/data/raw/r5_print/$L/$d $SM/raw/$L/$d; done +ls $SM/raw/$L | wc -l diff --git a/scripts/r5_print/r5_print_unexclude_sah.py b/scripts/r5_print/r5_print_unexclude_sah.py new file mode 100644 index 0000000000000000000000000000000000000000..25c608d930ebee56100b8b30ba970921198e1e1c --- /dev/null +++ b/scripts/r5_print/r5_print_unexclude_sah.py @@ -0,0 +1,5 @@ +p="/path/to/TURKIC_OCR_DATA/data/processed/r5/print_real/_excluded_docs.txt" +lines=[x.strip() for x in open(p) if x.strip()] +keep=[x for x in lines if not x.startswith("sah_")] +open(p,"w").write("\n".join(keep)+"\n") +print(len(lines), "->", len(keep)) diff --git a/scripts/r5_print/r5_print_validate.py b/scripts/r5_print/r5_print_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..a617367bb449a82e85015e98d32fb050dc767700 --- /dev/null +++ b/scripts/r5_print/r5_print_validate.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +"""Validate the PRINT manifests with the same rules as stage DATA's r5_validate_manifests.py (header, allowed +values, NFC, no tab or line break, absolute existing image path, ids unique), plus: ids unique against every +other manifest of the folder, and the 'paragraph' unit reported separately (DATA's list is word, line, page). +Writes the result to the path given as argument 1 (not to DATA's own validation file).""" +import collections +import json +import os +import sys +import unicodedata +from pathlib import Path + +MAN = Path("/path/to/TURKIC_OCR_DATA/data/processed/r5/manifests") +HDR = ["id", "image", "text", "lang", "script", "kind", "source", "split", "group", "unit"] +LANG = {"kk", "ky", "uz_cyrl", "uz_latn", "tr", "az", "tt", "ba", "tk", "sah", "ru", "other"} +SCRIPT = {"Cyrl", "Latn"} +KIND = {"hand_real", "hand_synth", "typed_real", "typed_synth", "clutter"} +SPLIT = {"train", "val", "test"} +UNIT = {"word", "line", "page"} +MINE = ["print_real_train", "print_real_val", "print_real_test", "more_real_print"] +res = {} +my_ids = {} +for name in MINE: + bad = collections.Counter() + n = 0 + with open(MAN / (name + ".tsv"), encoding="utf-8", newline="") as f: + if f.readline().rstrip("\n").split("\t") != HDR: + bad["bad_header"] += 1 + for line in f: + parts = line.rstrip("\n").split("\t") + n += 1 + if len(parts) != 10: + bad["wrong_column_count"] += 1 + continue + id_, img, text, lang, script, kind, source, split, group, unit = parts + if unicodedata.normalize("NFC", text) != text: + bad["text_not_nfc"] += 1 + if text == "": + bad["empty_text"] += 1 + if lang not in LANG: + bad["bad_lang"] += 1 + if script not in SCRIPT: + bad["bad_script"] += 1 + if kind not in KIND: + bad["bad_kind"] += 1 + if split not in SPLIT: + bad["bad_split"] += 1 + if unit not in UNIT: + bad["bad_unit_in_DATA_list:" + unit] += 1 + if not img.startswith("/"): + bad["image_not_absolute"] += 1 + elif not os.path.exists(img): + bad["image_missing"] += 1 + for sfx, sp in (("_train", "train"), ("_val", "val"), ("_test", "test")): + if name.endswith(sfx) and split != sp: + bad["split_value_vs_file_name"] += 1 + if id_ in my_ids: + bad["duplicate_id"] += 1 + my_ids[id_] = name + res[name] = {"rows": n, "problems": dict(bad)} +# ids against the other manifests +others = collections.Counter() +for p in sorted(MAN.glob("*.tsv")): + if p.stem in MINE: + continue + with open(p, encoding="utf-8", newline="") as f: + next(f) + for line in f: + i = line.split("\t", 1)[0] + if i in my_ids: + others[p.stem] += 1 +res["id_collisions_with_other_manifests"] = dict(others) +json.dump(res, open(sys.argv[1], "w", encoding="utf-8"), indent=1, ensure_ascii=False) +print(json.dumps(res, ensure_ascii=False)) diff --git a/scripts/r5_print/r5_print_verify_manifests.py b/scripts/r5_print/r5_print_verify_manifests.py new file mode 100644 index 0000000000000000000000000000000000000000..0ad6aab60797f829c8ceb090a2562b1a3806de76 --- /dev/null +++ b/scripts/r5_print/r5_print_verify_manifests.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +"""Read-only final check of the shipped manifests: every row's image exists and opens (PIL verify); writes sha256 of each manifest.""" +import concurrent.futures as cf +import hashlib +import json +import os +import sys +import time + +from PIL import Image + +MAN = "/path/to/TURKIC_OCR_DATA/data/processed/r5/manifests" +NAMES = ["print_real_train", "print_real_val", "print_real_test", "more_real_print"] + + +def opens(p): + try: + with Image.open(p) as im: + im.verify() + return True + except Exception: + return False + + +res = {"checked_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "manifests": {}} +for n in NAMES: + path = f"{MAN}/{n}.tsv" + h = hashlib.sha256(open(path, "rb").read()).hexdigest() + imgs = [] + with open(path, encoding="utf-8", newline="") as f: + next(f) + for line in f: + imgs.append(line.rstrip("\n").split("\t")[1]) + with cf.ThreadPoolExecutor(16) as ex: + flags = list(ex.map(opens, imgs, chunksize=256)) + res["manifests"][n] = {"rows": len(imgs), "images_missing": sum(1 for p in imgs if not os.path.exists(p)), + "images_unreadable_or_missing": sum(1 for x in flags if not x), "sha256": h} +json.dump(res, open(sys.argv[1], "w"), indent=1) +print(json.dumps(res)) diff --git a/scripts/r5_realcheck.sbatch b/scripts/r5_realcheck.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..d38252a4fcd1c3e82ce22bde775ba22f2d313eac --- /dev/null +++ b/scripts/r5_realcheck.sbatch @@ -0,0 +1,34 @@ +#!/bin/bash +#SBATCH --job-name=r5_eval_realcheck +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=4 +#SBATCH --mem=48G +#SBATCH --time=01:00:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# R5 EVALCODE: runs the report cards, the leader rule (amendment 3.4 E2) and the B1/B2 selection (provisional, with the paired intervals of clarification H14) on the REAL +# validation score files into SCRATCH folders (DATA/tmp/evalcode_realcheck), to check the real checkpoint names (curve_N, short_retry, short_lm_gated, long, long2x ...) and the +# real arms_info.json and models tables. Validation only; nothing is written to DATA/outputs/r5. +C=/path/to/TURKIC_OCR_CODE +D=/path/to/TURKIC_OCR_DATA +PY=$C/.venv_kraken/bin/python +# R5_STAGE (optional): a staged copy of the code (folders src/ and scripts/) to try before a deploy, for example sbatch --export=ALL,R5_STAGE=$C/_stage_check r5_realcheck.sbatch +S=${R5_STAGE:-$C} +O=$D/tmp/evalcode_realcheck${R5_STAGE:+_stage} +rm -rf $O +mkdir -p $O +TSV=$C/scripts/r5_vlma/models_r5.tsv,$C/scripts/r5_vlmb/models_r5_vlmb.tsv +AI="" +if [ -f $D/outputs/r5/arms_info.json ]; then AI="--arms-info $D/outputs/r5/arms_info.json"; fi +date -u +echo "code under test: $S" +$PY -I $S/scripts/r5eval/report_cards.py --scores $D/outputs/r5/scores --preds $D/outputs/r5/preds --out $O/report_cards \ + --models-tsv $TSV --zero-shot-tsv $C/config_r5eval/zero_shot_results.tsv --labels-rule $C/config_r5eval/r5_descriptive_labels.txt $AI +date -u +$PY -I $S/scripts/r5eval/select_leaders.py --scores $D/outputs/r5/scores --preds $D/outputs/r5/preds --out $O/leaders_selection.json --models-tsv $TSV $AI +date -u +$PY -I $S/scripts/r5eval/select_b1b2.py --scores $D/outputs/r5/scores --preds $D/outputs/r5/preds --out $O/selection.json --models-tsv $TSV --allow-short-b1 $AI +date -u +ls -la $O $O/report_cards | head -40 +sacct -j $SLURM_JOB_ID --format=JobID,Elapsed,MaxRSS,State diff --git a/scripts/r5_ref/code_log_groups.json b/scripts/r5_ref/code_log_groups.json new file mode 100644 index 0000000000000000000000000000000000000000..273e36a1fa7a7e8681035ca7c5a8a4208eff1750 --- /dev/null +++ b/scripts/r5_ref/code_log_groups.json @@ -0,0 +1,60 @@ +{ + "groups": [ + { + "kind": "maker code, pinned", + "revision": "arthurflor23/handwritten-text-recognition@1ca49af840dd8cb6d8498c152dbed3cc8441b6b0", + "root": "/path/to/TURKIC_OCR_CODE/src/ref/htrflor_1ca49af840dd8cb6d8498c152dbed3cc8441b6b0", + "files": ["src/network/model.py", "src/network/layers.py", "src/data/generator.py", "src/data/preproc.py", "src/data/evaluation.py", "src/data/reader.py", "src/main.py"], + "executed": true, + "read_as_text": {"default": "full (every line, 20-21 Nov 2026)", "src/data/reader.py": "full; imported by none of our scripts (not executed)", "src/main.py": "full; not executed (our scripts replace it)"}, + "notes": "model.py, layers.py, generator.py (Tokenizer only), preproc.py, evaluation.py are imported; reader.py and main.py are read but not run" + }, + { + "kind": "maker code, pinned", + "revision": "PaddlePaddle/PaddleOCR@e218c0a35fbcb5085ab3527931b2d8d08f8f0292 (v2.10.0)", + "root": "/path/to/TURKIC_OCR_CODE/src/ref/PaddleOCR-e218c0a35fbcb5085ab3527931b2d8d08f8f0292", + "list_file": "/path/to/TURKIC_OCR_DATA/outputs/r5/ref/executed_pinned_files_smoke.txt", + "executed": true, + "read_as_text": { + "default": "scanned, not read line by line: imported (class and function definitions run at import) but not used by this config; ppocr_executed_scan.tsv lists risk-pattern hits and module-level statements; hits are eval() of config-named classes, pickle.load of our own .states files, a download helper that is not called, and check_install (pip) that only detection code calls", + "tools/program.py": "read: ArgsParser, load_config, merge_config (lines 44-116), train() (184-630), preprocess() (797-922); eval() and the rest scanned", + "tools/__init__.py": "full (empty)", + "tools/naive_sync_bn.py": "scanned (not used: use_sync_bn false)", + "ppocr/data/__init__.py": "full", + "ppocr/data/simple_dataset.py": "read lines 1-253 (SimpleDataSet and MultiScaleDataSet)", + "ppocr/data/imaug/__init__.py": "full", + "ppocr/data/imaug/label_ops.py": "read: BaseRecLabelEncode, CTCLabelEncode (101-197), SARLabelEncode (863-904), MultiLabelEncode (1272-1315); rest scanned", + "ppocr/data/imaug/rec_img_aug.py": "read: RecAug, RecConAug, RecResizeImg, resize_norm_img (lines 34-67, 147-193, 284-309, 616-643); BaseDataAugmentation and the helper functions at the end scanned", + "ppocr/data/imaug/operators.py": "read: DecodeImage (lines 29-59); rest scanned", + "ppocr/losses/combined_loss.py": "full (lines 14-84; not used by MultiLoss config)", + "ppocr/losses/rec_multi_loss.py": "read lines 14-60", + "ppocr/losses/rec_ctc_loss.py": "full", + "ppocr/losses/rec_sar_loss.py": "read lines 14-36", + "ppocr/metrics/rec_metric.py": "read lines 14-80 (RecMetric)", + "ppocr/modeling/architectures/base_model.py": "full", + "ppocr/modeling/backbones/rec_mv1_enhance.py": "full", + "ppocr/modeling/heads/rec_multi_head.py": "full", + "ppocr/modeling/heads/rec_ctc_head.py": "full", + "ppocr/modeling/heads/rec_sar_head.py": "read lines 250-407 (forward paths and SARHead); the encoder and decoder layer definitions (1-250) scanned", + "ppocr/modeling/necks/rnn.py": "read lines 190-284 (EncoderWithSVTR forward, SequenceEncoder); the earlier part scanned", + "ppocr/optimizer/__init__.py": "full", + "ppocr/optimizer/regularizer.py": "full", + "ppocr/optimizer/learning_rate.py": "read: Cosine (lines 73-111); rest scanned", + "ppocr/optimizer/optimizer.py": "read: Adam (lines 56-100); rest scanned", + "ppocr/postprocess/rec_postprocess.py": "read: BaseRecLabelDecode init (30-60) and CTCLabelDecode (195-227); rest scanned", + "ppocr/utils/save_load.py": "full", + "ppocr/utils/utility.py": "read lines 180-216 (check_install, AverageMeter); rest scanned" + }, + "notes": "208 files were imported by the smoke run (list = executed_pinned_files_smoke.txt); the code that actually runs in training is the read set above" + }, + { + "kind": "own script (stage REF)", + "revision": "records/R5/REF/scripts, copied to CODE/scripts/r5_ref/", + "root": "/path/to/TURKIC_OCR_CODE/scripts/r5_ref", + "files": ["ref_common.py", "ref_build_data.py", "ref_flor_train.py", "ref_flor_predict.py", "ref_ppocr_run.py", "ref_ppocr_predict.py", "ref_paper_metrics.py", "ref_register_rand_test.py", "ref_make_mix_lists.py", "ref_label_stats.py", "ref_scan_executed.py", "ref_code_log.py", "make_gpu_tasks.py", "ref_step_build.sh", "ref_step_smoke_r1.sh", "ref_step_smoke_r2.sh", "ref_step_smoke_iii.sh", "test_pass_commands.sh", "ref_setup_env.sh", "ref_setup_env_paddle_cpu.sh", "ref_dev_alloc.sbatch", "mix_smoke.yaml"], + "executed": true, + "read_as_text": {"default": "written in the project (full)"}, + "notes": "ref_make_mix_lists.py contains a verbatim copy of the sampler of CODE/src/linedet/data.py (sha256 1c585b40...43f)" + } + ] +} diff --git a/scripts/r5_ref/make_gpu_tasks.py b/scripts/r5_ref/make_gpu_tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..30a1e38106b654938cd433b8e1ac8fe01a2e4f97 --- /dev/null +++ b/scripts/r5_ref/make_gpu_tasks.py @@ -0,0 +1,110 @@ +"""R5 REF: writes gpu_tasks.json, the task file that LINEDET's driver (job 51128) reads from DATA/outputs/r5/ref/gpu_tasks.json. +Layout: the one documented in records/R5/LINEDET/code/src/linedet/driver.py (name, cmd, venv with {VENV}, requires, after, env, max_runtime_s, reserve_s, cwd). +Extra keys (gpu_mem_gb, host_ram_gb, cpus, stopping_rule, resume, outputs, what) are for the readers; the driver ignores them. +Six reference runs: R1 (HTR-Flor) and R2 (PaddleOCR PP-OCRv3 recogniser) each trained (i) on the KOHTD train forms, (ii) on the replication split, +(iii) on mix_v1 to P_short = 150,016 samples (clarification H5). +Usage: python make_gpu_tasks.py +""" +import json +import sys + +C = "/path/to/TURKIC_OCR_CODE" +D = "/path/to/TURKIC_OCR_DATA" +S = C + "/scripts/r5_ref" +REFDATA = D + "/data/processed/r5/ref" +MAN = D + "/data/processed/r5/manifests" +CK = D + "/checkpoints/r5/ref" +OUT = D + "/outputs/r5/ref" +PRED = D + "/outputs/r5/preds" +TF, PD = C + "/.venv_ref_tf", C + "/.venv_ref_paddle" +TRAIN_BUDGET_S = 16800 # (i), (ii): 4 h 40 min of training per run; predictions follow (R1 <= 55 min, R2 <= 30 min) +TRAIN_KILL_S = 17700 # driver SIGTERM; the scripts stop themselves at the budget +MIX_BUDGET_S = 7200 # (iii): fixed 150,016 samples; 2 h is a ceiling, the run is expected to need well under 1 h +MIX_KILL_S = 8400 + +ENV_TF = {"TF_FORCE_GPU_ALLOW_GROWTH": "true", "TF_CPP_MIN_LOG_LEVEL": "2", "OMP_NUM_THREADS": "2", "MKL_NUM_THREADS": "2"} +ENV_PD = {"FLAGS_allocator_strategy": "auto_growth", "OMP_NUM_THREADS": "2", "MKL_NUM_THREADS": "2", "OPENBLAS_NUM_THREADS": "2"} +VAL_SETS = "V1=%s/kohtd_screen_v1.tsv,kohtd_val=%s/kohtd_val.tsv,kohtd_rand_val=%s/kohtd_rand_val.tsv" % (MAN, MAN, MAN) +VAL_SETS_MIX = "V1=%s/kohtd_screen_v1.tsv,kohtd_val=%s/kohtd_val.tsv" % (MAN, MAN) +CURVE = MAN + "/curve_v1.tsv" +CKNAME = {"i": "ours", "ii": "rand", "iii": "mix"} +QUARTER = 37504 + +tasks = [] +tasks.append({"name": "ref_warm", "venv": TF, "cmd": ["dd", "if=" + REFDATA + "/flor_pool_u8.npy", "of=/dev/null", "bs=16M"], "requires": [REFDATA + "/flor_pool_u8.npy"], "max_runtime_s": 1200, + "what": "reads the 15.9 GB preprocessed image array once so that both R1 runs (i) and (ii) share it in the page cache", "host_ram_gb": 0.1, "gpu_mem_gb": 0, "cpus": 1}) +pred_name_map = {} + + +def train(arm, run): + name = "ref_%s_%s_train" % (arm, run) + out = "%s/%s_%s" % (CK, arm, run) + mix = run == "iii" + budget, kill = (MIX_BUDGET_S, MIX_KILL_S) if mix else (TRAIN_BUDGET_S, TRAIN_KILL_S) + req = [REFDATA + "/build_report.json", REFDATA + "/charset_%s.json" % run] + if mix: + req = [REFDATA + "/mix_iii_stats.json", REFDATA + "/charset_iii.json", REFDATA + ("/mix_iii_R1.tsv" if arm == "R1" else "/ppocr_iii_train.txt")] + what_data = {"i": "the KOHTD train forms of the project split", "ii": "the crop-level random 70% of the train+validation pool", "iii": "mix_v1 (first 150,016 samples of the seeded mix stream the recipe can encode)"}[run] + if arm == "R1": + cmd = ["{VENV}/bin/python", "-I", S + "/ref_flor_train.py", "--run", run, "--out", out, "--budget_s", "{REMAIN}", "--budget_cap_s", str(budget), "--resume", "--workers", "3" if mix else "2", "--gpu_mem_mb", "14000"] + rule = ("fixed budget 150,016 samples (4 x 1,172 batches of 32), RMSprop 0.001, batch 32; weights saved at 25/50/75/100 %." if mix else + "EarlyStopping patience 20 on validation loss; ReduceLROnPlateau x0.2 after 10 epochs; RMSprop 0.001; batch 32 (KOHTD paper 5.2, 5.4). Stops earlier at the %d s budget and is then reported with the samples it saw." % budget) + t = {"name": name, "venv": TF, "cmd": cmd, "env": ENV_TF, "after": ["ref_warm"], "gpu_mem_gb": 14, "host_ram_gb": 8, "cpus": 5 if mix else 5, + "stopping_rule": rule, "what": "HTR-Flor, pinned code arthurflor23/handwritten-text-recognition@1ca49af, trained on " + what_data} + else: + cmd = ["{VENV}/bin/python", "-I", S + "/ref_ppocr_run.py", "--run", run, "--out", out, "--budget_s", "{REMAIN}", "--budget_cap_s", str(budget), "--resume", "--workers", "3"] + rule = ("fixed budget 150,016 samples = 4 epochs of 293 iterations of 128 (chunks of the mix list), cosine schedule, lr 1e-4, warm-up 1 % of the run; the epoch-4 weights are used." if mix else + "100 epochs of cosine schedule (Bimurat 2024 2.4); if 100 epochs do not fit in the %d s budget, the number of epochs is cut so that the schedule completes (measured speed), and the run is flagged 'compressed_schedule'." % budget) + t = {"name": name, "venv": PD, "cmd": cmd, "env": ENV_PD, "after": ["ref_warm"], "gpu_mem_gb": 8, "host_ram_gb": 9, "cpus": 5, "stopping_rule": rule, + "what": "PaddleOCR PP-OCRv3 recogniser (Bimurat 2024 'SVTR-Tiny'), pinned code PaddleOCR@e218c0a, trained on " + what_data} + # {REMAIN} = seconds from the task start to (driver stop - reserve_s); the stop is job start + 22,200 s. reserve_s leaves the time of the prediction tasks that follow. + reserve = 600 if mix else (4800 if arm == "R1" else 3300) + t.update({"requires": req, "max_runtime_s": kill, "reserve_s": reserve, "skip_if_missing_after_done": True, + "resume": "automatic: the command always carries --resume; state is saved at every epoch end and on SIGTERM", "outputs": out}) + tasks.append(t) + return name, out + + +def pred(arm, run, train_name, out, sets, suffix, requires_extra=None, kill=3300, extra_args=None, ck=None, no_beam=False): + name = "ref_%s_%s_pred%s" % (arm, run, suffix) + script = "/ref_flor_predict.py" if arm == "R1" else "/ref_ppocr_predict.py" + cmd = ["{VENV}/bin/python", "-I", S + script, "--run", run, "--sets", sets, "--train_dir", out] + (extra_args or []) + (["--no_beam"] if (no_beam and arm == "R1") else []) + t = {"name": name, "venv": TF if arm == "R1" else PD, "cmd": cmd, "env": ENV_TF if arm == "R1" else ENV_PD, "after": [train_name] + ([] if not suffix else ["ref_%s_%s_pred" % (arm, run)]), + "requires": [out + "/train_summary.json"] + (requires_extra or []), "max_runtime_s": kill, "skip_if_missing_after_done": True, "gpu_mem_gb": 10 if arm == "R1" else 4, "host_ram_gb": 6, "cpus": 4, + "what": "validation-set predictions of the %s checkpoint, shared format, DATA/outputs/r5/preds/%s/%s/" % (arm, arm, ck or CKNAME[run])} + tasks.append(t) + return name + + +def metrics(arm, run, ck): + folders = [ck] + ([ck + "_paperdec"] if arm == "R1" else []) + for fo in folders: + pth = "%s/%s/%s" % (PRED, arm, fo) + tasks.append({"name": "ref_%s_%s_metrics_%s" % (arm, run, fo), "venv": TF, "after": [pred_name_map[(arm, run)]], + "cmd": ["{VENV}/bin/python", "-I", S + "/ref_paper_metrics.py", pth + "/kohtd_rand_val.tsv", "%s/metrics/%s_%s_kohtd_rand_val.json" % (OUT, arm, fo)], + "requires": [pth + "/kohtd_rand_val.tsv"], "max_runtime_s": 900, "skip_if_missing_after_done": True, "gpu_mem_gb": 0, "host_ram_gb": 1, "cpus": 1, + "what": "the published papers' metrics on the validation part of the replication split (arm %s, checkpoint folder %s)" % (arm, fo)}) + + +for arm in ("R1", "R2"): + for run in ("i", "ii", "iii"): + tn, out = train(arm, run) + if run != "iii": + pn = pred(arm, run, tn, out, VAL_SETS, "", kill=3300 if arm == "R1" else 1800) + pred_name_map[(arm, run)] = pn + pred(arm, run, tn, out, "curve_v1=" + CURVE, "_curve", requires_extra=[CURVE], kill=1500) + metrics(arm, run, CKNAME[run]) + else: + pn = pred(arm, run, tn, out, VAL_SETS_MIX, "", kill=2400 if arm == "R1" else 1500) + pred_name_map[(arm, run)] = pn + # curve_v1 at the 100 % point (checkpoint folder "mix") and at 25, 50, 75 % (folders mix_curve_) + pred(arm, run, tn, out, "curve_v1=" + CURVE, "_curve", requires_extra=[CURVE], kill=1500) + for q in (1, 2, 3): + s = q * QUARTER + extra = (["--weights_file", "%s/curve_%d.hdf5" % (out, s), "--ck_name", "mix_curve_%d" % s] if arm == "R1" else ["--weights", "%s/model/iter_epoch_%d" % (out, q), "--ck_name", "mix_curve_%d" % s]) + pred(arm, run, tn, out, "curve_v1=" + CURVE, "_curve_%d" % s, requires_extra=[CURVE], kill=1500, extra_args=extra, ck="mix_curve_%d" % s, no_beam=True) + +spec = {"description": "Reference arms R1 (HTR-Flor) and R2 (PaddleOCR PP-OCRv3 recogniser of Bimurat 2024), each trained three times: (i) KOHTD train forms of the project split, (ii) replication split, (iii) mix_v1 to 150,016 samples. Written by stage REF; included by the driver of job 51128.", + "written_for_job": 51128, "train_budget_s": TRAIN_BUDGET_S, "tasks": tasks} +json.dump(spec, open(sys.argv[1], "w"), indent=1) +print(len(tasks), "tasks") diff --git a/scripts/r5_ref/mix_smoke.yaml b/scripts/r5_ref/mix_smoke.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c9cab235391b260bec2b1d29239103b626a817d0 --- /dev/null +++ b/scripts/r5_ref/mix_smoke.yaml @@ -0,0 +1,14 @@ +# R5 REF smoke test only: a small stand-in for mix_v1.yaml (the real file is frozen later). Train rows only are read. +components: + - name: kohtd_train + manifest: /path/to/TURKIC_OCR_DATA/data/processed/r5/manifests/kohtd_train.tsv + share: 0.5 + - name: hkr_train + manifest: /path/to/TURKIC_OCR_DATA/data/processed/r5/manifests/hkr_train.tsv + share: 0.2 + - name: chd_train + manifest: /path/to/TURKIC_OCR_DATA/data/processed/r5/manifests/chd_train.tsv + share: 0.2 + - name: school_train + manifest: /path/to/TURKIC_OCR_DATA/data/processed/r5/manifests/school_train.tsv + share: 0.1 diff --git a/scripts/r5_ref/ref_after_mix.sbatch b/scripts/r5_ref/ref_after_mix.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..2d92fd64f5a160645a0b5e40f93c810c826df27b --- /dev/null +++ b/scripts/r5_ref/ref_after_mix.sbatch @@ -0,0 +1,21 @@ +#!/bin/bash +#SBATCH --job-name=r5_ref_mixlists +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=4 +#SBATCH --mem=64G +#SBATCH --time=01:00:00 +#SBATCH --begin=2026-11-21T11:45:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# R5 REF, run (iii) of the reference arms (clarification H5): builds the 150,016-sample lists from the FROZEN mix_v1.yaml (text only, no image opened). +# --begin is in the cluster's local time (UTC+5): 11:45 local = 06:45 UTC, after the freeze (about 06:00, hard cap 06:30 UTC). +# If mix_v1.yaml does not exist yet the job stops with exit code 2; rerun it by hand: sbatch /path/to/TURKIC_OCR_CODE/scripts/r5_ref/ref_after_mix.sbatch +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN +C=/path/to/TURKIC_OCR_CODE +D=/path/to/TURKIC_OCR_DATA +MIX=$D/data/processed/r5/mix_v1.yaml +if [ ! -f $MIX ]; then echo "mix_v1.yaml does not exist yet: $MIX"; exit 2; fi +sha256sum $MIX +$C/.venv_kraken/bin/python -I $C/scripts/r5_ref/ref_make_mix_lists.py $MIX $D/data/processed/r5/ref +wc -l $D/data/processed/r5/ref/mix_iii_R1.tsv $D/data/processed/r5/ref/mix_iii_R2.tsv $D/data/processed/r5/ref/ppocr_iii_train.txt diff --git a/scripts/r5_ref/ref_build_data.py b/scripts/r5_ref/ref_build_data.py new file mode 100644 index 0000000000000000000000000000000000000000..237dce338732d695974fec9e4896dfd83fb71b37 --- /dev/null +++ b/scripts/r5_ref/ref_build_data.py @@ -0,0 +1,155 @@ +"""R5 REF: builds everything the four reference runs read. Reads ONLY kohtd_train.tsv and kohtd_val.tsv (never a test manifest, never a test image). + +Outputs + manifests (DATA/data/processed/r5/manifests/): kohtd_rand_train.tsv, kohtd_rand_val.tsv, kohtd_rand_test.tsv + replication split (amendment 3.3 D5 ii, clarification H1): crop-level random 70/15/15 split of the pool "all crops of the KOHTD train and + validation forms of our split" (kohtd_train + kohtd_val), seed 20261121. Algorithm: pool sorted by id, numpy default_rng(seed).permutation(N), + first int(0.70 N) -> train, next int(0.15 N) -> val, rest -> test. + run folder (DATA/data/processed/r5/ref/): + pool_ids.txt one id per line, row order of flor_pool_u8.npy (pool sorted by id) + flor_pool_u8.npy uint8 [N, 1024, 128]: HTR-Flor preprocessing (data/preproc.py preprocess, input_size (1024, 128, 1)) of every pool crop + charset_i.json, charset_ii.json characters of the training labels of runs (i) and (ii) (case kept, sorted by code point) + ppocr_{i,ii}_{train,val}.txt PaddleOCR label lists (absolute image path TAB text) + ppocr_dict_{i,ii}.txt PaddleOCR character dictionaries (one character per line; the space is added by use_space_char) + build_report.json counts and sha256 of every output +Usage: python ref_build_data.py [--workers 16] [--no_images] +Run on a compute node (it runs the pinned HTR-Flor preprocessing code). +""" +import argparse +import csv +import hashlib +import json +import multiprocessing +import os +import sys +import time +import unicodedata + +import numpy as np + +SEED = 20261121 +INPUT_SIZE = (1024, 128, 1) +COLS = ["id", "image", "text", "lang", "script", "kind", "source", "split", "group", "unit"] + + +def sha256(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for b in iter(lambda: f.read(1 << 20), b""): + h.update(b) + return h.hexdigest() + + +def read_manifest(path): + with open(path, encoding="utf-8", newline="") as f: + return list(csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE)) + + +def write_manifest(path, rows, split): + with open(path, "w", encoding="utf-8", newline="") as f: + f.write("\t".join(COLS) + "\n") + for r in rows: + r = dict(r) + r["split"] = split + f.write("\t".join(r[c] for c in COLS) + "\n") + + +_PP = None + + +def _init(src): + global _PP + sys.path.insert(0, src) + from data import preproc as pp # pinned HTR-Flor code + _PP = pp + + +def _prep(path): + try: + return _PP.preprocess(path, input_size=INPUT_SIZE), None + except Exception as e: # unreadable image: zero array, counted in the report + return np.zeros(INPUT_SIZE[:2], dtype=np.uint8), "%s: %s" % (path, e) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("src") + ap.add_argument("manifests") + ap.add_argument("out") + ap.add_argument("--workers", type=int, default=16) + ap.add_argument("--no_images", action="store_true") + ap.add_argument("--limit", type=int, default=0, help="smoke test: use only the first LIMIT pool rows (the rand manifests are still the full ones only if LIMIT is 0)") + a = ap.parse_args() + os.makedirs(a.out, exist_ok=True) + tr = read_manifest(os.path.join(a.manifests, "kohtd_train.tsv")) + va = read_manifest(os.path.join(a.manifests, "kohtd_val.tsv")) + assert all(r["split"] == "train" for r in tr) and all(r["split"] == "val" for r in va) + pool = sorted(tr + va, key=lambda r: r["id"]) + ids = [r["id"] for r in pool] + assert len(set(ids)) == len(ids), "duplicate ids in pool" + n = len(pool) + rep = {"seed": SEED, "pool_rows": n, "train_rows": len(tr), "val_rows": len(va), "forms_in_pool": len({r["group"] for r in pool})} + + # ---- replication split (H1) + perm = np.random.default_rng(SEED).permutation(n) + n_tr, n_va = int(0.70 * n), int(0.15 * n) + parts = {"train": perm[:n_tr], "val": perm[n_tr:n_tr + n_va], "test": perm[n_tr + n_va:]} + mdir = a.manifests if not a.limit else os.path.join(a.out, "smoke_manifests") + os.makedirs(mdir, exist_ok=True) + rand_rows = {} + for k, idx in parts.items(): + rows = [pool[i] for i in sorted(idx.tolist())] + rand_rows[k] = rows + p = os.path.join(mdir, "kohtd_rand_%s.tsv" % k) + write_manifest(p, rows, k) + rep["rand_" + k] = {"rows": len(rows), "forms": len({r["group"] for r in rows}), "path": p, "sha256": sha256(p)} + # forms shared by the three parts (a crop-level split puts every form into all of them) + rep["rand_forms_in_all_three_parts"] = len(set.intersection(*[{r["group"] for r in v} for v in rand_rows.values()])) + + # ---- run folders: character sets, PaddleOCR lists + runs = {"i": (tr, va), "ii": (rand_rows["train"], rand_rows["val"])} + for tag, (trn, val) in runs.items(): + chars = sorted({c for r in trn for c in unicodedata.normalize("NFC", r["text"])}) + assert "¶" not in chars and "¤" not in chars, "reserved HTR-Flor token in labels" + assert all(c not in "\n\r\t" for c in chars) + p = os.path.join(a.out, "charset_%s.json" % tag) + json.dump({"run": tag, "n_chars": len(chars), "chars": "".join(chars), "source": "all characters of the training labels (NFC, case kept), sorted by code point"}, open(p, "w", encoding="utf-8"), ensure_ascii=False, indent=1) + with open(os.path.join(a.out, "ppocr_dict_%s.txt" % tag), "w", encoding="utf-8", newline="") as f: + for c in chars: + if c != " ": + f.write(c + "\n") + for nm, rows in (("train", trn), ("val", val)): + with open(os.path.join(a.out, "ppocr_%s_%s.txt" % (tag, nm)), "w", encoding="utf-8", newline="") as f: + for r in rows: + f.write(r["image"] + "\t" + unicodedata.normalize("NFC", r["text"]) + "\n") + rep["charset_" + tag] = len(chars) + with open(os.path.join(a.out, "pool_ids.txt"), "w", encoding="utf-8") as f: + f.write("\n".join(ids) + "\n") + + # ---- preprocessed pool array (pinned HTR-Flor preprocessing) + fails = [] + if not a.no_images: + m = a.limit or n + arr_path = os.path.join(a.out, "flor_pool_u8.npy") + arr = np.lib.format.open_memmap(arr_path, mode="w+", dtype=np.uint8, shape=(m,) + INPUT_SIZE[:2]) + t0 = time.time() + with multiprocessing.Pool(a.workers, initializer=_init, initargs=(a.src,)) as pool_mp: + for i, (img, err) in enumerate(pool_mp.imap(_prep, [r["image"] for r in pool[:m]], chunksize=64)): + arr[i] = img + if err: + fails.append(err) + if i % 20000 == 0: + print("preprocessed", i, "of", m, "%.0fs" % (time.time() - t0), flush=True) + arr.flush() + del arr + rep["array"] = {"path": arr_path, "shape": [m] + list(INPUT_SIZE[:2]), "seconds": round(time.time() - t0, 1), "unreadable_images": len(fails), "unreadable_examples": fails[:5]} + for fn in sorted(os.listdir(a.out)): + p = os.path.join(a.out, fn) + if os.path.isfile(p) and fn != "build_report.json": + rep.setdefault("sha256", {})[fn] = sha256(p) + json.dump(rep, open(os.path.join(a.out, "build_report.json"), "w"), indent=1) + print(json.dumps({k: v for k, v in rep.items() if k != "sha256"}, indent=1)[:3000]) + + +if __name__ == "__main__": + main() diff --git a/scripts/r5_ref/ref_check_tasks.py b/scripts/r5_ref/ref_check_tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..45ec5fbfccca524426eebd975688ecb707456af2 --- /dev/null +++ b/scripts/r5_ref/ref_check_tasks.py @@ -0,0 +1,33 @@ +"""R5 REF: checks gpu_tasks.json against LINEDET's driver code: every task must survive normalize_task (name, cmd), every `after` must name a task of the file, +every {VENV}/{REMAIN} placeholder is replaced the way the driver does it, and every file path in cmd (scripts, venv python) must exist. +Usage: python ref_check_tasks.py """ +import json +import os +import sys + +sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src") +from linedet import driver # LINEDET's driver module (own project code) + +spec = json.load(open(sys.argv[1])) +names = {t["name"] for t in spec["tasks"]} +bad = 0 +for t in spec["tasks"]: + nt = driver.normalize_task(t) + if nt is None: + print("NOT NORMALISABLE", t.get("name")) + bad += 1 + continue + for a in nt["after"]: + if a not in names: + print("UNKNOWN AFTER", nt["name"], a) + bad += 1 + cmd = [c.replace("{PY}", driver.PY).replace("{REMAIN}", "1234") for c in nt["cmd"]] + for c in cmd: + if c.endswith(".py") or c.endswith("/python") or c.startswith("/shared/") and "/" in c and not c.startswith("--"): + if not os.path.exists(c): + print("MISSING FILE", nt["name"], c) + bad += 1 + if any("{" in c for c in cmd): + print("UNREPLACED PLACEHOLDER", nt["name"], cmd) + bad += 1 +print(len(spec["tasks"]), "tasks checked,", bad, "problems") diff --git a/scripts/r5_ref/ref_code_log.py b/scripts/r5_ref/ref_code_log.py new file mode 100644 index 0000000000000000000000000000000000000000..0d26a2af8fe2710134993de233659004ec51dcc2 --- /dev/null +++ b/scripts/r5_ref/ref_code_log.py @@ -0,0 +1,36 @@ +"""R5 REF: writes code_log.tsv (rule 0.11): one row per method-code file with its sha256, line count and how it was read. +Input: a JSON file {"groups": [{"kind", "revision", "root", "files": [relative paths] or "list_file": path of a text file with absolute paths, +"read_as_text": {"default": "...", "": "..."}, "executed": true/false, "notes": "..."}]} +Output: TSV with columns kind, repo_at_revision, path, sha256, lines, read_as_text, executed, notes. +Usage: python ref_code_log.py +""" +import hashlib +import json +import os +import sys + +spec = json.load(open(sys.argv[1], encoding="utf-8")) +rows = [] +for g in spec["groups"]: + root = g["root"] + if "list_file" in g: + paths = [p.strip() for p in open(g["list_file"], encoding="utf-8") if p.strip()] + rels = [os.path.relpath(p, root) for p in paths] + else: + rels = g["files"] + for rel in rels: + p = os.path.join(root, rel) + if not os.path.exists(p): + rows.append((g["kind"], g["revision"], rel, "MISSING", "", "", str(g.get("executed")), "file not found")) + continue + data = open(p, "rb").read() + mode = g["read_as_text"].get("default", "") + for pre, m in g["read_as_text"].items(): + if pre != "default" and rel.startswith(pre): + mode = m + rows.append((g["kind"], g["revision"], rel, hashlib.sha256(data).hexdigest(), str(data.count(b"\n")), mode, str(g.get("executed")), g.get("notes", ""))) +with open(sys.argv[2], "w", encoding="utf-8") as f: + f.write("kind\trepo_at_revision\tpath\tsha256\tlines\tread_as_text\texecuted\tnotes\n") + for r in rows: + f.write("\t".join(r) + "\n") +print(len(rows), "rows") diff --git a/scripts/r5_ref/ref_common.py b/scripts/r5_ref/ref_common.py new file mode 100644 index 0000000000000000000000000000000000000000..8909825a6a2217707cab98e69f4f01249ec09800 --- /dev/null +++ b/scripts/r5_ref/ref_common.py @@ -0,0 +1,84 @@ +"""R5 REF: small helpers shared by the reference-arm scripts (own code, no maker code).""" +import csv +import hashlib +import json +import os +import time + +CODE = "/path/to/TURKIC_OCR_CODE" +DATA = "/path/to/TURKIC_OCR_DATA" +MANIFESTS = DATA + "/data/processed/r5/manifests" +REFDATA = DATA + "/data/processed/r5/ref" +EVALSETS = DATA + "/data/processed/r5/evalsets.json" +PREDS = DATA + "/outputs/r5/preds" +HTRFLOR_SRC = CODE + "/src/ref/htrflor_1ca49af840dd8cb6d8498c152dbed3cc8441b6b0/src" +HTRFLOR_COMMIT = "arthurflor23/handwritten-text-recognition@1ca49af840dd8cb6d8498c152dbed3cc8441b6b0" +PPOCR_ROOT = CODE + "/src/ref/PaddleOCR-e218c0a35fbcb5085ab3527931b2d8d08f8f0292" +PPOCR_COMMIT = "PaddlePaddle/PaddleOCR@e218c0a35fbcb5085ab3527931b2d8d08f8f0292 (v2.10.0)" +TEST_TOKEN = DATA + "/outputs/r5/ref/test_pass_started.txt" # copy of records/R5/RULE/test_pass_started.txt, written by the scoring pass + + +def utc(): + return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) + + +def read_manifest(path): + with open(path, encoding="utf-8", newline="") as f: + return list(csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE)) + + +def sha256(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for b in iter(lambda: f.read(1 << 20), b""): + h.update(b) + return h.hexdigest() + + +def locked_names(): + try: + d = json.load(open(EVALSETS, encoding="utf-8")) + return {s["name"]: s["manifest"] for s in d["sets"] if s.get("locked")} + except Exception: + return {} + + +def check_locked(name, manifest_path, rows): + """Refuse a locked set or any manifest with split=test unless the scoring pass has started (token file exists).""" + locked = name in locked_names() or os.path.basename(manifest_path) in {os.path.basename(p) for p in locked_names().values()} \ + or any(r.get("split") == "test" for r in rows[:50]) or "test" in os.path.basename(manifest_path) + if locked and not os.path.exists(TEST_TOKEN): + raise SystemExit("REFUSED: %s is a locked test set and %s does not exist (the scoring pass has not started)" % (name, TEST_TOKEN)) + return locked + + +def data_role(run, set_name): + """What a figure on this set means for this run (written into meta.json).""" + if run == "ii": + if set_name in ("V1", "kohtd_val", "curve_v1"): + return {"training_set_figure": True, "note": "replication split: about 70 % of the crops of this set are in the training part of run (ii) (crop-level split of the train+validation forms); not a held-out figure"} + if set_name == "kohtd_rand_val": + return {"training_set_figure": False, "note": "validation part of the replication split: used for early stopping / best-checkpoint selection of run (ii)"} + return {"training_set_figure": False, "note": "replication test part (locked): overlaps the training forms; replication check only"} + if run == "i": + if set_name in ("V1", "kohtd_val"): + return {"training_set_figure": False, "note": "validation set of run (i): used for its early stopping and best-checkpoint selection (kohtd_val contains V1)"} + if set_name == "kohtd_rand_val": + return {"training_set_figure": True, "note": "a mix of crops of the KOHTD train forms (seen in training) and validation forms; not meaningful as a held-out figure"} + if set_name == "curve_v1": + return {"training_set_figure": None, "note": "check the origin of the curve set manifest before reading it as held-out"} + return {"training_set_figure": False, "note": "test set of the project split (locked)"} + return {"training_set_figure": False if set_name != "kohtd_rand_val" else None, + "note": "run (iii) trained on mix_v1 for a fixed number of samples; no validation figure was used for selection; kohtd_val and V1 are not training data of mix_v1"} + + +def write_preds(out_dir, name, rows, hyps, confs=None): + os.makedirs(out_dir, exist_ok=True) + p = os.path.join(out_dir, name + ".tsv") + with open(p, "w", encoding="utf-8", newline="") as f: + f.write("id\tref\thyp" + ("\tconf" if confs is not None else "") + "\n") + for i, r in enumerate(rows): + ref = r["text"].replace("\t", " ").replace("\n", " ") + hyp = hyps[i].replace("\t", " ").replace("\n", " ") + f.write("%s\t%s\t%s" % (r["id"], ref, hyp) + ("\t%.5f" % confs[i] if confs is not None else "") + "\n") + return p diff --git a/scripts/r5_ref/ref_dev_alloc.sbatch b/scripts/r5_ref/ref_dev_alloc.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..a3ec3dffd90b93095541d35dcdff64df1dcb2218 --- /dev/null +++ b/scripts/r5_ref/ref_dev_alloc.sbatch @@ -0,0 +1,14 @@ +#!/bin/bash +#SBATCH --job-name=r5_ref_dev +#SBATCH --partition=ZEN4 +#SBATCH --qos=nu-zen4 +#SBATCH --gres=none +#SBATCH --cpus-per-task=16 +#SBATCH --mem=48G +#SBATCH --time=05:00:00 +#SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out +# R5 REF: one CPU allocation held while the reference-arm code is built and smoke-tested. The ZEN4 queue was about 7 h long on +# 21 Nov 2026, so one wait is paid once; the steps run inside it with `srun --jobid --overlap