diff --git a/.eval_results/parsebench-2.yaml b/.eval_results/parsebench-2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..878435efaa7cda0d50c2ff1112e561217186e5da --- /dev/null +++ b/.eval_results/parsebench-2.yaml @@ -0,0 +1,32 @@ +- dataset: + id: llamaindex/ParseBench-2 + task_id: overall + value: 85.24 + source: + url: https://github.com/run-llama/ParseBench + name: parse-bench + notes: "Pipeline name: ocria_1 (dataset revision 2d9a2344, parse-bench 2.2.1)" +- dataset: + id: llamaindex/ParseBench-2 + task_id: text + value: 87.87 +- dataset: + id: llamaindex/ParseBench-2 + task_id: formatting + value: 91.59 +- dataset: + id: llamaindex/ParseBench-2 + task_id: tables + value: 86.28 +- dataset: + id: llamaindex/ParseBench-2 + task_id: charts + value: 77.63 +- dataset: + id: llamaindex/ParseBench-2 + task_id: layout + value: 85.96 +- dataset: + id: llamaindex/ParseBench-2 + task_id: forms + value: 82.09 diff --git a/.eval_results/parsebench.yaml b/.eval_results/parsebench.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3a6a1c551b4adf235880f32c339dad5b11220703 --- /dev/null +++ b/.eval_results/parsebench.yaml @@ -0,0 +1,28 @@ +- dataset: + id: llamaindex/ParseBench + task_id: mean + value: 84.65 + source: + url: https://github.com/run-llama/ParseBench + name: parse-bench + notes: "Pipeline name: ocria_1 (dataset revision 2805a1d9, parse-bench 2.2.1)" +- dataset: + id: llamaindex/ParseBench + task_id: table + value: 91.8 +- dataset: + id: llamaindex/ParseBench + task_id: chart + value: 82.47 +- dataset: + id: llamaindex/ParseBench + task_id: text_content + value: 90.27 +- dataset: + id: llamaindex/ParseBench + task_id: text_formatting + value: 85.5 +- dataset: + id: llamaindex/ParseBench + task_id: layout + value: 73.23 diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..ac39d6f221fceaa9d1e615e3a3ac2a65411284ef 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,12 @@ saved_model/**/* 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 +assets/boxes_table_texas.jpg filter=lfs diff=lfs merge=lfs -text +assets/chart_line_page.jpg filter=lfs diff=lfs merge=lfs -text +assets/format_hearing_output.png filter=lfs diff=lfs merge=lfs -text +assets/format_hearing_page.jpg filter=lfs diff=lfs merge=lfs -text +assets/handwritten_math_page.jpg filter=lfs diff=lfs merge=lfs -text +assets/ocria1_radar.png filter=lfs diff=lfs merge=lfs -text +assets/table_texas_output.png filter=lfs diff=lfs merge=lfs -text +assets/table_texas_page.jpg filter=lfs diff=lfs merge=lfs -text +tokenizer.json filter=lfs diff=lfs merge=lfs -text diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..4b0a1f25df5e7ce836f78ef15cfdf9f610ea135a --- /dev/null +++ b/LICENSE @@ -0,0 +1,73 @@ + OCRia-1 MODEL AND CODE LICENSE + +Licensor: LlamaIndex, Inc. +Based on the AI Pubs Open RAIL-M License, Version 0.1, March 2, 2023 (http://licenses.ai/), as modified below. + +LICENSING INQUIRIES: Anyone interested in licensing the Model or the Licensed Code, including for uses that Attachment A restricts, may contact LlamaIndex at https://www.llamaindex.ai/contact. This notice does not change the terms below. + +PLEASE READ THESE TERMS CAREFULLY BEFORE USING THE MODEL, THE LICENSED CODE OR A DERIVATIVE WORK OF EITHER MADE AVAILABLE IN CONNECTION WITH THESE TERMS. BY DOWNLOADING, REPRODUCING, DISTRIBUTING OR USING THE MODEL, THE LICENSED CODE OR A DERIVATIVE WORK OF EITHER IN ANY MANNER, YOU (“YOU”) AGREE TO BE BOUND BY THESE TERMS (THE “AGREEMENT”) TO THE EXCLUSION OF ALL OTHER TERMS. YOU REPRESENT AND WARRANT THAT YOU HAVE THE AUTHORITY TO ENTER INTO THIS AGREEMENT; IF YOU ARE ENTERING INTO THIS AGREEMENT ON BEHALF OF AN ORGANIZATION OR ENTITY, REFERENCES TO AND “YOU” IN THIS AGREEMENT, REFER TO THAT ORGANIZATION OR ENTITY. IF YOU DO NOT AGREE TO ALL OF THE FOLLOWING, YOU MAY NOT DOWNLOAD, REPRODUCE, DISTRIBUTE OR USE THE MODEL, THE LICENSED CODE OR A DERIVATIVE WORK OF EITHER IN ANY MANNER. + Section I: PREAMBLE +This OpenRAIL-M License, as modified, is generally applicable to any machine-learning Model. +The “Open” nomenclature indicates that the licensed Model is freely accessible to downstream and other users. The “RAIL” nomenclature indicates that there are use restrictions prohibiting the use of the Model. These restrictions are intended to avoid potential misuse. This License specifies that the use restrictions in the original License must apply to such derivatives. As modified, this License also covers the Licensed Code that Licensor distributes with the Model, on the same terms as the Model (see paragraph 1A). +NOW THEREFORE, You and Licensor agree as follows: +1. Definitions +(a) “Complementary Material” means the applicable source code and scripts used to define, run, load, benchmark or evaluate the Model, and used to prepare data for training or evaluation, if any. This includes any accompanying documentation, tutorials, examples, and any related information, if any. Complementary Material is not licensed under this License, except for the Licensed Code, which is. +(b) "Contribution" means any work, including the original version of the Model and any modifications or additions to that Model or Derivatives of the Model thereof, that is intentionally submitted to Licensor for inclusion in the Model by the rights owner or by an individual or legal entity authorized to submit on behalf of the rights 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 Model, but excluding communication that is conspicuously marked or otherwise designated in writing by the rights owner as "Not a Contribution." +(c) "Contributor" means Licensor and any individual or legal entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Model. +(d) “Data” means a collection of information and/or content extracted from the dataset used with the Model, including to train, pretrain, or otherwise evaluate the Model. The Data is not licensed under this License. +(e) “Derivatives of the Model” means all modifications to the Model, works based on the Model, or any other model which is created or initialized by transfer of patterns of the weights, parameters, activations or output of the Model, to the other model, in order to cause the other model to perform similarly to the Model, including - but not limited to - distillation methods entailing the use of intermediate data representations or methods based on the generation of synthetic data by the Model for training the other model. +(f) “Distribution” means any transmission, reproduction, publication, distribution, or other sharing of the Licensed Materials to a third party, including providing the Model or the Licensed Code as a hosted service made available by electronic or other remote means, including but not limited to API-based or web access. +(g) “Harm” includes but is not limited to physical, mental, psychological, financial and reputational damage, pain, or loss +(h) "License" means the terms and conditions for use, reproduction, and Distribution as defined in this document. +(i) “Licensor” means LlamaIndex, Inc., the rights owner of the Model, together with any entity authorized by it to distribute the Model. +(j) “Model” means any accompanying machine-learning based assemblies (including checkpoints), consisting of learnt weights, parameters (including optimizer states), corresponding to the model architecture as embodied in the Complementary Material, that have been trained or tuned, in whole or in part on the Data, using the Complementary Material. +(k) “Output” means the results of operating a Model or the Licensed Code as embodied in informational content resulting therefrom, including transcriptions and layout boxes. +(l) “Third Parties” means individuals or legal entities that are not under common control with Licensor or You. +(m) "You" (or "Your") means an individual or legal entity exercising permissions granted by this License and/or making use of the Model for whichever purpose and in any field of use, including usage of the Model in an end-use application, including but not limited to a chatbot, translator, or image generator. +(n) “Research Purposes” means (i) non-commercial research, teaching and study, including at academic and non-profit institutions; (ii) evaluating or benchmarking the Model, by any person or organization, including publishing the results; and (iii) internal research and development that does not use the Model, its Derivatives or its Output in a product, service or production workflow offered to or used for third parties or for Your business operations. +(o) “Competing Service” means any product or service, including any API, hosted service or software, that offers document parsing, optical character recognition, or extraction of text, tables, charts or fields from documents, and that competes with any product or service offered by Licensor or its affiliates, including LlamaParse and LlamaCloud. +(p) “Licensed Code” means the source code, and the configuration and data files it reads, that Licensor distributes together with the Model under this License, in source or compiled form, including the files in the `ocria_grounding` directory of the repository in which Licensor publishes the Model (the code that derives layout boxes from the Model’s attention, and its selection of attention heads), and any other file Licensor marks as licensed under this License. +(q) “Derivatives of the Licensed Code” means any modification of the Licensed Code, any work based on or derived from the Licensed Code, including a translation or port of it to another programming language or framework, and any software that incorporates the Licensed Code in whole or in part. +(r) “Licensed Materials” means the Model, Derivatives of the Model, the Licensed Code and Derivatives of the Licensed Code. +1A. Licensed Code. Every grant, condition, use-based restriction and other provision of this License that applies to the Model applies equally to the Licensed Code, and every provision that applies to Derivatives of the Model applies equally to Derivatives of the Licensed Code. In particular, the Licensed Code may be used, reproduced, modified and Distributed only as this License permits for the Model, and the use-based restrictions of Attachment A, including its revenue and funding thresholds and the Competing Service restriction, apply to the Licensed Code and to its Output. The Licensed Code is not open-source software. + Section II: INTELLECTUAL PROPERTY RIGHTS +Both copyright and patent grants may apply to the Model and Derivatives of the Model. The Model and Derivatives of the Model are subject to additional terms as described in Section III, which shall govern the use of the Model and Derivatives of the Model even in the event Section II is held unenforceable. +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, publicly display, publicly perform, sublicense, and distribute the Model and Derivatives of the Model. +3. Grant of Patent License. Subject to the terms and conditions of this License and where and as applicable, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this paragraph) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Model and/or Derivatives of the Model 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 Model or Derivatives of the Model 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 Model or Derivative of the Model and/or a Contribution incorporated within the Model or Derivative of the Model constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for the Model and/or Derivative of the Model shall terminate as of the date such litigation is asserted or filed. +Section III: CONDITIONS OF USAGE, DISTRIBUTION AND REDISTRIBUTION +4. Distribution and Redistribution. You may host the Model or Derivatives of the Model for remote access by Third Parties, including but not limited to software-as-a-service, reproduce, or Distribute copies of the Model or Derivatives of the Model thereof in any medium, with or without modifications, provided that You meet the conditions in this Section III: +(a) Use-based restrictions in paragraph 5 MUST be included as an enforceable provision by You in any type of legal agreement (for example, a license) governing the use and/or distribution of the Model or Derivatives of the Model, and You shall give notice to subsequent users You Distribute to, that the Model and Derivatives of the Model are subject to paragraph 5; +(b) You must give any Third Party recipients of the Model or Derivatives of the Model a copy of this License; +(c) You must cause any modified files to carry prominent notices stating that You changed the files; and +(d) You must retain all copyright, patent, trademark, and attribution notices excluding those notices that do not pertain to any part of the Model or Derivatives of the Model. +You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions, consistent with paragraph 4.a., for use, reproduction, or Distribution of Your modifications, or for any such Derivatives of the Model as a whole, provided Your use, reproduction, and Distribution of the Model otherwise complies with the conditions stated in this License. +5. Use-based restrictions. The restrictions set forth in Attachment A are considered Use-based restrictions. Accordingly, You cannot use the Model or the Derivatives of the Model in violation of such restrictions. You may use the Model subject to this License, including only for lawful purposes and in accordance with the License. Use may include creating any content with, fine-tuning, updating, running, training, evaluating and/or re-parametrizing the Model. You shall require all of Your users who use the Model or a Derivative of the Model to comply with the terms of this paragraph 5. +6. The Output You Generate. Except as set forth herein, Licensor claims no rights in the Output You generate using the Model. You are solely responsible for the Output you generate and its subsequent uses. No use of the Output can contravene any provision as stated in the License. +7. Attribution. In connection with any use or Distribution of any Model or Derivatives of the Model, You agree to give appropriate credit and attribution to Licensor, provide a link to the original Model or Derivatives of the Model, provide a copy of this License, and identify any changes You have made to the Model or Derivatives of the Model (collectively, the “Attribution”). The Attribution must not suggest endorsement by any Licensor. +8. Share-a-Like. As a condition to the license and authorizations herein, You agree to apply this License (to the exclusion of all others) to any and all copies of the Model, Derivatives of the Model, and any changes or improvements to the Model or Derivatives of the Model. This paragraph does not apply to Output, except that Output may not be used to create a Derivative of the Model (for example, by distillation) other than for Research Purposes. +Section IV: OTHER PROVISIONS +9. Updates and Runtime Restrictions. To the maximum extent permitted by law, Licensor reserves the right to restrict (remotely or otherwise) usage of the Model in violation of this License, update the Model through electronic means, or cause modification to the Output resulting from updates to the Model based. +10. Trademarks and related. Nothing in this License permits You to make use of Licensors’ trademarks, trade names, logos or to otherwise suggest endorsement or misrepresent the relationship between the parties; and any rights not expressly granted herein are reserved by the Licensors. +11. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Model (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 Model and Derivatives of the Model, and assume any risks associated with Your exercise of permissions under this License. +12. 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 Model (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. +13. Accepting Warranty or Additional Liability. While Distributing the Model or Derivatives of the Model, You may choose to charge a fee in exchange for support, warranty, indemnity, or other 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 or Licensor, and only if You agree to indemnify, defend, and hold each Contributor and the Licensor harmless for any liability incurred by, or claims asserted against, such Contributor or Licensor by reason of your accepting any such warranty or additional liability. +14. If any provision of this License is held to be invalid, illegal or unenforceable, the remaining provisions shall be unaffected thereby and remain valid as if such provision had not been set forth herein. +END OF TERMS AND CONDITIONS + + Attachment A +USE RESTRICTIONS +As conditions to the Licenses set forth in this Agreement, You agree not to use, reproduce, modify, create or Distribute the Licensed Materials or Output (collectively, “Use”) in any of the following ways: +1. Legal: +(a) In any way that violates any applicable national, federal, state, local or international law or regulation; or +(b) to directly or indirectly infringe or misappropriate any third party intellectual property rights (including those of Licensor or any Contributor) +2. Commercial: +(a) for any purpose if You (your employer, or the entity you are affiliated with) generated more than two million US Dollars ($2,000,000) in gross revenue in the prior year, except where Your Use is limited to personal use or Research Purposes; +(b) for any purpose if You (your employer, or the entity you are affiliated with) has raised more than two million US dollars ($2,000,000) in total equity or debt funding from any source, except where Your Use is limited to personal use or Research Purposes; or +(c) to provide, or as part of, a Competing Service, whatever Your revenue or funding, except for Research Purposes. +Anyone interested in licensing the Model or the Licensed Code, including commercial and broader use licenses for the uses restricted above, may contact LlamaIndex at: https://www.llamaindex.ai/contact + +Attachment B +THIRD-PARTY NOTICE +The Model is a fine-tuned derivative of Qwen3.5-4B (https://huggingface.co/Qwen/Qwen3.5-4B) by the Qwen team, Alibaba Cloud, licensed under the Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0). The Apache License, Version 2.0 continues to govern the Qwen3.5-4B materials as provided by their authors. +The Licensed Code uses, but does not include, third-party libraries (including PyTorch, Hugging Face Transformers, NumPy, SciPy, Pillow and pypdfium2), each governed by its own license. +The Licensed Code downloads and runs, but does not include, the Docling Heron layout detector (https://huggingface.co/docling-project/docling-layout-heron), licensed under the Apache License, Version 2.0, which continues to govern it. diff --git a/assets/boxes_table_texas.jpg b/assets/boxes_table_texas.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d1c222381ee1cd885db9695d3e5b4a7bdb1b4dde --- /dev/null +++ b/assets/boxes_table_texas.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f746cb579c4ac59d4bc4e8c32d64f27811e07f2b565d73198346bb6221cd433f +size 358498 diff --git a/assets/chart_line_output.png b/assets/chart_line_output.png new file mode 100644 index 0000000000000000000000000000000000000000..4e188a6437ca97e182bff479105f08bef35d8e51 Binary files /dev/null and b/assets/chart_line_output.png differ diff --git a/assets/chart_line_page.jpg b/assets/chart_line_page.jpg new file mode 100644 index 0000000000000000000000000000000000000000..1ed924dfcefac17b9d6051e149644c4b875eaf18 --- /dev/null +++ b/assets/chart_line_page.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:93593d987b1689cb685af0b2676fd327f7cd4110bcd8bba3f8a0e376adb2799e +size 111314 diff --git a/assets/format_hearing_output.png b/assets/format_hearing_output.png new file mode 100644 index 0000000000000000000000000000000000000000..6854e73e835327d60e560a6a13491b6d85615753 --- /dev/null +++ b/assets/format_hearing_output.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:84850f9794c890755f875e37be3ac652f5540e2877abec62e406b97d1cda41bf +size 287533 diff --git a/assets/format_hearing_page.jpg b/assets/format_hearing_page.jpg new file mode 100644 index 0000000000000000000000000000000000000000..bdf2c0423b0adb2200dccf1e85de82ca6b764c14 --- /dev/null +++ b/assets/format_hearing_page.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:adf6668209ba2dc7c31c1bf8398397f037ece24beebfa9a870d042201c268c41 +size 491958 diff --git a/assets/handwritten_math_output.png b/assets/handwritten_math_output.png new file mode 100644 index 0000000000000000000000000000000000000000..fefcd512a22881a9577e975f8a8841e74618a659 Binary files /dev/null and b/assets/handwritten_math_output.png differ diff --git a/assets/handwritten_math_page.jpg b/assets/handwritten_math_page.jpg new file mode 100644 index 0000000000000000000000000000000000000000..001f6c7b813c5558a40b6bc7d8010d20f0016dd6 --- /dev/null +++ b/assets/handwritten_math_page.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e65d04d4712f4d66a32de7137038ba60df0a2ded68fcfdae9cca3b0d0538eebd +size 208118 diff --git a/assets/llamaindex-logo.png b/assets/llamaindex-logo.png new file mode 100644 index 0000000000000000000000000000000000000000..7fdc63c29a113fc171fd1172cf4bb0fa0928fe4c Binary files /dev/null and b/assets/llamaindex-logo.png differ diff --git a/assets/ocria1_radar.png b/assets/ocria1_radar.png new file mode 100644 index 0000000000000000000000000000000000000000..c3a13107e06b5508cdc350862eb5b6ce3dadb800 --- /dev/null +++ b/assets/ocria1_radar.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:96f9bc2a7a3cfb20bb11ad3274ba9345386bad19fc9e40f5b86f68ced783e69f +size 120959 diff --git a/assets/table_texas_output.png b/assets/table_texas_output.png new file mode 100644 index 0000000000000000000000000000000000000000..632dbc4ce94cedf95446b91b41b350eaf14356f9 --- /dev/null +++ b/assets/table_texas_output.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fb4c254f097bba4d87e01cf050eada915ed732e6cc385e0024fa6da572774d4d +size 239619 diff --git a/assets/table_texas_page.jpg b/assets/table_texas_page.jpg new file mode 100644 index 0000000000000000000000000000000000000000..7c3d077700b6201b5357a66ded44b963f3efada5 --- /dev/null +++ b/assets/table_texas_page.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:77015e54fde0b30d7e75ae9b65629c774c5a4656bf532cb0e72d5aed98fa7b45 +size 323334 diff --git a/chat_template.jinja b/chat_template.jinja new file mode 100644 index 0000000000000000000000000000000000000000..a585dec894e63da457d9440ec6aa7caa16d20860 --- /dev/null +++ b/chat_template.jinja @@ -0,0 +1,154 @@ +{%- set image_count = namespace(value=0) %} +{%- set video_count = namespace(value=0) %} +{%- macro render_content(content, do_vision_count, is_system_content=false) %} + {%- if content is string %} + {{- content }} + {%- elif content is iterable and content is not mapping %} + {%- for item in content %} + {%- if 'image' in item or 'image_url' in item or item.type == 'image' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain images.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set image_count.value = image_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Picture ' ~ image_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|image_pad|><|vision_end|>' }} + {%- elif 'video' in item or item.type == 'video' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain videos.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set video_count.value = video_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Video ' ~ video_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|video_pad|><|vision_end|>' }} + {%- elif 'text' in item %} + {{- item.text }} + {%- else %} + {{- raise_exception('Unexpected item type in content.') }} + {%- endif %} + {%- endfor %} + {%- elif content is none or content is undefined %} + {{- '' }} + {%- else %} + {{- raise_exception('Unexpected content type.') }} + {%- endif %} +{%- endmacro %} +{%- if not messages %} + {{- raise_exception('No messages provided.') }} +{%- endif %} +{%- if tools and tools is iterable and tools is not mapping %} + {{- '<|im_start|>system\n' }} + {{- "# Tools\n\nYou have access to the following functions:\n\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n" }} + {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n' }} + {%- if messages[0].role == 'system' %} + {%- set content = render_content(messages[0].content, false, true)|trim %} + {%- if content %} + {{- '\n\n' + content }} + {%- endif %} + {%- endif %} + {{- '<|im_end|>\n' }} +{%- else %} + {%- if messages[0].role == 'system' %} + {%- set content = render_content(messages[0].content, false, true)|trim %} + {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %} +{%- for message in messages[::-1] %} + {%- set index = (messages|length - 1) - loop.index0 %} + {%- if ns.multi_step_tool and message.role == "user" %} + {%- set content = render_content(message.content, false)|trim %} + {%- if not(content.startswith('') and content.endswith('')) %} + {%- set ns.multi_step_tool = false %} + {%- set ns.last_query_index = index %} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if ns.multi_step_tool %} + {{- raise_exception('No user query found in messages.') }} +{%- endif %} +{%- for message in messages %} + {%- set content = render_content(message.content, true)|trim %} + {%- if message.role == "system" %} + {%- if not loop.first %} + {{- raise_exception('System message must be at the beginning.') }} + {%- endif %} + {%- elif message.role == "user" %} + {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} + {%- elif message.role == "assistant" %} + {%- set reasoning_content = '' %} + {%- if message.reasoning_content is string %} + {%- set reasoning_content = message.reasoning_content %} + {%- else %} + {%- if '' in content %} + {%- set reasoning_content = content.split('')[0].rstrip('\n').split('')[-1].lstrip('\n') %} + {%- set content = content.split('')[-1].lstrip('\n') %} + {%- endif %} + {%- endif %} + {%- set reasoning_content = reasoning_content|trim %} + {%- if loop.index0 > ns.last_query_index %} + {{- '<|im_start|>' + message.role + '\n\n' + reasoning_content + '\n\n\n' + content }} + {%- else %} + {{- '<|im_start|>' + message.role + '\n' + content }} + {%- endif %} + {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {%- if loop.first %} + {%- if content|trim %} + {{- '\n\n\n\n' }} + {%- else %} + {{- '\n\n' }} + {%- endif %} + {%- else %} + {{- '\n\n\n' }} + {%- endif %} + {%- if tool_call.arguments is defined %} + {%- for args_name, args_value in tool_call.arguments|items %} + {{- '\n' }} + {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %} + {{- args_value }} + {{- '\n\n' }} + {%- endfor %} + {%- endif %} + {{- '\n' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if loop.previtem and loop.previtem.role != "tool" %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {{- content }} + {{- '\n' }} + {%- if not loop.last and loop.nextitem.role != "tool" %} + {{- '<|im_end|>\n' }} + {%- elif loop.last %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- else %} + {{- raise_exception('Unexpected message role.') }} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} + {%- if enable_thinking is defined and enable_thinking is false %} + {{- '\n\n\n\n' }} + {%- else %} + {{- '\n' }} + {%- endif %} +{%- endif %} \ No newline at end of file diff --git a/config.json b/config.json new file mode 100644 index 0000000000000000000000000000000000000000..4bd9c4cada80e2d431c0891e26268b003125df3d --- /dev/null +++ b/config.json @@ -0,0 +1,632 @@ +{ + "architectures": [ + "Qwen3_5ForConditionalGeneration" + ], + "bos_token_id": null, + "dtype": "float32", + "eos_token_id": 248046, + "image_token_id": 248056, + "model_type": "qwen3_5", + "pad_token_id": 248044, + "text_config": { + "attention_bias": false, + "attention_dropout": 0.0, + "attn_output_gate": true, + "bos_token_id": null, + "dtype": "float32", + "eos_token_id": 248044, + "full_attention_interval": 4, + "head_dim": 256, + "hidden_act": "silu", + "hidden_size": 2560, + "initializer_range": 0.02, + "intermediate_size": 9216, + "layer_types": [ + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention" + ], + "linear_conv_kernel_dim": 4, + "linear_key_head_dim": 128, + "linear_num_key_heads": 16, + "linear_num_value_heads": 32, + "linear_value_head_dim": 128, + "mamba_ssm_dtype": "float32", + "max_position_embeddings": 262144, + "mlp_only_layers": [], + "model_type": "qwen3_5_text", + "mtp_num_hidden_layers": 1, + "mtp_use_dedicated_embeddings": false, + "num_attention_heads": 16, + "num_hidden_layers": 32, + "num_key_value_heads": 4, + "pad_token_id": null, + "partial_rotary_factor": 0.25, + "rms_norm_eps": 1e-06, + "rope_parameters": { + "mrope_interleaved": true, + "mrope_section": [ + 11, + 11, + 10 + ], + "partial_rotary_factor": 0.25, + "rope_theta": 10000000, + "rope_type": "default" + }, + "tie_word_embeddings": true, + "use_cache": true, + "vocab_size": 248320 + }, + "tie_word_embeddings": true, + "transformers_version": "5.3.0", + "video_token_id": 248057, + "vision_config": { + "deepstack_visual_indexes": [], + "depth": 24, + "dtype": "float32", + "hidden_act": "gelu_pytorch_tanh", + "hidden_size": 1024, + "in_channels": 3, + "initializer_range": 0.02, + "intermediate_size": 4096, + "model_type": "qwen3_5", + "num_heads": 16, + "num_position_embeddings": 2304, + "out_hidden_size": 2560, + "patch_size": 16, + "spatial_merge_size": 2, + "temporal_patch_size": 2 + }, + "vision_end_token_id": 248054, + "vision_start_token_id": 248053, + "quantization_config": { + "bits": 4, + "data_type": "int", + "group_size": 32, + "sym": true, + "amp": true, + "batch_size": 2, + "low_gpu_mem_usage": false, + "nsamples": 512, + "scale_dtype": "torch.float16", + "seqlen": 4096, + "iters": 1000, + "lr": 0.001, + "minmax_lr": 0.001, + "enable_minmax_tuning": true, + "enable_norm_bias_tuning": false, + "enable_quanted_input": true, + "gradient_accumulate_steps": 4, + "autoround_version": "0.17.0", + "block_name_to_quantize": "model.language_model.layers", + "quant_method": "auto-round", + "packing_format": "auto_round:auto_gptq", + "extra_config": { + "model.language_model.layers.0.linear_attn.out_proj": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.0.linear_attn.in_proj_qkv": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.0.linear_attn.in_proj_z": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.0.linear_attn.in_proj_b": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.0.linear_attn.in_proj_a": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.1.linear_attn.out_proj": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.1.linear_attn.in_proj_qkv": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.1.linear_attn.in_proj_z": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.1.linear_attn.in_proj_b": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.1.linear_attn.in_proj_a": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.2.linear_attn.out_proj": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.2.linear_attn.in_proj_qkv": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.2.linear_attn.in_proj_z": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.2.linear_attn.in_proj_b": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.2.linear_attn.in_proj_a": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.4.linear_attn.out_proj": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.4.linear_attn.in_proj_qkv": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.4.linear_attn.in_proj_z": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.4.linear_attn.in_proj_b": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.4.linear_attn.in_proj_a": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.5.linear_attn.out_proj": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.5.linear_attn.in_proj_qkv": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.5.linear_attn.in_proj_z": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.5.linear_attn.in_proj_b": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.5.linear_attn.in_proj_a": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.6.linear_attn.out_proj": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.6.linear_attn.in_proj_qkv": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.6.linear_attn.in_proj_z": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.6.linear_attn.in_proj_b": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.6.linear_attn.in_proj_a": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.8.linear_attn.out_proj": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.8.linear_attn.in_proj_qkv": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.8.linear_attn.in_proj_z": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.8.linear_attn.in_proj_b": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.8.linear_attn.in_proj_a": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.9.linear_attn.out_proj": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.9.linear_attn.in_proj_qkv": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.9.linear_attn.in_proj_z": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.9.linear_attn.in_proj_b": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.9.linear_attn.in_proj_a": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.10.linear_attn.out_proj": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.10.linear_attn.in_proj_qkv": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.10.linear_attn.in_proj_z": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.10.linear_attn.in_proj_b": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.10.linear_attn.in_proj_a": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.12.linear_attn.out_proj": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.12.linear_attn.in_proj_qkv": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.12.linear_attn.in_proj_z": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.12.linear_attn.in_proj_b": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.12.linear_attn.in_proj_a": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.13.linear_attn.out_proj": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.13.linear_attn.in_proj_qkv": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.13.linear_attn.in_proj_z": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.13.linear_attn.in_proj_b": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.13.linear_attn.in_proj_a": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.14.linear_attn.out_proj": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.14.linear_attn.in_proj_qkv": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.14.linear_attn.in_proj_z": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.14.linear_attn.in_proj_b": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.14.linear_attn.in_proj_a": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.16.linear_attn.out_proj": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.16.linear_attn.in_proj_qkv": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.16.linear_attn.in_proj_z": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.16.linear_attn.in_proj_b": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.16.linear_attn.in_proj_a": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.17.linear_attn.out_proj": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.17.linear_attn.in_proj_qkv": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.17.linear_attn.in_proj_z": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.17.linear_attn.in_proj_b": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.17.linear_attn.in_proj_a": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.18.linear_attn.out_proj": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.18.linear_attn.in_proj_qkv": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.18.linear_attn.in_proj_z": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.18.linear_attn.in_proj_b": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.18.linear_attn.in_proj_a": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.20.linear_attn.out_proj": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.20.linear_attn.in_proj_qkv": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.20.linear_attn.in_proj_z": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.20.linear_attn.in_proj_b": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.20.linear_attn.in_proj_a": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.21.linear_attn.out_proj": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.21.linear_attn.in_proj_qkv": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.21.linear_attn.in_proj_z": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.21.linear_attn.in_proj_b": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.21.linear_attn.in_proj_a": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.22.linear_attn.out_proj": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.22.linear_attn.in_proj_qkv": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.22.linear_attn.in_proj_z": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.22.linear_attn.in_proj_b": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.22.linear_attn.in_proj_a": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.24.linear_attn.out_proj": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.24.linear_attn.in_proj_qkv": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.24.linear_attn.in_proj_z": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.24.linear_attn.in_proj_b": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.24.linear_attn.in_proj_a": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.25.linear_attn.out_proj": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.25.linear_attn.in_proj_qkv": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.25.linear_attn.in_proj_z": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.25.linear_attn.in_proj_b": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.25.linear_attn.in_proj_a": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.26.linear_attn.out_proj": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.26.linear_attn.in_proj_qkv": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.26.linear_attn.in_proj_z": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.26.linear_attn.in_proj_b": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.26.linear_attn.in_proj_a": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.28.linear_attn.out_proj": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.28.linear_attn.in_proj_qkv": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.28.linear_attn.in_proj_z": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.28.linear_attn.in_proj_b": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.28.linear_attn.in_proj_a": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.29.linear_attn.out_proj": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.29.linear_attn.in_proj_qkv": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.29.linear_attn.in_proj_z": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.29.linear_attn.in_proj_b": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.29.linear_attn.in_proj_a": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.30.linear_attn.out_proj": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.30.linear_attn.in_proj_qkv": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.30.linear_attn.in_proj_z": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.30.linear_attn.in_proj_b": { + "bits": 16, + "data_type": "float" + }, + "model.language_model.layers.30.linear_attn.in_proj_a": { + "bits": 16, + "data_type": "float" + }, + ".*mtp.*": { + "bits": 16, + "data_type": "float" + }, + ".*mtp\\.fc.*": { + "data_type": "bfloat16" + }, + ".*linear_attn.*": { + "bits": 16, + "data_type": "float" + }, + ".*visual.*": { + "bits": 16, + "data_type": "float" + } + } + } +} \ No newline at end of file diff --git a/examples/boxes.py b/examples/boxes.py new file mode 100644 index 0000000000000000000000000000000000000000..a3e063656080ceaaf30d2c0df48c71b4be472bca --- /dev/null +++ b/examples/boxes.py @@ -0,0 +1,76 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Transcribe one page with OCRia-1 and draw its layout boxes (experimental). + + pip install "transformers==5.22.2" accelerate torchvision timm scipy pypdfium2 huggingface_hub + python examples/boxes.py doc.pdf --page 0 # a PDF page: exact word positions from its text layer + python examples/boxes.py page.png # an image: word positions from the model's attention + python examples/boxes.py page.png --attention-only # no layout detector (less accurate) + +Writes .boxes.png and .boxes.json next to the input. Needs a CUDA GPU for OCRia-1; the Heron layout +detector (docling-project/docling-layout-heron, Apache-2.0) is downloaded from its own repository on first use. Run it +from a download of this repository (huggingface-cli download llamaindex/OCRia-1 --local-dir OCRia-1); the weights come +from the Hub (or a local copy: OCRIA_MODEL=/path/to/OCRia-1). +""" +import argparse +import json +import os +import sys +import time +from pathlib import Path + +from PIL import Image, ImageDraw + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # the repository root holds ocria_grounding/ +from ocria_grounding import MODEL, ground_layout, load, load_detector, load_fast_layout, render_pdf_page, transcribe # noqa: E402 + +COLORS = {"Section-header": "#d62728", "Title": "#d62728", "Text": "#1f77b4", "List-item": "#2ca02c", + "Table": "#ff7f0e", "Picture": "#9467bd", "Caption": "#8c564b", "Footnote": "#8c564b", + "Page-header": "#7f7f7f", "Page-footer": "#7f7f7f"} + + +def main() -> None: + ap = argparse.ArgumentParser() + ap.add_argument("path", help="a PDF or a page image") + ap.add_argument("--page", type=int, default=0, help="PDF page index (0-based)") + ap.add_argument("--attention-only", action="store_true", help="skip the layout detector") + ap.add_argument("--layout", choices=["accurate-layout", "fast-layout"], default="accurate-layout") + args = ap.parse_args() + + if args.path.lower().endswith(".pdf"): + image, words = render_pdf_page(args.path, args.page, dpi=300) + else: + image, words = Image.open(args.path).convert("RGB"), None + g = load(os.environ.get("OCRIA_MODEL", MODEL)) + fast = load_fast_layout() if args.layout == "fast-layout" else None + det = None if args.attention_only or fast is not None else load_detector() + t0 = time.perf_counter() + answer = transcribe(g, image) + t1 = time.perf_counter() + page = ground_layout(g, image, answer, detector=det, words=words if fast is None else None, + method=args.layout, fast_backend=fast) + t2 = time.perf_counter() + + out = image.copy() + draw = ImageDraw.Draw(out) + width = max(2, image.width // 500) + pad = width + 2 # draw outside the box so the outline never covers the first or last letter + for it in page["items"]: + color = COLORS.get(it["type"], "#17becf") + x0, y0, x1, y1 = it["box"] + draw.rectangle([x0 - pad, y0 - pad, x1 + pad, y1 + pad], outline=color, width=width) + tw, th = draw.textbbox((0, 0), it["type"])[2:] # the type label sits above the box, on a white tab + ty = max(0, y0 - pad - th - 2) + draw.rectangle([x0 - pad, ty, x0 - pad + tw + 4, ty + th + 2], fill="white") + draw.text((x0 - pad + 2, ty), it["type"], fill=color) + stem = Path(args.path).with_suffix("") + if args.path.lower().endswith(".pdf"): + stem = Path(f"{stem}.p{args.page}") + out.save(f"{stem}.boxes.png") + Path(f"{stem}.boxes.json").write_text(json.dumps({"answer": answer, **page}, indent=1)) + print(f"{len(page['items'])} items -> {stem}.boxes.png (transcription {t1 - t0:.1f} s, boxes {t2 - t1:.1f} s)") + + +if __name__ == "__main__": + main() diff --git a/examples/serve_boxes.py b/examples/serve_boxes.py new file mode 100644 index 0000000000000000000000000000000000000000..b323f829d6da5e2b8cec62d5338c17b17173d421 --- /dev/null +++ b/examples/serve_boxes.py @@ -0,0 +1,86 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""HTTP server for OCRia-1 layout boxes: transcribe pages anywhere (vLLM, ...), get the boxes here. + + pip install "transformers==5.22.2" accelerate torchvision timm scipy pypdfium2 huggingface_hub + python examples/serve_boxes.py --port 8100 # loads OCRia-1 (CUDA) and the Heron layout detector + + POST /ground {"image_png_b64": ..., "answer": ..., "words": [{"text", "box": [x0, y0, x1, y1]}] | null} + -> {"width", "height", "items": [{"type", "label", "md", "box": [x0, y0, x1, y1], "start"}]} + GET /health -> {"ok": true} + +`image_png_b64` must be the exact page image the answer was generated from, and `answer` the raw answer. `words` are +the page's PDF text-layer words in pixels of that image (`ocria_grounding.pdf.page_words`); pass null for images. +Boxes are pixels of the image. One request runs at a time on the GPU; run several servers for throughput. +""" +import argparse +import base64 +import io +import json +import os +import sys +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path + +from PIL import Image + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # the repository root holds ocria_grounding/ +from ocria_grounding import MODEL, ground_layout, load, load_detector, load_fast_layout # noqa: E402 + +STATE: dict = {} +LOCK = threading.Lock() + + +class Handler(BaseHTTPRequestHandler): + def _send(self, code: int, obj: dict) -> None: + body = json.dumps(obj).encode() + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self) -> None: # noqa: N802 + self._send(200, {"ok": True}) if self.path == "/health" else self._send(404, {"error": "not found"}) + + def do_POST(self) -> None: # noqa: N802 + if self.path != "/ground": + return self._send(404, {"error": "not found"}) + try: + req = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0)))) + image = Image.open(io.BytesIO(base64.b64decode(req["image_png_b64"]))).convert("RGB") + answer = req["answer"] + except Exception as e: # malformed request + return self._send(400, {"error": f"bad request: {e}"}) + try: + with LOCK: + page = ground_layout(STATE["g"], image, answer, detector=STATE["det"], + words=req.get("words"), method=STATE["method"], + fast_backend=STATE["fast"]) + except Exception as e: + return self._send(500, {"error": repr(e)}) + self._send(200, page) + + def log_message(self, fmt, *args) -> None: # quiet access log + pass + + +def main() -> None: + ap = argparse.ArgumentParser() + ap.add_argument("--host", default="0.0.0.0") + ap.add_argument("--port", type=int, default=8100) + ap.add_argument("--no-detector", action="store_true", help="attention-only boxes (less accurate)") + ap.add_argument("--layout", choices=["accurate-layout", "fast-layout"], default="accurate-layout") + args = ap.parse_args() + STATE["g"] = load(os.environ.get("OCRIA_MODEL", MODEL)) + STATE["method"] = args.layout + STATE["fast"] = load_fast_layout() if args.layout == "fast-layout" else None + STATE["det"] = None if args.no_detector or STATE["fast"] is not None else load_detector() + print(f"serving OCRia-1 layout boxes on http://{args.host}:{args.port}", flush=True) + ThreadingHTTPServer((args.host, args.port), Handler).serve_forever() + + +if __name__ == "__main__": + main() diff --git a/fast_layout_models/manifest.json b/fast_layout_models/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..17aa837eac4bda14f39431cc5ce343af08ca0723 --- /dev/null +++ b/fast_layout_models/manifest.json @@ -0,0 +1,11 @@ +{ + "source_commit": "763c56ea11", + "frozen": true, + "sha256": { + "pictures.joblib": "8c3724d22c36e13d6bffebf90f7b1eecc7d2cae12ffd5d17f2de469f013c9d1a", + "peaks.joblib": "c6755864b47aad70f5ecc59173a6cd0879f889fc91e6243028617878fa61d5ea", + "words.joblib": "1fc131e9dfebe34647e31636a817000c2cfce0c9f6131481a59ee2ac35268b43", + "tables.joblib": "ea554fc7b19462b30ec55a925c24fa04c7107c13e72e655593320df07830fe4e", + "regions.joblib": "7837010ee75619bc70d07fa79162b6b58a4fab16b49c8f00c9fa2925e0e90329" + } +} diff --git a/fast_layout_models/peaks.joblib b/fast_layout_models/peaks.joblib new file mode 100644 index 0000000000000000000000000000000000000000..330cc14cd5c2e476fa725c998721fae7fea5eb65 --- /dev/null +++ b/fast_layout_models/peaks.joblib @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c6755864b47aad70f5ecc59173a6cd0879f889fc91e6243028617878fa61d5ea +size 235608 diff --git a/fast_layout_models/pictures.joblib b/fast_layout_models/pictures.joblib new file mode 100644 index 0000000000000000000000000000000000000000..14780866f41c3471cc974fb6dfcadfb33a3fd507 --- /dev/null +++ b/fast_layout_models/pictures.joblib @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8c3724d22c36e13d6bffebf90f7b1eecc7d2cae12ffd5d17f2de469f013c9d1a +size 1374212 diff --git a/fast_layout_models/regions.joblib b/fast_layout_models/regions.joblib new file mode 100644 index 0000000000000000000000000000000000000000..5d7fb2c00fe1a295a42d20ca3d7381ea2e536c65 --- /dev/null +++ b/fast_layout_models/regions.joblib @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7837010ee75619bc70d07fa79162b6b58a4fab16b49c8f00c9fa2925e0e90329 +size 3047721 diff --git a/fast_layout_models/tables.joblib b/fast_layout_models/tables.joblib new file mode 100644 index 0000000000000000000000000000000000000000..9b6c6b39d7d48b71759306a821564bbfa25d014f --- /dev/null +++ b/fast_layout_models/tables.joblib @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ea554fc7b19462b30ec55a925c24fa04c7107c13e72e655593320df07830fe4e +size 323350 diff --git a/fast_layout_models/words.joblib b/fast_layout_models/words.joblib new file mode 100644 index 0000000000000000000000000000000000000000..cdb9457c691aa1d849333f17de1e6fc8831db797 --- /dev/null +++ b/fast_layout_models/words.joblib @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1fc131e9dfebe34647e31636a817000c2cfce0c9f6131481a59ee2ac35268b43 +size 2629519 diff --git a/generation_config.json b/generation_config.json new file mode 100644 index 0000000000000000000000000000000000000000..785c447fc97e807a915a39d005684b941b706950 --- /dev/null +++ b/generation_config.json @@ -0,0 +1,9 @@ +{ + "_from_model_config": true, + "eos_token_id": 248046, + "output_attentions": false, + "output_hidden_states": false, + "pad_token_id": 248044, + "transformers_version": "5.24.1", + "use_cache": true +} diff --git a/model-00001-of-00002.safetensors b/model-00001-of-00002.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..8fb5da549b2d758152a6f915e38a6c7dd22ad0e1 --- /dev/null +++ b/model-00001-of-00002.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c7fb5defbb448d1576e5aa28abf4cd15dfa3fe0c12505625bbdc7fb7bf92b681 +size 4982546256 diff --git a/model-00002-of-00002.safetensors b/model-00002-of-00002.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..9e2aad5ee4cb6ef4ff580f4096b51612115edda0 --- /dev/null +++ b/model-00002-of-00002.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:056bf85227fd2ae96e518cc5816b34a670e93abadb2a26c3eb8ce2c247b4aaae +size 1729601144 diff --git a/model.safetensors.index.json b/model.safetensors.index.json new file mode 100644 index 0000000000000000000000000000000000000000..2294269d16378319a140634d400178cf548ddb77 --- /dev/null +++ b/model.safetensors.index.json @@ -0,0 +1,988 @@ +{ + "metadata": { + "total_parameters": 2616439296, + "total_size": 6712026112 + }, + "weight_map": { + "lm_head.weight": "model-00001-of-00002.safetensors", + "model.language_model.embed_tokens.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.0.input_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.0.linear_attn.A_log": "model-00001-of-00002.safetensors", + "model.language_model.layers.0.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.0.linear_attn.dt_bias": "model-00001-of-00002.safetensors", + "model.language_model.layers.0.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.0.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.0.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.0.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.0.linear_attn.norm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.0.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.0.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.0.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.0.mlp.down_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.0.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.0.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.0.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.0.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.0.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.0.mlp.up_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.0.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.1.input_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.1.linear_attn.A_log": "model-00001-of-00002.safetensors", + "model.language_model.layers.1.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.1.linear_attn.dt_bias": "model-00001-of-00002.safetensors", + "model.language_model.layers.1.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.1.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.1.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.1.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.1.linear_attn.norm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.1.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.1.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.1.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.1.mlp.down_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.1.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.1.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.1.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.1.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.1.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.1.mlp.up_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.1.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.10.input_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.10.linear_attn.A_log": "model-00001-of-00002.safetensors", + "model.language_model.layers.10.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.10.linear_attn.dt_bias": "model-00001-of-00002.safetensors", + "model.language_model.layers.10.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.10.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.10.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.10.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.10.linear_attn.norm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.10.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.10.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.10.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.10.mlp.down_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.10.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.10.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.10.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.10.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.10.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.10.mlp.up_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.10.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.11.input_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.11.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.11.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.11.mlp.down_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.11.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.11.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.11.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.11.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.11.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.11.mlp.up_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.11.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.11.self_attn.k_norm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.11.self_attn.k_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.11.self_attn.k_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.11.self_attn.k_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.11.self_attn.o_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.11.self_attn.o_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.11.self_attn.o_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.11.self_attn.q_norm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.11.self_attn.q_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.11.self_attn.q_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.11.self_attn.q_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.11.self_attn.v_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.11.self_attn.v_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.11.self_attn.v_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.12.input_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.12.linear_attn.A_log": "model-00001-of-00002.safetensors", + "model.language_model.layers.12.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.12.linear_attn.dt_bias": "model-00001-of-00002.safetensors", + "model.language_model.layers.12.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.12.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.12.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.12.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.12.linear_attn.norm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.12.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.12.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.12.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.12.mlp.down_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.12.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.12.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.12.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.12.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.12.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.12.mlp.up_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.12.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.13.input_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.13.linear_attn.A_log": "model-00001-of-00002.safetensors", + "model.language_model.layers.13.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.13.linear_attn.dt_bias": "model-00001-of-00002.safetensors", + "model.language_model.layers.13.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.13.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.13.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.13.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.13.linear_attn.norm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.13.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.13.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.13.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.13.mlp.down_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.13.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.13.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.13.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.13.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.13.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.13.mlp.up_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.13.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.14.input_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.14.linear_attn.A_log": "model-00001-of-00002.safetensors", + "model.language_model.layers.14.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.14.linear_attn.dt_bias": "model-00001-of-00002.safetensors", + "model.language_model.layers.14.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.14.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.14.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.14.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.14.linear_attn.norm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.14.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.14.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.14.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.14.mlp.down_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.14.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.14.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.14.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.14.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.14.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.14.mlp.up_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.14.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.15.input_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.15.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.15.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.15.mlp.down_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.15.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.15.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.15.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.15.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.15.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.15.mlp.up_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.15.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.15.self_attn.k_norm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.15.self_attn.k_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.15.self_attn.k_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.15.self_attn.k_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.15.self_attn.o_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.15.self_attn.o_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.15.self_attn.o_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.15.self_attn.q_norm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.15.self_attn.q_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.15.self_attn.q_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.15.self_attn.q_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.15.self_attn.v_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.15.self_attn.v_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.15.self_attn.v_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.16.input_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.16.linear_attn.A_log": "model-00001-of-00002.safetensors", + "model.language_model.layers.16.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.16.linear_attn.dt_bias": "model-00001-of-00002.safetensors", + "model.language_model.layers.16.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.16.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.16.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.16.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.16.linear_attn.norm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.16.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.16.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.16.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.16.mlp.down_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.16.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.16.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.16.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.16.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.16.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.16.mlp.up_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.16.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.17.input_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.17.linear_attn.A_log": "model-00001-of-00002.safetensors", + "model.language_model.layers.17.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.17.linear_attn.dt_bias": "model-00001-of-00002.safetensors", + "model.language_model.layers.17.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.17.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.17.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.17.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.17.linear_attn.norm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.17.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.17.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.17.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.17.mlp.down_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.17.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.17.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.17.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.17.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.17.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.17.mlp.up_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.17.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.18.input_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.18.linear_attn.A_log": "model-00001-of-00002.safetensors", + "model.language_model.layers.18.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.18.linear_attn.dt_bias": "model-00001-of-00002.safetensors", + "model.language_model.layers.18.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.18.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.18.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.18.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.18.linear_attn.norm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.18.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.18.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.18.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.18.mlp.down_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.18.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.18.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.18.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.18.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.18.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.18.mlp.up_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.18.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.19.input_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.19.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.19.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.19.mlp.down_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.19.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.19.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.19.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.19.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.19.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.19.mlp.up_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.19.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.19.self_attn.k_norm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.19.self_attn.k_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.19.self_attn.k_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.19.self_attn.k_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.19.self_attn.o_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.19.self_attn.o_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.19.self_attn.o_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.19.self_attn.q_norm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.19.self_attn.q_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.19.self_attn.q_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.19.self_attn.q_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.19.self_attn.v_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.19.self_attn.v_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.19.self_attn.v_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.2.input_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.2.linear_attn.A_log": "model-00001-of-00002.safetensors", + "model.language_model.layers.2.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.2.linear_attn.dt_bias": "model-00001-of-00002.safetensors", + "model.language_model.layers.2.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.2.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.2.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.2.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.2.linear_attn.norm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.2.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.2.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.2.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.2.mlp.down_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.2.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.2.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.2.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.2.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.2.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.2.mlp.up_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.2.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.20.input_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.20.linear_attn.A_log": "model-00001-of-00002.safetensors", + "model.language_model.layers.20.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.20.linear_attn.dt_bias": "model-00001-of-00002.safetensors", + "model.language_model.layers.20.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.20.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.20.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.20.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.20.linear_attn.norm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.20.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.20.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.20.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.20.mlp.down_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.20.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.20.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.20.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.20.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.20.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.20.mlp.up_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.20.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.21.input_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.21.linear_attn.A_log": "model-00001-of-00002.safetensors", + "model.language_model.layers.21.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.21.linear_attn.dt_bias": "model-00001-of-00002.safetensors", + "model.language_model.layers.21.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.21.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.21.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.21.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.21.linear_attn.norm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.21.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.21.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.21.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.21.mlp.down_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.21.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.21.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.21.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.21.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.21.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.21.mlp.up_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.21.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.22.input_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.22.linear_attn.A_log": "model-00001-of-00002.safetensors", + "model.language_model.layers.22.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.22.linear_attn.dt_bias": "model-00001-of-00002.safetensors", + "model.language_model.layers.22.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.22.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.22.linear_attn.in_proj_qkv.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.22.linear_attn.in_proj_z.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.22.linear_attn.norm.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.22.linear_attn.out_proj.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.22.mlp.down_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.22.mlp.down_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.22.mlp.down_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.22.mlp.gate_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.22.mlp.gate_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.22.mlp.gate_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.22.mlp.up_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.22.mlp.up_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.22.mlp.up_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.22.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.23.input_layernorm.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.23.mlp.down_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.23.mlp.down_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.23.mlp.down_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.23.mlp.gate_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.23.mlp.gate_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.23.mlp.gate_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.23.mlp.up_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.23.mlp.up_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.23.mlp.up_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.23.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.23.self_attn.k_norm.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.23.self_attn.k_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.23.self_attn.k_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.23.self_attn.k_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.23.self_attn.o_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.23.self_attn.o_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.23.self_attn.o_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.23.self_attn.q_norm.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.23.self_attn.q_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.23.self_attn.q_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.23.self_attn.q_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.23.self_attn.v_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.23.self_attn.v_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.23.self_attn.v_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.24.input_layernorm.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.24.linear_attn.A_log": "model-00002-of-00002.safetensors", + "model.language_model.layers.24.linear_attn.conv1d.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.24.linear_attn.dt_bias": "model-00002-of-00002.safetensors", + "model.language_model.layers.24.linear_attn.in_proj_a.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.24.linear_attn.in_proj_b.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.24.linear_attn.in_proj_qkv.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.24.linear_attn.in_proj_z.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.24.linear_attn.norm.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.24.linear_attn.out_proj.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.24.mlp.down_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.24.mlp.down_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.24.mlp.down_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.24.mlp.gate_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.24.mlp.gate_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.24.mlp.gate_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.24.mlp.up_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.24.mlp.up_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.24.mlp.up_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.24.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.25.input_layernorm.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.25.linear_attn.A_log": "model-00002-of-00002.safetensors", + "model.language_model.layers.25.linear_attn.conv1d.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.25.linear_attn.dt_bias": "model-00002-of-00002.safetensors", + "model.language_model.layers.25.linear_attn.in_proj_a.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.25.linear_attn.in_proj_b.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.25.linear_attn.in_proj_qkv.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.25.linear_attn.in_proj_z.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.25.linear_attn.norm.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.25.linear_attn.out_proj.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.25.mlp.down_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.25.mlp.down_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.25.mlp.down_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.25.mlp.gate_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.25.mlp.gate_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.25.mlp.gate_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.25.mlp.up_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.25.mlp.up_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.25.mlp.up_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.25.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.26.input_layernorm.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.26.linear_attn.A_log": "model-00002-of-00002.safetensors", + "model.language_model.layers.26.linear_attn.conv1d.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.26.linear_attn.dt_bias": "model-00002-of-00002.safetensors", + "model.language_model.layers.26.linear_attn.in_proj_a.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.26.linear_attn.in_proj_b.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.26.linear_attn.in_proj_qkv.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.26.linear_attn.in_proj_z.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.26.linear_attn.norm.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.26.linear_attn.out_proj.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.26.mlp.down_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.26.mlp.down_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.26.mlp.down_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.26.mlp.gate_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.26.mlp.gate_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.26.mlp.gate_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.26.mlp.up_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.26.mlp.up_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.26.mlp.up_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.26.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.27.input_layernorm.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.27.mlp.down_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.27.mlp.down_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.27.mlp.down_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.27.mlp.gate_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.27.mlp.gate_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.27.mlp.gate_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.27.mlp.up_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.27.mlp.up_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.27.mlp.up_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.27.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.27.self_attn.k_norm.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.27.self_attn.k_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.27.self_attn.k_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.27.self_attn.k_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.27.self_attn.o_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.27.self_attn.o_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.27.self_attn.o_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.27.self_attn.q_norm.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.27.self_attn.q_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.27.self_attn.q_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.27.self_attn.q_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.27.self_attn.v_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.27.self_attn.v_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.27.self_attn.v_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.28.input_layernorm.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.28.linear_attn.A_log": "model-00002-of-00002.safetensors", + "model.language_model.layers.28.linear_attn.conv1d.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.28.linear_attn.dt_bias": "model-00002-of-00002.safetensors", + "model.language_model.layers.28.linear_attn.in_proj_a.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.28.linear_attn.in_proj_b.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.28.linear_attn.in_proj_qkv.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.28.linear_attn.in_proj_z.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.28.linear_attn.norm.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.28.linear_attn.out_proj.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.28.mlp.down_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.28.mlp.down_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.28.mlp.down_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.28.mlp.gate_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.28.mlp.gate_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.28.mlp.gate_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.28.mlp.up_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.28.mlp.up_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.28.mlp.up_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.28.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.29.input_layernorm.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.29.linear_attn.A_log": "model-00002-of-00002.safetensors", + "model.language_model.layers.29.linear_attn.conv1d.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.29.linear_attn.dt_bias": "model-00002-of-00002.safetensors", + "model.language_model.layers.29.linear_attn.in_proj_a.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.29.linear_attn.in_proj_b.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.29.linear_attn.in_proj_qkv.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.29.linear_attn.in_proj_z.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.29.linear_attn.norm.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.29.linear_attn.out_proj.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.29.mlp.down_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.29.mlp.down_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.29.mlp.down_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.29.mlp.gate_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.29.mlp.gate_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.29.mlp.gate_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.29.mlp.up_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.29.mlp.up_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.29.mlp.up_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.29.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.3.input_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.3.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.3.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.3.mlp.down_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.3.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.3.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.3.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.3.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.3.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.3.mlp.up_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.3.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.3.self_attn.k_norm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.3.self_attn.k_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.3.self_attn.k_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.3.self_attn.k_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.3.self_attn.o_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.3.self_attn.o_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.3.self_attn.o_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.3.self_attn.q_norm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.3.self_attn.q_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.3.self_attn.q_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.3.self_attn.q_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.3.self_attn.v_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.3.self_attn.v_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.3.self_attn.v_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.30.input_layernorm.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.30.linear_attn.A_log": "model-00002-of-00002.safetensors", + "model.language_model.layers.30.linear_attn.conv1d.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.30.linear_attn.dt_bias": "model-00002-of-00002.safetensors", + "model.language_model.layers.30.linear_attn.in_proj_a.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.30.linear_attn.in_proj_b.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.30.linear_attn.in_proj_qkv.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.30.linear_attn.in_proj_z.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.30.linear_attn.norm.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.30.linear_attn.out_proj.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.30.mlp.down_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.30.mlp.down_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.30.mlp.down_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.30.mlp.gate_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.30.mlp.gate_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.30.mlp.gate_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.30.mlp.up_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.30.mlp.up_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.30.mlp.up_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.30.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.31.input_layernorm.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.31.mlp.down_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.31.mlp.down_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.31.mlp.down_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.31.mlp.gate_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.31.mlp.gate_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.31.mlp.gate_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.31.mlp.up_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.31.mlp.up_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.31.mlp.up_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.31.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.31.self_attn.k_norm.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.31.self_attn.k_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.31.self_attn.k_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.31.self_attn.k_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.31.self_attn.o_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.31.self_attn.o_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.31.self_attn.o_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.31.self_attn.q_norm.weight": "model-00002-of-00002.safetensors", + "model.language_model.layers.31.self_attn.q_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.31.self_attn.q_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.31.self_attn.q_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.31.self_attn.v_proj.qweight": "model-00002-of-00002.safetensors", + "model.language_model.layers.31.self_attn.v_proj.qzeros": "model-00002-of-00002.safetensors", + "model.language_model.layers.31.self_attn.v_proj.scales": "model-00002-of-00002.safetensors", + "model.language_model.layers.4.input_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.4.linear_attn.A_log": "model-00001-of-00002.safetensors", + "model.language_model.layers.4.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.4.linear_attn.dt_bias": "model-00001-of-00002.safetensors", + "model.language_model.layers.4.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.4.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.4.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.4.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.4.linear_attn.norm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.4.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.4.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.4.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.4.mlp.down_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.4.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.4.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.4.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.4.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.4.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.4.mlp.up_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.4.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.5.input_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.5.linear_attn.A_log": "model-00001-of-00002.safetensors", + "model.language_model.layers.5.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.5.linear_attn.dt_bias": "model-00001-of-00002.safetensors", + "model.language_model.layers.5.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.5.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.5.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.5.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.5.linear_attn.norm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.5.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.5.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.5.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.5.mlp.down_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.5.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.5.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.5.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.5.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.5.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.5.mlp.up_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.5.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.6.input_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.6.linear_attn.A_log": "model-00001-of-00002.safetensors", + "model.language_model.layers.6.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.6.linear_attn.dt_bias": "model-00001-of-00002.safetensors", + "model.language_model.layers.6.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.6.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.6.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.6.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.6.linear_attn.norm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.6.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.6.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.6.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.6.mlp.down_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.6.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.6.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.6.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.6.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.6.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.6.mlp.up_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.6.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.7.input_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.7.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.7.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.7.mlp.down_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.7.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.7.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.7.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.7.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.7.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.7.mlp.up_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.7.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.7.self_attn.k_norm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.7.self_attn.k_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.7.self_attn.k_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.7.self_attn.k_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.7.self_attn.o_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.7.self_attn.o_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.7.self_attn.o_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.7.self_attn.q_norm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.7.self_attn.q_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.7.self_attn.q_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.7.self_attn.q_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.7.self_attn.v_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.7.self_attn.v_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.7.self_attn.v_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.8.input_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.8.linear_attn.A_log": "model-00001-of-00002.safetensors", + "model.language_model.layers.8.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.8.linear_attn.dt_bias": "model-00001-of-00002.safetensors", + "model.language_model.layers.8.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.8.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.8.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.8.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.8.linear_attn.norm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.8.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.8.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.8.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.8.mlp.down_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.8.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.8.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.8.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.8.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.8.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.8.mlp.up_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.8.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.9.input_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.9.linear_attn.A_log": "model-00001-of-00002.safetensors", + "model.language_model.layers.9.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.9.linear_attn.dt_bias": "model-00001-of-00002.safetensors", + "model.language_model.layers.9.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.9.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.9.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.9.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.9.linear_attn.norm.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.9.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", + "model.language_model.layers.9.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.9.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.9.mlp.down_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.9.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.9.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.9.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.9.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", + "model.language_model.layers.9.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", + "model.language_model.layers.9.mlp.up_proj.scales": "model-00001-of-00002.safetensors", + "model.language_model.layers.9.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", + "model.language_model.norm.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.0.attn.proj.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.0.attn.proj.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.0.attn.qkv.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.0.attn.qkv.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.0.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.0.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.0.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.0.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.0.norm1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.0.norm1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.0.norm2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.0.norm2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.1.attn.proj.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.1.attn.proj.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.1.attn.qkv.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.1.attn.qkv.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.1.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.1.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.1.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.1.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.1.norm1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.1.norm1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.1.norm2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.1.norm2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.10.attn.proj.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.10.attn.proj.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.10.attn.qkv.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.10.attn.qkv.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.10.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.10.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.10.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.10.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.10.norm1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.10.norm1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.10.norm2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.10.norm2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.11.attn.proj.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.11.attn.proj.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.11.attn.qkv.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.11.attn.qkv.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.11.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.11.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.11.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.11.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.11.norm1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.11.norm1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.11.norm2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.11.norm2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.12.attn.proj.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.12.attn.proj.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.12.attn.qkv.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.12.attn.qkv.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.12.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.12.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.12.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.12.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.12.norm1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.12.norm1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.12.norm2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.12.norm2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.13.attn.proj.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.13.attn.proj.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.13.attn.qkv.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.13.attn.qkv.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.13.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.13.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.13.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.13.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.13.norm1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.13.norm1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.13.norm2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.13.norm2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.14.attn.proj.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.14.attn.proj.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.14.attn.qkv.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.14.attn.qkv.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.14.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.14.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.14.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.14.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.14.norm1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.14.norm1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.14.norm2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.14.norm2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.15.attn.proj.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.15.attn.proj.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.15.attn.qkv.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.15.attn.qkv.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.15.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.15.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.15.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.15.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.15.norm1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.15.norm1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.15.norm2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.15.norm2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.16.attn.proj.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.16.attn.proj.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.16.attn.qkv.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.16.attn.qkv.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.16.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.16.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.16.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.16.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.16.norm1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.16.norm1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.16.norm2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.16.norm2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.17.attn.proj.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.17.attn.proj.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.17.attn.qkv.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.17.attn.qkv.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.17.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.17.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.17.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.17.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.17.norm1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.17.norm1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.17.norm2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.17.norm2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.18.attn.proj.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.18.attn.proj.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.18.attn.qkv.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.18.attn.qkv.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.18.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.18.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.18.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.18.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.18.norm1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.18.norm1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.18.norm2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.18.norm2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.19.attn.proj.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.19.attn.proj.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.19.attn.qkv.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.19.attn.qkv.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.19.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.19.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.19.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.19.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.19.norm1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.19.norm1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.19.norm2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.19.norm2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.2.attn.proj.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.2.attn.proj.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.2.attn.qkv.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.2.attn.qkv.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.2.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.2.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.2.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.2.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.2.norm1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.2.norm1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.2.norm2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.2.norm2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.20.attn.proj.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.20.attn.proj.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.20.attn.qkv.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.20.attn.qkv.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.20.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.20.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.20.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.20.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.20.norm1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.20.norm1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.20.norm2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.20.norm2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.21.attn.proj.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.21.attn.proj.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.21.attn.qkv.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.21.attn.qkv.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.21.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.21.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.21.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.21.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.21.norm1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.21.norm1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.21.norm2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.21.norm2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.22.attn.proj.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.22.attn.proj.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.22.attn.qkv.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.22.attn.qkv.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.22.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.22.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.22.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.22.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.22.norm1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.22.norm1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.22.norm2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.22.norm2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.23.attn.proj.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.23.attn.proj.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.23.attn.qkv.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.23.attn.qkv.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.23.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.23.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.23.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.23.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.23.norm1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.23.norm1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.23.norm2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.23.norm2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.3.attn.proj.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.3.attn.proj.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.3.attn.qkv.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.3.attn.qkv.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.3.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.3.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.3.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.3.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.3.norm1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.3.norm1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.3.norm2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.3.norm2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.4.attn.proj.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.4.attn.proj.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.4.attn.qkv.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.4.attn.qkv.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.4.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.4.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.4.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.4.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.4.norm1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.4.norm1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.4.norm2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.4.norm2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.5.attn.proj.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.5.attn.proj.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.5.attn.qkv.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.5.attn.qkv.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.5.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.5.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.5.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.5.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.5.norm1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.5.norm1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.5.norm2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.5.norm2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.6.attn.proj.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.6.attn.proj.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.6.attn.qkv.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.6.attn.qkv.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.6.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.6.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.6.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.6.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.6.norm1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.6.norm1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.6.norm2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.6.norm2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.7.attn.proj.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.7.attn.proj.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.7.attn.qkv.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.7.attn.qkv.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.7.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.7.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.7.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.7.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.7.norm1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.7.norm1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.7.norm2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.7.norm2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.8.attn.proj.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.8.attn.proj.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.8.attn.qkv.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.8.attn.qkv.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.8.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.8.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.8.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.8.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.8.norm1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.8.norm1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.8.norm2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.8.norm2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.9.attn.proj.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.9.attn.proj.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.9.attn.qkv.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.9.attn.qkv.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.9.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.9.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.9.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.9.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.9.norm1.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.9.norm1.weight": "model-00002-of-00002.safetensors", + "model.visual.blocks.9.norm2.bias": "model-00002-of-00002.safetensors", + "model.visual.blocks.9.norm2.weight": "model-00002-of-00002.safetensors", + "model.visual.merger.linear_fc1.bias": "model-00002-of-00002.safetensors", + "model.visual.merger.linear_fc1.weight": "model-00002-of-00002.safetensors", + "model.visual.merger.linear_fc2.bias": "model-00002-of-00002.safetensors", + "model.visual.merger.linear_fc2.weight": "model-00002-of-00002.safetensors", + "model.visual.merger.norm.bias": "model-00002-of-00002.safetensors", + "model.visual.merger.norm.weight": "model-00002-of-00002.safetensors", + "model.visual.patch_embed.proj.bias": "model-00002-of-00002.safetensors", + "model.visual.patch_embed.proj.weight": "model-00002-of-00002.safetensors", + "model.visual.pos_embed.weight": "model-00002-of-00002.safetensors" + } +} diff --git a/ocria_grounding/__init__.py b/ocria_grounding/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..008a45131d40b96015917db41ec3f01209092d06 --- /dev/null +++ b/ocria_grounding/__init__.py @@ -0,0 +1,76 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Layout boxes for OCRia-1 answers (experimental). + +OCRia-1 writes markdown without boxes. This package places that markdown on the page: + +1. A layout detector (Docling's Heron, Apache-2.0, downloaded from its own repository) finds the page's regions. +2. Every word of the answer gets a position: its PDF word box when the page has a text layer, else the ink its + attention points at, read from a second, teacher-forced pass of the same weights over the page and the answer. +3. Each region becomes an item holding the answer's words that fall in it. + + from ocria_grounding import load, load_detector, transcribe, ground_layout, render_pdf_page + g, det = load(), load_detector() # OCRia-1 (CUDA) and Heron (cuda, else mps, else cpu) + image, words = render_pdf_page("doc.pdf", 0) # 300-DPI page + its text-layer words (omit for image inputs) + answer = transcribe(g, image) # or the raw answer from any other server (vLLM, ...) + page = ground_layout(g, image, answer, detector=det, words=words) + # {width, height, items: [{type, label, md, box: [x0, y0, x1, y1], start}]}, boxes in pixels of `image` + +Pass exactly the image and system prompt the answer was generated with. `to_layout_items_page` serializes the result +as a ParseBench layout page. Without a detector, `ground_layout` (and the older `ground_page`) fall back to boxes +from attention alone, which are much less accurate. +""" +from __future__ import annotations + +from pathlib import Path + +from .detector import DETECTOR, Detector +from .ground import ground_page, to_box_markdown, to_layout_page +from .heads import heads_for +from .layout import ground_layout, to_layout_items_page +from .pdf import render_pdf_page + +MODEL = "llamaindex/OCRia-1" +__all__ = ["load_fast_layout", "MODEL", "DETECTOR", "load", "load_detector", "transcribe", "ground_layout", "to_layout_items_page", + "render_pdf_page", "Detector", "ground_page", "to_box_markdown", "to_layout_page", "heads_for"] + + +def load_detector(model: str = DETECTOR, device: str | None = None) -> Detector: + """Docling's Heron layout detector (Apache-2.0, a separate download from its own repository).""" + return Detector(model, device) + + +def load(model: str = MODEL, device: str = "cuda", heads=None, system_prompt: str | None = None): + """A Grounder for OCRia-1: `model` is the repo id or a local copy of it; the heads and the system prompt default + to the ones shipped in this repository (prompt.txt).""" + from .capture import Grounder + + if system_prompt is None: + local = Path(__file__).resolve().parent.parent / "prompt.txt" + if not local.exists(): + from huggingface_hub import hf_hub_download + + local = Path(hf_hub_download(MODEL, "prompt.txt")) + system_prompt = local.read_text() + return Grounder(model, heads or heads_for(MODEL), system_prompt, device) + + +def transcribe(grounder, image, max_new_tokens: int = 24576) -> str: + """OCRia-1's raw answer for one page image (greedy), from the grounder's own model, so one model load serves both + the transcription and the boxes. For throughput, transcribe with vLLM instead and pass its raw answer.""" + import torch + + enc = grounder.proc(text=[grounder.prompt], images=[image.convert("RGB")], return_tensors="pt").to(grounder.device) + with torch.no_grad(): + ids = grounder.model.generate(**enc, max_new_tokens=max_new_tokens, do_sample=False) + return grounder.proc.decode(ids[0, enc["input_ids"].shape[1]:], skip_special_tokens=True) + + +def load_fast_layout(model_dir: str | Path | None = None): + """Load the five trusted frozen layout artifacts once, without GPU or downloads.""" + from parse_rl_utils.ocria_attention_grounding.api import FastLayout + + directory = Path(model_dir) if model_dir else Path(__file__).resolve().parent.parent / "fast_layout_models" + return FastLayout(**{key: directory / f"{key}.joblib" + for key in ("words", "pictures", "regions", "tables", "peaks")}) diff --git a/ocria_grounding/align.py b/ocria_grounding/align.py new file mode 100644 index 0000000000000000000000000000000000000000..e0b55bb1f1d4cdb10efeeae131f4c0f1ff8ae05d --- /dev/null +++ b/ocria_grounding/align.py @@ -0,0 +1,123 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Answer words -> PDF word boxes, by character-level alignment of the answer with the page's text layer. + +PDF text layers split words (kerning), merge them, and store columns and sidebars in another order than the answer. +The answer and the PDF text are folded to lowercase alphanumerics and aligned in order; then each long unmatched run +of the answer is aligned against the PDF text not used yet, in any order, but only where that text is unique on the +page (a header repeated in several tables would otherwise be matched to the wrong copy).""" +import difflib +import unicodedata + +def _fold(ch): + ch = unicodedata.normalize("NFKC", ch).lower() + return "".join(c for c in ch if c.isalnum()) + +def pdf_chars(words): + """Flatten PDF words into (char, box) with each word's box split evenly across its folded chars.""" + out = [] + for w in words: + t = "".join(_fold(c) for c in w["text"]) + if not t: + continue + x0, y0, x1, y1 = w["box"]; n = len(t); dx = (x1 - x0) / n + for k, c in enumerate(t): + out.append((c, [x0 + k * dx, y0, x0 + (k + 1) * dx, y1])) + return out + +def unit_boxes(answer, units, words, min_share=0.6, min_block=3): + pc = pdf_chars(words) + if not pc: + return {} + ps = "".join(c for c, _ in pc) + achars, owner = [], [] + for u, (s, e) in enumerate(units): + for ch in answer[s:e]: + f = _fold(ch) + for c in f: + achars.append(c); owner.append(u) + a = "".join(achars) + sm = difflib.SequenceMatcher(None, a, ps, autojunk=False) + hit = {} + for m in sm.get_matching_blocks(): + if m.size < min_block: + continue + for k in range(m.size): + hit.setdefault(owner[m.a + k], []).append(pc[m.b + k][1]) + n_by_unit = {} + for u in owner: + n_by_unit[u] = n_by_unit.get(u, 0) + 1 + out = {} + for u, bs in hit.items(): + if len(bs) < min_share * n_by_unit[u]: + continue + # keep the chars on the line of the median char (a word never spans lines) + ys = sorted((b[1] + b[3]) / 2 for b in bs); ym = ys[len(ys) // 2] + h = sorted(b[3] - b[1] for b in bs)[len(bs) // 2] + bs = [b for b in bs if abs((b[1] + b[3]) / 2 - ym) <= 0.6 * h] + out[u] = [min(b[0] for b in bs), min(b[1] for b in bs), max(b[2] for b in bs), max(b[3] for b in bs)] + return out + + +def unit_boxes_multi(answer, units, words, min_share=0.6, min_block=4, seg_min=8, passes=3, unique=True): + """unit_boxes plus out-of-order passes: each long run of unmatched answer chars is aligned against the PDF chars + not used yet (used ones masked), so columns / sidebars the PDF stores in another order still get boxes.""" + pc = pdf_chars(words) + if not pc: + return {} + pchars = [c for c, _ in pc] + achars, owner = [], [] + for u, (s, e) in enumerate(units): + for ch in answer[s:e]: + for c in _fold(ch): + achars.append(c); owner.append(u) + amatch = [None] * len(achars); pused = [False] * len(pchars) + + full = "".join(pchars) + + def align(a_lo, a_hi, out_of_order=False): + a = "".join(achars[a_lo:a_hi]) + p = "".join(c if not pused[k] else "\x00" for k, c in enumerate(pchars)) + sm = difflib.SequenceMatcher(None, a, p, autojunk=False) + for m in sm.get_matching_blocks(): + if m.size < (max(min_block, 8) if out_of_order and unique else min_block): + continue + if out_of_order and unique and full.count(a[m.a:m.a + m.size]) > 1: + continue # repeated text (same header in several tables): the out-of-order pass cannot tell which + for k in range(m.size): + if amatch[a_lo + m.a + k] is None and not pused[m.b + k]: + amatch[a_lo + m.a + k] = m.b + k; pused[m.b + k] = True + align(0, len(achars)) + for _ in range(passes): + segs, k = [], 0 + while k < len(achars): + if amatch[k] is None: + j = k + while j < len(achars) and amatch[j] is None: + j += 1 + if j - k >= seg_min: + segs.append((k, j)) + k = j + else: + k += 1 + if not segs: + break + for lo, hi in sorted(segs, key=lambda x: x[0] - x[1]): + align(lo, hi, out_of_order=True) + hit = {} + for i, b in enumerate(amatch): + if b is not None: + hit.setdefault(owner[i], []).append(pc[b][1]) + n_by_unit = {} + for u in owner: + n_by_unit[u] = n_by_unit.get(u, 0) + 1 + out = {} + for u, bs in hit.items(): + if len(bs) < min_share * n_by_unit[u]: + continue + ys = sorted((b[1] + b[3]) / 2 for b in bs); ym = ys[len(ys) // 2] + h = sorted(b[3] - b[1] for b in bs)[len(bs) // 2] + bs = [b for b in bs if abs((b[1] + b[3]) / 2 - ym) <= 0.6 * h] + out[u] = [min(b[0] for b in bs), min(b[1] for b in bs), max(b[2] for b in bs), max(b[3] for b in bs)] + return out diff --git a/ocria_grounding/blocks.py b/ocria_grounding/blocks.py new file mode 100644 index 0000000000000000000000000000000000000000..b2a5334a7999a8c76eee8812aac2abb5e6fe6e98 --- /dev/null +++ b/ocria_grounding/blocks.py @@ -0,0 +1,227 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Layout elements of a raw ocria answer: the character spans that each get one box, with a type. + +The answer is ocria's no-layout transcription (markdown, HTML tables, ``/``/`` +furniture tags, `![label: description]` image references, ```mermaid diagrams). Each element becomes one +`` marker, so the types are the box-mode vocabulary the layout scorer already reads +(`layout_score._BOX_TYPE_TO_REGION_LABEL`): text, heading, list, table, image, code, header, footer. + +Granularity (one element per ...): paragraph (blank-line separated), heading line, list item (with its indented +continuation lines), whole table, image reference, fenced block, display-math block, furniture band. A standalone +`` gets type "page_number" and is resolved to header/footer from its box (`resolve_page_numbers`). +Offsets index the raw answer, fence included, so they line up with the teacher-forced tokens. +""" +from __future__ import annotations + +import re +from dataclasses import dataclass + +from .tune import FLAGS + +_OPEN_FENCE = re.compile(r"\A\s*```(?:markdown|md)?[ \t]*\n") +_FURN_OPEN = re.compile(r"<(page_header|page_footer|watermark)>") +_PAGE_NUMBER = re.compile(r"^\s*.*?\s*$") +_HEADING = re.compile(r"^\s{0,3}#{1,6}\s") +_IMAGE = re.compile(r"^\s*!\[") +_FENCE = re.compile(r"^\s*```") +_MATH = re.compile(r"^\s*\$\$") +_PIPE_ROW = re.compile(r"^\s*\|") +_TABLE_OPEN = re.compile(r"<(table|rcl)\b", re.I) # HTML table, or ocria-1.5's RCL grid +_LIST_ITEM = re.compile(r"^(\s*)(?:[*\-+•▪◦]\s|\d{1,3}[.)]\s|\(?[a-zA-Z][.)]\s|\[[ xX_]*\]\s)") +_BOLD_LINE = re.compile(r"^\s*\*\*[^*]+\*\*:?\s*$") +_TYPES_FOR_FURN = {"page_header": "header", "page_footer": "footer", "watermark": "text"} + + +@dataclass +class Block: + type: str + start: int + end: int + + +def _lines(text: str, lo: int, hi: int) -> list[tuple[int, int, str]]: + """(start, end, line) for each line of text[lo:hi]; end excludes the newline.""" + out, pos = [], lo + while pos < hi: + nl = text.find("\n", pos, hi) + end = hi if nl < 0 else nl + out.append((pos, end, text[pos:end])) + pos = end + 1 + return out + + +def body_span(text: str) -> tuple[int, int]: + """The transcription inside the ```markdown fence (the whole answer when there is none).""" + lo, hi = 0, len(text) + m = _OPEN_FENCE.match(text) + if m: + lo = m.end() + close = text.rfind("```") + if close >= lo: + hi = close + return lo, hi + + +def _starts_construct(line: str) -> bool: + return bool(_HEADING.match(line) or _IMAGE.match(line) or _FENCE.match(line) or _MATH.match(line) + or _PIPE_ROW.match(line) or _TABLE_OPEN.search(line) or _FURN_OPEN.search(line) + or _PAGE_NUMBER.match(line) or _LIST_ITEM.match(line)) + + +def split_blocks(text: str) -> list[Block]: + """Layout elements of one page's raw answer, in reading order.""" + lo, hi = body_span(text) + lines = _lines(text, lo, hi) + blocks: list[Block] = [] + i = 0 + + def until(j: int, pred) -> int: + """Index of the first line from j on for which pred holds (the last line when none does).""" + while j < len(lines) and not pred(lines[j][2]): + j += 1 + return min(j, len(lines) - 1) + + while i < len(lines): + s, e, line = lines[i] + if not line.strip(): + i += 1 + continue + m = _FURN_OPEN.search(line) + if m: + tag = m.group(1) + close = f"" + j = i if close in line else until(i + 1, lambda x: close in x) + blocks.append(Block(_TYPES_FOR_FURN[tag], s, lines[j][1])) + i = j + 1 + continue + if _PAGE_NUMBER.match(line): + blocks.append(Block("page_number", s, e)) + i += 1 + continue + tm = _TABLE_OPEN.search(line) + if tm: + close = "" if tm.group(1).lower() == "table" else "" + j = i if close in line.lower() else until(i + 1, lambda x: close in x.lower()) + if "split_layout_tables" in FLAGS and _is_layout_table(text[s:lines[j][1]]): + blocks.extend(_layout_table_blocks(text, s, lines[j][1])) + else: + blocks.append(Block("table", s, lines[j][1])) + i = j + 1 + continue + if _FENCE.match(line): + j = until(i + 1, lambda x: _FENCE.match(x) is not None) + kind = "image" if "mermaid" in line.lower() else "code" + blocks.append(Block(kind, s, lines[j][1])) + i = j + 1 + continue + if _MATH.match(line): + rest = line.strip()[2:] + j = i if "$$" in rest else until(i + 1, lambda x: "$$" in x) + blocks.append(Block("text", s, lines[j][1])) + i = j + 1 + continue + if _HEADING.match(line): + blocks.append(Block("heading", s, e)) + i += 1 + continue + if _IMAGE.match(line): + blocks.append(Block("image", s, e)) + i += 1 + continue + if _PIPE_ROW.match(line): + j = i + while j + 1 < len(lines) and _PIPE_ROW.match(lines[j + 1][2]): + j += 1 + blocks.append(Block("table", s, lines[j][1])) + i = j + 1 + continue + lm = _LIST_ITEM.match(line) + if lm: + indent = len(lm.group(1)) + j = i + while j + 1 < len(lines): + nxt = lines[j + 1][2] + if not nxt.strip() or _starts_construct(nxt): + break + if len(nxt) - len(nxt.lstrip()) <= indent: # a continuation line is indented under the marker + break + j += 1 + blocks.append(Block("list", s, lines[j][1])) + i = j + 1 + continue + if "split_lines" in FLAGS: # each line its own element; a bold-only line is a heading + blocks.append(Block("heading" if _BOLD_LINE.match(line) else "text", s, e)) + i += 1 + continue + j = i # paragraph: until a blank line or a line that opens another element + while j + 1 < len(lines) and lines[j + 1][2].strip() and not _starts_construct(lines[j + 1][2]): + j += 1 + blocks.append(Block("text", s, lines[j][1])) + i = j + 1 + if "inline_images" in FLAGS: + blocks = [p for b in blocks for p in _split_inline_images(text, b)] + return blocks + + +_INLINE_IMAGE = re.compile(r"!\[[^\]\n]*\](?:\([^)\s]*\))?") + + +def _split_inline_images(text: str, b: Block) -> list[Block]: + """An image reference inside a text-like element (an icon after a heading, a logo next to a footer's page number) + is a picture of its own on the page: the element is cut into the text before it, the image, and the text after.""" + if b.type in ("image", "table", "code") or "![" not in text[b.start:b.end]: + return [b] + out, pos = [], b.start + for m in _INLINE_IMAGE.finditer(text, b.start, b.end): + if _TAGS.sub("", text[pos:m.start()]).strip(" \t\n|*#-"): + out.append(Block(b.type, pos, m.start())) + out.append(Block("image", m.start(), m.end())) + pos = m.end() + if _TAGS.sub("", text[pos:b.end]).strip(" \t\n|*#-"): + out.append(Block(b.type, pos, b.end)) + return out or [b] + + +def resolve_page_numbers(blocks: list[Block], boxes: list, page_height: float) -> None: + """A standalone page number is furniture: header when its box sits in the top half, else footer.""" + for b, box in zip(blocks, boxes): + if b.type == "page_number": + b.type = "header" if box is not None and (box[1] + box[3]) / 2 < page_height / 2 else "footer" + +_CELL = re.compile(r"]*>(.*?)", re.S | re.I) +_TAGS = re.compile(r"<[^>]+>") + + +def _is_layout_table(html: str) -> bool: + """A table used to lay out a page (people grids, card layouts), not data: it holds image references, or its + cells hold prose (mean >= 8 words).""" + if "![" in html: + return True + words = [len(_TAGS.sub(" ", c).split()) for c in _CELL.findall(html) if c.strip()] + return bool(words) and sum(words) / len(words) >= 8 + + +def _layout_table_blocks(text: str, lo: int, hi: int) -> list[Block]: + """One element per segment of each cell: segments split at blank lines (two or more
, or any
with + split_br), an image reference is its own element.""" + sep = re.compile(r"(?:\s*)+" if "split_br" in FLAGS else r"(?:\s*){2,}", re.I) + out: list[Block] = [] + for m in _CELL.finditer(text, lo, hi): + a, b = m.start(1), m.end(1) + pos = a + for cut in [*sep.finditer(text, a, b), None]: + end = cut.start() if cut else b + seg = text[pos:end] + if _TAGS.sub("", seg).strip(): + k = pos + (len(seg) - len(seg.lstrip())) + for im in re.finditer(r"!\[[^\]]*\]", text[k:end]): + if text[k:k + im.start()].strip(): + out.append(Block("text", k, k + im.start())) + out.append(Block("image", k + im.start(), k + im.end())) + k = k + im.end() + if _TAGS.sub("", text[k:end]).strip(): + out.append(Block("text", k, end)) + pos = cut.end() if cut else b + return out diff --git a/ocria_grounding/boxes.py b/ocria_grounding/boxes.py new file mode 100644 index 0000000000000000000000000000000000000000..ee4c811ab5f40dbeb0ba321ecf441594317f4606 --- /dev/null +++ b/ocria_grounding/boxes.py @@ -0,0 +1,390 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Attention maps -> boxes on the page image (CPU only: numpy, scipy, PIL). + +Word boxes (82% of words at IoU >= 0.5 against exact PDF word boxes on held-out pages): the page ink is closed along the line into word blobs, and each word takes the blob near its attention peak +that has the most attention times a width prior from its character count, grown along the line toward that width. + +An element's box is the envelope of its words' boxes, after dropping words that sit apart from the element's main +cluster (a stray token attending somewhere else must not stretch the box across the page). An image reference has no +words on the page, so its box comes from the attention of its own tokens, snapped to the graphic under the peak. +""" +from __future__ import annotations + +import statistics + +import numpy as np +from PIL import Image +from scipy import ndimage + +from .tune import FLAGS + + +BIG_FONT = 2.0 # blob height / body glyph height above which a word is set in a larger font +MAX_FONT = 5.0 # taller blobs are frames, rules or graphics, never one line of text + + +def _u8(a): + return a.view(np.uint8) if a.dtype == bool else a.astype(np.uint8) + + +def dilate(a, shape): + """binary_dilation by an all-ones (h, w) rectangle, as two 1D max filters (same output, linear time).""" + h, w = shape + out = _u8(a) + if h > 1: + out = ndimage.maximum_filter1d(out, h, axis=0, mode="constant", cval=0, origin=-1 if h % 2 == 0 else 0) + if w > 1: + out = ndimage.maximum_filter1d(out, w, axis=1, mode="constant", cval=0, origin=-1 if w % 2 == 0 else 0) + return out.astype(bool) + + +def erode(a, shape): + """binary_erosion by an all-ones (h, w) rectangle (border counts as background), as two 1D min filters.""" + h, w = shape + out = _u8(a) + if h > 1: + out = ndimage.minimum_filter1d(out, h, axis=0, mode="constant", cval=0) + if w > 1: + out = ndimage.minimum_filter1d(out, w, axis=1, mode="constant", cval=0) + return out.astype(bool) + + +def close(a, shape): + """binary_closing by an all-ones (h, w) rectangle.""" + return erode(dilate(a, shape), shape) + + +class Page: + """Ink analysis of one rendered page, computed once and shared by every word on it.""" + + def __init__(self, rgb: np.ndarray, grid: tuple[int, int]): + self.h, self.w = rgb.shape[:2] + self.gh, self.gw = grid + self.cell = (self.w / self.gw, self.h / self.gh) + gray = np.asarray(Image.fromarray(rgb).convert("L"), dtype=np.float32) # PIL luma + self.ink = gray < min(160.0, float(gray.mean()) - 40.0) + if "contrast_ink" in FLAGS: # also light text on a dark local background (white on a coloured panel) + k = 8 + small = gray[::k, ::k] + bg_small = ndimage.median_filter(small, size=int(FLAGS.get("bg_size", "9"))) + bg = np.kron(bg_small, np.ones((k, k), np.float32))[:self.h, :self.w] + dark_bg = bg < float(FLAGS.get("dark_bg", "120")) + self.ink = (self.ink & ~dark_bg) | (dark_bg & (gray > bg + float(FLAGS.get("light_delta", "60")))) + # any non-background mark, light colours included: photos, chart fills, shaded boxes + sat = rgb.max(-1).astype(np.float32) - rgb.min(-1).astype(np.float32) + self.fg = (gray < 235.0) | (sat > 40.0) + lab, _ = ndimage.label(self.ink) + hs = [s[0].stop - s[0].start for s in ndimage.find_objects(lab) if s is not None] + self.line_h = float(statistics.median([x for x in hs if x >= 4] or [10])) + closed = close(self.ink, (1, max(3, int(0.45 * self.line_h)))) | self.ink + self.lab, n = ndimage.label(closed) + self.blobs = [[s[1].start, s[0].start, s[1].stop, s[0].stop] for s in ndimage.find_objects(self.lab)] + tall = sorted(b[3] - b[1] for b in self.blobs if b[3] - b[1] >= 4) + self.med_h = float(tall[len(tall) // 2] if tall else 10) + # long thin or large ink pieces (table rulings, frames, rules): what a table box snaps out to + raw = [[s[1].start, s[0].start, s[1].stop, s[0].stop] for s in ndimage.find_objects(lab) if s is not None] + big = 4 * self.line_h + self.structures = [b for b in raw if b[2] - b[0] > big or b[3] - b[1] > big] + self.blob_arr = np.array(self.blobs, dtype=np.float64).reshape(-1, 4) + self._fg_lab = None + + def fg_components(self): + """Labels and slices of the foreground closed by one body line: the graphics an image reference snaps to + (computed once per page; every image reference on it reads the same).""" + if self._fg_lab is None: + k = int(self.line_h) | 1 # a k x k closing + fg = close(self.fg, (k, k)) + lab, _ = ndimage.label(fg) + self._fg_lab = (lab, ndimage.find_objects(lab)) + return self._fg_lab + + def snap_word(self, m: np.ndarray, n_chars: int) -> list[float] | None: + """Box of one word from its attention map (gh x gw): see the module docstring. None when there is no ink + around the attention peak: the peak sits on blank paper (often an edge column of the image grid), which says + nothing about where the word is, and a cell box there would stretch the element's box to the margin.""" + gh, gw = m.shape + cw, ch = self.cell + py, px = np.unravel_index(int(m.argmax()), m.shape) + y0, y1 = int(max(0, (py - 1) * ch)), int(min(self.h, (py + 2) * ch)) + x0, x1 = int(max(0, (px - 1) * cw)), int(min(self.w, (px + 2) * cw)) + ids = np.unique(self.lab[y0:y1, x0:x1]) + ids = ids[ids > 0] + n = max(n_chars, 1) + + def fit(b): + # expected width = characters x half the body glyph height; on a blob clearly taller than body text (a + # large heading) its own height, else the heading looks like several short words. Measuring every blob's + # own height instead cost 2.3 points of word IoU>=0.5 on the dev pages (ascenders, brackets). + bh = float(b[3] - b[1]) + ew = n * 0.5 * (bh if BIG_FONT * self.med_h < bh <= MAX_FONT * self.med_h else self.med_h) + return abs(np.log(max(b[2] - b[0], 1) / ew)) + + best, best_s = None, -1.0 + for i in ids: + b = self.blobs[i - 1] + ty0, ty1 = int(b[1] // ch), int(min(gh - 1, (b[3] - 1) // ch)) + tx0, tx1 = int(b[0] // cw), int(min(gw - 1, (b[2] - 1) // cw)) + s = float(m[ty0:ty1 + 1, tx0:tx1 + 1].sum()) * float(np.exp(-fit(b))) + if s > best_s: + best, best_s = b, s + if best is None: + return None + b = list(best) + A = self.blob_arr + while True: # grow along the line while the width gets closer to the expected width + h, nxt = b[3] - b[1], None + vo = np.minimum(b[3], A[:, 3]) - np.maximum(b[1], A[:, 1]) + gap = np.maximum(A[:, 0] - b[2], b[0] - A[:, 2]) + for k in np.nonzero((vo >= 0.5 * np.minimum(h, A[:, 3] - A[:, 1])) & (gap >= 0) & (gap <= 0.8 * h))[0]: + o = self.blobs[k] + nb = [min(b[0], o[0]), min(b[1], o[1]), max(b[2], o[2]), max(b[3], o[3])] + if fit(nb) < fit(b) - 1e-6 and (nxt is None or gap[k] < nxt[0]): + nxt = (gap[k], nb) + if nxt is None: + return [float(v) for v in b] + b = nxt[1] + + def graphic_around(self, box: list[float], max_frac: float = 0.6) -> list[float] | None: + """The union of `box` with the graphic it sits on (a chart ocria read as a table: the words are its values and + labels, the figure is larger), or None. The graphic is the closed-foreground component that overlaps the box + most; it must be larger than the box, under `max_frac` of the page, and filled like a figure (not text).""" + lab, sl = self.fg_components() + x0, y0, x1, y1 = (int(v) for v in box) + ids, counts = np.unique(lab[max(0, y0):y1, max(0, x0):x1], return_counts=True) + keep = ids > 0 + if not keep.any(): + return None + i = int(ids[keep][np.argmax(counts[keep])]) + s = sl[i - 1] + g = [s[1].start, s[0].start, s[1].stop, s[0].stop] + ga, ba = (g[2] - g[0]) * (g[3] - g[1]), max((x1 - x0) * (y1 - y0), 1) + if ga <= 1.2 * ba or ga > max_frac * self.w * self.h: + return None + if float(self.fg[s].mean()) < float(FLAGS.get("chart_fill", "0.15")) or float(self.ink[s].mean()) > 0.5: + return None + return [float(min(box[0], g[0])), float(min(box[1], g[1])), float(max(box[2], g[2])), float(max(box[3], g[3]))] + + def image_hot_box(self, m: np.ndarray) -> list[float]: + """The attention hot area of an image reference (cells >= 30% of its peak), without snapping to graphics.""" + cw, ch = self.cell + ys, xs = np.nonzero(m >= 0.3 * float(m.max())) + return [float(xs.min() * cw), float(ys.min() * ch), float((xs.max() + 1) * cw), float((ys.max() + 1) * ch)] + + def image_box(self, m: np.ndarray) -> list[float]: + """Box of an image reference: the graphic (foreground component) under its strongest attention.""" + cw, ch = self.cell + hot = m >= 0.3 * float(m.max()) + ys, xs = np.nonzero(hot) + tok = [xs.min() * cw, ys.min() * ch, (xs.max() + 1) * cw, (ys.max() + 1) * ch] + lab, sl = self.fg_components() + if "exact_image_grid" in FLAGS: + # Map pixels back to their cells; rounding cell widths before repeating + # accumulates drift toward the bottom/right of non-divisible images. + iy = np.arange(self.h) * self.gh // self.h + ix = np.arange(self.w) * self.gw // self.w + up = hot[iy[:, None], ix[None, :]] + else: + up = np.kron(hot, np.ones((int(np.ceil(ch)), int(np.ceil(cw))), dtype=bool))[:self.h, :self.w] + ids = np.unique(lab[:up.shape[0], :up.shape[1]][up]) + ids = ids[ids > 0] + if not len(ids): + return [float(v) for v in tok] + boxes = [[sl[i - 1][1].start, sl[i - 1][0].start, sl[i - 1][1].stop, sl[i - 1][0].stop] for i in ids] + # the component that holds most of the attention, plus any other big one inside the hot area + mass = [float(m[int(b[1] // ch):int(np.ceil(b[3] / ch)), int(b[0] // cw):int(np.ceil(b[2] / cw))].sum()) for b in boxes] + b = boxes[int(np.argmax(mass))] + if (b[2] - b[0]) * (b[3] - b[1]) > 0.9 * self.w * self.h: # the closing merged the whole page + return [float(v) for v in tok] + return [float(v) for v in b] + + +def snap_table(page: Page, env: list[float]) -> list[float]: + """A table box reaches its ruling: the envelope of its words grows to the ruling pieces that touch it and either + stay within a few lines of it, or are the table's own grid (covers most of the envelope, at most twice its area). + A page-wide rule above a heading or a form's page frame is neither.""" + m = 3 * page.line_h + lim = [env[0] - m, env[1] - m, env[2] + m, env[3] + m] + area = max((env[2] - env[0]) * (env[3] - env[1]), 1.0) + box = list(env) + for s in page.structures: + touches = s[0] < env[2] and s[2] > env[0] and s[1] < env[3] and s[3] > env[1] + inside = s[0] >= lim[0] and s[1] >= lim[1] and s[2] <= lim[2] and s[3] <= lim[3] + inter = max(0, min(s[2], env[2]) - max(s[0], env[0])) * max(0, min(s[3], env[3]) - max(s[1], env[1])) + grid = inter >= 0.6 * area and (s[2] - s[0]) * (s[3] - s[1]) <= 2.0 * area + if touches and (inside or grid): + box = [min(box[0], s[0]), min(box[1], s[1]), max(box[2], s[2]), max(box[3], s[3])] + return [float(v) for v in box] + + +def _overlap(a0: float, a1: float, b0: float, b1: float) -> float: + return max(0.0, min(a1, b1) - max(a0, b0)) + + +def absorb_uncovered_ink(page: Page, boxes: list, can_grow: list[bool], passes: int = 0, + line_only: list[bool] | None = None) -> list: + """Every word blob on the page that no element box covers joins the nearest element on its line (the label of a + form row whose value sits far to the right, a time printed left of an entry, a closing "2)") or on the line just + above or below it (the rest of a heading or paragraph), provided no other element's box lies between them. The + attention places most words of an element, but the words it misses or that the cluster drops as strays are still + the element's ink, and a box that leaves them out cuts the element's content. + + Only text-sized blobs count (rulings, frames and graphics are not words). `can_grow[i]` False keeps box i as it + is (pictures: their box is the graphic). Returns new boxes; None stays None.""" + passes = passes or int(FLAGS.get("absorb_passes", "3")) + out = [None if b is None else list(map(float, b)) for b in boxes] + lo, hi = 0.4 * page.med_h, MAX_FONT * page.med_h + words = [b for b in page.blobs if lo <= b[3] - b[1] <= hi and b[2] - b[0] <= 0.6 * page.w] + + def covered(b) -> bool: + area = max((b[2] - b[0]) * (b[3] - b[1]), 1) + return any(e is not None and _overlap(b[0], b[2], e[0], e[2]) * _overlap(b[1], b[3], e[1], e[3]) >= 0.5 * area + for e in ref) + + def blocked(i: int, region: list[float]) -> bool: + return any(j != i and e is not None and _overlap(region[0], region[2], e[0], e[2]) > 0 + and _overlap(region[1], region[3], e[1], e[3]) > 0 for j, e in enumerate(ref)) + + # absorb_frozen: every blob is matched against the attention boxes as they came in and all growth is applied at + # once, so a box that took one line cannot reach the next one through it (a cascade down a column, across a page) + frozen = "absorb_frozen" in FLAGS + ref = [None if b is None else list(b) for b in out] if frozen else out + if frozen: + passes = 1 + for _ in range(passes): + changed = False + for b in words: + if covered(b): + continue + h = b[3] - b[1] + best, best_gap = None, None + for i, e in enumerate(ref): + if e is None or not can_grow[i]: + continue + if _overlap(b[1], b[3], e[1], e[3]) >= 0.5 * h: # same line: gap along x + gap = max(e[0] - b[2], b[0] - e[2], 0.0) + if "absorb_gap" in FLAGS and gap > float(FLAGS["absorb_gap"]) * page.med_h: + continue + region = [min(b[2], e[2]), b[1], max(b[0], e[0]), b[3]] + elif line_only and line_only[i]: # a heading or furniture band does not take the lines around it + continue + elif _overlap(b[0], b[2], e[0], e[2]) >= 0.5 * (b[2] - b[0]): # line above or below: gap along y + gap = max(e[1] - b[3], b[1] - e[3], 0.0) + if gap > float(FLAGS.get("absorb_vgap", "1.0")) * page.med_h: + continue + region = [max(b[0], e[0]), min(b[3], e[3]), min(b[2], e[2]), max(b[1], e[1])] + else: + continue + if region[2] > region[0] and region[3] > region[1] and blocked(i, region): + continue + if best_gap is None or gap < best_gap: + best, best_gap = i, gap + if best is not None: + e = out[best] + out[best] = [min(e[0], b[0]), min(e[1], b[1]), max(e[2], b[2]), max(e[3], b[3])] + changed = True + if not changed: + break + return out + + +def envelope(boxes: list[list[float]]) -> list[float]: + return [min(b[0] for b in boxes), min(b[1] for b in boxes), max(b[2] for b in boxes), max(b[3] for b in boxes)] + + +def main_cluster(boxes: list[list[float]], line_h: float, wide: bool = False) -> list[list[float]]: + """The largest group of word boxes chained by proximity (vertical gap <= 1.5 lines; horizontal gap <= 4 lines, + or any for a table, whose columns sit far apart). Words outside it are attention strays.""" + n = len(boxes) + if n <= 2: + return boxes + dy_max, dx_max = 1.5 * line_h, (float("inf") if wide else 4.0 * line_h) + parent = list(range(n)) + + def find(i): + while parent[i] != i: + parent[i] = parent[parent[i]] + i = parent[i] + return i + + order = sorted(range(n), key=lambda i: boxes[i][1]) + for a_i, a in enumerate(order): + for b in order[a_i + 1:]: + if boxes[b][1] - boxes[a][3] > dy_max: + break + p, q = boxes[a], boxes[b] + dy = max(0.0, max(p[1], q[1]) - min(p[3], q[3])) + dx = max(0.0, max(p[0], q[0]) - min(p[2], q[2])) + if dy <= dy_max and dx <= dx_max: + parent[find(a)] = find(b) + groups: dict[int, list[int]] = {} + for i in range(n): + groups.setdefault(find(i), []).append(i) + best = max(groups.values(), key=len) + return [boxes[i] for i in best] + +def unclaimed_graphics(page: Page, boxes: list, min_side: float = 2.0, max_frac: float = 0.4) -> list[list[float]]: + """Graphics on the page that no element covers (icons, logos, photos the answer does not mention): foreground + components that are filled or coloured like a picture (not thin text strokes), between `min_side` body-glyph + heights square and `max_frac` of the page, and less than 30% covered by element boxes.""" + rgb_sat = None + fg = close(page.fg, (int(page.line_h) | 1, int(page.line_h) | 1)) + lab, _ = ndimage.label(fg) + out = [] + side = min_side * page.med_h + for sl in ndimage.find_objects(lab): + if sl is None: + continue + y0, y1, x0, x1 = sl[0].start, sl[0].stop, sl[1].start, sl[1].stop + w, h = x1 - x0, y1 - y0 + if w < side or h < side or w * h > max_frac * page.w * page.h or max(w / h, h / w) > 6: + continue + b = [float(x0), float(y0), float(x1), float(y1)] + area = w * h + cov = sum(_overlap(b[0], b[2], e[0], e[2]) * _overlap(b[1], b[3], e[1], e[3]) for e in boxes if e is not None) + if cov >= 0.3 * area: + continue + fill = float(page.fg[y0:y1, x0:x1].mean()) + if fill < float(FLAGS.get("pic_fill", "0.35")): # thin strokes: text or line art the answer left out + continue + out.append(b) + return out + + +def fill_tables(page: Page, boxes: list, is_table: list[bool], max_gap: float = 2.5) -> list: + """A table box grows up and down through the ink lines inside its horizontal range, line by line, while the gap to + the next line stays under `max_gap` body lines and the line touches no other element's box. ocria's attention + collapses a long table's later rows onto its first ones, so the words alone stop short of the table's end.""" + out = [None if b is None else list(map(float, b)) for b in boxes] + gap_px = max_gap * page.line_h + for i, b in enumerate(out): + if b is None or not is_table[i]: + continue + x0, x1 = int(max(0, b[0])), int(min(page.w, b[2])) + prof = page.ink[:, x0:x1].sum(1) > max(2, 0.002 * (x1 - x0)) + others = [o for j, o in enumerate(out) if j != i and o is not None and _overlap(o[0], o[2], b[0], b[2]) > 0] + + def hits(y0: float, y1: float) -> bool: + return any(_overlap(y0, y1, o[1], o[3]) > 0 for o in others) + for step in (1, -1): # down, then up + edge = int(b[3]) if step == 1 else int(b[1]) - 1 + while True: + y, gap = edge + step, 0 + while 0 <= y < page.h and not prof[y] and gap <= gap_px: + y += step + gap += 1 + if not (0 <= y < page.h) or gap > gap_px: + break + y_end = y + while 0 <= y_end + step < page.h and prof[y_end + step]: + y_end += step + lo, hi = sorted((y, y_end)) + if hits(lo, hi + 1) or hi - lo > 6 * page.line_h: # another element, or a graphic / frame + break + edge = y_end + if step == 1: + b[3] = float(hi + 1) + else: + b[1] = float(lo) + return out diff --git a/ocria_grounding/capture.py b/ocria_grounding/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..96ae4afc3513b0f5bb59fc440b00c9bd7e21e5c4 --- /dev/null +++ b/ocria_grounding/capture.py @@ -0,0 +1,103 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Teacher-forced attention of ocria over the page image, per text unit (GPU; torch + transformers imported lazily). + +The answer is appended as the assistant turn after the system prompt and the image-only user turn, and ONE forward +pass is run. A decoder's attention at a position depends only on the tokens before it, so this is the attention the +model had while writing that text (teacher forcing and the model's own decoding gave the same box quality). For each unit (a char span: a word, or a whole image reference) and each chosen (layer, head): +the mean softmax over image tokens of the queries that GENERATE the unit's tokens (query i-1 predicts token i), +divided by that head's total image mass for the unit; the unit's map is the sum over the chosen heads. + +Only Qwen3.5's full-attention layers have attention maps (the Gated DeltaNet layers have none); the probe runs inside +those layers' attention call and computes q.k only for the chosen heads. +""" +from __future__ import annotations + +import numpy as np + +CHUNK = 256 + + +class Grounder: + def __init__(self, model_dir: str, heads: list[tuple[int, int]], system_prompt: str, device: str = "cuda"): + import torch + from transformers import AttentionInterface, AutoProcessor, Qwen3_5ForConditionalGeneration + from transformers.integrations.sdpa_attention import sdpa_attention_forward + + self.torch, self.device, self.ctx = torch, device, {} + self.by_layer: dict[int, list[int]] = {} + for layer, head in heads: + self.by_layer.setdefault(int(layer), []).append(int(head)) + ctx = self.ctx + + def probe(module, query, key, value, attention_mask=None, scaling=None, **kwargs): + out, w = sdpa_attention_forward(module, query, key, value, attention_mask=attention_mask, scaling=scaling, **kwargs) + hs = self.by_layer.get(module.layer_idx) + if not hs or "W" not in ctx or query.shape[2] == 1: + return out, w + g = query.shape[1] // key.shape[1] + hsel = torch.tensor(hs, device=query.device) + k = key[0, hsel // g].float() # (h, T, d): each query head's own kv head (GQA) + T = k.shape[1] + img, q0, W = ctx["img"], ctx["q0"], ctx["W"] + acc = torch.zeros(W.shape[0], len(hs), int(img.sum()), device=query.device) + for c0 in range(q0, T, CHUNK): + q = query[0, hsel, c0:c0 + CHUNK].float() + pos = torch.arange(c0, c0 + q.shape[1], device=query.device) + s = torch.einsum("hqd,htd->hqt", q, k) * scaling + s = s.masked_fill(torch.arange(T, device=query.device)[None, None, :] > pos[None, :, None], float("-inf")) + p = s.softmax(-1)[..., img] + acc += torch.einsum("uc,hcn->uhn", W[:, c0 - q0:c0 - q0 + q.shape[1]], p) + acc = acc / acc.sum(-1, keepdim=True).clamp_min(1e-9) + ctx["maps"] += acc.sum(1) + return out, w + + AttentionInterface.register("ocria_ground_probe", probe) + self.model = Qwen3_5ForConditionalGeneration.from_pretrained( + model_dir, dtype=torch.bfloat16, attn_implementation="sdpa").to(device).eval() + self.model.config.text_config._attn_implementation = "ocria_ground_probe" + self.proc = AutoProcessor.from_pretrained(model_dir) + full = [i for i, t in enumerate(self.model.config.text_config.layer_types) if t == "full_attention"] + bad = sorted(set(self.by_layer) - set(full)) + if bad: + raise ValueError(f"heads on layers {bad}, which have no attention map (full-attention layers: {full})") + self.prompt = self.proc.apply_chat_template( + [{"role": "system", "content": [{"type": "text", "text": system_prompt}]}, + {"role": "user", "content": [{"type": "image"}]}], add_generation_prompt=True, enable_thinking=False) + + def unit_maps(self, image, answer: str, units: list[tuple[int, int]]) -> tuple[np.ndarray, tuple[int, int], np.ndarray]: + """(maps [U, gh, gw] float32, (gh, gw), has_tokens [U] bool) for char spans `units` of `answer`.""" + torch, dev = self.torch, self.device + enc = self.proc(text=[self.prompt], images=[image.convert("RGB")], return_tensors="pt") + tok = self.proc.tokenizer(answer, add_special_tokens=False, return_offsets_mapping=True) + ans = torch.tensor([tok["input_ids"]]) + offs = tok["offset_mapping"] + start = enc["input_ids"].shape[1] + enc["input_ids"] = torch.cat([enc["input_ids"], ans], 1) + enc["attention_mask"] = torch.cat([enc["attention_mask"], torch.ones_like(ans)], 1) + if "mm_token_type_ids" in enc: + enc["mm_token_type_ids"] = torch.cat([enc["mm_token_type_ids"], torch.zeros_like(ans)], 1) + enc = {k: v.to(dev) for k, v in enc.items()} + img = enc["input_ids"][0] == self.model.config.image_token_id + thw = enc["image_grid_thw"][0].tolist() + gh, gw = thw[1] // 2, thw[2] // 2 + assert int(img.sum()) == gh * gw, (int(img.sum()), gh, gw) + T, q0 = start + ans.shape[1], start - 1 + W = torch.zeros(len(units), T - q0, device=dev) + has = np.zeros(len(units), bool) + tok_starts = np.array([a for a, b in offs]) if offs else np.zeros(0) + tok_ends = np.array([b for a, b in offs]) if offs else np.zeros(0) + for u, (s, e) in enumerate(units): + t = np.nonzero((tok_starts < e) & (tok_ends > s) & (tok_ends > tok_starts))[0] + if len(t): + W[u, torch.as_tensor(start + t - 1 - q0, device=dev)] = 1.0 / len(t) + has[u] = True + self.ctx.update(W=W, img=img, q0=q0, maps=torch.zeros(len(units), gh * gw, device=dev)) + try: + with torch.no_grad(): + self.model(**enc, use_cache=False, logits_to_keep=1) + maps = self.ctx["maps"].reshape(len(units), gh, gw).float().cpu().numpy() + finally: + self.ctx.clear() + return maps, (gh, gw), has diff --git a/ocria_grounding/detector.py b/ocria_grounding/detector.py new file mode 100644 index 0000000000000000000000000000000000000000..ff53c7025bfe5c8d53bc8ba3fd4a2ba6e30a7bef --- /dev/null +++ b/ocria_grounding/detector.py @@ -0,0 +1,44 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Layout regions from Docling's Heron detector (docling-project/docling-layout-heron, RT-DETRv2, Apache-2.0). + +Heron is a third-party model: it is downloaded from its own repository and governed by its own license (Apache-2.0), +not by this repository's license. + + det = Detector() # cuda, else mps, else cpu + regions = det(image) # [{label, score, box: [x0, y0, x1, y1]}] in pixels of `image` +""" +from __future__ import annotations + +DETECTOR = "docling-project/docling-layout-heron" + + +class Detector: + def __init__(self, model: str = DETECTOR, device: str | None = None, max_side: int = 1600): + import torch + from transformers import AutoImageProcessor, AutoModelForObjectDetection + + if device is None: + device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu" + self.torch, self.device, self.max_side = torch, device, max_side + self.proc = AutoImageProcessor.from_pretrained(model) + self.model = AutoModelForObjectDetection.from_pretrained(model).to(device).eval() + + def __call__(self, image, threshold: float = 0.2) -> list[dict]: + """Detections in pixels of `image`. The page is downscaled to <= max_side px first (Heron reads 640 x 640).""" + from PIL import Image + + im = image.convert("RGB") + w, h = im.size + s = min(1.0, self.max_side / max(w, h)) + if s < 1: + im = im.resize((max(1, int(w * s)), max(1, int(h * s))), Image.LANCZOS) + sx, sy = w / im.width, h / im.height + with self.torch.no_grad(): + out = self.model(**self.proc(images=[im], return_tensors="pt").to(self.device)) + r = self.proc.post_process_object_detection(out, target_sizes=[(im.height, im.width)], threshold=threshold)[0] + return [{"label": self.model.config.id2label[int(lab)], "score": round(float(sc), 3), + "box": [round(float(b[0]) * sx, 1), round(float(b[1]) * sy, 1), + round(float(b[2]) * sx, 1), round(float(b[3]) * sy, 1)]} + for sc, lab, b in zip(r["scores"], r["labels"], r["boxes"])] diff --git a/ocria_grounding/geometry.py b/ocria_grounding/geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..4baabdac82ee181b820da5fa2ccf0257503adc1d --- /dev/null +++ b/ocria_grounding/geometry.py @@ -0,0 +1,90 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Conservative reading-order paths for horizontal left-to-right prose. + +Coordinates are image pixels. Word indices remain in transcript order, so a +skipped attention outlier does not delete text. Unsupported layouts fall back +to the existing spatial clustering; tables, formulas and code bypass this pass. +""" + +import statistics + +WordBox = list[float] + + +def paragraph_paths(boxes: list[WordBox]) -> list[list[int]] | None: + """Return supported word paths, splitting column continuations when justified. + + Nearby words form spatial components. Within each component a longest path + must move right on a line or wrap onto a nearby lower line. At least 60% of + words must support the result. Separate columns need three words each and + non-interleaving transcript spans; otherwise keep only a dominant path. + """ + n = len(boxes) + if n < 3: + return None + height = max(1.0, statistics.median(b[3] - b[1] for b in boxes)) + parents = list(range(n)) + + def root(i: int) -> int: + while parents[i] != i: + parents[i] = parents[parents[i]] + i = parents[i] + return i + + # Proximity establishes candidate columns independently of transcript order. + # A nearby wrong word can still belong here; the ordered path rejects it. + for i, a in enumerate(boxes): + for j in range(i): + b = boxes[j] + dx = max(a[0] - b[2], b[0] - a[2], 0.0) + dy = max(a[1] - b[3], b[1] - a[3], 0.0) + if dx <= 4 * height and dy <= 2.5 * height: + parents[root(i)] = root(j) + components: dict[int, list[int]] = {} + for i in range(n): + components.setdefault(root(i), []).append(i) + + paths: list[list[int]] = [] + for indices in components.values(): + lengths = {i: 1 for i in indices} + previous: dict[int, int] = {} + for pos, i in enumerate(indices): + b = boxes[i] + for j in indices[:pos]: + a = boxes[j] + overlap = min(a[3], b[3]) - max(a[1], b[1]) + same_line = overlap >= 0.5 * min(a[3] - a[1], b[3] - b[1]) + if same_line: + follows = b[0] >= a[0] + 0.2 * height and -0.5 * height <= b[0] - a[2] <= 4 * height + else: + follows = ( + b[1] >= a[1] + 0.5 * height + and b[1] - a[3] <= 2.5 * height + and b[0] < a[2] + ) + if follows and lengths[j] + 1 > lengths[i]: + lengths[i] = lengths[j] + 1 + previous[i] = j + end = max(indices, key=lengths.__getitem__) + path = [end] + while path[-1] in previous: + path.append(previous[path[-1]]) + path.reverse() + if len(path) >= 3: + paths.append(path) + if not paths: + return None + paths.sort(key=lambda p: p[0]) + if sum(map(len, paths)) < 0.6 * n: + return None + + # A column jump is supported by whole runs, not a single distant word. + # Interleaved components or a jump down to unrelated text are ambiguous. + for left, right in zip(paths, paths[1:]): + gutter = min(boxes[i][0] for i in right) - max(boxes[i][2] for i in left) + if left[-1] >= right[0] or gutter < height or boxes[right[0]][1] > boxes[left[-1]][1]: + dominant = max(paths, key=len) + return [dominant] if len(dominant) >= 0.6 * n else None + return paths diff --git a/ocria_grounding/ground.py b/ocria_grounding/ground.py new file mode 100644 index 0000000000000000000000000000000000000000..4c0d0a0bfe2858007997bc7c7690189e4e76f5e9 --- /dev/null +++ b/ocria_grounding/ground.py @@ -0,0 +1,415 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""One page: raw ocria answer + page image -> layout elements with boxes, in the two forms the benches read. + + elements = ground_page(grounder, image, answer) # GPU pass + CPU snapping + md = to_box_markdown(answer, elements, w, h) # box-mode markers (0-1000 grid) + page = to_layout_page(answer, elements, w, h, scale) # a ParseBench layout page + +Pure functions below `ground_page` need no GPU and are what the tests exercise. +""" +from __future__ import annotations + +import re + +import numpy as np + +from .blocks import Block, body_span, resolve_page_numbers, split_blocks +from .boxes import Page, absorb_uncovered_ink, envelope, fill_tables, main_cluster, snap_table, unclaimed_graphics +from .geometry import paragraph_paths +from .tune import FLAGS +from .words import norm, word_spans + +_PAGE_NO = re.compile(r"(?:^|\s)(?:page\s*)?\d{1,4}(?:\s*(?:of|/)\s*\d{1,4})?\s*$", re.I) +_FURN_TAG = re.compile(r"") + + +def units_for(answer: str, blocks: list[Block]) -> tuple[list[tuple[int, int]], list[list[int]]]: + """Attention units and, per block, the indices of its units: every content word inside the block; an image + block is one unit (its whole reference), because the picture it points at has no words to snap to.""" + spans = word_spans(answer) + units: list[tuple[int, int]] = [] + per_block: list[list[int]] = [] + k = 0 + for b in blocks: + mine: list[int] = [] + if b.type == "image": + mine.append(len(units)) + units.append((b.start, b.end)) + per_block.append(mine) + continue + while k < len(spans) and spans[k][0] < b.start: + k += 1 + j = k + while j < len(spans) and spans[j][1] <= b.end: + mine.append(len(units)) + units.append((spans[j][0], spans[j][1])) + j += 1 + per_block.append(mine) + return units, per_block + + +def element_boxes(page: Page, answer: str, blocks: list[Block], units, per_block, maps, has) -> list: + """Pixel box [x0, y0, x1, y1] per block (None when none of its units reached a token).""" + return [bx for _, bx in element_pieces(page, answer, blocks, units, per_block, maps, has, split=False)] + + +def element_pieces(page: Page, answer: str, blocks: list[Block], units, per_block, maps, has, + split: bool = True, words_out: dict | None = None, + geometry_spans: set[tuple[int, int]] | None = None) -> list[tuple[Block, list | None]]: + """(block, box) per element. With `split` (tuning flag split_gaps), a text element whose words fall into + clusters separated by whitespace gaps becomes one element per cluster when the clusters follow each other in + the text (vertical gap > 1.4, horizontal > 2.0 line heights).""" + out = [] + W, H = page.w, page.h + snaps = {} # unit -> word box, for every text unit on the page (image units excluded) + for b, idx in zip(blocks, per_block): + if b.type != "image": + for u in idx: + if has[u]: + snaps[u] = page.snap_word(maps[u], len(norm(answer[units[u][0]:units[u][1]]))) + if "drop_big_words" in FLAGS: # not inside tables: a table word on its ruling gives the table its extent + table_units = {u for b, idx in zip(blocks, per_block) if b.type == "table" for u in idx} + dropped = _drop_oversized(snaps) + snaps = {u: (w if u in table_units else dropped[u]) for u, w in snaps.items()} + for b, idx in zip(blocks, per_block): + idx = [u for u in idx if has[u]] + if not idx: + out.append((b, None)) + continue + if b.type == "image": + bx = page.image_box(maps[idx[0]]) + if "pic_cap" in FLAGS and (bx[2] - bx[0]) * (bx[3] - bx[1]) > float(FLAGS["pic_cap"]) * W * H: + bx = page.image_hot_box(maps[idx[0]]) + if (bx[2] - bx[0]) * (bx[3] - bx[1]) > float(FLAGS["pic_cap"]) * W * H: + bx = None + out.append((b, bx)) + continue + snapped = [(u, snaps.get(u)) for u in idx] + snapped = [(u, w) for u, w in snapped if w is not None] + if not snapped: + out.append((b, None)) + continue + words = [w for _, w in snapped] + if "paragraph_geometry" in FLAGS and b.type in ("text", "list"): + paths = paragraph_paths(words) + if paths and (split or len(paths) == 1): + for k, path in enumerate(paths): + start = b.start if k == 0 else units[snapped[path[0]][0]][0] + end = b.end if k + 1 == len(paths) else units[snapped[paths[k + 1][0]][0]][0] + piece = Block(b.type, start, end) + core = [words[i] for i in path] + if words_out is not None: + words_out[id(piece)] = core + if geometry_spans is not None: + geometry_spans.add((start, end)) + out.append((piece, envelope(core))) + continue + if "seq_filter" in FLAGS and b.type != "table" and len(words) >= 3: + words = _reading_order_core(words, page.med_h) or words + core = main_cluster(words, page.line_h, wide=b.type == "table") + if words_out is not None: + words_out[id(b)] = core + env = envelope(core) + if b.type == "table": + bx = snap_table(page, env) + if "chart_tables" in FLAGS and bx == [float(v) for v in env]: + bx = page.graphic_around(bx) or bx + out.append((b, bx)) + continue + pieces = _split_at_gaps(page, b, snapped, units, env) if split and "split_gaps" in FLAGS else None + if pieces: + out.extend(pieces) + else: + out.append((b, env)) + return out + + +def _follows(a, b, h: float) -> bool: + """Word box b can be the word written after a: further right on the same line, or the start of a line below.""" + ha, hb = a[3] - a[1], b[3] - b[1] + same_line = min(a[3], b[3]) - max(a[1], b[1]) >= 0.5 * min(ha, hb) + if same_line: + return -0.5 * h <= b[0] - a[2] <= float(FLAGS.get("seq_dx", "4")) * h + return b[1] > a[1] + 0.3 * h and b[1] - a[3] <= float(FLAGS.get("seq_dy", "2.5")) * h and b[0] < a[2] + + +def _reading_order_core(words: list, h: float) -> list | None: + """The words that sit where the text order says they should: runs of consecutive words in which each follows the + previous one on the page (`_follows`, one missing word allowed), keeping runs of >= 2 words; None when no run.""" + n = len(words) + parent = list(range(n)) + + def find(i): + while parent[i] != i: + parent[i] = parent[parent[i]] + i = parent[i] + return i + for i in range(n - 1): + if _follows(words[i], words[i + 1], h): + parent[find(i + 1)] = find(i) + elif i + 2 < n and _follows(words[i], words[i + 2], h): + parent[find(i + 2)] = find(i) + groups: dict[int, list[int]] = {} + for i in range(n): + groups.setdefault(find(i), []).append(i) + keep = sorted(i for g in groups.values() if len(g) >= 2 for i in g) + return [words[i] for i in keep] if keep else None + + +def _iou(a, b) -> float: + i = max(0.0, min(a[2], b[2]) - max(a[0], b[0])) * max(0.0, min(a[3], b[3]) - max(a[1], b[1])) + u = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - i + return i / u if u > 0 else 0.0 + + +def _drop_duplicate_boxes(answer: str, blocks, boxes) -> list: + """Of two elements whose boxes overlap at IoU >= 0.5, the + one with fewer letters loses its box (two elements placed on the same block: one of them is misplaced, and the + longer text is more likely to own the block).""" + letters = [sum(c.isalnum() for c in answer[b.start:b.end]) for b in blocks] + out = list(boxes) + for i in range(len(out)): + for j in range(i + 1, len(out)): + if out[i] is None or out[j] is None or _iou(out[i], out[j]) < 0.5: + continue + if letters[i] >= letters[j]: + out[j] = None + else: + out[i] = None + return out + + +def _drop_nested_text_boxes(blocks, boxes) -> list: + """A text box >= 90% inside another element's text + box at least 1.5x its area is a misplaced fragment of that block.""" + text = [b.type not in ("image", "table") for b in blocks] + area = [0.0 if bx is None else (bx[2] - bx[0]) * (bx[3] - bx[1]) for bx in boxes] + out = list(boxes) + for i, r in enumerate(boxes): + if r is None or not text[i] or area[i] <= 0: + continue + for j, host in enumerate(boxes): + if j == i or host is None or not text[j] or area[j] <= 1.5 * area[i]: + continue + inter = max(0.0, min(r[2], host[2]) - max(r[0], host[0])) * max(0.0, min(r[3], host[3]) - max(r[1], host[1])) + if inter / area[i] >= 0.9: + out[i] = None + break + return out + + +def _drop_oversized(snaps: dict) -> dict: + """A word whose box is taller than 4x the page's + median word height or larger than 50x its median word area snapped to a frame, a rule or a graphic, not to a word, + and one such box stretches its element across the page. Such words get no box (pages with >= 10 words).""" + boxes = [w for w in snaps.values() if w is not None] + if len(boxes) < 10: + return snaps + hs = sorted(w[3] - w[1] for w in boxes) + areas = sorted((w[2] - w[0]) * (w[3] - w[1]) for w in boxes) + mh, ma = hs[len(hs) // 2], areas[len(areas) // 2] + return {u: (None if w is None or w[3] - w[1] > 4 * mh or (w[2] - w[0]) * (w[3] - w[1]) > 50 * ma else w) + for u, w in snaps.items()} + + +def _split_at_gaps(page: Page, b: Block, snapped, units, env): + """Pieces of one element split at whitespace gaps, or None. Only for big elements (>= 4% of the page, >= 6 + words), and only when each cluster is one run of consecutive words (else the text cannot be cut).""" + W, H = page.w, page.h + if len(snapped) < int(FLAGS.get("sg_min_words", "6")) or \ + (env[2] - env[0]) * (env[3] - env[1]) < float(FLAGS.get("sg_min_area", "0.04")) * W * H: + return None + vg, hg = float(FLAGS.get("sg_v", "1.4")) * page.line_h, float(FLAGS.get("sg_h", "2.0")) * page.line_h + n = len(snapped) + parent = list(range(n)) + + def find(i): + while parent[i] != i: + parent[i] = parent[parent[i]] + i = parent[i] + return i + for i in range(n): + p = snapped[i][1] + for j in range(i + 1, n): + q = snapped[j][1] + dy = max(0.0, max(p[1], q[1]) - min(p[3], q[3])) + dx = max(0.0, max(p[0], q[0]) - min(p[2], q[2])) + if dy <= vg and dx <= hg: + parent[find(i)] = find(j) + lab = [find(i) for i in range(n)] + runs = [] # consecutive words with the same cluster + for i, l in enumerate(lab): + if runs and runs[-1][0] == l: + runs[-1][1].append(i) + else: + runs.append((l, [i])) + # a single stray word between two runs of one cluster joins its neighbours + merged = [] + for l, ws in runs: + if merged and (merged[-1][0] == l or len(ws) == 1): + merged[-1][1].extend(ws) + else: + merged.append((l, ws)) + if len(merged) < 2 or len({l for l, _ in merged}) != len(merged): + return None + pieces = [] + for k, (_, ws) in enumerate(merged): + start = b.start if k == 0 else units[snapped[ws[0]][0]][0] + end = b.end if k == len(merged) - 1 else units[snapped[merged[k + 1][1][0]][0]][0] + pieces.append((Block(b.type, start, end), envelope([snapped[i][1] for i in ws]))) + return pieces + + +def ground_page(grounder, image, answer: str, keep_maps: bool = False) -> dict: + """{width, height, elements: [{type, start, end, box}]} for one page (box in pixels of `image`, or None). + `keep_maps` also returns the sparse attention maps (`sparse_maps`) so the CPU step can be re-run offline.""" + blocks = split_blocks(answer) + units, per_block = units_for(answer, blocks) + w, h = image.size + if not units: + return {"width": w, "height": h, "elements": []} + maps, grid, has = grounder.unit_maps(image, answer, units) + out = boxes_from_maps(image, answer, blocks, units, per_block, maps, grid, has) + if keep_maps: + out["sparse_maps"] = sparsify(maps, has, [b.type == "image" for b in blocks], per_block) + return out + + +def boxes_from_maps(image, answer: str, blocks, units, per_block, maps, grid, has, regions: list | None = None, + page: Page | None = None) -> dict: + """The CPU half of `ground_page`: attention maps -> element boxes. With `regions` (layout-detector detections, + [{label, score, box}] in image pixels) elements are placed on the regions (regions.place_on_regions).""" + w, h = image.size + page = page or Page(np.asarray(image.convert("RGB")), grid) + words_of: dict = {} + geometry_spans: set[tuple[int, int]] = set() + pieces = element_pieces(page, answer, blocks, units, per_block, maps, has, words_out=words_of, + geometry_spans=geometry_spans) + piece_words = [words_of.get(id(pb), []) for pb, _ in pieces] + blocks = [Block(pb.type, pb.start, pb.end) for pb, _ in pieces] + boxes = [bx for _, bx in pieces] + if regions is None and "ink_regions" in FLAGS: + from .regions import ink_regions + regions = ink_regions(page, float(FLAGS.get("ink_kv", "1.0")), float(FLAGS.get("ink_kh", "1.5"))) + if regions is not None: + from .regions import clean_regions, place_on_regions + boxes, extra_pics = place_on_regions([b.type for b in blocks], piece_words, boxes, + clean_regions(regions, float(FLAGS.get("region_score", "0.35"))), + page.line_h, add_unclaimed_pictures="no_region_pics" not in FLAGS, + text_too=FLAGS.get("region_kinds", "all") != "visual") + if "region_absorb" not in FLAGS and FLAGS.get("region_kinds", "all") != "visual": # regions cover blocks + FLAGS_NO_ABSORB = True + else: + FLAGS_NO_ABSORB = False + else: + extra_pics, FLAGS_NO_ABSORB = [], False + if "no_absorb" not in FLAGS and not FLAGS_NO_ABSORB: + # Unconstrained ink absorption can reattach a rejected outlier or bridge + # the gutter. Keep accepted geometry paths at their supported extent. + boxes = absorb_uncovered_ink(page, boxes, + [b.type != "image" and (b.start, b.end) not in geometry_spans for b in blocks], + line_only=[b.type in ("heading", "header", "footer", "page_number") for b in blocks] + if "absorb_head_line" in FLAGS else None) + if "table_fill" in FLAGS: + boxes = fill_tables(page, boxes, [b.type == "table" for b in blocks], float(FLAGS.get("table_gap", "2.5"))) + if "pad" in FLAGS: # ink-tight boxes vs annotated boxes with a margin: grow text-like boxes by pad x body glyph height + m = float(FLAGS["pad"]) * page.med_h + boxes = [bx if bx is None or b.type == "image" else + [max(0.0, bx[0] - m), max(0.0, bx[1] - m), min(float(w), bx[2] + m), min(float(h), bx[3] + m)] + for b, bx in zip(blocks, boxes)] + if "dedupe" in FLAGS: + boxes = _drop_duplicate_boxes(answer, blocks, boxes) + if "drop_nested" in FLAGS: + boxes = _drop_nested_text_boxes(blocks, boxes) + resolve_page_numbers(blocks, boxes, h) + if "furniture_bands" in FLAGS: # detector-free furniture labels by position + for b, bx in zip(blocks, boxes): + if bx is None or b.type not in ("text", "heading"): + continue + if bx[3] <= 0.09 * h: + b.type = "header" + elif bx[1] >= 0.93 * h or (bx[1] >= 0.88 * h and _PAGE_NO.search(answer[b.start:b.end])): + b.type = "footer" + elements = [{"type": b.type, "start": b.start, "end": b.end, + "box": None if bx is None else [round(float(v), 1) for v in bx]} for b, bx in zip(blocks, boxes)] + if extra_pics: # detector pictures the answer does not mention + end = body_span(answer)[1] + elements += [{"type": "image", "start": end, "end": end, "box": [round(float(v), 1) for v in bx]} + for bx in extra_pics] + elif "add_pictures" in FLAGS: # graphics the answer does not mention: picture boxes with no text, at the end + end = body_span(answer)[1] + elements += [{"type": "image", "start": end, "end": end, "box": [round(v, 1) for v in bx]} + for bx in unclaimed_graphics(page, boxes)] + return {"width": w, "height": h, "grid": list(grid), "elements": elements} + + +def sparsify(maps, has, is_image_block, per_block, k_word: int = 64, k_image: int = 512) -> dict: + """Top-k cells per unit (indices into the flattened grid, fp16 values): enough to re-run snapping offline at a + fraction of the size of the dense maps. Image units keep more cells (their hot area is large).""" + img_units = {u for blk, idx in zip(is_image_block, per_block) if blk for u in idx} + flat = maps.reshape(maps.shape[0], -1) + idx, val = [], [] + for u in range(flat.shape[0]): + k = min(flat.shape[1], k_image if u in img_units else k_word) + top = np.argpartition(-flat[u], k - 1)[:k] if has[u] else np.zeros(0, dtype=np.int64) + idx.append(top.astype(np.int32).tolist()) + val.append(np.round(flat[u][top].astype(np.float32), 6).tolist()) + return {"idx": idx, "val": val, "has": [bool(x) for x in has]} + + +def dense_maps(sparse: dict, grid) -> tuple[np.ndarray, np.ndarray]: + """Inverse of `sparsify` (cells outside the kept top-k are 0).""" + gh, gw = grid + maps = np.zeros((len(sparse["idx"]), gh * gw), np.float32) + for u, (i, v) in enumerate(zip(sparse["idx"], sparse["val"])): + if i: + maps[u, i] = v + return maps.reshape(-1, gh, gw), np.array(sparse["has"], bool) + + +def to_box_markdown(answer: str, elements: list[dict], width: float, height: float) -> str: + """The answer with a box-mode marker `` (0-1000 grid) opening each boxed element, + i.e. what a box-mode model would have written; `layout_score.box_markers_to_attribution` reads it unchanged.""" + out, pos = [], 0 + for el in sorted(elements, key=lambda e: e["start"]): + if el["box"] is None: + continue + x0, y0, x1, y1 = el["box"] + g = [int(round(1000 * x0 / width)), int(round(1000 * y0 / height)), + int(round(1000 * x1 / width)), int(round(1000 * y1 / height))] + g = [max(0, min(1000, v)) for v in g] + if g[2] <= g[0] or g[3] <= g[1]: + continue + out.append(answer[pos:el["start"]]) + out.append(f"\n") + pos = el["start"] + out.append(answer[pos:]) + return "".join(out) + + +# (item type, segment label). The v2 detection metrics resolve a box's class from Canonical17 names only, so a raw +# "heading"/"header"/"footer"/"image" type is dropped from localization/classification; segment labels keep the +# raw LlamaParse layout names ("heading" itself is excluded by ParseBench's label mapper). +_V2_TYPE = {"text": ("Text", "text"), "heading": ("Section-header", "paragraph_title"), "table": ("Table", "table"), + "image": ("Picture", "image"), "header": ("Page-header", "header"), "footer": ("Page-footer", "footer")} + + +def to_layout_page(answer: str, elements: list[dict], width: float, height: float, scale: float = 1.0, + page_md: str = "") -> dict: + """A ParseBench `layout_pages` entry. Boxes are x, y, w, h in the page's own units (pixels x + `scale`; use 72 / DPI for PDF points), each item with one `layout_segments` entry equal to its box, because + the v2 layout scorer ignores items without layout-aware segments.""" + items = [] + for el in elements: + if el["box"] is None: + continue + x0, y0, x1, y1 = (v * scale for v in el["box"]) + if x1 <= x0 or y1 <= y0: + continue + md = _FURN_TAG.sub("", answer[el["start"]:el["end"]]).strip() + typ, label = _V2_TYPE.get(el["type"], _V2_TYPE["text"]) + seg = {"x": x0, "y": y0, "w": x1 - x0, "h": y1 - y0, "label": label} + items.append({"type": typ, "md": md, "value": md, "bbox": dict(seg), "layout_segments": [seg]}) + return {"page_number": 1, "width": width * scale, "height": height * scale, "md": page_md, "items": items} diff --git a/ocria_grounding/heads.json b/ocria_grounding/heads.json new file mode 100644 index 0000000000000000000000000000000000000000..639ffe0cd2a6645cffad9f711afbecf56e0d7186 --- /dev/null +++ b/ocria_grounding/heads.json @@ -0,0 +1,10 @@ +{ + "llamaindex/OCRia-1": { + "heads": [[27, 13], [19, 12], [23, 14], [15, 13], [23, 0], [19, 13], [27, 1], [27, 2]], + "chosen_on": "6 pages with exact PDF word boxes (none from any public benchmark)", + "word_iou50_held_out": { + "pages": 24, + "percent": 81.8 + } + } +} diff --git a/ocria_grounding/heads.py b/ocria_grounding/heads.py new file mode 100644 index 0000000000000000000000000000000000000000..c7a6919d1416ced099f4b4e2eed39653b1db4137 --- /dev/null +++ b/ocria_grounding/heads.py @@ -0,0 +1,16 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Attention heads (layer, head) used for grounding, per model. Chosen on pages with exact PDF word boxes (none from +any public benchmark): the heads whose top image token most often falls inside the word being written.""" +import json +from pathlib import Path + +_FILE = Path(__file__).with_name("heads.json") + + +def heads_for(model: str) -> list[tuple[int, int]]: + table = json.loads(_FILE.read_text()) + if model not in table: + raise KeyError(f"no grounding heads recorded for {model}; known: {sorted(table)}") + return [tuple(h) for h in table[model]["heads"]] diff --git a/ocria_grounding/layout.py b/ocria_grounding/layout.py new file mode 100644 index 0000000000000000000000000000000000000000..e6434b6de17840977ee66e42e4600e4e59da5ddf --- /dev/null +++ b/ocria_grounding/layout.py @@ -0,0 +1,258 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Region-first layout: a layout detector's regions are the items, and OCRia-1's answer is distributed into them. + +Per page: +1. Every word of the answer gets a position: its PDF word box when the page has a text layer (align.py), else the + ink blob its attention points at (boxes.Page.snap_word). +2. A word goes to the smallest non-picture region holding its centre; a word with no position, or outside every region, + takes the region of the word before it in the same block (else the next one). Each region's text is its words in + answer order, one block's words kept together. +3. An image reference goes to the Picture or Table region under its attention box. A table goes to the Table region + holding most of its words (else the Picture region); with neither, the table gets its own box around its words. +4. Regions that get no text are dropped, except pictures. Pictures scoring under 0.6 are dropped first, and of a + Picture and a Table region with IoU >= 0.5 only the higher-scoring one is kept. +5. Elements none of whose words reach a region keep their attention box. Finally, of two items whose boxes overlap at + IoU >= 0.5, the one with less text is dropped, and image references are removed from text items. + +Boxes are pixels of the page image, like the detector's regions and the word boxes. +""" +from __future__ import annotations + +import re + +import numpy as np + +from .align import unit_boxes_multi +from .blocks import split_blocks +from .boxes import Page +from .ground import _FURN_TAG, boxes_from_maps, units_for +from .regions import PICTURE, TABLE, clean_regions +from .words import norm + +MIN_SCORE = 0.35 # detections below this are ignored +PICTURE_MIN_SCORE = 0.6 # pictures need more (most low-score pictures duplicate a table, a chart or an icon) +PAIR_IOU = 0.5 # a Picture and a Table region this close are one region +TABLE_SHARE = 0.3 # a table goes to the Table/Picture region holding at least this share of its words + +# detector label -> (item type, segment label), Docling label names +TYPE = {"text": "Text", "section_header": "Section-header", "list_item": "List-item", "picture": "Picture", + "page_header": "Page-header", "page_footer": "Page-footer", "caption": "Caption", "footnote": "Footnote", + "table": "Table", "formula": "Formula", "title": "Title", "code": "Code", "document_index": "Document Index", + "form": "Form", "key_value_region": "Key-Value Region"} +SEG = {"Section-header": "paragraph_title", "Title": "doc_title", "Picture": "image", "Table": "table", + "Page-header": "header", "Page-footer": "footer"} +EL_TYPE = {"text": "Text", "heading": "Section-header", "table": "Table", "image": "Picture", "header": "Page-header", + "footer": "Page-footer", "list": "List-item", "code": "Code", "page_number": "Page-footer"} +_IMAGE_REF = re.compile(r"[ \t]*!\[[^\]]*\](\([^)]*\))?[ \t]*") + + +def _ov(a, b): + i = max(0.0, min(a[2], b[2]) - max(a[0], b[0])) * max(0.0, min(a[3], b[3]) - max(a[1], b[1])) + aa, ab = max(1e-9, (a[2] - a[0]) * (a[3] - a[1])), max(1e-9, (b[2] - b[0]) * (b[3] - b[1])) + return i / (aa + ab - i) + + +def tidy_regions(regs: list[dict]) -> list[dict]: + """Of a Picture and a Table region with IoU >= PAIR_IOU keep the higher-scoring one; drop weak pictures.""" + drop = set() + by_score = sorted(range(len(regs)), key=lambda j: -regs[j]["score"]) + for a in by_score: + if a in drop: + continue + la, ba = regs[a]["label"], regs[a]["box"] + for b in by_score: + if b == a or b in drop: + continue + lb = regs[b]["label"] + if {la, lb} <= PICTURE | TABLE and (la in TABLE) != (lb in TABLE) and _ov(ba, regs[b]["box"]) >= PAIR_IOU: + drop.add(b) + return [r for j, r in enumerate(regs) if j not in drop and (r["label"] not in PICTURE or r["score"] >= PICTURE_MIN_SCORE)] + + +def _table_region(words, regs, R): + ws = [w for w in words if w is not None] + if not ws: + return None + for kinds in (TABLE, PICTURE): + cnt = [(sum(R[j][0] <= (w[0] + w[2]) / 2 <= R[j][2] and R[j][1] <= (w[1] + w[3]) / 2 <= R[j][3] for w in ws), j) + for j in range(len(R)) if regs[j]["label"] in kinds] + if cnt and max(cnt)[0] >= TABLE_SHARE * len(ws): + return max(cnt)[1] + return None + + +def _dedupe(out_items): + """Two items whose boxes overlap at IoU >= 0.5 are one element: the one with more text keeps it.""" + order = sorted(range(len(out_items)), key=lambda k: -len(out_items[k][1]["md"])) + keep, gone = [], set() + for k in order: + if any(_ov(out_items[k][1]["box"], out_items[h][1]["box"]) >= 0.5 for h in keep): + gone.add(k) + else: + keep.append(k) + return [x for k, x in enumerate(out_items) if k not in gone] + + +def page_words(image, answer, blocks, units, per_block, maps, grid, has, words=None) -> list[dict]: + """Per block: its type, span, markdown, attention box, and (for non-image blocks) each word's box and offset.""" + page = Page(np.asarray(image.convert("RGB")), grid) + base = boxes_from_maps(image, answer, blocks, units, per_block, maps, grid, has, page=page) # attention-only boxes + pdfbox = unit_boxes_multi(answer, units, words) if words else {} + el_by_span = {(e["start"], e["end"]): e for e in base["elements"]} + out = [] + for b, idx in zip(blocks, per_block): + el = el_by_span.get((b.start, b.end)) + f = {"type": b.type, "start": b.start, "end": b.end, "md": _FURN_TAG.sub("", answer[b.start:b.end]).strip(), + "box": el["box"] if el else None} + if b.type != "image": + ws, starts = [], [] + for u in idx: + w = pdfbox.get(u) + if w is None and has[u]: + w = page.snap_word(maps[u], len(norm(answer[units[u][0]:units[u][1]]))) + ws.append(w) + starts.append(units[u][0]) + f["words"], f["starts"] = ws, starts + out.append(f) + return out + + +def place(answer: str, blocks_info: list[dict], detections: list[dict]) -> list[dict]: + """Region-first items [{type, label, md, box, start}] from `page_words` output and detector regions.""" + regs = tidy_regions(clean_regions(detections, MIN_SCORE)) + R = [r["box"] for r in regs] + area = [(r[2] - r[0]) * (r[3] - r[1]) for r in R] + + def region_of(b): + cx, cy = (b[0] + b[2]) / 2, (b[1] + b[3]) / 2 + hold = [j for j, r in enumerate(R) if r[0] <= cx <= r[2] and r[1] <= cy <= r[3] + and regs[j]["label"] not in PICTURE] + return min(hold, key=lambda j: area[j]) if hold else None + + texts = {j: [] for j in range(len(R))} # region -> [(answer offset, md)] + leftovers = [] # (element type, md, attention box) + for b in blocks_info: + md = b["md"] + if b["type"] == "image": + bx = b["box"] + cand = [(j, max(0.0, min(bx[2], R[j][2]) - max(bx[0], R[j][0])) + * max(0.0, min(bx[3], R[j][3]) - max(bx[1], R[j][1])) + / max(1e-9, min(area[j], (bx[2] - bx[0]) * (bx[3] - bx[1])))) + for j in range(len(R)) if regs[j]["label"] in PICTURE | TABLE] if bx else [] + cand = [c for c in cand if c[1] >= 0.5] + if cand: + texts[max(cand, key=lambda c: c[1])[0]].append((b["start"], md)) + elif bx: + leftovers.append(("image", md, bx)) + continue + ws = [region_of(w) if w is not None else None for w in b["words"]] + last = None + for k in range(len(ws)): # words without a region: the previous word's, else the next one's + if ws[k] is None: + ws[k] = last + last = ws[k] + nxt = None + for k in range(len(ws) - 1, -1, -1): + if ws[k] is None: + ws[k] = nxt + nxt = ws[k] + if not ws or all(w is None for w in ws): + if b["box"]: + leftovers.append((b["type"], md, b["box"])) + continue + if b["type"] == "table": + tj = _table_region(b["words"], regs, R) + bw = [w for w in b["words"] if w is not None] + if tj is None and bw: # no Table/Picture region: the table's own words give its box + h = sorted(w[3] - w[1] for w in bw)[len(bw) // 2] * 0.3 + box = [min(w[0] for w in bw) - h, min(w[1] for w in bw) - h, max(w[2] for w in bw) + h, + max(w[3] for w in bw) + h] + regs.append({"label": "table", "score": 0.0, "box": box}) + R.append(box) + area.append((box[2] - box[0]) * (box[3] - box[1])) + texts[len(R) - 1] = [(b["start"], md)] + continue + texts[tj if tj is not None else max(set(ws), key=ws.count)].append((b["start"], md)) + continue + starts = b["starts"] + run_start = 0 # contiguous runs of words per region keep their own markdown slice + for k in range(1, len(ws) + 1): + if k == len(ws) or ws[k] != ws[run_start]: + s = starts[run_start] if run_start else b["start"] + e = starts[k] if k < len(ws) else b["end"] + texts[ws[run_start]].append((s, _FURN_TAG.sub("", answer[s:e]).strip())) + run_start = k + + def item(t, md, bx): + if t != "Picture": # an image reference's alt text is not page text + md = _IMAGE_REF.sub(" ", md).strip() + return {"type": t, "label": SEG.get(t, "text"), "md": md, "box": [round(float(v), 1) for v in bx]} + + out = [] + for j, r in enumerate(regs): + t = TYPE.get(r["label"], "Text") + parts = [m for _, m in sorted(texts[j]) if m] + if not parts and r["label"] not in PICTURE: + continue + out.append((min((o for o, _ in texts[j]), default=10 ** 9), item(t, "\n\n".join(parts), R[j]))) + for t, md, bx in leftovers: + out.append((10 ** 9, item(EL_TYPE.get(t, "Text"), md, bx))) + out.sort(key=lambda x: x[0]) + return [{**it, "start": off if off < 10 ** 9 else None} for off, it in _dedupe(out)] + + +def ground_layout(grounder, image, answer: str, detector=None, words: list[dict] | None = None, + detections: list[dict] | None = None, *, method: str = "accurate-layout", + fast_backend=None, attention: dict | None = None) -> dict: + """{width, height, items: [{type, label, md, box, start}]} for one page; `box` is [x0, y0, x1, y1] in pixels of + `image`. `detector` (detector.Detector) or precomputed `detections` give the regions; `words` (pdf.render_pdf_page) + give exact word positions on pages with a text layer. With neither detector nor detections the items are the + attention-only elements.""" + if method == "fast-layout": + if fast_backend is None: + raise ValueError("fast-layout requires an initialized FastLayout backend") + if detector is not None or detections is not None or words is not None: + raise ValueError("fast-layout accepts attention only; omit detector, detections, and words") + from parse_rl_utils.ocria_attention_grounding.hf_adapter import ground_fast_layout + + return ground_fast_layout(grounder, image, answer, backend=fast_backend, attention=attention) + if method != "accurate-layout": + raise ValueError(f"Unknown layout method: {method}") + if attention is not None or fast_backend is not None: + raise ValueError("attention and fast_backend require method='fast-layout'") + w, h = image.size + blocks = split_blocks(answer) + units, per_block = units_for(answer, blocks) + if not units: + return {"width": w, "height": h, "items": []} + maps, grid, has = grounder.unit_maps(image, answer, units) + if detections is None and detector is not None: + detections = detector(image) + if detections is None: + base = boxes_from_maps(image, answer, blocks, units, per_block, maps, grid, has) + items = [{"type": EL_TYPE.get(e["type"], "Text"), "label": SEG.get(EL_TYPE.get(e["type"], "Text"), "text"), + "md": _FURN_TAG.sub("", answer[e["start"]:e["end"]]).strip(), "box": e["box"], "start": e["start"]} + for e in base["elements"] if e["box"] is not None] + return {"width": w, "height": h, "items": items} + info = page_words(image, answer, blocks, units, per_block, maps, grid, has, words) + return {"width": w, "height": h, "items": place(answer, info, detections)} + + +def to_layout_items_page(page: dict, scale: float = 1.0, page_md: str = "") -> dict: + """`ground_layout` output as a ParseBench `layout_pages` entry (x, y, w, h boxes in pixels x `scale`; use 72 / DPI + for PDF points).""" + items = [] + for it in page["items"]: + x0, y0, x1, y1 = (v * scale for v in it["box"]) + if x1 <= x0 or y1 <= y0: + continue + seg = {"x": x0, "y": y0, "w": x1 - x0, "h": y1 - y0, "label": it["label"]} + segments = [seg] + if "layout_segments" in it: + segments = [{**part, **{key: part[key] * scale for key in ("x", "y", "w", "h")}} + for part in it["layout_segments"]] + items.append({"type": it["type"], "md": it["md"], "value": it["md"], "bbox": dict(seg), "layout_segments": segments}) + return {"page_number": 1, "width": page["width"] * scale, "height": page["height"] * scale, "md": page_md, + "items": items} diff --git a/ocria_grounding/pdf.py b/ocria_grounding/pdf.py new file mode 100644 index 0000000000000000000000000000000000000000..394d02d10bbccfda649e733109ae0c0dbe9ead01 --- /dev/null +++ b/ocria_grounding/pdf.py @@ -0,0 +1,59 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""A PDF page as an image plus its text-layer words, both in the same pixel frame (pypdfium2). + + image, words = render_pdf_page("doc.pdf", page=0, dpi=300) # words: [{text, box: [x0, y0, x1, y1]}] + +The page is rendered from its CropBox with its /Rotate applied, which is how PDF viewers and ParseBench show it, and +every word box is mapped into that image (CropBox origin, rotation). Pages without a text layer give no words; the +boxes then come from the model's attention alone. +""" +from __future__ import annotations + + +def _to_image(l, b, r, t, crop, rot, s): + cx0, cy0, cx1, cy1 = crop + + def m(ux, uy): + return {0: (ux - cx0, cy1 - uy), 90: (uy - cy0, ux - cx0), 180: (cx1 - ux, uy - cy0), + 270: (cy1 - uy, cx1 - ux)}[rot] + xs, ys = zip(m(l, b), m(r, t)) + return [min(xs) * s, min(ys) * s, max(xs) * s, max(ys) * s] + + +def page_words(page, dpi: int = 300) -> list[dict]: + """Words of a pypdfium2 page in pixels of its `render_pdf_page` image: characters joined while the gap to the + next one is under 0.35 of the line height and they stay on the same line.""" + s, rot, crop = dpi / 72, page.get_rotation() % 360, page.get_cropbox() + tp = page.get_textpage() + out, cur = [], None + for i in range(tp.count_chars()): + ch = tp.get_text_range(i, 1) + if not ch or ch.isspace() or ch in "\r\n\x00￾": + if cur: + out.append(cur) + cur = None + continue + box = _to_image(*tp.get_charbox(i), crop, rot, s) + hgt = box[3] - box[1] + if cur and box[0] - cur["box"][2] < 0.35 * hgt and abs(box[1] - cur["box"][1]) < 0.5 * hgt: + cur["text"] += ch + cb = cur["box"] + cur["box"] = [min(cb[0], box[0]), min(cb[1], box[1]), max(cb[2], box[2]), max(cb[3], box[3])] + else: + if cur: + out.append(cur) + cur = {"text": ch, "box": box} + if cur: + out.append(cur) + return out + + +def render_pdf_page(path: str, page: int = 0, dpi: int = 300): + """(PIL image of the page at `dpi`, its text-layer words in that image's pixels).""" + import pypdfium2 as pdfium + + pg = pdfium.PdfDocument(path)[page] + image = pg.render(scale=dpi / 72).to_pil().convert("RGB") + return image, page_words(pg, dpi) diff --git a/ocria_grounding/regions.py b/ocria_grounding/regions.py new file mode 100644 index 0000000000000000000000000000000000000000..af56ed99512d196cb6ff0054fc8551d06e3ac020 --- /dev/null +++ b/ocria_grounding/regions.py @@ -0,0 +1,165 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Place attention-grounded elements on layout-detector regions (element-first placement). + +The attention says WHICH words belong to an element and roughly where they are; a detector region says where a block +of the page starts and ends. Each element takes the region(s) holding most of its words: + +- one region, owned by this element alone -> the region's box +- one region shared with other elements -> the region's width, over this element's own words (vertically) +- several regions each holding >= 25% of words -> their union (a paragraph that continues in the next column) +- a table -> the Table region holding most of its words (union with its words) +- an image reference -> the Picture/Table region under its attention box (IoU or holding) +- no region holding any of its words -> its attention box, unchanged + +Picture regions no element claims become picture elements of their own (graphics the answer does not mention). +Region boxes are pixels of the page image, like the element boxes. +""" +from __future__ import annotations + +PICTURE = {"picture", "chart", "figure"} +TABLE = {"table"} +SKIP = {"checkbox_selected", "checkbox_unselected"} + + +def _norm(label: str) -> str: + """Detector label in one spelling: Docling's "Picture" / "picture", "Checkbox-Selected" / "checkbox_selected".""" + return label.lower().replace("-", "_").replace(" ", "_") + + +def _inter(a, b) -> float: + return max(0.0, min(a[2], b[2]) - max(a[0], b[0])) * max(0.0, min(a[3], b[3]) - max(a[1], b[1])) + + +def _area(a) -> float: + return max(0.0, a[2] - a[0]) * max(0.0, a[3] - a[1]) + + +def _holds(r, w, pad: float) -> bool: + cx, cy = (w[0] + w[2]) / 2, (w[1] + w[3]) / 2 + return r[0] - pad <= cx <= r[2] + pad and r[1] - pad <= cy <= r[3] + pad + + +def clean_regions(dets: list[dict], min_score: float = 0.35) -> list[dict]: + """Detections above `min_score`, minus a box mostly (>= 80%) inside a higher-scoring box of the same kind.""" + keep: list[dict] = [] + dets = [{**d, "label": _norm(d["label"])} for d in dets] + for d in sorted((d for d in dets if d["score"] >= min_score and d["label"] not in SKIP), key=lambda d: -d["score"]): + b = d["box"] + if any(k["label"] == d["label"] and _inter(b, k["box"]) >= 0.8 * max(_area(b), 1e-9) for k in keep): + continue + keep.append(d) + return keep + + +def place_on_regions(types: list[str], words: list[list], boxes: list, regions: list[dict], line_h: float, + add_unclaimed_pictures: bool = True, text_too: bool = True) -> tuple[list, list[list[float]]]: + """(new boxes per element, extra picture boxes). `types[i]` is element i's block type, `words[i]` its snapped word + boxes (after stray filtering), `boxes[i]` its attention box (None allowed).""" + pad = 0.3 * line_h + R = [r["box"] for r in regions] + counts = [[sum(_holds(r, w, pad) for w in ws) for r in R] for ws in words] + # region -> elements that hold words in it + users: dict[int, list[int]] = {} + for i, c in enumerate(counts): + for j, n in enumerate(c): + if n and types[i] not in ("image",): + users.setdefault(j, []).append(i) + out = list(boxes) + claimed: set[int] = set() + for i, t in enumerate(types): + if t == "image": + b = boxes[i] + if b is None: + continue + cand = [(j, _inter(b, R[j]) / max(min(_area(b), _area(R[j])), 1e-9)) for j, r in enumerate(regions) + if r["label"] in PICTURE | TABLE] + cand = [(j, v) for j, v in cand if v >= 0.5] + if cand: + j = max(cand, key=lambda x: x[1])[0] + out[i] = list(R[j]) + claimed.add(j) + continue + ws, c = words[i], counts[i] + n = len(ws) + if not n or not any(c): + continue + if t == "table": + tj = [j for j in range(len(R)) if regions[j]["label"] in TABLE | PICTURE and c[j]] + if tj: + j = max(tj, key=lambda j: c[j]) + if c[j] >= 0.3 * n: + r = R[j] + b = boxes[i] or r + out[i] = [min(r[0], b[0]), min(r[1], b[1]), max(r[2], b[2]), max(r[3], b[3])] \ + if _inter(b, r) >= 0.5 * _area(b) else list(r) + claimed.add(j) + continue + if not text_too: # visual-only mode: text keeps its attention box + continue + main = [j for j in range(len(R)) if c[j] >= 0.25 * n and regions[j]["label"] not in PICTURE] + if not main: + continue + for j in main: + claimed.add(j) + if len(main) == 1 and len(users.get(main[0], [])) == 1: + out[i] = list(R[main[0]]) + continue + if len(main) > 1 and all(len(users.get(j, [])) == 1 for j in main): + out[i] = [min(R[j][0] for j in main), min(R[j][1] for j in main), max(R[j][2] for j in main), + max(R[j][3] for j in main)] + continue + # shared region(s): the region's horizontal extent, the element's own words vertically + inside = [w for w in ws if any(_holds(R[j], w, pad) for j in main)] + if not inside: + continue + x0 = min(R[j][0] for j in main) + x1 = max(R[j][2] for j in main) + y0 = max(min(w[1] for w in inside), min(R[j][1] for j in main)) + y1 = min(max(w[3] for w in inside), max(R[j][3] for j in main)) + if y1 > y0: + out[i] = [x0, y0, x1, y1] + extra = [] + if add_unclaimed_pictures: + for j, r in enumerate(regions): + if j in claimed or r["label"] not in PICTURE: + continue + if any(b is not None and _inter(b, R[j]) >= 0.5 * _area(R[j]) for b in out): + continue + extra.append(list(R[j])) + return out, extra + + +def ink_regions(page, kv: float = 1.0, kh: float = 1.5) -> list[dict]: + """Detector-free regions from the page image alone: text blocks are the ink closed across word gaps (kh x body + glyph height) and line spacing (kv x), so a paragraph is one block and a column gutter stays open; pictures are + filled foreground components (the graphics an image reference snaps to). Same shape as detector output.""" + import numpy as np + from scipy import ndimage + + h = page.med_h + row, col = np.ones((1, max(3, int(kh * h)) | 1), bool), np.ones((max(3, int(kv * h)) | 1, 1), bool) + closed = ndimage.binary_erosion(ndimage.binary_erosion( + ndimage.binary_dilation(ndimage.binary_dilation(page.ink, row), col), row), col) + lab, _ = ndimage.label(closed | page.ink) + out = [] + for s in ndimage.find_objects(lab): + if s is None: + continue + y0, y1, x0, x1 = s[0].start, s[0].stop, s[1].start, s[1].stop + if (y1 - y0) < 0.5 * h or (x1 - x0) < h: + continue + out.append({"label": "text", "score": 1.0, "box": [float(x0), float(y0), float(x1), float(y1)]}) + flab, fsl = page.fg_components() + for s in fsl: + if s is None: + continue + y0, y1, x0, x1 = s[0].start, s[0].stop, s[1].start, s[1].stop + w_, h_ = x1 - x0, y1 - y0 + if w_ < 3 * h or h_ < 3 * h or w_ * h_ > 0.6 * page.w * page.h: + continue + if float(page.fg[s].mean()) < 0.35 or float(page.ink[s].mean()) > 0.5: + continue + out.append({"label": "picture", "score": 1.0, "box": [float(x0), float(y0), float(x1), float(y1)]}) + return out diff --git a/ocria_grounding/tune.py b/ocria_grounding/tune.py new file mode 100644 index 0000000000000000000000000000000000000000..f65356b741e17791de9dd88d79215630bdfabf5c --- /dev/null +++ b/ocria_grounding/tune.py @@ -0,0 +1,5 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""The attention-box settings this release uses (fixed; the code paths behind other switches are kept but off).""" +FLAGS: dict[str, str] = {"table_fill": "1", "add_pictures": "1", "chart_tables": "1", "drop_big_words": "1", "dedupe": "1"} diff --git a/ocria_grounding/words.py b/ocria_grounding/words.py new file mode 100644 index 0000000000000000000000000000000000000000..b33ac5ea4a55280947deb9dbb0c542bec367aa80 --- /dev/null +++ b/ocria_grounding/words.py @@ -0,0 +1,32 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Content words of a transcript (shared by the GPU capture and the scoring): character spans that hold page text, +with markup removed, so ocria's RCL / HTML / markdown and Gemini's markdown / HTML are cut the same way.""" +import re + +# HTML tags (a letter after "<", one line: a bare "<" is text, e.g. RCL's merge-left cell or "< 8.0 V"); +# markdown link / image targets +TAG = re.compile(r"\n]*>|\]\([^)\s]*\)|!\[") +# a word starts with a letter or digit (or a currency sign / opening bracket before one) and runs over letters, digits and +# in-word punctuation; markdown/RCL markup (#, *, |, !, `, _, quotes) is never part of a word +WORD = re.compile(r"[$€£¥₹(]?[^\W_][^\s<>|*`\"\t]*") +TRAIL = ".,;:)]}!?'’" + + +def norm(w: str) -> str: + return re.sub(r"[\W_]", "", w.lower()) + + +def word_spans(text: str) -> list[tuple[int, int, str]]: + masked = TAG.sub(lambda m: " " * len(m.group()), text) + masked = masked.replace(" ", " ").replace("&", "& ") + out = [] + for m in WORD.finditer(masked): + s, e = m.start(), m.end() + while e > s + 1 and masked[e - 1] in TRAIL and not (masked[e - 1] == ")" and "(" in masked[s:e - 1]): + e -= 1 + w = text[s:e] + if norm(w): + out.append((s, e, w)) + return out diff --git a/parse_rl_utils/ocria_attention_grounding/__init__.py b/parse_rl_utils/ocria_attention_grounding/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f2cf410704c309347de17d1acf38dc261b17cab2 --- /dev/null +++ b/parse_rl_utils/ocria_attention_grounding/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""CPU grounding from cached attention and generated text, without raster processing.""" diff --git a/parse_rl_utils/ocria_attention_grounding/api.py b/parse_rl_utils/ocria_attention_grounding/api.py new file mode 100644 index 0000000000000000000000000000000000000000..5006007af085a572bd8824cc13da66c56fc79464 --- /dev/null +++ b/parse_rl_utils/ocria_attention_grounding/api.py @@ -0,0 +1,155 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Reusable pixel-free layout extraction from precomputed word attention. + +Frozen predictors are loaded once per instance. Capture coordinates and output +boxes use the original image pixel frame; PDF frame conversion belongs to the caller. +""" + +from pathlib import Path +import time +from numbers import Integral + +import numpy as np + +import joblib + +from .navigation import constrain_sidebar_icons +from .headings import ( + expand_table_to_embedded_heading, + merge_bold_heading_continuations, + merge_heading_lines, + merge_numeric_callouts, + trim_paragraph_heading_overlap, +) +from .pictures import ( + merge_figure_tables, + trim_picture_text_overlap, + trim_picture_table_overlap, +) +from .io import join_paragraph_segments, merge_duplicate_text, to_layout_page +from .learned import ground_cached + + +def finalize_layout(answer: str, page: dict) -> dict: + """Apply the retained checkpoint's geometry rules in their evaluation order.""" + page["items"] = merge_duplicate_text(merge_heading_lines(page["items"])) + trim_picture_text_overlap(page["items"]) + page["items"] = merge_numeric_callouts(page["items"]) + trim_paragraph_heading_overlap(page["items"]) + page["items"] = join_paragraph_segments(answer, page["items"]) + page["items"] = merge_figure_tables(page["items"]) + page["items"] = merge_bold_heading_continuations(answer, page["items"]) + page["items"] = constrain_sidebar_icons( + page["items"], page["width"], page["height"] + ) + trim_picture_table_overlap(page["items"]) + expand_table_to_embedded_heading(page["items"]) + return page + + +def validate_capture(attention: dict) -> None: + """Check external sparse coordinates before indexing arrays or native buffers.""" + dimensions = np.asarray([attention["width"], attention["height"]], dtype=float) + if not np.isfinite(dimensions).all() or (dimensions <= 0).any(): + raise ValueError("Page dimensions must be finite and positive") + grid = attention["grid"] + if len(grid) != 2 or any( + not isinstance(n, Integral) or isinstance(n, bool) or n <= 0 for n in grid + ): + raise ValueError("Attention grid must contain two positive integers") + sparse = attention["sparse_maps"] + if not len(sparse["idx"]) == len(sparse["val"]) == len(sparse["has"]): + raise ValueError("Sparse indices, values, and validity rows must align") + flags = np.asarray(sparse["has"]) + if flags.ndim != 1 or (len(flags) and flags.dtype.kind != "b"): + raise ValueError("Attention validity flags must be boolean") + cells = int(grid[0]) * int(grid[1]) + for indices, values in zip(sparse["idx"], sparse["val"], strict=True): + if len(indices) != len(values): + raise ValueError("Each sparse index must have one attention value") + if not len(indices): + continue + indices = np.asarray(indices) + values = np.asarray(values, dtype=np.float32) + if ( + indices.ndim != 1 + or indices.dtype.kind not in "iu" + or (indices < 0).any() + or (indices >= cells).any() + ): + raise ValueError( + "Sparse indices must be integers inside the attention grid" + ) + if values.ndim != 1 or not np.isfinite(values).all() or (values < 0).any(): + raise ValueError("Sparse attention values must be finite and nonnegative") + + +class FastLayout: + """A reusable backend with explicit, trusted frozen predictor artifacts.""" + + def __init__( + self, *, words: Path, pictures: Path, regions: Path, tables: Path, peaks: Path + ) -> None: + self.words = joblib.load(words) + self.pictures = joblib.load(pictures) + self.regions = joblib.load(regions) + self.tables = joblib.load(tables) + self.peaks = joblib.load(peaks) + + def layout_page(self, *, answer: str, attention: dict) -> dict: + """Return a ParseBench page in pixels, including spatial text segments. + + Attention uses the existing cache contract: width, height, grid [h,w], + sparse_maps {idx, val, has}, one row per transcript attention unit. + This method performs no image, PDF, network, or model-inference I/O. + """ + validate_capture(attention) + result = ground_cached( + answer, + attention, + self.words, + picture_model=self.pictures, + with_extended_context=True, + region_models=self.regions, + table_model=self.tables, + with_region_context=True, + peak_model=self.peaks, + ) + page = to_layout_page( + answer, result["elements"], attention["width"], attention["height"] + ) + return finalize_layout(answer, page) + + def __call__(self, *, answer: str, attention: dict) -> dict: + """Return the public OCRia item schema, retaining detailed text segments.""" + started = time.perf_counter() + page = self.layout_page(answer=answer, attention=attention) + items = [] + for item in page["items"]: + box = item["bbox"] + items.append( + { + "type": item["type"], + "label": box["label"], + "md": item["md"], + "box": [ + box["x"], + box["y"], + box["x"] + box["w"], + box["y"] + box["h"], + ], + "layout_segments": item["layout_segments"], + } + ) + return { + "width": page["width"], + "height": page["height"], + "items": items, + "attention_source": "precomputed", + "timings_ms": { + "attention_capture": 0.0, + "layout_postprocessing": (time.perf_counter() - started) * 1000, + }, + } diff --git a/parse_rl_utils/ocria_attention_grounding/blocks.py b/parse_rl_utils/ocria_attention_grounding/blocks.py new file mode 100644 index 0000000000000000000000000000000000000000..6bb08bcdb695812eae16474978f15fce647df6f8 --- /dev/null +++ b/parse_rl_utils/ocria_attention_grounding/blocks.py @@ -0,0 +1,289 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Layout elements of a raw ocria answer: the character spans that each get one box, with a type. + +The answer is ocria's no-layout transcription (markdown, HTML tables, ``/``/`` +furniture tags, `![label: description]` image references, ```mermaid diagrams). Each element becomes one +`` marker, so the types are the box-mode vocabulary the layout scorer already reads +(`layout_score._BOX_TYPE_TO_REGION_LABEL`): text, heading, list, table, image, code, header, footer. + +Granularity (one element per ...): paragraph (blank-line separated), heading line, list item (with its indented +continuation lines), whole table, image reference, fenced block, display-math block, furniture band. A standalone +`` gets type "page_number" and is resolved to header/footer from its box (`resolve_page_numbers`). +Offsets index the raw answer, fence included, so they line up with the teacher-forced tokens. +""" + +from __future__ import annotations + +import re +from collections.abc import Callable +from dataclasses import dataclass + +from .tune import FLAGS + +_OPEN_FENCE = re.compile(r"\A\s*```(?:markdown|md)?[ \t]*\n") +_FURN_OPEN = re.compile(r"<(page_header|page_footer|watermark)>") +_PAGE_NUMBER = re.compile(r"^\s*.*?\s*$") +_HEADING = re.compile(r"^\s{0,3}#{1,6}\s") +_IMAGE = re.compile(r"^\s*!\[") +_FENCE = re.compile(r"^\s*```") +_MATH = re.compile(r"^\s*\$\$") +_PIPE_ROW = re.compile(r"^\s*\|") +_TABLE_OPEN = re.compile(r"<(table|rcl)\b", re.I) # HTML table, or ocria-1.5's RCL grid +_LIST_ITEM = re.compile( + r"^(\s*)(?:[*\-+•▪◦»]\s|\d{1,3}[.)]\s|\(?[a-zA-Z][.)]\s|\[[ xX_]*\]\s)" +) +_QUOTE_PREFIX = re.compile(r"^(?: {0,3}>[ \t]?)+") +_BOLD_LINE = re.compile(r"^\s*\*\*[^*]+\*\*:?\s*$") +_TYPES_FOR_FURN = { + "page_header": "header", + "page_footer": "footer", + "watermark": "text", +} + + +@dataclass +class Block: + type: str + start: int + end: int + + +def _lines(text: str, lo: int, hi: int) -> list[tuple[int, int, str]]: + """(start, end, line) for each line of text[lo:hi]; end excludes the newline.""" + out, pos = [], lo + while pos < hi: + nl = text.find("\n", pos, hi) + end = hi if nl < 0 else nl + out.append((pos, end, text[pos:end])) + pos = end + 1 + return out + + +def body_span(text: str) -> tuple[int, int]: + """The transcription inside the ```markdown fence (the whole answer when there is none).""" + lo, hi = 0, len(text) + m = _OPEN_FENCE.match(text) + if m: + lo = m.end() + close = text.rfind("```") + if close >= lo: + hi = close + return lo, hi + + +def _starts_construct(line: str) -> bool: + return bool( + _HEADING.match(line) + or _IMAGE.match(line) + or _FENCE.match(line) + or _MATH.match(line) + or _PIPE_ROW.match(line) + or _TABLE_OPEN.search(line) + or _FURN_OPEN.search(line) + or _PAGE_NUMBER.match(line) + or _LIST_ITEM.match(line) + ) + + +def split_blocks(text: str) -> list[Block]: + """Layout elements of one page's raw answer, in reading order.""" + lo, hi = body_span(text) + lines = _lines(text, lo, hi) + blocks: list[Block] = [] + i = 0 + + def until(j: int, pred: Callable[[str], bool]) -> int: + """Index of the first line from j on for which pred holds (the last line when none does).""" + while j < len(lines) and not pred(lines[j][2]): + j += 1 + return min(j, len(lines) - 1) + + while i < len(lines): + s, e, line = lines[i] + if not line.strip(): + i += 1 + continue + m = _FURN_OPEN.search(line) + if m: + tag = m.group(1) + close = f"" + j = i if close in line else until(i + 1, lambda x: close in x) + blocks.append(Block(_TYPES_FOR_FURN[tag], s, lines[j][1])) + i = j + 1 + continue + if _PAGE_NUMBER.match(line): + blocks.append(Block("page_number", s, e)) + i += 1 + continue + tm = _TABLE_OPEN.search(line) + if tm: + close = "" if tm.group(1).lower() == "table" else "" + j = ( + i + if close in line.lower() + else until(i + 1, lambda x: close in x.lower()) + ) + if "split_layout_tables" in FLAGS and _is_layout_table( + text[s : lines[j][1]] + ): + blocks.extend(_layout_table_blocks(text, s, lines[j][1])) + else: + blocks.append(Block("table", s, lines[j][1])) + i = j + 1 + continue + if _FENCE.match(line): + j = until(i + 1, lambda x: _FENCE.match(x) is not None) + kind = "image" if "mermaid" in line.lower() else "code" + blocks.append(Block(kind, s, lines[j][1])) + i = j + 1 + continue + if _MATH.match(line): + rest = line.strip()[2:] + j = i if "$$" in rest else until(i + 1, lambda x: "$$" in x) + blocks.append(Block("text", s, lines[j][1])) + i = j + 1 + continue + if _HEADING.match(line): + blocks.append(Block("heading", s, e)) + i += 1 + continue + if _IMAGE.match(line): + blocks.append(Block("image", s, e)) + i += 1 + continue + if _PIPE_ROW.match(line): + j = i + while j + 1 < len(lines) and _PIPE_ROW.match(lines[j + 1][2]): + j += 1 + blocks.append(Block("table", s, lines[j][1])) + i = j + 1 + continue + lm = _LIST_ITEM.match(line) + if lm: + indent = len(lm.group(1)) + j = i + while j + 1 < len(lines): + nxt = lines[j + 1][2] + if not nxt.strip() or _starts_construct(nxt): + break + if ( + len(nxt) - len(nxt.lstrip()) <= indent + ): # a continuation line is indented under the marker + break + j += 1 + blocks.append(Block("list", s, lines[j][1])) + i = j + 1 + continue + if ( + "split_lines" in FLAGS + ): # each line its own element; a bold-only line is a heading + blocks.append(Block("heading" if _BOLD_LINE.match(line) else "text", s, e)) + i += 1 + continue + j = i # paragraph: until a blank line or a line that opens another element + while ( + j + 1 < len(lines) + and lines[j + 1][2].strip() + and not _starts_construct(lines[j + 1][2]) + ): + j += 1 + blocks.append(Block("text", s, lines[j][1])) + i = j + 1 + blocks = [piece for block in blocks for piece in _split_quoted_list(text, block)] + if "inline_images" in FLAGS: + blocks = [p for b in blocks for p in _split_inline_images(text, b)] + return blocks + + +def _split_quoted_list(text: str, block: Block) -> list[Block]: + """Expose quoted list items while retaining raw offsets and continuation lines. + + Quote prefixes are ignored only for recognizing markers. Keeping the raw + spans preserves the word sequence used by cached sparse attention maps. + """ + if block.type != "text" or ">" not in text[block.start : block.end]: + return [block] + result: list[Block] = [] + start, kind = block.start, block.type + for line_start, _, line in _lines(text, block.start, block.end): + prefix = _QUOTE_PREFIX.match(line) + if prefix is None or not _LIST_ITEM.match(line[prefix.end() :]): + continue + if line_start > start and text[start:line_start].strip(" >\t\r\n"): + result.append(Block(kind, start, line_start)) + start, kind = line_start, "list" + result.append(Block(kind, start, block.end)) + return result + + +_INLINE_IMAGE = re.compile(r"!\[[^\]\n]*\](?:\([^)\s]*\))?") + + +def _split_inline_images(text: str, b: Block) -> list[Block]: + """An image reference inside a text-like element (an icon after a heading, a logo next to a footer's page number) + is a picture of its own on the page: the element is cut into the text before it, the image, and the text after.""" + if b.type in ("image", "table", "code") or "![" not in text[b.start : b.end]: + return [b] + out, pos = [], b.start + for m in _INLINE_IMAGE.finditer(text, b.start, b.end): + if _TAGS.sub("", text[pos : m.start()]).strip(" \t\n|*#-"): + out.append(Block(b.type, pos, m.start())) + out.append(Block("image", m.start(), m.end())) + pos = m.end() + if _TAGS.sub("", text[pos : b.end]).strip(" \t\n|*#-"): + out.append(Block(b.type, pos, b.end)) + return out or [b] + + +def resolve_page_numbers(blocks: list[Block], boxes: list, page_height: float) -> None: + """A standalone page number is furniture: header when its box sits in the top half, else footer.""" + for b, box in zip(blocks, boxes): + if b.type == "page_number": + b.type = ( + "header" + if box is not None and (box[1] + box[3]) / 2 < page_height / 2 + else "footer" + ) + + +_CELL = re.compile(r"]*>(.*?)", re.S | re.I) +_TAGS = re.compile(r"<[^>]+>") + + +def _is_layout_table(html: str) -> bool: + """A table used to lay out a page (people grids, card layouts), not data: it holds image references, or its + cells hold prose (mean >= 8 words).""" + if "![" in html: + return True + words = [len(_TAGS.sub(" ", c).split()) for c in _CELL.findall(html) if c.strip()] + return bool(words) and sum(words) / len(words) >= 8 + + +def _layout_table_blocks(text: str, lo: int, hi: int) -> list[Block]: + """One element per segment of each cell: segments split at blank lines (two or more
, or any
with + split_br), an image reference is its own element.""" + sep = re.compile( + r"(?:\s*)+" if "split_br" in FLAGS else r"(?:\s*){2,}", re.I + ) + out: list[Block] = [] + for m in _CELL.finditer(text, lo, hi): + a, b = m.start(1), m.end(1) + pos = a + for cut in [*sep.finditer(text, a, b), None]: + end = cut.start() if cut else b + seg = text[pos:end] + if _TAGS.sub("", seg).strip(): + k = pos + (len(seg) - len(seg.lstrip())) + origin = k + for im in re.finditer(r"!\[[^\]]*\]", text[origin:end]): + start, stop = origin + im.start(), origin + im.end() + if text[k:start].strip(): + out.append(Block("text", k, start)) + out.append(Block("image", start, stop)) + k = stop + if _TAGS.sub("", text[k:end]).strip(): + out.append(Block("text", k, end)) + pos = cut.end() if cut else b + return out diff --git a/parse_rl_utils/ocria_attention_grounding/boxes.py b/parse_rl_utils/ocria_attention_grounding/boxes.py new file mode 100644 index 0000000000000000000000000000000000000000..f2cb68d9ab412c8f24268ed30f595c4b50afe381 --- /dev/null +++ b/parse_rl_utils/ocria_attention_grounding/boxes.py @@ -0,0 +1,61 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Spatial operations on attention-derived rectangles; no raster input.""" + + +def envelope(boxes: list[list[float]]) -> list[float]: + return [ + min(b[0] for b in boxes), + min(b[1] for b in boxes), + max(b[2] for b in boxes), + max(b[3] for b in boxes), + ] + + +def main_cluster( + boxes: list[list[float]], line_h: float, wide: bool = False +) -> list[list[float]]: + """The largest group of word boxes chained by proximity (vertical gap <= 1.5 lines; horizontal gap <= 4 lines, + or any for a table, whose columns sit far apart). Words outside it are attention strays.""" + n = len(boxes) + if n <= 2: + return boxes + dy_max, dx_max = 1.5 * line_h, (float("inf") if wide else 4.0 * line_h) + if wide and line_h >= 0: + # With no horizontal limit, connected components are merged y intervals. + interval_groups = [] + current = [] + bottom = float("-inf") + for i in sorted(range(n), key=lambda i: boxes[i][1]): + if current and boxes[i][1] - bottom > dy_max: + interval_groups.append(current) + current = [] + current.append(i) + bottom = max(bottom, boxes[i][3]) + interval_groups.append(current) + best = max(interval_groups, key=lambda group: (len(group), -min(group))) + return [boxes[i] for i in sorted(best)] + parent = list(range(n)) + + def find(i: int) -> int: + while parent[i] != i: + parent[i] = parent[parent[i]] + i = parent[i] + return i + + order = sorted(range(n), key=lambda i: boxes[i][1]) + for a_i, a in enumerate(order): + for b in order[a_i + 1 :]: + if boxes[b][1] - boxes[a][3] > dy_max: + break + p, q = boxes[a], boxes[b] + dy = max(0.0, max(p[1], q[1]) - min(p[3], q[3])) + dx = max(0.0, max(p[0], q[0]) - min(p[2], q[2])) + if dy <= dy_max and dx <= dx_max: + parent[find(a)] = find(b) + groups: dict[int, list[int]] = {} + for i in range(n): + groups.setdefault(find(i), []).append(i) + best = max(groups.values(), key=len) + return [boxes[i] for i in best] diff --git a/parse_rl_utils/ocria_attention_grounding/bullet_tables.py b/parse_rl_utils/ocria_attention_grounding/bullet_tables.py new file mode 100644 index 0000000000000000000000000000000000000000..8903839f00a5b86dba0909dba82d7eea93e69ea6 --- /dev/null +++ b/parse_rl_utils/ocria_attention_grounding/bullet_tables.py @@ -0,0 +1,63 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Recover list items stored as HTML rows with a bullet-only first cell.""" + +import re + +from .blocks import Block + +_TABLE = re.compile(r"\s*]*>(.*?)\s*", re.I | re.S) +_ROW = re.compile(r"]*>(.*?)", re.I | re.S) +_CELL = re.compile(r"<(td|th)\b([^>]*)>(.*?)", re.I | re.S) +_TAG = re.compile(r"<[^>]*>") +_SPAN = re.compile(r"\b(?:rowspan|colspan)\s*=", re.I) + + +def split_bullet_tables(answer: str, blocks: list[Block]) -> list[Block]: + """Keep raw content spans so existing cached word indices remain valid. + + Every body row must contain exactly a literal bullet cell and a text cell. + An optional first header becomes a heading. Unparsed content or merged body + cells preserve the whole table, avoiding loss of words or table relationships. + """ + result = [] + for block in blocks: + if block.type != "table": + result.append(block) + continue + table = _TABLE.fullmatch(answer[block.start : block.end]) + if table is None or "= 2: + result.extend(pieces) + else: + result.append(block) + return result diff --git a/parse_rl_utils/ocria_attention_grounding/coarse.py b/parse_rl_utils/ocria_attention_grounding/coarse.py new file mode 100644 index 0000000000000000000000000000000000000000..3b5705208bca672e6c53fb1af506a1f1129e6ad5 --- /dev/null +++ b/parse_rl_utils/ocria_attention_grounding/coarse.py @@ -0,0 +1,159 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Detector-free boxes from attention cells, without reading page pixels.""" + +import statistics + +import numpy as np +from scipy import ndimage + +from .blocks import Block, resolve_page_numbers +from .boxes import envelope, main_cluster +from .geometry import paragraph_paths +from .words import norm +from .io import SparseWordMaps + + +def attention_boxes( + size: tuple[int, int], + blocks: list[Block], + units: list[tuple[int, int]], + per_block: list[list[int]], + maps: np.ndarray | SparseWordMaps, + grid: tuple[int, int], + has: np.ndarray, + support: bool = False, + answer: str = "", + infer_words: bool = False, + support_boxes: dict[int, tuple[int, int, int, int]] | None = None, + peak_indices: np.ndarray | None = None, +) -> dict: + """Use peak cells for words and connected attention support for pictures. + + Coordinates are projected directly from the attention grid to image pixels. + Consecutive words sharing a cell collapse for path selection, while their + original text spans remain intact. No ink, rendering, or pixel masks are used. + Optional support boxes are per-unit cell bounds for the same 0.3-threshold, + eight-connected peak component; omitted entries use the normal calculation. + """ + width, height = size + gh, gw = grid + cw, ch = width / gw, height / gh + if peak_indices is None and isinstance(maps, SparseWordMaps): + peaks = maps.peaks + elif peak_indices is None: + peaks = ( + np.argmax(maps.reshape(len(maps), -1), axis=1) + if len(maps) + else np.array([], dtype=int) + ) + else: + peaks = peak_indices + lengths = [max(1, len(norm(answer[s:e]))) for s, e in units] if infer_words else [] + advances: dict[int, list[float]] = {} + if infer_words: + # Adjacent word centres constrain character advance without a font or + # pixel detector. Ignore reversed/different-line pairs and large gaps. + for k, (block, indices) in enumerate(zip(blocks, per_block)): + if block.type == "image": + continue + estimates = [] + for a, b in zip(indices, indices[1:]): + ya, xa = divmod(int(peaks[a]), gw) + yb, xb = divmod(int(peaks[b]), gw) + advance = (xb - xa) * cw / ((lengths[a] + lengths[b]) / 2 + 1) + if has[a] and has[b] and ya == yb and 0.1 * cw <= advance <= 1.5 * cw: + estimates.append(advance) + advances[k] = estimates + global_advance = statistics.median( + [a for values in advances.values() for a in values] or [0.5 * ch] + ) + pieces: list[Block] = [] + boxes: list[list[float] | None] = [] + for block_index, (block, indices) in enumerate(zip(blocks, per_block)): + estimates = advances.get(block_index, []) + advance = ( + statistics.median(estimates) if len(estimates) >= 3 else global_advance + ) + located: list[tuple[int, list[float]]] = [] + for u in indices: + if not has[u]: + continue + y, x = divmod(int(peaks[u]), gw) + maximum = ( + maps.maxima[u] if isinstance(maps, SparseWordMaps) else maps[u, y, x] + ) + if maximum <= 0: + continue + x0, y0, x1, y1 = int(x), int(y), int(x) + 1, int(y) + 1 + if support and support_boxes is not None and u in support_boxes: + x0, y0, x1, y1 = support_boxes[u] + elif support or block.type == "image": + m = maps[u] + labels, _ = ndimage.label( + m >= 0.3 * float(m[y, x]), structure=np.ones((3, 3)) + ) + yy, xx = np.nonzero(labels == labels[y, x]) + x0, y0, x1, y1 = ( + int(xx.min()), + int(yy.min()), + int(xx.max()) + 1, + int(yy.max()) + 1, + ) + box = [x0 * cw, y0 * ch, x1 * cw, y1 * ch] + if infer_words and block.type != "image": + cx, cy = (x + 0.5) * cw, (y + 0.5) * ch + half_width, half_height = ( + max(cw / 2, lengths[u] * advance / 2), + 0.85 * advance, + ) + box = [ + max(0.0, cx - half_width), + max(0.0, cy - half_height), + min(float(width), cx + half_width), + min(float(height), cy + half_height), + ] + if not located or box != located[-1][1]: + located.append((u, box)) + if not located: + pieces.append(Block(block.type, block.start, block.end)) + boxes.append(None) + continue + words = [box for _, box in located] + paths = ( + paragraph_paths(words) + if block.type in ("text", "list", "heading") + else None + ) + if infer_words and block.type == "heading" and paths: + # A heading can have wide spaces; its supported runs share one box. + paths = [[i for path in paths for i in path]] + if paths: + for k, path in enumerate(paths): + start = block.start if k == 0 else units[located[path[0]][0]][0] + end = ( + block.end + if k + 1 == len(paths) + else units[located[paths[k + 1][0]][0]][0] + ) + pieces.append(Block(block.type, start, end)) + boxes.append(envelope([words[i] for i in path])) + else: + pieces.append(Block(block.type, block.start, block.end)) + boxes.append(envelope(main_cluster(words, ch, wide=block.type == "table"))) + resolve_page_numbers(pieces, boxes, height) + return { + "width": width, + "height": height, + "grid": list(grid), + "elements": [ + { + "type": b.type, + "start": b.start, + "end": b.end, + "box": None if box is None else [round(v, 1) for v in box], + } + for b, box in zip(pieces, boxes) + ], + } diff --git a/parse_rl_utils/ocria_attention_grounding/columns.py b/parse_rl_utils/ocria_attention_grounding/columns.py new file mode 100644 index 0000000000000000000000000000000000000000..3efb1ce541486f9b3b3b0d7d14c3d4321fbc93e7 --- /dev/null +++ b/parse_rl_utils/ocria_attention_grounding/columns.py @@ -0,0 +1,149 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Separate prose that continues into another column without a Markdown break.""" + +import numpy as np + +from .blocks import Block +from .io import units_for + +_COLUMN_WINDOW = 12 +_COLUMN_TAIL_MIN = 6 +_COLUMN_JUMP = 0.15 + + +def split_column_blocks(answer: str, capture: dict, blocks: list[Block]) -> list[Block]: + """Split at sustained rightward/upward transitions in cached word peaks. + + Offsets stay in the original transcript and attention-grid coordinates. + Twelve preceding words must support a disjoint horizontal band. A tail + can have six words if they form coherent rows beyond that band. The + upward jump must exceed three typical line steps, allowing short columns + while excluding ordinary left-to-right line wraps. + Only prose is eligible, preserving image/table attention-unit contracts. + """ + units, per_block = units_for(answer, blocks) + sparse = capture["sparse_maps"] + gh, gw = capture["grid"] + result = [] + for block, indices in zip(blocks, per_block): + if block.type != "text" or len(indices) < 2 * _COLUMN_WINDOW: + result.append(block) + continue + valid, points = [], [] + for unit in indices: + if sparse["val"][unit]: + cell = sparse["idx"][unit][int(np.argmax(sparse["val"][unit]))] + valid.append(unit) + points.append([cell % gw + 0.5, cell // gw + 0.5]) + positions = np.asarray(points) + # Estimate line spacing in attention-grid cells. Small positive steps + # capture wraps; larger jumps can belong to a different region. + deltas = np.diff(positions[:, 1]) if len(positions) else np.array([]) + line_steps = deltas[(deltas > 0) & (deltas <= max(2, gh * 0.03))] + vertical_jump = ( + max(2.0, 3 * float(np.median(line_steps))) + if len(line_steps) + else _COLUMN_JUMP * gh + ) + cuts = [] + last = -_COLUMN_WINDOW + for index in range(_COLUMN_WINDOW, len(valid) - _COLUMN_TAIL_MIN + 1): + if ( + index - last < _COLUMN_WINDOW + or positions[index, 1] - positions[index - 1, 1] >= -vertical_jump + ): + continue + before = positions[index - _COLUMN_WINDOW : index] + after = positions[index : index + _COLUMN_WINDOW] + if len(after) < _COLUMN_WINDOW: + # Short tails need multiple coherent rows and every word to + # clear the preceding column's right edge (grid coordinates). + dy = np.diff(after[:, 1]) + if ( + np.ptp(after[:, 1]) < 1 + or np.any(dy < -1) + or after[:, 0].min() <= np.quantile(before[:, 0], 0.9) + ): + continue + if ( + np.quantile(after[:, 0], 0.1) > np.quantile(before[:, 0], 0.9) + and np.median(after[:, 1]) - np.median(before[:, 1]) < -vertical_jump + ): + cuts.append(units[valid[index]][0]) + last = index + boundaries = [block.start, *cuts, block.end] + result.extend( + Block(block.type, start, end) + for start, end in zip(boundaries, boundaries[1:]) + ) + return _split_short_openings(answer, capture, result) + + +def _split_short_openings( + answer: str, capture: dict, blocks: list[Block] +) -> list[Block]: + """Recover 4–11 opening words stranded at the foot of a previous column. + + Twelve following words must support a disjoint column above the opening. + Both windows follow row order; all coordinates are attention-grid cells. + Splits preserve transcript offsets and therefore cached attention indices. + """ + units, per_block = units_for(answer, blocks) + sparse = capture["sparse_maps"] + grid_width = capture["grid"][1] + result = [] + for block, indices in zip(blocks, per_block): + cut = None + if block.type == "text" and len(indices) >= 17: + points = [] + for unit in indices[:23]: + values = sparse["val"][unit] + if not values: + break + cell = sparse["idx"][unit][int(np.argmax(values))] + points.append([cell % grid_width, cell // grid_width]) + # All candidate cuts lie within the first 23 words. Reject ordinary + # same-column prose before reading the rest of its attention maps. + if len(points) == min(23, len(indices)): + horizontal = [point[0] for point in points] + if not any( + min(horizontal[index : index + 12]) > max(horizontal[:index]) + for index in range(4, min(12, len(indices) - 11)) + ): + result.append(block) + continue + for unit in indices[23:]: + values = sparse["val"][unit] + if not values: + break + cell = sparse["idx"][unit][int(np.argmax(values))] + points.append([cell % grid_width, cell // grid_width]) + if len(points) == len(indices): + positions = np.asarray(points) + steps = np.diff(positions[:, 1]) + steps = steps[(steps > 0) & (steps <= 3)] + jump = max(3, 3 * float(np.median(steps))) if len(steps) else 3 + for index in range(4, min(12, len(indices) - 11)): + before, after = positions[:index], positions[index : index + 12] + if ( + after[:, 0].min() <= before[:, 0].max() + or np.median(before[:, 1]) - np.median(after[:, 1]) <= jump + or any(np.any(np.diff(p[:, 1]) < -1) for p in (before, after)) + or any(np.ptp(p[:, 1]) > jump for p in (before, after)) + or any( + np.any(np.diff(p[:, 0])[np.diff(p[:, 1]) == 0] <= 0) + for p in (before, after) + ) + ): + continue + cut = units[indices[index]][0] + break + if cut is None: + result.append(block) + else: + result.extend( + [Block(block.type, block.start, cut), Block(block.type, cut, block.end)] + ) + return result diff --git a/parse_rl_utils/ocria_attention_grounding/context.py b/parse_rl_utils/ocria_attention_grounding/context.py new file mode 100644 index 0000000000000000000000000000000000000000..e1ebe133f5fb067a0ab596fe17f064ee23135e1f --- /dev/null +++ b/parse_rl_utils/ocria_attention_grounding/context.py @@ -0,0 +1,165 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Typography, shared-line profiles, and sparse support beyond the local patch.""" + +from .rust import get_rust + +import numpy as np + +from .blocks import Block +from .native import get_native + +_BLOCK_TYPES = ( + "text", + "list", + "heading", + "header", + "footer", + "page_number", + "table", + "image", + "code", + "formula", +) + + +def extended_features( + answer: str, + units: list[tuple[int, int]], + blocks: list[Block], + per_block: list[list[int]], + features: np.ndarray, + valid: list[int], + peaks: np.ndarray, + sparse: dict, + grid: tuple[int, int], +) -> np.ndarray: + """Append 51 features to the 53-feature context representation. + + Nearby word profiles share the current word's grid-row frame. Full-support + quantiles and threshold extents retain evidence beyond the local 5x5 patch. + All offsets use grid cells; no annotation or page-image input is accepted. + """ + gh, gw = grid + owners = {u: k for k, indices in enumerate(per_block) for u in indices} + lookup = {u: j for j, u in enumerate(valid)} + positions = np.full((len(units), 2), np.nan) + positions[valid] = peaks + # Each word profile is shared by up to 24 neighbors; normalize it once. + profiles = features[:, 9:34].reshape(-1, 5, 5).sum(2) + profiles /= np.maximum(profiles.sum(1), 1e-12)[:, None] + native = get_native() + pooled_profiles = ( + native.pool_profiles(positions, owners, valid, profiles) + if native is not None + else None + ) + rust = get_rust() + stats, packed = ( + rust.context_bounds(sparse, valid, peaks, gw) + if rust is not None + else (None, None) + ) + mass_stats = None + if packed: + masses = np.concatenate([row[2] for row in packed]) + starts = np.r_[ + 0, np.cumsum([len(row[2]) for row in packed[:-1]], dtype=np.intp) + ] + mass_stats = np.column_stack( + [ + np.maximum.reduceat(masses, starts), + -np.add.reduceat(masses * np.log(np.maximum(masses, 1e-12)), starts), + ] + ) + block_types = [ + [float(block.type == kind) for kind in _BLOCK_TYPES] for block in blocks + ] + typography: dict[str, list[float]] = {} + extras = [] + for row, u in enumerate(valid): + owner = owners[u] + word = answer[units[u][0] : units[u][1]] + glyphs = typography.get(word) + if glyphs is None: + length = max(1, len(word)) + glyphs = [ + sum(c.isupper() for c in word) / length, + sum(c.isdigit() for c in word) / length, + sum( + "\u2e80" <= c <= "\u9fff" or "\uac00" <= c <= "\ud7af" for c in word + ) + / length, + sum(c in "iljtf1" for c in word) / length, + sum(c.lower() in "mw" for c in word) / length, + ] + typography[word] = glyphs + px, py = peaks[row] + values = block_types[owner] + glyphs + values.extend( + [ + px / gw, + py / gh, + len(per_block[owner]), + (u - per_block[owner][0]) / max(1, len(per_block[owner]) - 1), + ] + ) + if pooled_profiles is not None: + values.extend(pooled_profiles[row].tolist()) + else: + pooled = np.zeros(7) + count = 0 + for neighbor in range(max(0, u - 12), min(len(units), u + 13)): + if ( + neighbor == u + or owners.get(neighbor) != owner + or neighbor not in lookup + or abs(positions[neighbor, 1] - py) > 1 + ): + continue + profile = profiles[lookup[neighbor]] + offset = int(round(positions[neighbor, 1] - py)) + pooled[1 + offset : 6 + offset] += profile + count += 1 + if count: + pooled /= count + values.extend([*pooled.tolist(), count]) + if stats is not None: + _, attention, mass = packed[row] + values.extend(stats[row].tolist()) + else: + indices = np.asarray(sparse["idx"][u]) + attention = np.asarray(sparse["val"][u]) + mass = attention / attention.sum() + xx, yy = indices % gw + 0.5, indices // gw + 0.5 + for coords, peak in ((xx, px), (yy, py)): + order = np.argsort(coords) + cdf = np.cumsum(mass[order]) + quantiles = np.searchsorted(cdf, (0.05, 0.25, 0.5, 0.75, 0.95)) + np.minimum(quantiles, len(order) - 1, out=quantiles) + values.extend((coords[order[quantiles]] - peak).tolist()) + for threshold in (0.1, 0.3, 0.6): + keep = attention >= threshold * attention.max() + values.extend( + [ + float(xx[keep].min() - 0.5 - px), + float(yy[keep].min() - 0.5 - py), + float(xx[keep].max() + 0.5 - px), + float(yy[keep].max() + 0.5 - py), + ] + ) + if mass_stats is not None: + values.extend(mass_stats[row].tolist()) + else: + values.extend( + [ + float(mass.max()), + float(-(mass * np.log(np.maximum(mass, 1e-12))).sum()), + ] + ) + extras.append(values) + extra_array = np.asarray(extras).reshape(len(valid), 51) + # Quantile and threshold offsets share the same grid-cell clipping bounds. + np.clip(extra_array[:, 27:49], -20, 20, out=extra_array[:, 27:49]) + return np.column_stack([features, extra_array]) diff --git a/parse_rl_utils/ocria_attention_grounding/density_kernels.rs b/parse_rl_utils/ocria_attention_grounding/density_kernels.rs new file mode 100644 index 0000000000000000000000000000000000000000..90d3f602059acf8a31a45cc4aec940dfb7a2c8bd --- /dev/null +++ b/parse_rl_utils/ocria_attention_grounding/density_kernels.rs @@ -0,0 +1,117 @@ +// Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +// Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +// This is not open-source software: see the license for permitted uses. +use std::slice; +// Caller supplies contiguous float32 attention and same-shape float64 density. +// Seed is a positive maximum; bounds are exclusive cell edges in x/y order. +#[no_mangle] +pub unsafe extern "C" fn add_component_centroid( + h: usize, + w: usize, + map: *const f32, + seed: usize, + density: *mut f64, + bounds: *mut i64, + center: *mut f64, +) -> usize { + let m = slice::from_raw_parts(map, h * w); + let d = slice::from_raw_parts_mut(density, h * w); + + let threshold = 0.3f32 * m[seed]; + let mut total = 0.0f64; + let mut visited = vec![false; m.len()]; + let mut queue = vec![seed]; + visited[seed] = true; + let mut k = 0; + let mut x0 = seed % w; + let mut y0 = seed / w; + let mut x1 = x0 + 1; + let mut y1 = y0 + 1; + while k < queue.len() { + let j = queue[k]; + k += 1; + total += m[j] as f64; + let x = j % w; + let y = j / w; + x0 = x0.min(x); + y0 = y0.min(y); + x1 = x1.max(x + 1); + y1 = y1.max(y + 1); + for yy in y.saturating_sub(1)..(y + 2).min(h) { + for xx in x.saturating_sub(1)..(x + 2).min(w) { + let p = yy * w + xx; + if !visited[p] && m[p] >= threshold { + visited[p] = true; + queue.push(p); + } + } + } + } + for j in queue { + d[j] += m[j] as f64 / total; + } + for (k, v) in [x0, y0, x1, y1].iter().enumerate() { + *bounds.add(k) = *v as i64; + } + let y = seed / w; + let x = seed % w; + let mut mass = 0.0; + let mut weighted_x = 0.0; + let mut weighted_y = 0.0; + for yy in y.saturating_sub(1)..(y + 2).min(h) { + for xx in x.saturating_sub(1)..(x + 2).min(w) { + let value = m[yy * w + xx] as f64; + mass += value; + weighted_x += value * (xx as f64 + 0.5); + weighted_y += value * (yy as f64 + 0.5); + } + } + *center = weighted_x / mass; + *center.add(1) = weighted_y / mass; + seed +} + +// Sparse rows share one scratch grid; accumulation follows transcript order. +// Python validates offsets, cell indices, seeds, and output capacities. +#[no_mangle] +pub unsafe extern "C" fn add_components( + h: usize, + w: usize, + words: usize, + offsets: *const i64, + indices: *const i64, + values: *const f32, + seeds: *const i64, + density: *mut f64, + bounds: *mut i64, + centers: *mut f64, +) -> bool { + let offsets = slice::from_raw_parts(offsets, words + 1); + let indices = slice::from_raw_parts(indices, offsets[words] as usize); + let values = slice::from_raw_parts(values, indices.len()); + let mut grid = vec![0.0f32; h * w]; + for u in 0..words { + let start = offsets[u] as usize; + let end = offsets[u + 1] as usize; + for j in start..end { + grid[indices[j] as usize] = values[j]; + } + let seed = *seeds.add(u) as usize; + if !grid[seed].is_finite() || grid[seed] <= 0.0 { + return false; + } + add_component_centroid( + h, + w, + grid.as_ptr(), + seed, + density, + bounds.add(u * 4), + centers.add(u * 2), + ); + for j in start..end { + grid[indices[j] as usize] = 0.0; + } + } + true +} diff --git a/parse_rl_utils/ocria_attention_grounding/geometry.py b/parse_rl_utils/ocria_attention_grounding/geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..0a6dace7fa603c23dc31eaa6f4837e838f67d466 --- /dev/null +++ b/parse_rl_utils/ocria_attention_grounding/geometry.py @@ -0,0 +1,102 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Conservative reading-order paths for horizontal left-to-right prose. + +Coordinates are image pixels. Word indices remain in transcript order, so a +skipped attention outlier does not delete text. Unsupported layouts fall back +to the existing spatial clustering; tables, formulas and code bypass this pass. +""" + +import statistics + +from .rust import get_rust + +WordBox = list[float] + + +def paragraph_paths(boxes: list[WordBox]) -> list[list[int]] | None: + """Return supported word paths, splitting column continuations when justified. + + Nearby words form spatial components. Within each component a longest path + must move right on a line or wrap onto a nearby lower line. At least 60% of + words must support the result. Separate columns need three words each and + non-interleaving transcript spans; otherwise keep only a dominant path. + """ + rust = get_rust() + if rust is not None: + return rust.paragraph_paths(boxes) + n = len(boxes) + if n < 3: + return None + height = max(1.0, statistics.median(b[3] - b[1] for b in boxes)) + parents = list(range(n)) + + def root(i: int) -> int: + while parents[i] != i: + parents[i] = parents[parents[i]] + i = parents[i] + return i + + # Proximity establishes candidate columns independently of transcript order. + # A nearby wrong word can still belong here; the ordered path rejects it. + for i, a in enumerate(boxes): + for j in range(i): + b = boxes[j] + dx = max(a[0] - b[2], b[0] - a[2], 0.0) + dy = max(a[1] - b[3], b[1] - a[3], 0.0) + if dx <= 4 * height and dy <= 2.5 * height: + parents[root(i)] = root(j) + components: dict[int, list[int]] = {} + for i in range(n): + components.setdefault(root(i), []).append(i) + + paths: list[list[int]] = [] + for indices in components.values(): + lengths = {i: 1 for i in indices} + previous: dict[int, int] = {} + for pos, i in enumerate(indices): + b = boxes[i] + for j in indices[:pos]: + a = boxes[j] + overlap = min(a[3], b[3]) - max(a[1], b[1]) + same_line = overlap >= 0.5 * min(a[3] - a[1], b[3] - b[1]) + if same_line: + follows = ( + b[0] >= a[0] + 0.2 * height + and -0.5 * height <= b[0] - a[2] <= 4 * height + ) + else: + follows = ( + b[1] >= a[1] + 0.5 * height + and b[1] - a[3] <= 2.5 * height + and b[0] < a[2] + ) + if follows and lengths[j] + 1 > lengths[i]: + lengths[i] = lengths[j] + 1 + previous[i] = j + end = max(indices, key=lengths.__getitem__) + path = [end] + while path[-1] in previous: + path.append(previous[path[-1]]) + path.reverse() + if len(path) >= 3: + paths.append(path) + if not paths: + return None + paths.sort(key=lambda p: p[0]) + if sum(map(len, paths)) < 0.6 * n: + return None + + # A column jump is supported by whole runs, not a single distant word. + # Interleaved components or a jump down to unrelated text are ambiguous. + for left, right in zip(paths, paths[1:]): + gutter = min(boxes[i][0] for i in right) - max(boxes[i][2] for i in left) + if ( + left[-1] >= right[0] + or gutter < height + or boxes[right[0]][1] > boxes[left[-1]][1] + ): + dominant = max(paths, key=len) + return [dominant] if len(dominant) >= 0.6 * n else None + return paths diff --git a/parse_rl_utils/ocria_attention_grounding/geometry_kernels.rs b/parse_rl_utils/ocria_attention_grounding/geometry_kernels.rs new file mode 100644 index 0000000000000000000000000000000000000000..6887a7d52e38e6cc6574cf3dd5bac340772e612f --- /dev/null +++ b/parse_rl_utils/ocria_attention_grounding/geometry_kernels.rs @@ -0,0 +1,142 @@ +// Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +// Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +// This is not open-source software: see the license for permitted uses. +use std::slice; +fn root(parents: &mut [usize], mut i: usize) -> usize { + while parents[i] != i { + parents[i] = parents[parents[i]]; + i = parents[i]; + } + i +} +// The Python boundary provides finite N x 4 boxes in pixel-edge coordinates. +// Output indices retain transcript order; offsets delimit at most N paths. +#[no_mangle] +pub unsafe extern "C" fn paragraph_paths( + n: usize, + boxes: *const f64, + output: *mut i64, + offsets: *mut i64, +) -> usize { + if n < 3 { + return 0; + } + let flat = slice::from_raw_parts(boxes, n * 4); + let b: Vec<&[f64]> = flat.chunks_exact(4).collect(); + let mut heights: Vec = b.iter().map(|a| a[3] - a[1]).collect(); + heights.sort_by(|a, b| a.total_cmp(b)); + let h = if n % 2 == 1 { + heights[n / 2] + } else { + (heights[n / 2 - 1] + heights[n / 2]) / 2.0 + }; + let h = h.max(1.0); + let mut parents: Vec = (0..n).collect(); + for i in 0..n { + for j in 0..i { + let a = b[i]; + let z = b[j]; + let dx = (a[0] - z[2]).max(z[0] - a[2]).max(0.0); + let dy = (a[1] - z[3]).max(z[1] - a[3]).max(0.0); + if dx <= 4.0 * h && dy <= 2.5 * h { + let r = root(&mut parents, i); + let q = root(&mut parents, j); + parents[r] = q; + } + } + } + let mut keys = Vec::new(); + let mut groups: Vec> = Vec::new(); + for i in 0..n { + let r = root(&mut parents, i); + if let Some(k) = keys.iter().position(|&x| x == r) { + groups[k].push(i); + } else { + keys.push(r); + groups.push(vec![i]); + } + } + let mut paths: Vec> = Vec::new(); + for ids in groups { + let mut lengths = vec![1; n]; + let mut prev = vec![usize::MAX; n]; + for (pos, &i) in ids.iter().enumerate() { + for &j in &ids[..pos] { + let a = b[j]; + let z = b[i]; + let overlap = a[3].min(z[3]) - a[1].max(z[1]); + let same = overlap >= 0.5 * (a[3] - a[1]).min(z[3] - z[1]); + let follows = if same { + z[0] >= a[0] + 0.2 * h && z[0] - a[2] >= -0.5 * h && z[0] - a[2] <= 4.0 * h + } else { + z[1] >= a[1] + 0.5 * h && z[1] - a[3] <= 2.5 * h && z[0] < a[2] + }; + if follows && lengths[j] + 1 > lengths[i] { + lengths[i] = lengths[j] + 1; + prev[i] = j; + } + } + } + let mut end = ids[0]; + for &i in &ids { + if lengths[i] > lengths[end] { + end = i; + } + } + let mut path = vec![end]; + while prev[end] != usize::MAX { + end = prev[end]; + path.push(end); + } + path.reverse(); + if path.len() >= 3 { + paths.push(path); + } + } + if paths.is_empty() { + return 0; + } + paths.sort_by_key(|p| p[0]); + if (paths.iter().map(|p| p.len()).sum::() as f64) < 0.6 * n as f64 { + return 0; + } + let mut ambiguous = false; + for pair in paths.windows(2) { + let left = &pair[0]; + let right = &pair[1]; + let gutter = right.iter().map(|&i| b[i][0]).fold(f64::INFINITY, f64::min) + - left + .iter() + .map(|&i| b[i][2]) + .fold(f64::NEG_INFINITY, f64::max); + if left[left.len() - 1] >= right[0] + || gutter < h + || b[right[0]][1] > b[left[left.len() - 1]][1] + { + ambiguous = true; + break; + } + } + if ambiguous { + let mut best = 0; + for i in 1..paths.len() { + if paths[i].len() > paths[best].len() { + best = i; + } + } + if (paths[best].len() as f64) < 0.6 * n as f64 { + return 0; + } + paths = vec![paths[best].clone()]; + } + let mut count = 0; + *offsets = 0; + for (k, path) in paths.iter().enumerate() { + for &i in path { + *output.add(count) = i as i64; + count += 1; + } + *offsets.add(k + 1) = count as i64; + } + paths.len() +} diff --git a/parse_rl_utils/ocria_attention_grounding/headers.py b/parse_rl_utils/ocria_attention_grounding/headers.py new file mode 100644 index 0000000000000000000000000000000000000000..58b359409258b82d55352411e4341c661cbcef3e --- /dev/null +++ b/parse_rl_utils/ocria_attention_grounding/headers.py @@ -0,0 +1,80 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Separate navigation sections using transcript delimiters and word attention.""" + +import re + +import numpy as np + +from .blocks import Block +from .io import units_for + + +def split_navigation_headers( + answer: str, capture: dict, blocks: list[Block] +) -> list[Block]: + """Split pipe-delimited headers at spatial gaps between same-line word groups. + + Transcript offsets and attention-unit order stay fixed. Numeric menu labels + attach to their following section; peaks and gap thresholds use grid cells. + """ + if not any( + b.type == "header" and answer[b.start : b.end].count("|") >= 2 for b in blocks + ): + return blocks + units, _ = units_for(answer, blocks) + sp = capture["sparse_maps"] + gw = capture["grid"][1] + result = [] + for block in blocks: + text = answer[block.start : block.end] + if block.type != "header" or text.count("|") < 2: + result.append(block) + continue + cuts = [ + block.start, + *[block.start + m.end() for m in re.finditer(r"\|", text)], + block.end, + ] + segments = [] + pending = None + for lo, hi in zip(cuts, cuts[1:]): + clean = re.sub(r"<[^>]+>|[|*]", "", answer[lo:hi]).strip() + if pending is None: + pending = lo + if re.fullmatch(r"\d{1,2}", clean): + continue + segments.append((pending, hi)) + pending = None + if pending is not None: + if segments: + segments[-1] = (segments[-1][0], block.end) + else: + segments = [(pending, block.end)] + if len(segments) < 3: + result.append(block) + continue + bands = [] + for lo, hi in segments: + ps = [] + for u, (aa, zz) in enumerate(units): + if lo <= aa and zz <= hi and sp["has"][u] and sp["val"][u]: + peak = sp["idx"][u][int(np.argmax(sp["val"][u]))] + ps.append([peak % gw + 0.5, peak // gw + 0.5]) + bands.append(np.array(ps).reshape(-1, 2)) + boundaries = [] + for j in range(1, len(segments)): + left, right = bands[j - 1], bands[j] + if len(left) < 2 or len(right) < 2: + continue + if abs(np.median(left[:, 1]) - np.median(right[:, 1])) > 1.5: + continue + if np.quantile(right[:, 0], 0.1) - np.quantile(left[:, 0], 0.9) > 2: + boundaries.append(segments[j][0]) + if not boundaries: + result.append(block) + continue + cuts = [block.start, *boundaries, block.end] + result.extend(Block(block.type, lo, hi) for lo, hi in zip(cuts, cuts[1:])) + return result diff --git a/parse_rl_utils/ocria_attention_grounding/headings.py b/parse_rl_utils/ocria_attention_grounding/headings.py new file mode 100644 index 0000000000000000000000000000000000000000..1c56f24c7ae16abd59de30967dc9c0c97821c64f --- /dev/null +++ b/parse_rl_utils/ocria_attention_grounding/headings.py @@ -0,0 +1,227 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Join consecutive lines of a heading in visible-page coordinates.""" + +import re + +_HEADING_LEVEL = re.compile(r"^\s*(#{1,6})(?:\s|$)") + + +def merge_heading_lines(items: list[dict]) -> list[dict]: + """Preserve ordered Markdown while joining aligned, equally ranked headings. + + Call after PDF crop/rotation conversion. All distances use the visible page's + units and are normalized by line height. Compare successive original lines, + not accumulated group bounds, so a multiline heading can grow consistently. + """ + groups: list[list[dict]] = [] + for item in items: + if ( + groups + and item["type"] == "Section-header" + and groups[-1][-1]["type"] == "Section-header" + ): + previous = groups[-1][-1] + a, b = previous["bbox"], item["bbox"] + height = min(a["h"], b["h"]) + gap = b["y"] - a["y"] - a["h"] + levels = [_HEADING_LEVEL.match(v["md"]) for v in (previous, item)] + ranks = [len(m.group(1)) if m else 0 for m in levels] + # Center estimates for wide lines can differ by more than a line height. + # Scale tolerance by the shorter line so neighboring columns stay apart. + aligned = abs(a["x"] + a["w"] / 2 - b["x"] - b["w"] / 2) <= max( + height, 0.25 * min(a["w"], b["w"]) + ) + if ( + ranks[0] == ranks[1] + and height > 0 + and max(a["h"], b["h"]) <= 1.5 * height + and -0.3 * height <= gap <= height + and aligned + ): + groups[-1].append(item) + continue + groups.append([item]) + result = [] + for group in groups: + if len(group) == 1: + result.extend(group) + continue + boxes = [item["bbox"] for item in group] + x, y = min(b["x"] for b in boxes), min(b["y"] for b in boxes) + right = max(b["x"] + b["w"] for b in boxes) + bottom = max(b["y"] + b["h"] for b in boxes) + box = {**boxes[0], "x": x, "y": y, "w": right - x, "h": bottom - y} + md = "\n".join(item["md"] for item in group) + result.append( + { + **group[0], + "bbox": box, + "layout_segments": [dict(box)], + "md": md, + "value": md, + } + ) + return result + + +def merge_numeric_callouts(items: list[dict]) -> list[dict]: + """Join a numeric heading and its short aligned label in page coordinates. + + The label must follow below, within two label heights, and be no taller + than the number. Preserve both Markdown spans and their union box as text. + """ + kept: list[dict] = [] + for item in items: + if ( + kept + and kept[-1]["type"] == "Section-header" + and item["type"] == "Text" + and len(item["md"]) <= 100 + and len(item["md"].split()) <= 15 + ): + previous = kept[-1] + value = re.sub(r"^#{1,6}\s*", "", previous["md"]) + value = value.replace("*", "").replace("_", "").strip() + a, b = previous["bbox"], item["bbox"] + gap = b["y"] - a["y"] - a["h"] + overlap = min(a["x"] + a["w"], b["x"] + b["w"]) - max(a["x"], b["x"]) + if ( + re.fullmatch(r"[$€£]?\d[\d,.]*(?:%|[kKmMbB])?\+?", value) + and 0 <= gap <= 2 * b["h"] + and b["h"] <= a["h"] + and overlap >= 0.5 * min(a["w"], b["w"]) + ): + x, y = min(a["x"], b["x"]), min(a["y"], b["y"]) + box = { + **b, + "x": x, + "y": y, + "w": max(a["x"] + a["w"], b["x"] + b["w"]) - x, + "h": max(a["y"] + a["h"], b["y"] + b["h"]) - y, + } + md = previous["md"] + "\n" + item["md"] + kept[-1] = { + **item, + "md": md, + "value": md, + "bbox": box, + "layout_segments": [dict(box)], + } + continue + kept.append(item) + return kept + + +def trim_paragraph_heading_overlap(items: list[dict]) -> None: + """Trim shallow paragraph incursions into external horizontal headings. + + Boxes use visible-page coordinates. A heading must be at least twice as wide + as tall: elongated vertical predictions are unreliable boundary evidence. + Original paragraph edges anchor every comparison so trimming cannot cascade. + """ + headings = [ + item["bbox"] + for item in items + if item["type"] == "Section-header" + and item["bbox"]["w"] >= 2 * item["bbox"]["h"] + ] + for item in items: + if item["type"] != "Text": + continue + box = item["bbox"] + top, bottom = box["y"], box["y"] + box["h"] + new_top, new_bottom = top, bottom + for heading in headings: + overlap = min(box["x"] + box["w"], heading["x"] + heading["w"]) - max( + box["x"], heading["x"] + ) + if overlap <= 0 or overlap < 0.75 * heading["w"]: + continue + center = heading["y"] + heading["h"] / 2 + end = heading["y"] + heading["h"] + if center < top and top < end < top + 0.2 * box["h"]: + new_top = max(new_top, end) + if center > bottom and bottom - 0.2 * box["h"] < heading["y"] < bottom: + new_bottom = min(new_bottom, heading["y"]) + if new_top != top or new_bottom != bottom: + trimmed = {**box, "y": new_top, "h": new_bottom - new_top} + item["bbox"] = trimmed + item["layout_segments"] = [trimmed] + + +def merge_bold_heading_continuations(answer: str, items: list[dict]) -> list[dict]: + """Join a heading with its adjacent bold source line in visible-page units. + + Source adjacency excludes paragraph breaks. Horizontal overlap and a gap + of at most two continuation heights restrict joining to nearby lines. + The union represents the full label while preserving its Markdown. + """ + kept: list[dict] = [] + for item in items: + if ( + kept + and kept[-1]["type"] == "Section-header" + and item["type"] == "Text" + and re.fullmatch(r"\*\*[^\n]+\*\*", item["md"].strip()) + ): + previous = kept[-1] + a, b = previous["bbox"], item["bbox"] + gap = b["y"] - a["y"] - a["h"] + overlap = min(a["x"] + a["w"], b["x"] + b["w"]) - max(a["x"], b["x"]) + markdown = previous["md"].strip() + "\n" + item["md"].strip() + if ( + markdown in answer + and 0 <= gap <= 2 * b["h"] + and overlap >= 0.5 * min(a["w"], b["w"]) + ): + x, y = min(a["x"], b["x"]), min(a["y"], b["y"]) + box = { + **a, + "x": x, + "y": y, + "w": max(a["x"] + a["w"], b["x"] + b["w"]) - x, + "h": max(a["y"] + a["h"], b["y"] + b["h"]) - y, + } + kept[-1] = { + **previous, + "md": markdown, + "value": markdown, + "bbox": box, + "layout_segments": [dict(box)], + } + continue + kept.append(item) + return kept + + +def expand_table_to_embedded_heading(items: list[dict]) -> None: + """Include an embedded title's edges in the following table's page-space box. + + Attention can cover a chart's plot while missing its title overhang. Keep + the heading's precise box and text independent, expanding only a table + that contains its center and overlaps most of its width. + """ + for heading, table in zip(items, items[1:]): + if heading["type"] != "Section-header" or table["type"] != "Table": + continue + a, b = heading["bbox"], table["bbox"] + cx, cy = a["x"] + a["w"] / 2, a["y"] + a["h"] / 2 + overlap = min(a["x"] + a["w"], b["x"] + b["w"]) - max(a["x"], b["x"]) + if ( + b["x"] <= cx <= b["x"] + b["w"] + and b["y"] <= cy <= b["y"] + b["h"] + and overlap >= 0.75 * a["w"] + and b["h"] >= 3 * a["h"] + ): + x, y = min(a["x"], b["x"]), min(a["y"], b["y"]) + box = { + **b, + "x": x, + "y": y, + "w": max(a["x"] + a["w"], b["x"] + b["w"]) - x, + "h": max(a["y"] + a["h"], b["y"] + b["h"]) - y, + } + table["bbox"] = box + table["layout_segments"] = [dict(box)] diff --git a/parse_rl_utils/ocria_attention_grounding/hf_adapter.py b/parse_rl_utils/ocria_attention_grounding/hf_adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..369dfedc056481469f8c86e1eec7659f3f784b25 --- /dev/null +++ b/parse_rl_utils/ocria_attention_grounding/hf_adapter.py @@ -0,0 +1,67 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Optional bridge from the public Transformers capture to the pixel-free backend.""" + +import time +from typing import Any, Protocol + +import numpy as np + +from .blocks import split_blocks +from .io import units_for + + +class LayoutBackend(Protocol): + def __call__(self, *, answer: str, attention: dict) -> dict: ... + + +def ground_fast_layout( + grounder: Any, + image: Any, + answer: str, + *, + backend: LayoutBackend, + attention: dict | None = None, +) -> dict: + """Capture with public OCRia when needed; cached calls only inspect image.size. + + Use this backend's token spans, not the public package's block parser: sparse + row indices must follow exactly the transcript units consumed by ground_cached. + Retain 512 cells per unit, matching our replay cache, rounded to six decimals. + """ + capture_ms = 0.0 + source = "precomputed" + if attention is None: + started = time.perf_counter() + units, _ = units_for(answer, split_blocks(answer)) + width, height = image.size + if units: + maps, grid, has = grounder.unit_maps(image, answer, units) + flat = maps.reshape(len(units), -1) + indices, values = [], [] + for row, valid in zip(flat, has, strict=True): + count = min(512, len(row)) + top = ( + np.argpartition(-row, count - 1)[:count] + if valid + else np.empty(0, dtype=np.int64) + ) + indices.append(top.tolist()) + values.append(np.round(row[top].astype(np.float32), 6).tolist()) + else: + grid, has, indices, values = (1, 1), [], [], [] + attention = { + "width": width, + "height": height, + "grid": list(grid), + "sparse_maps": {"idx": indices, "val": values, "has": list(has)}, + } + capture_ms = (time.perf_counter() - started) * 1000 + source = "teacher-forced" + elif tuple(image.size) != (attention["width"], attention["height"]): + raise ValueError("Image dimensions differ from the attention coordinate frame") + page = backend(answer=answer, attention=attention) + page["attention_source"] = source + page["timings_ms"]["attention_capture"] = capture_ms + return page diff --git a/parse_rl_utils/ocria_attention_grounding/io.py b/parse_rl_utils/ocria_attention_grounding/io.py new file mode 100644 index 0000000000000000000000000000000000000000..24646438f688b9c36917ebd74bcbd1cae44e7b3e --- /dev/null +++ b/parse_rl_utils/ocria_attention_grounding/io.py @@ -0,0 +1,267 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Transcript spans, sparse attention decoding, and layout serialization.""" + +import re +import numpy as np +from .blocks import Block, split_blocks +from .words import word_spans + +_FURN_TAG = re.compile(r"") +_HEADING_PREFIX = re.compile(r"^#{1,6}\s+") + + +def merge_duplicate_text(items: list[dict]) -> list[dict]: + """Merge identical text predictions occupying the same page region. + + Formatting markers and whitespace do not distinguish duplicate text; + punctuation, numbers and element types do. Keep the first occurrence's + content with the tighter of two boxes whose intersection-over-union exceeds + one half. Distinct locations remain separate occurrences. + """ + kept: list[dict] = [] + seen: dict[tuple[str, str], list[int]] = {} + for item in items: + typ = item["type"] + if typ not in {"Text", "Section-header", "Page-header", "Page-footer"}: + kept.append(item) + continue + text = _HEADING_PREFIX.sub("", item["md"].strip()) + text = text.replace("**", "").replace("__", "").strip("*`_ \n") + key = (typ, " ".join(text.casefold().split())) + if len(key[1]) < 12: + kept.append(item) + continue + box = item["bbox"] + area = box["w"] * box["h"] + for index in seen.get(key, []): + old = kept[index] + other = old["bbox"] + other_area = other["w"] * other["h"] + intersection = max( + 0, + min(box["x"] + box["w"], other["x"] + other["w"]) + - max(box["x"], other["x"]), + ) * max( + 0, + min(box["y"] + box["h"], other["y"] + other["h"]) + - max(box["y"], other["y"]), + ) + if intersection / max(1e-12, area + other_area - intersection) <= 0.5: + continue + if area < other_area: + kept[index] = { + **old, + "bbox": box, + "layout_segments": item["layout_segments"], + } + break + else: + seen.setdefault(key, []).append(len(kept)) + kept.append(item) + return kept + + +def element_text(answer: str, start: int, end: int) -> str: + """Return scored element text while retaining raw spans for attention lookup.""" + return _FURN_TAG.sub("", answer[start:end]).strip() + + +def units_for( + answer: str, blocks: list[Block] +) -> tuple[list[tuple[int, int]], list[list[int]]]: + """Attention units and, per block, the indices of its units: every content word inside the block; an image + block is one unit (its whole reference), because the picture it points at has no words to snap to.""" + spans = word_spans(answer) + units: list[tuple[int, int]] = [] + per_block: list[list[int]] = [] + k = 0 + for b in blocks: + mine: list[int] = [] + if b.type == "image": + mine.append(len(units)) + units.append((b.start, b.end)) + per_block.append(mine) + continue + while k < len(spans) and spans[k][0] < b.start: + k += 1 + j = k + while j < len(spans) and spans[j][1] <= b.end: + mine.append(len(units)) + units.append((spans[j][0], spans[j][1])) + j += 1 + per_block.append(mine) + return units, per_block + + +def dense_maps(sparse: dict, grid: tuple[int, int]) -> tuple[np.ndarray, np.ndarray]: + """Inverse of `sparsify` (cells outside the kept top-k are 0).""" + gh, gw = grid + maps = np.zeros((len(sparse["idx"]), gh * gw), np.float32) + for u, (i, v) in enumerate(zip(sparse["idx"], sparse["val"])): + if i: + maps[u, i] = v + return maps.reshape(-1, gh, gw), np.array(sparse["has"], bool) + + +class SparseWordMaps: + """Sparse float32 maps with one borrowed grid, valid until the next lookup.""" + + def __init__(self, sparse: dict, grid: tuple[int, int]) -> None: + self._scratch = np.zeros(grid, dtype=np.float32) + self._last = np.empty(0, dtype=np.intp) + self.indices = [] + self.values = [] + self.peaks = np.zeros(len(sparse["idx"]), dtype=np.intp) + self.maxima = np.zeros(len(sparse["idx"]), dtype=np.float32) + for u, (indices, values) in enumerate(zip(sparse["idx"], sparse["val"])): + # Dense scatter keeps the last occurrence of a repeated cell. + if len(set(indices)) != len(indices): + cells = dict(zip(indices, values)) + indices, values = list(cells), list(cells.values()) + ix = np.asarray(indices, dtype=np.intp) + mass = np.asarray(values, dtype=np.float32) + self.indices.append(ix) + self.values.append(mass) + lengths = np.asarray([len(v) for v in self.values], dtype=np.intp) + valid = np.flatnonzero(lengths) + if len(valid): + mass = np.concatenate(self.values) + indices = np.concatenate(self.indices) + starts = np.r_[0, np.cumsum(lengths[valid][:-1])] + maxima = np.maximum.reduceat(mass, starts) + if not np.isfinite(maxima).all(): + raise ValueError("Sparse word attention must have a finite maximum") + # Resolve float32 ties by the first cell in dense grid order. + candidates = np.where( + mass == np.repeat(maxima, lengths[valid]), indices, grid[0] * grid[1] + ) + peaks = np.minimum.reduceat(candidates, starts) + positive = maxima > 0 + self.maxima[valid[positive]] = maxima[positive] + self.peaks[valid[positive]] = peaks[positive] + + def __getitem__(self, unit: int) -> np.ndarray: + self._scratch.flat[self._last] = 0 + self._scratch.flat[self.indices[unit]] = self.values[unit] + self._last = self.indices[unit] + return self._scratch + + +_V2_TYPE = { + "text": ("Text", "text"), + "heading": ("Section-header", "paragraph_title"), + "table": ("Table", "table"), + "image": ("Picture", "image"), + "header": ("Page-header", "header"), + "footer": ("Page-footer", "footer"), +} + + +def to_layout_page( + answer: str, + elements: list[dict], + width: float, + height: float, + scale: float = 1.0, + page_md: str = "", +) -> dict: + """llamacloud-bench / ParseBench `layout_pages` entry. Boxes are x, y, w, h in the page's own units (pixels x + `scale`; use 72 / DPI for PDF points), each item with one `layout_segments` entry equal to its box, because + the v2 layout scorer ignores items without layout-aware segments.""" + items = [] + for el in elements: + if el["box"] is None: + continue + x0, y0, x1, y1 = (v * scale for v in el["box"]) + if x1 <= x0 or y1 <= y0: + continue + md = element_text(answer, el["start"], el["end"]) + if el.get("close_table"): + md += "" + typ, label = _V2_TYPE.get(el["type"], _V2_TYPE["text"]) + seg = {"x": x0, "y": y0, "w": x1 - x0, "h": y1 - y0, "label": label} + items.append( + { + "type": typ, + "md": md, + "value": md, + "bbox": dict(seg), + "layout_segments": [seg], + } + ) + return { + "page_number": 1, + "width": width * scale, + "height": height * scale, + "md": page_md, + "items": items, + } + + +def join_paragraph_segments(answer: str, items: list[dict]) -> list[dict]: + """Keep transcript paragraphs as logical items with indexed spatial segments. + + Adjacent text fragments must exactly reconstruct one original paragraph. + Segment indices are inclusive offsets in the reconstructed Markdown, while + boxes retain the page coordinate frame supplied by the caller. + """ + paragraphs = {} + for block in split_blocks(answer): + if block.type == "text": + markdown = element_text(answer, block.start, block.end) + paragraphs["".join(markdown.split())] = markdown + texts = ["".join(item["md"].split()) for item in items] + result = [] + index = 0 + while index < len(items): + item = items[index] + stop = None + if item["type"] == "Text" and texts[index] not in paragraphs: + joined = [] + # Bound the search for a paragraph crossing several columns. + for end in range(index, min(index + 8, len(items))): + if ( + items[end]["type"] != "Text" + or len(items[end]["layout_segments"]) != 1 + ): + break + joined.append(texts[end]) + if end > index and "".join(joined) in paragraphs: + stop = end + 1 + break + if stop is None: + result.append(item) + index += 1 + continue + markdown = paragraphs["".join(texts[index:stop])] + # Map the whitespace-free match back to the untouched source Markdown. + # Column cuts can fall beside formatting markers, not just spaces. + offsets = [offset for offset, char in enumerate(markdown) if not char.isspace()] + segments = [] + position = 0 + for piece, text in zip(items[index:stop], texts[index:stop]): + segments.append( + { + **piece["layout_segments"][0], + "start_index": offsets[position], + "end_index": offsets[position + len(text) - 1], + } + ) + position += len(text) + x = min(segment["x"] for segment in segments) + y = min(segment["y"] for segment in segments) + x1 = max(segment["x"] + segment["w"] for segment in segments) + y1 = max(segment["y"] + segment["h"] for segment in segments) + result.append( + { + **item, + "md": markdown, + "value": markdown, + "bbox": {**item["bbox"], "x": x, "y": y, "w": x1 - x, "h": y1 - y}, + "layout_segments": segments, + } + ) + index = stop + return result diff --git a/parse_rl_utils/ocria_attention_grounding/learned.py b/parse_rl_utils/ocria_attention_grounding/learned.py new file mode 100644 index 0000000000000000000000000000000000000000..e6930421660224aad616b42a8feb61c945f12865 --- /dev/null +++ b/parse_rl_utils/ocria_attention_grounding/learned.py @@ -0,0 +1,887 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Sub-cell word boundaries from attention, composed with conservative block grouping.""" + +from bisect import bisect_left, bisect_right +from typing import Protocol +import re + +from .predict import predict + +import numpy as np + +from .headers import split_navigation_headers +from .columns import split_column_blocks +from .native import get_native +from .blocks import split_blocks +from .bullet_tables import split_bullet_tables +from .context import extended_features +from .io import SparseWordMaps, dense_maps, element_text, units_for +from .orientation import ( + coherent_rotated_words, + rotate_attention_clockwise, + vertical_text_spans, +) +from .rectangles import RectangleConfig, rectangle_boxes +from .pictures import PicturePredictor, refine_pictures +from .rust import get_rust +from .words import norm +from .regions import ( + HeadingGlyphRegionBlend, + contextual_region_features, + heading_glyph_features, + region_features, +) +from .tables import TablePredictor, refine_tables, refine_table_word_boxes +from .repeated import recover_repeated_paragraphs +from .peaks import PeakPredictor, select_word_peaks + +_INLINE_IMAGE_REFERENCE = re.compile(r"!\[[^\]\n]+\]") + +_NUMERIC_WORD = re.compile(r"[\s*$€£+\d.,%−-]+") + +BASE_CONFIG = RectangleConfig( + keep_tables=True, + fit_lines=True, + font_height=2.2, + anchor_fraction=0.25, + connected_words=True, + image_quantile=0.15, + y_offset=0.125, + guard_expansion=1.5, + heading_x_scale=1.05, + text_x_scale=1.025, + furniture_y_inset=0.125, + furniture_x_scale=1.1, + fit_blend_x=0.75, + fit_blend_y=0.75, + image_text_suppression=16, +) +_TEXT_TYPES = {"text", "list", "heading", "header", "footer"} + + +class Predictor(Protocol): + def predict(self, features: np.ndarray) -> np.ndarray: ... + + +def attention_features( + answer: str, + units: list[tuple[int, int]], + sparse: dict, + grid: tuple[int, int], + anchors: dict[int, int] | None = None, +) -> tuple[np.ndarray, list[int], np.ndarray]: + """Return features, retained unit indices, and peak centers in grid-cell units. + + The 5x5 patch is normalized by the strongest cached cell. Optional anchors + select a sparse-array position without modifying weights. Relative moments are clipped + to five cells so a weak distant hotspot cannot dominate a word's features. + Preserve this feature order when fitting or loading boundary regressors. + """ + rust = get_rust() + if rust is not None: + return rust.local_features(answer, units, sparse, grid, anchors) + gh, gw = grid + features, valid, peaks = [], [], [] + for u, (start, end) in enumerate(units): + indices = np.asarray(sparse["idx"][u]) + values = np.asarray(sparse["val"][u]) + if not len(indices) or not sparse["has"][u]: + continue + maximum = values.max() + if not maximum: + continue + order = np.argsort(-values) + if anchors and u in anchors: + chosen = anchors[u] + order = np.r_[chosen, order[order != chosen]] + indices, values = indices[order], values[order] + yy, xx = indices // gw, indices % gw + dx, dy = (xx - xx[0]).astype(float), (yy - yy[0]).astype(float) + patch = np.zeros((5, 5)) + local = (abs(dx) <= 2) & (abs(dy) <= 2) + patch[(dy[local] + 2).astype(int), (dx[local] + 2).astype(int)] = ( + values[local] / maximum + ) + total = values.sum() + mass = values / total + clipped_x, clipped_y = dx.clip(-5, 5), dy.clip(-5, 5) + features.append( + [ + len(norm(answer[start:end])), + gh, + gw, + float(maximum), + float(total), + float((mass * clipped_x).sum()), + float((mass * clipped_y).sum()), + float((mass * clipped_x**2).sum()), + float((mass * clipped_y**2).sum()), + *patch.ravel().tolist(), + ] + ) + valid.append(u) + peaks.append((xx[0] + 0.5, yy[0] + 0.5)) + return ( + np.asarray(features, dtype=float).reshape(-1, 34), + valid, + np.asarray(peaks, dtype=float).reshape(-1, 2), + ) + + +def contextual_features( + answer: str, + units: list[tuple[int, int]], + per_block: list[list[int]], + features: np.ndarray, + valid: list[int], + peaks: np.ndarray, +) -> np.ndarray: + """Append transcript-neighbor and local line-spacing evidence in grid cells. + + Only words in the same emitted block contribute. Missing attention keeps its + original unit index, so a missing word cannot shift the neighborhood. A local + 25-word window bounds work independently of document length. + """ + positions = np.full((len(units), 2), np.nan) + positions[valid] = peaks + # Python scalar access avoids repeated NumPy indexing in fixed-size windows. + coordinates = positions.tolist() + present = np.isfinite(positions[:, 0]).tolist() + lengths = [len(norm(answer[start:end])) for start, end in units] + owners = {u: k for k, indices in enumerate(per_block) for u in indices} + native = get_native() + if native is not None: + return np.column_stack( + [features, native.neighborhood(positions, lengths, owners, valid)] + ) + context = [] + for u in valid: + px, py = coordinates[u] + row = [] + for offset in (-2, -1, 1, 2): + neighbor = u + offset + if ( + 0 <= neighbor < len(units) + and owners.get(neighbor) == owners.get(u) + and present[neighbor] + ): + nx, ny = coordinates[neighbor] + row.extend( + [ + float(nx - px), + float(ny - py), + lengths[neighbor], + 1.0, + ] + ) + else: + row.extend([0.0, 0.0, 0.0, 0.0]) + nearby = [ + j + for j in range(max(0, u - 12), min(len(units), u + 13)) + if owners.get(j) == owners.get(u) + and present[j] + and abs(coordinates[j][1] - py) <= 1 + ] + advances = [] + for first, second in zip(nearby, nearby[1:]): + delta = coordinates[second][0] - coordinates[first][0] + chars = 0.75 * lengths[first] + 1 + 0.25 * lengths[second] + if 0.1 <= delta / max(chars, 1) <= 1.5: + advances.append(delta / chars) + row.extend( + [ + len(nearby), + float(np.median(advances)) if advances else 0.0, + float(np.median(positions[nearby, 1])) - py if nearby else 0.0, + ] + ) + context.append(row) + context_array = np.asarray(context).reshape(-1, 19) + # Batch neighbor-offset clipping instead of dispatching eight scalar ufuncs. + context_array[:, 0:16:4] = np.clip(context_array[:, 0:16:4], -20, 20) + context_array[:, 1:16:4] = np.clip(context_array[:, 1:16:4], -10, 10) + return np.column_stack([features, context_array]) + + +def recover_line_tails( + accepted: set[int], candidates: set[int], peaks: np.ndarray +) -> list[int]: + """Recover omitted word runs bracketed by a line continuation and a wrap. + + Indices follow transcript order; coordinates are attention-grid cells. + Candidates already satisfy the paragraph's vertical guard. A misplaced + word may interrupt the line. A quantized row tie requires earlier downward + progression and a short horizontal gap relative to local word spacing. + """ + accepted = set(accepted) + runs: list[list[int]] = [] + for j in sorted(candidates - accepted): + if not runs or j != runs[-1][-1] + 1: + runs.append([j]) + else: + runs[-1].append(j) + for run in runs: + if len(run) < 3: + continue + first, last = run[0], run[-1] + before = next((j for j in (first - 1, first - 2) if j in accepted), None) + after = last + 1 + if before is None or after not in accepted: + continue + positions = peaks[run] + low, high = positions.min(0), positions.max(0) + prior, following = peaks[before], peaks[after] + if high[1] - low[1] > 1 or np.mean(np.diff(positions[:, 0]) >= -1) < 0.8: + continue + if ( + prior[0] < low[0] + and following[0] < low[0] + and low[1] - 1 <= prior[1] <= high[1] + 1 + and ( + high[1] < following[1] <= high[1] + 3 + or ( + following[1] == high[1] + and prior[1] < high[1] + and low[0] - prior[0] + <= max( + 3, 3 * float(np.median(np.maximum(0, np.diff(positions[:, 0])))) + ) + ) + ) + ): + accepted.update(run) + return sorted(accepted) + + +def recover_short_line_tails( + selected: list[int], candidates: set[int], peaks: np.ndarray, boxes: np.ndarray +) -> list[int]: + """Recover one or two omitted words at a supported line end. + + All coordinates use attention-grid cells. Neighboring word boxes must be + separated by at most two median word heights, with a left/down wrap after + the omitted run. This bounds gaps without assuming a page-wide font size. + """ + accepted = set(selected) + runs: list[list[int]] = [] + for j in sorted(candidates - accepted): + if not runs or j != runs[-1][-1] + 1: + runs.append([j]) + else: + runs[-1].append(j) + for run in runs: + before, after = run[0] - 1, run[-1] + 1 + if len(run) > 2 or before not in accepted or after not in accepted: + continue + sequence = [before, *run] + positions = peaks[sequence] + height = float(np.median(boxes[sequence, 3] - boxes[sequence, 1])) + gaps = boxes[sequence[1:], 0] - boxes[sequence[:-1], 2] + if ( + np.ptp(positions[:, 1]) <= 1 + and np.all(np.diff(positions[:, 0]) > 0) + and np.all((gaps >= -height) & (gaps <= 2 * height)) + and peaks[after, 0] < peaks[before, 0] + and 0 < peaks[after, 1] - positions[:, 1].max() <= 3 + ): + accepted.update(run) + return sorted(accepted) + + +def recover_paragraph_opening( + selected: list[int], + element_units: list[tuple[int, tuple[int, int]]], + lookup: dict[int, int], + peaks: np.ndarray, + boxes: np.ndarray, +) -> list[int]: + """Recover one or two opening words continuous with an accepted first line. + + Peaks and word boxes use grid cells. Require increasing horizontal positions + on one attention row and gaps of at most two local word heights. A substantial + accepted body anchors the paragraph before relaxing its coarse boundary. + """ + if len(selected) < 8: + return selected + ordered = [lookup[u] for u, _ in element_units if u in lookup] + if not ordered: + return selected + accepted = set(selected) + prefix = [] + for index in ordered: + if index in accepted: + break + prefix.append(index) + if not 1 <= len(prefix) <= 2 or len(prefix) == len(ordered): + return selected + sequence = prefix + [ordered[len(prefix)]] + positions = peaks[sequence] + height = float(np.median(boxes[sequence, 3] - boxes[sequence, 1])) + gaps = boxes[sequence[1:], 0] - boxes[sequence[:-1], 2] + if ( + np.ptp(positions[:, 1]) <= 1 + and np.all(np.diff(positions[:, 0]) > 0) + and np.all((gaps >= -height) & (gaps <= 2 * height)) + ): + return sorted(accepted | set(prefix)) + return selected + + +def align_word_boxes_to_neighbor_row( + selected: list[int], + element_units: list[tuple[int, tuple[int, int]]], + lookup: dict[int, int], + peaks: np.ndarray, + grid_boxes: np.ndarray, + word_boxes: np.ndarray, + cell_height: float, +) -> None: + """Repair displaced word boxes when consecutive peaks agree on one line. + + Update grid-cell and capture-pixel boxes together, preserving word heights. + Both neighbors must agree vertically and all three peaks must advance left + to right on one row; a line wrap or isolated peak cannot trigger correction. + """ + ordered = [lookup[u] for u, _ in element_units if u in lookup] + accepted = set(selected) + for k in range(1, len(ordered) - 1): + left, mid, right = ordered[k - 1 : k + 2] + if not {left, mid, right} <= accepted: + continue + ax, ay = peaks[left] + bx, by = peaks[mid] + cx, cy = peaks[right] + if max(ay, by, cy) - min(ay, by, cy) > 1 or not ax < bx < cx: + continue + ltop, lbottom = grid_boxes[left, 1], grid_boxes[left, 3] + rtop, rbottom = grid_boxes[right, 1], grid_boxes[right, 3] + height = float((lbottom - ltop + rbottom - rtop) / 2) + lcenter, rcenter = (ltop + lbottom) / 2, (rtop + rbottom) / 2 + target = float((lcenter + rcenter) / 2) + center = float((grid_boxes[mid, 1] + grid_boxes[mid, 3]) / 2) + if abs(lcenter - rcenter) <= height and abs(center - target) > max( + 2, 2 * height + ): + delta = target - center + grid_boxes[mid, [1, 3]] += delta + word_boxes[mid, [1, 3]] += delta * cell_height + + +def align_word_boxes_to_reading_order( + selected: list[int], + element_units: list[tuple[int, tuple[int, int]]], + lookup: dict[int, int], + peaks: np.ndarray, + grid_boxes: np.ndarray, + word_boxes: np.ndarray, + cell_width: float, +) -> None: + """Place an isolated reversed word between agreeing same-row neighbors. + + Require both its peak and box center to violate the neighbors' reading + order. The positive inter-word gap is bounded by word width and height; + preserve box width while updating grid-cell and capture-pixel coordinates. + """ + ordered = [lookup[u] for u, _ in element_units if u in lookup] + accepted = set(selected) + for k in range(1, len(ordered) - 1): + left, mid, right = ordered[k - 1 : k + 2] + if not {left, mid, right} <= accepted: + continue + ax, ay = peaks[left] + bx, by = peaks[mid] + cx, cy = peaks[right] + if max(ay, by, cy) - min(ay, by, cy) > 1 or not ax < cx or ax <= bx <= cx: + continue + height = ( + grid_boxes[left, 3] + - grid_boxes[left, 1] + + grid_boxes[right, 3] + - grid_boxes[right, 1] + ) / 2 + lo, hi = grid_boxes[left, 2], grid_boxes[right, 0] + width = grid_boxes[mid, 2] - grid_boxes[mid, 0] + center = (grid_boxes[mid, 0] + grid_boxes[mid, 2]) / 2 + if 0 < hi - lo <= 2 * width + 2 * height and (center < ax or center > cx): + delta = (lo + hi) / 2 - center + grid_boxes[mid, [0, 2]] += delta + word_boxes[mid, [0, 2]] += delta * cell_width + + +def coherent_paragraph_words( + selected: list[int], peaks: np.ndarray, boxes: np.ndarray +) -> list[int]: + """Check attention peaks and predicted box centers for isolated internal words. + + A word regressor can shift a box away from an otherwise coherent peak band. + Both passes preserve transcript endpoints and retain at least 90% of words. + """ + selected = _coherent_vertical_words(selected, peaks[:, 1], boxes) + if len(selected) < 12: + return selected + centers = (boxes[:, 1] + boxes[:, 3]) / 2 + return _coherent_vertical_words(selected, centers, boxes) + + +def _coherent_vertical_words( + selected: list[int], vertical: np.ndarray, boxes: np.ndarray +) -> list[int]: + """Remove up to two internal word positions detached from a dominant text band. + + Coordinates are grid cells. The gap scales with median word height; at least + 90% of selected words must stay connected vertically. Transcript endpoints + remain intact because short opening or closing lines may be widely spaced. + """ + if len(selected) < 12: + return selected + ordered = sorted(selected, key=lambda j: vertical[j]) + height = float(np.median(boxes[selected, 3] - boxes[selected, 1])) + gap = max(2, 2 * height) + bands: list[list[int]] = [[]] + for j in ordered: + if bands[-1] and vertical[j] - vertical[bands[-1][-1]] > gap: + bands.append([]) + bands[-1].append(j) + largest = max(bands, key=len) + if ( + len(largest) == len(selected) + or len(largest) < 0.9 * len(selected) + or len(selected) - len(largest) > 2 + ): + return selected + removed = set(selected) - set(largest) + if min(selected) in removed or max(selected) in removed: + return selected + return sorted(largest) + + +_SOURCE_FOOTER = re.compile( + r"\s*]*colspan=[\"']?\d+[\"']?[^>]*>" + r"(Source:(?:(?!\s*\s*\s*$", + re.I | re.S, +) + + +def separate_table_sources( + answer: str, + elements: list[dict], + units: list[tuple[int, int]], + lookup: dict[int, int], + peaks: np.ndarray, + grid_boxes: np.ndarray, + word_boxes: np.ndarray, +) -> list[dict]: + """Ground explicit final source rows using existing word predictions. + + Spans remain offsets into the original transcript and boxes use capture + pixels. Table geometry is already refined and stays unchanged. A marker + tells serialization to restore the closing tag after removing the row. + """ + rebuilt: list[dict] = [] + for element in elements: + match = ( + _SOURCE_FOOTER.search(answer, element["start"], element["end"]) + if element["type"] == "table" + else None + ) + if match: + start, end = match.span(1) + selected = [ + lookup[u] + for u, (s, e) in enumerate(units) + if start <= s and e <= end and u in lookup + ] + selected = coherent_paragraph_words(selected, peaks, grid_boxes) + if selected: + boxes = word_boxes[selected] + bounds = np.r_[boxes[:, :2].min(0), boxes[:, 2:].max(0)] + rebuilt.append({**element, "end": match.start(), "close_table": True}) + rebuilt.append( + { + "type": "text", + "start": start, + "end": end, + "box": np.round(bounds, 1).tolist(), + } + ) + continue + rebuilt.append(element) + return rebuilt + + +def ground_cached( + answer: str, + capture: dict, + models: list[Predictor] | None = None, + with_context: bool = False, + picture_model: PicturePredictor | None = None, + with_extended_context: bool = False, + region_models: list[Predictor] | None = None, + collect_region_features: bool = False, + table_model: TablePredictor | None = None, + with_region_context: bool = False, + peak_model: PeakPredictor | None = None, + *, + _rotated_spans: set[tuple[int, int]] | None = None, +) -> dict: + """Reconstruct pixel-coordinate boxes from dimensions and cached attention. + + Models predict center dx/dy and log width/height in attention-grid cells. + The caller owns model loading; this function performs no file or image I/O. + Without models, return the deterministic rectangle baseline. Region models + adjust outer edges in local word-height units. Feature collection returns + each region's element index, feature row, grid-cell anchor, and word height + for offline training-label construction. + """ + if (region_models is not None or collect_region_features) and models is None: + raise ValueError("Region refinement requires word boundary models") + if region_models is not None and len(region_models) != 4: + raise ValueError("Expected four region edge predictors") + width, height = capture["width"], capture["height"] + gh, gw = capture["grid"] + cw, ch = width / gw, height / gh + blocks = split_column_blocks(answer, capture, split_blocks(answer)) + blocks = split_bullet_tables(answer, blocks) + blocks = split_navigation_headers(answer, capture, blocks) + units, per_block = units_for(answer, blocks) + sparse = capture["sparse_maps"] + if len(units) != len(sparse["idx"]): + raise ValueError("Cached attention units do not match the transcript") + if get_rust() is not None: + maps, has = ( + SparseWordMaps(sparse, (gh, gw)), + np.asarray(sparse["has"], dtype=bool), + ) + else: + maps, has = dense_maps(sparse, (gh, gw)) + base = rectangle_boxes( + (width, height), + answer, + blocks, + units, + per_block, + maps, + (gh, gw), + has, + BASE_CONFIG, + ) + if picture_model is not None: + refine_pictures(capture, blocks, per_block, base, picture_model, answer=answer) + if table_model is not None: + refine_tables(capture, answer, blocks, per_block, units, base, table_model) + if models is None: + return base + if len(models) != 4: + raise ValueError( + "Expected center-x, center-y, log-width, and log-height predictors" + ) + features, valid, peaks = attention_features(answer, units, sparse, (gh, gw)) + if not len(valid): + if collect_region_features: + base["region_features"] = [] + return base + if peak_model is not None: + context = contextual_features(answer, units, per_block, features, valid, peaks) + anchors = select_word_peaks( + context, valid, peaks, sparse, (gh, gw), blocks, per_block, peak_model + ) + if anchors: + # Local attention features depend only on the changed word's map. + # Recompute those rows; contextual features below still see every peak. + changed = [u for u in valid if u in anchors] + changed_sparse = { + key: [values[u] for u in changed] for key, values in sparse.items() + } + changed_features, _, changed_peaks = attention_features( + answer, + [units[u] for u in changed], + changed_sparse, + (gh, gw), + {i: anchors[u] for i, u in enumerate(changed)}, + ) + lookup = {u: row for row, u in enumerate(valid)} + rows = [lookup[u] for u in changed] + features[rows] = changed_features + peaks[rows] = changed_peaks + if with_context or with_extended_context: + if peak_model is not None and not anchors: + features = context + else: + features = contextual_features( + answer, units, per_block, features, valid, peaks + ) + if with_extended_context: + features = extended_features( + answer, units, blocks, per_block, features, valid, peaks, sparse, (gh, gw) + ) + predicted = np.column_stack([predict(model, features) for model in models]) + centers, sizes = peaks + predicted[:, :2], np.exp(predicted[:, 2:]) + grid_boxes = np.column_stack([centers - sizes / 2, centers + sizes / 2]) + word_boxes = grid_boxes * [ + cw, + ch, + cw, + ch, + ] + lookup = {u: j for j, u in enumerate(valid)} + valid_starts = [units[u][0] for u in valid] + # Descriptions inside image references are not printed text. Keep their + # cached indices intact, but exclude them from text-region boundaries. + image_units = set() + for match in _INLINE_IMAGE_REFERENCE.finditer(answer): + first = bisect_left(valid_starts, match.start()) + last = bisect_left(valid_starts, match.end()) + image_units.update(u for u in valid[first:last] if units[u][1] <= match.end()) + region_records = [] + cell_scale = np.array([cw, ch, cw, ch]) + refine_table_word_boxes( + answer, base["elements"], units, valid, grid_boxes, peaks, cell_scale + ) + # Snapshot pixel-coordinate paragraph edges before any word-based updates. + # Three agreeing right edges provide a candidate width for the same left column. + column_evidence = [ + list(e["box"]) + for e in base["elements"] + if e["box"] is not None + and e["type"] in {"text", "list"} + and e["end"] - e["start"] >= 80 + and e["box"][3] - e["box"][1] >= 2 * ch + ] + for element_index, element in enumerate(base["elements"]): + box = element["box"] + if box is None or element["type"] not in _TEXT_TYPES: + continue + # Units are in transcript order; only this element's span can contribute. + first = bisect_left(valid_starts, element["start"]) + last = bisect_right(valid_starts, element["end"]) + element_units = [ + (u, units[u]) for u in valid[first:last] if u not in image_units + ] + column_right = box[2] + if element["type"] in {"text", "list"}: + rights = np.array( + [ + b[2] + for b in column_evidence + if abs(b[0] - box[0]) <= 2 * cw and b[2] > box[2] + cw + ] + ) + if len(rights) >= 3: + groups = [rights[abs(rights - r) <= cw] for r in rights] + support = max(groups, key=len) + if len(support) >= 3: + column_right = float(np.median(support)) + # Require two consecutive valid words in the added band to advance along + # one attention row. This guards against isolated peaks in adjacent blocks. + # Peak distances are grid cells; the original vertical band stays fixed. + if column_right > box[2]: + outer = [ + lookup[u] + for u, (start, end) in element_units + if u in lookup + and element["start"] <= start + and end <= element["end"] + and box[2] + cw < peaks[lookup[u], 0] * cw <= column_right + cw + and box[1] - ch <= peaks[lookup[u], 1] * ch <= box[3] + ch + ] + coherent = any( + b == a + 1 + and abs(peaks[a, 1] - peaks[b, 1]) <= 1 + and 0 <= peaks[b, 0] - peaks[a, 0] <= 3 + for a, b in zip(outer, outer[1:]) + ) + if not coherent: + column_right = box[2] + selected = [ + lookup[u] + for u, (start, end) in element_units + if u in lookup + and element["start"] <= start + and end <= element["end"] + and ( + element["type"] in {"heading", "header", "footer"} + or (element["start"], element["end"]) in (_rotated_spans or ()) + or box[0] - cw <= peaks[lookup[u], 0] * cw <= column_right + cw + ) + and box[1] - ch <= peaks[lookup[u], 1] * ch <= box[3] + ch + ] + # Extend paragraph and list lines through nearby transcript neighbors. Cell + # distances keep the rule independent of render resolution; the original + # vertical guard keeps recovery within the existing vertical band. + if selected and element["type"] in {"text", "list"}: + candidates = { + lookup[u] + for u, (start, end) in element_units + if u in lookup + and element["start"] <= start + and end <= element["end"] + and box[1] - ch <= peaks[lookup[u], 1] * ch <= box[3] + ch + } + accepted = set(selected) + changed = True + while changed: + changed = False + for j in sorted(candidates - accepted): + for neighbor in (j - 1, j + 1): + if ( + neighbor not in accepted + or abs(peaks[j, 1] - peaks[neighbor, 1]) > 1 + ): + continue + gap = max( + 0, + grid_boxes[j, 0] - grid_boxes[neighbor, 2], + grid_boxes[neighbor, 0] - grid_boxes[j, 2], + ) + if gap <= 1: + accepted.add(j) + changed = True + break + selected = recover_line_tails(accepted, candidates, peaks) + selected = recover_short_line_tails(selected, candidates, peaks, grid_boxes) + if selected and element["type"] in {"text", "list"} and _rotated_spans is None: + selected = coherent_paragraph_words(selected, peaks, grid_boxes) + # Short key/value blocks can have distant right-aligned values. + # Require overlapping word extents on distinct rows; one isolated + # numeric peak cannot expand the paragraph's horizontal boundary. + if 4 <= len(element_units) <= 16: + numeric = [ + lookup[u] + for u, (start, end) in element_units + if u in lookup + and lookup[u] not in selected + and _NUMERIC_WORD.fullmatch(answer[start:end]) + and box[1] - ch <= peaks[lookup[u], 1] * ch <= box[3] + ch + and peaks[lookup[u], 0] * cw > box[2] + cw + ] + supported = [ + j + for j in numeric + if any( + k != j + and max(grid_boxes[j, 0], grid_boxes[k, 0]) + <= min(grid_boxes[j, 2], grid_boxes[k, 2]) + and abs(peaks[j, 1] - peaks[k, 1]) >= 2 + for k in numeric + ) + ] + selected = sorted(set(selected) | set(supported)) + + if element["type"] in {"text", "list"}: + selected = recover_paragraph_opening( + selected, element_units, lookup, peaks, grid_boxes + ) + if selected and (element["start"], element["end"]) in (_rotated_spans or ()): + selected = coherent_rotated_words(selected, peaks) + if selected and element["type"] in {"text", "list", "heading"}: + align_word_boxes_to_neighbor_row( + selected, element_units, lookup, peaks, grid_boxes, word_boxes, ch + ) + align_word_boxes_to_reading_order( + selected, element_units, lookup, peaks, grid_boxes, word_boxes, cw + ) + if selected: + boxes = word_boxes[selected] + bounds = np.r_[boxes[:, :2].min(0), boxes[:, 2:].max(0)] + bounds = np.clip(bounds, 0, [width, height, width, height]) + if bounds[2] > bounds[0] and bounds[3] > bounds[1]: + element["box"] = np.round(bounds, 1).tolist() + if region_models is not None or collect_region_features: + anchor = np.asarray(element["box"]) / cell_scale + row, word_height = region_features( + element["type"], + answer[element["start"] : element["end"]], + anchor, + np.asarray(box) / cell_scale, + grid_boxes[selected], + features[selected, 0], + (gh, gw), + ) + region_records.append( + { + "element_index": element_index, + "text": element_text( + answer, element["start"], element["end"] + ), + "features": row, + "anchor": anchor.tolist(), + "height": word_height, + } + ) + if with_region_context and region_records: + for record, row in zip( + region_records, contextual_region_features(region_records) + ): + record["features"] = row.tolist() + if region_models is not None and region_records: + rows = np.asarray([record["features"] for record in region_records]) + glyph_rows = None + if any(isinstance(model, HeadingGlyphRegionBlend) for model in region_models): + glyph_rows = np.column_stack( + [ + rows, + heading_glyph_features( + [record["text"] for record in region_records] + ), + ] + ) + residuals = np.column_stack( + [ + predict( + model, + glyph_rows if isinstance(model, HeadingGlyphRegionBlend) else rows, + ) + for model in region_models + ] + ) + for record, residual in zip(region_records, residuals): + # Limit extrapolation to two local word heights on each edge. + bounds = np.clip( + np.asarray(record["anchor"]) + residual.clip(-2, 2) * record["height"], + 0, + [gw, gh, gw, gh], + ) + if bounds[2] > bounds[0] and bounds[3] > bounds[1]: + base["elements"][record["element_index"]]["box"] = np.round( + bounds * cell_scale, 1 + ).tolist() + base["elements"] = separate_table_sources( + answer, base["elements"], units, lookup, peaks, grid_boxes, word_boxes + ) + if collect_region_features: + base["region_features"] = region_records + # Region feature records describe the original pre-refinement anchors. + # Orientation recovery only replaces final boxes; the private span set + # marks the normalized pass and prevents recursively rotating it again. + if _rotated_spans is None: + spans = vertical_text_spans(answer, capture) + if spans: + rotated = ground_cached( + answer, + rotate_attention_clockwise(capture), + models, + with_context=with_context, + picture_model=picture_model, + with_extended_context=with_extended_context, + region_models=region_models, + table_model=table_model, + with_region_context=with_region_context, + peak_model=peak_model, + _rotated_spans=spans, + ) + lookup_boxes = { + (element["start"], element["end"]): element["box"] + for element in rotated["elements"] + } + for element in base["elements"]: + key = (element["start"], element["end"]) + rotated_box = lookup_boxes.get(key) + if key in spans and rotated_box is not None: + x0, y0, x1, y1 = rotated_box + element["box"] = [y0, height - x1, y1, height - x0] + if _rotated_spans is None: + recover_repeated_paragraphs(answer, capture, base["elements"], units) + return base diff --git a/parse_rl_utils/ocria_attention_grounding/native.py b/parse_rl_utils/ocria_attention_grounding/native.py new file mode 100644 index 0000000000000000000000000000000000000000..ad81f4df9d57bd027c0b9d46bbb59e984a80dbec --- /dev/null +++ b/parse_rl_utils/ocria_attention_grounding/native.py @@ -0,0 +1,254 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Optional native kernels; build explicitly, then set OCRIA_GROUNDING_NATIVE.""" + +import argparse +import ctypes +from functools import lru_cache +import os +from pathlib import Path +import subprocess + +import numpy as np + +# Matches TreeNode in native_kernels.cpp: two doubles and four 32-bit integers. +# Flags use bit 0 for missing-go-left and bit 1 for leaves. +TREE_NODE_DTYPE = np.dtype( + [ + ("value", np.float64), + ("threshold", np.float64), + ("feature", np.int32), + ("left", np.int32), + ("right", np.int32), + ("flags", np.int32), + ], + align=True, +) + +_LIBRARY_ENV = "OCRIA_GROUNDING_NATIVE" + + +class NativeKernels: + """Own a trusted shared library and its typed, contiguous-array interfaces.""" + + def __init__(self, path: str) -> None: + self.library = ctypes.CDLL(path) + double = np.ctypeslib.ndpointer(np.float64, flags="C_CONTIGUOUS") + integer = np.ctypeslib.ndpointer(np.int32, flags="C_CONTIGUOUS") + boolean = np.ctypeslib.ndpointer(np.bool_, flags="C_CONTIGUOUS") + self.library.neighborhood.argtypes = [ + ctypes.c_int, + ctypes.c_int, + double, + double, + integer, + integer, + double, + ] + self.library.pool_profiles.argtypes = [ + ctypes.c_int, + ctypes.c_int, + double, + integer, + integer, + integer, + double, + double, + ] + self.library.peak_component.argtypes = [ + ctypes.c_int, + ctypes.c_int, + boolean, + ctypes.c_int, + boolean, + ] + self.library.peak_component_bounds.argtypes = [ + *self.library.peak_component.argtypes, + integer, + ] + self.library.predict_compact_trees.argtypes = [ + ctypes.c_int, + ctypes.c_int, + double, + ctypes.c_int, + integer, + np.ctypeslib.ndpointer(TREE_NODE_DTYPE, flags="C_CONTIGUOUS"), + ctypes.c_double, + double, + ] + self.library.component_boxes.argtypes = [ + ctypes.c_int, + ctypes.c_int, + boolean, + integer, + ] + self.library.component_boxes.restype = ctypes.c_int + self.library.box_maxima.argtypes = [ + ctypes.c_int, + double, + ctypes.c_int, + integer, + double, + ] + self.library.box_maxima.restype = None + self.library.mass_boxes.argtypes = [ + ctypes.c_int, + ctypes.c_int, + double, + ctypes.c_int, + double, + double, + ] + self.library.mass_boxes.restype = None + for name in ( + "neighborhood", + "pool_profiles", + "peak_component", + "peak_component_bounds", + "predict_compact_trees", + ): + getattr(self.library, name).restype = None + + def neighborhood( + self, + positions: np.ndarray, + lengths: list[int], + owners: dict[int, int], + valid: list[int], + ) -> np.ndarray: + """Return 19 contextual features per valid word, preserving unit indices.""" + owner_array = np.full(len(positions), -1, dtype=np.int32) + for u, owner in owners.items(): + owner_array[u] = owner + out = np.empty((len(valid), 19)) + self.library.neighborhood( + len(positions), + len(valid), + positions, + np.asarray(lengths, dtype=np.float64), + owner_array, + np.asarray(valid, dtype=np.int32), + out, + ) + return out + + def pool_profiles( + self, + positions: np.ndarray, + owners: dict[int, int], + valid: list[int], + profiles: np.ndarray, + ) -> np.ndarray: + """Return seven pooled profile bins and a neighbor count per valid word.""" + owner_array = np.full(len(positions), -1, dtype=np.int32) + for u, owner in owners.items(): + owner_array[u] = owner + inverse = np.full(len(positions), -1, dtype=np.int32) + inverse[valid] = np.arange(len(valid), dtype=np.int32) + out = np.empty((len(valid), 8)) + self.library.pool_profiles( + len(positions), + len(valid), + positions, + owner_array, + np.asarray(valid, dtype=np.int32), + inverse, + profiles, + out, + ) + return out + + def mass_boxes( + self, density: np.ndarray, quantiles: list[float] + ) -> list[list[float]]: + """Compute cell-edge mass boxes while sharing the marginal reductions.""" + density = np.ascontiguousarray(density, dtype=np.float64) + levels = np.asarray(quantiles, dtype=np.float64) + if density.ndim != 2 or 0 in density.shape or levels.ndim != 1: + raise ValueError( + "Expected a nonempty density and one-dimensional quantiles" + ) + out = np.empty((len(levels), 4)) + self.library.mass_boxes(*density.shape, density, len(levels), levels, out) + return out.tolist() + + def box_maxima(self, density: np.ndarray, bounds: np.ndarray) -> np.ndarray: + """Reduce clipped nonempty cell-edge rectangles without per-box calls.""" + density = np.ascontiguousarray(density, dtype=np.float64) + bounds = np.ascontiguousarray(bounds, dtype=np.int32) + if density.ndim != 2 or bounds.ndim != 2 or bounds.shape[1] != 4: + raise ValueError("Expected a two-dimensional density and N x 4 bounds") + limits = np.array([density.shape[1], density.shape[0]]) + if ( + np.any(bounds[:, :2] < 0) + or np.any(bounds[:, 2:] > limits) + or np.any(bounds[:, 2:] <= bounds[:, :2]) + ): + raise ValueError("Bounds must be clipped and nonempty") + out = np.empty(len(bounds)) + self.library.box_maxima(density.shape[1], density, len(bounds), bounds, out) + return out + + def component_boxes(self, mask: np.ndarray) -> np.ndarray: + """Return eight-connected component edges in row-major seed order.""" + if mask.ndim != 2: + raise ValueError("Component mask must be two-dimensional") + mask = np.ascontiguousarray(mask, dtype=np.bool_) + bounds = np.empty((mask.size, 4), dtype=np.int32) + count = self.library.component_boxes(*mask.shape, mask, bounds) + return bounds[:count] + + def peak_component_bounds( + self, mask: np.ndarray, y: int, x: int + ) -> tuple[np.ndarray, tuple[int, int, int, int]]: + """Return the peak component and exclusive cell bounds in x/y order.""" + out = np.zeros_like(mask) + bounds = np.empty(4, dtype=np.int32) + self.library.peak_component_bounds( + *mask.shape, mask, int(y * mask.shape[1] + x), out, bounds + ) + return out, (int(bounds[0]), int(bounds[1]), int(bounds[2]), int(bounds[3])) + + def peak_component(self, mask: np.ndarray, y: int, x: int) -> np.ndarray: + """Flood the true peak's eight-connected component in a boolean grid.""" + out = np.zeros_like(mask) + self.library.peak_component(*mask.shape, mask, int(y * mask.shape[1] + x), out) + return out + + +@lru_cache(maxsize=1) +def get_native() -> NativeKernels | None: + """Read the opt-in library path once; an invalid explicit path fails visibly.""" + path = os.environ.get(_LIBRARY_ENV) + return NativeKernels(path) if path else None + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", required=True, type=Path) + parser.add_argument("--compiler", default="c++") + args = parser.parse_args() + source = Path(__file__).with_name("native_kernels.cpp") + args.output.parent.mkdir(parents=True, exist_ok=True) + # Disable fused arithmetic so feature rounding matches the NumPy reference. + subprocess.run( + [ + args.compiler, + "-O3", + "-std=c++17", + "-ffp-contract=off", + "-shared", + "-fPIC", + str(source), + "-o", + str(args.output), + ], + check=True, + timeout=120, + ) + print(f"Set {_LIBRARY_ENV}={args.output.resolve()}") + + +if __name__ == "__main__": + main() diff --git a/parse_rl_utils/ocria_attention_grounding/native_kernels.cpp b/parse_rl_utils/ocria_attention_grounding/native_kernels.cpp new file mode 100644 index 0000000000000000000000000000000000000000..88444e5e18446255647f96094e3ad3a9b4c80957 --- /dev/null +++ b/parse_rl_utils/ocria_attention_grounding/native_kernels.cpp @@ -0,0 +1,176 @@ +// Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +// Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +// This is not open-source software: see the license for permitted uses. +// Arrays are contiguous float64, int32, or byte booleans, owned by Python. +// Coordinates use attention-grid cells; valid indices retain transcript positions. +// Compile without fused arithmetic to preserve reference feature rounding. +#include +#include +#include +static double median(std::vector& v) { + std::sort(v.begin(),v.end()); const auto n=v.size(); + return n%2 ? v[n/2] : (v[n/2-1]+v[n/2])/2.0; +} +extern "C" void neighborhood(int n, int m, const double* xy, const double* lengths, + const int* owner, const int* valid, double* out) { + for (int r=0;r=0 && v nearby;std::vector ys,adv; + for(int v=std::max(0,u-12);v=.1 && ratio<=1.5)adv.push_back(delta/chars); + } + row[16]=nearby.size();row[17]=adv.empty()?0:median(adv);row[18]=ys.empty()?0:median(ys)-py; + } +} +// Sum neighbors in transcript order to match the reference floating-point order. +extern "C" void pool_profiles(int n, int m, const double* xy, const int* owner, + const int* valid, const int* lookup, + const double* profiles, double* out) { + for(int r=0;r1)continue; + const int offset=static_cast(std::nearbyint(xy[2*v+1]-xy[2*u+1])); + for(int k=0;k<5;++k)row[1+offset+k]+=profiles[5*lookup[v]+k]; + ++count; + } + if(count)for(int k=0;k<7;++k)row[k]/=count; + row[7]=count; + } +} +// The caller supplies a true seed and a zeroed output mask. Visit only its +// eight-connected component; unrelated components do not need labels. +extern "C" void peak_component_bounds(int h, int w, const unsigned char* mask, int seed, + unsigned char* selected, int* bounds) { + bounds[0]=seed%w; bounds[1]=seed/w; + bounds[2]=bounds[0]+1; bounds[3]=bounds[1]+1; + std::vector queue;queue.push_back(seed);selected[seed]=1; + for(size_t k=0;k +#include + +// Interleave eight independent rows to overlap dependent node loads. Each row +// still accumulates leaves in tree order; the tail handles incomplete groups. +// Compact nodes avoid converting integer links and fit two nodes per cache line. +struct TreeNode { + double value, threshold; + int feature, left, right, flags; +}; +static_assert(sizeof(TreeNode)==32); +extern "C" void predict_compact_trees(int rows,int cols,const double* x,int trees, + const int* roots,const TreeNode* nodes,double baseline,double* out) { + std::fill(out,out+rows,baseline); + for(int t=0;t +#include +extern "C" int component_boxes(int h,int w,const uint8_t* mask,int* out) { + const int n=h*w;std::vector seen(n);std::vector q;q.reserve(n);int count=0; + for(int seed=0;seedx1)x1=x+1;if(yy1)y1=y+1; + for(int dy=-1;dy<=1;++dy)for(int dx=-1;dx<=1;++dx){int nx=x+dx,ny=y+dy; + if(nx<0||nx>=w||ny<0||ny>=h)continue;int j=ny*w+nx; + if(mask[j]&&!seen[j]){seen[j]=1;q.push_back(j);} + } + } + out[count*4]=x0;out[count*4+1]=y0;out[count*4+2]=x1;out[count*4+3]=y1;++count; + } + return count; +} + +// Bounds are clipped, nonempty cell-edge rectangles in x0,y0,x1,y1 order. +extern "C" void box_maxima(int width,const double* values,int count, + const int* bounds,double* out) { + for(int k=0;k=maximum)maximum=v; + } + out[k]=maximum; + } +} + +// Share marginal sums and cumulative mass across quantile rectangles. +#include +#include +extern "C" void mass_boxes(int h,int w,const double* v,int count,const double* q,double* out) { + std::vector x(w,0),y(h,0); + for(int r=0;r list[dict]: + """Clip oversized icons to the slots above their short sidebar labels. + + Visible-page coordinates define a narrow left-edge menu with four or more + aligned labels. Preserve text items and normally sized pictures. Only explicit + icon references immediately preceding a label can use its inferred slot. + """ + groups: list[list[int]] = [] + group: list[int] = [] + for index, item in enumerate(items): + box = item["bbox"] + eligible = ( + item["type"] == "Text" + and 1 <= len(item["md"].split()) <= 5 + and box["x"] + box["w"] <= 0.12 * width + ) + if eligible: + if group: + previous = items[group[-1]]["bbox"] + aligned = ( + abs(previous["x"] + previous["w"] / 2 - box["x"] - box["w"] / 2) + <= 0.03 * width + ) + gap = box["y"] - previous["y"] - previous["h"] + if not (aligned and 0 <= gap <= 0.1 * height): + groups.append(group) + group = [] + group.append(index) + elif item["type"] == "Picture" and item["md"].startswith("![icon:"): + continue + else: + groups.append(group) + group = [] + groups.append(group) + replacements: dict[int, dict] = {} + for group in groups: + if len(group) < 4: + continue + boxes = [items[index]["bbox"] for index in group] + left = min(box["x"] for box in boxes) + right = max(box["x"] + box["w"] for box in boxes) + pitch = sum(boxes[k]["y"] - boxes[k - 1]["y"] for k in range(1, len(boxes))) / ( + len(boxes) - 1 + ) + for k, index in enumerate(group): + if not index: + continue + icon = items[index - 1] + if icon["type"] != "Picture" or not icon["md"].startswith("![icon:"): + continue + box, label = icon["bbox"], boxes[k] + if box["w"] <= 2 * (right - left) and box["h"] <= pitch: + continue + top = ( + boxes[k - 1]["y"] + boxes[k - 1]["h"] + if k + else max(0, label["y"] - pitch / 2) + ) + x, y = max(left, box["x"]), max(top, box["y"]) + x1 = min(right, box["x"] + box["w"]) + y1 = min(label["y"], box["y"] + box["h"]) + if x1 > x and y1 > y: + clipped = {**box, "x": x, "y": y, "w": x1 - x, "h": y1 - y} + replacements[index - 1] = { + **icon, + "bbox": clipped, + "layout_segments": [dict(clipped)], + } + return [replacements.get(index, item) for index, item in enumerate(items)] diff --git a/parse_rl_utils/ocria_attention_grounding/orientation.py b/parse_rl_utils/ocria_attention_grounding/orientation.py new file mode 100644 index 0000000000000000000000000000000000000000..061e614c31f3536f45dddfc878903e42b65f81b7 --- /dev/null +++ b/parse_rl_utils/ocria_attention_grounding/orientation.py @@ -0,0 +1,88 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Normalize bottom-to-top text using cached attention coordinates.""" + +import numpy as np + +from .blocks import split_blocks +from .io import units_for + + +def vertical_text_spans(answer: str, capture: dict) -> set[tuple[int, int]]: + """Find narrow attention bands whose transcript mostly advances upward. + + Distances are in attention cells. Quantile spans tolerate isolated peaks; + at least three nonzero vertical steps must support the reading direction. + """ + blocks = split_blocks(answer) + units, per_block = units_for(answer, blocks) + sparse = capture["sparse_maps"] + _, gw = capture["grid"] + selected = set() + for block, indices in zip(blocks, per_block): + if block.type not in {"text", "heading", "header", "footer"}: + continue + points = [] + for unit in indices: + if sparse["val"][unit]: + cell = sparse["idx"][unit][int(np.argmax(sparse["val"][unit]))] + points.append([cell % gw + 0.5, cell // gw + 0.5]) + if len(points) < 4: + continue + positions = np.asarray(points) + dx, dy = np.quantile(positions, 0.9, axis=0) - np.quantile( + positions, 0.1, axis=0 + ) + steps = np.diff(positions[:, 1]) + steps = steps[np.abs(steps) >= 1] + if ( + dx <= 4 + and dy >= max(8, 4 * dx) + and len(steps) >= 3 + and np.mean(steps < 0) >= 0.75 + ): + selected.add((block.start, block.end)) + return selected + + +def coherent_rotated_words(selected: list[int], peaks: np.ndarray) -> list[int]: + """Exclude detached attention rows from a strongly supported rotated band. + + Coordinates are in the normalized, horizontal attention grid. Adjacent + rows may belong to a multi-line paragraph; only gaps over two cells split + bands. A dominant band needs four words and three quarters of the support. + """ + if len(selected) < 4: + return selected + ys = peaks[selected, 1] + ordered = np.sort(ys) + groups = np.split(ordered, np.flatnonzero(np.diff(ordered) > 2) + 1) + main = max(groups, key=len) + coherent = (ys >= main[0]) & (ys <= main[-1]) + if coherent.sum() >= max(4, 0.75 * len(selected)): + return np.asarray(selected)[coherent].tolist() + return selected + + +def rotate_attention_clockwise(capture: dict) -> dict: + """Rotate sparse cell indices 90 degrees, sharing unchanged attention values. + + Grid cell (x, y) becomes (grid_height - 1 - y, x). Pixel dimensions swap; + the input capture and its sparse arrays remain unchanged. + """ + gh, gw = capture["grid"] + sparse = capture["sparse_maps"] + return { + **capture, + "width": capture["height"], + "height": capture["width"], + "grid": [gw, gh], + "sparse_maps": { + **sparse, + "idx": [ + [int((cell % gw) * gh + gh - 1 - cell // gw) for cell in indices] + for indices in sparse["idx"] + ], + }, + } diff --git a/parse_rl_utils/ocria_attention_grounding/peak_kernels.rs b/parse_rl_utils/ocria_attention_grounding/peak_kernels.rs new file mode 100644 index 0000000000000000000000000000000000000000..3ea816116b6e71aab123b3db957bb72668f30709 --- /dev/null +++ b/parse_rl_utils/ocria_attention_grounding/peak_kernels.rs @@ -0,0 +1,249 @@ +// Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +// Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +// This is not open-source software: see the license for permitted uses. +mod density_kernels; +mod geometry_kernels; +use std::slice; +unsafe fn peak_features( + n: usize, + width: i64, + idx: *const i64, + val: *const f64, + order: *const i64, + context: *const f64, + peak: *const f64, + logs: *const f64, + retained: *mut i64, + out: *mut f64, +) -> usize { + let ix = slice::from_raw_parts(idx, n); + let v = slice::from_raw_parts(val, n); + let order = slice::from_raw_parts(order, n); + let ctx = slice::from_raw_parts(context, 53); + let peak = slice::from_raw_parts(peak, 2); + let logs = slice::from_raw_parts(logs, 5); + let retained = slice::from_raw_parts_mut(retained, 4); + let out = slice::from_raw_parts_mut(out, 88); + let xy: Vec<(f64, f64)> = ix + .iter() + .map(|i| ((i % width) as f64 + 0.5, (i / width) as f64 + 0.5)) + .collect(); + let mut count = 0; + for &j in order { + let j = j as usize; + if (0..count).any(|k| { + let p = xy[retained[k] as usize]; + (xy[j].0 - p.0).powi(2) + (xy[j].1 - p.1).powi(2) < 2.25 + }) { + continue; + } + retained[count] = j as i64; + count += 1; + if count == 4 { + break; + } + } + let total = v.iter().sum::(); + let maximum = v.iter().copied().fold(f64::NEG_INFINITY, f64::max); + for k in 0..count { + let j = retained[k] as usize; + let p = xy[j]; + let dx = p.0 - peak[0]; + let dy = p.1 - peak[1]; + let nearby_mass: f64 = (0..n) + .filter(|&i| (xy[i].0 - p.0).abs() <= 1.0 && (xy[i].1 - p.1).abs() <= 1.0) + .map(|i| v[i]) + .sum(); + let r = &mut out[k * 22..(k + 1) * 22]; + r[0] = k as f64; + r[1] = v[j] / maximum; + r[2] = nearby_mass / total; + r[3] = logs[0]; + r[4] = dx; + r[5] = dy; + for h in 0..4 { + let c = 34 + h * 4; + let t = 6 + h * 4; + r[t] = if ctx[c + 3] != 0.0 { + (ctx[c] - dx).clamp(-30.0, 30.0) + } else { + 0.0 + }; + r[t + 1] = if ctx[c + 3] != 0.0 { + (ctx[c + 1] - dy).clamp(-30.0, 30.0) + } else { + 0.0 + }; + r[t + 2] = logs[h + 1]; + r[t + 3] = ctx[c + 3]; + } + } + count +} +// Python validates nonempty matching sparse arrays and contiguous buffers. +// Offsets index flattened cells; contexts have 53 columns, outputs four x 22. +// Caller owns all buffers for the duration of this synchronous call. +#[no_mangle] +pub unsafe extern "C" fn page_peak_features( + words: usize, + width: i64, + offsets: *const i64, + idx: *const i64, + val: *const f64, + order: *const i64, + context: *const f64, + peaks: *const f64, + logs: *const f64, + retained: *mut i64, + out: *mut f64, + counts: *mut i64, +) { + let offsets = slice::from_raw_parts(offsets, words + 1); + for w in 0..words { + let start = offsets[w] as usize; + let n = (offsets[w + 1] - offsets[w]) as usize; + *counts.add(w) = peak_features( + n, + width, + idx.add(start), + val.add(start), + order.add(start), + context.add(w * 53), + peaks.add(w * 2), + logs.add(w * 5), + retained.add(w * 4), + out.add(w * 88), + ) as i64; + } +} + +// Caller validates sparse lengths and supplies matching NumPy sort orders. +// Output contains ten quantile offsets and twelve threshold edge offsets per word. +#[no_mangle] +pub unsafe extern "C" fn context_bounds( + words: usize, + width: i64, + offsets: *const i64, + indices: *const i64, + attention: *const f64, + mass: *const f64, + orders_x: *const i64, + orders_y: *const i64, + peaks: *const f64, + output: *mut f64, +) { + let offsets = slice::from_raw_parts(offsets, words + 1); + for w in 0..words { + let start = offsets[w] as usize; + let n = (offsets[w + 1] - offsets[w]) as usize; + let ix = slice::from_raw_parts(indices.add(start), n); + let a = slice::from_raw_parts(attention.add(start), n); + let m = slice::from_raw_parts(mass.add(start), n); + let p = slice::from_raw_parts(peaks.add(w * 2), 2); + let out = slice::from_raw_parts_mut(output.add(w * 22), 22); + for axis in 0..2 { + let order = slice::from_raw_parts( + if axis == 0 { + orders_x.add(start) + } else { + orders_y.add(start) + }, + n, + ); + let mut cdf = Vec::with_capacity(n); + let mut total = 0.0; + for &j in order { + total += m[j as usize]; + cdf.push(total); + } + for (q, &v) in [0.05, 0.25, 0.5, 0.75, 0.95].iter().enumerate() { + let k = cdf.partition_point(|&x| x < v).min(n - 1); + let cell = ix[order[k] as usize]; + let coordinate = if axis == 0 { + cell % width + } else { + cell / width + }; + out[axis * 5 + q] = coordinate as f64 + 0.5 - p[axis]; + } + } + let maximum = a.iter().copied().fold(f64::NEG_INFINITY, f64::max); + for (t, &threshold) in [0.1, 0.3, 0.6].iter().enumerate() { + let mut minx = i64::MAX; + let mut miny = i64::MAX; + let mut maxx = i64::MIN; + let mut maxy = i64::MIN; + for j in 0..n { + if a[j] >= threshold * maximum { + let x = ix[j] % width; + let y = ix[j] / width; + minx = minx.min(x); + miny = miny.min(y); + maxx = maxx.max(x); + maxy = maxy.max(y); + } + } + out[10 + t * 4] = minx as f64 - p[0]; + out[11 + t * 4] = miny as f64 - p[1]; + out[12 + t * 4] = maxx as f64 + 1.0 - p[0]; + out[13 + t * 4] = maxy as f64 + 1.0 - p[1]; + } + } +} + +// Python supplies nonempty sparse rows and optional anchor positions (-1 means argmax). +// Each output row has 34 features and a separate two-coordinate peak center. +#[no_mangle] +pub unsafe extern "C" fn local_features_unsorted( + words: usize, + height: i64, + width: i64, + offsets: *const i64, + indices: *const i64, + values: *const f64, + lengths: *const i64, + anchors: *const i64, + output: *mut f64, + peaks: *mut f64, +) { + let offsets = slice::from_raw_parts(offsets, words + 1); + for w in 0..words { + let start = offsets[w] as usize; + let n = (offsets[w + 1] - offsets[w]) as usize; + let ix = slice::from_raw_parts(indices.add(start), n); + let v = slice::from_raw_parts(values.add(start), n); + let out = slice::from_raw_parts_mut(output.add(w * 34), 34); + out.fill(0.0); + let maximum = v.iter().copied().fold(f64::NEG_INFINITY, f64::max); + let total = v.iter().sum::(); + let anchor = *anchors.add(w); + let peak = if anchor >= 0 { + anchor as usize + } else { + v.iter().position(|&value| value == maximum).unwrap() + }; + let x = ix[peak] % width; + let y = ix[peak] / width; + out[0] = *lengths.add(w) as f64; + out[1] = height as f64; + out[2] = width as f64; + out[3] = maximum; + out[4] = total; + *peaks.add(w * 2) = x as f64 + 0.5; + *peaks.add(w * 2 + 1) = y as f64 + 0.5; + for j in 0..n { + let dx = ix[j] % width - x; + let dy = ix[j] / width - y; + if dx.abs() <= 2 && dy.abs() <= 2 { + out[9 + ((dy + 2) * 5 + dx + 2) as usize] = v[j] / maximum; + } + let mass = v[j] / total; + let cx = dx.clamp(-5, 5) as f64; + let cy = dy.clamp(-5, 5) as f64; + out[5] += mass * cx; + out[6] += mass * cy; + out[7] += mass * (cx * cx); + out[8] += mass * (cy * cy); + } + } +} diff --git a/parse_rl_utils/ocria_attention_grounding/peaks.py b/parse_rl_utils/ocria_attention_grounding/peaks.py new file mode 100644 index 0000000000000000000000000000000000000000..ede64109236bcbbd71279cc312ff5d908ca9d3db --- /dev/null +++ b/parse_rl_utils/ocria_attention_grounding/peaks.py @@ -0,0 +1,173 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Select a word attention mode using sparse support and transcript neighbors.""" + +from typing import Protocol +from .predict import predict +from .rust import get_rust + +import numpy as np +from .blocks import Block + +PEAK_FEATURE_VERSION = "word-peaks-v1" +PEAK_FEATURE_COUNT = 22 +PEAK_SELECTION_MARGIN = 0.1 + + +class PeakPredictor(Protocol): + def predict(self, features: np.ndarray) -> np.ndarray: ... + + +def peak_candidates( + context: np.ndarray, + peak: np.ndarray, + indices: list[int], + values: list[float], + grid_width: int, +) -> tuple[list[int], list[list[float]]]: + """Return sparse-array positions and features for four separated modes. + + Positions index the original sparse arrays, not sorted ranks or grid cells. + Geometry uses grid-cell units. Neighbor offsets come from the existing + 53-column word context representation; reference boxes are not inputs. + """ + ix, attention = np.asarray(indices), np.asarray(values) + points = np.column_stack([ix % grid_width + 0.5, ix // grid_width + 0.5]) + remaining = np.argsort(-attention) + retained = [] + while len(remaining) and len(retained) < 4: + index = int(remaining[0]) + retained.append(index) + # Squared distance preserves the 1.5-cell separation without square roots. + distance = points[remaining] - points[index] + remaining = remaining[distance[:, 0] ** 2 + distance[:, 1] ** 2 >= 2.25] + selected = points[retained] + delta = selected - peak + nearby = (abs(points[None, :, 0] - selected[:, None, 0]) <= 1) & ( + abs(points[None, :, 1] - selected[:, None, 1]) <= 1 + ) + rows = np.empty((len(retained), PEAK_FEATURE_COUNT)) + rows[:, 0] = np.arange(len(retained)) + rows[:, 1] = attention[retained] / attention.max() + total = attention.sum() + rows[:, 2] = [attention[mask].sum() / total for mask in nearby] + rows[:, 3] = np.log1p(context[0]) + rows[:, 4:6] = delta + neighbors = context[34:50].reshape(4, 4) + offsets = np.clip(neighbors[None, :, :2] - delta[:, None, :], -30, 30) + offsets = np.where(neighbors[None, :, 3:4] != 0, offsets, 0) + tail = rows[:, 6:].reshape(-1, 4, 4) + tail[:, :, :2] = offsets + tail[:, :, 2] = np.log1p(neighbors[:, 2]) + tail[:, :, 3] = neighbors[:, 3] + return retained, rows.tolist() + + +def select_word_peaks( + context: np.ndarray, + valid: list[int], + peaks: np.ndarray, + sparse: dict, + grid: tuple[int, int], + blocks: list[Block], + per_block: list[list[int]], + model: PeakPredictor, +) -> dict[int, int]: + """Map original text-unit indices to selected sparse-array positions. + + Batch candidate scoring across the page. Preserve the primary mode unless + an alternative clears the quality margin; image and table maps are skipped. + """ + eligible = { + u + for block, units in zip(blocks, per_block) + if block.type in {"text", "list", "heading", "header", "footer"} + for u in units + } + rust = get_rust() + if rust is not None: + rows, records = rust.peak_features( + context, valid, peaks, sparse, grid, eligible + ) + else: + rows, records = [], [] + for j, u in enumerate(valid): + if u not in eligible: + continue + retained, features = peak_candidates( + context[j], peaks[j], sparse["idx"][u], sparse["val"][u], grid[1] + ) + records.append((u, len(rows), retained)) + rows.extend(features) + if not len(rows): + return {} + quality = predict(model, np.asarray(rows)) + choices = {} + for u, start, retained in records: + scores = quality[start : start + len(retained)] + best = int(scores.argmax()) + if best and scores[best] > scores[0] + PEAK_SELECTION_MARGIN: + choices[u] = retained[best] + _repair_bracketed_peaks(choices, valid, peaks, sparse, grid, blocks, per_block) + return choices + + +def _repair_bracketed_peaks( + choices: dict[int, int], + valid: list[int], + peaks: np.ndarray, + sparse: dict, + grid: tuple[int, int], + blocks: list[Block], + per_block: list[list[int]], +) -> None: + """Repair isolated vertical outliers bracketed by same-line transcript words. + + Coordinates and tolerances use attention cells. Snapshot ranked peaks before + repairs so changes do not propagate into subsequent repair decisions. Choices + retain original sparse-array positions, including gaps from missing attention. + """ + grid_width = grid[1] + lookup = {unit: row for row, unit in enumerate(valid)} + positions = peaks.copy() + for unit, index in choices.items(): + cell = sparse["idx"][unit][index] + positions[lookup[unit]] = [cell % grid_width + 0.5, cell // grid_width + 0.5] + for block, units in zip(blocks, per_block): + if block.type not in {"text", "list"}: + continue + rows = [lookup[unit] for unit in units if unit in lookup] + if len(rows) < 8: + continue + for index in range(1, len(rows) - 1): + row = rows[index] + before, after = positions[rows[index - 1]], positions[rows[index + 1]] + if abs(before[1] - after[1]) > 1 or after[0] < before[0]: + continue + neighbors = rows[max(0, index - 3) : index] + rows[index + 1 : index + 4] + nearby = positions[neighbors] + ys = nearby[:, 1] + low, high = ys.min(), ys.max() + # A point inside a one-cell band cannot be 1.5 cells from its median. + # Reject these common cases before computing the median. + if high - low > 1 or low <= positions[row, 1] <= high: + continue + line_y = float(np.median(ys)) + if abs(positions[row, 1] - line_y) <= 1.5: + continue + unit = valid[row] + cells = np.asarray(sparse["idx"][unit]) + values = np.asarray(sparse["val"][unit]) + x, y = cells % grid_width + 0.5, cells // grid_width + 0.5 + # Require a strong alternative between immediate neighbors. Endpoints + # and line resets lack this evidence and retain the ranked choice. + eligible = ( + (abs(y - line_y) <= 0.5) + & (x >= before[0] - 0.5) + & (x <= after[0] + 0.5) + & (values >= 0.25 * values.max()) + ) + if eligible.any(): + indices = np.flatnonzero(eligible) + choices[unit] = int(indices[values[indices].argmax()]) diff --git a/parse_rl_utils/ocria_attention_grounding/pictures.py b/parse_rl_utils/ocria_attention_grounding/pictures.py new file mode 100644 index 0000000000000000000000000000000000000000..8e2d943ca62653fd041c4e9ea938ee8e7373edff --- /dev/null +++ b/parse_rl_utils/ocria_attention_grounding/pictures.py @@ -0,0 +1,513 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Picture proposals from sparse attention regions, with learned quality ranking.""" + +from dataclasses import dataclass +import re +from typing import Protocol +from .predict import predict +from .native import get_native + +import numpy as np +from scipy import ndimage + +from .blocks import Block +from .rectangles import mass_boxes + + +class PicturePredictor(Protocol): + def predict(self, features: np.ndarray) -> np.ndarray: ... + + +# The 19 base columns include absolute edges at 1–4 and grid resolution at 16–17. +POSITION_INDEPENDENT_COLUMNS = [i for i in range(19) if i not in (1, 2, 3, 4, 16, 17)] +PICTURE_CATEGORY_LABELS = ("photo", "logo", "icon", "image", "chart", "diagram") + + +def picture_category_features(features: np.ndarray, description: str) -> np.ndarray: + """Append emitted alt-text category indicators to 13 geometry features. + + Unknown categories have an all-zero indicator vector. Trailing prose after + the image reference is excluded from category extraction. + """ + match = re.match(r"!\[([^:\]]+)", description) + prefix = match.group(1).strip().lower() if match else "" + category = [float(prefix == kind) for kind in PICTURE_CATEGORY_LABELS] + return np.column_stack( + [ + features[:, POSITION_INDEPENDENT_COLUMNS], + np.tile(category, (len(features), 1)), + ] + ) + + +@dataclass +class PictureCategoryRanker: + geometry: PicturePredictor + semantic: PicturePredictor + photo_specialist: PicturePredictor | None = None + prose_specialist: PicturePredictor | None = None + edge_models: tuple[PicturePredictor, ...] | None = None + + def predict(self, features: np.ndarray, description: str = "") -> np.ndarray: + """Rank mixed prose separately; blend shared geometry for other pictures.""" + if self.prose_specialist is not None and description.startswith("!["): + tail = re.sub(r"^!\[[^\]]+\](?:\([^)]*\))?", "", description, count=1) + # Short prose captions need text-region geometry too. For 3–7 words, + # require lowercase Latin text and exclude additional image references. + word_count = len(re.findall(r"\w+", tail)) + if word_count >= 8 or ( + word_count >= 3 and re.search(r"[a-z]", tail) and "![" not in tail + ): + return predict( + self.prose_specialist, features[:, POSITION_INDEPENDENT_COLUMNS] + ) + semantic_features = picture_category_features(features, description) + quality = predict(self.semantic, semantic_features) + # Mixed image/prose spans need the shared model's broader geometry. + # The specialist receives the same 19 category/geometry columns. + if self.photo_specialist is not None and re.fullmatch( + r"!\[photo:[^\]]+\](?:\([^)]*\))?", description.strip() + ): + quality = 0.5 * ( + quality + predict(self.photo_specialist, semantic_features) + ) + return 0.5 * predict(self.geometry, features) + 0.5 * quality + + +def ious(boxes: np.ndarray, targets: np.ndarray) -> np.ndarray: + inter = np.maximum( + 0, + np.minimum(boxes[:, None, 2:], targets[None, :, 2:]) + - np.maximum(boxes[:, None, :2], targets[None, :, :2]), + ).prod(2) + a = (boxes[:, 2:] - boxes[:, :2]).prod(1) + b = (targets[:, 2:] - targets[:, :2]).prod(1) + return inter / np.maximum(1e-10, a[:, None] + b[None, :] - inter) + + +def candidates( + m: np.ndarray, original: list[float] +) -> tuple[list[list[float]], list[int]]: + gh, gw = m.shape + m = m / m.sum() + norm = m / m.max() + boxes = [original] + kinds = [0] + + def add(box: list, kind: int) -> None: + box = [ + float(min(max(v, 0), gw if j % 2 == 0 else gh)) for j, v in enumerate(box) + ] + if box[2] > box[0] and box[3] > box[1] and box not in boxes: + boxes.append(box) + kinds.append(kind) + + for box in mass_boxes(m, [0, 0.025, 0.05, 0.1, 0.2, 0.3, 0.4]): + add(box, 1) + # Positive thresholds commute with min/max filters and zero-valued borders. + closed = {1: norm} + for size in (3, 5): + closed[size] = ndimage.minimum_filter( + ndimage.maximum_filter(norm, size=size, mode="constant", cval=0), + size=size, + mode="constant", + cval=0, + ) + native = get_native() + for threshold in [0.01, 0.03, 0.06, 0.1, 0.2, 0.4, 0.6]: + for close in [1, 3, 5]: + joined = closed[close] >= threshold + if native is not None: + components = native.component_boxes(joined) + else: + labels, _ = ndimage.label(joined, structure=np.ones((3, 3))) + components = [ + (x.start, y.start, x.stop, y.stop) + for y, x in ndimage.find_objects(labels) + ] + for x0, y0, x1, y1 in components: + if m[y0:y1, x0:x1].sum() >= 0.005: + add([x0, y0, x1, y1], close + 1) + peaks = np.argwhere((norm == ndimage.maximum_filter(norm, size=3)) & (norm > 0)) + peaks = sorted(peaks, key=lambda p: -norm[tuple(p)])[:8] + for y, x in peaks: + for radius in [2, 4, 8, 16]: + y0, y1 = max(0, y - radius), min(gh, y + radius + 1) + x0, x1 = max(0, x - radius), min(gw, x + radius + 1) + local = m[y0:y1, x0:x1] + for b in mass_boxes(local, [0.05, 0.2]): + add([b[0] + x0, b[1] + y0, b[2] + x0, b[3] + y0], 8) + return boxes, kinds + + +def candidate_features( + density: np.ndarray, + text: np.ndarray, + boxes: list[list[float]], + kinds: list[int], + description_length: int, +) -> np.ndarray: + """Candidate shape, attention mass, and overlap with separately emitted text. + + Boxes use attention-grid cell edges. The first candidate is the unchanged + baseline; its overlap is an input feature, never a target or GT measurement. + """ + gh, gw = density.shape + density = density / density.sum() + peak = np.unravel_index(density.argmax(), density.shape) + coords = np.asarray(boxes) + x0, y0, x1, y1 = coords.T + widths, heights = x1 - x0, y1 - y0 + area = widths * heights + # Summed-area tables share density and text reductions across overlapping proposals. + integral = np.pad( + np.stack([density, density * text, text, (density * text) != 0]) + .cumsum(1) + .cumsum(2), + ((0, 0), (1, 0), (1, 0)), + ) + # Match Python slicing: starts truncate, stops round up, negative indices + # count from the far edge, and all coordinates clip to the grid. + bounds = np.column_stack([np.trunc(coords[:, :2]), np.ceil(coords[:, 2:])]).astype( + np.int64 + ) + limits = np.array([gw, gh, gw, gh]) + bounds = np.clip(np.where(bounds < 0, bounds + limits, bounds), 0, limits) + native = get_native() + maxima = ( + native.box_maxima(density, bounds) + if native is not None + else [float(density[ya:yb, xa:xb].max()) for xa, ya, xb, yb in bounds] + ) + xa, ya, xb, yb = bounds.T + mass, overlap, text_sum, overlap_cells = ( + integral[:, yb, xb] + - integral[:, ya, xb] + - integral[:, yb, xa] + + integral[:, ya, xa] + ) + # Preserve exact zero overlap; subtraction can leave cancellation noise. + overlap[overlap_cells == 0] = 0 + return np.column_stack( + [ + kinds, + x0 / gw, + y0 / gh, + x1 / gw, + y1 / gh, + widths / gw, + heights / gh, + area / (gw * gh), + mass, + mass / np.maximum(area, 1), + maxima, + overlap, + text_sum / ((xb - xa) * (yb - ya)), + (x0 <= peak[1]) & (peak[1] < x1) & (y0 <= peak[0]) & (peak[0] < y1), + np.sqrt(((x0 + x1) / 2 - peak[1]) ** 2 + ((y0 + y1) / 2 - peak[0]) ** 2) + / max(gh, gw), + np.full(len(boxes), description_length), + np.full(len(boxes), gh), + np.full(len(boxes), gw), + ious(coords, coords[:1]), + ] + ) + + +def picture_records( + capture: dict, + blocks: list[Block], + per_block: list[list[int]], + result: dict, +) -> list[dict]: + """Build attention-only picture candidates in transcript order.""" + elements = { + (e["start"], e["end"]): e + for e in result["elements"] + if e["type"] == "image" and e["box"] is not None + } + if not elements: + return [] + gh, gw = capture["grid"] + cw, ch = capture["width"] / gw, capture["height"] / gh + sparse = capture["sparse_maps"] + text = np.zeros((gh, gw)) + for block, indices in zip(blocks, per_block): + if block.type in ("image", "table"): + continue + for u in indices: + if sparse["has"][u] and sparse["val"][u] and max(sparse["val"][u]) > 0: + text.flat[sparse["idx"][u][int(np.argmax(sparse["val"][u]))]] = 1 + text = ndimage.maximum_filter(text, size=3) + records = [] + for block, indices in zip(blocks, per_block): + element = elements.get((block.start, block.end)) + if block.type != "image" or element is None: + continue + u = indices[0] + density = np.zeros(gh * gw) + density[sparse["idx"][u]] = sparse["val"][u] + density = density.reshape(gh, gw) + if not density.max(): + continue + original = (np.asarray(element["box"]) / [cw, ch, cw, ch]).tolist() + boxes, kinds = candidates(density, original) + features = candidate_features( + density, text, boxes, kinds, block.end - block.start + ) + records.append({"element": element, "boxes": boxes, "features": features}) + return records + + +def complementary_picture_spans(answer: str, first: dict, second: dict) -> bool: + """An adjacent image reference and Mermaid block can describe one figure.""" + earlier, later = sorted((first, second), key=lambda element: element["start"]) + if answer[earlier["end"] : later["start"]].strip(): + return False + texts = [answer[e["start"] : e["end"]].strip() for e in (first, second)] + return any( + re.fullmatch(r"!\[[^\]]+\](?:\([^)]*\))?", texts[index]) is not None + and texts[1 - index].startswith("```mermaid") + for index in (0, 1) + ) + + +def refine_pictures( + capture: dict, + blocks: list[Block], + per_block: list[list[int]], + result: dict, + model: PicturePredictor, + answer: str = "", +) -> None: + """Rank secondary regions, suppressing near-duplicate picture boxes in order. + + Adjacent image/Mermaid descriptions with overlapping best boxes become one + reference preserving both spans. Candidates use attention-grid coordinates; + selected boxes return to pixels. + """ + gh, gw = capture["grid"] + cw, ch = capture["width"] / gw, capture["height"] / gh + chosen = [] + chosen_elements = [] + chosen_quality = [] + removed = set() + records = picture_records(capture, blocks, per_block, result) + for record in records: + if isinstance(model, PictureCategoryRanker): + element = record["element"] + quality = model.predict( + record["features"], answer[element["start"] : element["end"]] + ) + else: + quality = predict(model, record["features"]) + boxes = record["boxes"] + top = int(np.argmax(quality)) + if chosen: + overlap = ious(np.asarray([boxes[top]]), np.asarray(chosen))[0] + prior = int(np.argmax(overlap)) + current, previous = record["element"], chosen_elements[prior] + if overlap[prior] > 0.7 and complementary_picture_spans( + answer, previous, current + ): + previous["start"] = min(previous["start"], current["start"]) + previous["end"] = max(previous["end"], current["end"]) + if quality[top] > chosen_quality[prior]: + chosen[prior] = boxes[top] + chosen_quality[prior] = quality[top] + previous["box"] = ( + np.asarray(boxes[top]) * [cw, ch, cw, ch] + ).tolist() + removed.add(id(current)) + continue + selected = 0 + for index in np.argsort(-quality): + duplicate = ( + bool(chosen) + and ious(np.asarray([boxes[index]]), np.asarray(chosen)).max() > 0.7 + ) + if not duplicate: + selected = int(index) + break + box = boxes[selected] + # Average nearby proposals only when their quality is close to the winner. + # This stabilizes edges while keeping separate attention regions apart. + coords = np.asarray(boxes) + overlap = ious(coords, coords[selected : selected + 1])[:, 0] + eligible = np.flatnonzero( + (overlap >= 0.7) & (quality >= quality[selected] - 0.05) + ) + eligible = eligible[np.argsort(-quality[eligible])[:5]] + if len(eligible) >= 2: + weights = np.exp((quality[eligible] - quality[eligible].max()) / 0.02) + box = np.average(coords[eligible], axis=0, weights=weights).tolist() + chosen.append(box) + chosen_elements.append(record["element"]) + chosen_quality.append(quality[selected]) + record["element"]["box"] = (np.asarray(box) * [cw, ch, cw, ch]).tolist() + + result["elements"] = [e for e in result["elements"] if id(e) not in removed] + + if isinstance(model, PictureCategoryRanker) and model.edge_models and records: + # Calibrate final boxes after selection and merging. Features come from + # the closest original proposal; offsets scale with the selected box. + scale = np.array([cw, ch, cw, ch]) + selected_boxes, edge_features = [], [] + for record in records: + element = record["element"] + box = np.asarray(element["box"]) / scale + nearest = int( + np.abs(np.asarray(record["boxes"]) - box).sum(axis=1).argmin() + ) + edge_features.append( + picture_category_features( + record["features"], answer[element["start"] : element["end"]] + )[nearest] + ) + selected_boxes.append(box) + residuals = np.column_stack( + [ + predict(edge_model, np.asarray(edge_features)) + for edge_model in model.edge_models + ] + ) + for record, box, residual in zip(records, selected_boxes, residuals): + size = np.tile(np.maximum(box[2:] - box[:2], 1), 2) + corrected = np.clip( + box + 0.25 * residual.clip(-0.5, 0.5) * size, 0, [gw, gh, gw, gh] + ) + if (corrected[2:] > corrected[:2]).all(): + record["element"]["box"] = (corrected * scale).tolist() + + +def trim_picture_text_overlap(items: list[dict]) -> None: + """Trim shallow incursions by external text in final page-coordinate boxes. + + Text must sit mostly alongside the picture and have its center outside it. + Photo/image/logo categories permit this separation; chart and diagram labels + may belong inside their picture. Update the single layout segment together. + """ + text_boxes = [ + (b["x"], b["y"], b["x"] + b["w"], b["y"] + b["h"]) + for item in items + if item["type"] in {"Text", "Section-header", "Page-header", "Page-footer"} + for b in [item["bbox"]] + ] + for item in items: + if item["type"] != "Picture" or not re.match( + r"!\[(?:photo|image|logo):", item["md"], re.I + ): + continue + b = item["bbox"] + original = [b["x"], b["y"], b["x"] + b["w"], b["y"] + b["h"]] + edges = original.copy() + for text in text_boxes: + for axis in (0, 1): + cross = 1 - axis + overlap = min(original[cross + 2], text[cross + 2]) - max( + original[cross], text[cross] + ) + if overlap <= 0 or overlap < 0.75 * (text[cross + 2] - text[cross]): + continue + span = original[axis + 2] - original[axis] + center = (text[axis] + text[axis + 2]) / 2 + if ( + center < original[axis] + and original[axis] < text[axis + 2] < original[axis] + 0.2 * span + ): + edges[axis] = max(edges[axis], text[axis + 2]) + if ( + center > original[axis + 2] + and original[axis + 2] - 0.2 * span + < text[axis] + < original[axis + 2] + ): + edges[axis + 2] = min(edges[axis + 2], text[axis]) + if edges != original: + box = { + **b, + "x": edges[0], + "y": edges[1], + "w": edges[2] - edges[0], + "h": edges[3] - edges[1], + } + item["bbox"] = box + item["layout_segments"] = [dict(box)] + + +_NUMBERED_FIGURE_CAPTION = re.compile(r"^\s*\*?\*?(?:fig(?:ure)?\.?)\s*\d", re.I) + + +def merge_figure_tables(items: list[dict]) -> list[dict]: + """Ground chart-data tables associated with a numbered figure caption. + + Headings may separate panels; prose or another caption ends the group. + Keep all table content and heading items. The caption, when below the + tables' combined center, bounds the figure's lower edge in page units. + """ + removed: set[int] = set() + replacements: dict[int, dict] = {} + for index, caption in enumerate(items): + if caption["type"] != "Text" or not _NUMBERED_FIGURE_CAPTION.match( + caption["md"] + ): + continue + start = index - 1 + while start >= 0 and items[start]["type"] in {"Table", "Section-header"}: + start -= 1 + tables = [j for j in range(start + 1, index) if items[j]["type"] == "Table"] + if not tables: + continue + boxes = [items[j]["bbox"] for j in tables] + x = min(b["x"] for b in boxes) + y = min(b["y"] for b in boxes) + right = max(b["x"] + b["w"] for b in boxes) + bottom = max(b["y"] + b["h"] for b in boxes) + cap = caption["bbox"] + if cap["y"] < (y + bottom) / 2 or cap["x"] + cap["w"] < x or cap["x"] > right: + continue + bottom = min(bottom, cap["y"]) + box = {"x": x, "y": y, "w": right - x, "h": bottom - y, "label": "image"} + markdown = "\n\n".join(items[j]["md"] for j in tables) + replacements[tables[0]] = { + **items[tables[0]], + "type": "Picture", + "md": markdown, + "value": markdown, + "bbox": box, + "layout_segments": [dict(box)], + } + removed.update(tables[1:]) + return [ + replacements.get(index, item) + for index, item in enumerate(items) + if index not in removed + ] + + +def trim_picture_table_overlap(items: list[dict]) -> None: + """Use a following external table to bound a picture in page coordinates. + + A table must cross the picture's bottom edge, begin below its center, and + cover most of its width. Preserve charts and figures whose descriptions + explicitly include a table, since their overlapping geometry may be valid. + """ + for picture, table in zip(items, items[1:]): + if ( + picture["type"] != "Picture" + or table["type"] != "Table" + or not re.match(r"!\[(?:photo|image|map|logo):", picture["md"], re.I) + or re.search(r"\btable\b", picture["md"].split("]", 1)[0], re.I) + ): + continue + a, b = picture["bbox"], table["bbox"] + overlap = min(a["x"] + a["w"], b["x"] + b["w"]) - max(a["x"], b["x"]) + if ( + overlap >= 0.75 * a["w"] + and a["y"] + 0.5 * a["h"] < b["y"] < a["y"] + a["h"] < b["y"] + b["h"] + ): + box = {**a, "h": b["y"] - a["y"]} + picture["bbox"] = box + picture["layout_segments"] = [dict(box)] diff --git a/parse_rl_utils/ocria_attention_grounding/predict.py b/parse_rl_utils/ocria_attention_grounding/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..fd0445f53e2c9703b96f98d3b02390d756335953 --- /dev/null +++ b/parse_rl_utils/ocria_attention_grounding/predict.py @@ -0,0 +1,88 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Native prediction for compatible fitted histogram regressors.""" + +from typing import Protocol +from weakref import WeakKeyDictionary + +import numpy as np + +from .native import TREE_NODE_DTYPE, get_native + + +class Predictor(Protocol): + def predict(self, features: np.ndarray) -> np.ndarray: ... + + +# Keep model lifetime and packed-tree lifetime aligned. A refit replaces _predictors. +_PACKED: WeakKeyDictionary = WeakKeyDictionary() + + +def predict(model: Predictor, features: np.ndarray) -> np.ndarray: + """Preserve the model's normal path unless its numerical trees are supported.""" + native = get_native() + if native is None: + return model.predict(features) + from sklearn.ensemble import HistGradientBoostingRegressor + from sklearn.pipeline import Pipeline + + if type(model) is Pipeline and isinstance( + model.steps[-1][1], HistGradientBoostingRegressor + ): + transformed = ( + model[:-1].transform(features) if len(model.steps) > 1 else features + ) + return predict(model.steps[-1][1], transformed) + + if not isinstance(model, HistGradientBoostingRegressor): + return model.predict(features) + if ( + model._preprocessor is not None + or model._loss.link.__class__.__name__ != "IdentityLink" + ): + return model.predict(features) + packed = _PACKED.get(model) + if packed is None or packed[0] is not model._predictors: + roots, nodes, offset = [], [], 0 + for stage in model._predictors: + if len(stage) != 1 or stage[0].nodes["is_categorical"].any(): + return model.predict(features) + tree = stage[0].nodes + roots.append(offset) + packed_tree = np.empty(len(tree), dtype=TREE_NODE_DTYPE) + packed_tree["value"] = tree["value"] + packed_tree["threshold"] = tree["num_threshold"] + packed_tree["feature"] = tree["feature_idx"] + packed_tree["left"] = tree["left"] + offset + packed_tree["right"] = tree["right"] + offset + packed_tree["flags"] = tree["missing_go_to_left"] | (tree["is_leaf"] << 1) + nodes.append(packed_tree) + offset += len(tree) + packed = ( + model._predictors, + np.asarray(roots, dtype=np.int32), + np.ascontiguousarray(np.concatenate(nodes)), + float(model._baseline_prediction[0, 0]), + ) + _PACKED[model] = packed + values = np.ascontiguousarray(features, dtype=np.float64) + if ( + values.ndim != 2 + or values.shape[1] != model.n_features_in_ + or not len(values) + or np.isinf(values).any() + ): + return model.predict(features) + out = np.empty(len(values)) + native.library.predict_compact_trees( + len(values), + values.shape[1], + values, + len(packed[1]), + packed[1], + packed[2], + packed[3], + out, + ) + return out diff --git a/parse_rl_utils/ocria_attention_grounding/rectangles.py b/parse_rl_utils/ocria_attention_grounding/rectangles.py new file mode 100644 index 0000000000000000000000000000000000000000..d93b0eb6b1947d72e64e339a72ff9033558bb498 --- /dev/null +++ b/parse_rl_utils/ocria_attention_grounding/rectangles.py @@ -0,0 +1,560 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Rectangular block estimates from attention density and transcript geometry.""" + +from dataclasses import dataclass +import statistics + +import numpy as np + +from .native import get_native +from .io import SparseWordMaps +from scipy import ndimage +from scipy.signal import find_peaks + +from .blocks import Block, resolve_page_numbers +from .boxes import envelope +from .words import norm +from .rust import get_rust + + +@dataclass(frozen=True) +class RectangleConfig: + word_threshold: float = 0.3 + text_quantile: float = 0.01 + image_quantile: float = 0.05 + text_y_scale: float = 1.0 + x_padding: float = 0.0 + y_offset: float = 0.0 + image_padding: float = 0.0 + image_whitespace: float = 0.0 + fit_lines: bool = False + centroid: bool = True + anchor_fraction: float = 0.5 + font_height: float = 1.7 + connected_words: bool = False + y_inset: float = 0.0 + keep_prose: bool = False + keep_tables: bool = False + line_density: bool = False + line_fill: float = 0.7 + density_floor: float = 0.1 + compact_image: bool = False + adaptive_anchor: bool = False + guard_expansion: float = 0.0 + heading_x_scale: float = 1.0 + heading_y_inset: float = 0.0 + heading_y_shift: float = 0.0 + furniture_x_scale: float = 1.0 + furniture_y_inset: float = 0.0 + furniture_y_shift: float = 0.0 + text_x_scale: float = 1.0 + text_y_inset: float = 0.0 + component_centroid: bool = False + component_center: bool = False + centroid_radius: float = 1.0 + glyph_widths: bool = False + fit_blend_x: float = 1.0 + fit_blend_y: float = 1.0 + image_power: float = 1.0 + image_component_share: float = 0.0 + image_hot_threshold: float = 0.3 + image_text_suppression: float = 0.0 + + +def mass_box( + density: np.ndarray, quantile: float, compact: bool = False +) -> list[float]: + """Axis-wise attention quantiles in cell-edge coordinates, including edge cells.""" + bounds = [] + for marginal in (density.sum(axis=0), density.sum(axis=1)): + cdf = np.cumsum(marginal) + total = float(cdf[-1]) + lo = int(np.searchsorted(cdf, quantile * total, side="right")) + hi = int(np.searchsorted(cdf, (1 - quantile) * total, side="left")) + 1 + if compact: + prefix = np.concatenate(([0.0], cdf)) + target = (1 - 2 * quantile) * total + candidates = [ + ( + start, + int(np.searchsorted(prefix, prefix[start] + target, side="left")), + ) + for start in range(len(marginal)) + if prefix[start] + target <= total + ] + lo, hi = min(candidates, key=lambda pair: pair[1] - pair[0]) + bounds.append((lo, min(len(marginal), hi))) + return [ + float(bounds[0][0]), + float(bounds[1][0]), + float(bounds[0][1]), + float(bounds[1][1]), + ] + + +def mass_boxes(density: np.ndarray, quantiles: list[float]) -> list[list[float]]: + """Share reductions across attention quantiles when the native backend is enabled.""" + native = get_native() + if native is not None: + return native.mass_boxes(density, quantiles) + return [mass_box(density, q) for q in quantiles] + + +def fitted_lines( + points: list[tuple[float, float, float]], + cw: float, + ch: float, + config: RectangleConfig, +) -> list[float] | None: + """Fit word positions to cumulative character counts within transcript-order lines. + + A peak may land partway through a word. The anchor fraction models that + offset; robust slopes and intercepts recover the line's first and last edge. + Coordinates and inferred character advances are in rendered-page pixels. + """ + groups: list[list[tuple[float, float, float]]] = [] + for point in points: + if ( + not groups + or abs(point[1] - statistics.median(p[1] for p in groups[-1])) > 0.8 * ch + or point[0] < groups[-1][-1][0] - 1.5 * cw + ): + groups.append([]) + groups[-1].append(point) + slopes = [] + for group in groups: + for a, b in zip(group, group[1:]): + chars = ( + (1 - config.anchor_fraction) * a[2] + 1 + config.anchor_fraction * b[2] + ) + advance = (b[0] - a[0]) / chars + if 0.1 * cw <= advance <= 1.5 * cw: + slopes.append(advance) + if not slopes: + return None + default_advance = statistics.median(slopes) + lines = [] + for group in groups: + local = [] + for a, b in zip(group, group[1:]): + chars = ( + (1 - config.anchor_fraction) * a[2] + 1 + config.anchor_fraction * b[2] + ) + advance = (b[0] - a[0]) / chars + if 0.1 * cw <= advance <= 1.5 * cw: + local.append(advance) + advance = statistics.median(local) if len(local) >= 2 else default_advance + offsets, length = [], 0 + for x, _, chars in group: + offsets.append(x - advance * (length + config.anchor_fraction * chars)) + length += chars + 1 + left = statistics.median(offsets) + if ( + config.adaptive_anchor + and len(group) >= 5 + and len({p[2] for p in group}) >= 3 + ): + chars = np.array([p[2] for p in group], dtype=float) + preceding = np.concatenate(([0.0], np.cumsum(chars[:-1] + 1))) + xs = np.array([p[0] for p in group]) + design = np.column_stack((np.ones(len(group)), preceding, chars)) + weights = np.ones(len(group)) + for _ in range(3): + fit = np.linalg.lstsq( + design * weights[:, None], xs * weights, rcond=None + )[0] + residual = np.abs(xs - design @ fit) + scale = max(0.35 * cw, 1.5 * float(np.median(residual))) + weights = np.sqrt(np.minimum(1.0, scale / np.maximum(residual, 1e-9))) + if 0.1 * cw <= fit[1] <= 1.5 * cw and 0 <= fit[2] / fit[1] <= 1: + # Separately fitting cumulative characters and word length lets + # the observed peaks choose their own within-word anchor. + left, advance = float(fit[0]), float(fit[1]) + cy = statistics.median(p[1] for p in group) + config.y_offset * ch + h = max(0.5 * ch, min(3 * ch, config.font_height * advance)) + lines.append([left, cy - h / 2, left + advance * (length - 1), cy + h / 2]) + return envelope(lines) + + +def rectangle_boxes( + size: tuple[int, int], + answer: str, + blocks: list[Block], + units: list[tuple[int, int]], + per_block: list[list[int]], + maps: np.ndarray | SparseWordMaps, + grid: tuple[int, int], + has: np.ndarray, + config: RectangleConfig, +) -> dict: + """Fit one rectangle per emitted block using only attention and text. + + Normalize each word's retained attention before pooling so a few confident + words cannot dominate the block. Pictures retain their own spatial density. + No source pixels, PDF text layer, detector, or ground-truth boxes are read. + """ + width, height = size + gh, gw = grid + cw, ch = width / gw, height / gh + # Reuse one peak scan for occupancy, word support, and the coarse guard. + if isinstance(maps, SparseWordMaps): + peaks, maxima = maps.peaks, maps.maxima + else: + peaks = ( + maps.reshape(len(maps), -1).argmax(axis=1) + if len(maps) + else np.array([], dtype=np.int64) + ) + maxima = maps.reshape(len(maps), gh * gw)[np.arange(len(maps)), peaks] + text_occupancy = np.zeros(grid, dtype=float) + if config.image_text_suppression: + for block, indices in zip(blocks, per_block): + if block.type in ("image", "table"): + continue + for u in indices: + if has[u] and maxima[u] > 0: + text_occupancy.flat[int(peaks[u])] = 1 + text_occupancy = ndimage.maximum_filter(text_occupancy, size=3) + # The coarse guard uses the same 0.3-threshold connected word support. + # Cache cell bounds locally so that pass need not relabel each word map. + support_boxes: dict[int, tuple[int, int, int, int]] = {} + native = get_native() + reuse_support = config.connected_words and config.word_threshold == 0.3 + rust = get_rust() + fused_density = ( + rust is not None + and reuse_support + and ( + isinstance(maps, SparseWordMaps) + or (maps.dtype == np.float32 and maps.flags.c_contiguous) + ) + and not config.component_centroid + and not config.component_center + ) + boxes: list[list[float] | None] = [] + for block, indices in zip(blocks, per_block): + batch = None + if ( + fused_density + and isinstance(maps, SparseWordMaps) + and block.type != "image" + and config.centroid_radius == 1 + ): + indices = [u for u in indices if has[u] and maxima[u] > 0] + density, batch_bounds, batch_centers = rust.add_components( + [maps.indices[u] for u in indices], + [maps.values[u] for u in indices], + peaks[indices], + grid, + ) + batch = { + u: (tuple(int(v) for v in b), c) + for u, b, c in zip(indices, batch_bounds, batch_centers) + } + else: + density = np.zeros(grid, dtype=np.float64) + points = [] + for u in indices: + if not has[u] or maxima[u] <= 0: + continue + m = None if batch is not None else maps[u] + if block.type == "image": + density += m / m.sum() + continue + if fused_density: + if batch is not None: + y, x = divmod(int(peaks[u]), gw) + bounds, center = batch[u] + else: + y, x, bounds, center = rust.add_component(m, density, int(peaks[u])) + support_boxes[u] = bounds + else: + y, x = divmod(int(peaks[u]), gw) + mask = m >= config.word_threshold * maxima[u] + if config.connected_words: + if native is not None and mask[y, x]: + mask, bounds = native.peak_component_bounds(mask, y, x) + if reuse_support: + support_boxes[u] = bounds + else: + labels, _ = ndimage.label(mask, structure=np.ones((3, 3))) + mask = labels == labels[y, x] + if reuse_support and u not in support_boxes: + yy, xx = np.nonzero(mask) + support_boxes[u] = ( + int(xx.min()), + int(yy.min()), + int(xx.max()) + 1, + int(yy.max()) + 1, + ) + selected = np.where(mask, m, 0) + total = selected.sum() + if u in support_boxes: + # Preserve the full-map reduction order, but normalize and add + # only the nonzero component's bounding rectangle. + bx0, by0, bx1, by1 = support_boxes[u] + density[by0:by1, bx0:bx1] += selected[by0:by1, bx0:bx1] / total + else: + density += selected / total + px, py = x + 0.5, y + 0.5 + if config.centroid and fused_density and config.centroid_radius == 1: + px, py = center + elif config.centroid: + radius = int(config.centroid_radius) + y0, y1, x0, x1 = ( + max(0, y - radius), + min(gh, y + radius + 1), + max(0, x - radius), + min(gw, x + radius + 1), + ) + local = m[y0:y1, x0:x1] + px = float(np.dot(local.sum(0), np.arange(x0, x1) + 0.5) / local.sum()) + py = float(np.dot(local.sum(1), np.arange(y0, y1) + 0.5) / local.sum()) + if config.component_centroid: + px = float( + np.dot(selected.sum(0), np.arange(gw) + 0.5) / selected.sum() + ) + py = float( + np.dot(selected.sum(1), np.arange(gh) + 0.5) / selected.sum() + ) + if config.component_center: + yy, xx = np.nonzero(selected) + px, py = ( + (float(xx.min() + xx.max()) + 1) / 2, + (float(yy.min() + yy.max()) + 1) / 2, + ) + start, end = units[u] + word = norm(answer[start:end]) + chars = ( + sum(0.6 if c in "iljtf1" else 1.4 if c in "mw" else 1.0 for c in word) + if config.glyph_widths + else len(word) + ) + points.append((px * cw, py * ch, max(1.0, float(chars)))) + if not density.any(): + boxes.append(None) + continue + q = config.image_quantile if block.type == "image" else config.text_quantile + if block.type == "image": + peak = np.unravel_index(int(density.argmax()), grid) + labels, _ = ndimage.label( + density >= config.image_hot_threshold * density.max(), + structure=np.ones((3, 3)), + ) + core = labels == labels[peak] + if config.image_text_suppression: + # Preserve the image's strongest connected region; downweight + # distant attention that lands on separately emitted text. + density = density / ( + 1 + config.image_text_suppression * text_occupancy * ~core + ) + if config.image_power != 1: + density = (density / density.max()) ** config.image_power + share = float(density[core].sum() / density.sum()) + if config.image_component_share and share >= config.image_component_share: + density = np.where(core, density, 0) + q = 0.0 + cell_box = mass_box( + density, q, compact=config.compact_image and block.type == "image" + ) + box = [cell_box[0] * cw, cell_box[1] * ch, cell_box[2] * cw, cell_box[3] * ch] + if block.type != "image": + if config.fit_lines and block.type != "table": + box = fitted_lines(points, cw, ch, config) or box + else: + cy = (box[1] + box[3]) / 2 + config.y_offset * ch + half_height = (box[3] - box[1]) * config.text_y_scale / 2 + box[1], box[3] = cy - half_height, cy + half_height + if config.line_density and block.type != "table": + profile = density.sum(axis=1) + peaks, _ = find_peaks( + np.pad(profile, (1, 1)), height=config.density_floor * profile.max() + ) + rows = peaks - 1 + rows = rows[(rows >= cell_box[1]) & (rows < cell_box[3])] + if len(rows): + pitch = float(np.median(np.diff(rows))) if len(rows) > 1 else 2.0 + glyph_height = max(0.5, min(3.0, config.line_fill * pitch)) * ch + box[1] = (rows[0] + 0.5 + config.y_offset) * ch - glyph_height / 2 + box[3] = (rows[-1] + 0.5 + config.y_offset) * ch + glyph_height / 2 + box[0] -= config.x_padding * cw + box[2] += config.x_padding * cw + inset = min(config.y_inset * ch, 0.45 * (box[3] - box[1])) + box[1] += inset + box[3] -= inset + else: + box = [ + box[0] - config.image_padding * cw, + box[1] - config.image_padding * ch, + box[2] + config.image_padding * cw, + box[3] + config.image_padding * ch, + ] + boxes.append(box) + if config.image_whitespace: + # Only text entirely outside the seed rectangle can bound its expansion; + # chart labels inside the image must not clip the picture. + text_boxes = [ + box + for b, box in zip(blocks, boxes) + if box is not None and b.type in ("text", "heading", "list") + ] + for block, box in zip(blocks, boxes): + if block.type != "image" or box is None: + continue + x0, y0, x1, y1 = box + left, top, right, bottom = 0.0, 0.0, float(width), float(height) + for text in text_boxes: + if min(x1, text[2]) > max(x0, text[0]): + if text[3] <= y0: + top = max(top, text[3]) + elif text[1] >= y1: + bottom = min(bottom, text[1]) + if min(y1, text[3]) > max(y0, text[1]): + if text[2] <= x0: + left = max(left, text[2]) + elif text[0] >= x1: + right = min(right, text[0]) + f = config.image_whitespace + box[:] = [ + x0 + f * (left - x0), + y0 + f * (top - y0), + x1 + f * (right - x1), + y1 + f * (bottom - y1), + ] + for i, box in enumerate(boxes): + if box is None: + continue + box[:] = [ + float(np.clip(v, 0, width if axis % 2 == 0 else height)) + for axis, v in enumerate(box) + ] + if box[2] <= box[0] or box[3] <= box[1]: + boxes[i] = None + pieces = [Block(b.type, b.start, b.end) for b in blocks] + resolve_page_numbers(pieces, boxes, height) + elements = [ + { + "type": b.type, + "start": b.start, + "end": b.end, + "box": None if box is None else [round(v, 1) for v in box], + } + for b, box in zip(pieces, boxes) + ] + if config.keep_prose or config.keep_tables or config.guard_expansion: + from .coarse import attention_boxes + + prose = ( + {"text", "list", "table", "code", "formula"} + if config.keep_prose + else ({"table"} if config.keep_tables else set()) + ) + guarded = ( + {"text", "list", "heading", "header", "footer", "code", "formula"} + if config.guard_expansion + else set() + ) + selected = [ + (b, indices) + for b, indices in zip(blocks, per_block) + if b.type in prose | guarded + ] + coarse = attention_boxes( + size, + [b for b, _ in selected], + units, + [indices for _, indices in selected], + maps, + grid, + has, + support=True, + answer=answer, + support_boxes=support_boxes, + peak_indices=peaks, + ) + kept = [] + for element in elements: + if element["type"] in prose: + continue + alternatives = [ + e + for e in coarse["elements"] + if e["box"] is not None + and e["type"] == element["type"] + and e["start"] >= element["start"] + and e["end"] <= element["end"] + ] + if element["type"] in guarded and alternatives: + support_box = envelope([e["box"] for e in alternatives]) + box = element["box"] + replace = box is None or len(alternatives) > 1 + if box is not None: + sw, sh = ( + support_box[2] - support_box[0], + support_box[3] - support_box[1], + ) + overlap = max( + 0.0, min(box[2], support_box[2]) - max(box[0], support_box[0]) + ) * max( + 0.0, min(box[3], support_box[3]) - max(box[1], support_box[1]) + ) + replace |= ( + box[2] - box[0] > config.guard_expansion * sw + or box[3] - box[1] > config.guard_expansion * sh + or overlap < 0.5 * sw * sh + ) + # Preserve separately supported columns and reject extrapolation + # far beyond the words that the attention-only baseline retained. + if replace: + kept.extend(alternatives) + continue + element["box"] = [ + round(f * v + (1 - f) * support_box[axis], 1) + for axis, v in enumerate(box) + for f in [ + config.fit_blend_x if axis % 2 == 0 else config.fit_blend_y + ] + ] + kept.append(element) + elements = kept + [e for e in coarse["elements"] if e["type"] in prose] + elements.sort(key=lambda e: e["start"]) + for element in elements: + box = element["box"] + if box is None: + continue + if element["type"] == "heading": + x_scale, inset, shift = ( + config.heading_x_scale, + config.heading_y_inset, + config.heading_y_shift, + ) + elif element["type"] in ("header", "footer"): + x_scale, inset, shift = ( + config.furniture_x_scale, + config.furniture_y_inset, + config.furniture_y_shift, + ) + elif element["type"] in ("text", "list"): + x_scale, inset, shift = config.text_x_scale, config.text_y_inset, 0.0 + else: + continue + # Correct outer-edge uncertainty in cell units. Fixed edge trimming + # preserves the interior line spacing of multi-line paragraphs. + cx = (box[0] + box[2]) / 2 + half_width = (box[2] - box[0]) * x_scale / 2 + trim = min(inset * ch, 0.4 * (box[3] - box[1])) + adjusted = [ + cx - half_width, + box[1] + trim + shift * ch, + cx + half_width, + box[3] - trim + shift * ch, + ] + adjusted = [ + round(float(np.clip(v, 0, width if axis % 2 == 0 else height)), 1) + for axis, v in enumerate(adjusted) + ] + if adjusted[2] > adjusted[0] and adjusted[3] > adjusted[1]: + element["box"] = adjusted + return {"width": width, "height": height, "grid": list(grid), "elements": elements} diff --git a/parse_rl_utils/ocria_attention_grounding/regions.py b/parse_rl_utils/ocria_attention_grounding/regions.py new file mode 100644 index 0000000000000000000000000000000000000000..1c784c2e04bd3a7c6a339f8933a549fefaae8b5a --- /dev/null +++ b/parse_rl_utils/ocria_attention_grounding/regions.py @@ -0,0 +1,189 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Conservative region-edge features from predicted word boxes.""" + +from dataclasses import dataclass + +import numpy as np + +from .predict import Predictor, predict + +REGION_FEATURE_VERSION = "region-edges-v1" +REGION_FEATURE_COUNT = 47 +REGION_CONTEXT_VERSION = "region-edges-context-v1" +REGION_CONTEXT_COUNT = 86 +_REGION_TYPES = ("text", "list", "heading", "header", "footer") + + +@dataclass +class HeadingRegionBlend: + """Blend shared and heading-specific edge corrections in word-height units.""" + + base: Predictor + specialist: Predictor + + def predict(self, features: np.ndarray) -> np.ndarray: + result = predict(self.base, features).copy() + headings = features[:, _REGION_TYPES.index("heading")] == 1 + if headings.any(): + result[headings] = 0.5 * result[headings] + 0.5 * predict( + self.specialist, features[headings] + ) + return result + + +@dataclass +class HeaderRegionOverride: + """Use refreshed edge models for headers and retained models for other types.""" + + base: Predictor + refreshed: Predictor + + def predict(self, features: np.ndarray) -> np.ndarray: + headers = features[:, _REGION_TYPES.index("header")] == 1 + result = np.empty(len(features)) + if headers.any(): + result[headers] = predict(self.refreshed, features[headers]) + if (~headers).any(): + result[~headers] = predict(self.base, features[~headers]) + return result + + +@dataclass +class HeadingGlyphRegionBlend: + """Refine a heading edge with letter-shape features; preserve other types.""" + + base: Predictor + shared: Predictor + specialist: Predictor + + def predict(self, features: np.ndarray) -> np.ndarray: + geometry = features[:, :REGION_CONTEXT_COUNT] + result = np.empty(len(features)) + headings = geometry[:, _REGION_TYPES.index("heading")] == 1 + if (~headings).any(): + result[~headings] = predict(self.base, geometry[~headings]) + if headings.any(): + result[headings] = 0.5 * ( + predict(self.shared, geometry[headings]) + + predict(self.specialist, features[headings]) + ) + return result + + +def heading_glyph_features(texts: list[str]) -> np.ndarray: + """Return ascender/capital and Latin descender fractions among letters. + + These are text-shape hints, not font measurements. Geometry remains the + primary signal, including for scripts without Latin ascender conventions. + """ + result = np.zeros((len(texts), 2)) + for i, text in enumerate(texts): + letters = [char for char in text if char.isalpha()] + count = max(1, len(letters)) + result[i, 0] = ( + sum(char in "bdfhklt" or char.isupper() for char in letters) / count + ) + result[i, 1] = sum(char in "gjpqy" for char in letters) / count + return result + + +def contextual_region_features(records: list[dict]) -> np.ndarray: + """Append neighboring region geometry to uncorrected region features. + + Records are in transcript order, with grid-cell anchors and median word + heights. All neighbors use their original anchors, so applying corrections + later cannot make features depend on the order of model evaluation. + """ + anchors = [np.asarray(record["anchor"]) for record in records] + kinds = [np.argmax(record["features"][:5]) for record in records] + rows = [] + for i, record in enumerate(records): + box = anchors[i] + height = record["height"] + extra = [] + for offset in (-2, -1, 1, 2): + j = i + offset + if not 0 <= j < len(records): + extra.extend([0.0] * 7) + continue + neighbor = records[j] + extra.extend( + [ + 1.0, + *(((anchors[j] - box) / height).clip(-30, 30)).tolist(), + neighbor["height"] / height, + float(kinds[j] == kinds[i]), + ] + ) + nearby = [ + records[j] for j in range(max(0, i - 8), min(len(records), i + 9)) if j != i + ] + # Edge consensus is local in reading order and within three word heights, + # reducing interference from a separate column or an indented list. + for edge in (0, 2): + aligned = [ + (neighbor["anchor"][edge] - box[edge]) / height + for neighbor in nearby + if abs(neighbor["anchor"][edge] - box[edge]) / height < 3 + ] + extra.extend( + [len(aligned), *np.quantile(aligned, [0.1, 0.5, 0.9]).tolist()] + if aligned + else [0.0] * 4 + ) + heights = [neighbor["height"] / height for neighbor in nearby] + extra.extend( + np.quantile(heights, [0.1, 0.5, 0.9]).tolist() if heights else [0.0] * 3 + ) + rows.append([*record["features"], *extra]) + return np.asarray(rows).reshape(-1, REGION_CONTEXT_COUNT) + + +def region_features( + kind: str, + text: str, + box: np.ndarray, + gate: np.ndarray, + words: np.ndarray, + lengths: np.ndarray, + grid: tuple[int, int], +) -> tuple[list[float], float]: + """Describe a region's edges in units of its median predicted word height. + + All input boxes use grid-cell edges. `gate` is the pre-regression attention + box, and `words` contains only the words retained by that spatial guard. + Returned height converts model residuals back into grid-cell coordinates. + """ + gh, gw = grid + heights = words[:, 3] - words[:, 1] + height = max(0.1, float(np.median(heights))) + widths = words[:, 2] - words[:, 0] + relative = (np.quantile(words, [0, 0.1, 0.5, 0.9, 1], axis=0) - box) / height + area = max(0.1, (box[2] - box[0]) * (box[3] - box[1])) + features = [float(kind == value) for value in _REGION_TYPES] + features.extend( + [ + np.log1p(len(words)), + np.log1p(len(text)), + height, + (box[2] - box[0]) / height, + (box[3] - box[1]) / height, + float((widths * heights).sum() / area), + float(np.median(widths / np.maximum(1, lengths)) / height), + gh, + gw, + ] + ) + features.extend((box / [gw, gh, gw, gh]).tolist()) + features.extend(((gate - box) / height).tolist()) + features.extend(relative.ravel().tolist()) + features.extend((np.quantile(heights, [0.1, 0.5, 0.9]) / height).tolist()) + features.extend( + [ + float(np.mean([c.isupper() for c in text])) if text else 0.0, + float(np.mean([c.isdigit() for c in text])) if text else 0.0, + ] + ) + return np.asarray(features, dtype=float).tolist(), height diff --git a/parse_rl_utils/ocria_attention_grounding/repeated.py b/parse_rl_utils/ocria_attention_grounding/repeated.py new file mode 100644 index 0000000000000000000000000000000000000000..739c372cdefd0b9da0f1ad216836703a5b27daef --- /dev/null +++ b/parse_rl_utils/ocria_attention_grounding/repeated.py @@ -0,0 +1,125 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Recover a second text instance from translated, sequence-wide attention.""" + +from bisect import bisect_left, bisect_right +from collections import Counter + +import numpy as np + +from .words import norm + +_MIN_RELATIVE_PEAK = 0.15 +_MIN_SEQUENCE_SUPPORT = 0.8 + + +def recover_repeated_paragraphs( + answer: str, + capture: dict, + elements: list[dict], + units: list[tuple[int, int]], +) -> None: + """Append a translated copy only when distinctive and common words support it. + + Elements use pixel-edge boxes; sparse attention uses flattened grid cells. + Units retain the original transcript order and cache indices. Distinctive + words propose a translation, then the full sequence must corroborate it. + Original elements and their boxes remain intact. + """ + keys = [norm(answer[start:end]) for start, end in units] + counts = Counter(keys) + gh, gw = capture["grid"] + scale = np.array([capture["width"] / gw, capture["height"] / gh] * 2) + sparse = capture["sparse_maps"] + starts = [start for start, _ in units] + ends = [end for _, end in units] + added = [] + for element in elements: + if element["type"] not in {"text", "list"} or element.get("box") is None: + continue + indices = range( + bisect_left(starts, element["start"]), + bisect_right(ends, element["end"]), + ) + if len(indices) < 40: + continue + distinctive = [ + unit + for unit in indices + if len(keys[unit]) >= 5 and counts[keys[unit]] == 1 and sparse["val"][unit] + ] + if len(distinctive) < 8: + continue + box = np.asarray(element["box"]) / scale + deltas = [] + for position, unit in enumerate(distinctive): + # Even perfect support from the remaining words cannot rescue this + # proposal once its required supporting count becomes unreachable. + if len(deltas) + len(distinctive) - position < max( + 8, _MIN_SEQUENCE_SUPPORT * len(distinctive) + ): + break + mass = np.asarray(sparse["val"][unit]) + peak = int(mass.argmax()) + maximum = mass[peak] + if maximum <= 0: + continue + primary = sparse["idx"][unit][peak] + px, py = primary % gw + 0.5, primary // gw + 0.5 + if not (box[0] - 2 <= px <= box[2] + 2 and box[1] - 2 <= py <= box[3] + 2): + continue + selected = mass >= _MIN_RELATIVE_PEAK * maximum + cells = np.asarray(sparse["idx"][unit])[selected] + weights = mass[selected] + xs, ys = cells % gw + 0.5, cells // gw + 0.5 + outside = ( + (xs < box[0] - 2) + | (xs > box[2] + 2) + | (ys < box[1] - 2) + | (ys > box[3] + 2) + ) + if not outside.any(): + continue + candidates = np.flatnonzero(outside) + chosen = candidates[weights[candidates].argmax()] + deltas.append([xs[chosen] - px, ys[chosen] - py]) + if len(deltas) < 8 or len(deltas) < _MIN_SEQUENCE_SUPPORT * len(distinctive): + continue + delta = np.median(deltas, axis=0) + agreement = np.max(np.abs(np.asarray(deltas) - delta), axis=1) <= 2 + if ( + agreement.sum() < 8 + or agreement.mean() < 0.85 + or np.max(np.abs(delta) / [gw, gh]) < 0.15 + ): + continue + shifted = box + np.tile(delta, 2) + if np.any(shifted[:2] < 0) or np.any(shifted[2:] > [gw, gh]): + continue + if ( + np.maximum( + 0, np.minimum(box[2:], shifted[2:]) - np.maximum(box[:2], shifted[:2]) + ).prod() + > 0 + ): + continue + # A few distinctive words can share spurious secondary attention. + # Require the translated locations to explain the whole word sequence. + supported = 0 + for unit in indices: + if not sparse["val"][unit]: + continue + mass = np.asarray(sparse["val"][unit]) + if mass.max() <= 0: + continue + cells = np.asarray(sparse["idx"][unit]) + points = np.column_stack([cells % gw + 0.5, cells // gw + 0.5]) + target = points[mass.argmax()] + delta + nearby = np.max(abs(points - target), axis=1) <= 2 + supported += bool( + nearby.any() and mass[nearby].max() >= _MIN_RELATIVE_PEAK * mass.max() + ) + if supported >= _MIN_SEQUENCE_SUPPORT * len(indices): + added.append({**element, "box": (shifted * scale).tolist()}) + elements.extend(added) diff --git a/parse_rl_utils/ocria_attention_grounding/rust.py b/parse_rl_utils/ocria_attention_grounding/rust.py new file mode 100644 index 0000000000000000000000000000000000000000..42abae8130e7654e8c70b1004642f52a34367802 --- /dev/null +++ b/parse_rl_utils/ocria_attention_grounding/rust.py @@ -0,0 +1,436 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Optional page-batched Rust peak features, built explicitly outside the package.""" + +import argparse +import ctypes +from functools import lru_cache +import os +from pathlib import Path +import subprocess + +import numpy as np + +from .words import norm + +_LIBRARY_ENV = "OCRIA_GROUNDING_RUST" + + +class RustKernels: + """Own a trusted library; validate array dimensions before crossing the ABI.""" + + def __init__(self, path: str) -> None: + self.library = ctypes.CDLL(path) + integer = np.ctypeslib.ndpointer(np.int64, flags="C_CONTIGUOUS") + double = np.ctypeslib.ndpointer(np.float64, flags="C_CONTIGUOUS") + self.function = self.library.page_peak_features + self.function.argtypes = [ + ctypes.c_size_t, + ctypes.c_int64, + integer, + integer, + double, + integer, + double, + double, + double, + integer, + double, + integer, + ] + self.function.restype = None + self.bounds_function = self.library.context_bounds + self.bounds_function.argtypes = [ + ctypes.c_size_t, + ctypes.c_int64, + integer, + integer, + double, + double, + integer, + integer, + double, + double, + ] + self.bounds_function.restype = None + self.local_function = self.library.local_features_unsorted + self.local_function.argtypes = [ + ctypes.c_size_t, + ctypes.c_int64, + ctypes.c_int64, + integer, + integer, + double, + integer, + integer, + double, + double, + ] + self.local_function.restype = None + self.paths_function = self.library.paragraph_paths + self.paths_function.argtypes = [ctypes.c_size_t, double, integer, integer] + self.paths_function.restype = ctypes.c_size_t + self.components_function = self.library.add_components + self.components_function.argtypes = [ + ctypes.c_size_t, + ctypes.c_size_t, + ctypes.c_size_t, + integer, + integer, + np.ctypeslib.ndpointer(np.float32, flags="C_CONTIGUOUS"), + integer, + double, + integer, + double, + ] + self.components_function.restype = ctypes.c_bool + self.density_function = self.library.add_component_centroid + self.density_function.argtypes = [ + ctypes.c_size_t, + ctypes.c_size_t, + np.ctypeslib.ndpointer(np.float32, flags="C_CONTIGUOUS"), + ctypes.c_size_t, + double, + integer, + double, + ] + self.density_function.restype = ctypes.c_size_t + + def peak_features( + self, + context: np.ndarray, + valid: list[int], + positions: np.ndarray, + sparse: dict, + grid: tuple[int, int], + eligible: set[int], + ) -> tuple[np.ndarray, list[tuple[int, int, list[int]]]]: + """Pack eligible words once; return features and original sparse positions.""" + chosen = [(j, u) for j, u in enumerate(valid) if u in eligible] + if not chosen: + return np.empty((0, 22)), [] + if ( + context.ndim != 2 + or context.shape[0] != len(valid) + or context.shape[1] < 53 + or positions.shape != (len(valid), 2) + or grid[1] <= 0 + ): + raise ValueError("Invalid peak context, positions, or grid width") + js, us = zip(*chosen) + arrays = [np.asarray(sparse["val"][u], dtype=np.float64) for u in us] + indices = [np.asarray(sparse["idx"][u], dtype=np.int64) for u in us] + if any( + a.ndim != 1 or ix.ndim != 1 or not len(a) or len(a) != len(ix) + for a, ix in zip(arrays, indices) + ): + raise ValueError( + "Peak attention needs matching finite nonempty sparse arrays" + ) + offsets = np.r_[0, np.cumsum([len(a) for a in arrays])].astype(np.int64) + values = np.concatenate(arrays) + packed_indices = np.concatenate(indices) + if not np.isfinite(values).all() or np.any(packed_indices < 0): + raise ValueError( + "Peak attention needs matching finite nonempty sparse arrays" + ) + # NumPy retains the reference tie order and logarithm rounding. + order = np.concatenate([np.argsort(-a) for a in arrays]) + contexts = np.ascontiguousarray(context[list(js), :53], dtype=np.float64) + ps = np.ascontiguousarray(positions[list(js)], dtype=np.float64) + logs = np.ascontiguousarray(np.log1p(contexts[:, [0, 36, 40, 44, 48]])) + retained = np.empty((len(us), 4), dtype=np.int64) + out = np.empty((len(us), 4, 22)) + counts = np.empty(len(us), dtype=np.int64) + self.function( + len(us), + grid[1], + offsets, + packed_indices, + values, + order, + contexts, + ps, + logs, + retained, + out, + counts, + ) + records = [] + start = 0 + for j, u in enumerate(us): + n = int(counts[j]) + records.append((u, start, retained[j, :n].tolist())) + start += n + # Keep the native feature buffer; incomplete candidate rows are padding. + rows = ( + out.reshape(-1, 22) + if np.all(counts == 4) + else out[np.arange(4) < counts[:, None]] + ) + return rows, records + + def context_bounds( + self, + sparse: dict, + valid: list[int], + peaks: np.ndarray, + grid_width: int, + ) -> tuple[np.ndarray, list[tuple[np.ndarray, np.ndarray, np.ndarray]]]: + """Batch cell quantiles and threshold bounds, retaining normalized masses.""" + if grid_width <= 0 or peaks.shape != (len(valid), 2): + raise ValueError("Invalid context peak shape or grid width") + rows = [] + for u in valid: + ix = np.asarray(sparse["idx"][u], dtype=np.int64) + attention = np.asarray(sparse["val"][u], dtype=np.float64) + if ( + ix.ndim != 1 + or attention.ndim != 1 + or not len(ix) + or len(ix) != len(attention) + ): + raise ValueError( + "Context needs matching finite positive sparse attention" + ) + rows.append((ix, attention)) + if not rows: + return np.empty((0, 22)), [] + offsets = np.r_[0, np.cumsum([len(v[0]) for v in rows])].astype(np.int64) + indices = np.concatenate([v[0] for v in rows]) + attention = np.concatenate([v[1] for v in rows]) + if ( + np.any(indices < 0) + or not np.isfinite(attention).all() + or np.any(attention < 0) + or np.any(np.maximum.reduceat(attention, offsets[:-1]) <= 0) + ): + raise ValueError("Context needs matching finite positive sparse attention") + # Preserve reference float-coordinate tie ordering before cumulative sums. + if all(len(row[0]) == len(rows[0][0]) for row in rows): + # Top-k captures usually have equal row lengths. Sort both axes in + # batches while retaining NumPy's per-row coordinate tie ordering. + weights = attention.reshape(len(rows), -1) + normalized = weights / weights.sum(axis=1)[:, None] + mass = normalized.ravel() + packed = [ + (ix, values, normalized[j]) for j, (ix, values) in enumerate(rows) + ] + cells = indices.reshape(len(rows), -1) + order_x = np.argsort(cells % grid_width + 0.5, axis=1).ravel() + order_y = np.argsort(cells // grid_width + 0.5, axis=1).ravel() + else: + packed = [(ix, values, values / values.sum()) for ix, values in rows] + mass = np.concatenate([v[2] for v in packed]) + order_x = np.concatenate( + [np.argsort(v[0] % grid_width + 0.5) for v in packed] + ) + order_y = np.concatenate( + [np.argsort(v[0] // grid_width + 0.5) for v in packed] + ) + out = np.empty((len(valid), 22)) + self.bounds_function( + len(valid), + grid_width, + offsets, + indices, + attention, + mass, + order_x, + order_y, + np.ascontiguousarray(peaks, dtype=np.float64), + out, + ) + return out, packed + + def local_features( + self, + answer: str, + units: list[tuple[int, int]], + sparse: dict, + grid: tuple[int, int], + anchors: dict[int, int] | None = None, + ) -> tuple[np.ndarray, list[int], np.ndarray]: + """Batch word patches and moments, preserving original unit indices.""" + if grid[0] <= 0 or grid[1] <= 0: + raise ValueError("Attention grid dimensions must be positive") + arrays, indices, valid, lengths, selected = [], [], [], [], [] + rows = [] + for u, (start, end) in enumerate(units): + ix = np.asarray(sparse["idx"][u], dtype=np.int64) + values = np.asarray(sparse["val"][u], dtype=np.float64) + if not len(ix) or not sparse["has"][u]: + continue + if ix.ndim != 1 or values.ndim != 1 or len(ix) != len(values): + raise ValueError("Invalid sparse word attention") + rows.append((u, start, end, ix, values)) + # Validate before dropping zero-mass rows, using one scan per packed array. + if rows: + all_indices = np.concatenate([row[3] for row in rows]) + all_values = np.concatenate([row[4] for row in rows]) + if ( + not np.isfinite(all_values).all() + or np.any(all_indices < 0) + or np.any(all_indices >= grid[0] * grid[1]) + or np.any(all_values < 0) + ): + raise ValueError("Invalid sparse word attention") + for u, start, end, ix, values in rows: + if not values.max(): + continue + chosen = -1 + if anchors and u in anchors: + chosen = anchors[u] + if chosen < 0 or chosen >= len(values): + raise ValueError("Anchor is outside sparse word attention") + selected.append(chosen) + indices.append(ix) + arrays.append(values) + valid.append(u) + lengths.append(len(norm(answer[start:end]))) + out = np.empty((len(valid), 34)) + peaks = np.empty((len(valid), 2)) + if not valid: + return out, valid, peaks + offsets = np.r_[0, np.cumsum([len(a) for a in arrays])].astype(np.int64) + self.local_function( + len(valid), + grid[0], + grid[1], + offsets, + np.concatenate(indices), + np.concatenate(arrays), + np.asarray(lengths, dtype=np.int64), + np.asarray(selected, dtype=np.int64), + out, + peaks, + ) + return out, valid, peaks + + def paragraph_paths(self, boxes: list[list[float]]) -> list[list[int]] | None: + """Return transcript-index paths through finite pixel-coordinate boxes.""" + if len(boxes) < 3: + return None + values = np.ascontiguousarray(boxes, dtype=np.float64) + if values.shape != (len(boxes), 4) or not np.isfinite(values).all(): + raise ValueError("Paragraph paths require finite N x 4 boxes") + out = np.empty(len(boxes), dtype=np.int64) + offsets = np.empty(len(boxes) + 1, dtype=np.int64) + count = self.paths_function(len(boxes), values, out, offsets) + return ( + [out[offsets[k] : offsets[k + 1]].tolist() for k in range(count)] + if count + else None + ) + + def add_components( + self, + indices: list[np.ndarray], + values: list[np.ndarray], + seeds: np.ndarray, + grid: tuple[int, int], + ) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Accumulate sparse word components in order, returning bounds and centroids.""" + if len(indices) != len(values) or seeds.shape != (len(indices),): + raise ValueError("Component rows and seeds must match") + if ( + grid[0] <= 0 + or grid[1] <= 0 + or any( + ix.ndim != 1 or v.ndim != 1 or len(ix) != len(v) + for ix, v in zip(indices, values) + ) + ): + raise ValueError("Invalid component grid or sparse row shape") + density = np.zeros(grid, dtype=np.float64) + bounds = np.empty((len(indices), 4), dtype=np.int64) + centers = np.empty((len(indices), 2)) + if not indices: + return density, bounds, centers + offsets = np.r_[0, np.cumsum([len(ix) for ix in indices])].astype(np.int64) + cells = np.ascontiguousarray(np.concatenate(indices), dtype=np.int64) + mass = np.ascontiguousarray(np.concatenate(values), dtype=np.float32) + seeds = np.ascontiguousarray(seeds, dtype=np.int64) + if ( + np.any(cells < 0) + or np.any(cells >= density.size) + or np.any(seeds < 0) + or np.any(seeds >= density.size) + ): + raise ValueError("Component cell is outside the attention grid") + if not self.components_function( + *grid, len(indices), offsets, cells, mass, seeds, density, bounds, centers + ): + raise ValueError("Component seed must have positive finite attention") + return density, bounds, centers + + def add_component( + self, + attention: np.ndarray, + density: np.ndarray, + seed: int | None = None, + ) -> tuple[int, int, tuple[int, int, int, int], np.ndarray]: + """Normalize the 0.3-threshold peak component using float64 accumulation.""" + if ( + attention.ndim != 2 + or not attention.size + or attention.dtype != np.float32 + or not attention.flags.c_contiguous + or density.shape != attention.shape + or density.dtype != np.float64 + or not density.flags.c_contiguous + or not density.flags.writeable + ): + raise ValueError("Component accumulation needs matching contiguous grids") + seed = int(attention.argmax()) if seed is None else seed + if seed < 0 or seed >= attention.size: + raise ValueError("Component seed is outside the attention grid") + if not np.isfinite(attention.flat[seed]) or attention.flat[seed] <= 0: + raise ValueError("Component seed must have positive finite attention") + bounds = np.empty(4, dtype=np.int64) + center = np.empty(2) + self.density_function( + *attention.shape, attention, seed, density, bounds, center + ) + y, x = divmod(seed, attention.shape[1]) + return ( + y, + x, + (int(bounds[0]), int(bounds[1]), int(bounds[2]), int(bounds[3])), + center, + ) + + +@lru_cache(maxsize=1) +def get_rust() -> RustKernels | None: + """Load only an explicitly configured local shared library.""" + path = os.environ.get(_LIBRARY_ENV) + return RustKernels(path) if path else None + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", required=True, type=Path) + args = parser.parse_args() + args.output.parent.mkdir(parents=True, exist_ok=True) + subprocess.run( + [ + "rustc", + "--crate-type", + "cdylib", + "--edition", + "2021", + "-O", + str(Path(__file__).with_name("peak_kernels.rs")), + "-o", + str(args.output), + ], + check=True, + timeout=120, + ) + print(f"Set {_LIBRARY_ENV}={args.output.resolve()}") + + +if __name__ == "__main__": + main() diff --git a/parse_rl_utils/ocria_attention_grounding/tables.py b/parse_rl_utils/ocria_attention_grounding/tables.py new file mode 100644 index 0000000000000000000000000000000000000000..83351262ee5e79d660fa4e4915a306b97bb96fe0 --- /dev/null +++ b/parse_rl_utils/ocria_attention_grounding/tables.py @@ -0,0 +1,529 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Candidate table/chart extents from transcript structure and sparse attention.""" + +from bisect import bisect_left, bisect_right +import re +from typing import Protocol +from .predict import predict + +import numpy as np +from .blocks import Block +from .rectangles import mass_box, mass_boxes +from .pictures import ious + +TABLE_FEATURE_VERSION = "table-candidates-v1" +TABLE_FEATURE_COUNT = 41 +TABLE_SELECTION_MARGIN = 0.05 + + +class TablePredictor(Protocol): + def predict(self, features: np.ndarray) -> np.ndarray: ... + + +_HINTS = ( + "figure", + "chart", + "graph", + "plot", + "series", + "axis", + "reference line", + "table", +) + + +def table_candidates( + answer: str, + blocks: list[Block], + per: list[list[int]], + units: list[tuple[int, int]], + capture: dict, + block_index: int, + original: list[float], +) -> tuple[list[list[float]], list[list[float]]]: + """Propose grid-cell rectangles using table words, cell alignment, and neighbors. + + The first candidate preserves the original box. Chart-like transcripts can + place numeric cells throughout a plot; their pooled attention and adjacent + captions provide broader extents than a connected-word component alone. + """ + gh, gw = capture["grid"] + sp = capture["sparse_maps"] + block = blocks[block_index] + us = [ + u + for u in per[block_index] + if sp["has"][u] and sp["val"][u] and max(sp["val"][u]) > 0 + ] + if not us: + return [], [] + peak_by = {} + density = np.zeros((gh, gw)) + sharp = np.zeros_like(density) + for u in us: + ix = np.asarray(sp["idx"][u]) + v = np.asarray(sp["val"][u]) + p = ix[v.argmax()] + peak_by[u] = (p % gw + 0.5, p // gw + 0.5) + density.flat[ix] += v / v.sum() + keep = v >= 0.3 * v.max() + sharp.flat[ix[keep]] += v[keep] / v[keep].sum() + density /= density.sum() + sharp /= sharp.sum() + peaks = np.array([peak_by[u] for u in us]) + boxes = [original] + kinds = [0] + + def add(b: np.ndarray | list[float], kind: int) -> None: + b = np.clip(b, 0, [gw, gh, gw, gh]).tolist() + if b[2] > b[0] and b[3] > b[1] and b not in boxes: + boxes.append(b) + kinds.append(kind) + + for kind, m in [(1, density), (2, sharp)]: + for box in mass_boxes(m, [0, 0.01, 0.025, 0.05, 0.1, 0.2]): + add(box, kind) + quantiles = np.array([0, 0.01, 0.025, 0.05, 0.1]) + low, high = np.quantile(peaks, [quantiles, 1 - quantiles], axis=0) + for lower, upper in zip(low, high): + bb = np.r_[lower - 0.5, upper + 0.5] + for pad in [0, 0.5, 1, 2]: + add(bb + np.array([-pad, -pad, pad, pad]), 3) + # The generated heading often represents axis/legend text of a chart. + if block_index and blocks[block_index - 1].type == "heading": + heading = [] + for u in per[block_index - 1]: + if sp["has"][u] and sp["val"][u] and max(sp["val"][u]) > 0: + p = sp["idx"][u][int(np.argmax(sp["val"][u]))] + heading.append([p % gw + 0.5, p // gw + 0.5]) + if heading: + joint = np.vstack([peaks, heading]) + add( + np.r_[ + np.quantile(joint, 0.01, axis=0) - 0.5, + np.quantile(joint, 0.99, axis=0) + 0.5, + ], + 4, + ) + anchors = [] + for direction in [-1, 1]: + anchor = None + for k in range( + block_index + direction, -1 if direction < 0 else len(blocks), direction + ): + if blocks[k].type in ("image", "table"): + break + pts = [] + for u in per[k]: + if sp["has"][u] and sp["val"][u] and max(sp["val"][u]) > 0: + p = sp["idx"][u][int(np.argmax(sp["val"][u]))] + pts.append([p % gw + 0.5, p // gw + 0.5]) + if pts: + pts = np.array(pts) + anchor = np.r_[ + np.quantile(pts, 0.05, axis=0) - 0.5, + np.quantile(pts, 0.95, axis=0) + 0.5, + ] + break + anchors.append(anchor) + seed = np.array(mass_box(sharp, 0.025)) + prev, nxt = anchors + top = prev[3] if prev is not None and prev[3] < seed[1] else seed[1] + bottom = nxt[1] if nxt is not None and nxt[1] > seed[3] else seed[3] + for fraction in [0.25, 0.5, 0.75, 1.0]: + b = seed.copy() + b[1] += fraction * (top - b[1]) + b[3] += fraction * (bottom - b[3]) + add(b, 5) + available = [a for a in anchors if a is not None] + if available: + b[0] = min(b[0], min(a[0] for a in available)) + b[2] = max(b[2], max(a[2] for a in available)) + add(b, 6) + # Cell alignment distinguishes a printed grid from values read off a plot. + cells = [] + word_starts = [units[u][0] for u in us] + for row, tr in enumerate( + re.finditer( + r"]*>(.*?)", answer[block.start : block.end], re.I | re.S + ) + ): + for col, cell in enumerate( + re.finditer(r"]*>(.*?)", tr.group(1), re.I | re.S) + ): + start = block.start + tr.start(1) + cell.start(1) + end = block.start + tr.start(1) + cell.end(1) + first = bisect_left(word_starts, start) + last = bisect_right(word_starts, end) + ps = [peak_by[u] for u in us[first:last] if units[u][1] <= end] + if ps: + cells.append([row, col, *np.median(ps, axis=0)]) + structure = [0.0] * 8 + if cells: + c = np.array(cells) + rows = np.unique(c[:, 0]) + cols = np.unique(c[:, 1]) + sx = max(1.0, np.std(c[:, 2])) + sy = max(1.0, np.std(c[:, 3])) + row_scatter = np.mean([np.std(c[c[:, 0] == r, 3]) for r in rows]) / sy + col_scatter = np.mean([np.std(c[c[:, 1] == r, 2]) for r in cols]) / sx + + def corr(a: np.ndarray, b: np.ndarray) -> float: + a = a - a.mean() + b = b - b.mean() + return float( + (a * b).sum() / max(1e-9, np.sqrt((a * a).sum() * (b * b).sum())) + ) + + structure = [ + len(rows), + len(cols), + len(cells), + row_scatter, + col_scatter, + corr(c[:, 0], c[:, 3]), + corr(c[:, 1], c[:, 2]), + sx / sy, + ] + nearby = ( + answer[max(0, block.start - 400) : block.start].lower() + + " " + + answer[block.end : block.end + 250].lower() + ) + hints = [float(h in nearby) for h in _HINTS] + numeric_fraction = sum( + answer[units[u][0] : units[u][1]].replace(".", "").replace("-", "").isdigit() + for u in us + ) / len(us) + features = [] + for b, kind in zip(boxes, kinds): + x0, y0, x1, y1 = b + inside = ( + (peaks[:, 0] >= x0) + & (peaks[:, 0] <= x1) + & (peaks[:, 1] >= y0) + & (peaks[:, 1] <= y1) + ) + patch = density[int(y0) : int(np.ceil(y1)), int(x0) : int(np.ceil(x1))] + area = (x1 - x0) * (y1 - y0) + mass = float(patch.sum()) + f = [ + kind, + x0 / gw, + y0 / gh, + x1 / gw, + y1 / gh, + (x1 - x0) / gw, + (y1 - y0) / gh, + area / (gw * gh), + mass, + float(inside.mean()), + np.log1p(len(us)), + float(numeric_fraction), + gh, + gw, + ] + f += ( + structure + + hints + + ious(np.array([b]), np.array([original])).ravel().tolist() + + ((np.array(b) - original) / [gw, gh, gw, gh]).tolist() + ) + for anchor in anchors: + f.extend( + [0.0, 0.0, 0.0] + if anchor is None + else [1.0, (y0 - anchor[3]) / gh, (y1 - anchor[1]) / gh] + ) + features.append(f) + return boxes, features + + +def refine_tables( + capture: dict, + answer: str, + blocks: list[Block], + per_block: list[list[int]], + units: list[tuple[int, int]], + result: dict, + model: TablePredictor, +) -> None: + """Replace a table box only when predicted quality clears the baseline margin. + + Transcript spans and table types are preserved, including charts transcribed + as HTML tables. Features use cached attention and text, with no page pixels. + """ + gh, gw = capture["grid"] + scale = np.array([capture["width"] / gw, capture["height"] / gh] * 2) + elements = { + (element["start"], element["end"]): element + for element in result["elements"] + if element["type"] == "table" and element["box"] is not None + } + for block_index, block in enumerate(blocks): + if block.type != "table": + continue + element = elements.get((block.start, block.end)) + if element is None: + continue + original = (np.asarray(element["box"]) / scale).tolist() + boxes, features = table_candidates( + answer, blocks, per_block, units, capture, block_index, original + ) + if not boxes: + continue + quality = predict(model, np.asarray(features)) + selected = int(quality.argmax()) + if quality[selected] > quality[0] + TABLE_SELECTION_MARGIN: + element["box"] = (np.asarray(boxes[selected]) * scale).tolist() + + +_TABLE_CELL = re.compile(r"]*>(.*?)", re.S | re.I) + + +def coherent_table_words( + selected: list[int], + cells: list[list[int]], + boxes: np.ndarray, + peaks: np.ndarray, +) -> list[int]: + """Drop isolated word bands while preserving support in every table cell. + + Coordinates and predicted word heights use attention-grid cells. Each axis + needs a band containing 90% of the words; sparse genuine rows or columns + survive when any cell depends on them. + """ + for axis in (0, 1): + if len(selected) < 12: + break + ordered = sorted(selected, key=lambda j: peaks[j, axis]) + gap = max(3.0, 3 * float(np.median(boxes[selected, 3] - boxes[selected, 1]))) + bands: list[list[int]] = [[]] + for j in ordered: + if bands[-1] and peaks[j, axis] - peaks[bands[-1][-1], axis] > gap: + bands.append([]) + bands[-1].append(j) + main = max(bands, key=len) + members = set(main) + if len(main) >= 0.9 * len(selected) and all( + members.intersection(cell) for cell in cells + ): + selected = main + return selected + + +def _refine_supported_table_words( + answer: str, + elements: list[dict], + units: list[tuple[int, int]], + valid: list[int], + boxes: np.ndarray, + peaks: np.ndarray, + scale: np.ndarray, +) -> None: + """Refine whole-table extents from supported cell words, preserving one region. + + Word boxes and peaks use grid cells; element boxes and the result use pixels. + Every cell with available word predictions must have support inside the old + table bounds plus one grid cell. A cell whose predictions all lie outside + that guard preserves the old table box. + """ + starts = [units[u][0] for u in valid] + for element in elements: + if element["type"] != "table" or element["box"] is None: + continue + bounds = np.asarray(element["box"]) / scale + selected: list[int] = [] + cell_groups: list[list[int]] = [] + complete = True + for cell in _TABLE_CELL.finditer(answer, element["start"], element["end"]): + first = bisect_left(starts, cell.start(1)) + last = bisect_right(starts, cell.end(1)) + rows = [j for j in range(first, last) if units[valid[j]][1] <= cell.end(1)] + if not rows: + continue + supported = [ + j + for j in rows + if bounds[0] - 1 <= peaks[j, 0] <= bounds[2] + 1 + and bounds[1] - 1 <= peaks[j, 1] <= bounds[3] + 1 + ] + if not supported: + complete = False + break + selected.extend(supported) + cell_groups.append(supported) + if complete and len(cell_groups) >= 2: + selected = coherent_table_words(selected, cell_groups, boxes, peaks) + words = boxes[selected] + element["box"] = ( + np.r_[words[:, :2].min(0), words[:, 2:].max(0)] * scale + ).tolist() + # Text glyphs stop short of the table's vertical cell padding. + padding = 0.25 * float(np.median(words[:, 3] - words[:, 1])) * scale[1] + element["box"][1] -= padding + element["box"][3] += padding + + +_TABLE_ROW = re.compile(r"]*>(.*?)", re.S | re.I) + + +def refine_table_word_boxes( + answer: str, + elements: list[dict], + units: list[tuple[int, int]], + valid: list[int], + boxes: np.ndarray, + peaks: np.ndarray, + scale: np.ndarray, +) -> None: + """Recover vertically truncated tables from ordered, multi-column cell rows. + + Peaks and word boxes use grid cells; element boxes use pixels. Two HTML rows + must independently agree outside the coarse bounds before those bounds expand. + The expanded guard still requires support from every available table cell. + """ + snapshots = [ + (e, list(e["box"])) + for e in elements + if e["type"] == "table" and e["box"] is not None + ] + _refine_supported_table_words(answer, elements, units, valid, boxes, peaks, scale) + starts = [units[u][0] for u in valid] + for element, old in snapshots: + bounds = np.array(old) / scale + votes: list[list[tuple[list[int], float]]] = [[], []] + for row in _TABLE_ROW.finditer(answer, element["start"], element["end"]): + cells: list[list[list[int]]] = [[], []] + for cell in _TABLE_CELL.finditer(answer, row.start(1), row.end(1)): + first = bisect_left(starts, cell.start(1)) + last = bisect_right(starts, cell.end(1)) + indices = [ + j for j in range(first, last) if units[valid[j]][1] <= cell.end(1) + ] + if not indices: + continue + supported = [ + j for j in indices if bounds[0] - 1 <= peaks[j, 0] <= bounds[2] + 1 + ] + if len(supported) < 0.9 * len(indices): + continue + for direction in (0, 1): + outside = [ + j + for j in supported + if ( + peaks[j, 1] < bounds[1] - 1 + if direction == 0 + else peaks[j, 1] > bounds[3] + 1 + ) + ] + if len(outside) >= 0.8 * len(supported): + cells[direction].append(outside) + for direction in (0, 1): + row_cells = cells[direction] + if len(row_cells) < 2: + continue + # Separate columns must agree on a row band, allowing multiline cells. + centers = np.array( + [ + np.median(peaks[word_indices], axis=0) + for word_indices in row_cells + ] + ) + heights = [np.ptp(peaks[word_indices, 1]) for word_indices in row_cells] + if np.ptp(centers[:, 0]) < 2 or np.ptp(centers[:, 1]) > max( + 2, float(np.median(heights)) + ): + continue + votes[direction].append( + ( + [j for word_indices in row_cells for j in word_indices], + float(np.median(centers[:, 1])), + ) + ) + expanded = bounds.copy() + for direction in (0, 1): + ordered_rows = votes[direction] + if len(ordered_rows) < 2 or any( + b[1] <= a[1] for a, b in zip(ordered_rows, ordered_rows[1:]) + ): + continue + indices = [j for word_indices, _ in ordered_rows for j in word_indices] + if direction == 0: + expanded[1] = min(expanded[1], float(peaks[indices, 1].min())) + else: + expanded[3] = max(expanded[3], float(peaks[indices, 1].max())) + if np.array_equal(expanded, bounds): + continue + guard = (expanded * scale).tolist() + candidate = {**element, "box": guard.copy()} + _refine_supported_table_words( + answer, [candidate], units, valid, boxes, peaks, scale + ) + # A cell without support leaves the guard untouched; preserve the prior result. + if candidate["box"] != guard: + element["box"] = candidate["box"] + expand_chart_category_axis(answer, elements, units, valid, peaks, scale) + + +def expand_chart_category_axis( + answer: str, + elements: list[dict], + units: list[tuple[int, int]], + valid: list[int], + peaks: np.ndarray, + scale: np.ndarray, +) -> None: + """Extend categorical chart bounds by half the category spacing at each end. + + HTML data rows can describe bars rather than physical table rows. Require + three evenly spaced horizontal labels with aligned values above them. + Peaks use grid cells; element boxes and the updated bounds use pixels. + """ + starts = [units[u][0] for u in valid] + for element in elements: + if element["type"] != "table" or element["box"] is None: + continue + rows = list(_TABLE_ROW.finditer(answer, element["start"], element["end"])) + labels = [] + values = [] + for row in rows[1:]: + cells = list(_TABLE_CELL.finditer(answer, row.start(1), row.end(1))) + if len(cells) != 2: + break + centers = [] + for cell in cells: + first = bisect_left(starts, cell.start(1)) + last = bisect_right(starts, cell.end(1)) + indices = [ + j for j in range(first, last) if units[valid[j]][1] <= cell.end(1) + ] + if not indices: + break + centers.append(np.median(peaks[indices], axis=0)) + if len(centers) != 2: + break + labels.append(centers[0]) + values.append(centers[1]) + if len(labels) < 3 or len(labels) != len(rows) - 1: + continue + category_points = np.asarray(labels) + value_points = np.asarray(values) + steps = np.diff(category_points[:, 0]) + if ( + np.ptp(category_points[:, 1]) > 1 + or np.any(steps < 2) + or steps.max() > 1.5 * steps.min() + or np.any(abs(value_points[:, 0] - category_points[:, 0]) > 2) + or np.sum(value_points[:, 1] < category_points[:, 1] - 2) + < 0.75 * len(labels) + ): + continue + bounds = np.asarray(element["box"]) / scale + half_step = float(np.median(steps)) / 2 + bounds[0] = min(bounds[0], category_points[0, 0] - half_step) + bounds[2] = max(bounds[2], category_points[-1, 0] + half_step) + element["box"] = (bounds * scale).tolist() diff --git a/parse_rl_utils/ocria_attention_grounding/tune.py b/parse_rl_utils/ocria_attention_grounding/tune.py new file mode 100644 index 0000000000000000000000000000000000000000..2d9002d7229b791c443e03ce756f5725af8d0837 --- /dev/null +++ b/parse_rl_utils/ocria_attention_grounding/tune.py @@ -0,0 +1,14 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Hill-climbing switches: OCRIA_ATTENTION_TUNE="flag,key=value,..." read once at import. Code behind a switch must behave as +before when the switch is off, so earlier replays stay reproducible; a winning switch becomes the default and is +removed (README.md).""" + +import os + +FLAGS: dict[str, str] = {} +for _item in os.environ.get("OCRIA_ATTENTION_TUNE", "").split(","): + if _item.strip(): + _k, _, _v = _item.partition("=") + FLAGS[_k.strip()] = _v.strip() or "1" diff --git a/parse_rl_utils/ocria_attention_grounding/words.py b/parse_rl_utils/ocria_attention_grounding/words.py new file mode 100644 index 0000000000000000000000000000000000000000..46e9971a08f84bd2a146f22389c645fc992f66ba --- /dev/null +++ b/parse_rl_utils/ocria_attention_grounding/words.py @@ -0,0 +1,39 @@ +# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. +# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). +# This is not open-source software: see the license for permitted uses. +"""Content words of a transcript (shared by the GPU capture and the scoring): character spans that hold page text, +with markup removed, so ocria's RCL / HTML / markdown and Gemini's markdown / HTML are cut the same way.""" + +import re + +# HTML tags (a letter after "<", one line: a bare "<" is text, e.g. RCL's merge-left cell or "< 8.0 V"); +# markdown link / image targets +TAG = re.compile(r"\n]*>|\]\([^)\s]*\)|!\[") +# a word starts with a letter or digit (or a currency sign / opening bracket before one) and runs over letters, digits and +# in-word punctuation; markdown/RCL markup (#, *, |, !, `, _, quotes) is never part of a word +WORD = re.compile(r"[$€£¥₹(]?[^\W_][^\s<>|*`\"\t]*") +_NON_WORD = re.compile(r"[\W_]") +TRAIL = ".,;:)]}!?'’" + + +def norm(w: str) -> str: + lowered = w.lower() + return lowered if lowered.isalnum() else _NON_WORD.sub("", lowered) + + +def word_spans(text: str) -> list[tuple[int, int, str]]: + masked = TAG.sub(lambda m: " " * len(m.group()), text) + masked = masked.replace(" ", " ").replace("&", "& ") + out = [] + for m in WORD.finditer(masked): + s, e = m.start(), m.end() + while ( + e > s + 1 + and masked[e - 1] in TRAIL + and not (masked[e - 1] == ")" and "(" in masked[s : e - 1]) + ): + e -= 1 + w = text[s:e] + if norm(w): + out.append((s, e, w)) + return out diff --git a/processor_config.json b/processor_config.json new file mode 100644 index 0000000000000000000000000000000000000000..a9804dd9789683a33fe72bd98bc0ccb71663afd1 --- /dev/null +++ b/processor_config.json @@ -0,0 +1,64 @@ +{ + "image_processor": { + "data_format": "channels_first", + "do_convert_rgb": true, + "do_normalize": true, + "do_rescale": true, + "do_resize": true, + "image_mean": [ + 0.5, + 0.5, + 0.5 + ], + "image_processor_type": "Qwen2VLImageProcessor", + "image_std": [ + 0.5, + 0.5, + 0.5 + ], + "merge_size": 2, + "patch_size": 16, + "resample": 3, + "rescale_factor": 0.00392156862745098, + "size": { + "longest_edge": 16777216, + "shortest_edge": 65536 + }, + "temporal_patch_size": 2 + }, + "processor_class": "Qwen3VLProcessor", + "video_processor": { + "data_format": "channels_first", + "default_to_square": true, + "do_convert_rgb": true, + "do_normalize": true, + "do_rescale": true, + "do_resize": true, + "do_sample_frames": true, + "fps": 2, + "image_mean": [ + 0.5, + 0.5, + 0.5 + ], + "image_std": [ + 0.5, + 0.5, + 0.5 + ], + "max_frames": 768, + "max_video_tokens": 768, + "merge_size": 2, + "min_frames": 4, + "patch_size": 16, + "resample": 3, + "rescale_factor": 0.00392156862745098, + "return_metadata": false, + "size": { + "longest_edge": 25165824, + "shortest_edge": 4096 + }, + "temporal_patch_size": 2, + "video_processor_type": "Qwen3VLVideoProcessor" + } +} diff --git a/prompt.txt b/prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..f4a14666fe7cd3b3807fb6f02dca423ee4fbc038 --- /dev/null +++ b/prompt.txt @@ -0,0 +1,55 @@ +Transcribe this Page in markdown, be as accurate as possible in your transcription, do not describe/summarize. + +Formatting: +- Use ** for bold text and * for italic text. +- Use ~~ text ~~ for strikethrough text. Only use this for text that is visually stricken through. +- Use and tags for highlighted text, aka text to wich a stabilo hilight was applied Only use to hilight sentence or words, not full block of text/tables. Use HTML color names for different colors of highlight, e.g. text. Do not use mark for first cell of a table, as it is often used for the header and should not be highlighted. +- Use and tags for underlined text. +- Use \* for bullet points and - for sub-bullets. +- Use > for blockquotes. +- Use ` for inline code. +- Use ``` for code blocks. +- Use [ ] for empty checkboxes. +- Use [x] for checked checkboxes. +- Use and for subscript text. +- Use and for superscript text. +- Use [___] for empty fields to fill, if the field is already filled, represent them as field content in markdown. +- Use $...$ for inline equations and $$...$$ for display equations. Do NOT use \(...\) or \[...\] — the corpus uses dollar delimiters (43,604 inline occurrences against 35 in the parenthesis form). +- Chemical formulas are NOT LaTeX: write them as plain text with and , e.g. K3Fe(CN)6 and 2H2O, never $K_3Fe(CN)_6$. Reserve $...$ for real mathematics. + +Tables: +- Output tables in HTML when possible. +- Table should not be use for page formatting (column or grid like layout), but only for tabular data. +- Some table may be irregular, with merged cells, missing cells, or inconsistent formatting, or have an exotic structure (like a triangular table). Do your best to represent the table accurately with correct reading order. + +Charts, Graphs, and Figures: +- IMPORTANT: Every chart or graph MUST be converted into an HTML . This is non-negotiable. The table represent the chart data, not the chart layout. Focus on accurately capturing the underlying data and relationships in the table format. +- FORBIDDEN outputs for charts: