[
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\nweights/\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\n*.egg-info/\n.installed.cfg\n*.egg\n\n# PyInstaller\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n.hypothesis/\n.pytest_cache/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# pyenv\n.python-version\n\n# celery beat schedule file\ncelerybeat-schedule\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n.dmypy.json\ndmypy.json\n\n# IDEs\n.vscode/\n.idea/\n*.swp\n*.swo\n*~\n\n# MacOS\n.DS_Store\n\n# OCR related\n#*.jpg\n# *.jpeg\n#*.png\n#*.pdf\ntemp/\noutput/ \n# playground/"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2025 rednote-hilab\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "NOTICE",
    "content": "==================================================================\n=============== Copyright Notice and License Texts ===============\n==================================================================\n\n\n------------- LICENSE FOR gradio CODE --------------\n \nCopyright notice:No copyright info provided\n\nLicense:apache2.0\n\nApache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n    \"License\" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.\n\n    \"Licensor\" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.\n\n    \"Legal Entity\" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition,\n      \n\"control\" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.\n\n    \"You\" (or \"Your\") shall mean an individual or Legal Entity exercising permissions granted by this License.\n\n    \"Source\" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.\n\n    \"Object\" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.\n\n    \"Work\" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).\n\n    \"Derivative Works\" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.\n\n   \"Contribution\" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, \"submitted\" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as \"Not a Contribution.\"\n\n    \"Contributor\" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:\n\n    (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and\n\n    (b) You must cause any modified files to carry prominent notices stating that You changed the files; and\n\n    (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and\n\n    (d) If the Work includes a \"NOTICE\" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.\n\n    You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions.Not withstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n    To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets \"[]\" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same \"printed page\" as the copyright notice for easier identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at\n\n   http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n\n\n\n------------- LICENSE FOR gradio_image_annotation CODE --------------\n \nCopyright notice：Copyright (c) 2024 Edgar Gracia\nLicense :MIT\nMIT License\n\nCopyright (c) 2024 Edgar Gracia\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n\n------------- LICENSE FOR PyMuPDF CODE  --------------\n \nCopyright notice：Copyright (C) 2007 Free Software Foundation, Inc.\n\nLicense ：AGPL-3.0 license\n\nGNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.\n\n  The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.\n\n  When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.\n\n  Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.\n\n  A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.\n\n  The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.\n\n  An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.\n\n  The precise terms and conditions for copying, distribution and modification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU Affero General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this License. Each licensee is addressed as \"you\".  \"Licensees\" and \"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a \"modified version\" of the earlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based on theProgram.\n\n  To \"propagate\" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work for makingmodifications to it.  \"Object code\" means any non-source form of a work.\n\n  A \"Standard Interface\" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Co ponent, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A \"Major Component\", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which theexecutable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.\n\n  The Corresponding Source for a work in source code form is that same work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.\n\n  When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you receive it in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:\n\n  a) The work must carry prominent notices stating that you modified it, and giving a relevant date.\n\n  b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to \"keep intact all notices\".\n\n  c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.\n\n  d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.\n\n  A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an \"aggregate\" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:\n\n  a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on an adurable physical medium customarily used for software interchange.\n\n  b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.\n\n  c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.\n\n  d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.\n\n  e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, \"normally used\" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.\n\n  If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).\n\n  The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided, in accordance with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separatelyunder those permissions, but the entire Program remains governed by this License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it.  (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further restrictions\" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly providedunder this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).\n\n  However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, \"control\" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To \"grant\" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients.  \"Knowingly relying\" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.\n\n  13. Remote Network Interaction; Use with the GNU General Public License.\n\n  Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to theCorresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.\n\n  Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version3 of the GNU General Public License.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.\n\n  Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License \"or any later version\" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the\nGNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.\n\n  Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the \"copyright\" line and a pointer to where the full notice is found.\n\n  <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year>  <name of author>\n\n  This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n\n  This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\n\n  You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a \"Source\" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.\n\n\n\n------------- LICENSE FOR openai CODE --------------\n\nCopyright notice:Copyright 2025 OpenAI\n\nLicense:apache2.0\n\nPlease see above.\n\n\n\n------------- LICENSE FOR qwen_vl_utils CODE --------------\n\nCopyright notice:No copyright info provided\n\nLicense:apache2.0\n\nPlease see above.\n\n\n\n------------- LICENSE FOR transformers CODE --------------\n\nCopyright notice:Copyright 2018- The Hugging Face team. All rights reserved.\n\nLicense:apache2.0\n\nPlease see above.\n\n\n\n------------- LICENSE FOR huggingface_hub CODE --------------\n\nCopyright notice:No copyright info provided\n\nLicense:apache2.0\n\nPlease see above.\n\n\n\n------------- LICENSE FOR flash-attn CODE --------------\n\nCopyright notice:Copyright (c) 2022, the respective contributors, as shown by the AUTHORS file. All rights reserved.\n\nLicense:BSD-3-Clause license\n\nBSD 3-Clause License\n\nCopyright (c) 2022, the respective contributors, as shown by the AUTHORS file. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this list ofconditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n\n* Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISEDOF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n\n------------- LICENSE FOR accelerate CODE --------------\n\nCopyright notice:No copyright info provided\n\nLicense:apache2.0\n\nPlease see above.\n\n\n\n------------- LICENSE FOR MonkeyOCR CODE --------------\n\nCopyright notice:No copyright info provided\n\nLicense:apache2.0\n\nPlease see above.\n\n\n\n------------- LICENSE FOR OmniDocbench CODE --------------\n\nCopyright notice:No copyright info provided\n\nLicense:apache2.0\n\nPlease see above.\n\n\n\n------------- LICENSE FOR Qwen2.5-VL CODE --------------\n\nCopyright notice:No copyright info provided\n\nLicense:apache2.0\n\nPlease see above.\n\n\n\n------------- LICENSE FOR aimv2 CODE --------------\n\nCopyright notice: Copyright (C) 2024 Apple Inc. All Rights Reserved.\n\nLicense：\n\nIMPORTANT:  This Apple software is supplied to you by Apple Inc. (\"Apple\") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms.  If you do not agree with these terms, please do not use, install, modify or\nredistribute this Apple software.\n\nIn consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the \"Apple Software\"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. May be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple.  Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated.\n\nThe Apple Software is provided by Apple on an \"AS IS\" basis.  APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS\nFOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL\nOR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nSOFTWARE DISTRIBUTED WITH AUTOREGRESSIVE IMAGE MODELS:\n\nThe Autoregressive Image Models software includes a number of subcomponents with\nseparate  copyright notices and license terms - please see the file ACKNOWLEDGEMENTS.\n\nAcknowledgements：\n\nPortions of the Autoregressive Image Models project may utilize the following copyrighted material, the use of which is hereby acknowledged.\n\n\n------------- LICENSE FOR Hugging Face CODE --------------\n\nCopyright notice：Copyright 2019 Ross Wightman\n\nLicense:apache2.0\n\nPlease see above.\n\n\n\n------------- LICENSE FOR vLLM CODE --------------\n\nCopyright notice:No copyright info provided\n\nLicense:apache2.0\n\nPlease see above.\n\n\n\n------------- LICENSE FOR Doclaynet --------------\n\nCopyright notice:No copyright info provided\n\nLicense:Community Data License Agreement\n\nCommunity Data License Agreement – Permissive – Version 1.0\n\nThis is the Community Data License Agreement – Permissive, Version 1.0 (“Agreement”). Data is provided to You under this Agreement by each of the Data Providers. Your exercise of any of the rights and permissions granted below constitutes your acceptance and agreement to be bound by the terms and conditions of this Agreement.\n\nThe benefits that each Data Provider receives from making Data available and that You receive from Data or otherwise under these terms and conditions shall be deemed sufficient consideration for the formation of this Agreement. Accordingly, Data Provider(s) and You (the \"Parties\") agree as follows:\n\nSection 1.  Definitions\n\n1.1 \"Add\" means to supplement Data with Your own or someone else's Data, resulting in Your “Additions.” Additions do not include Results.\n\n1.2 \"Computational Use\" means Your analysis (through the use of computational devices or otherwise) or other interpretation of Data. By way of example and not limitation, \"Computational Use\" includes the application of any computational analytical technique, the purpose of which is the analysis of any Data in digital form to generate information about Data such as patterns, trends, correlations, inferences, insights and attributes.\n\n1.3 \"Data\" means the information (including copyrightable information, such as images or text), collectively or individually, whether created or gathered by a Data Provider or an Entity acting on its behalf, to which rights are granted under this Agreement.\n\n1.4 \"Data Provider\" means any Entity (including any employee or contractor of such Entity authorized to Publish Data on behalf of such Entity) that Publishes Data under this Agreement prior to Your Receiving it.\n\n1.5 \"Enhanced Data\" means the subset of Data that You Publish and that is composed of (a) Your Additions and/or (b) Modifications to Data You have received under this Agreement.\n\n1.6 \"Entity\" means any natural person or organization that exists under the laws of the jurisdiction in which it is organized, together with all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, \"control\" means (a) the power, directly or indirectly, to cause the direction or management of such entity, whether by contract or otherwise, (b) the ownership of more than fifty percent (50%) of the outstanding shares or securities, (c) the beneficial ownership of such entity or, (d) the ability to appoint, whether by agreement or right, the majority of directors of an Entity.\n\n1.7 \"Modify\" means to delete, erase, correct or re-arrange Data, resulting in “Modifications.” Modifications do not include Results.\n\n1.8 \"Publish\" means to make all or a subset of Data (including Your Enhanced Data) available in any manner which enables its use, including by providing a copy on physical media or remote access. For any form of Entity, that is to make the Data available to any individual who is not employed by that Entity or engaged as a contractor or agent to perform work on that Entity's behalf. A \"Publication\" occurs each time you Publish Data.\n\n1.9 \"Receive\" or \"Receives\" means to have been given access to Data, locally or remotely.\n\n1.10 \"Results\" means the outcomes or outputs that You obtain from Your Computational Use of Data. Results shall not include more than a de minimis portion of the Data on which the Computational Use is based.\n\n1.11 \"Sui Generis Database Rights\" means rights, other than copyright, resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other equivalent rights anywhere in the world.\n\n1.12 \"Use\" means using Data (including accessing, copying, studying, reviewing, adapting, analyzing, evaluating, or making Computational Use of it), either by machines or humans, or a combination of both.\n\n1.13 \"You\" or \"Your\" means any Entity that Receives Data under this Agreement.\n\nSection 2. Right and License to Use and to Publish\n\n2.1 Subject to the conditions set forth in Section 3 of this Agreement, Data Provider(s) hereby grant(s) to You a worldwide, non-exclusive, irrevocable (except as provided in Section 5) right to: (a) Use Data; and (b) Publish Data.\n\n2.2 To the extent that the Data or the coordination, selection or arrangement of Data is protected or protectable under copyright, Sui Generis Database Rights, or other law, Data Provider(s) further agree(s) that such Data or coordination, selection or arrangement is hereby licensed to You and to anyone else who Receives Data under this Agreement for Use and Publication, subject to the conditions set forth in Section 3 of this Agreement.\n\n2.3 Except for these rights and licenses expressly granted, no other intellectual property rights are granted or should be implied.\n\nSection 3. Conditions on Rights Granted\n\n3.1 If You Publish Data You Receive or Enhanced Data:\n\n(a) You may do so under a license of your choice provided that you give anyone who receives the data from you the text of this Agreement, the name of this Agreement and/or a hyperlink or other method reasonably likely to provide a copy of the text of this Agreement; and\n\n(b) You must cause any Data files containing Enhanced Data to carry prominent notices that you have changed those files; and\n\n(c) If You Publish Data You Receive, You must preserve all credit or attribution to the Data Provider(s). Such retained credit or attribution includes any of the following to the extent they exist in the Data as You have Received it: legal notices or metadata; identification of the Data Provider(s); or hyperlinks to Data to the extent it is practical to do so.\n\n3.2 You may provide additional or different license terms and conditions for use, reproduction, or distribution of that Enhanced Data, or for any combination of Data and Enhanced Data as a whole, provided that Your Use and Publication of that combined Data otherwise complies with the conditions stated in this License.\n\n3.3 You and each Data Provider agree that Enhanced Data shall not be considered a work of joint authorship by virtue of its relationship to Data licensed under this Agreement and shall not require either any obligation of accounting to or the consent of any Data Provider.\n\n3.4 This Agreement imposes no obligations or restrictions on Your Use or Publication of Results.\n\nSection 4. Data Provider(s)' Representations\n\n4.1 Each Data Provider represents that the Data Provider has exercised reasonable care, to assure that: (a) the Data it Publishes was created or generated by it or was obtained from others with the right to Publish the Data under this Agreement; and (b) Publication of such Data does not violate any privacy or confidentiality obligation undertaken by the Data Provider.\n\nSection 5.  Termination\n\n5.1 All of Your rights under this Agreement will terminate, and Your right to Receive, Use or Publish the Data will be revoked or modified if You materially fail to comply with the terms and conditions of this Agreement and You do not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If your rights under this Agreement terminate, you agree to cease Receipt, Use and Publication of Data. However, your obligations and any rights and permissions granted by you under this Agreement relating to Data that you published prior to such termination will continue and survive.\n\n5.2 If you institute litigation against a Data Provider or anyone else who Receives the Data (including a cross-claim in a lawsuit) based on the Data, other than a claim asserting breach of this Agreement, then any rights previously granted to You to Receive, Use and Publish Data under this Agreement will terminate as of the date such litigation is filed.\n\nSection 6. Disclaimer of Warranties and Limitation of Liability\n\n6.1 EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE DATA (INCLUDING ENHANCED DATA) IS PROVIDED 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.\n\n6.2 NEITHER YOU NOR ANY DATA PROVIDERS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE DATA OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n\nSection 7.  Miscellaneous\n\n7.1 You agree that it is solely your responsibility to comply with all applicable laws with regard to Your Use or Publication of Data, including any applicable privacy, data protection, security and export laws. You agree to take reasonable steps to assist a Data Provider fulfilling responsibilities to comply with applicable laws with regard to Use or Publication of Data Received hereunder.\n\n7.2 You and Data Provider(s), collectively and individually, waive and/or agree not to assert, to the extent permitted by law, any moral rights you or they hold in Data.\n\n7.3 This Agreement confers no rights or remedies upon any person or entity other than the Parties and their respective heirs, executors, successors and assigns.\n\n7.4 The Data Provider(s) reserve no right or expectation of privacy, data protection or confidentiality in any Data that they Publish under this Agreement. If you choose to Publish Data under this Agreement, you similarly do so with no reservation or expectation of any rights of privacy or confidentiality in that Data.\n\n7.5 The Community Data License Agreement workgroup under The Linux Foundation is the steward of this Agreement (“Steward”). No one other than the Steward has the right to modify or publish new versions of this Agreement. Each version will be given a distinguishing version number. You may Use and Publish Data Received hereunder under the terms of the version of the Agreement under which You originally Received the Data, or under the terms of any subsequent version published by the Steward.\n\n\n\n------------- LICENSE FOR M6Doc --------------\n\nCopyright notice:No copyright info provided\n\nLicense:Attribution-NonCommercial-NoDerivatives 4.0\n\n=======Attribution-NonCommercial-NoDerivatives 4.0 International==========\n\nCreative Commons Corporation (\"Creative Commons\") is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an \"as-is\" basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.\n\nUsing Creative Commons Public Licenses\n\nCreative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.\n\nConsiderations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC- licensed material, or material used under an exception or limitation to copyright. More considerations for licensors: wiki.creativecommons.org/Considerations_for_licensors\n\nConsiderations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor's permission is not necessary for any reason--for example, because of any applicable exception or limitation to copyright--then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public: wiki.creativecommons.org/Considerations_for_licensees\n\nCreative Commons Attribution-NonCommercial-NoDerivatives 4.0 International Public License\n\nBy exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International Public License (\"Public License\"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.\n\n\nSection 1 -- Definitions.\n\n  a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.\n\n  b. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.\n\n  c. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.\n\n  d. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.\n\n  e. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.\n\n  f. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.\n\n  g. Licensor means the individual(s) or entity(ies) granting rights under this Public License.\n\n  h. NonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.\n\n  i. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.\n\n  j. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.\n\n  k. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.\n\n\nSection 2 -- Scope.\n\n  a. License granted.\n\n  1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:\n\n a. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and\n\n   b. produce and reproduce, but not Share, Adapted Material for NonCommercial purposes only.\n\n  2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.\n\n   3. Term. The term of this Public License is specified in Section 6(a).\n\n   4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a) (4) never produces Adapted Material.\n\n   5. Downstream recipients.\n\n   a. Offer from the Licensor -- Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.\n\n   b. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.\n\n   6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that you are, or that your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).\n\n  b. Other rights.\n\n  1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.\n\n   2. Patent and trademark rights are not licensed under this Public License.\n\n   3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.\n\n\nSection 3 -- License Conditions.\n\nYour exercise of the Licensed Rights is expressly made subject to the\nfollowing conditions.\n\n  a. Attribution.\n\n  1. If You Share the Licensed Material, You must:\n\n a. retain the following if it is supplied by the Licensor with the Licensed Material:\n\n    i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);\n\n    ii. a copyright notice;\n\n    iii. a notice that refers to this Public License;\n\n    iv. a notice that refers to the disclaimer of warranties;\n\n    v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;\n\n    b. indicate if you modified the Licensed Material and retain an indication of any previous modifications; and\n\n    c. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. For the avoidance of doubt, you do not have permission under this Public License to Share Adapted Material.\n\n   2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which you share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.\n\n   3. If requested by the Licensor, you must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.\n\n\nSection 4 -- Sui Generis Database Rights.\n\nWhere the Licensed Rights include Sui Generis Database Rights that\napply to Your use of the Licensed Material:\n\n  a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only and provided You do not Share Adapted Material;\n\n  b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and\n\n  c. You must comply with the conditions in Section 3(a) if you share all or a substantial portion of the contents of the database.\n\nFor the avoidance of doubt, this Section 4 supplements and does not replace your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.\n\n\nSection 5 -- Disclaimer of Warranties and Limitation of Liability.\n\n  a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.\n\n  b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.\n\n  c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer andwaiver of all liability.\n\n\nSection 6 -- Term and Termination.\n\n  a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.\n\n  b. Where your right to use the Licensed Material has terminated under Section 6(a), it reinstates:\n\n  1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or\n\n  2. upon express reinstatement by the Licensor.\n\n  For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.\n\n  c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.\n\n  d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.\n\n\nSection 7 -- Other Terms and Conditions.\n\n  a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.\n\n  b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.\n\n\nSection 8 -- Interpretation.\n\n  a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.\n\n  b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.\n\n  c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.\n\n  d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.\n\nCreative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the \"Licensor.\" The text of the Creative Commons public licenses is dedicated to the public domain under the CC0 Public\nDomain Dedication. Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark \"Creative Commons\" or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.\n\nCreative Commons may be contacted at creativecommons.org.\n\n\n\n------------- LICENSE FOR CDLA --------------\n\nCopyright notice:No copyright info provided\n\nLicense:No License info provided\n\n\n\n------------- LICENSE FOR D4LA --------------\n\nCopyright notice:No copyright info provided\n\nLicense:No License info provided"
  },
  {
    "path": "README.md",
    "content": "<div align=\"center\">\n\n<p align=\"center\">\n    <img src=\"https://raw.githubusercontent.com/rednote-hilab/dots.ocr/master/assets/logo.png\" width=\"300\"/>\n<p>\n\n<h1 align=\"center\">\ndots.ocr\n</h1>\n\n[![HuggingFace](https://img.shields.io/badge/HuggingFace%20Weights-black.svg?logo=HuggingFace)](https://huggingface.co/rednote-hilab/dots.ocr-1.5)\n[![Arxiv](https://img.shields.io/badge/arXiv-Paper-B31B1B.svg?logo=arxiv)](https://arxiv.org/abs/2512.02498)\n\n\n<div align=\"center\">\n  <a href=\"https://dotsocr.xiaohongshu.com\" target=\"_blank\" rel=\"noopener noreferrer\"><strong>🖥️ Live Demo</strong></a> | \n  <a href=\"https://raw.githubusercontent.com/rednote-hilab/dots.ocr/master/assets/wechat.jpg\" target=\"_blank\" rel=\"noopener noreferrer\"><strong>💬 WeChat</strong></a> | \n  <a href=\"https://www.xiaohongshu.com/user/profile/683ffe42000000001d021a4c\" target=\"_blank\" rel=\"noopener noreferrer\"><strong>📕 rednote</strong></a> | \n  <a href=\"https://x.com/rednotehilab\" target=\"_blank\" rel=\"noopener noreferrer\"><strong>🐦 X</strong></a>\n</div>\n\n</div>\n\n\n\n## Introduction\n\n**dots.ocr** Designed for universal accessibility, it possesses the capability to recognize virtually any human script. Beyond achieving state-of-the-art (SOTA) performance in standard multilingual document parsing among models of comparable size, dots.ocr-1.5 excels at converting structured graphics (e.g., charts and diagrams) directly into SVG code, parsing web screens and spotting scene text. \n\n## News \n* ```2026.03.19 ``` We have rebranded `dots.ocr-1.5` as [dots.mocr](https://github.com/rednote-hilab/dots.mocr). For technical details, please refer to our [paper](https://arxiv.org/abs/2603.13032v1). The model weights are available on Hugging Face: [dots.mocr](https://huggingface.co/rednote-hilab/dots.mocr) and [dots.mocr-svg](https://huggingface.co/rednote-hilab/dots.mocr-svg).\n* ```2025.10.31 ``` 🚀 We release [dots.ocr.base](https://huggingface.co/rednote-hilab/dots.ocr.base), foundation VLM focus on OCR tasks, also the base model of [dots.ocr](https://huggingface.co/rednote-hilab/dots.ocr). Try it out!\n* ```2025.07.30 ``` 🚀 We release [dots.ocr](https://huggingface.co/rednote-hilab/dots.ocr), — a multilingual documents parsing model based on 1.7b llm, with SOTA performance.\n\n\n\n\n## Evaluation\n\n### 1. Document Parsing\n\n#### 1.1 Elo Score of different bench between latest models\n\n<table>\n  <thead>\n    <tr>\n      <th>models</th>\n      <th>olmOCR-Bench</th>\n      <th>OmniDocBench (v1.5)</th>\n      <th>XDocParse</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>GLM-OCR</td>\n      <td>859.9</td>\n      <td>937.5</td>\n      <td>742.1</td>\n    </tr>\n    <tr>\n      <td>PaddleOCR-VL-1.5</td>\n      <td>873.6</td>\n      <td>965.6</td>\n      <td>797.6</td>\n    </tr>\n    <tr>\n      <td>HuanyuanOCR</td>\n      <td>978.9</td>\n      <td>974.4</td>\n      <td>895.9</td>\n    </tr>\n    <tr>\n      <td>dots.ocr</td>\n      <td>1027.4</td>\n      <td>994.7</td>\n      <td>1133.4</td>\n    </tr>\n    <!-- Highlighting dots.ocr-1.5 row with bold tags -->\n    <tr>\n      <td><strong>dots.ocr-1.5</strong></td>\n      <td><strong>1089.0</strong></td>\n      <td><strong>1025.8</strong></td>\n      <td><strong>1157.1</strong></td>\n    </tr>\n    <tr>\n      <td>Gemini 3 Pro</td>\n      <td>1171.2</td>\n      <td>1102.1</td>\n      <td>1273.9</td>\n    </tr>\n  </tbody>\n</table>\n\n\n> **Notes:** \n> - Results for Gemini 3 Pro, PaddleOCR-VL-1.5, and GLM-OCR were obtained via APIs, while HuanyuanOCR results were generated using local inference.\n> - The Elo score evaluation was conducted using Gemini 3 Flash. The prompt can be found at: [Elo Score Prompt](https://github.com/rednote-hilab/dots.ocr/blob/master/tools/elo_score_prompt.py). These results are consistent with the findings on [ocrarena](https://www.ocrarena.ai/battle).\n\n\n#### 1.2 olmOCR-bench\n<table>\n    <thead>\n        <tr>\n            <th>Model</th>\n            <th>ArXiv</th>\n            <th>Old scans math</th>\n            <th>Tables</th>\n            <th>Old scans</th>\n            <th>Headers & footers</th>\n            <th>Multi column</th>\n            <th>Long tiny text</th>\n            <th>Base</th>\n            <th>Overall</th>\n        </tr>\n    </thead>\n    <tbody>\n        <tr>\n            <td>Mistral OCR API</td>\n            <td>77.2</td>\n            <td>67.5</td>\n            <td>60.6</td>\n            <td>29.3</td>\n            <td>93.6</td>\n            <td>71.3</td>\n            <td>77.1</td>\n            <td>99.4</td>\n            <td>72.0±1.1</td>\n        </tr>\n        <tr>\n            <td>Marker 1.10.1</td>\n            <td>83.8</td>\n            <td>66.8</td>\n            <td>72.9</td>\n            <td>33.5</td>\n            <td>86.6</td>\n            <td>80.0</td>\n            <td>85.7</td>\n            <td>99.3</td>\n            <td>76.1±1.1</td>\n        </tr>\n        <tr>\n            <td>MinerU 2.5.4*</td>\n            <td>76.6</td>\n            <td>54.6</td>\n            <td>84.9</td>\n            <td>33.7</td>\n            <td>96.6</td>\n            <td>78.2</td>\n            <td>83.5</td>\n            <td>93.7</td>\n            <td>75.2±1.1</td>\n        </tr>\n        <tr>\n            <td>DeepSeek-OCR</td>\n            <td>77.2</td>\n            <td>73.6</td>\n            <td>80.2</td>\n            <td>33.3</td>\n            <td>96.1</td>\n            <td>66.4</td>\n            <td>79.4</td>\n            <td>99.8</td>\n            <td>75.7±1.0</td>\n        </tr>\n        <tr>\n            <td>Nanonets-OCR2-3B</td>\n            <td>75.4</td>\n            <td>46.1</td>\n            <td>86.8</td>\n            <td>40.9</td>\n            <td>32.1</td>\n            <td>81.9</td>\n            <td>93.0</td>\n            <td>99.6</td>\n            <td>69.5±1.1</td>\n        </tr>\n        <tr>\n            <td>PaddleOCR-VL*</td>\n            <td>85.7</td>\n            <td>71.0</td>\n            <td>84.1</td>\n            <td>37.8</td>\n            <td>97.0</td>\n            <td>79.9</td>\n            <td>85.7</td>\n            <td>98.5</td>\n            <td>80.0±1.0</td>\n        </tr>\n        <tr>\n            <td>Infinity-Parser 7B*</td>\n            <td>84.4</td>\n            <td>83.8</td>\n            <td>85.0</td>\n            <td>47.9</td>\n            <td>88.7</td>\n            <td>84.2</td>\n            <td>86.4</td>\n            <td>99.8</td>\n            <td>82.5±?</td>\n        </tr>\n        <tr>\n            <td>olmOCR v0.4.0</td>\n            <td>83.0</td>\n            <td>82.3</td>\n            <td>84.9</td>\n            <td>47.7</td>\n            <td>96.1</td>\n            <td>83.7</td>\n            <td>81.9</td>\n            <td>99.7</td>\n            <td>82.4±1.1</td>\n        </tr>\n        <tr>\n            <td>Chandra OCR 0.1.0*</td>\n            <td>82.2</td>\n            <td>80.3</td>\n            <td>88.0</td>\n            <td>50.4</td>\n            <td>90.8</td>\n            <td>81.2</td>\n            <td>92.3</td>\n            <td>99.9</td>\n            <td>83.1±0.9</td>\n        </tr>\n        <tr>\n            <td>dots.ocr</td>\n            <td>82.1</td>\n            <td>64.2</td>\n            <td>88.3</td>\n            <td>40.9</td>\n            <td>94.1</td>\n            <td>82.4</td>\n            <td>81.2</td>\n            <td>99.5</td>\n            <td>79.1±1.0</td>\n        </tr>\n        <tr>\n            <td><strong>dots.ocr-1.5</strong></td>\n            <td><strong>85.9</strong></td>\n            <td><strong>85.5</strong></td>\n            <td><strong>90.7</strong></td>\n            <td>48.2</td>\n            <td>94.0</td>\n            <td><strong>85.3</strong></td>\n            <td>81.6</td>\n            <td>99.7</td>\n            <td><strong>83.9±0.9</strong></td>\n        </tr>\n    </tbody>\n</table>\n\n\n> **Note:**\n> - The metrics are from [olmocr](https://github.com/allenai/olmocr), and our own internal evaluations.\n> - We delete the Page-header and Page-footer cells in the result markdown.\n\n\n#### 1.3 Other Benchmarks\n\n<table>\n  <thead>\n    <tr>\n      <th>Model Type</th>\n      <th>Methods</th>\n      <th>Size</th>\n      <th>OmniDocBench(v1.5)<br>TextEdit↓</th>\n      <th>OmniDocBench(v1.5)<br>Read OrderEdit↓</th>\n      <th>pdf-parse-bench</th>\n    </tr>\n  </thead>\n  <tbody>\n    <!-- GeneralVLMs Group (Reversed Order, 3 rows) -->\n    <tr>\n      <td rowspan=\"3\"><strong>GeneralVLMs</strong></td>\n      <td>Gemini-2.5 Pro</td>\n      <td>-</td>\n      <td>0.075</td>\n      <td>0.097</td>\n      <td>9.06</td>\n    </tr>\n    <tr>\n      <td>Qwen3-VL-235B-A22B-Instruct</td>\n      <td>235B</td>\n      <td>0.069</td>\n      <td>0.068</td>\n      <td><strong>9.71</strong></td>\n    </tr>\n    <tr>\n      <td>gemini3pro</td>\n      <td>-</td>\n      <td>0.066</td>\n      <td>0.079</td>\n      <td>9.68</td>\n    </tr>\n    <!-- SpecializedVLMs Group (Reversed Order, 12 rows) -->\n    <tr>\n      <td rowspan=\"12\"><strong>SpecializedVLMs</strong></td>\n      <td>Mistral OCR</td>\n      <td>-</td>\n      <td>0.164</td>\n      <td>0.144</td>\n      <td>8.84</td>\n    </tr>\n    <tr>\n      <td>Deepseek-OCR</td>\n      <td>3B</td>\n      <td>0.073</td>\n      <td>0.086</td>\n      <td>8.26</td>\n    </tr>\n    <tr>\n      <td>MonkeyOCR-3B</td>\n      <td>3B</td>\n      <td>0.075</td>\n      <td>0.129</td>\n      <td>9.27</td>\n    </tr>\n    <tr>\n      <td>OCRVerse</td>\n      <td>4B</td>\n      <td>0.058</td>\n      <td>0.071</td>\n      <td>--</td>\n    </tr>\n    <tr>\n      <td>MonkeyOCR-pro-3B</td>\n      <td>3B</td>\n      <td>0.075</td>\n      <td>0.128</td>\n      <td>-</td>\n    </tr>\n    <tr>\n      <td>MinerU2.5</td>\n      <td>1.2B</td>\n      <td>0.047</td>\n      <td>0.044</td>\n      <td>-</td>\n    </tr>\n    <tr>\n      <td>PaddleOCR-VL</td>\n      <td>0.9B</td>\n      <td>0.035</td>\n      <td>0.043</td>\n      <td>9.51</td>\n    </tr>\n    <tr>\n      <td>HunyuanOCR</td>\n      <td>0.9B</td>\n      <td>0.042</td>\n      <td>-</td>\n      <td>-</td>\n    </tr>\n    <tr>\n      <td>PaddleOCR-VL1.5</td>\n      <td>0.9B</td>\n      <td>0.035</td>\n      <td>0.042</td>\n      <td>-</td>\n    </tr>\n    <tr>\n      <td>GLMOCR</td>\n      <td>0.9B</td>\n      <td>0.04</td>\n      <td>0.043</td>\n      <td>-</td>\n    </tr>\n    <tr>\n      <td>dots.ocr</td>\n      <td>3B</td>\n      <td>0.048</td>\n      <td>0.053</td>\n      <td>9.29</td>\n    </tr>\n    <tr>\n      <td><u><strong>dots.ocr-1.5</strong></u></td>\n      <td>3B</td>\n      <td><strong>0.031</strong></td>\n      <td><strong>0.029</strong></td>\n      <td>9.54</td>\n    </tr>\n  </tbody>\n</table>\n\n> **Note:**\n> - Metrics are sourced from [OmniDocBench](https://github.com/opendatalab/OmniDocBench) and other model publications. [pdf-parse-bench](https://github.com/phorn1/pdf-parse-bench) results are reproduced by Qwen3-VL-235B-A22B-Instruct.\n> - Formula and Table metrics for OmniDocBench1.5 are omitted due to their high sensitivity to detection and matching protocols.\n\n\n### 2. Vision-Language Parsing\nVisual languages (e.g., charts, graphics, chemical formulas, logos) encapsulate dense human knowledge. **dots.ocr-1.5** unifies the interpretation of these elements by parsing them directly into **SVG code**.\n\n<table>\n  <thead>\n    <tr>\n      <th rowspan=\"2\" style=\"text-align: left;\">Methods</th>\n      <th colspan=\"3\">Unisvg</th>\n      <th rowspan=\"2\">Chartmimic</th>\n      <th rowspan=\"2\">Design2Code</th>\n      <th rowspan=\"2\">Genexam</th>\n      <th rowspan=\"2\">SciGen</th>\n      <th rowspan=\"2\">ChemDraw</th>\n    </tr>\n    <tr>\n      <th>Low-Level</th>\n      <th>High-Level</th>\n      <th>Score</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td style=\"text-align: left;\">OCRVerse</td>\n      <td>0.632</td>\n      <td>0.852</td>\n      <td>0.763</td>\n      <td>0.799</td>\n      <td>-</td>\n      <td>-</td>\n      <td>-</td>\n      <td>0.881</td>\n    </tr>\n    <tr>\n      <td style=\"text-align: left;\">Gemini 3 Pro</td>\n      <td>0.563</td>\n      <td>0.850</td>\n      <td>0.735</td>\n      <td>0.788</td>\n      <td>0.760</td>\n      <td>0.756</td>\n      <td>0.783</td>\n      <td>0.839</td>\n    </tr>\n    <tr>\n      <td style=\"text-align: left;\">dots.ocr-1.5</td>\n      <td>0.850</td>\n      <td>0.923</td>\n      <td>0.894</td>\n      <td>0.772</td>\n      <td>0.801</td>\n      <td>0.664</td>\n      <td>0.660</td>\n      <td>0.790</td>\n    </tr>\n    <tr>\n      <td style=\"text-align: left;\"><strong>dots.ocr-1.5-svg</strong></td>\n      <td><strong>0.860</strong></td>\n      <td><strong>0.931</strong></td>\n      <td><strong>0.902</strong></td>\n      <td><strong>0.905</strong></td>\n      <td><strong>0.834</strong></td>\n      <td><strong>0.8</strong></td>\n      <td><strong>0.797</strong></td>\n      <td><strong>0.901</strong></td>\n    </tr>\n  </tbody>\n</table>\n\n\n> **Note:**\n> - We use the ISVGEN metric from [UniSVG](https://ryanlijinke.github.io/) to evaluate the parsing result. For benchmarks that do not natively support image parsing, we use the original images as input, and calculate the ISVGEN score between the rendered output and the original image. \n> - [OCRVerse](https://github.com/DocTron-hub/OCRVerse) results are derived from various code formats (e.g., SVG, Python), whereas results for Gemini 3 Pro and dots.ocr-1.5 are based specifically on SVG code.\n> - Due to the capacity constraints of a 3B-parameter VLM, dots.ocr-1.5 may not excel in all tasks yet like svg. To complement this, we are simultaneously releasing dots.ocr-1.5-svg. We plan to further address these limitations in future updates.\n\n\n### 3. General Vision Tasks\n\n<table>\n    <thead>\n        <tr>\n            <th>Model</th>\n            <th>CharXiv_descriptive</th>\n            <th>CharXiv_reasoning</th>\n            <th>OCR_Reasoning</th>\n            <th>infovqa</th>\n            <th>docvqa</th>\n            <th>ChartQA</th>\n            <th>OCRBench</th>\n            <th>AI2D</th>\n            <th>CountBenchQA</th>\n            <th>refcoco</th>\n        </tr>\n    </thead>\n    <tbody>\n        <tr>\n            <td>Qwen3vl-2b-instruct</td>\n            <td>62.3</td>\n            <td>26.8</td>\n            <td>-</td>\n            <td>72.4</td>\n            <td>93.3</td>\n            <td>-</td>\n            <td>85.8</td>\n            <td>76.9</td>\n            <td>88.4</td>\n            <td>-</td>\n        </tr>\n        <tr>\n            <td><strong>dots.ocr-1.5</strong></td>\n            <td>77.4</td>\n            <td>55.3</td>\n            <td>22.85</td>\n            <td>73.76</td>\n            <td>91.85</td>\n            <td>83.2</td>\n            <td>86.0</td>\n            <td>82.16</td>\n            <td>94.46</td>\n            <td>80.03</td>\n        </tr>\n    </tbody>\n</table>\n\n\n\n# Quick Start\n## 1. Installation\n### Install dots.ocr-1.5\n```shell\nconda create -n dots_ocr python=3.12\nconda activate dots_ocr\n\ngit clone https://github.com/rednote-hilab/dots.ocr.git\ncd dots.ocr\n\n# Install pytorch, see https://pytorch.org/get-started/previous-versions/ for your cuda version\npip install torch==2.7.0 torchvision==0.22.0 torchaudio==2.7.0 --index-url https://download.pytorch.org/whl/cu128\npip install -e .\n```\n\nIf you have trouble with the installation, try our [Docker Image](https://hub.docker.com/r/rednotehilab/dots.ocr) for an easier setup, and follow these steps:\n```shell\ngit clone https://github.com/rednote-hilab/dots.ocr.git\ncd dots.ocr\npip install -e .\n```\n\n\n### Download Model Weights\n> 💡**Note:** Please use a directory name without periods (e.g., `DotsOCR_1_5` instead of `dots.ocr-1.5`) for the model save path. This is a temporary workaround pending our integration with Transformers.\n```shell\npython3 tools/download_model.py\n\n# with modelscope\npython3 tools/download_model.py --type modelscope\n```\n\n\n## 2. Deployment\n### vLLM inference\nWe highly recommend using vLLM for deployment and inference. All of our evaluations results are based on vLLM 0.9.1 via out-of-tree model registration. **Since vLLM version 0.11.0, Dots OCR has been officially integrated into vLLM with verified performance** and you can use vLLM docker image directly (e.g, `vllm/vllm-openai:v0.11.0`) to deploy the model server.\n\n> **Note:**\n> - We found a little bit performance drop when using vLLM 0.11.0. We are working on a fix.\n\n```shell\n# Launch vLLM model server\n## dots.ocr-1.5\nCUDA_VISIBLE_DEVICES=0 vllm serve rednote-hilab/dots.ocr-1.5 --tensor-parallel-size 1 --gpu-memory-utilization 0.9 --chat-template-content-format string --served-model-name model --trust-remote-code\n\n## dots.ocr-1.5-svg\nCUDA_VISIBLE_DEVICES=0 vllm serve rednote-hilab/dots.ocr-1.5-svg --tensor-parallel-size 1 --gpu-memory-utilization 0.9 --chat-template-content-format string --served-model-name model --trust-remote-code\n\n# vLLM API Demo\n# See dots_ocr/model/inference.py and dots_ocr/utils/prompts.py for details on parameter and prompt settings \n# that help achieve the best output quality.\n## document parsing\npython3 ./demo/demo_vllm.py --prompt_mode prompt_layout_all_en \n## web parsing \npython3 ./demo/demo_vllm.py --prompt_mode prompt_web_parsing --image_path ./assets/showcase_dots_ocr_1_5/origin/webpage_1.png\n## scene spoting\npython3 ./demo/demo_vllm.py --prompt_mode prompt_scene_spotting --image_path ./assets/showcase_dots_ocr_1_5/origin/scene_1.jpg\n## image parsing with svg code\npython3 ./demo/demo_vllm_svg.py --prompt_mode prompt_image_to_svg \n## general qa\npython3 ./demo/demo_vllm_general.py\n```\n\n### Hugginface inference\n```shell\npython3 demo/demo_hf.py\n```\n\n<details>\n<summary><b>Hugginface inference details</b></summary>\n\n```python\nimport torch\nfrom transformers import AutoModelForCausalLM, AutoProcessor, AutoTokenizer\nfrom qwen_vl_utils import process_vision_info\nfrom dots_ocr.utils import dict_promptmode_to_prompt\n\nmodel_path = \"./weights/DotsOCR_1_5\"\nmodel = AutoModelForCausalLM.from_pretrained(\n    model_path,\n    attn_implementation=\"flash_attention_2\",\n    torch_dtype=torch.bfloat16,\n    device_map=\"auto\",\n    trust_remote_code=True\n)\nprocessor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)\n\nimage_path = \"demo/demo_image1.jpg\"\nprompt = \"\"\"Please output the layout information from the PDF image, including each layout element's bbox, its category, and the corresponding text content within the bbox.\n\n1. Bbox format: [x1, y1, x2, y2]\n\n2. Layout Categories: The possible categories are ['Caption', 'Footnote', 'Formula', 'List-item', 'Page-footer', 'Page-header', 'Picture', 'Section-header', 'Table', 'Text', 'Title'].\n\n3. Text Extraction & Formatting Rules:\n    - Picture: For the 'Picture' category, the text field should be omitted.\n    - Formula: Format its text as LaTeX.\n    - Table: Format its text as HTML.\n    - All Others (Text, Title, etc.): Format their text as Markdown.\n\n4. Constraints:\n    - The output text must be the original text from the image, with no translation.\n    - All layout elements must be sorted according to human reading order.\n\n5. Final Output: The entire output must be a single JSON object.\n\"\"\"\n\nmessages = [\n        {\n            \"role\": \"user\",\n            \"content\": [\n                {\n                    \"type\": \"image\",\n                    \"image\": image_path\n                },\n                {\"type\": \"text\", \"text\": prompt}\n            ]\n        }\n    ]\n\n# Preparation for inference\ntext = processor.apply_chat_template(\n    messages, \n    tokenize=False, \n    add_generation_prompt=True\n)\nimage_inputs, video_inputs = process_vision_info(messages)\ninputs = processor(\n    text=[text],\n    images=image_inputs,\n    videos=video_inputs,\n    padding=True,\n    return_tensors=\"pt\",\n)\n\ninputs = inputs.to(\"cuda\")\n\n# Inference: Generation of the output\ngenerated_ids = model.generate(**inputs, max_new_tokens=24000)\ngenerated_ids_trimmed = [\n    out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)\n]\noutput_text = processor.batch_decode(\n    generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False\n)\nprint(output_text)\n\n```\n\n</details>\n\n### Hugginface inference with CPU\nPlease refer to [CPU inference](https://github.com/rednote-hilab/dots.ocr/issues/1#issuecomment-3148962536)\n\n\n## 3. Document Parse\n**Based on vLLM server**, you can parse an image or a pdf file using the following commands:\n```bash\n\n# Parse all layout info, both detection and recognition\n# Parse a single image\npython3 dots_ocr/parser.py demo/demo_image1.jpg\n# Parse a single PDF\npython3 dots_ocr/parser.py demo/demo_pdf1.pdf  --num_thread 64  # try bigger num_threads for pdf with a large number of pages\n\n# Layout detection only\npython3 dots_ocr/parser.py demo/demo_image1.jpg --prompt prompt_layout_only_en\n\n# Parse text only, except Page-header and Page-footer\npython3 dots_ocr/parser.py demo/demo_image1.jpg --prompt prompt_ocr\n\n\n```\n**Based on Transformers**, you can parse an image or a pdf file using the same commands above, just add `--use_hf true`. \n\n> Notice: transformers is slower than vllm, if you want to use demo/* with transformers，just add `use_hf=True` in `DotsOCRParser(..,use_hf=True)`\n\n<details>\n<summary><b>Output Results</b></summary>\n\n1.  **Structured Layout Data** (`demo_image1.json`): A JSON file containing the detected layout elements, including their bounding boxes, categories, and extracted text.\n2.  **Processed Markdown File** (`demo_image1.md`): A Markdown file generated from the concatenated text of all detected cells.\n    *   An additional version, `demo_image1_nohf.md`, is also provided, which excludes page headers and footers for compatibility with benchmarks like Omnidocbench and olmOCR-bench.\n3.  **Layout Visualization** (`demo_image1.jpg`): The original image with the detected layout bounding boxes drawn on it.\n\n</details>\n\n\n## 4. Demo\nHave fun with the [live demo](https://dotsocr.xiaohongshu.com/).\n\n\n### Examples for document parsing\n<img src=\"https://raw.githubusercontent.com/rednote-hilab/dots.ocr/master/assets/showcase/formula1.png\" alt=\"formula1.png\" border=\"0\" />\n<img src=\"https://raw.githubusercontent.com/rednote-hilab/dots.ocr/master/assets/showcase/table3.png\" alt=\"table3.png\" border=\"0\" />\n<img src=\"https://raw.githubusercontent.com/rednote-hilab/dots.ocr/master/assets/showcase/Tibetan.png\" alt=\"Tibetan.png\" border=\"0\" />\n<img src=\"https://raw.githubusercontent.com/rednote-hilab/dots.ocr/master/assets/showcase/tradition_zh.png\" alt=\"tradition_zh.png\" border=\"0\" />\n<img src=\"https://raw.githubusercontent.com/rednote-hilab/dots.ocr/master/assets/showcase/nl.png\" alt=\"nl.png\" border=\"0\" />\n<img src=\"https://raw.githubusercontent.com/rednote-hilab/dots.ocr/master/assets/showcase/kannada.png\" alt=\"kannada.png\" border=\"0\" />\n<img src=\"https://raw.githubusercontent.com/rednote-hilab/dots.ocr/master/assets/showcase/russian.png\" alt=\"russian.png\" border=\"0\" />\n\n\n### Examples for image parsing\n<img src=\"https://raw.githubusercontent.com/rednote-hilab/dots.ocr/master/assets/showcase_dots_ocr_1_5/result/svg_1.png\" alt=\"svg_1.png\" border=\"0\" />\n<img src=\"https://raw.githubusercontent.com/rednote-hilab/dots.ocr/master/assets/showcase_dots_ocr_1_5/result/svg_2.png\" alt=\"svg_2.png\" border=\"0\" />\n<img src=\"https://raw.githubusercontent.com/rednote-hilab/dots.ocr/master/assets/showcase_dots_ocr_1_5/result/svg_4.png\" alt=\"svg_4.png\" border=\"0\" />\n<img src=\"https://raw.githubusercontent.com/rednote-hilab/dots.ocr/master/assets/showcase_dots_ocr_1_5/result/svg_5.png\" alt=\"svg_5.png\" border=\"0\" />\n<img src=\"https://raw.githubusercontent.com/rednote-hilab/dots.ocr/master/assets/showcase_dots_ocr_1_5/result/svg_6.png\" alt=\"svg_6.png\" border=\"0\" />\n\n> **Note:**\n> - Inferenced by dots.ocr-1.5-svg\n\n### Example for web parsing\n<img src=\"https://raw.githubusercontent.com/rednote-hilab/dots.ocr/master/assets/showcase_dots_ocr_1_5/result/webpage_1.png\" alt=\"webpage_1.png\" border=\"0\" />\n<img src=\"https://raw.githubusercontent.com/rednote-hilab/dots.ocr/master/assets/showcase_dots_ocr_1_5/result/webpage_2.png\" alt=\"webpage_2.png\" border=\"0\" />\n\n### Examples for scene spotting\n<img src=\"https://raw.githubusercontent.com/rednote-hilab/dots.ocr/master/assets/showcase_dots_ocr_1_5/result/scene_1.png\" alt=\"scene_1.png\" border=\"0\" />\n<img src=\"https://raw.githubusercontent.com/rednote-hilab/dots.ocr/master/assets/showcase_dots_ocr_1_5/result/scene_2.png\" alt=\"scene_2.png\" border=\"0\" />\n\n\n# Limitation & Future Work\n\n- **Complex Document Elements:**\n  - **Table&Formula**: The extraction of complex tables and mathematical formulas persists as a difficult task given the model's compact architecture.\n  - **Picture**: We have adopted an SVG code representation for parsing structured graphics; however, the performance has yet to achieve the desired level of robustness.\n\n- **Parsing Failures:** While we have reduced the rate of parsing failures compared to the previous version, these issues may still occur occasionally. We remain committed to further resolving these edge cases in future updates. \n\n\n# Citation\n\n```BibTeX\n@misc{li2025dotsocrmultilingualdocumentlayout,\n      title={dots.ocr: Multilingual Document Layout Parsing in a Single Vision-Language Model}, \n      author={Yumeng Li and Guang Yang and Hao Liu and Bowen Wang and Colin Zhang},\n      year={2025},\n      eprint={2512.02498},\n      archivePrefix={arXiv},\n      primaryClass={cs.CV},\n      url={https://arxiv.org/abs/2512.02498}, \n}\n```\n"
  },
  {
    "path": "assets/blog.md",
    "content": "<h1 align=\"center\">\ndots.ocr: Multilingual Document Layout Parsing in a Single Vision-Language Model\n</h1>\n\n\n## Introduction\n\n**dots.ocr** is a powerful, multilingual document parser that unifies layout detection and content recognition within a single vision-language model while maintaining good reading order. Despite its compact 1.7B-parameter LLM foundation, it achieves state-of-the-art(SOTA) performance.\n\n1. **Powerful Performance:** **dots.ocr** achieves SOTA performance for text, tables, and reading order on [OmniDocBench](https://github.com/opendatalab/OmniDocBench), while delivering formula recognition results comparable to much larger models like Doubao-1.5 and gemini2.5-pro.\n2. **Multilingual Support:** **dots.ocr** demonstrates robust parsing capabilities for low-resource languages, achieving decisive advantages across both layout detection and content recognition on our in-house multilingual documents benchmark.\n3. **Unified and Simple Architecture:** By leveraging a single vision-language model, **dots.ocr** offers a significantly more streamlined architecture than conventional methods that rely on complex, multi-model pipelines. Switching between tasks is accomplished simply by altering the input prompt, proving that a VLM can achieve competitive detection results compared to traditional detection models like DocLayout-YOLO.\n4.  **Efficient and Fast Performance:** Built upon a compact 1.7B LLM, **dots.ocr** provides faster inference speeds than many other high-performing models based on larger foundations.\n\n\n### Performance Comparison on Document Parsing Benchmarks\n<img src=\"https://raw.githubusercontent.com/rednote-hilab/dots.ocr/master/assets/chart.png\" border=\"0\" />\n\n> **Notes:** \n> - The EN, ZH metrics are the end2end evaluation results of [OmniDocBench](https://github.com/opendatalab/OmniDocBench), and Multilingual metric is the end2end evaluation results of dots.ocr-bench.\n\n\n## Show Case\n### Example for formula document\n<img src=\"https://raw.githubusercontent.com/rednote-hilab/dots.ocr/master/assets/showcase/formula1.png\" alt=\"formula1.png\" border=\"0\" />\n<img src=\"https://raw.githubusercontent.com/rednote-hilab/dots.ocr/master/assets/showcase/formula2.png\" alt=\"formula2.png\" border=\"0\" />\n<img src=\"https://raw.githubusercontent.com/rednote-hilab/dots.ocr/master/assets/showcase/formula3.png\" alt=\"formula3.png\" border=\"0\" />\n\n### Example for table document\n<img src=\"https://raw.githubusercontent.com/rednote-hilab/dots.ocr/master/assets/showcase/table1.png\" alt=\"table1.png\" border=\"0\" />\n<img src=\"https://raw.githubusercontent.com/rednote-hilab/dots.ocr/master/assets/showcase/table2.png\" alt=\"table2.png\" border=\"0\" />\n<img src=\"https://raw.githubusercontent.com/rednote-hilab/dots.ocr/master/assets/showcase/table3.png\" alt=\"table3.png\" border=\"0\" />\n\n### Example for multilingual document\n<img src=\"https://raw.githubusercontent.com/rednote-hilab/dots.ocr/master/assets/showcase/Tibetan.png\" alt=\"Tibetan.png\" border=\"0\" />\n<img src=\"https://raw.githubusercontent.com/rednote-hilab/dots.ocr/master/assets/showcase/tradition_zh.png\" alt=\"tradition_zh.png\" border=\"0\" />\n<img src=\"https://raw.githubusercontent.com/rednote-hilab/dots.ocr/master/assets/showcase/nl.png\" alt=\"nl.png\" border=\"0\" />\n<img src=\"https://raw.githubusercontent.com/rednote-hilab/dots.ocr/master/assets/showcase/kannada.png\" alt=\"kannada.png\" border=\"0\" />\n<img src=\"https://raw.githubusercontent.com/rednote-hilab/dots.ocr/master/assets/showcase/russian.png\" alt=\"russian.png\" border=\"0\" />\n\n### Example for reading order\n<img src=\"https://raw.githubusercontent.com/rednote-hilab/dots.ocr/master/assets/showcase/reading_order.png\" alt=\"reading_order.png\" border=\"0\" />\n\n### Example for grounding ocr\n<img src=\"https://raw.githubusercontent.com/rednote-hilab/dots.ocr/master/assets/showcase/grounding.png\" alt=\"grounding.png\" border=\"0\" />\n\n\n\n## Benchmark Results\n\n### 1. OmniDocBench\n\n#### The end-to-end evaluation results of different tasks.\n\n<table>\n<thead>\n<tr>\n<th rowspan=\"2\"><strong>Model<br>Type</strong></th>\n<th rowspan=\"2\"><strong>Methods</strong></th>\n<th colspan=\"2\"><strong>Overall<sup>Edit</sup>↓</strong></th>\n<th colspan=\"2\"><strong>Text<sup>Edit</sup>↓</strong></th>\n<th colspan=\"2\"><strong>Formula<sup>Edit</sup>↓</strong></th>\n<th colspan=\"2\"><strong>Table<sup>TEDS</sup>↑</strong></th>\n<th colspan=\"2\"><strong>Table<sup>Edit</sup>↓</strong></th>\n<th colspan=\"2\"><strong>Read Order<sup>Edit</sup>↓</strong></th>\n</tr>\n<tr>\n<th><em>EN</em></th>\n<th><em>ZH</em></th>\n<th><em>EN</em></th>\n<th><em>ZH</em></th>\n<th><em>EN</em></th>\n<th><em>ZH</em></th>\n<th><em>EN</em></th>\n<th><em>ZH</em></th>\n<th><em>EN</em></th>\n<th><em>ZH</em></th>\n<th><em>EN</em></th>\n<th><em>ZH</em></th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td rowspan=\"8\"><strong>Pipeline<br>Tools</strong></td>\n<td>MinerU</td>\n<td>0.150</td>\n<td>0.357</td>\n<td>0.061</td>\n<td>0.215</td>\n<td>0.278</td>\n<td>0.577</td>\n<td>78.6</td>\n<td>62.1</td>\n<td>0.180</td>\n<td>0.344</td>\n<td>0.079</td>\n<td>0.292</td>\n</tr>\n<tr>\n<td>Marker</td>\n<td>0.336</td>\n<td>0.556</td>\n<td>0.080</td>\n<td>0.315</td>\n<td>0.530</td>\n<td>0.883</td>\n<td>67.6</td>\n<td>49.2</td>\n<td>0.619</td>\n<td>0.685</td>\n<td>0.114</td>\n<td>0.340</td>\n</tr>\n<tr>\n<td>Mathpix</td>\n<td>0.191</td>\n<td>0.365</td>\n<td>0.105</td>\n<td>0.384</td>\n<td>0.306</td>\n<td>0.454</td>\n<td>77.0</td>\n<td>67.1</td>\n<td>0.243</td>\n<td>0.320</td>\n<td>0.108</td>\n<td>0.304</td>\n</tr>\n<tr>\n<td>Docling</td>\n<td>0.589</td>\n<td>0.909</td>\n<td>0.416</td>\n<td>0.987</td>\n<td>0.999</td>\n<td>1</td>\n<td>61.3</td>\n<td>25.0</td>\n<td>0.627</td>\n<td>0.810</td>\n<td>0.313</td>\n<td>0.837</td>\n</tr>\n<tr>\n<td>Pix2Text</td>\n<td>0.320</td>\n<td>0.528</td>\n<td>0.138</td>\n<td>0.356</td>\n<td>0.276</td>\n<td>0.611</td>\n<td>73.6</td>\n<td>66.2</td>\n<td>0.584</td>\n<td>0.645</td>\n<td>0.281</td>\n<td>0.499</td>\n</tr>\n<tr>\n<td>Unstructured</td>\n<td>0.586</td>\n<td>0.716</td>\n<td>0.198</td>\n<td>0.481</td>\n<td>0.999</td>\n<td>1</td>\n<td>0</td>\n<td>0.06</td>\n<td>1</td>\n<td>0.998</td>\n<td>0.145</td>\n<td>0.387</td>\n</tr>\n<tr>\n<td>OpenParse</td>\n<td>0.646</td>\n<td>0.814</td>\n<td>0.681</td>\n<td>0.974</td>\n<td>0.996</td>\n<td>1</td>\n<td>64.8</td>\n<td>27.5</td>\n<td>0.284</td>\n<td>0.639</td>\n<td>0.595</td>\n<td>0.641</td>\n</tr>\n<tr>\n<td>PPStruct-V3</td>\n<td>0.145</td>\n<td>0.206</td>\n<td>0.058</td>\n<td>0.088</td>\n<td>0.295</td>\n<td>0.535</td>\n<td>-</td>\n<td>-</td>\n<td>0.159</td>\n<td>0.109</td>\n<td>0.069</td>\n<td>0.091</td>\n</tr>\n<tr>\n<td rowspan=\"9\"><strong>Expert<br>VLMs</strong></td>\n<td>GOT-OCR</td>\n<td>0.287</td>\n<td>0.411</td>\n<td>0.189</td>\n<td>0.315</td>\n<td>0.360</td>\n<td>0.528</td>\n<td>53.2</td>\n<td>47.2</td>\n<td>0.459</td>\n<td>0.520</td>\n<td>0.141</td>\n<td>0.280</td>\n</tr>\n<tr>\n<td>Nougat</td>\n<td>0.452</td>\n<td>0.973</td>\n<td>0.365</td>\n<td>0.998</td>\n<td>0.488</td>\n<td>0.941</td>\n<td>39.9</td>\n<td>0</td>\n<td>0.572</td>\n<td>1.000</td>\n<td>0.382</td>\n<td>0.954</td>\n</tr>\n<tr>\n<td>Mistral OCR</td>\n<td>0.268</td>\n<td>0.439</td>\n<td>0.072</td>\n<td>0.325</td>\n<td>0.318</td>\n<td>0.495</td>\n<td>75.8</td>\n<td>63.6</td>\n<td>0.600</td>\n<td>0.650</td>\n<td>0.083</td>\n<td>0.284</td>\n</tr>\n<tr>\n<td>OLMOCR-sglang</td>\n<td>0.326</td>\n<td>0.469</td>\n<td>0.097</td>\n<td>0.293</td>\n<td>0.455</td>\n<td>0.655</td>\n<td>68.1</td>\n<td>61.3</td>\n<td>0.608</td>\n<td>0.652</td>\n<td>0.145</td>\n<td>0.277</td>\n</tr>\n<tr>\n<td>SmolDocling-256M</td>\n<td>0.493</td>\n<td>0.816</td>\n<td>0.262</td>\n<td>0.838</td>\n<td>0.753</td>\n<td>0.997</td>\n<td>44.9</td>\n<td>16.5</td>\n<td>0.729</td>\n<td>0.907</td>\n<td>0.227</td>\n<td>0.522</td>\n</tr>\n<tr>\n<td>Dolphin</td>\n<td>0.206</td>\n<td>0.306</td>\n<td>0.107</td>\n<td>0.197</td>\n<td>0.447</td>\n<td>0.580</td>\n<td>77.3</td>\n<td>67.2</td>\n<td>0.180</td>\n<td>0.285</td>\n<td>0.091</td>\n<td>0.162</td>\n</tr>\n<tr>\n<td>MinerU 2</td>\n<td>0.139</td>\n<td>0.240</td>\n<td>0.047</td>\n<td>0.109</td>\n<td>0.297</td>\n<td>0.536</td>\n<td>82.5</td>\n<td>79.0</td>\n<td>0.141</td>\n<td>0.195</td>\n<td>0.069<</td>\n<td>0.118</td>\n</tr>\n<tr>\n<td>OCRFlux</td>\n<td>0.195</td>\n<td>0.281</td>\n<td>0.064</td>\n<td>0.183</td>\n<td>0.379</td>\n<td>0.613</td>\n<td>71.6</td>\n<td>81.3</td>\n<td>0.253</td>\n<td>0.139</td>\n<td>0.086</td>\n<td>0.187</td>\n</tr>\n<tr>\n<td>MonkeyOCR-pro-3B</td>\n<td>0.138</td>\n<td>0.206</td>\n<td>0.067</td>\n<td>0.107</td>\n<td><strong>0.246</strong></td>\n<td>0.421</td>\n<td>81.5</td>\n<td>87.5</td>\n<td>0.139</td>\n<td>0.111</td>\n<td>0.100</td>\n<td>0.185</td>\n</tr>\n<tr>\n\n<td rowspan=\"5\"><strong>General<br>VLMs</strong></td>\n<td>GPT4o</td>\n<td>0.233</td>\n<td>0.399</td>\n<td>0.144</td>\n<td>0.409</td>\n<td>0.425</td>\n<td>0.606</td>\n<td>72.0</td>\n<td>62.9</td>\n<td>0.234</td>\n<td>0.329</td>\n<td>0.128</td>\n<td>0.251</td>\n</tr>\n    <tr>\n      <td>Qwen2-VL-72B</td>\n      <td>0.252</td>\n      <td>0.327</td>\n      <td>0.096</td>\n      <td>0.218</td>\n      <td>0.404</td>\n      <td>0.487</td>\n      <td>76.8</td>\n      <td>76.4</td>\n      <td>0.387</td>\n      <td>0.408</td>\n      <td>0.119</td>\n      <td>0.193</td>\n    </tr>\n    <tr>\n      <td>Qwen2.5-VL-72B</td>\n      <td>0.214</td>\n      <td>0.261</td>\n      <td>0.092</td>\n      <td>0.18</td>\n      <td>0.315</td>\n      <td>0.434</td>\n      <td>82.9</td>\n      <td>83.9</td>\n      <td>0.341</td>\n      <td>0.262</td>\n      <td>0.106</td>\n      <td>0.168</td>\n    </tr>\n    <tr>\n      <td>Gemini2.5-Pro</td>\n      <td>0.148</td>\n      <td>0.212</td>\n      <td>0.055</td>\n      <td>0.168</td>\n      <td>0.356</td>\n      <td>0.439</td>\n      <td>85.8</td>\n      <td>86.4</td>\n      <td>0.13</td>\n      <td>0.119</td>\n      <td>0.049</td>\n      <td>0.121</td>\n    </tr>\n    <tr>\n      <td>doubao-1-5-thinking-vision-pro-250428</td>\n      <td>0.140</td>\n      <td>0.162</td>\n      <td>0.043</td>\n      <td>0.085</td>\n      <td>0.295</td>\n      <td><strong>0.384</strong></td>\n      <td>83.3</td>\n      <td><strong>89.3</strong></td>\n      <td>0.165</td>\n      <td><strong>0.085</strong></td>\n      <td>0.058</td>\n      <td>0.094</td>\n    </tr>\n<tr>\n<td rowspan=\"1\"><strong>Expert VLMs</strong></td>\n<td><strong>dots.ocr</strong></td>\n<td><strong>0.125</strong></td>\n<td><strong>0.160</strong></td>\n<td><strong>0.032</strong></td>\n<td><strong>0.066</strong></td>\n<td>0.329</td>\n<td>0.416</td>\n<td><strong>88.6</strong></td>\n<td>89.0</td>\n<td><strong>0.099</strong></td>\n<td>0.092</td>\n<td><strong>0.040</strong></td>\n<td><strong>0.067</strong></td>\n</tr>\n<tr>\n</tbody>\n</table>\n\n\n#### The end-to-end text recognition performance across 9 PDF page types.\n\n<table>\n<thead>\n<tr>\n<th><strong>Model<br>Type</strong></th>\n<th><strong>Models</strong></th>\n<th><strong>Book</strong></th>\n<th><strong>Slides</strong></th>\n<th><strong>Financial<br>Report</strong></th>\n<th><strong>Textbook</strong></th>\n<th><strong>Exam<br>Paper</strong></th>\n<th><strong>Magazine</strong></th>\n<th><strong>Academic<br>Papers</strong></th>\n<th><strong>Notes</strong></th>\n<th><strong>Newspaper</strong></th>\n<th><strong>Overall</strong></th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td rowspan=\"3\"><strong>Pipeline<br>Tools</strong></td>\n<td>MinerU</td>\n<td>0.055</td>\n<td>0.124</td>\n<td><u>0.033</u></td>\n<td>0.102</td>\n<td>0.159</td>\n<td><strong>0.072</strong></td>\n<td><u>0.025</u></td>\n<td>0.984</td>\n<td>0.171</td>\n<td>0.206</td>\n</tr>\n<tr>\n<td>Marker</td>\n<td>0.074</td>\n<td>0.340</td>\n<td>0.089</td>\n<td>0.319</td>\n<td>0.452</td>\n<td>0.153</td>\n<td>0.059</td>\n<td>0.651</td>\n<td>0.192</td>\n<td>0.274</td>\n</tr>\n<tr>\n<td>Mathpix</td>\n<td>0.131</td>\n<td>0.220</td>\n<td>0.202</td>\n<td>0.216</td>\n<td>0.278</td>\n<td>0.147</td>\n<td>0.091</td>\n<td>0.634</td>\n<td>0.690</td>\n<td>0.300</td>\n</tr>\n<tr>\n<td rowspan=\"5\"><strong>Expert<br>VLMs</strong></td>\n<td>GOT-OCR</td>\n<td>0.111</td>\n<td>0.222</td>\n<td>0.067</td>\n<td>0.132</td>\n<td>0.204</td>\n<td>0.198</td>\n<td>0.179</td>\n<td>0.388</td>\n<td>0.771</td>\n<td>0.267</td>\n</tr>\n<tr>\n<td>Nougat</td>\n<td>0.734</td>\n<td>0.958</td>\n<td>1.000</td>\n<td>0.820</td>\n<td>0.930</td>\n<td>0.830</td>\n<td>0.214</td>\n<td>0.991</td>\n<td>0.871</td>\n<td>0.806</td>\n</tr>\n<tr>\n<td>Dolphin</td>\n<td>0.091</td>\n<td>0.131</td>\n<td>0.057</td>\n<td>0.146</td>\n<td>0.231</td>\n<td>0.121</td>\n<td>0.074</td>\n<td>0.363</td>\n<td>0.307</td>\n<td>0.177</td>\n</tr>\n<tr>\n<td>OCRFlux</td>\n<td>0.068</td>\n<td>0.125</td>\n<td>0.092</td>\n<td>0.102</td>\n<td>0.119</td>\n<td>0.083</td>\n<td>0.047</td>\n<td>0.223</td>\n<td>0.536</td>\n<td>0.149</td>\n</tr>\n<tr>\n<td>MonkeyOCR-pro-3B</td>\n<td>0.084</td>\n<td>0.129</td>\n<td>0.060</td>\n<td>0.090</td>\n<td>0.107</td>\n<td>0.073</td>\n<td>0.050</td>\n<td>0.171</td>\n<td>0.107</td>\n<td>0.100</td>\n</tr>\n<tr>\n<td rowspan=\"4\"><strong>General<br>VLMs</strong></td>\n<td>GPT4o</td>\n<td>0.157</td>\n<td>0.163</td>\n<td>0.348</td>\n<td>0.187</td>\n<td>0.281</td>\n<td>0.173</td>\n<td>0.146</td>\n<td>0.607</td>\n<td>0.751</td>\n<td>0.316</td>\n</tr>\n<tr>\n<td>Qwen2.5-VL-7B</td>\n<td>0.148</td>\n<td>0.053</td>\n<td>0.111</td>\n<td>0.137</td>\n<td>0.189</td>\n<td>0.117</td>\n<td>0.134</td>\n<td>0.204</td>\n<td>0.706</td>\n<td>0.205</td>\n</tr>\n<tr>\n<td>InternVL3-8B</td>\n<td>0.163</td>\n<td>0.056</td>\n<td>0.107</td>\n<td>0.109</td>\n<td>0.129</td>\n<td>0.100</td>\n<td>0.159</td>\n<td>0.150</td>\n<td>0.681</td>\n<td>0.188</td>\n</tr>\n<tr>\n<td>doubao-1-5-thinking-vision-pro-250428</td>\n<td>0.048</td>\n<td>0.048</td>\n<td>0.024</td>\n<td><strong>0.062</strong></td>\n<td>0.085</td>\n<td>0.051</td>\n<td>0.039</td>\n<td><strong>0.096</strong></td>\n<td>0.181</td>\n<td>0.073</td>\n</tr>\n<tr>\n<td rowspan=\"1\"><strong>Expert VLMs</strong></td>\n<td><strong>dots.ocr</strong></td>\n<td><strong>0.031</strong></td>\n<td><strong>0.047</strong></td>\n<td><strong>0.011</strong></td>\n<td>0.082</td>\n<td><strong>0.079</strong></td>\n<td><strong>0.028</strong></td>\n<td><strong>0.029</strong></td>\n<td>0.109</td>\n<td><strong>0.056</strong></td>\n<td><strong>0.055</strong></td>\n</tr>\n\n</tbody>\n</table>\n\n> **Notes:** \n> - The metrics are from [MonkeyOCR](https://github.com/Yuliang-Liu/MonkeyOCR), [OmniDocBench](https://github.com/opendatalab/OmniDocBench), and our own internal evaluations.\n> - We delete the Page-header and Page-footer cells in the result markdown.\n> - We use tikz_preprocess pipeline to upsample the images to dpi 200.\n\n\n### 2. **dots.ocr-bench**\n\nThis is an inhouse benchmark which contain 1493 pdf images with 100 languages.\n\n#### The end-to-end evaluation results of different tasks.\n\n<table>\n<thead>\n<tr>\n<th rowspan=\"1\"><strong>Methods</strong></th>\n<th colspan=\"1\"><strong>Overall<sup>Edit</sup>↓</strong></th>\n<th colspan=\"1\"><strong>Text<sup>Edit</sup>↓</strong></th>\n<th colspan=\"1\"><strong>Formula<sup>Edit</sup>↓</strong></th>\n<th colspan=\"1\"><strong>Table<sup>TEDS</sup>↑</strong></th>\n<th colspan=\"1\"><strong>Table<sup>Edit</sup>↓</strong></th>\n<th colspan=\"1\"><strong>Read Order<sup>Edit</sup>↓</strong></th>\n</tr>\n</thead>\n<tbody>\n<td>MonkeyOCR-3B</td>\n<td>0.483</td>\n<td>0.445</td>\n<td>0.627</td>\n<td>50.93</td>\n<td>0.452</td>\n<td>0.409</td>\n</tr>\n<tr>\n<td>doubao-1-5-thinking-vision-pro-250428</td>\n<td>0.291</td>\n<td>0.226</td>\n<td>0.440</td>\n<td>71.2</td>\n<td>0.260</td>\n<td>0.238</td>\n</tr>\n<tr>\n<td>doubao-1-6</td>\n<td>0.299</td>\n<td>0.270</td>\n<td>0.417</td>\n<td>71.0</td>\n<td>0.258</td>\n<td>0.253</td>\n</tr>\n<tr>\n<td>Gemini2.5-Pro</td>\n<td>0.251</td>\n<td>0.163</td>\n<td>0.402</td>\n<td>77.1</td>\n<td>0.236</td>\n<td>0.202</td>\n</tr>\n<tr>\n<td><strong>dots.ocr</strong> </td>\n<td><strong>0.177</strong></td>\n<td><strong>0.075</strong></td>\n<td><strong>0.297</strong></td>\n<td><strong>79.2</strong></td>\n<td><strong>0.186</strong></td>\n<td><strong>0.152</strong></td>\n</tr>\n\n</tbody>\n</table>\n\n> **Notes:** \n> - We use the same metric calculation pipeline of [OmniDocBench](https://github.com/opendatalab/OmniDocBench).\n> - We delete the Page-header and Page-footer cells in the result markdown.\n\n#### Layout Detection\n\n<table>\n<thead>\n<tr>\n<th rowspan=\"2\"><strong>Method</strong></th>\n<th colspan=\"5\" style=\"text-align: center;\"><strong>F1@IoU=.50:.05:.95↑</strong></th>\n<th colspan=\"5\" style=\"text-align: center;\"><strong>F1@IoU=.50↑</strong></th>\n</tr>\n<tr>\n<th>Overall</th>\n<th>Text</th>\n<th>Formula</th>\n<th>Table</th>\n<th>Picture</th>\n<th>Overall</th>\n<th>Text</th>\n<th>Formula</th>\n<th>Table</th>\n<th>Picture</th>\n</tr>\n</thead>\n\n<tbody>\n<td>DocLayout-YOLO-DocStructBench</td>\n<td>0.733</td>\n<td>0.694</td>\n<td>0.480</td>\n<td>0.803</td>\n<td>0.619</td>\n<td>0.806</td>\n<td>0.779</td>\n<td>0.620</td>\n<td>0.858</td>\n<td>0.678</td>\n</tr>\n\n<tr>\n<td>dots.ocr-parse all</td>\n<td>0.831</td>\n<td>0.801</td>\n<td>0.654</td>\n<td>0.838</td>\n<td>0.748</td>\n<td>0.922</td>\n<td>0.909</td>\n<td>0.770</td>\n<td>0.888</td>\n<td>0.831</td>\n</tr>\n\n<tr>\n<td> <strong>dots.ocr-detection only</strong> </td>\n<td><strong>0.845</strong></td>\n<td><strong>0.816</strong></td>\n<td><strong>0.716</strong></td>\n<td><strong>0.875</strong></td>\n<td><strong>0.765</strong></td>\n<td><strong>0.930</strong></td>\n<td><strong>0.917</strong></td>\n<td><strong>0.832</strong></td>\n<td><strong>0.918</strong></td>\n<td><strong>0.843</strong></td>\n</tr>\n\n</tbody>\n</table>\n\n> **Notes:**  \n> - prompt_layout_all_en for **parse all**, prompt_layout_only_en for **detection only**, please refer to [prompts](https://github.com/rednote-hilab/dots.ocr/blob/master/dots_ocr/utils/prompts.py)\n\n\n### 3. olmOCR-bench.\n\n<table>\n<thead>\n<tr>\n<th>Model</th>\n<th>ArXiv</th>\n<th>Old Scans<br>Math</th>\n<th>Tables</th>\n<th>Old Scans</th>\n<th>Headers and<br>Footers</th>\n<th>Multi<br>column</th>\n<th>Long Tiny<br>Text</th>\n<th>Base</th>\n<th>Overall</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>GOT OCR</td>\n<td>52.7</td>\n<td>52.0</td>\n<td>0.2</td>\n<td>22.1</td>\n<td>93.6</td>\n<td>42.0</td>\n<td>29.9</td>\n<td>94.0</td>\n<td>48.3 ± 1.1</td>\n</tr>\n<tr>\n<td>Marker</td>\n<td>76.0</td>\n<td>57.9</td>\n<td>57.6</td>\n<td>27.8</td>\n<td>84.9</td>\n<td>72.9</td>\n<td>84.6</td>\n<td>99.1</td>\n<td>70.1 ± 1.1</td>\n</tr>\n<tr>\n<td>MinerU</td>\n<td>75.4</td>\n<td>47.4</td>\n<td>60.9</td>\n<td>17.3</td>\n<td><strong>96.6</strong></td>\n<td>59.0</td>\n<td>39.1</td>\n<td>96.6</td>\n<td>61.5 ± 1.1</td>\n</tr>\n<tr>\n<td>Mistral OCR</td>\n<td>77.2</td>\n<td>67.5</td>\n<td>60.6</td>\n<td>29.3</td>\n<td>93.6</td>\n<td>71.3</td>\n<td>77.1</td>\n<td>99.4</td>\n<td>72.0 ± 1.1</td>\n</tr>\n<tr>\n<td>Nanonets OCR</td>\n<td>67.0</td>\n<td>68.6</td>\n<td><strong>77.7</strong></td>\n<td>39.5</td>\n<td>40.7</td>\n<td>69.9</td>\n<td>53.4</td>\n<td>99.3</td>\n<td>64.5 ± 1.1</td>\n</tr>\n<tr>\n<td>GPT-4o<br>(No Anchor)</td>\n<td>51.5</td>\n<td><strong>75.5</strong></td>\n<td>69.1</td>\n<td>40.9</td>\n<td>94.2</td>\n<td>68.9</td>\n<td>54.1</td>\n<td>96.7</td>\n<td>68.9 ± 1.1</td>\n</tr>\n<tr>\n<td>GPT-4o<br>(Anchored)</td>\n<td>53.5</td>\n<td>74.5</td>\n<td>70.0</td>\n<td>40.7</td>\n<td>93.8</td>\n<td>69.3</td>\n<td>60.6</td>\n<td>96.8</td>\n<td>69.9 ± 1.1</td>\n</tr>\n<tr>\n<td>Gemini Flash 2<br>(No Anchor)</td>\n<td>32.1</td>\n<td>56.3</td>\n<td>61.4</td>\n<td>27.8</td>\n<td>48.0</td>\n<td>58.7</td>\n<td><strong>84.4</strong></td>\n<td>94.0</td>\n<td>57.8 ± 1.1</td>\n</tr>\n<tr>\n<td>Gemini Flash 2<br>(Anchored)</td>\n<td>54.5</td>\n<td>56.1</td>\n<td>72.1</td>\n<td>34.2</td>\n<td>64.7</td>\n<td>61.5</td>\n<td>71.5</td>\n<td>95.6</td>\n<td>63.8 ± 1.2</td>\n</tr>\n<tr>\n<td>Qwen 2 VL<br>(No Anchor)</td>\n<td>19.7</td>\n<td>31.7</td>\n<td>24.2</td>\n<td>17.1</td>\n<td>88.9</td>\n<td>8.3</td>\n<td>6.8</td>\n<td>55.5</td>\n<td>31.5 ± 0.9</td>\n</tr>\n<tr>\n<td>Qwen 2.5 VL<br>(No Anchor)</td>\n<td>63.1</td>\n<td>65.7</td>\n<td>67.3</td>\n<td>38.6</td>\n<td>73.6</td>\n<td>68.3</td>\n<td>49.1</td>\n<td>98.3</td>\n<td>65.5 ± 1.2</td>\n</tr>\n<tr>\n<td>olmOCR v0.1.75<br>(No Anchor)</td>\n<td>71.5</td>\n<td>71.4</td>\n<td>71.4</td>\n<td><strong>42.8</strong></td>\n<td>94.1</td>\n<td>77.7</td>\n<td>71.0</td>\n<td>97.8</td>\n<td>74.7 ± 1.1</td>\n</tr>\n<tr>\n<td>olmOCR v0.1.75<br>(Anchored)</td>\n<td>74.9</td>\n<td>71.2</td>\n<td>71.0</td>\n<td>42.2</td>\n<td>94.5</td>\n<td>78.3</td>\n<td>73.3</td>\n<td>98.3</td>\n<td>75.5 ± 1.0</td>\n</tr>\n<tr>\n<td>MonkeyOCR-pro-3B</td>\n<td><strong>83.8</strong></td>\n<td>68.8</td>\n<td>74.6</td>\n<td>36.1</td>\n<td>91.2</td>\n<td>76.6</td>\n<td>80.1</td>\n<td>95.3</td>\n<td>75.8 ± 1.0</td>\n</tr>\n<tr>\n<td><strong>dots.ocr</strong></td>\n<td>82.1</td>\n<td>64.2</td>\n<td><strong>88.3</strong></td>\n<td>40.9</td>\n<td>94.1</td>\n<td><strong>82.4</strong></td>\n<td>81.2</td>\n<td><strong>99.5</strong></td>\n<td><strong>79.1 ± 1.0</strong></td>\n</tr>\n</tbody>\n</table>\n\n\n> **Note:**\n> - The metrics are from [MonkeyOCR](https://github.com/Yuliang-Liu/MonkeyOCR), \n[olmocr](https://github.com/allenai/olmocr), and our own internal evaluations.\n> - We delete the Page-header and Page-footer cells in the result markdown.\n\n## Methods\n\n### Pretrain\n\nWe developed a foundational Vision-Language Model (VLM) through a three-stage training process:\n\n*   **Stage1: Vision Encoder Pre-training**\n    We trained a 1.2-billion-parameter Vision Encoder (VE) from scratch on a vast and comprehensive dataset of image-text pairs.\n*   **Stage2: VE Continued Pre-training**\n    We incorporated additional visual data, including OCR, video, grounding data, etc. Leveraging the `NaViT` architecture, our model supports high-resolution inputs of up to 11 million pixels. The VE was then aligned with the `Qwen2.5-1.5B` language model and trained on this diverse visual data with LLM frozen, which resulted in our general vision encoder `dots.vit`.\n*   **Stage3: VLM Specialization for OCR**\n    We then used a pure OCR dataset for training. To improve training efficiency, we first trained on a certain volume of tokens with the VE parameters frozen. Subsequently, we unfroze all parameters and continued training on an additional one-fifth of that token volume, which produced our foundational OCR model, `dots.ocr.base`.\n\n### SFT\n\nThe SFT stage was implemented on the following key strategies:\n\n*   **Diverse SFT Dataset:** We constructed a dataset of nearly 300,000 samples, integrating our in-house manual annotations, synthetic data (tables, formulas, multilingual OCR), as well as open-source datasets.\n*   **Iterative Data Flywheel:** We employed a feedback loop to build an inhouse multilingual structured layout data with 15k samples. This process, repeated over three iterations, involved:\n    *   Sampling \"bad cases\" based on model performance.\n    *   Manually annotating these cases.\n    *   Adding them back into the training set.\n*   **Reading Order:** We corrected the sequence of all layout element boxes to establish the correct reading order. This was primarily done using larger models for sorting, supplemented by rule-based post-processing methods. We found that with sufficient data diversity and quality, training the model on a list of elements sorted in their natural reading order yields excellent results.\n*   **Quality and Robustness:** We build a multi-expert system for data cleaning and distillation, and applied data augmentation (resizing, rotation, noise) to improve model robustness.\n*   **Multitask training:** We leveraged a single source of structured layout data to generate the SFT data with a variety of prompts. This approach enables the model to perform different tasks, such as detection and recognition, based on the specific prompt provided.\n\nThe resulting `dots.ocr` model demonstrates performance on par with models possessing significantly more parameters.\n\n\n## Limitation & Future Work\n\n- **Complex Document Elements:**\n  - **Table&Formula**: dots.ocr is not yet perfect for high-complexity tables and formula extraction.\n  - **Picture**: Pictures in documents are currently not parsed.\n\n- **Parsing Failures:** The model may fail to parse under certain conditions:\n  - When the character-to-pixel ratio is excessively high. Try enlarging the image or increasing the PDF parsing DPI (a setting of 200 is recommended). However, please note that the model performs optimally on images with a resolution under 11289600 pixels.\n  - Continuous special characters, such as ellipses (`...`) and underscores (`_`), may cause the prediction output to repeat endlessly. In such scenarios, consider using alternative prompts like `prompt_layout_only_en`, `prompt_ocr`, or `prompt_grounding_ocr` ([details here](https://github.com/rednote-hilab/dots.ocr/blob/master/dots_ocr/utils/prompts.py)).\n    \n- **Performance Bottleneck:** Despite its 1.7B parameter LLM foundation, **dots.ocr** is not yet optimized for high-throughput processing of large PDF volumes. \n\nWe are committed to achieving more accurate table and formula parsing, as well as enhancing the model's OCR capabilities for broader generalization, all while aiming for **a more powerful, more efficient model**. Furthermore, we are actively considering the development of **a more general-purpose perception model** based on Vision-Language Models (VLMs), which would integrate general detection, image captioning, and OCR tasks into a unified framework. **Parsing the content of the pictures in the documents** is also a key priority for our future work.\nWe believe that collaboration is the key to tackling these exciting challenges. If you are passionate about advancing the frontiers of document intelligence and are interested in contributing to these future endeavors, we would love to hear from you. Please reach out to us via email at: [yanqing4@xiaohongshu.com].\n\n## Author List\n\n### Contributors\nMi Jian, Yumeng Li, Bowen Wang, Xiaomin He, Zheyuan Gu\n\n### Project Leader\nQing Yan\n\n### Advisor\nColin Zhang, Lei Zhang\n"
  },
  {
    "path": "demo/demo_colab_remote_server.ipynb",
    "content": "{\n  \"nbformat\": 4,\n  \"nbformat_minor\": 0,\n  \"metadata\": {\n    \"colab\": {\n      \"provenance\": [],\n      \"machine_shape\": \"hm\",\n      \"gpuType\": \"L4\",\n      \"authorship_tag\": \"ABX9TyOkGQh7maXiQhQ6pYoY2NaU\",\n      \"include_colab_link\": true\n    },\n    \"kernelspec\": {\n      \"name\": \"python3\",\n      \"display_name\": \"Python 3\"\n    },\n    \"language_info\": {\n      \"name\": \"python\"\n    },\n    \"accelerator\": \"GPU\"\n  },\n  \"cells\": [\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"view-in-github\",\n        \"colab_type\": \"text\"\n      },\n      \"source\": [\n        \"<a href=\\\"https://colab.research.google.com/github/louisoutin/dots.ocr/blob/master/dots_ocr.ipynb\\\" target=\\\"_parent\\\"><img src=\\\"https://colab.research.google.com/assets/colab-badge.svg\\\" alt=\\\"Open In Colab\\\"/></a>\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"source\": [\n        \"# DotsOCR vLLM Openai API Compatible server\"\n      ],\n      \"metadata\": {\n        \"id\": \"PshK9ZarVTfM\"\n      }\n    },\n    {\n      \"cell_type\": \"code\",\n      \"source\": [\n        \"!pip install pyngrok\\n\",\n        \"!ngrok authtoken  # Get this from https://dashboard.ngrok.com/\"\n      ],\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"oyY3E3mlOXNX\",\n        \"outputId\": \"8d7ba92f-7170-4b2e-e8a0-c7f94096f7e0\"\n      },\n      \"execution_count\": null,\n      \"outputs\": [\n        {\n          \"output_type\": \"stream\",\n          \"name\": \"stdout\",\n          \"text\": [\n            \"Requirement already satisfied: pyngrok in /usr/local/lib/python3.11/dist-packages (7.3.0)\\n\",\n            \"Requirement already satisfied: PyYAML>=5.1 in /usr/local/lib/python3.11/dist-packages (from pyngrok) (6.0.2)\\n\",\n            \"Authtoken saved to configuration file: /root/.config/ngrok/ngrok.yml\\n\"\n          ]\n        }\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"source\": [\n        \"!conda create -n dots_ocr python=3.12\\n\",\n        \"!conda activate dots_ocr\\n\",\n        \"\\n\",\n        \"!git clone https://github.com/rednote-hilab/dots.ocr.git\"\n      ],\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"BcV7hkvuRnwS\",\n        \"outputId\": \"7cb9c743-6f41-4c90-a05b-90bce2c29ced\"\n      },\n      \"execution_count\": null,\n      \"outputs\": [\n        {\n          \"output_type\": \"stream\",\n          \"name\": \"stdout\",\n          \"text\": [\n            \"/bin/bash: line 1: conda: command not found\\n\",\n            \"/bin/bash: line 1: conda: command not found\\n\",\n            \"Cloning into 'dots.ocr'...\\n\",\n            \"remote: Enumerating objects: 163, done.\\u001b[K\\n\",\n            \"remote: Counting objects: 100% (51/51), done.\\u001b[K\\n\",\n            \"remote: Compressing objects: 100% (31/31), done.\\u001b[K\\n\",\n            \"remote: Total 163 (delta 30), reused 30 (delta 20), pack-reused 112 (from 1)\\u001b[K\\n\",\n            \"Receiving objects: 100% (163/163), 35.82 MiB | 13.64 MiB/s, done.\\n\",\n            \"Resolving deltas: 100% (56/56), done.\\n\"\n          ]\n        }\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"source\": [\n        \"cd /content/dots.ocr\"\n      ],\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"Rsc_MkGfRpit\",\n        \"outputId\": \"5265315f-c27c-4346-cda7-aba7d4c226d6\"\n      },\n      \"execution_count\": null,\n      \"outputs\": [\n        {\n          \"output_type\": \"stream\",\n          \"name\": \"stdout\",\n          \"text\": [\n            \"/content/dots.ocr\\n\"\n          ]\n        }\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"source\": [\n        \"# Install pytorch, see https://pytorch.org/get-started/previous-versions/ for your cuda version\\n\",\n        \"!pip install torch==2.7.0 torchvision==0.22.0 torchaudio==2.7.0 --index-url https://download.pytorch.org/whl/cu128\\n\",\n        \"!pip install -e .\"\n      ],\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"OxLaSyTJPFwk\",\n        \"outputId\": \"a073dcdd-5e5d-4f62-d3b9-be9e9cf98d2f\"\n      },\n      \"execution_count\": null,\n      \"outputs\": [\n        {\n          \"output_type\": \"stream\",\n          \"name\": \"stdout\",\n          \"text\": [\n            \"Looking in indexes: https://download.pytorch.org/whl/cu128\\n\",\n            \"Requirement already satisfied: torch==2.7.0 in /usr/local/lib/python3.11/dist-packages (2.7.0+cu128)\\n\",\n            \"Requirement already satisfied: torchvision==0.22.0 in /usr/local/lib/python3.11/dist-packages (0.22.0+cu128)\\n\",\n            \"Requirement already satisfied: torchaudio==2.7.0 in /usr/local/lib/python3.11/dist-packages (2.7.0+cu128)\\n\",\n            \"Requirement already satisfied: filelock in /usr/local/lib/python3.11/dist-packages (from torch==2.7.0) (3.18.0)\\n\",\n            \"Requirement already satisfied: typing-extensions>=4.10.0 in /usr/local/lib/python3.11/dist-packages (from torch==2.7.0) (4.14.1)\\n\",\n            \"Requirement already satisfied: sympy>=1.13.3 in /usr/local/lib/python3.11/dist-packages (from torch==2.7.0) (1.13.3)\\n\",\n            \"Requirement already satisfied: networkx in /usr/local/lib/python3.11/dist-packages (from torch==2.7.0) (3.5)\\n\",\n            \"Requirement already satisfied: jinja2 in /usr/local/lib/python3.11/dist-packages (from torch==2.7.0) (3.1.6)\\n\",\n            \"Requirement already satisfied: fsspec in /usr/local/lib/python3.11/dist-packages (from torch==2.7.0) (2025.3.0)\\n\",\n            \"Requirement already satisfied: nvidia-cuda-nvrtc-cu12==12.8.61 in /usr/local/lib/python3.11/dist-packages (from torch==2.7.0) (12.8.61)\\n\",\n            \"Requirement already satisfied: nvidia-cuda-runtime-cu12==12.8.57 in /usr/local/lib/python3.11/dist-packages (from torch==2.7.0) (12.8.57)\\n\",\n            \"Requirement already satisfied: nvidia-cuda-cupti-cu12==12.8.57 in /usr/local/lib/python3.11/dist-packages (from torch==2.7.0) (12.8.57)\\n\",\n            \"Requirement already satisfied: nvidia-cudnn-cu12==9.7.1.26 in /usr/local/lib/python3.11/dist-packages (from torch==2.7.0) (9.7.1.26)\\n\",\n            \"Requirement already satisfied: nvidia-cublas-cu12==12.8.3.14 in /usr/local/lib/python3.11/dist-packages (from torch==2.7.0) (12.8.3.14)\\n\",\n            \"Requirement already satisfied: nvidia-cufft-cu12==11.3.3.41 in /usr/local/lib/python3.11/dist-packages (from torch==2.7.0) (11.3.3.41)\\n\",\n            \"Requirement already satisfied: nvidia-curand-cu12==10.3.9.55 in /usr/local/lib/python3.11/dist-packages (from torch==2.7.0) (10.3.9.55)\\n\",\n            \"Requirement already satisfied: nvidia-cusolver-cu12==11.7.2.55 in /usr/local/lib/python3.11/dist-packages (from torch==2.7.0) (11.7.2.55)\\n\",\n            \"Requirement already satisfied: nvidia-cusparse-cu12==12.5.7.53 in /usr/local/lib/python3.11/dist-packages (from torch==2.7.0) (12.5.7.53)\\n\",\n            \"Requirement already satisfied: nvidia-cusparselt-cu12==0.6.3 in /usr/local/lib/python3.11/dist-packages (from torch==2.7.0) (0.6.3)\\n\",\n            \"Requirement already satisfied: nvidia-nccl-cu12==2.26.2 in /usr/local/lib/python3.11/dist-packages (from torch==2.7.0) (2.26.2)\\n\",\n            \"Requirement already satisfied: nvidia-nvtx-cu12==12.8.55 in /usr/local/lib/python3.11/dist-packages (from torch==2.7.0) (12.8.55)\\n\",\n            \"Requirement already satisfied: nvidia-nvjitlink-cu12==12.8.61 in /usr/local/lib/python3.11/dist-packages (from torch==2.7.0) (12.8.61)\\n\",\n            \"Requirement already satisfied: nvidia-cufile-cu12==1.13.0.11 in /usr/local/lib/python3.11/dist-packages (from torch==2.7.0) (1.13.0.11)\\n\",\n            \"Requirement already satisfied: triton==3.3.0 in /usr/local/lib/python3.11/dist-packages (from torch==2.7.0) (3.3.0)\\n\",\n            \"Requirement already satisfied: numpy in /usr/local/lib/python3.11/dist-packages (from torchvision==0.22.0) (2.0.2)\\n\",\n            \"Requirement already satisfied: pillow!=8.3.*,>=5.3.0 in /usr/local/lib/python3.11/dist-packages (from torchvision==0.22.0) (11.3.0)\\n\",\n            \"Requirement already satisfied: setuptools>=40.8.0 in /usr/local/lib/python3.11/dist-packages (from triton==3.3.0->torch==2.7.0) (75.2.0)\\n\",\n            \"Requirement already satisfied: mpmath<1.4,>=1.1.0 in /usr/local/lib/python3.11/dist-packages (from sympy>=1.13.3->torch==2.7.0) (1.3.0)\\n\",\n            \"Requirement already satisfied: MarkupSafe>=2.0 in /usr/local/lib/python3.11/dist-packages (from jinja2->torch==2.7.0) (3.0.2)\\n\",\n            \"Obtaining file:///content/dots.ocr\\n\",\n            \"  Preparing metadata (setup.py) ... \\u001b[?25l\\u001b[?25hdone\\n\",\n            \"Requirement already satisfied: gradio in /usr/local/lib/python3.11/dist-packages (from dots_ocr==1.0) (5.39.0)\\n\",\n            \"Collecting gradio_image_annotation (from dots_ocr==1.0)\\n\",\n            \"  Downloading gradio_image_annotation-0.4.0-py3-none-any.whl.metadata (17 kB)\\n\",\n            \"Collecting PyMuPDF (from dots_ocr==1.0)\\n\",\n            \"  Downloading pymupdf-1.26.3-cp39-abi3-manylinux_2_28_x86_64.whl.metadata (3.4 kB)\\n\",\n            \"Requirement already satisfied: openai in /usr/local/lib/python3.11/dist-packages (from dots_ocr==1.0) (1.98.0)\\n\",\n            \"Collecting qwen_vl_utils (from dots_ocr==1.0)\\n\",\n            \"  Downloading qwen_vl_utils-0.0.11-py3-none-any.whl.metadata (6.3 kB)\\n\",\n            \"Collecting transformers==4.51.3 (from dots_ocr==1.0)\\n\",\n            \"  Downloading transformers-4.51.3-py3-none-any.whl.metadata (38 kB)\\n\",\n            \"Requirement already satisfied: huggingface_hub in /usr/local/lib/python3.11/dist-packages (from dots_ocr==1.0) (0.34.3)\\n\",\n            \"Collecting modelscope (from dots_ocr==1.0)\\n\",\n            \"  Downloading modelscope-1.28.2-py3-none-any.whl.metadata (39 kB)\\n\",\n            \"Collecting flash-attn==2.8.0.post2 (from dots_ocr==1.0)\\n\",\n            \"  Downloading flash_attn-2.8.0.post2.tar.gz (7.9 MB)\\n\",\n            \"\\u001b[2K     \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m7.9/7.9 MB\\u001b[0m \\u001b[31m124.7 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25h  Preparing metadata (setup.py) ... \\u001b[?25l\\u001b[?25hdone\\n\",\n            \"Requirement already satisfied: accelerate in /usr/local/lib/python3.11/dist-packages (from dots_ocr==1.0) (1.9.0)\\n\",\n            \"Requirement already satisfied: torch in /usr/local/lib/python3.11/dist-packages (from flash-attn==2.8.0.post2->dots_ocr==1.0) (2.7.0+cu128)\\n\",\n            \"Requirement already satisfied: einops in /usr/local/lib/python3.11/dist-packages (from flash-attn==2.8.0.post2->dots_ocr==1.0) (0.8.1)\\n\",\n            \"Requirement already satisfied: filelock in /usr/local/lib/python3.11/dist-packages (from transformers==4.51.3->dots_ocr==1.0) (3.18.0)\\n\",\n            \"Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.11/dist-packages (from transformers==4.51.3->dots_ocr==1.0) (2.0.2)\\n\",\n            \"Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.11/dist-packages (from transformers==4.51.3->dots_ocr==1.0) (25.0)\\n\",\n            \"Requirement already satisfied: pyyaml>=5.1 in /usr/local/lib/python3.11/dist-packages (from transformers==4.51.3->dots_ocr==1.0) (6.0.2)\\n\",\n            \"Requirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.11/dist-packages (from transformers==4.51.3->dots_ocr==1.0) (2024.11.6)\\n\",\n            \"Requirement already satisfied: requests in /usr/local/lib/python3.11/dist-packages (from transformers==4.51.3->dots_ocr==1.0) (2.32.3)\\n\",\n            \"Requirement already satisfied: tokenizers<0.22,>=0.21 in /usr/local/lib/python3.11/dist-packages (from transformers==4.51.3->dots_ocr==1.0) (0.21.4)\\n\",\n            \"Requirement already satisfied: safetensors>=0.4.3 in /usr/local/lib/python3.11/dist-packages (from transformers==4.51.3->dots_ocr==1.0) (0.5.3)\\n\",\n            \"Requirement already satisfied: tqdm>=4.27 in /usr/local/lib/python3.11/dist-packages (from transformers==4.51.3->dots_ocr==1.0) (4.67.1)\\n\",\n            \"Requirement already satisfied: fsspec>=2023.5.0 in /usr/local/lib/python3.11/dist-packages (from huggingface_hub->dots_ocr==1.0) (2025.3.0)\\n\",\n            \"Requirement already satisfied: typing-extensions>=3.7.4.3 in /usr/local/lib/python3.11/dist-packages (from huggingface_hub->dots_ocr==1.0) (4.14.1)\\n\",\n            \"Requirement already satisfied: hf-xet<2.0.0,>=1.1.3 in /usr/local/lib/python3.11/dist-packages (from huggingface_hub->dots_ocr==1.0) (1.1.5)\\n\",\n            \"Requirement already satisfied: psutil in /usr/local/lib/python3.11/dist-packages (from accelerate->dots_ocr==1.0) (5.9.5)\\n\",\n            \"Requirement already satisfied: aiofiles<25.0,>=22.0 in /usr/local/lib/python3.11/dist-packages (from gradio->dots_ocr==1.0) (24.1.0)\\n\",\n            \"Requirement already satisfied: anyio<5.0,>=3.0 in /usr/local/lib/python3.11/dist-packages (from gradio->dots_ocr==1.0) (4.10.0)\\n\",\n            \"Requirement already satisfied: brotli>=1.1.0 in /usr/local/lib/python3.11/dist-packages (from gradio->dots_ocr==1.0) (1.1.0)\\n\",\n            \"Requirement already satisfied: fastapi<1.0,>=0.115.2 in /usr/local/lib/python3.11/dist-packages (from gradio->dots_ocr==1.0) (0.116.1)\\n\",\n            \"Requirement already satisfied: ffmpy in /usr/local/lib/python3.11/dist-packages (from gradio->dots_ocr==1.0) (0.6.1)\\n\",\n            \"Requirement already satisfied: gradio-client==1.11.0 in /usr/local/lib/python3.11/dist-packages (from gradio->dots_ocr==1.0) (1.11.0)\\n\",\n            \"Requirement already satisfied: groovy~=0.1 in /usr/local/lib/python3.11/dist-packages (from gradio->dots_ocr==1.0) (0.1.2)\\n\",\n            \"Requirement already satisfied: httpx<1.0,>=0.24.1 in /usr/local/lib/python3.11/dist-packages (from gradio->dots_ocr==1.0) (0.28.1)\\n\",\n            \"Requirement already satisfied: jinja2<4.0 in /usr/local/lib/python3.11/dist-packages (from gradio->dots_ocr==1.0) (3.1.6)\\n\",\n            \"Requirement already satisfied: markupsafe<4.0,>=2.0 in /usr/local/lib/python3.11/dist-packages (from gradio->dots_ocr==1.0) (3.0.2)\\n\",\n            \"Requirement already satisfied: orjson~=3.0 in /usr/local/lib/python3.11/dist-packages (from gradio->dots_ocr==1.0) (3.11.1)\\n\",\n            \"Requirement already satisfied: pandas<3.0,>=1.0 in /usr/local/lib/python3.11/dist-packages (from gradio->dots_ocr==1.0) (2.2.2)\\n\",\n            \"Requirement already satisfied: pillow<12.0,>=8.0 in /usr/local/lib/python3.11/dist-packages (from gradio->dots_ocr==1.0) (11.3.0)\\n\",\n            \"Requirement already satisfied: pydantic<2.12,>=2.0 in /usr/local/lib/python3.11/dist-packages (from gradio->dots_ocr==1.0) (2.11.7)\\n\",\n            \"Requirement already satisfied: pydub in /usr/local/lib/python3.11/dist-packages (from gradio->dots_ocr==1.0) (0.25.1)\\n\",\n            \"Requirement already satisfied: python-multipart>=0.0.18 in /usr/local/lib/python3.11/dist-packages (from gradio->dots_ocr==1.0) (0.0.20)\\n\",\n            \"Requirement already satisfied: ruff>=0.9.3 in /usr/local/lib/python3.11/dist-packages (from gradio->dots_ocr==1.0) (0.12.7)\\n\",\n            \"Requirement already satisfied: safehttpx<0.2.0,>=0.1.6 in /usr/local/lib/python3.11/dist-packages (from gradio->dots_ocr==1.0) (0.1.6)\\n\",\n            \"Requirement already satisfied: semantic-version~=2.0 in /usr/local/lib/python3.11/dist-packages (from gradio->dots_ocr==1.0) (2.10.0)\\n\",\n            \"Requirement already satisfied: starlette<1.0,>=0.40.0 in /usr/local/lib/python3.11/dist-packages (from gradio->dots_ocr==1.0) (0.47.2)\\n\",\n            \"Requirement already satisfied: tomlkit<0.14.0,>=0.12.0 in /usr/local/lib/python3.11/dist-packages (from gradio->dots_ocr==1.0) (0.13.3)\\n\",\n            \"Requirement already satisfied: typer<1.0,>=0.12 in /usr/local/lib/python3.11/dist-packages (from gradio->dots_ocr==1.0) (0.16.0)\\n\",\n            \"Requirement already satisfied: uvicorn>=0.14.0 in /usr/local/lib/python3.11/dist-packages (from gradio->dots_ocr==1.0) (0.35.0)\\n\",\n            \"Requirement already satisfied: websockets<16.0,>=10.0 in /usr/local/lib/python3.11/dist-packages (from gradio-client==1.11.0->gradio->dots_ocr==1.0) (15.0.1)\\n\",\n            \"Requirement already satisfied: setuptools in /usr/local/lib/python3.11/dist-packages (from modelscope->dots_ocr==1.0) (75.2.0)\\n\",\n            \"Requirement already satisfied: urllib3>=1.26 in /usr/local/lib/python3.11/dist-packages (from modelscope->dots_ocr==1.0) (2.5.0)\\n\",\n            \"Requirement already satisfied: distro<2,>=1.7.0 in /usr/local/lib/python3.11/dist-packages (from openai->dots_ocr==1.0) (1.9.0)\\n\",\n            \"Requirement already satisfied: jiter<1,>=0.4.0 in /usr/local/lib/python3.11/dist-packages (from openai->dots_ocr==1.0) (0.10.0)\\n\",\n            \"Requirement already satisfied: sniffio in /usr/local/lib/python3.11/dist-packages (from openai->dots_ocr==1.0) (1.3.1)\\n\",\n            \"Collecting av (from qwen_vl_utils->dots_ocr==1.0)\\n\",\n            \"  Downloading av-15.0.0-cp311-cp311-manylinux_2_28_x86_64.whl.metadata (4.6 kB)\\n\",\n            \"Requirement already satisfied: idna>=2.8 in /usr/local/lib/python3.11/dist-packages (from anyio<5.0,>=3.0->gradio->dots_ocr==1.0) (3.10)\\n\",\n            \"Requirement already satisfied: certifi in /usr/local/lib/python3.11/dist-packages (from httpx<1.0,>=0.24.1->gradio->dots_ocr==1.0) (2025.8.3)\\n\",\n            \"Requirement already satisfied: httpcore==1.* in /usr/local/lib/python3.11/dist-packages (from httpx<1.0,>=0.24.1->gradio->dots_ocr==1.0) (1.0.9)\\n\",\n            \"Requirement already satisfied: h11>=0.16 in /usr/local/lib/python3.11/dist-packages (from httpcore==1.*->httpx<1.0,>=0.24.1->gradio->dots_ocr==1.0) (0.16.0)\\n\",\n            \"Requirement already satisfied: python-dateutil>=2.8.2 in /usr/local/lib/python3.11/dist-packages (from pandas<3.0,>=1.0->gradio->dots_ocr==1.0) (2.9.0.post0)\\n\",\n            \"Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.11/dist-packages (from pandas<3.0,>=1.0->gradio->dots_ocr==1.0) (2025.2)\\n\",\n            \"Requirement already satisfied: tzdata>=2022.7 in /usr/local/lib/python3.11/dist-packages (from pandas<3.0,>=1.0->gradio->dots_ocr==1.0) (2025.2)\\n\",\n            \"Requirement already satisfied: annotated-types>=0.6.0 in /usr/local/lib/python3.11/dist-packages (from pydantic<2.12,>=2.0->gradio->dots_ocr==1.0) (0.7.0)\\n\",\n            \"Requirement already satisfied: pydantic-core==2.33.2 in /usr/local/lib/python3.11/dist-packages (from pydantic<2.12,>=2.0->gradio->dots_ocr==1.0) (2.33.2)\\n\",\n            \"Requirement already satisfied: typing-inspection>=0.4.0 in /usr/local/lib/python3.11/dist-packages (from pydantic<2.12,>=2.0->gradio->dots_ocr==1.0) (0.4.1)\\n\",\n            \"Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.11/dist-packages (from requests->transformers==4.51.3->dots_ocr==1.0) (3.4.2)\\n\",\n            \"Requirement already satisfied: sympy>=1.13.3 in /usr/local/lib/python3.11/dist-packages (from torch->flash-attn==2.8.0.post2->dots_ocr==1.0) (1.13.3)\\n\",\n            \"Requirement already satisfied: networkx in /usr/local/lib/python3.11/dist-packages (from torch->flash-attn==2.8.0.post2->dots_ocr==1.0) (3.5)\\n\",\n            \"Requirement already satisfied: nvidia-cuda-nvrtc-cu12==12.8.61 in /usr/local/lib/python3.11/dist-packages (from torch->flash-attn==2.8.0.post2->dots_ocr==1.0) (12.8.61)\\n\",\n            \"Requirement already satisfied: nvidia-cuda-runtime-cu12==12.8.57 in /usr/local/lib/python3.11/dist-packages (from torch->flash-attn==2.8.0.post2->dots_ocr==1.0) (12.8.57)\\n\",\n            \"Requirement already satisfied: nvidia-cuda-cupti-cu12==12.8.57 in /usr/local/lib/python3.11/dist-packages (from torch->flash-attn==2.8.0.post2->dots_ocr==1.0) (12.8.57)\\n\",\n            \"Requirement already satisfied: nvidia-cudnn-cu12==9.7.1.26 in /usr/local/lib/python3.11/dist-packages (from torch->flash-attn==2.8.0.post2->dots_ocr==1.0) (9.7.1.26)\\n\",\n            \"Requirement already satisfied: nvidia-cublas-cu12==12.8.3.14 in /usr/local/lib/python3.11/dist-packages (from torch->flash-attn==2.8.0.post2->dots_ocr==1.0) (12.8.3.14)\\n\",\n            \"Requirement already satisfied: nvidia-cufft-cu12==11.3.3.41 in /usr/local/lib/python3.11/dist-packages (from torch->flash-attn==2.8.0.post2->dots_ocr==1.0) (11.3.3.41)\\n\",\n            \"Requirement already satisfied: nvidia-curand-cu12==10.3.9.55 in /usr/local/lib/python3.11/dist-packages (from torch->flash-attn==2.8.0.post2->dots_ocr==1.0) (10.3.9.55)\\n\",\n            \"Requirement already satisfied: nvidia-cusolver-cu12==11.7.2.55 in /usr/local/lib/python3.11/dist-packages (from torch->flash-attn==2.8.0.post2->dots_ocr==1.0) (11.7.2.55)\\n\",\n            \"Requirement already satisfied: nvidia-cusparse-cu12==12.5.7.53 in /usr/local/lib/python3.11/dist-packages (from torch->flash-attn==2.8.0.post2->dots_ocr==1.0) (12.5.7.53)\\n\",\n            \"Requirement already satisfied: nvidia-cusparselt-cu12==0.6.3 in /usr/local/lib/python3.11/dist-packages (from torch->flash-attn==2.8.0.post2->dots_ocr==1.0) (0.6.3)\\n\",\n            \"Requirement already satisfied: nvidia-nccl-cu12==2.26.2 in /usr/local/lib/python3.11/dist-packages (from torch->flash-attn==2.8.0.post2->dots_ocr==1.0) (2.26.2)\\n\",\n            \"Requirement already satisfied: nvidia-nvtx-cu12==12.8.55 in /usr/local/lib/python3.11/dist-packages (from torch->flash-attn==2.8.0.post2->dots_ocr==1.0) (12.8.55)\\n\",\n            \"Requirement already satisfied: nvidia-nvjitlink-cu12==12.8.61 in /usr/local/lib/python3.11/dist-packages (from torch->flash-attn==2.8.0.post2->dots_ocr==1.0) (12.8.61)\\n\",\n            \"Requirement already satisfied: nvidia-cufile-cu12==1.13.0.11 in /usr/local/lib/python3.11/dist-packages (from torch->flash-attn==2.8.0.post2->dots_ocr==1.0) (1.13.0.11)\\n\",\n            \"Requirement already satisfied: triton==3.3.0 in /usr/local/lib/python3.11/dist-packages (from torch->flash-attn==2.8.0.post2->dots_ocr==1.0) (3.3.0)\\n\",\n            \"Requirement already satisfied: click>=8.0.0 in /usr/local/lib/python3.11/dist-packages (from typer<1.0,>=0.12->gradio->dots_ocr==1.0) (8.2.1)\\n\",\n            \"Requirement already satisfied: shellingham>=1.3.0 in /usr/local/lib/python3.11/dist-packages (from typer<1.0,>=0.12->gradio->dots_ocr==1.0) (1.5.4)\\n\",\n            \"Requirement already satisfied: rich>=10.11.0 in /usr/local/lib/python3.11/dist-packages (from typer<1.0,>=0.12->gradio->dots_ocr==1.0) (13.9.4)\\n\",\n            \"Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.11/dist-packages (from python-dateutil>=2.8.2->pandas<3.0,>=1.0->gradio->dots_ocr==1.0) (1.17.0)\\n\",\n            \"Requirement already satisfied: markdown-it-py>=2.2.0 in /usr/local/lib/python3.11/dist-packages (from rich>=10.11.0->typer<1.0,>=0.12->gradio->dots_ocr==1.0) (3.0.0)\\n\",\n            \"Requirement already satisfied: pygments<3.0.0,>=2.13.0 in /usr/local/lib/python3.11/dist-packages (from rich>=10.11.0->typer<1.0,>=0.12->gradio->dots_ocr==1.0) (2.19.2)\\n\",\n            \"Requirement already satisfied: mpmath<1.4,>=1.1.0 in /usr/local/lib/python3.11/dist-packages (from sympy>=1.13.3->torch->flash-attn==2.8.0.post2->dots_ocr==1.0) (1.3.0)\\n\",\n            \"Requirement already satisfied: mdurl~=0.1 in /usr/local/lib/python3.11/dist-packages (from markdown-it-py>=2.2.0->rich>=10.11.0->typer<1.0,>=0.12->gradio->dots_ocr==1.0) (0.1.2)\\n\",\n            \"Downloading transformers-4.51.3-py3-none-any.whl (10.4 MB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m10.4/10.4 MB\\u001b[0m \\u001b[31m132.8 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading gradio_image_annotation-0.4.0-py3-none-any.whl (91 kB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m91.5/91.5 kB\\u001b[0m \\u001b[31m9.2 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading modelscope-1.28.2-py3-none-any.whl (5.9 MB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m5.9/5.9 MB\\u001b[0m \\u001b[31m129.0 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading pymupdf-1.26.3-cp39-abi3-manylinux_2_28_x86_64.whl (24.1 MB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m24.1/24.1 MB\\u001b[0m \\u001b[31m101.7 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading qwen_vl_utils-0.0.11-py3-none-any.whl (7.6 kB)\\n\",\n            \"Downloading av-15.0.0-cp311-cp311-manylinux_2_28_x86_64.whl (39.7 MB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m39.7/39.7 MB\\u001b[0m \\u001b[31m61.6 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hBuilding wheels for collected packages: flash-attn\\n\",\n            \"  Building wheel for flash-attn (setup.py) ... \\u001b[?25l\\u001b[?25hdone\\n\",\n            \"  Created wheel for flash-attn: filename=flash_attn-2.8.0.post2-cp311-cp311-linux_x86_64.whl size=255941661 sha256=8ed71ac092f80b079d2e6043b769135904d6e834916cb6da7d372b394581447b\\n\",\n            \"  Stored in directory: /root/.cache/pip/wheels/a2/75/55/57ba1e272fd7fa1a01d9ba6b5334b7adaabf79900ede22c040\\n\",\n            \"Successfully built flash-attn\\n\",\n            \"Installing collected packages: PyMuPDF, av, qwen_vl_utils, modelscope, transformers, flash-attn, gradio_image_annotation, dots_ocr\\n\",\n            \"  Attempting uninstall: transformers\\n\",\n            \"    Found existing installation: transformers 4.54.1\\n\",\n            \"    Uninstalling transformers-4.54.1:\\n\",\n            \"      Successfully uninstalled transformers-4.54.1\\n\",\n            \"  Running setup.py develop for dots_ocr\\n\",\n            \"Successfully installed PyMuPDF-1.26.3 av-15.0.0 dots_ocr-1.0 flash-attn-2.8.0.post2 gradio_image_annotation-0.4.0 modelscope-1.28.2 qwen_vl_utils-0.0.11 transformers-4.51.3\\n\"\n          ]\n        }\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"source\": [\n        \"!python3 tools/download_model.py\"\n      ],\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"z0nKSOYsRaA2\",\n        \"outputId\": \"e4d67ed5-0cb9-437a-abec-5514f7bb8ccc\"\n      },\n      \"execution_count\": null,\n      \"outputs\": [\n        {\n          \"output_type\": \"stream\",\n          \"name\": \"stdout\",\n          \"text\": [\n            \"Attention: The model save dir dots.ocr should be replace by a name without `.` like DotsOCR, util we merge our code to transformers.\\n\",\n            \"/usr/local/lib/python3.11/dist-packages/huggingface_hub/file_download.py:945: FutureWarning: `resume_download` is deprecated and will be removed in version 1.0.0. Downloads always resume when possible. If you want to force a new download, use `force_download=True`.\\n\",\n            \"  warnings.warn(\\n\",\n            \"/usr/local/lib/python3.11/dist-packages/huggingface_hub/file_download.py:982: UserWarning: `local_dir_use_symlinks` parameter is deprecated and will be ignored. The process to download files to a local folder has been updated and do not rely on symlinks anymore. You only need to pass a destination folder as`local_dir`.\\n\",\n            \"For more details, check out https://huggingface.co/docs/huggingface_hub/main/en/guides/download#download-files-to-local-folder.\\n\",\n            \"  warnings.warn(\\n\",\n            \"Fetching 19 files:   0% 0/19 [00:00<?, ?it/s]\\n\",\n            \"chat_template.json: 1.11kB [00:00, 2.48MB/s]\\n\",\n            \"\\n\",\n            \"generation_config.json: 100% 74.0/74.0 [00:00<00:00, 727kB/s]\\n\",\n            \"\\n\",\n            \"configuration_dots.py: 2.93kB [00:00, 15.1MB/s]\\n\",\n            \"\\n\",\n            \".gitattributes: 1.52kB [00:00, 8.96MB/s]\\n\",\n            \"Fetching 19 files:   5% 1/19 [00:00<00:05,  3.39it/s]\\n\",\n            \"config.json: 1.47kB [00:00, 9.48MB/s]\\n\",\n            \"\\n\",\n            \"README.md: 31.1kB [00:00, 76.2MB/s]\\n\",\n            \"\\n\",\n            \"NOTICE: 118kB [00:00, 148MB/s]\\n\",\n            \"\\n\",\n            \"model-00002-of-00002.safetensors:   0% 0.00/1.79G [00:00<?, ?B/s]\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:   0% 0.00/4.29G [00:00<?, ?B/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"\\n\",\n            \"model.safetensors.index.json: 52.2kB [00:00, 153MB/s]\\n\",\n            \"\\n\",\n            \"\\n\",\n            \"\\n\",\n            \"modeling_dots_ocr_vllm.py: 17.5kB [00:00, 53.8MB/s]\\n\",\n            \"\\n\",\n            \"\\n\",\n            \"\\n\",\n            \"modeling_dots_ocr.py: 4.98kB [00:00, 17.7MB/s]\\n\",\n            \"\\n\",\n            \"\\n\",\n            \"\\n\",\n            \"modeling_dots_vision.py: 14.9kB [00:00, 44.7MB/s]\\n\",\n            \"\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:   0% 21.0M/4.29G [00:00<00:21, 202MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"\\n\",\n            \"preprocessor_config.json: 100% 347/347 [00:00<00:00, 2.95MB/s]\\n\",\n            \"\\n\",\n            \"model-00002-of-00002.safetensors:   1% 21.0M/1.79G [00:00<00:10, 175MB/s]\\u001b[A\\n\",\n            \"\\n\",\n            \"\\n\",\n            \"merges.txt: 0.00B [00:00, ?B/s]\\u001b[A\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"merges.txt: 1.67MB [00:00, 71.2MB/s]\\n\",\n            \"Fetching 19 files:  42% 8/19 [00:00<00:00, 12.00it/s]\\n\",\n            \"model-00002-of-00002.safetensors:   3% 52.4M/1.79G [00:00<00:07, 227MB/s]\\u001b[A\\n\",\n            \"\\n\",\n            \"\\n\",\n            \"special_tokens_map.json: 100% 494/494 [00:00<00:00, 2.97MB/s]\\n\",\n            \"\\n\",\n            \"\\n\",\n            \"\\n\",\n            \"tokenizer.json: 0.00B [00:00, ?B/s]\\u001b[A\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"\\n\",\n            \"\\n\",\n            \"tokenizer_config.json: 9.31kB [00:00, 33.9MB/s]\\n\",\n            \"\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:   2% 105M/4.29G [00:00<00:11, 350MB/s] \\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"\\n\",\n            \"\\n\",\n            \"tokenizer.json: 7.04MB [00:00, 133MB/s]\\n\",\n            \"vocab.json: 2.78MB [00:00, 102MB/s]\\n\",\n            \"\\n\",\n            \"model-00002-of-00002.safetensors:   5% 94.4M/1.79G [00:00<00:05, 292MB/s]\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:   4% 157M/4.29G [00:00<00:10, 413MB/s]\\u001b[A\\u001b[A\\n\",\n            \"model-00002-of-00002.safetensors:   9% 157M/1.79G [00:00<00:04, 389MB/s] \\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:   5% 220M/4.29G [00:00<00:08, 461MB/s]\\u001b[A\\u001b[A\\n\",\n            \"model-00002-of-00002.safetensors:  12% 210M/1.79G [00:00<00:03, 432MB/s]\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:   6% 273M/4.29G [00:00<00:08, 479MB/s]\\u001b[A\\u001b[A\\n\",\n            \"model-00002-of-00002.safetensors:  15% 273M/1.79G [00:00<00:03, 466MB/s]\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:   8% 325M/4.29G [00:00<00:08, 489MB/s]\\u001b[A\\u001b[A\\n\",\n            \"model-00002-of-00002.safetensors:  18% 325M/1.79G [00:00<00:03, 477MB/s]\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:   9% 377M/4.29G [00:00<00:07, 496MB/s]\\u001b[A\\u001b[A\\n\",\n            \"model-00002-of-00002.safetensors:  21% 377M/1.79G [00:00<00:02, 484MB/s]\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  10% 430M/4.29G [00:00<00:07, 484MB/s]\\u001b[A\\u001b[A\\n\",\n            \"model-00002-of-00002.safetensors:  24% 430M/1.79G [00:01<00:02, 473MB/s]\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  11% 482M/4.29G [00:01<00:08, 469MB/s]\\u001b[A\\u001b[A\\n\",\n            \"model-00002-of-00002.safetensors:  27% 482M/1.79G [00:01<00:02, 464MB/s]\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  12% 535M/4.29G [00:01<00:08, 444MB/s]\\u001b[A\\u001b[A\\n\",\n            \"model-00002-of-00002.safetensors:  30% 535M/1.79G [00:01<00:02, 469MB/s]\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  14% 587M/4.29G [00:01<00:08, 439MB/s]\\u001b[A\\u001b[A\\n\",\n            \"model-00002-of-00002.safetensors:  33% 587M/1.79G [00:01<00:02, 462MB/s]\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  15% 640M/4.29G [00:01<00:08, 437MB/s]\\u001b[A\\u001b[A\\n\",\n            \"model-00002-of-00002.safetensors:  36% 640M/1.79G [00:01<00:02, 459MB/s]\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  16% 692M/4.29G [00:03<00:50, 71.2MB/s]\\u001b[A\\u001b[A\\n\",\n            \"model-00002-of-00002.safetensors:  39% 692M/1.79G [00:03<00:15, 72.2MB/s]\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  17% 744M/4.29G [00:03<00:37, 95.4MB/s]\\u001b[A\\u001b[A\\n\",\n            \"model-00002-of-00002.safetensors:  42% 744M/1.79G [00:03<00:10, 96.8MB/s]\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  19% 797M/4.29G [00:03<00:27, 125MB/s] \\u001b[A\\u001b[A\\n\",\n            \"model-00002-of-00002.safetensors:  45% 797M/1.79G [00:03<00:07, 127MB/s] \\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  20% 849M/4.29G [00:03<00:21, 159MB/s]\\u001b[A\\u001b[A\\n\",\n            \"model-00002-of-00002.safetensors:  48% 849M/1.79G [00:03<00:05, 161MB/s]\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  21% 891M/4.29G [00:04<00:17, 189MB/s]\\u001b[A\\u001b[A\\n\",\n            \"model-00002-of-00002.safetensors:  51% 902M/1.79G [00:04<00:04, 201MB/s]\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  22% 944M/4.29G [00:04<00:14, 229MB/s]\\u001b[A\\u001b[A\\n\",\n            \"model-00002-of-00002.safetensors:  53% 954M/1.79G [00:04<00:03, 242MB/s]\\u001b[A\\n\",\n            \"model-00002-of-00002.safetensors:  56% 1.01G/1.79G [00:04<00:02, 288MB/s]\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  23% 996M/4.29G [00:04<00:12, 269MB/s]\\u001b[A\\u001b[A\\n\",\n            \"model-00002-of-00002.safetensors:  59% 1.06G/1.79G [00:04<00:02, 318MB/s]\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  24% 1.05G/4.29G [00:04<00:10, 304MB/s]\\u001b[A\\u001b[A\\n\",\n            \"model-00002-of-00002.safetensors:  62% 1.11G/1.79G [00:04<00:01, 343MB/s]\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  26% 1.10G/4.29G [00:04<00:09, 327MB/s]\\u001b[A\\u001b[A\\n\",\n            \"model-00002-of-00002.safetensors:  65% 1.16G/1.79G [00:04<00:01, 364MB/s]\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  27% 1.15G/4.29G [00:04<00:08, 353MB/s]\\u001b[A\\u001b[A\\n\",\n            \"model-00002-of-00002.safetensors:  68% 1.22G/1.79G [00:04<00:01, 387MB/s]\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  28% 1.21G/4.29G [00:04<00:08, 370MB/s]\\u001b[A\\u001b[A\\n\",\n            \"model-00002-of-00002.safetensors:  72% 1.28G/1.79G [00:04<00:01, 425MB/s]\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  29% 1.26G/4.29G [00:04<00:08, 355MB/s]\\u001b[A\\u001b[A\\n\",\n            \"model-00002-of-00002.safetensors:  75% 1.33G/1.79G [00:05<00:01, 348MB/s]\\u001b[A\\n\",\n            \"model-00002-of-00002.safetensors:  78% 1.39G/1.79G [00:05<00:00, 400MB/s]\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  30% 1.30G/4.29G [00:05<00:12, 240MB/s]\\u001b[A\\u001b[A\\n\",\n            \"model-00002-of-00002.safetensors:  81% 1.45G/1.79G [00:05<00:00, 415MB/s]\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  31% 1.34G/4.29G [00:05<00:11, 264MB/s]\\u001b[A\\u001b[A\\n\",\n            \"model-00002-of-00002.safetensors:  84% 1.50G/1.79G [00:07<00:04, 68.5MB/s]\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  32% 1.38G/4.29G [00:07<00:52, 55.7MB/s]\\u001b[A\\u001b[A\\n\",\n            \"model-00002-of-00002.safetensors:  87% 1.55G/1.79G [00:07<00:02, 91.2MB/s]\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  33% 1.44G/4.29G [00:07<00:36, 78.6MB/s]\\u001b[A\\u001b[A\\n\",\n            \"model-00002-of-00002.safetensors:  90% 1.60G/1.79G [00:07<00:01, 120MB/s] \\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  35% 1.49G/4.29G [00:07<00:26, 106MB/s] \\u001b[A\\u001b[A\\n\",\n            \"model-00002-of-00002.safetensors:  93% 1.66G/1.79G [00:08<00:00, 154MB/s]\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  36% 1.54G/4.29G [00:08<00:19, 139MB/s]\\u001b[A\\u001b[A\\n\",\n            \"model-00002-of-00002.safetensors:  96% 1.71G/1.79G [00:08<00:00, 194MB/s]\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  37% 1.58G/4.29G [00:08<00:16, 169MB/s]\\u001b[A\\u001b[A\\n\",\n            \"model-00002-of-00002.safetensors:  99% 1.76G/1.79G [00:08<00:00, 233MB/s]\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00002-of-00002.safetensors: 100% 1.79G/1.79G [00:08<00:00, 215MB/s]\\n\",\n            \"\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  39% 1.68G/4.29G [00:08<00:10, 247MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  40% 1.73G/4.29G [00:08<00:08, 294MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  42% 1.78G/4.29G [00:08<00:07, 331MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  43% 1.84G/4.29G [00:08<00:06, 361MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  44% 1.89G/4.29G [00:08<00:06, 385MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  45% 1.94G/4.29G [00:08<00:05, 419MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  46% 1.99G/4.29G [00:09<00:05, 445MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  48% 2.04G/4.29G [00:09<00:04, 466MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  49% 2.10G/4.29G [00:09<00:04, 478MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  50% 2.15G/4.29G [00:09<00:04, 490MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  52% 2.21G/4.29G [00:09<00:04, 508MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  53% 2.28G/4.29G [00:09<00:03, 513MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  54% 2.34G/4.29G [00:09<00:03, 518MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  56% 2.40G/4.29G [00:09<00:03, 531MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  57% 2.46G/4.29G [00:09<00:03, 554MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  59% 2.53G/4.29G [00:10<00:03, 573MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  60% 2.59G/4.29G [00:10<00:02, 585MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  62% 2.65G/4.29G [00:10<00:02, 596MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  63% 2.72G/4.29G [00:10<00:04, 365MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  65% 2.78G/4.29G [00:10<00:03, 404MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  66% 2.84G/4.29G [00:10<00:03, 439MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  68% 2.90G/4.29G [00:10<00:02, 468MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  69% 2.97G/4.29G [00:11<00:02, 489MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  71% 3.03G/4.29G [00:11<00:03, 406MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  72% 3.08G/4.29G [00:11<00:03, 350MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  73% 3.12G/4.29G [00:11<00:03, 327MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  74% 3.17G/4.29G [00:11<00:03, 306MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  75% 3.21G/4.29G [00:11<00:03, 289MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  75% 3.24G/4.29G [00:12<00:03, 281MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  76% 3.27G/4.29G [00:12<00:03, 285MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  77% 3.31G/4.29G [00:12<00:03, 293MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  78% 3.36G/4.29G [00:12<00:02, 315MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  79% 3.41G/4.29G [00:12<00:02, 366MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  81% 3.46G/4.29G [00:12<00:02, 403MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  82% 3.50G/4.29G [00:15<00:18, 42.7MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  83% 3.57G/4.29G [00:15<00:11, 65.4MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  85% 3.63G/4.29G [00:16<00:07, 94.9MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  86% 3.69G/4.29G [00:16<00:04, 132MB/s] \\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  87% 3.75G/4.29G [00:16<00:03, 177MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  89% 3.82G/4.29G [00:16<00:02, 228MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  90% 3.88G/4.29G [00:16<00:01, 284MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  92% 3.94G/4.29G [00:16<00:01, 340MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  93% 4.01G/4.29G [00:16<00:00, 394MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  95% 4.07G/4.29G [00:16<00:00, 438MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  96% 4.13G/4.29G [00:16<00:00, 474MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors:  98% 4.19G/4.29G [00:17<00:00, 503MB/s]\\u001b[A\\u001b[A\\n\",\n            \"\\n\",\n            \"model-00001-of-00002.safetensors: 100% 4.29G/4.29G [00:17<00:00, 250MB/s]\\n\",\n            \"Fetching 19 files: 100% 19/19 [00:17<00:00,  1.07it/s]\\n\",\n            \"model downloaded to /content/dots.ocr/weights/DotsOCR\\n\"\n          ]\n        }\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"source\": [\n        \"import os\\n\",\n        \"from pathlib import Path\\n\",\n        \"\\n\",\n        \"# Set up model path (using a directory in Colab's temporary storage)\\n\",\n        \"hf_model_path = \\\"./weights/DotsOCR\\\"\\n\",\n        \"os.environ[\\\"hf_model_path\\\"] = hf_model_path\\n\",\n        \"\\n\",\n        \"# Create directory if it doesn't exist\\n\",\n        \"Path(hf_model_path).mkdir(parents=True, exist_ok=True)\\n\",\n        \"\\n\",\n        \"# Add to PYTHONPATH\\n\",\n        \"os.environ[\\\"PYTHONPATH\\\"] = f\\\"{os.path.dirname(hf_model_path)}:{os.environ.get('PYTHONPATH', '')}\\\"\\n\",\n        \"\\n\",\n        \"# Install required packages\\n\",\n        \"!pip install vllm==0.10.0 transformers\\n\",\n        \"\\n\",\n        \"# Modify vllm import (this is a workaround - may need adjustment based on vllm version)\\n\",\n        \"try:\\n\",\n        \"    vllm_path = !which vllm\\n\",\n        \"    if vllm_path:\\n\",\n        \"        vllm_path = vllm_path[0]\\n\",\n        \"        !sed -i '/^from vllm\\\\.entrypoints\\\\.cli\\\\.main import main$/a from DotsOCR import modeling_dots_ocr_vllm' {vllm_path}\\n\",\n        \"except:\\n\",\n        \"    print(\\\"Could not automatically modify vllm imports. You may need to do this manually.\\\")\"\n      ],\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"m1eyfkYlTGTs\",\n        \"outputId\": \"04548a02-fc8c-4891-8b95-0fad33f0f20e\"\n      },\n      \"execution_count\": null,\n      \"outputs\": [\n        {\n          \"output_type\": \"stream\",\n          \"name\": \"stdout\",\n          \"text\": [\n            \"Collecting vllm\\n\",\n            \"  Downloading vllm-0.10.0-cp38-abi3-manylinux1_x86_64.whl.metadata (14 kB)\\n\",\n            \"Requirement already satisfied: transformers in /usr/local/lib/python3.11/dist-packages (4.51.3)\\n\",\n            \"Requirement already satisfied: regex in /usr/local/lib/python3.11/dist-packages (from vllm) (2024.11.6)\\n\",\n            \"Requirement already satisfied: cachetools in /usr/local/lib/python3.11/dist-packages (from vllm) (5.5.2)\\n\",\n            \"Requirement already satisfied: psutil in /usr/local/lib/python3.11/dist-packages (from vllm) (5.9.5)\\n\",\n            \"Requirement already satisfied: sentencepiece in /usr/local/lib/python3.11/dist-packages (from vllm) (0.2.0)\\n\",\n            \"Requirement already satisfied: numpy in /usr/local/lib/python3.11/dist-packages (from vllm) (2.0.2)\\n\",\n            \"Requirement already satisfied: requests>=2.26.0 in /usr/local/lib/python3.11/dist-packages (from vllm) (2.32.3)\\n\",\n            \"Requirement already satisfied: tqdm in /usr/local/lib/python3.11/dist-packages (from vllm) (4.67.1)\\n\",\n            \"Collecting blake3 (from vllm)\\n\",\n            \"  Downloading blake3-1.0.5-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (4.2 kB)\\n\",\n            \"Requirement already satisfied: py-cpuinfo in /usr/local/lib/python3.11/dist-packages (from vllm) (9.0.0)\\n\",\n            \"Collecting transformers\\n\",\n            \"  Downloading transformers-4.55.0-py3-none-any.whl.metadata (39 kB)\\n\",\n            \"Requirement already satisfied: huggingface-hub>=0.33.0 in /usr/local/lib/python3.11/dist-packages (from huggingface-hub[hf_xet]>=0.33.0->vllm) (0.34.3)\\n\",\n            \"Requirement already satisfied: tokenizers>=0.21.1 in /usr/local/lib/python3.11/dist-packages (from vllm) (0.21.4)\\n\",\n            \"Requirement already satisfied: protobuf in /usr/local/lib/python3.11/dist-packages (from vllm) (5.29.5)\\n\",\n            \"Requirement already satisfied: fastapi>=0.115.0 in /usr/local/lib/python3.11/dist-packages (from fastapi[standard]>=0.115.0->vllm) (0.116.1)\\n\",\n            \"Requirement already satisfied: aiohttp in /usr/local/lib/python3.11/dist-packages (from vllm) (3.12.15)\\n\",\n            \"Collecting openai<=1.90.0,>=1.87.0 (from vllm)\\n\",\n            \"  Downloading openai-1.90.0-py3-none-any.whl.metadata (26 kB)\\n\",\n            \"Requirement already satisfied: pydantic>=2.10 in /usr/local/lib/python3.11/dist-packages (from vllm) (2.11.7)\\n\",\n            \"Requirement already satisfied: prometheus_client>=0.18.0 in /usr/local/lib/python3.11/dist-packages (from vllm) (0.22.1)\\n\",\n            \"Requirement already satisfied: pillow in /usr/local/lib/python3.11/dist-packages (from vllm) (11.3.0)\\n\",\n            \"Collecting prometheus-fastapi-instrumentator>=7.0.0 (from vllm)\\n\",\n            \"  Downloading prometheus_fastapi_instrumentator-7.1.0-py3-none-any.whl.metadata (13 kB)\\n\",\n            \"Requirement already satisfied: tiktoken>=0.6.0 in /usr/local/lib/python3.11/dist-packages (from vllm) (0.9.0)\\n\",\n            \"Collecting lm-format-enforcer<0.11,>=0.10.11 (from vllm)\\n\",\n            \"  Downloading lm_format_enforcer-0.10.12-py3-none-any.whl.metadata (17 kB)\\n\",\n            \"Collecting llguidance<0.8.0,>=0.7.11 (from vllm)\\n\",\n            \"  Downloading llguidance-0.7.30-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (10 kB)\\n\",\n            \"Collecting outlines_core==0.2.10 (from vllm)\\n\",\n            \"  Downloading outlines_core-0.2.10-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (5.8 kB)\\n\",\n            \"Collecting diskcache==5.6.3 (from vllm)\\n\",\n            \"  Downloading diskcache-5.6.3-py3-none-any.whl.metadata (20 kB)\\n\",\n            \"Collecting lark==1.2.2 (from vllm)\\n\",\n            \"  Downloading lark-1.2.2-py3-none-any.whl.metadata (1.8 kB)\\n\",\n            \"Collecting xgrammar==0.1.21 (from vllm)\\n\",\n            \"  Downloading xgrammar-0.1.21-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (6.3 kB)\\n\",\n            \"Requirement already satisfied: typing_extensions>=4.10 in /usr/local/lib/python3.11/dist-packages (from vllm) (4.14.1)\\n\",\n            \"Requirement already satisfied: filelock>=3.16.1 in /usr/local/lib/python3.11/dist-packages (from vllm) (3.18.0)\\n\",\n            \"Collecting partial-json-parser (from vllm)\\n\",\n            \"  Downloading partial_json_parser-0.2.1.1.post6-py3-none-any.whl.metadata (6.1 kB)\\n\",\n            \"Requirement already satisfied: pyzmq>=25.0.0 in /usr/local/lib/python3.11/dist-packages (from vllm) (26.2.1)\\n\",\n            \"Collecting msgspec (from vllm)\\n\",\n            \"  Downloading msgspec-0.19.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (6.9 kB)\\n\",\n            \"Collecting gguf>=0.13.0 (from vllm)\\n\",\n            \"  Downloading gguf-0.17.1-py3-none-any.whl.metadata (4.3 kB)\\n\",\n            \"Collecting mistral_common>=1.8.2 (from mistral_common[audio,image]>=1.8.2->vllm)\\n\",\n            \"  Downloading mistral_common-1.8.3-py3-none-any.whl.metadata (3.8 kB)\\n\",\n            \"Requirement already satisfied: opencv-python-headless>=4.11.0 in /usr/local/lib/python3.11/dist-packages (from vllm) (4.12.0.88)\\n\",\n            \"Requirement already satisfied: pyyaml in /usr/local/lib/python3.11/dist-packages (from vllm) (6.0.2)\\n\",\n            \"Requirement already satisfied: einops in /usr/local/lib/python3.11/dist-packages (from vllm) (0.8.1)\\n\",\n            \"Collecting compressed-tensors==0.10.2 (from vllm)\\n\",\n            \"  Downloading compressed_tensors-0.10.2-py3-none-any.whl.metadata (7.0 kB)\\n\",\n            \"Collecting depyf==0.19.0 (from vllm)\\n\",\n            \"  Downloading depyf-0.19.0-py3-none-any.whl.metadata (7.3 kB)\\n\",\n            \"Requirement already satisfied: cloudpickle in /usr/local/lib/python3.11/dist-packages (from vllm) (3.1.1)\\n\",\n            \"Collecting watchfiles (from vllm)\\n\",\n            \"  Downloading watchfiles-1.1.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (4.9 kB)\\n\",\n            \"Collecting python-json-logger (from vllm)\\n\",\n            \"  Downloading python_json_logger-3.3.0-py3-none-any.whl.metadata (4.0 kB)\\n\",\n            \"Requirement already satisfied: scipy in /usr/local/lib/python3.11/dist-packages (from vllm) (1.16.1)\\n\",\n            \"Collecting ninja (from vllm)\\n\",\n            \"  Using cached ninja-1.11.1.4-py3-none-manylinux_2_12_x86_64.manylinux2010_x86_64.whl.metadata (5.0 kB)\\n\",\n            \"Collecting pybase64 (from vllm)\\n\",\n            \"  Downloading pybase64-1.4.2-cp311-cp311-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl.metadata (8.7 kB)\\n\",\n            \"Collecting cbor2 (from vllm)\\n\",\n            \"  Downloading cbor2-5.6.5-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (6.0 kB)\\n\",\n            \"Collecting numba==0.61.2 (from vllm)\\n\",\n            \"  Downloading numba-0.61.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl.metadata (2.8 kB)\\n\",\n            \"Collecting ray!=2.44.*,>=2.43.0 (from ray[cgraph]!=2.44.*,>=2.43.0->vllm)\\n\",\n            \"  Downloading ray-2.48.0-cp311-cp311-manylinux2014_x86_64.whl.metadata (19 kB)\\n\",\n            \"Collecting torch==2.7.1 (from vllm)\\n\",\n            \"  Downloading torch-2.7.1-cp311-cp311-manylinux_2_28_x86_64.whl.metadata (29 kB)\\n\",\n            \"Collecting torchaudio==2.7.1 (from vllm)\\n\",\n            \"  Downloading torchaudio-2.7.1-cp311-cp311-manylinux_2_28_x86_64.whl.metadata (6.6 kB)\\n\",\n            \"Collecting torchvision==0.22.1 (from vllm)\\n\",\n            \"  Downloading torchvision-0.22.1-cp311-cp311-manylinux_2_28_x86_64.whl.metadata (6.1 kB)\\n\",\n            \"Collecting xformers==0.0.31 (from vllm)\\n\",\n            \"  Downloading xformers-0.0.31-cp39-abi3-manylinux_2_28_x86_64.whl.metadata (1.0 kB)\\n\",\n            \"Collecting astor (from depyf==0.19.0->vllm)\\n\",\n            \"  Downloading astor-0.8.1-py2.py3-none-any.whl.metadata (4.2 kB)\\n\",\n            \"Requirement already satisfied: dill in /usr/local/lib/python3.11/dist-packages (from depyf==0.19.0->vllm) (0.3.8)\\n\",\n            \"Collecting llvmlite<0.45,>=0.44.0dev0 (from numba==0.61.2->vllm)\\n\",\n            \"  Downloading llvmlite-0.44.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (4.8 kB)\\n\",\n            \"Requirement already satisfied: sympy>=1.13.3 in /usr/local/lib/python3.11/dist-packages (from torch==2.7.1->vllm) (1.13.3)\\n\",\n            \"Requirement already satisfied: networkx in /usr/local/lib/python3.11/dist-packages (from torch==2.7.1->vllm) (3.5)\\n\",\n            \"Requirement already satisfied: jinja2 in /usr/local/lib/python3.11/dist-packages (from torch==2.7.1->vllm) (3.1.6)\\n\",\n            \"Requirement already satisfied: fsspec in /usr/local/lib/python3.11/dist-packages (from torch==2.7.1->vllm) (2025.3.0)\\n\",\n            \"Collecting nvidia-cuda-nvrtc-cu12==12.6.77 (from torch==2.7.1->vllm)\\n\",\n            \"  Downloading nvidia_cuda_nvrtc_cu12-12.6.77-py3-none-manylinux2014_x86_64.whl.metadata (1.5 kB)\\n\",\n            \"Collecting nvidia-cuda-runtime-cu12==12.6.77 (from torch==2.7.1->vllm)\\n\",\n            \"  Downloading nvidia_cuda_runtime_cu12-12.6.77-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl.metadata (1.5 kB)\\n\",\n            \"Collecting nvidia-cuda-cupti-cu12==12.6.80 (from torch==2.7.1->vllm)\\n\",\n            \"  Downloading nvidia_cuda_cupti_cu12-12.6.80-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl.metadata (1.6 kB)\\n\",\n            \"Collecting nvidia-cudnn-cu12==9.5.1.17 (from torch==2.7.1->vllm)\\n\",\n            \"  Downloading nvidia_cudnn_cu12-9.5.1.17-py3-none-manylinux_2_28_x86_64.whl.metadata (1.6 kB)\\n\",\n            \"Collecting nvidia-cublas-cu12==12.6.4.1 (from torch==2.7.1->vllm)\\n\",\n            \"  Downloading nvidia_cublas_cu12-12.6.4.1-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl.metadata (1.5 kB)\\n\",\n            \"Collecting nvidia-cufft-cu12==11.3.0.4 (from torch==2.7.1->vllm)\\n\",\n            \"  Downloading nvidia_cufft_cu12-11.3.0.4-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl.metadata (1.5 kB)\\n\",\n            \"Collecting nvidia-curand-cu12==10.3.7.77 (from torch==2.7.1->vllm)\\n\",\n            \"  Downloading nvidia_curand_cu12-10.3.7.77-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl.metadata (1.5 kB)\\n\",\n            \"Collecting nvidia-cusolver-cu12==11.7.1.2 (from torch==2.7.1->vllm)\\n\",\n            \"  Downloading nvidia_cusolver_cu12-11.7.1.2-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl.metadata (1.6 kB)\\n\",\n            \"Collecting nvidia-cusparse-cu12==12.5.4.2 (from torch==2.7.1->vllm)\\n\",\n            \"  Downloading nvidia_cusparse_cu12-12.5.4.2-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl.metadata (1.6 kB)\\n\",\n            \"Requirement already satisfied: nvidia-cusparselt-cu12==0.6.3 in /usr/local/lib/python3.11/dist-packages (from torch==2.7.1->vllm) (0.6.3)\\n\",\n            \"Requirement already satisfied: nvidia-nccl-cu12==2.26.2 in /usr/local/lib/python3.11/dist-packages (from torch==2.7.1->vllm) (2.26.2)\\n\",\n            \"Collecting nvidia-nvtx-cu12==12.6.77 (from torch==2.7.1->vllm)\\n\",\n            \"  Downloading nvidia_nvtx_cu12-12.6.77-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl.metadata (1.6 kB)\\n\",\n            \"Collecting nvidia-nvjitlink-cu12==12.6.85 (from torch==2.7.1->vllm)\\n\",\n            \"  Downloading nvidia_nvjitlink_cu12-12.6.85-py3-none-manylinux2010_x86_64.manylinux_2_12_x86_64.whl.metadata (1.5 kB)\\n\",\n            \"Collecting nvidia-cufile-cu12==1.11.1.6 (from torch==2.7.1->vllm)\\n\",\n            \"  Downloading nvidia_cufile_cu12-1.11.1.6-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl.metadata (1.5 kB)\\n\",\n            \"Collecting triton==3.3.1 (from torch==2.7.1->vllm)\\n\",\n            \"  Downloading triton-3.3.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl.metadata (1.5 kB)\\n\",\n            \"Requirement already satisfied: setuptools>=40.8.0 in /usr/local/lib/python3.11/dist-packages (from triton==3.3.1->torch==2.7.1->vllm) (75.2.0)\\n\",\n            \"Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.11/dist-packages (from transformers) (25.0)\\n\",\n            \"Requirement already satisfied: safetensors>=0.4.3 in /usr/local/lib/python3.11/dist-packages (from transformers) (0.5.3)\\n\",\n            \"Requirement already satisfied: starlette<0.48.0,>=0.40.0 in /usr/local/lib/python3.11/dist-packages (from fastapi>=0.115.0->fastapi[standard]>=0.115.0->vllm) (0.47.2)\\n\",\n            \"Collecting fastapi-cli>=0.0.8 (from fastapi-cli[standard]>=0.0.8; extra == \\\"standard\\\"->fastapi[standard]>=0.115.0->vllm)\\n\",\n            \"  Downloading fastapi_cli-0.0.8-py3-none-any.whl.metadata (6.3 kB)\\n\",\n            \"Requirement already satisfied: httpx>=0.23.0 in /usr/local/lib/python3.11/dist-packages (from fastapi[standard]>=0.115.0->vllm) (0.28.1)\\n\",\n            \"Requirement already satisfied: python-multipart>=0.0.18 in /usr/local/lib/python3.11/dist-packages (from fastapi[standard]>=0.115.0->vllm) (0.0.20)\\n\",\n            \"Collecting email-validator>=2.0.0 (from fastapi[standard]>=0.115.0->vllm)\\n\",\n            \"  Downloading email_validator-2.2.0-py3-none-any.whl.metadata (25 kB)\\n\",\n            \"Requirement already satisfied: uvicorn>=0.12.0 in /usr/local/lib/python3.11/dist-packages (from uvicorn[standard]>=0.12.0; extra == \\\"standard\\\"->fastapi[standard]>=0.115.0->vllm) (0.35.0)\\n\",\n            \"Requirement already satisfied: hf-xet<2.0.0,>=1.1.3 in /usr/local/lib/python3.11/dist-packages (from huggingface-hub>=0.33.0->huggingface-hub[hf_xet]>=0.33.0->vllm) (1.1.5)\\n\",\n            \"Collecting interegular>=0.3.2 (from lm-format-enforcer<0.11,>=0.10.11->vllm)\\n\",\n            \"  Downloading interegular-0.3.3-py37-none-any.whl.metadata (3.0 kB)\\n\",\n            \"Requirement already satisfied: jsonschema>=4.21.1 in /usr/local/lib/python3.11/dist-packages (from mistral_common>=1.8.2->mistral_common[audio,image]>=1.8.2->vllm) (4.25.0)\\n\",\n            \"Collecting pydantic-extra-types>=2.10.5 (from pydantic-extra-types[pycountry]>=2.10.5->mistral_common>=1.8.2->mistral_common[audio,image]>=1.8.2->vllm)\\n\",\n            \"  Downloading pydantic_extra_types-2.10.5-py3-none-any.whl.metadata (3.9 kB)\\n\",\n            \"Requirement already satisfied: anyio<5,>=3.5.0 in /usr/local/lib/python3.11/dist-packages (from openai<=1.90.0,>=1.87.0->vllm) (4.10.0)\\n\",\n            \"Requirement already satisfied: distro<2,>=1.7.0 in /usr/local/lib/python3.11/dist-packages (from openai<=1.90.0,>=1.87.0->vllm) (1.9.0)\\n\",\n            \"Requirement already satisfied: jiter<1,>=0.4.0 in /usr/local/lib/python3.11/dist-packages (from openai<=1.90.0,>=1.87.0->vllm) (0.10.0)\\n\",\n            \"Requirement already satisfied: sniffio in /usr/local/lib/python3.11/dist-packages (from openai<=1.90.0,>=1.87.0->vllm) (1.3.1)\\n\",\n            \"Requirement already satisfied: annotated-types>=0.6.0 in /usr/local/lib/python3.11/dist-packages (from pydantic>=2.10->vllm) (0.7.0)\\n\",\n            \"Requirement already satisfied: pydantic-core==2.33.2 in /usr/local/lib/python3.11/dist-packages (from pydantic>=2.10->vllm) (2.33.2)\\n\",\n            \"Requirement already satisfied: typing-inspection>=0.4.0 in /usr/local/lib/python3.11/dist-packages (from pydantic>=2.10->vllm) (0.4.1)\\n\",\n            \"Requirement already satisfied: click>=7.0 in /usr/local/lib/python3.11/dist-packages (from ray!=2.44.*,>=2.43.0->ray[cgraph]!=2.44.*,>=2.43.0->vllm) (8.2.1)\\n\",\n            \"Requirement already satisfied: msgpack<2.0.0,>=1.0.0 in /usr/local/lib/python3.11/dist-packages (from ray!=2.44.*,>=2.43.0->ray[cgraph]!=2.44.*,>=2.43.0->vllm) (1.1.1)\\n\",\n            \"Requirement already satisfied: cupy-cuda12x in /usr/local/lib/python3.11/dist-packages (from ray[cgraph]!=2.44.*,>=2.43.0->vllm) (13.3.0)\\n\",\n            \"Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.11/dist-packages (from requests>=2.26.0->vllm) (3.4.2)\\n\",\n            \"Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.11/dist-packages (from requests>=2.26.0->vllm) (3.10)\\n\",\n            \"Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.11/dist-packages (from requests>=2.26.0->vllm) (2.5.0)\\n\",\n            \"Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.11/dist-packages (from requests>=2.26.0->vllm) (2025.8.3)\\n\",\n            \"Requirement already satisfied: aiohappyeyeballs>=2.5.0 in /usr/local/lib/python3.11/dist-packages (from aiohttp->vllm) (2.6.1)\\n\",\n            \"Requirement already satisfied: aiosignal>=1.4.0 in /usr/local/lib/python3.11/dist-packages (from aiohttp->vllm) (1.4.0)\\n\",\n            \"Requirement already satisfied: attrs>=17.3.0 in /usr/local/lib/python3.11/dist-packages (from aiohttp->vllm) (25.3.0)\\n\",\n            \"Requirement already satisfied: frozenlist>=1.1.1 in /usr/local/lib/python3.11/dist-packages (from aiohttp->vllm) (1.7.0)\\n\",\n            \"Requirement already satisfied: multidict<7.0,>=4.5 in /usr/local/lib/python3.11/dist-packages (from aiohttp->vllm) (6.6.3)\\n\",\n            \"Requirement already satisfied: propcache>=0.2.0 in /usr/local/lib/python3.11/dist-packages (from aiohttp->vllm) (0.3.2)\\n\",\n            \"Requirement already satisfied: yarl<2.0,>=1.17.0 in /usr/local/lib/python3.11/dist-packages (from aiohttp->vllm) (1.20.1)\\n\",\n            \"Collecting dnspython>=2.0.0 (from email-validator>=2.0.0->fastapi[standard]>=0.115.0->vllm)\\n\",\n            \"  Downloading dnspython-2.7.0-py3-none-any.whl.metadata (5.8 kB)\\n\",\n            \"Requirement already satisfied: typer>=0.15.1 in /usr/local/lib/python3.11/dist-packages (from fastapi-cli>=0.0.8->fastapi-cli[standard]>=0.0.8; extra == \\\"standard\\\"->fastapi[standard]>=0.115.0->vllm) (0.16.0)\\n\",\n            \"Collecting rich-toolkit>=0.14.8 (from fastapi-cli>=0.0.8->fastapi-cli[standard]>=0.0.8; extra == \\\"standard\\\"->fastapi[standard]>=0.115.0->vllm)\\n\",\n            \"  Downloading rich_toolkit-0.14.9-py3-none-any.whl.metadata (999 bytes)\\n\",\n            \"Collecting fastapi-cloud-cli>=0.1.1 (from fastapi-cli[standard]>=0.0.8; extra == \\\"standard\\\"->fastapi[standard]>=0.115.0->vllm)\\n\",\n            \"  Downloading fastapi_cloud_cli-0.1.5-py3-none-any.whl.metadata (3.2 kB)\\n\",\n            \"Requirement already satisfied: httpcore==1.* in /usr/local/lib/python3.11/dist-packages (from httpx>=0.23.0->fastapi[standard]>=0.115.0->vllm) (1.0.9)\\n\",\n            \"Requirement already satisfied: h11>=0.16 in /usr/local/lib/python3.11/dist-packages (from httpcore==1.*->httpx>=0.23.0->fastapi[standard]>=0.115.0->vllm) (0.16.0)\\n\",\n            \"Requirement already satisfied: MarkupSafe>=2.0 in /usr/local/lib/python3.11/dist-packages (from jinja2->torch==2.7.1->vllm) (3.0.2)\\n\",\n            \"Requirement already satisfied: jsonschema-specifications>=2023.03.6 in /usr/local/lib/python3.11/dist-packages (from jsonschema>=4.21.1->mistral_common>=1.8.2->mistral_common[audio,image]>=1.8.2->vllm) (2025.4.1)\\n\",\n            \"Requirement already satisfied: referencing>=0.28.4 in /usr/local/lib/python3.11/dist-packages (from jsonschema>=4.21.1->mistral_common>=1.8.2->mistral_common[audio,image]>=1.8.2->vllm) (0.36.2)\\n\",\n            \"Requirement already satisfied: rpds-py>=0.7.1 in /usr/local/lib/python3.11/dist-packages (from jsonschema>=4.21.1->mistral_common>=1.8.2->mistral_common[audio,image]>=1.8.2->vllm) (0.26.0)\\n\",\n            \"Collecting pycountry>=23 (from pydantic-extra-types[pycountry]>=2.10.5->mistral_common>=1.8.2->mistral_common[audio,image]>=1.8.2->vllm)\\n\",\n            \"  Downloading pycountry-24.6.1-py3-none-any.whl.metadata (12 kB)\\n\",\n            \"Requirement already satisfied: mpmath<1.4,>=1.1.0 in /usr/local/lib/python3.11/dist-packages (from sympy>=1.13.3->torch==2.7.1->vllm) (1.3.0)\\n\",\n            \"Collecting httptools>=0.6.3 (from uvicorn[standard]>=0.12.0; extra == \\\"standard\\\"->fastapi[standard]>=0.115.0->vllm)\\n\",\n            \"  Downloading httptools-0.6.4-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (3.6 kB)\\n\",\n            \"Collecting python-dotenv>=0.13 (from uvicorn[standard]>=0.12.0; extra == \\\"standard\\\"->fastapi[standard]>=0.115.0->vllm)\\n\",\n            \"  Downloading python_dotenv-1.1.1-py3-none-any.whl.metadata (24 kB)\\n\",\n            \"Collecting uvloop>=0.15.1 (from uvicorn[standard]>=0.12.0; extra == \\\"standard\\\"->fastapi[standard]>=0.115.0->vllm)\\n\",\n            \"  Downloading uvloop-0.21.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (4.9 kB)\\n\",\n            \"Requirement already satisfied: websockets>=10.4 in /usr/local/lib/python3.11/dist-packages (from uvicorn[standard]>=0.12.0; extra == \\\"standard\\\"->fastapi[standard]>=0.115.0->vllm) (15.0.1)\\n\",\n            \"Requirement already satisfied: fastrlock>=0.5 in /usr/local/lib/python3.11/dist-packages (from cupy-cuda12x->ray[cgraph]!=2.44.*,>=2.43.0->vllm) (0.8.3)\\n\",\n            \"Requirement already satisfied: soundfile>=0.12.1 in /usr/local/lib/python3.11/dist-packages (from mistral_common>=1.8.2->mistral_common[audio,image]>=1.8.2->vllm) (0.13.1)\\n\",\n            \"Requirement already satisfied: soxr>=0.5.0 in /usr/local/lib/python3.11/dist-packages (from mistral_common>=1.8.2->mistral_common[audio,image]>=1.8.2->vllm) (0.5.0.post1)\\n\",\n            \"Collecting rignore>=0.5.1 (from fastapi-cloud-cli>=0.1.1->fastapi-cli[standard]>=0.0.8; extra == \\\"standard\\\"->fastapi[standard]>=0.115.0->vllm)\\n\",\n            \"  Downloading rignore-0.6.4-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (3.8 kB)\\n\",\n            \"Requirement already satisfied: sentry-sdk>=2.20.0 in /usr/local/lib/python3.11/dist-packages (from fastapi-cloud-cli>=0.1.1->fastapi-cli[standard]>=0.0.8; extra == \\\"standard\\\"->fastapi[standard]>=0.115.0->vllm) (2.34.1)\\n\",\n            \"Requirement already satisfied: rich>=13.7.1 in /usr/local/lib/python3.11/dist-packages (from rich-toolkit>=0.14.8->fastapi-cli>=0.0.8->fastapi-cli[standard]>=0.0.8; extra == \\\"standard\\\"->fastapi[standard]>=0.115.0->vllm) (13.9.4)\\n\",\n            \"Requirement already satisfied: cffi>=1.0 in /usr/local/lib/python3.11/dist-packages (from soundfile>=0.12.1->mistral_common>=1.8.2->mistral_common[audio,image]>=1.8.2->vllm) (1.17.1)\\n\",\n            \"Requirement already satisfied: shellingham>=1.3.0 in /usr/local/lib/python3.11/dist-packages (from typer>=0.15.1->fastapi-cli>=0.0.8->fastapi-cli[standard]>=0.0.8; extra == \\\"standard\\\"->fastapi[standard]>=0.115.0->vllm) (1.5.4)\\n\",\n            \"Requirement already satisfied: pycparser in /usr/local/lib/python3.11/dist-packages (from cffi>=1.0->soundfile>=0.12.1->mistral_common>=1.8.2->mistral_common[audio,image]>=1.8.2->vllm) (2.22)\\n\",\n            \"Requirement already satisfied: markdown-it-py>=2.2.0 in /usr/local/lib/python3.11/dist-packages (from rich>=13.7.1->rich-toolkit>=0.14.8->fastapi-cli>=0.0.8->fastapi-cli[standard]>=0.0.8; extra == \\\"standard\\\"->fastapi[standard]>=0.115.0->vllm) (3.0.0)\\n\",\n            \"Requirement already satisfied: pygments<3.0.0,>=2.13.0 in /usr/local/lib/python3.11/dist-packages (from rich>=13.7.1->rich-toolkit>=0.14.8->fastapi-cli>=0.0.8->fastapi-cli[standard]>=0.0.8; extra == \\\"standard\\\"->fastapi[standard]>=0.115.0->vllm) (2.19.2)\\n\",\n            \"Requirement already satisfied: mdurl~=0.1 in /usr/local/lib/python3.11/dist-packages (from markdown-it-py>=2.2.0->rich>=13.7.1->rich-toolkit>=0.14.8->fastapi-cli>=0.0.8->fastapi-cli[standard]>=0.0.8; extra == \\\"standard\\\"->fastapi[standard]>=0.115.0->vllm) (0.1.2)\\n\",\n            \"Downloading vllm-0.10.0-cp38-abi3-manylinux1_x86_64.whl (386.6 MB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m386.6/386.6 MB\\u001b[0m \\u001b[31m2.9 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading compressed_tensors-0.10.2-py3-none-any.whl (169 kB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m169.0/169.0 kB\\u001b[0m \\u001b[31m14.4 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading depyf-0.19.0-py3-none-any.whl (39 kB)\\n\",\n            \"Downloading diskcache-5.6.3-py3-none-any.whl (45 kB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m45.5/45.5 kB\\u001b[0m \\u001b[31m5.3 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading lark-1.2.2-py3-none-any.whl (111 kB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m111.0/111.0 kB\\u001b[0m \\u001b[31m11.7 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading numba-0.61.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl (3.8 MB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m3.8/3.8 MB\\u001b[0m \\u001b[31m105.8 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading outlines_core-0.2.10-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (2.3 MB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m2.3/2.3 MB\\u001b[0m \\u001b[31m89.3 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading torch-2.7.1-cp311-cp311-manylinux_2_28_x86_64.whl (821.2 MB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m821.2/821.2 MB\\u001b[0m \\u001b[31m2.1 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading torchaudio-2.7.1-cp311-cp311-manylinux_2_28_x86_64.whl (3.5 MB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m3.5/3.5 MB\\u001b[0m \\u001b[31m111.6 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading torchvision-0.22.1-cp311-cp311-manylinux_2_28_x86_64.whl (7.5 MB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m7.5/7.5 MB\\u001b[0m \\u001b[31m133.7 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading xformers-0.0.31-cp39-abi3-manylinux_2_28_x86_64.whl (117.1 MB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m117.1/117.1 MB\\u001b[0m \\u001b[31m20.8 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading xgrammar-0.1.21-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (11.8 MB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m11.8/11.8 MB\\u001b[0m \\u001b[31m128.0 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading nvidia_cublas_cu12-12.6.4.1-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl (393.1 MB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m393.1/393.1 MB\\u001b[0m \\u001b[31m3.2 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading nvidia_cuda_cupti_cu12-12.6.80-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl (8.9 MB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m8.9/8.9 MB\\u001b[0m \\u001b[31m134.6 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading nvidia_cuda_nvrtc_cu12-12.6.77-py3-none-manylinux2014_x86_64.whl (23.7 MB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m23.7/23.7 MB\\u001b[0m \\u001b[31m99.7 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading nvidia_cuda_runtime_cu12-12.6.77-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl (897 kB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m897.7/897.7 kB\\u001b[0m \\u001b[31m52.8 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading nvidia_cudnn_cu12-9.5.1.17-py3-none-manylinux_2_28_x86_64.whl (571.0 MB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m571.0/571.0 MB\\u001b[0m \\u001b[31m2.3 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading nvidia_cufft_cu12-11.3.0.4-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl (200.2 MB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m200.2/200.2 MB\\u001b[0m \\u001b[31m6.2 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading nvidia_cufile_cu12-1.11.1.6-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl (1.1 MB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m1.1/1.1 MB\\u001b[0m \\u001b[31m65.8 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading nvidia_curand_cu12-10.3.7.77-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl (56.3 MB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m56.3/56.3 MB\\u001b[0m \\u001b[31m43.0 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading nvidia_cusolver_cu12-11.7.1.2-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl (158.2 MB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m158.2/158.2 MB\\u001b[0m \\u001b[31m5.9 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading nvidia_cusparse_cu12-12.5.4.2-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl (216.6 MB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m216.6/216.6 MB\\u001b[0m \\u001b[31m4.9 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading nvidia_nvjitlink_cu12-12.6.85-py3-none-manylinux2010_x86_64.manylinux_2_12_x86_64.whl (19.7 MB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m19.7/19.7 MB\\u001b[0m \\u001b[31m109.7 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading nvidia_nvtx_cu12-12.6.77-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl (89 kB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m89.3/89.3 kB\\u001b[0m \\u001b[31m9.5 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading triton-3.3.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl (155.7 MB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m155.7/155.7 MB\\u001b[0m \\u001b[31m6.2 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading transformers-4.55.0-py3-none-any.whl (11.3 MB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m11.3/11.3 MB\\u001b[0m \\u001b[31m141.6 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading gguf-0.17.1-py3-none-any.whl (96 kB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m96.2/96.2 kB\\u001b[0m \\u001b[31m9.2 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading llguidance-0.7.30-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (15.0 MB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m15.0/15.0 MB\\u001b[0m \\u001b[31m129.9 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading lm_format_enforcer-0.10.12-py3-none-any.whl (44 kB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m44.3/44.3 kB\\u001b[0m \\u001b[31m4.2 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading mistral_common-1.8.3-py3-none-any.whl (6.5 MB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m6.5/6.5 MB\\u001b[0m \\u001b[31m133.4 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading openai-1.90.0-py3-none-any.whl (734 kB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m734.6/734.6 kB\\u001b[0m \\u001b[31m53.9 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading prometheus_fastapi_instrumentator-7.1.0-py3-none-any.whl (19 kB)\\n\",\n            \"Downloading ray-2.48.0-cp311-cp311-manylinux2014_x86_64.whl (70.1 MB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m70.1/70.1 MB\\u001b[0m \\u001b[31m37.7 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading blake3-1.0.5-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (385 kB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m385.5/385.5 kB\\u001b[0m \\u001b[31m35.3 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading cbor2-5.6.5-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (249 kB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m249.2/249.2 kB\\u001b[0m \\u001b[31m25.2 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading msgspec-0.19.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (210 kB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m210.7/210.7 kB\\u001b[0m \\u001b[31m22.9 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hUsing cached ninja-1.11.1.4-py3-none-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (422 kB)\\n\",\n            \"Downloading partial_json_parser-0.2.1.1.post6-py3-none-any.whl (10 kB)\\n\",\n            \"Downloading pybase64-1.4.2-cp311-cp311-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl (71 kB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m71.4/71.4 kB\\u001b[0m \\u001b[31m7.9 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading python_json_logger-3.3.0-py3-none-any.whl (15 kB)\\n\",\n            \"Downloading watchfiles-1.1.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (453 kB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m453.1/453.1 kB\\u001b[0m \\u001b[31m41.8 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading email_validator-2.2.0-py3-none-any.whl (33 kB)\\n\",\n            \"Downloading fastapi_cli-0.0.8-py3-none-any.whl (10 kB)\\n\",\n            \"Downloading interegular-0.3.3-py37-none-any.whl (23 kB)\\n\",\n            \"Downloading llvmlite-0.44.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (42.4 MB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m42.4/42.4 MB\\u001b[0m \\u001b[31m61.1 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading pydantic_extra_types-2.10.5-py3-none-any.whl (38 kB)\\n\",\n            \"Downloading astor-0.8.1-py2.py3-none-any.whl (27 kB)\\n\",\n            \"Downloading dnspython-2.7.0-py3-none-any.whl (313 kB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m313.6/313.6 kB\\u001b[0m \\u001b[31m29.0 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading fastapi_cloud_cli-0.1.5-py3-none-any.whl (18 kB)\\n\",\n            \"Downloading httptools-0.6.4-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl (459 kB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m459.8/459.8 kB\\u001b[0m \\u001b[31m36.0 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading pycountry-24.6.1-py3-none-any.whl (6.3 MB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m6.3/6.3 MB\\u001b[0m \\u001b[31m127.7 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading python_dotenv-1.1.1-py3-none-any.whl (20 kB)\\n\",\n            \"Downloading rich_toolkit-0.14.9-py3-none-any.whl (25 kB)\\n\",\n            \"Downloading uvloop-0.21.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (4.0 MB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m4.0/4.0 MB\\u001b[0m \\u001b[31m114.2 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hDownloading rignore-0.6.4-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (950 kB)\\n\",\n            \"\\u001b[2K   \\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\u001b[0m \\u001b[32m950.6/950.6 kB\\u001b[0m \\u001b[31m60.8 MB/s\\u001b[0m eta \\u001b[36m0:00:00\\u001b[0m\\n\",\n            \"\\u001b[?25hInstalling collected packages: blake3, uvloop, triton, rignore, python-json-logger, python-dotenv, pycountry, pybase64, partial-json-parser, outlines_core, nvidia-nvtx-cu12, nvidia-nvjitlink-cu12, nvidia-curand-cu12, nvidia-cufile-cu12, nvidia-cuda-runtime-cu12, nvidia-cuda-nvrtc-cu12, nvidia-cuda-cupti-cu12, nvidia-cublas-cu12, ninja, msgspec, llvmlite, llguidance, lark, interegular, httptools, gguf, dnspython, diskcache, cbor2, astor, watchfiles, nvidia-cusparse-cu12, nvidia-cufft-cu12, nvidia-cudnn-cu12, numba, email-validator, depyf, rich-toolkit, pydantic-extra-types, prometheus-fastapi-instrumentator, openai, nvidia-cusolver-cu12, lm-format-enforcer, transformers, torch, ray, fastapi-cloud-cli, fastapi-cli, xgrammar, xformers, torchvision, torchaudio, mistral_common, compressed-tensors, vllm\\n\",\n            \"  Attempting uninstall: triton\\n\",\n            \"    Found existing installation: triton 3.3.0\\n\",\n            \"    Uninstalling triton-3.3.0:\\n\",\n            \"      Successfully uninstalled triton-3.3.0\\n\",\n            \"  Attempting uninstall: nvidia-nvtx-cu12\\n\",\n            \"    Found existing installation: nvidia-nvtx-cu12 12.8.55\\n\",\n            \"    Uninstalling nvidia-nvtx-cu12-12.8.55:\\n\",\n            \"      Successfully uninstalled nvidia-nvtx-cu12-12.8.55\\n\",\n            \"  Attempting uninstall: nvidia-nvjitlink-cu12\\n\",\n            \"    Found existing installation: nvidia-nvjitlink-cu12 12.8.61\\n\",\n            \"    Uninstalling nvidia-nvjitlink-cu12-12.8.61:\\n\",\n            \"      Successfully uninstalled nvidia-nvjitlink-cu12-12.8.61\\n\",\n            \"  Attempting uninstall: nvidia-curand-cu12\\n\",\n            \"    Found existing installation: nvidia-curand-cu12 10.3.9.55\\n\",\n            \"    Uninstalling nvidia-curand-cu12-10.3.9.55:\\n\",\n            \"      Successfully uninstalled nvidia-curand-cu12-10.3.9.55\\n\",\n            \"  Attempting uninstall: nvidia-cufile-cu12\\n\",\n            \"    Found existing installation: nvidia-cufile-cu12 1.13.0.11\\n\",\n            \"    Uninstalling nvidia-cufile-cu12-1.13.0.11:\\n\",\n            \"      Successfully uninstalled nvidia-cufile-cu12-1.13.0.11\\n\",\n            \"  Attempting uninstall: nvidia-cuda-runtime-cu12\\n\",\n            \"    Found existing installation: nvidia-cuda-runtime-cu12 12.8.57\\n\",\n            \"    Uninstalling nvidia-cuda-runtime-cu12-12.8.57:\\n\",\n            \"      Successfully uninstalled nvidia-cuda-runtime-cu12-12.8.57\\n\",\n            \"  Attempting uninstall: nvidia-cuda-nvrtc-cu12\\n\",\n            \"    Found existing installation: nvidia-cuda-nvrtc-cu12 12.8.61\\n\",\n            \"    Uninstalling nvidia-cuda-nvrtc-cu12-12.8.61:\\n\",\n            \"      Successfully uninstalled nvidia-cuda-nvrtc-cu12-12.8.61\\n\",\n            \"  Attempting uninstall: nvidia-cuda-cupti-cu12\\n\",\n            \"    Found existing installation: nvidia-cuda-cupti-cu12 12.8.57\\n\",\n            \"    Uninstalling nvidia-cuda-cupti-cu12-12.8.57:\\n\",\n            \"      Successfully uninstalled nvidia-cuda-cupti-cu12-12.8.57\\n\",\n            \"  Attempting uninstall: nvidia-cublas-cu12\\n\",\n            \"    Found existing installation: nvidia-cublas-cu12 12.8.3.14\\n\",\n            \"    Uninstalling nvidia-cublas-cu12-12.8.3.14:\\n\",\n            \"      Successfully uninstalled nvidia-cublas-cu12-12.8.3.14\\n\",\n            \"  Attempting uninstall: llvmlite\\n\",\n            \"    Found existing installation: llvmlite 0.43.0\\n\",\n            \"    Uninstalling llvmlite-0.43.0:\\n\",\n            \"      Successfully uninstalled llvmlite-0.43.0\\n\",\n            \"  Attempting uninstall: nvidia-cusparse-cu12\\n\",\n            \"    Found existing installation: nvidia-cusparse-cu12 12.5.7.53\\n\",\n            \"    Uninstalling nvidia-cusparse-cu12-12.5.7.53:\\n\",\n            \"      Successfully uninstalled nvidia-cusparse-cu12-12.5.7.53\\n\",\n            \"  Attempting uninstall: nvidia-cufft-cu12\\n\",\n            \"    Found existing installation: nvidia-cufft-cu12 11.3.3.41\\n\",\n            \"    Uninstalling nvidia-cufft-cu12-11.3.3.41:\\n\",\n            \"      Successfully uninstalled nvidia-cufft-cu12-11.3.3.41\\n\",\n            \"  Attempting uninstall: nvidia-cudnn-cu12\\n\",\n            \"    Found existing installation: nvidia-cudnn-cu12 9.7.1.26\\n\",\n            \"    Uninstalling nvidia-cudnn-cu12-9.7.1.26:\\n\",\n            \"      Successfully uninstalled nvidia-cudnn-cu12-9.7.1.26\\n\",\n            \"  Attempting uninstall: numba\\n\",\n            \"    Found existing installation: numba 0.60.0\\n\",\n            \"    Uninstalling numba-0.60.0:\\n\",\n            \"      Successfully uninstalled numba-0.60.0\\n\",\n            \"  Attempting uninstall: openai\\n\",\n            \"    Found existing installation: openai 1.98.0\\n\",\n            \"    Uninstalling openai-1.98.0:\\n\",\n            \"      Successfully uninstalled openai-1.98.0\\n\",\n            \"  Attempting uninstall: nvidia-cusolver-cu12\\n\",\n            \"    Found existing installation: nvidia-cusolver-cu12 11.7.2.55\\n\",\n            \"    Uninstalling nvidia-cusolver-cu12-11.7.2.55:\\n\",\n            \"      Successfully uninstalled nvidia-cusolver-cu12-11.7.2.55\\n\",\n            \"  Attempting uninstall: transformers\\n\",\n            \"    Found existing installation: transformers 4.51.3\\n\",\n            \"    Uninstalling transformers-4.51.3:\\n\",\n            \"      Successfully uninstalled transformers-4.51.3\\n\",\n            \"  Attempting uninstall: torch\\n\",\n            \"    Found existing installation: torch 2.7.0+cu128\\n\",\n            \"    Uninstalling torch-2.7.0+cu128:\\n\",\n            \"      Successfully uninstalled torch-2.7.0+cu128\\n\",\n            \"  Attempting uninstall: torchvision\\n\",\n            \"    Found existing installation: torchvision 0.22.0+cu128\\n\",\n            \"    Uninstalling torchvision-0.22.0+cu128:\\n\",\n            \"      Successfully uninstalled torchvision-0.22.0+cu128\\n\",\n            \"  Attempting uninstall: torchaudio\\n\",\n            \"    Found existing installation: torchaudio 2.7.0+cu128\\n\",\n            \"    Uninstalling torchaudio-2.7.0+cu128:\\n\",\n            \"      Successfully uninstalled torchaudio-2.7.0+cu128\\n\",\n            \"\\u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\\n\",\n            \"fastai 2.7.19 requires torch<2.7,>=1.10, but you have torch 2.7.1 which is incompatible.\\n\",\n            \"dots-ocr 1.0 requires transformers==4.51.3, but you have transformers 4.55.0 which is incompatible.\\u001b[0m\\u001b[31m\\n\",\n            \"\\u001b[0mSuccessfully installed astor-0.8.1 blake3-1.0.5 cbor2-5.6.5 compressed-tensors-0.10.2 depyf-0.19.0 diskcache-5.6.3 dnspython-2.7.0 email-validator-2.2.0 fastapi-cli-0.0.8 fastapi-cloud-cli-0.1.5 gguf-0.17.1 httptools-0.6.4 interegular-0.3.3 lark-1.2.2 llguidance-0.7.30 llvmlite-0.44.0 lm-format-enforcer-0.10.12 mistral_common-1.8.3 msgspec-0.19.0 ninja-1.11.1.4 numba-0.61.2 nvidia-cublas-cu12-12.6.4.1 nvidia-cuda-cupti-cu12-12.6.80 nvidia-cuda-nvrtc-cu12-12.6.77 nvidia-cuda-runtime-cu12-12.6.77 nvidia-cudnn-cu12-9.5.1.17 nvidia-cufft-cu12-11.3.0.4 nvidia-cufile-cu12-1.11.1.6 nvidia-curand-cu12-10.3.7.77 nvidia-cusolver-cu12-11.7.1.2 nvidia-cusparse-cu12-12.5.4.2 nvidia-nvjitlink-cu12-12.6.85 nvidia-nvtx-cu12-12.6.77 openai-1.90.0 outlines_core-0.2.10 partial-json-parser-0.2.1.1.post6 prometheus-fastapi-instrumentator-7.1.0 pybase64-1.4.2 pycountry-24.6.1 pydantic-extra-types-2.10.5 python-dotenv-1.1.1 python-json-logger-3.3.0 ray-2.48.0 rich-toolkit-0.14.9 rignore-0.6.4 torch-2.7.1 torchaudio-2.7.1 torchvision-0.22.1 transformers-4.55.0 triton-3.3.1 uvloop-0.21.0 vllm-0.10.0 watchfiles-1.1.0 xformers-0.0.31 xgrammar-0.1.21\\n\",\n            \"nohup: failed to run command 'CUDA_VISIBLE_DEVICES=0': No such file or directory\\n\"\n          ]\n        }\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"source\": [\n        \"from pyngrok import ngrok\\n\",\n        \"public_url = ngrok.connect(8000, bind_tls=True)  # Adjust port if needed\\n\",\n        \"print(\\\"Public URL:\\\", public_url)\"\n      ],\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"iNPRVOjmUxJb\",\n        \"outputId\": \"66388365-796e-4489-9285-17ad6ccad0ed\"\n      },\n      \"execution_count\": null,\n      \"outputs\": [\n        {\n          \"output_type\": \"stream\",\n          \"name\": \"stdout\",\n          \"text\": [\n            \"Public URL: NgrokTunnel: \\\"https://988ecbb0776c.ngrok-free.app\\\" -> \\\"http://localhost:8000\\\"\\n\"\n          ]\n        }\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"source\": [\n        \"!CUDA_VISIBLE_DEVICES=0 vllm serve ./weights/DotsOCR --tensor-parallel-size 1 --gpu-memory-utilization 0.95  --chat-template-content-format string --served-model-name model --trust-remote-code\"\n      ],\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"QbYEd_foT2QY\",\n        \"outputId\": \"6c980927-042e-498a-e013-a575d4cf5132\"\n      },\n      \"execution_count\": null,\n      \"outputs\": [\n        {\n          \"output_type\": \"stream\",\n          \"name\": \"stdout\",\n          \"text\": [\n            \"2025-08-07 20:57:52.107021: I tensorflow/core/util/port.cc:153] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`.\\n\",\n            \"2025-08-07 20:57:52.125111: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:467] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered\\n\",\n            \"WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\\n\",\n            \"E0000 00:00:1754600272.146783   10516 cuda_dnn.cc:8579] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered\\n\",\n            \"E0000 00:00:1754600272.153513   10516 cuda_blas.cc:1407] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered\\n\",\n            \"W0000 00:00:1754600272.170115   10516 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.\\n\",\n            \"W0000 00:00:1754600272.170145   10516 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.\\n\",\n            \"W0000 00:00:1754600272.170148   10516 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.\\n\",\n            \"W0000 00:00:1754600272.170151   10516 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.\\n\",\n            \"2025-08-07 20:57:52.174913: I tensorflow/core/platform/cpu_feature_guard.cc:210] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.\\n\",\n            \"To enable the following instructions: AVX2 AVX512F AVX512_VNNI FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.\\n\",\n            \"INFO 08-07 20:57:57 [__init__.py:235] Automatically detected platform cuda.\\n\",\n            \"INFO 08-07 20:58:01 [api_server.py:1755] vLLM API server version 0.10.0\\n\",\n            \"INFO 08-07 20:58:01 [cli_args.py:261] non-default args: {'model_tag': './weights/DotsOCR', 'chat_template_content_format': 'string', 'model': './weights/DotsOCR', 'trust_remote_code': True, 'served_model_name': ['model'], 'gpu_memory_utilization': 0.95}\\n\",\n            \"INFO 08-07 20:58:01 [config.py:1604] Using max model len 131072\\n\",\n            \"INFO 08-07 20:58:01 [config.py:2434] Chunked prefill is enabled with max_num_batched_tokens=2048.\\n\",\n            \"2025-08-07 20:58:05.950037: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:467] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered\\n\",\n            \"WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\\n\",\n            \"E0000 00:00:1754600285.970806   10621 cuda_dnn.cc:8579] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered\\n\",\n            \"E0000 00:00:1754600285.977110   10621 cuda_blas.cc:1407] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered\\n\",\n            \"W0000 00:00:1754600285.992571   10621 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.\\n\",\n            \"W0000 00:00:1754600285.992601   10621 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.\\n\",\n            \"W0000 00:00:1754600285.992604   10621 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.\\n\",\n            \"W0000 00:00:1754600285.992606   10621 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.\\n\",\n            \"INFO 08-07 20:58:11 [__init__.py:235] Automatically detected platform cuda.\\n\",\n            \"INFO 08-07 20:58:14 [core.py:572] Waiting for init message from front-end.\\n\",\n            \"INFO 08-07 20:58:14 [core.py:71] Initializing a V1 LLM engine (v0.10.0) with config: model='./weights/DotsOCR', speculative_config=None, tokenizer='./weights/DotsOCR', skip_tokenizer_init=False, tokenizer_mode=auto, revision=None, override_neuron_config={}, tokenizer_revision=None, trust_remote_code=True, dtype=torch.bfloat16, max_seq_len=131072, download_dir=None, load_format=LoadFormat.AUTO, tensor_parallel_size=1, pipeline_parallel_size=1, disable_custom_all_reduce=False, quantization=None, enforce_eager=False, kv_cache_dtype=auto,  device_config=cuda, decoding_config=DecodingConfig(backend='auto', disable_fallback=False, disable_any_whitespace=False, disable_additional_properties=False, reasoning_backend=''), observability_config=ObservabilityConfig(show_hidden_metrics_for_version=None, otlp_traces_endpoint=None, collect_detailed_traces=None), seed=0, served_model_name=model, num_scheduler_steps=1, multi_step_stream_outputs=True, enable_prefix_caching=True, chunked_prefill_enabled=True, use_async_output_proc=True, pooler_config=None, compilation_config={\\\"level\\\":3,\\\"debug_dump_path\\\":\\\"\\\",\\\"cache_dir\\\":\\\"\\\",\\\"backend\\\":\\\"\\\",\\\"custom_ops\\\":[],\\\"splitting_ops\\\":[\\\"vllm.unified_attention\\\",\\\"vllm.unified_attention_with_output\\\",\\\"vllm.mamba_mixer2\\\"],\\\"use_inductor\\\":true,\\\"compile_sizes\\\":[],\\\"inductor_compile_config\\\":{\\\"enable_auto_functionalized_v2\\\":false},\\\"inductor_passes\\\":{},\\\"use_cudagraph\\\":true,\\\"cudagraph_num_of_warmups\\\":1,\\\"cudagraph_capture_sizes\\\":[512,504,496,488,480,472,464,456,448,440,432,424,416,408,400,392,384,376,368,360,352,344,336,328,320,312,304,296,288,280,272,264,256,248,240,232,224,216,208,200,192,184,176,168,160,152,144,136,128,120,112,104,96,88,80,72,64,56,48,40,32,24,16,8,4,2,1],\\\"cudagraph_copy_inputs\\\":false,\\\"full_cuda_graph\\\":false,\\\"max_capture_size\\\":512,\\\"local_cache_dir\\\":null}\\n\",\n            \"INFO 08-07 20:58:15 [parallel_state.py:1102] rank 0 in world size 1 is assigned as DP rank 0, PP rank 0, TP rank 0, EP rank 0\\n\",\n            \"WARNING 08-07 20:58:15 [topk_topp_sampler.py:59] FlashInfer is not available. Falling back to the PyTorch-native implementation of top-p & top-k sampling. For the best performance, please install FlashInfer.\\n\",\n            \"INFO 08-07 20:58:15 [gpu_model_runner.py:1843] Starting to load model ./weights/DotsOCR...\\n\",\n            \"INFO 08-07 20:58:15 [gpu_model_runner.py:1875] Loading model from scratch...\\n\",\n            \"INFO 08-07 20:58:16 [cuda.py:290] Using Flash Attention backend on V1 engine.\\n\",\n            \"Loading safetensors checkpoint shards: 100% 2/2 [00:01<00:00,  1.06it/s]\\n\",\n            \"INFO 08-07 20:58:18 [default_loader.py:262] Loading weights took 1.99 seconds\\n\",\n            \"INFO 08-07 20:58:19 [gpu_model_runner.py:1892] Model loading took 5.7174 GiB and 2.253556 seconds\\n\",\n            \"INFO 08-07 20:58:19 [gpu_model_runner.py:2380] Encoder cache will be initialized with a budget of 14400 tokens, and profiled with 1 image items of the maximum feature size.\\n\",\n            \"The image processor of type `Qwen2VLImageProcessor` is now loaded as a fast processor by default, even if the model checkpoint was saved with a slow processor. This is a breaking change and may produce slightly different outputs. To continue using the slow processor, instantiate this class with `use_fast=False`. Note that this behavior will be extended to all models in a future release.\\n\",\n            \"You have video processor config saved in `preprocessor.json` file which is deprecated. Video processor configs should be saved in their own `video_preprocessor.json` file. You can rename the file or load and save the processor back which renames it automatically. Loading from `preprocessor.json` will be removed in v5.0.\\n\",\n            \"INFO 08-07 20:58:49 [backends.py:530] Using cache directory: /root/.cache/vllm/torch_compile_cache/f40f68567f/rank_0_0/backbone for vLLM's torch.compile\\n\",\n            \"INFO 08-07 20:58:49 [backends.py:541] Dynamo bytecode transform time: 8.76 s\\n\",\n            \"INFO 08-07 20:58:56 [backends.py:161] Directly load the compiled graph(s) for dynamic shape from the cache, took 6.316 s\\n\",\n            \"INFO 08-07 20:58:56 [monitor.py:34] torch.compile takes 8.76 s in total\\n\",\n            \"INFO 08-07 20:58:58 [gpu_worker.py:255] Available KV cache memory: 12.20 GiB\\n\",\n            \"INFO 08-07 20:58:58 [kv_cache_utils.py:833] GPU KV cache size: 456,816 tokens\\n\",\n            \"INFO 08-07 20:58:58 [kv_cache_utils.py:837] Maximum concurrency for 131,072 tokens per request: 3.49x\\n\",\n            \"Capturing CUDA graph shapes: 100% 67/67 [00:02<00:00, 24.17it/s]\\n\",\n            \"INFO 08-07 20:59:01 [gpu_model_runner.py:2485] Graph capturing finished in 3 secs, took 0.44 GiB\\n\",\n            \"INFO 08-07 20:59:01 [core.py:193] init engine (profile, create kv cache, warmup model) took 42.75 seconds\\n\",\n            \"INFO 08-07 20:59:02 [loggers.py:141] Engine 000: vllm cache_config_info with initialization after num_gpu_blocks is: 28551\\n\",\n            \"INFO 08-07 20:59:02 [api_server.py:1818] Starting vLLM API server 0 on http://0.0.0.0:8000\\n\",\n            \"INFO 08-07 20:59:02 [launcher.py:29] Available routes are:\\n\",\n            \"INFO 08-07 20:59:02 [launcher.py:37] Route: /openapi.json, Methods: HEAD, GET\\n\",\n            \"INFO 08-07 20:59:02 [launcher.py:37] Route: /docs, Methods: HEAD, GET\\n\",\n            \"INFO 08-07 20:59:02 [launcher.py:37] Route: /docs/oauth2-redirect, Methods: HEAD, GET\\n\",\n            \"INFO 08-07 20:59:02 [launcher.py:37] Route: /redoc, Methods: HEAD, GET\\n\",\n            \"INFO 08-07 20:59:02 [launcher.py:37] Route: /health, Methods: GET\\n\",\n            \"INFO 08-07 20:59:02 [launcher.py:37] Route: /load, Methods: GET\\n\",\n            \"INFO 08-07 20:59:02 [launcher.py:37] Route: /ping, Methods: POST\\n\",\n            \"INFO 08-07 20:59:02 [launcher.py:37] Route: /ping, Methods: GET\\n\",\n            \"INFO 08-07 20:59:02 [launcher.py:37] Route: /tokenize, Methods: POST\\n\",\n            \"INFO 08-07 20:59:02 [launcher.py:37] Route: /detokenize, Methods: POST\\n\",\n            \"INFO 08-07 20:59:02 [launcher.py:37] Route: /v1/models, Methods: GET\\n\",\n            \"INFO 08-07 20:59:02 [launcher.py:37] Route: /version, Methods: GET\\n\",\n            \"INFO 08-07 20:59:02 [launcher.py:37] Route: /v1/responses, Methods: POST\\n\",\n            \"INFO 08-07 20:59:02 [launcher.py:37] Route: /v1/responses/{response_id}, Methods: GET\\n\",\n            \"INFO 08-07 20:59:02 [launcher.py:37] Route: /v1/responses/{response_id}/cancel, Methods: POST\\n\",\n            \"INFO 08-07 20:59:02 [launcher.py:37] Route: /v1/chat/completions, Methods: POST\\n\",\n            \"INFO 08-07 20:59:02 [launcher.py:37] Route: /v1/completions, Methods: POST\\n\",\n            \"INFO 08-07 20:59:02 [launcher.py:37] Route: /v1/embeddings, Methods: POST\\n\",\n            \"INFO 08-07 20:59:02 [launcher.py:37] Route: /pooling, Methods: POST\\n\",\n            \"INFO 08-07 20:59:02 [launcher.py:37] Route: /classify, Methods: POST\\n\",\n            \"INFO 08-07 20:59:02 [launcher.py:37] Route: /score, Methods: POST\\n\",\n            \"INFO 08-07 20:59:02 [launcher.py:37] Route: /v1/score, Methods: POST\\n\",\n            \"INFO 08-07 20:59:02 [launcher.py:37] Route: /v1/audio/transcriptions, Methods: POST\\n\",\n            \"INFO 08-07 20:59:02 [launcher.py:37] Route: /v1/audio/translations, Methods: POST\\n\",\n            \"INFO 08-07 20:59:02 [launcher.py:37] Route: /rerank, Methods: POST\\n\",\n            \"INFO 08-07 20:59:02 [launcher.py:37] Route: /v1/rerank, Methods: POST\\n\",\n            \"INFO 08-07 20:59:02 [launcher.py:37] Route: /v2/rerank, Methods: POST\\n\",\n            \"INFO 08-07 20:59:02 [launcher.py:37] Route: /scale_elastic_ep, Methods: POST\\n\",\n            \"INFO 08-07 20:59:02 [launcher.py:37] Route: /is_scaling_elastic_ep, Methods: POST\\n\",\n            \"INFO 08-07 20:59:02 [launcher.py:37] Route: /invocations, Methods: POST\\n\",\n            \"INFO 08-07 20:59:02 [launcher.py:37] Route: /metrics, Methods: GET\\n\",\n            \"\\u001b[32mINFO\\u001b[0m:     Started server process [\\u001b[36m10516\\u001b[0m]\\n\",\n            \"\\u001b[32mINFO\\u001b[0m:     Waiting for application startup.\\n\",\n            \"\\u001b[32mINFO\\u001b[0m:     Application startup complete.\\n\",\n            \"\\u001b[32mINFO\\u001b[0m:     2001:818:c61b:b000:457e:d747:75e4:7263:0 - \\\"\\u001b[1mGET / HTTP/1.1\\u001b[0m\\\" \\u001b[31m404 Not Found\\u001b[0m\\n\",\n            \"\\u001b[32mINFO\\u001b[0m:     2001:818:c61b:b000:457e:d747:75e4:7263:0 - \\\"\\u001b[1mGET /favicon.ico HTTP/1.1\\u001b[0m\\\" \\u001b[31m404 Not Found\\u001b[0m\\n\",\n            \"INFO 08-07 21:00:28 [launcher.py:80] Shutting down FastAPI HTTP server.\\n\",\n            \"[rank0]:[W807 21:00:29.608158947 ProcessGroupNCCL.cpp:1479] Warning: WARNING: destroy_process_group() was not called before program exit, which can leak resources. For more info, please see https://pytorch.org/docs/stable/distributed.html#shutdown (function operator())\\n\",\n            \"\\u001b[32mINFO\\u001b[0m:     Shutting down\\n\",\n            \"\\u001b[31mERROR\\u001b[0m:    Traceback (most recent call last):\\n\",\n            \"  File \\\"/usr/local/lib/python3.11/dist-packages/starlette/routing.py\\\", line 701, in lifespan\\n\",\n            \"    await receive()\\n\",\n            \"  File \\\"/usr/local/lib/python3.11/dist-packages/uvicorn/lifespan/on.py\\\", line 137, in receive\\n\",\n            \"    return await self.receive_queue.get()\\n\",\n            \"           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\\n\",\n            \"  File \\\"/usr/lib/python3.11/asyncio/queues.py\\\", line 158, in get\\n\",\n            \"    await getter\\n\",\n            \"asyncio.exceptions.CancelledError\\n\",\n            \"\\n\"\n          ]\n        }\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"source\": [],\n      \"metadata\": {\n        \"id\": \"mbOe-1sxU1-r\"\n      },\n      \"execution_count\": null,\n      \"outputs\": []\n    }\n  ]\n}\n"
  },
  {
    "path": "demo/demo_gradio.py",
    "content": "\"\"\"\nLayout Inference Web Application with Gradio\n\nA Gradio-based layout inference tool that supports image uploads and multiple backend inference engines.\nIt adopts a reference-style interface design while preserving the original inference logic.\n\"\"\"\n\nimport gradio as gr\nimport json\nimport os\nimport io\nimport tempfile\nimport base64\nimport zipfile\nimport uuid\nimport re\nfrom pathlib import Path\nfrom PIL import Image\nimport requests\nimport shutil # Import shutil for cleanup\n\n# Local tool imports\nfrom dots_ocr.utils import dict_promptmode_to_prompt\nfrom dots_ocr.utils.consts import MIN_PIXELS, MAX_PIXELS\nfrom dots_ocr.utils.demo_utils.display import read_image\nfrom dots_ocr.utils.doc_utils import load_images_from_pdf\n\n# Add DotsOCRParser import\nfrom dots_ocr.parser import DotsOCRParser\n\n\n# ==================== Configuration ====================\nDEFAULT_CONFIG = {\n    'ip': \"127.0.0.1\",\n    'port_vllm': 8000,\n    'min_pixels': MIN_PIXELS,\n    'max_pixels': MAX_PIXELS,\n    'test_images_dir': \"./assets/showcase_origin\",\n}\n\n# ==================== Global Variables ====================\n# Store current configuration\ncurrent_config = DEFAULT_CONFIG.copy()\n\n# Create DotsOCRParser instance\ndots_parser = DotsOCRParser(\n    ip=DEFAULT_CONFIG['ip'],\n    port=DEFAULT_CONFIG['port_vllm'],\n    dpi=200,\n    min_pixels=DEFAULT_CONFIG['min_pixels'],\n    max_pixels=DEFAULT_CONFIG['max_pixels']\n)\n\ndef get_initial_session_state():\n    return {\n        'processing_results': {\n            'original_image': None,\n            'processed_image': None,\n            'layout_result': None,\n            'markdown_content': None,\n            'cells_data': None,\n            'temp_dir': None,\n            'session_id': None,\n            'result_paths': None,\n            'pdf_results': None\n        },\n        'pdf_cache': {\n            \"images\": [],\n            \"current_page\": 0,\n            \"total_pages\": 0,\n            \"file_type\": None,\n            \"is_parsed\": False,\n            \"results\": []\n        }\n    }\n\ndef read_image_v2(img):\n    \"\"\"Reads an image, supports URLs and local paths\"\"\"\n    if isinstance(img, str) and img.startswith((\"http://\", \"https://\")):\n        with requests.get(img, stream=True) as response:\n            response.raise_for_status()\n            img = Image.open(io.BytesIO(response.content))\n    elif isinstance(img, str):\n        img, _, _ = read_image(img, use_native=True)\n    elif isinstance(img, Image.Image):\n        pass\n    else:\n        raise ValueError(f\"Invalid image type: {type(img)}\")\n    return img\n\ndef load_file_for_preview(file_path, session_state):\n    \"\"\"Loads a file for preview, supports PDF and image files\"\"\"\n    pdf_cache = session_state['pdf_cache']\n    \n    if not file_path or not os.path.exists(file_path):\n        return None, \"<div id='page_info_box'>0 / 0</div>\", session_state\n    \n    file_ext = os.path.splitext(file_path)[1].lower()\n    \n    try:\n        if file_ext == '.pdf':\n            pages = load_images_from_pdf(file_path)\n            pdf_cache[\"file_type\"] = \"pdf\"\n        elif file_ext in ['.jpg', '.jpeg', '.png']:\n            image = Image.open(file_path)\n            pages = [image]\n            pdf_cache[\"file_type\"] = \"image\"\n        else:\n            return None, \"<div id='page_info_box'>Unsupported file format</div>\", session_state\n    except Exception as e:\n        return None, f\"<div id='page_info_box'>PDF loading failed: {str(e)}</div>\", session_state\n    \n    pdf_cache[\"images\"] = pages\n    pdf_cache[\"current_page\"] = 0\n    pdf_cache[\"total_pages\"] = len(pages)\n    pdf_cache[\"is_parsed\"] = False\n    pdf_cache[\"results\"] = []\n    \n    return pages[0], f\"<div id='page_info_box'>1 / {len(pages)}</div>\", session_state\n\ndef turn_page(direction, session_state):\n    \"\"\"Page turning function\"\"\"\n    pdf_cache = session_state['pdf_cache']\n    \n    if not pdf_cache[\"images\"]:\n        return None, \"<div id='page_info_box'>0 / 0</div>\", \"\", session_state\n\n    if direction == \"prev\":\n        pdf_cache[\"current_page\"] = max(0, pdf_cache[\"current_page\"] - 1)\n    elif direction == \"next\":\n        pdf_cache[\"current_page\"] = min(pdf_cache[\"total_pages\"] - 1, pdf_cache[\"current_page\"] + 1)\n\n    index = pdf_cache[\"current_page\"]\n    current_image = pdf_cache[\"images\"][index]  # Use the original image by default\n    page_info = f\"<div id='page_info_box'>{index + 1} / {pdf_cache['total_pages']}</div>\"\n    \n    current_json = \"\"\n    if pdf_cache[\"is_parsed\"] and index < len(pdf_cache[\"results\"]):\n        result = pdf_cache[\"results\"][index]\n        if 'cells_data' in result and result['cells_data']:\n            try:\n                current_json = json.dumps(result['cells_data'], ensure_ascii=False, indent=2)\n            except:\n                current_json = str(result.get('cells_data', ''))\n        if 'layout_image' in result and result['layout_image']:\n            current_image = result['layout_image']\n    \n    return current_image, page_info, current_json, session_state\n\ndef get_test_images():\n    \"\"\"Gets the list of test images\"\"\"\n    test_images = []\n    test_dir = current_config['test_images_dir']\n    if os.path.exists(test_dir):\n        test_images = [os.path.join(test_dir, name) for name in os.listdir(test_dir) \n                      if name.lower().endswith(('.png', '.jpg', '.jpeg', '.pdf'))]\n    return test_images\n\ndef create_temp_session_dir():\n    \"\"\"Creates a unique temporary directory for each processing request\"\"\"\n    session_id = uuid.uuid4().hex[:8]\n    temp_dir = os.path.join(tempfile.gettempdir(), f\"dots_ocr_demo_{session_id}\")\n    os.makedirs(temp_dir, exist_ok=True)\n    return temp_dir, session_id\n\ndef parse_image_with_high_level_api(parser, image, prompt_mode, fitz_preprocess=False):\n    \"\"\"\n    Processes using the high-level API parse_image from DotsOCRParser\n    \"\"\"\n    # Create a temporary session directory\n    temp_dir, session_id = create_temp_session_dir()\n    \n    try:\n        # Save the PIL Image as a temporary file\n        temp_image_path = os.path.join(temp_dir, f\"input_{session_id}.png\")\n        image.save(temp_image_path, \"PNG\")\n        \n        # Use the high-level API parse_image\n        filename = f\"demo_{session_id}\"\n        results = parser.parse_image(\n            input_path=image,\n            filename=filename, \n            prompt_mode=prompt_mode,\n            save_dir=temp_dir,\n            fitz_preprocess=fitz_preprocess\n        )\n        \n        # Parse the results\n        if not results:\n            raise ValueError(\"No results returned from parser\")\n        \n        result = results[0]  # parse_image returns a list with a single result\n        \n        layout_image = None\n        if 'layout_image_path' in result and os.path.exists(result['layout_image_path']):\n            layout_image = Image.open(result['layout_image_path'])\n        \n        cells_data = None\n        if 'layout_info_path' in result and os.path.exists(result['layout_info_path']):\n            with open(result['layout_info_path'], 'r', encoding='utf-8') as f:\n                cells_data = json.load(f)\n        \n        md_content = None\n        if 'md_content_path' in result and os.path.exists(result['md_content_path']):\n            with open(result['md_content_path'], 'r', encoding='utf-8') as f:\n                md_content = f.read()\n        \n        return {\n            'layout_image': layout_image,\n            'cells_data': cells_data,\n            'md_content': md_content,\n            'filtered': result.get('filtered', False),\n            'temp_dir': temp_dir,\n            'session_id': session_id,\n            'result_paths': result,\n            'input_width': result.get('input_width', 0),\n            'input_height': result.get('input_height', 0),\n        }\n    except Exception as e:\n        if os.path.exists(temp_dir):\n            shutil.rmtree(temp_dir, ignore_errors=True)\n        raise e\n\ndef parse_pdf_with_high_level_api(parser, pdf_path, prompt_mode):\n    \"\"\"\n    Processes using the high-level API parse_pdf from DotsOCRParser\n    \"\"\"\n    # Create a temporary session directory\n    temp_dir, session_id = create_temp_session_dir()\n    \n    try:\n        # Use the high-level API parse_pdf\n        filename = f\"demo_{session_id}\"\n        results = parser.parse_pdf(\n            input_path=pdf_path,\n            filename=filename,\n            prompt_mode=prompt_mode,\n            save_dir=temp_dir\n        )\n        \n        # Parse the results\n        if not results:\n            raise ValueError(\"No results returned from parser\")\n        \n        # Handle multi-page results\n        parsed_results = []\n        all_md_content = []\n        all_cells_data = []\n        \n        for i, result in enumerate(results):\n            page_result = {\n                'page_no': result.get('page_no', i),\n                'layout_image': None,\n                'cells_data': None,\n                'md_content': None,\n                'filtered': False\n            }\n            \n            # Read the layout image\n            if 'layout_image_path' in result and os.path.exists(result['layout_image_path']):\n                page_result['layout_image'] = Image.open(result['layout_image_path'])\n            \n            # Read the JSON data\n            if 'layout_info_path' in result and os.path.exists(result['layout_info_path']):\n                with open(result['layout_info_path'], 'r', encoding='utf-8') as f:\n                    page_result['cells_data'] = json.load(f)\n                    all_cells_data.extend(page_result['cells_data'])\n            \n            # Read the Markdown content\n            if 'md_content_path' in result and os.path.exists(result['md_content_path']):\n                with open(result['md_content_path'], 'r', encoding='utf-8') as f:\n                    page_content = f.read()\n                    page_result['md_content'] = page_content\n                    all_md_content.append(page_content)\n            page_result['filtered'] = result.get('filtered', False)\n            parsed_results.append(page_result)\n        \n        combined_md = \"\\n\\n---\\n\\n\".join(all_md_content) if all_md_content else \"\"\n        return {\n            'parsed_results': parsed_results,\n            'combined_md_content': combined_md,\n            'combined_cells_data': all_cells_data,\n            'temp_dir': temp_dir,\n            'session_id': session_id,\n            'total_pages': len(results)\n        }\n        \n    except Exception as e:\n        if os.path.exists(temp_dir):\n            shutil.rmtree(temp_dir, ignore_errors=True)\n        raise e\n\n# ==================== Core Processing Function ====================\ndef process_image_inference(session_state, test_image_input, file_input,\n                          prompt_mode, server_ip, server_port, min_pixels, max_pixels,\n                          fitz_preprocess=False\n                          ):\n    \"\"\"Core function to handle image/PDF inference\"\"\"\n    # Use session_state instead of global variables\n    processing_results = session_state['processing_results']\n    pdf_cache = session_state['pdf_cache']\n    \n    if processing_results.get('temp_dir') and os.path.exists(processing_results['temp_dir']):\n        try:\n            shutil.rmtree(processing_results['temp_dir'], ignore_errors=True)\n        except Exception as e:\n            print(f\"Failed to clean up previous temporary directory: {e}\")\n    \n    # Reset processing results for the current session\n    session_state['processing_results'] = get_initial_session_state()['processing_results']\n    processing_results = session_state['processing_results']\n    \n    current_config.update({\n        'ip': server_ip,\n        'port_vllm': server_port,\n        'min_pixels': min_pixels,\n        'max_pixels': max_pixels\n    })\n    \n    # Update parser configuration\n    dots_parser.ip = server_ip\n    dots_parser.port = server_port\n    dots_parser.min_pixels = min_pixels\n    dots_parser.max_pixels = max_pixels\n    \n    input_file_path = file_input if file_input else test_image_input\n    \n    if not input_file_path:\n        return None, \"Please upload image/PDF file or select test image\", \"\", \"\", gr.update(value=None), None, \"\", session_state\n    \n    file_ext = os.path.splitext(input_file_path)[1].lower()\n    \n    try:\n        if file_ext == '.pdf':\n            # MINIMAL CHANGE: The `process_pdf_file` function is now inlined and uses session_state.\n            preview_image, page_info, session_state = load_file_for_preview(input_file_path, session_state)\n            pdf_result = parse_pdf_with_high_level_api(dots_parser, input_file_path, prompt_mode)\n            \n            session_state['pdf_cache'][\"is_parsed\"] = True\n            session_state['pdf_cache'][\"results\"] = pdf_result['parsed_results']\n            \n            processing_results.update({\n                'markdown_content': pdf_result['combined_md_content'],\n                'cells_data': pdf_result['combined_cells_data'],\n                'temp_dir': pdf_result['temp_dir'],\n                'session_id': pdf_result['session_id'],\n                'pdf_results': pdf_result['parsed_results']\n            })\n            \n            total_elements = len(pdf_result['combined_cells_data'])\n            info_text = f\"**PDF Information:**\\n- Total Pages: {pdf_result['total_pages']}\\n- Server: {current_config['ip']}:{current_config['port_vllm']}\\n- Total Detected Elements: {total_elements}\\n- Session ID: {pdf_result['session_id']}\"\n            \n            current_page_layout_image = preview_image\n            current_page_json = \"\"\n            if session_state['pdf_cache'][\"results\"]:\n                first_result = session_state['pdf_cache'][\"results\"][0]\n                if 'layout_image' in first_result and first_result['layout_image']:\n                    current_page_layout_image = first_result['layout_image']\n                if first_result.get('cells_data'):\n                    try:\n                        current_page_json = json.dumps(first_result['cells_data'], ensure_ascii=False, indent=2)\n                    except:\n                        current_page_json = str(first_result['cells_data'])\n\n            download_zip_path = None\n            if pdf_result['temp_dir']:\n                download_zip_path = os.path.join(pdf_result['temp_dir'], f\"layout_results_{pdf_result['session_id']}.zip\")\n                with zipfile.ZipFile(download_zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:\n                    for root, _, files in os.walk(pdf_result['temp_dir']):\n                        for file in files:\n                            if not file.endswith('.zip'): zipf.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), pdf_result['temp_dir']))\n\n            return (\n                current_page_layout_image, info_text, pdf_result['combined_md_content'] or \"No markdown content generated\",\n                pdf_result['combined_md_content'] or \"No markdown content generated\",\n                gr.update(value=download_zip_path, visible=bool(download_zip_path)), page_info, current_page_json, session_state\n            )\n        \n        else: # Image processing\n            image = read_image_v2(input_file_path)\n            session_state['pdf_cache'] = get_initial_session_state()['pdf_cache']\n            \n            original_image = image\n            parse_result = parse_image_with_high_level_api(dots_parser, image, prompt_mode, fitz_preprocess)\n            \n            if parse_result['filtered']:\n                 info_text = f\"**Image Information:**\\n- Original Size: {original_image.width} x {original_image.height}\\n- Processing: JSON parsing failed, using cleaned text output\\n- Server: {current_config['ip']}:{current_config['port_vllm']}\\n- Session ID: {parse_result['session_id']}\"\n                 processing_results.update({\n                     'original_image': original_image, 'markdown_content': parse_result['md_content'],\n                     'temp_dir': parse_result['temp_dir'], 'session_id': parse_result['session_id'],\n                     'result_paths': parse_result['result_paths']\n                 })\n                 return original_image, info_text, parse_result['md_content'], parse_result['md_content'], gr.update(visible=False), None, \"\", session_state\n            \n            md_content_raw = parse_result['md_content'] or \"No markdown content generated\"\n            processing_results.update({\n                'original_image': original_image, 'layout_result': parse_result['layout_image'],\n                'markdown_content': parse_result['md_content'], 'cells_data': parse_result['cells_data'],\n                'temp_dir': parse_result['temp_dir'], 'session_id': parse_result['session_id'],\n                'result_paths': parse_result['result_paths']\n            })\n            \n            num_elements = len(parse_result['cells_data']) if parse_result['cells_data'] else 0\n            info_text = f\"**Image Information:**\\n- Original Size: {original_image.width} x {original_image.height}\\n- Model Input Size: {parse_result['input_width']} x {parse_result['input_height']}\\n- Server: {current_config['ip']}:{current_config['port_vllm']}\\n- Detected {num_elements} layout elements\\n- Session ID: {parse_result['session_id']}\"\n            \n            current_json = json.dumps(parse_result['cells_data'], ensure_ascii=False, indent=2) if parse_result['cells_data'] else \"\"\n            \n            download_zip_path = None\n            if parse_result['temp_dir']:\n                download_zip_path = os.path.join(parse_result['temp_dir'], f\"layout_results_{parse_result['session_id']}.zip\")\n                with zipfile.ZipFile(download_zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:\n                    for root, _, files in os.walk(parse_result['temp_dir']):\n                        for file in files:\n                            if not file.endswith('.zip'): zipf.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), parse_result['temp_dir']))\n            \n            return (\n                parse_result['layout_image'], info_text, parse_result['md_content'] or \"No markdown content generated\",\n                md_content_raw, gr.update(value=download_zip_path, visible=bool(download_zip_path)),\n                None, current_json, session_state\n            )\n    except Exception as e:\n        import traceback\n        traceback.print_exc()\n        return None, f\"Error during processing: {e}\", \"\", \"\", gr.update(value=None), None, \"\", session_state\n\n# MINIMAL CHANGE: Functions now take `session_state` as an argument.\ndef clear_all_data(session_state):\n    \"\"\"Clears all data\"\"\"\n    processing_results = session_state['processing_results']\n    \n    if processing_results.get('temp_dir') and os.path.exists(processing_results['temp_dir']):\n        try:\n            shutil.rmtree(processing_results['temp_dir'], ignore_errors=True)\n        except Exception as e:\n            print(f\"Failed to clean up temporary directory: {e}\")\n    \n    # Reset the session state by returning a new initial state\n    new_session_state = get_initial_session_state()\n    \n    return (\n        None,  # Clear file input\n        \"\",    # Clear test image selection\n        None,  # Clear result image\n        \"Waiting for processing results...\",  # Reset info display\n        \"## Waiting for processing results...\",  # Reset Markdown display\n        \"🕐 Waiting for parsing result...\",    # Clear raw Markdown text\n        gr.update(visible=False),  # Hide download button\n        \"<div id='page_info_box'>0 / 0</div>\",  # Reset page info\n        \"🕐 Waiting for parsing result...\",     # Clear current page JSON\n        new_session_state\n    )\n\ndef update_prompt_display(prompt_mode):\n    \"\"\"Updates the prompt display content\"\"\"\n    return dict_promptmode_to_prompt[prompt_mode]\n\n# ==================== Gradio Interface ====================\ndef create_gradio_interface():\n    \"\"\"Creates the Gradio interface\"\"\"\n    \n    # CSS styles, matching the reference style\n    css = \"\"\"\n\n    #parse_button {\n        background: #FF576D !important; /* !important 确保覆盖主题默认样式 */\n        border-color: #FF576D !important;\n    }\n    /* 鼠标悬停时的颜色 */\n    #parse_button:hover {\n        background: #F72C49 !important;\n        border-color: #F72C49 !important;\n    }\n    \n    #page_info_html {\n        display: flex;\n        align-items: center;\n        justify-content: center;\n        height: 100%;\n        margin: 0 12px;\n    }\n\n    #page_info_box {\n        padding: 8px 20px;\n        font-size: 16px;\n        border: 1px solid #bbb;\n        border-radius: 8px;\n        background-color: #f8f8f8;\n        text-align: center;\n        min-width: 80px;\n        box-shadow: 0 1px 3px rgba(0,0,0,0.1);\n    }\n\n    #markdown_output {\n        min-height: 800px;\n        overflow: auto;\n    }\n\n    footer {\n        visibility: hidden;\n    }\n    \n    #info_box {\n        padding: 10px;\n        background-color: #f8f9fa;\n        border-radius: 8px;\n        border: 1px solid #dee2e6;\n        margin: 10px 0;\n        font-size: 14px;\n    }\n    \n    #result_image {\n        border-radius: 8px;\n    }\n    \n    #markdown_tabs {\n        height: 100%;\n    }\n    \"\"\"\n    \n    with gr.Blocks(theme=\"ocean\", css=css, title='dots.ocr') as demo:\n        session_state = gr.State(value=get_initial_session_state())\n        \n        # Title\n        gr.HTML(\"\"\"\n            <div style=\"display: flex; align-items: center; justify-content: center; margin-bottom: 20px;\">\n                <h1 style=\"margin: 0; font-size: 2em;\">🔍 dots.ocr</h1>\n            </div>\n            <div style=\"text-align: center; margin-bottom: 10px;\">\n                <em>Supports image/PDF layout analysis and structured output</em>\n            </div>\n        \"\"\")\n        \n        with gr.Row():\n            # Left side: Input and Configuration\n            with gr.Column(scale=1, elem_id=\"left-panel\"):\n                gr.Markdown(\"### 📥 Upload & Select\")\n                file_input = gr.File(\n                    label=\"Upload PDF/Image\", \n                    type=\"filepath\", \n                    file_types=[\".pdf\", \".jpg\", \".jpeg\", \".png\"],\n                )\n                \n                test_images = get_test_images()\n                test_image_input = gr.Dropdown(\n                    label=\"Or Select an Example\",\n                    choices=[\"\"] + test_images,\n                    value=\"\",\n                )\n\n                gr.Markdown(\"### ⚙️ Prompt & Actions\")\n                prompt_mode = gr.Dropdown(\n                    label=\"Select Prompt\",\n                    choices=[\"prompt_layout_all_en\", \"prompt_layout_only_en\", \"prompt_ocr\"],\n                    value=\"prompt_layout_all_en\",\n                )\n                \n                # Display current prompt content\n                prompt_display = gr.Textbox(\n                    label=\"Current Prompt Content\",\n                    value=dict_promptmode_to_prompt[list(dict_promptmode_to_prompt.keys())[0]],\n                    lines=4,\n                    max_lines=8,\n                    interactive=False,\n                    show_copy_button=True\n                )\n                \n                with gr.Row():\n                    process_btn = gr.Button(\"🔍 Parse\", variant=\"primary\", scale=2, elem_id=\"parse_button\")\n                    clear_btn = gr.Button(\"🗑️ Clear\", variant=\"secondary\", scale=1)\n                \n                with gr.Accordion(\"🛠️ Advanced Configuration\", open=False):\n                    fitz_preprocess = gr.Checkbox(\n                        label=\"Enable fitz_preprocess for images\", \n                        value=True,\n                        info=\"Processes image via a PDF-like pipeline (image->pdf->200dpi image). Recommended if your image DPI is low.\"\n                    )\n                    with gr.Row():\n                        server_ip = gr.Textbox(label=\"Server IP\", value=DEFAULT_CONFIG['ip'])\n                        server_port = gr.Number(label=\"Port\", value=DEFAULT_CONFIG['port_vllm'], precision=0)\n                    with gr.Row():\n                        min_pixels = gr.Number(label=\"Min Pixels\", value=DEFAULT_CONFIG['min_pixels'], precision=0)\n                        max_pixels = gr.Number(label=\"Max Pixels\", value=DEFAULT_CONFIG['max_pixels'], precision=0)\n            # Right side: Result Display\n            with gr.Column(scale=6, variant=\"compact\"):\n                with gr.Row():\n                    # Result Image\n                    with gr.Column(scale=3):\n                        gr.Markdown(\"### 👁️ File Preview\")\n                        result_image = gr.Image(\n                            label=\"Layout Preview\",\n                            visible=True,\n                            height=800,\n                            show_label=False\n                        )\n                        \n                        # Page navigation (shown during PDF preview)\n                        with gr.Row():\n                            prev_btn = gr.Button(\"⬅ Previous\", size=\"sm\")\n                            page_info = gr.HTML(\n                                value=\"<div id='page_info_box'>0 / 0</div>\", \n                                elem_id=\"page_info_html\"\n                            )\n                            next_btn = gr.Button(\"Next ➡\", size=\"sm\")\n                        \n                        # Info Display\n                        info_display = gr.Markdown(\n                            \"Waiting for processing results...\",\n                            elem_id=\"info_box\"\n                        )\n                    \n                    # Markdown Result\n                    with gr.Column(scale=3):\n                        gr.Markdown(\"### ✔️ Result Display\")\n                        \n                        with gr.Tabs(elem_id=\"markdown_tabs\"):\n                            with gr.TabItem(\"Markdown Render Preview\"):\n                                md_output = gr.Markdown(\n                                    \"## Please click the parse button to parse or select for single-task recognition...\",\n                                    max_height=600,\n                                    latex_delimiters=[\n                                        {\"left\": \"$$\", \"right\": \"$$\", \"display\": True},\n                                        {\"left\": \"$\", \"right\": \"$\", \"display\": False}\n                                    ],\n                                    show_copy_button=False,\n                                    elem_id=\"markdown_output\"\n                                )\n                            \n                            with gr.TabItem(\"Markdown Raw Text\"):\n                                md_raw_output = gr.Textbox(\n                                    value=\"🕐 Waiting for parsing result...\",\n                                    label=\"Markdown Raw Text\",\n                                    max_lines=100,\n                                    lines=38,\n                                    show_copy_button=True,\n                                    elem_id=\"markdown_output\",\n                                    show_label=False\n                                )\n                            \n                            with gr.TabItem(\"Current Page JSON\"):\n                                current_page_json = gr.Textbox(\n                                    value=\"🕐 Waiting for parsing result...\",\n                                    label=\"Current Page JSON\",\n                                    max_lines=100,\n                                    lines=38,\n                                    show_copy_button=True,\n                                    elem_id=\"markdown_output\",\n                                    show_label=False\n                                )\n                \n                # Download Button\n                with gr.Row():\n                    download_btn = gr.DownloadButton(\n                        \"⬇️ Download Results\",\n                        visible=False\n                    )\n        \n        # When the prompt mode changes, update the display content\n        prompt_mode.change(\n            fn=update_prompt_display,\n            inputs=prompt_mode,\n            outputs=prompt_display,\n        )\n        \n        # Show preview on file upload\n        file_input.upload(\n            # fn=lambda file_data, state: load_file_for_preview(file_data, state),\n            fn=load_file_for_preview,\n            inputs=[file_input, session_state],\n            outputs=[result_image, page_info, session_state]\n        )\n        \n        # Also handle test image selection\n        test_image_input.change(\n            # fn=lambda path, state: load_file_for_preview(path, state),\n            fn=load_file_for_preview,\n            inputs=[test_image_input, session_state],\n            outputs=[result_image, page_info, session_state]\n        )\n\n        prev_btn.click(\n            fn=lambda s: turn_page(\"prev\", s),\n            inputs=[session_state], \n            outputs=[result_image, page_info, current_page_json, session_state]\n        )\n        \n        next_btn.click(\n            fn=lambda s: turn_page(\"next\", s),\n            inputs=[session_state], \n            outputs=[result_image, page_info, current_page_json, session_state]\n        )\n        \n        process_btn.click(\n            fn=process_image_inference,\n            inputs=[\n                session_state, test_image_input, file_input,\n                prompt_mode, server_ip, server_port, min_pixels, max_pixels, \n                fitz_preprocess\n            ],\n            outputs=[\n                result_image, info_display, md_output, md_raw_output,\n                download_btn, page_info, current_page_json, session_state\n            ]\n        )\n        \n        clear_btn.click(\n            fn=clear_all_data,\n            inputs=[session_state],\n            outputs=[\n                file_input, test_image_input,\n                result_image, info_display, md_output, md_raw_output,\n                download_btn, page_info, current_page_json, session_state\n            ]\n        )\n    \n    return demo\n\n# ==================== Main Program ====================\nif __name__ == \"__main__\":\n    import sys\n    port = int(sys.argv[1])\n    demo = create_gradio_interface()\n    demo.queue().launch(\n        server_name=\"0.0.0.0\", \n        server_port=port, \n        debug=True\n    )\n"
  },
  {
    "path": "demo/demo_gradio_annotion.py",
    "content": "\"\"\"\nLayout Inference Web Application with Gradio - Annotation Version\n\nA Gradio-based layout inference tool that supports image uploads and multiple backend inference engines.\nThis version adds an image annotation feature, allowing users to draw bounding boxes on an image and send both the image and the boxes to the model.\n\"\"\"\n\nimport gradio as gr\nimport json\nimport os\nimport io\nimport tempfile\nimport base64\nimport zipfile\nimport uuid\nimport re\nfrom pathlib import Path\nfrom PIL import Image\nimport requests\nfrom gradio_image_annotation import image_annotator\n\n# Local utility imports\nfrom dots_ocr.utils import dict_promptmode_to_prompt\nfrom dots_ocr.utils.consts import MIN_PIXELS, MAX_PIXELS\nfrom dots_ocr.utils.demo_utils.display import read_image\nfrom dots_ocr.utils.doc_utils import load_images_from_pdf\n\n# Add DotsOCRParser import\nfrom dots_ocr.parser import DotsOCRParser\n\n# ==================== Configuration ====================\nDEFAULT_CONFIG = {\n    'ip': \"127.0.0.1\",\n    'port_vllm': 8000,\n    'min_pixels': MIN_PIXELS,\n    'max_pixels': MAX_PIXELS,\n    'test_images_dir': \"./assets/showcase_origin\",\n}\n\n# ==================== Global Variables ====================\n# Store the current configuration\ncurrent_config = DEFAULT_CONFIG.copy()\n\n# Create a DotsOCRParser instance\ndots_parser = DotsOCRParser(\n    ip=DEFAULT_CONFIG['ip'],\n    port=DEFAULT_CONFIG['port_vllm'],\n    dpi=200,\n    min_pixels=DEFAULT_CONFIG['min_pixels'],\n    max_pixels=DEFAULT_CONFIG['max_pixels']\n)\n\n# Store processing results\nprocessing_results = {\n    'original_image': None,\n    'processed_image': None,\n    'layout_result': None,\n    'markdown_content': None,\n    'cells_data': None,\n    'temp_dir': None,\n    'session_id': None,\n    'result_paths': None,\n    'annotation_data': None  # Store annotation data\n}\n\n# ==================== Utility Functions ====================\ndef read_image_v2(img):\n    \"\"\"Reads an image, supporting URLs and local paths.\"\"\"\n    if isinstance(img, str) and img.startswith((\"http://\", \"https://\")):\n        with requests.get(img, stream=True) as response:\n            response.raise_for_status()\n            img = Image.open(io.BytesIO(response.content))\n    elif isinstance(img, str):\n        img, _, _ = read_image(img, use_native=True)\n    elif isinstance(img, Image.Image):\n        pass\n    else:\n        raise ValueError(f\"Invalid image type: {type(img)}\")\n    return img\n\ndef get_test_images():\n    \"\"\"Gets the list of test images.\"\"\"\n    test_images = []\n    test_dir = current_config['test_images_dir']\n    if os.path.exists(test_dir):\n        test_images = [os.path.join(test_dir, name) for name in os.listdir(test_dir) \n                      if name.lower().endswith(('.png', '.jpg', '.jpeg'))]\n    return test_images\n\ndef create_temp_session_dir():\n    \"\"\"Creates a unique temporary directory for each processing request.\"\"\"\n    session_id = uuid.uuid4().hex[:8]\n    temp_dir = os.path.join(tempfile.gettempdir(), f\"dots_ocr_demo_{session_id}\")\n    os.makedirs(temp_dir, exist_ok=True)\n    return temp_dir, session_id\n\ndef parse_image_with_bbox(parser, image, prompt_mode, bbox=None, fitz_preprocess=False):\n    \"\"\"\n    Processes an image using DotsOCRParser, with support for the bbox parameter.\n    \"\"\"\n    # Create a temporary session directory\n    temp_dir, session_id = create_temp_session_dir()\n    \n    try:\n        # Save the PIL Image to a temporary file\n        temp_image_path = os.path.join(temp_dir, f\"input_{session_id}.png\")\n        image.save(temp_image_path, \"PNG\")\n        \n        # Use the high-level parse_image interface, passing the bbox parameter\n        filename = f\"demo_{session_id}\"\n        results = parser.parse_image(\n            input_path=temp_image_path,\n            filename=filename, \n            prompt_mode=prompt_mode,\n            save_dir=temp_dir,\n            bbox=bbox,\n            fitz_preprocess=fitz_preprocess\n        )\n        \n        # Parse the results\n        if not results:\n            raise ValueError(\"No results returned from parser\")\n        \n        result = results[0]  # parse_image returns a list with a single result\n        \n        # Read the result files\n        layout_image = None\n        cells_data = None\n        md_content = None\n        filtered = False\n        \n        # Read the layout image\n        if 'layout_image_path' in result and os.path.exists(result['layout_image_path']):\n            layout_image = Image.open(result['layout_image_path'])\n        \n        # Read the JSON data\n        if 'layout_info_path' in result and os.path.exists(result['layout_info_path']):\n            with open(result['layout_info_path'], 'r', encoding='utf-8') as f:\n                cells_data = json.load(f)\n        \n        # Read the Markdown content\n        if 'md_content_path' in result and os.path.exists(result['md_content_path']):\n            with open(result['md_content_path'], 'r', encoding='utf-8') as f:\n                md_content = f.read()\n        \n        # Check for the original response file (if JSON parsing fails)\n        if 'filtered' in result:\n            filtered = result['filtered']\n        \n        return {\n            'layout_image': layout_image,\n            'cells_data': cells_data,\n            'md_content': md_content,\n            'filtered': filtered,\n            'temp_dir': temp_dir,\n            'session_id': session_id,\n            'result_paths': result\n        }\n        \n    except Exception as e:\n        # Clean up the temporary directory on error\n        import shutil\n        if os.path.exists(temp_dir):\n            shutil.rmtree(temp_dir, ignore_errors=True)\n        raise e\n\ndef process_annotation_data(annotation_data):\n    \"\"\"Processes annotation data, converting it to the format required by the model.\"\"\"\n    if not annotation_data or not annotation_data.get('boxes'):\n        return None, None\n    \n    # Get image and box data\n    image = annotation_data.get('image')\n    boxes = annotation_data.get('boxes', [])\n    \n    if not boxes:\n        return image, None\n    \n    # Ensure the image is in PIL Image format\n    if image is not None:\n        import numpy as np\n        if isinstance(image, np.ndarray):\n            image = Image.fromarray(image)\n        elif not isinstance(image, Image.Image):\n            # If it's another format, try to convert it\n            try:\n                image = Image.open(image) if isinstance(image, str) else Image.fromarray(image)\n            except Exception as e:\n                print(f\"Image format conversion failed: {e}\")\n                return None, None\n    \n    # Get the coordinate information of the box (only one box)\n    box = boxes[0]\n    bbox = [box['xmin'], box['ymin'], box['xmax'], box['ymax']]\n    \n    return image, bbox\n\n# ==================== Core Processing Function ====================\ndef process_image_inference_with_annotation(annotation_data, test_image_input,\n                          prompt_mode, server_ip, server_port, min_pixels, max_pixels,\n                          fitz_preprocess=False\n                          ):\n    \"\"\"Core function for image inference, supporting annotation data.\"\"\"\n    global current_config, processing_results, dots_parser\n    \n    # First, clean up previous processing results\n    if processing_results.get('temp_dir') and os.path.exists(processing_results['temp_dir']):\n        import shutil\n        try:\n            shutil.rmtree(processing_results['temp_dir'], ignore_errors=True)\n        except Exception as e:\n            print(f\"Failed to clean up previous temporary directory: {e}\")\n    \n    # Reset processing results\n    processing_results = {\n        'original_image': None,\n        'processed_image': None,\n        'layout_result': None,\n        'markdown_content': None,\n        'cells_data': None,\n        'temp_dir': None,\n        'session_id': None,\n        'result_paths': None,\n        'annotation_data': annotation_data\n    }\n    \n    # Update configuration\n    current_config.update({\n        'ip': server_ip,\n        'port_vllm': server_port,\n        'min_pixels': min_pixels,\n        'max_pixels': max_pixels\n    })\n    \n    # Update parser configuration\n    dots_parser.ip = server_ip\n    dots_parser.port = server_port\n    dots_parser.min_pixels = min_pixels\n    dots_parser.max_pixels = max_pixels\n    \n    # Determine the input source and process annotation data\n    image = None\n    bbox = None\n    \n    # Prioritize processing annotation data\n    if annotation_data and annotation_data.get('image') is not None:\n        image, bbox = process_annotation_data(annotation_data)\n        if image is not None:\n            # If there's a bbox, force the use of 'prompt_grounding_ocr' mode\n            assert bbox is not None\n            prompt_mode = \"prompt_grounding_ocr\"\n    \n    # If there's no annotation data, check the test image input\n    if image is None and test_image_input and test_image_input != \"\":\n        try:\n            image = read_image_v2(test_image_input)\n        except Exception as e:\n            return None, f\"Failed to read test image: {e}\", \"\", \"\", gr.update(value=None), \"\"\n    \n    if image is None:\n        return None, \"Please select a test image or add an image in the annotation component\", \"\", \"\", gr.update(value=None), \"\"\n    if bbox is None:\n        return None, \"Please select a bounding box by mouse\", \"Please select a bounding box by mouse\", \"\", \"\", gr.update(value=None)\n    \n    try:\n        # Process using DotsOCRParser, passing the bbox parameter\n        original_image = image\n        parse_result = parse_image_with_bbox(dots_parser, image, prompt_mode, bbox, fitz_preprocess)\n        \n        # Extract parsing results\n        layout_image = parse_result['layout_image']\n        cells_data = parse_result['cells_data']\n        md_content = parse_result['md_content']\n        filtered = parse_result['filtered']\n        \n        # Store the results\n        processing_results.update({\n            'original_image': original_image,\n            'processed_image': None,\n            'layout_result': layout_image,\n            'markdown_content': md_content,\n            'cells_data': cells_data,\n            'temp_dir': parse_result['temp_dir'],\n            'session_id': parse_result['session_id'],\n            'result_paths': parse_result['result_paths'],\n            'annotation_data': annotation_data\n        })\n        \n        # Handle the case where parsing fails\n        if filtered:\n            info_text = f\"\"\"\n**Image Information:**\n- Original Dimensions: {original_image.width} x {original_image.height}\n- Processing Mode: {'Region OCR' if bbox else 'Full Image OCR'}\n- Processing Status: JSON parsing failed, using cleaned text output\n- Server: {current_config['ip']}:{current_config['port_vllm']}\n- Session ID: {parse_result['session_id']}\n- Box Coordinates: {bbox if bbox else 'None'}\n            \"\"\"\n            \n            return (\n                md_content or \"No markdown content generated\",\n                info_text,\n                md_content or \"No markdown content generated\",\n                md_content or \"No markdown content generated\",\n                gr.update(visible=False),\n                \"\"\n            )\n        \n        # Handle the case where JSON parsing succeeds\n        num_elements = len(cells_data) if cells_data else 0\n        info_text = f\"\"\"\n**Image Information:**\n- Original Dimensions: {original_image.width} x {original_image.height}\n- Processing Mode: {'Region OCR' if bbox else 'Full Image OCR'}\n- Server: {current_config['ip']}:{current_config['port_vllm']}\n- Detected {num_elements} layout elements\n- Session ID: {parse_result['session_id']}\n- Box Coordinates: {bbox if bbox else 'None'}\n        \"\"\"\n        \n        # Current page JSON output\n        current_json = \"\"\n        if cells_data:\n            try:\n                current_json = json.dumps(cells_data, ensure_ascii=False, indent=2)\n            except:\n                current_json = str(cells_data)\n        \n        # Create a downloadable ZIP file\n        download_zip_path = None\n        if parse_result['temp_dir']:\n            download_zip_path = os.path.join(parse_result['temp_dir'], f\"layout_results_{parse_result['session_id']}.zip\")\n            try:\n                with zipfile.ZipFile(download_zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:\n                    for root, dirs, files in os.walk(parse_result['temp_dir']):\n                        for file in files:\n                            if file.endswith('.zip'):\n                                continue\n                            file_path = os.path.join(root, file)\n                            arcname = os.path.relpath(file_path, parse_result['temp_dir'])\n                            zipf.write(file_path, arcname)\n            except Exception as e:\n                print(f\"Failed to create download ZIP: {e}\")\n                download_zip_path = None\n        \n        return (\n            md_content or \"No markdown content generated\",\n            info_text,\n            md_content or \"No markdown content generated\",\n            md_content or \"No markdown content generated\",\n            gr.update(value=download_zip_path, visible=True) if download_zip_path else gr.update(visible=False),\n            current_json\n        )\n        \n    except Exception as e:\n        return f\"An error occurred during processing: {e}\", f\"An error occurred during processing: {e}\", \"\", \"\", gr.update(value=None), \"\"\n\ndef load_image_to_annotator(test_image_input):\n    \"\"\"Loads an image into the annotation component.\"\"\"\n    image = None\n    \n    # Check the test image input\n    if test_image_input and test_image_input != \"\":\n        try:\n            image = read_image_v2(test_image_input)\n        except Exception as e:\n            return None\n    \n    if image is None:\n        return None\n    \n    # Return the format required by the annotation component\n    return {\n        \"image\": image,\n        \"boxes\": []\n    }\n\ndef clear_all_data():\n    \"\"\"Clears all data.\"\"\"\n    global processing_results\n    \n    # Clean up the temporary directory\n    if processing_results.get('temp_dir') and os.path.exists(processing_results['temp_dir']):\n        import shutil\n        try:\n            shutil.rmtree(processing_results['temp_dir'], ignore_errors=True)\n        except Exception as e:\n            print(f\"Failed to clean up temporary directory: {e}\")\n    \n    # Reset processing results\n    processing_results = {\n        'original_image': None,\n        'processed_image': None,\n        'layout_result': None,\n        'markdown_content': None,\n        'cells_data': None,\n        'temp_dir': None,\n        'session_id': None,\n        'result_paths': None,\n        'annotation_data': None\n    }\n    \n    return (\n        \"\",    # Clear test image selection\n        None,  # Clear annotation component\n        \"Waiting for processing results...\",  # Reset info display\n        \"## Waiting for processing results...\",  # Reset Markdown display\n        \"🕐 Waiting for parsing results...\",    # Clear raw Markdown text\n        gr.update(visible=False),  # Hide download button\n        \"🕐 Waiting for parsing results...\"     # Clear JSON\n    )\n\ndef update_prompt_display(prompt_mode):\n    \"\"\"Updates the displayed prompt content.\"\"\"\n    return dict_promptmode_to_prompt[prompt_mode]\n\n# ==================== Gradio Interface ====================\ndef create_gradio_interface():\n    \"\"\"Creates the Gradio interface.\"\"\"\n    \n    # CSS styling to match the reference style\n    css = \"\"\"\n    footer {\n        visibility: hidden;\n    }\n    \n    #info_box {\n        padding: 10px;\n        background-color: #f8f9fa;\n        border-radius: 8px;\n        border: 1px solid #dee2e6;\n        margin: 10px 0;\n        font-size: 14px;\n    }\n    \n    #markdown_tabs {\n        height: 100%;\n    }\n    \n    #annotation_component {\n        border-radius: 8px;\n    }\n    \"\"\"\n    \n    with gr.Blocks(theme=\"ocean\", css=css, title='dots.ocr - Annotation') as demo:\n        \n        # Title\n        gr.HTML(\"\"\"\n            <div style=\"display: flex; align-items: center; justify-content: center; margin-bottom: 20px;\">\n                <h1 style=\"margin: 0; font-size: 2em;\">🔍 dots.ocr - Annotation Version</h1>\n            </div>\n            <div style=\"text-align: center; margin-bottom: 10px;\">\n                <em>Supports image annotation, drawing boxes, and sending box information to the model for OCR.</em>\n            </div>\n        \"\"\")\n        \n        with gr.Row():\n            # Left side: Input and Configuration\n            with gr.Column(scale=1, variant=\"compact\"):\n                gr.Markdown(\"### 📁 Select Example\")\n                test_images = get_test_images()\n                test_image_input = gr.Dropdown(\n                    label=\"Select Example\",\n                    choices=[\"\"] + test_images,\n                    value=\"\",\n                    show_label=True\n                )\n                \n                # Button to load image into the annotation component\n                load_btn = gr.Button(\"📷 Load Image to Annotation Area\", variant=\"secondary\")\n                \n                prompt_mode = gr.Dropdown(\n                    label=\"Select Prompt\",\n                    # choices=[\"prompt_layout_all_en\", \"prompt_layout_only_en\", \"prompt_ocr\", \"prompt_grounding_ocr\"],\n                    choices=[\"prompt_grounding_ocr\"],\n                    value=\"prompt_grounding_ocr\",\n                    show_label=True,\n                    info=\"If a box is drawn, 'prompt_grounding_ocr' mode will be used automatically.\"\n                )\n                \n                # Display the current prompt content\n                prompt_display = gr.Textbox(\n                    label=\"Current Prompt Content\",\n                    # value=dict_promptmode_to_prompt[list(dict_promptmode_to_prompt.keys())[0]],\n                    value=dict_promptmode_to_prompt[\"prompt_grounding_ocr\"],\n                    lines=4,\n                    max_lines=8,\n                    interactive=False,\n                    show_copy_button=True\n                )\n                \n                gr.Markdown(\"### ⚙️ Actions\")\n                process_btn = gr.Button(\"🔍 Parse\", variant=\"primary\")\n                clear_btn = gr.Button(\"🗑️ Clear\", variant=\"secondary\")\n                \n                gr.Markdown(\"### 🛠️ Configuration\")\n\n                fitz_preprocess = gr.Checkbox(\n                    label=\"Enable fitz_preprocess\", \n                    value=False,\n                    info=\"Performs fitz preprocessing on the image input, converting the image to a PDF and then to a 200dpi image.\"\n                )\n                \n                with gr.Row():\n                    server_ip = gr.Textbox(\n                        label=\"Server IP\",\n                        value=DEFAULT_CONFIG['ip']\n                    )\n                    server_port = gr.Number(\n                        label=\"Port\",\n                        value=DEFAULT_CONFIG['port_vllm'],\n                        precision=0\n                    )\n                \n                with gr.Row():\n                    min_pixels = gr.Number(\n                        label=\"Min Pixels\",\n                        value=DEFAULT_CONFIG['min_pixels'],\n                        precision=0\n                    )\n                    max_pixels = gr.Number(\n                        label=\"Max Pixels\", \n                        value=DEFAULT_CONFIG['max_pixels'],\n                        precision=0\n                    )\n            \n            # Right side: Result Display\n            with gr.Column(scale=6, variant=\"compact\"):\n                with gr.Row():\n                    # Image Annotation Area\n                    with gr.Column(scale=3):\n                        gr.Markdown(\"### 🎯 Image Annotation Area\")\n                        gr.Markdown(\"\"\"\n                        **Instructions:**\n                        - Method 1: Select an example image on the left and click \"Load Image to Annotation Area\".\n                        - Method 2: Upload an image directly in the annotation area below (drag and drop or click to upload).\n                        - Use the mouse to draw a box on the image to select the region for recognition.\n                        - Only one box can be drawn. To draw a new one, please delete the old one first.\n                        - **Hotkey: Press the Delete key to remove the selected box.**\n                        - After drawing a box, clicking Parse will automatically use the Region OCR mode.\n                        \"\"\")\n                        \n                        annotator = image_annotator(\n                            value=None,\n                            label=\"Image Annotation\",\n                            height=600,\n                            show_label=False,\n                            elem_id=\"annotation_component\",\n                            single_box=True,  # Only allow one box; a new box will replace the old one\n                            box_min_size=10,\n                            interactive=True,\n                            disable_edit_boxes=True,  # Disable the edit dialog\n                            label_list=[\"OCR Region\"],  # Set the default label\n                            label_colors=[(255, 0, 0)],  # Set color to red\n                            use_default_label=True,  # Use the default label\n                            image_type=\"pil\"  # Ensure it returns a PIL Image format\n                        )\n                        \n                        # Information Display\n                        info_display = gr.Markdown(\n                            \"Waiting for processing results...\",\n                            elem_id=\"info_box\"\n                        )\n                    \n                    # Result Display Area\n                    with gr.Column(scale=3):\n                        gr.Markdown(\"### ✅ Results\")\n                        \n                        with gr.Tabs(elem_id=\"markdown_tabs\"):\n                            with gr.TabItem(\"Markdown Rendered View\"):\n                                md_output = gr.Markdown(\n                                    \"## Please upload an image and click the Parse button for recognition...\",\n                                    label=\"Markdown Preview\",\n                                    max_height=1000,\n                                    latex_delimiters=[\n                                        {\"left\": \"$$\", \"right\": \"$$\", \"display\": True},\n                                        {\"left\": \"$\", \"right\": \"$\", \"display\": False},\n                                    ],\n                                    show_copy_button=False,\n                                    elem_id=\"markdown_output\"\n                                )\n                            \n                            with gr.TabItem(\"Markdown Raw Text\"):\n                                md_raw_output = gr.Textbox(\n                                    value=\"🕐 Waiting for parsing results...\",\n                                    label=\"Markdown Raw Text\",\n                                    max_lines=100,\n                                    lines=38,\n                                    show_copy_button=True,\n                                    elem_id=\"markdown_output\",\n                                    show_label=False\n                                )\n                            \n                            with gr.TabItem(\"JSON Result\"):\n                                json_output = gr.Textbox(\n                                    value=\"🕐 Waiting for parsing results...\",\n                                    label=\"JSON Result\",\n                                    max_lines=100,\n                                    lines=38,\n                                    show_copy_button=True,\n                                    elem_id=\"markdown_output\",\n                                    show_label=False\n                                )\n                \n                # Download Button\n                with gr.Row():\n                    download_btn = gr.DownloadButton(\n                        \"⬇️ Download Results\",\n                        visible=False\n                    )\n        \n        # Event Binding\n        \n        # When the prompt mode changes, update the displayed content\n        prompt_mode.change(\n            fn=update_prompt_display,\n            inputs=prompt_mode,\n            outputs=prompt_display,\n            show_progress=False\n        )\n        \n        # Load image into the annotation component\n        load_btn.click(\n            fn=load_image_to_annotator,\n            inputs=[test_image_input],\n            outputs=annotator,\n            show_progress=False\n        )\n        \n        # Process Inference\n        process_btn.click(\n            fn=process_image_inference_with_annotation,\n            inputs=[\n                annotator, test_image_input,\n                prompt_mode, server_ip, server_port, min_pixels, max_pixels, \n                fitz_preprocess\n            ],\n            outputs=[\n                md_output, info_display, md_raw_output, md_raw_output,\n                download_btn, json_output\n            ],\n            show_progress=True\n        )\n        \n        # Clear Data\n        clear_btn.click(\n            fn=clear_all_data,\n            outputs=[\n                test_image_input, annotator,\n                info_display, md_output, md_raw_output,\n                download_btn, json_output\n            ],\n            show_progress=False\n        )\n    \n    return demo\n\n# ==================== Main Program ====================\nif __name__ == \"__main__\":\n    demo = create_gradio_interface()\n    demo.queue().launch(\n        server_name=\"0.0.0.0\", \n        server_port=7861,  # Use a different port to avoid conflicts\n        debug=True\n    )\n"
  },
  {
    "path": "demo/demo_gradio_batch.py",
    "content": "import os\nimport io\nimport uuid\nimport json\nimport zipfile\nimport tempfile\nimport threading\nimport queue\nimport shutil\nfrom pathlib import Path\nfrom PIL import Image\nimport requests\nimport gradio as gr\nimport re\nimport math\nimport datetime\n\n# Local project imports (assumed available)\nfrom dots_ocr.utils import dict_promptmode_to_prompt\nfrom dots_ocr.utils.consts import MIN_PIXELS, MAX_PIXELS\nfrom dots_ocr.utils.demo_utils.display import read_image\nfrom dots_ocr.parser import DotsOCRParser\n\n# ---------------- Config & globals ----------------\nDEFAULT_CONFIG = {\n    \"ip\": \"127.0.0.1\",\n    \"port_vllm\": 8000,\n    \"min_pixels\": MIN_PIXELS,\n    \"max_pixels\": MAX_PIXELS,\n}\n\n# Absolute constraints discovered from runtime:\nABS_MIN_PIXELS = 3136\nABS_MAX_PIXELS = 11289600\n\ncurrent_config = DEFAULT_CONFIG.copy()\n\n# default parser instance (can be overridden per-task)\ndots_parser = DotsOCRParser(\n    ip=DEFAULT_CONFIG[\"ip\"],\n    port=DEFAULT_CONFIG[\"port_vllm\"],\n    dpi=200,\n    min_pixels=DEFAULT_CONFIG[\"min_pixels\"],\n    max_pixels=DEFAULT_CONFIG[\"max_pixels\"],\n)\n\nRESULTS_CACHE = {}  # rid -> result dict or placeholder\nTASK_QUEUE = queue.Queue()\n# Worker pool for background processing (adjustable via UI)\nWORKER_THREADS = []\nMAX_CONCURRENCY = 6\nTHREAD_LOCK = threading.Lock()\nRETRY_COUNTS = {}  # rid -> attempts\nMAX_AUTO_RETRIES = 5\nRETRY_BACKOFF_BASE = 1.7\nDEFAULT_SCRIPT_TEMPLATE = \"\"\"# 高级脚本使用说明\n# 提供对象: api\n# 日志: 使用 print(...) 或 debug(...) 输出到下方“脚本日志”实时区域。\n# api.get_ids() -> [rid,...] 按当前 UI 顺序返回\n# api.get_status(rid) -> {'status','ui': {'tab','nohf','source'}, 'filtered': bool, 'input_width': int, 'input_height': int}\n# api.get_texts(rid) -> {\n#   'md': 原始 Markdown, 'md_nohf': 原始 NOHF Markdown, 'json': 原始 JSON,\n#   'md_edit': 编辑版 Markdown 或 None, 'md_nohf_edit': 编辑版 NOHF Markdown 或 None, 'json_edit': 编辑版 JSON 或 None\n# }\n# api.choose_texts(rid, prefer_ui=True, prefer_edit=True, prefer_nohf=None) -> {'md','json'}\n#   - prefer_ui: True 时根据当前 UI 的 NOHF/来源选择内容\n#   - prefer_edit: True 时优先用编辑内容（若存在）\n#   - prefer_nohf: 显式指定是否使用 NOHF（覆盖 UI），None 表示跟随 UI\n# api.list_paths(rid) -> {\n#   'temp_dir': str, 'session_id': str,\n#   'result': {'md':path,'md_nohf':path,'json':path,'layout':path or None,'image':path or None},\n#   'edited': {'md':path or None,'md_nohf':path or None,'json':path or None}\n# }\n# api.path_exists(path) -> bool   判断路径是否存在\n# api.build_export(name='custom') -> ExportBuilder\n# ExportBuilder:\n#   .add_text('dir/file.md', '...')            写入文本\n#   .add_bytes('bin/data.bin', b'...')         写入二进制\n#   .add_file('/abs/path/file.md', 'dir/file.md')  拷贝已有文件\n#   .mkdir('subdir/')                           创建目录\n#   .finalize() -> zip_path                     打包为 zip 并返回路径\n#\n# 约定: 定义 main(api) 并返回以下之一：\n# - ExportBuilder 实例（将自动 finalize）\n# - 目录路径或文件路径（目录将被打包为 zip）\n# - None（若存在变量 export=ExportBuilder，将自动 finalize）\n#\n# 示例：按 UI 所见优先使用“编辑源码”与 NOHF，导出每个结果的 md/json，同时附带原始与编辑文件\ndef main(api):\n    ids = api.get_ids()\n    eb = api.build_export('custom_export')\n    for i, rid in enumerate(ids, start=1):\n        st = api.get_status(rid)\n        if st['status'] != 'done':\n            continue\n        choice = api.choose_texts(rid, prefer_ui=True, prefer_edit=True)\n        eb.add_text(f'result_{i}_{rid}/content.md', choice['md'] or '')\n        eb.add_text(f'result_{i}_{rid}/data.json', choice['json'] or '{}')\n        paths = api.list_paths(rid)\n        # 附带原始文件\n        for p in (paths.get('result') or {}).values():\n            if p and api.path_exists(p):\n                name = Path(p).name\n                eb.add_file(p, f'result_{i}_{rid}/raw/{name}')\n        # 附带编辑文件\n        for p in (paths.get('edited') or {}).values():\n            if p and api.path_exists(p):\n                name = Path(p).name\n                eb.add_file(p, f'result_{i}_{rid}/edited/{name}')\n    return eb\n\"\"\"\n\n\n# ---------------- Helpers ----------------\ndef read_image_v2(img):\n    \"\"\"Read image from URL or local path / PIL.Image. Supports file paths and URLs.\"\"\"\n    if isinstance(img, Image.Image):\n        return img\n    if isinstance(img, str) and img.startswith((\"http://\", \"https://\")):\n        with requests.get(img, stream=True) as r:\n            r.raise_for_status()\n            return Image.open(io.BytesIO(r.content)).convert(\"RGB\")\n    if isinstance(img, str) and os.path.exists(img):\n        return Image.open(img).convert(\"RGB\")\n    try:\n        img_res = read_image(img, use_native=True)\n        if isinstance(img_res, tuple) and isinstance(img_res[0], Image.Image):\n            return img_res[0]\n    except Exception:\n        pass\n    raise ValueError(f\"Unsupported image input: {type(img)} / {repr(img)[:200]}\")\n\n\ndef create_temp_session_dir():\n    session_id = uuid.uuid4().hex[:8]\n    temp_dir = os.path.join(tempfile.gettempdir(), f\"dots_ocr_demo_{session_id}\")\n    os.makedirs(temp_dir, exist_ok=True)\n    return temp_dir, session_id\n\n\ndef classify_parse_failure(exc, min_p, max_p):\n    \"\"\"Return a user-friendly error message for known failure causes.\"\"\"\n    msg = str(exc)\n    reasons = []\n    # Absolute & semantic constraints\n    if min_p < ABS_MIN_PIXELS:\n        reasons.append(\n            f\"Min Pixels 过小：{min_p}，必须 >= {ABS_MIN_PIXELS}。建议提高 Min Pixels。\"\n        )\n    if max_p > ABS_MAX_PIXELS:\n        reasons.append(\n            f\"Max Pixels 过大：{max_p}，必须 <= {ABS_MAX_PIXELS}。建议降低 Max Pixels。\"\n        )\n    if min_p >= max_p:\n        reasons.append(\n            f\"像素参数不合法：Min Pixels({min_p}) >= Max Pixels({max_p})，必须满足 Min Pixels < Max Pixels。\"\n        )\n\n    lower = msg.lower()\n    if \"no results returned from parser\" in lower or \"no results returned\" in lower:\n        reasons.append(\n            \"解析未返回结果。可能原因：图像过小、Min Pixels 设置过小或过滤过强。\"\n            f\"建议：Min Pixels >= {ABS_MIN_PIXELS} 且 Max Pixels <= {ABS_MAX_PIXELS}。\"\n        )\n    if \"failed to read input\" in lower or \"cannot identify image file\" in lower:\n        reasons.append(\"无法读取输入文件，请确认文件是否为有效图片或PDF。\")\n    if (\"connection\" in lower and \"refused\" in lower) or (\"connectionerror\" in lower):\n        reasons.append(\"无法连接后端推理服务，请检查 Server IP/Port 与服务状态。\")\n\n    if not reasons:\n        reasons.append(f\"未知错误：{msg}\")\n\n    detail = \"\\n\".join(f\"- {r}\" for r in reasons)\n    cfg = f\"(当前参数：min_pixels={min_p}, max_pixels={max_p})\"\n    return f\"解析失败：\\n{detail}\\n{cfg}\"\n\n\ndef _is_transient_backend_error(exc: Exception):\n    lower = str(exc).lower()\n    # Common signals: connection refused/reset, timeout, gateway, service unavailable\n    keywords = [\n        \"connection refused\",\n        \"connectionerror\",\n        \"timeout\",\n        \"timed out\",\n        \"gateway\",\n        \"service unavailable\",\n        \"failed to establish a new connection\",\n        \"max retries exceeded\",\n        \"read timeout\",\n        \"connect timeout\",\n    ]\n    return any(k in lower for k in keywords)\n\n\ndef parse_image_with_high_level_api(parser, image, prompt_mode, fitz_preprocess=False):\n    \"\"\"\n    Calls parser.parse_image with a PIL image (or accepts image path if parser expects path).\n    Returns dictionary with artifacts. Keeps a temp PNG of the input for traceability.\n    \"\"\"\n    temp_dir, session_id = create_temp_session_dir()\n    if not isinstance(image, Image.Image):\n        image = read_image_v2(image)\n    temp_image_path = os.path.join(temp_dir, f\"input_{session_id}.png\")\n    image.save(temp_image_path, \"PNG\")\n\n    filename = f\"demo_{session_id}\"\n    results = parser.parse_image(\n        input_path=image,\n        filename=filename,\n        prompt_mode=prompt_mode,\n        save_dir=temp_dir,\n        fitz_preprocess=fitz_preprocess,\n    )\n    if not results:\n        raise RuntimeError(\"No results returned from parser\")\n\n    result = results[0]\n    layout_image = None\n    if result.get(\"layout_image_path\") and os.path.exists(result[\"layout_image_path\"]):\n        try:\n            layout_image = Image.open(result[\"layout_image_path\"]).convert(\"RGB\")\n        except Exception:\n            layout_image = None\n\n    cells_data = None\n    if result.get(\"layout_info_path\") and os.path.exists(result[\"layout_info_path\"]):\n        with open(result[\"layout_info_path\"], \"r\", encoding=\"utf-8\") as f:\n            cells_data = json.load(f)\n\n    md_content = None\n    if result.get(\"md_content_path\") and os.path.exists(result[\"md_content_path\"]):\n        with open(result[\"md_content_path\"], \"r\", encoding=\"utf-8\") as f:\n            md_content = f.read()\n\n    md_content_nohf = None\n    if result.get(\"md_content_nohf_path\") and os.path.exists(\n        result[\"md_content_nohf_path\"]\n    ):\n        with open(result[\"md_content_nohf_path\"], \"r\", encoding=\"utf-8\") as f:\n            md_content_nohf = f.read()\n\n    json_code = \"\"\n    if cells_data is not None:\n        try:\n            json_code = json.dumps(cells_data, ensure_ascii=False, indent=2)\n        except Exception:\n            json_code = str(cells_data)\n\n    return {\n        \"original_image\": image,\n        \"layout_image\": layout_image,\n        \"cells_data\": cells_data,\n        \"md_content\": md_content,\n        \"md_content_nohf\": md_content_nohf,\n        \"json_code\": json_code,\n        \"filtered\": result.get(\"filtered\", False),\n        \"temp_dir\": temp_dir,\n        \"session_id\": session_id,\n        \"result_paths\": result,\n        \"input_width\": result.get(\"input_width\", 0),\n        \"input_height\": result.get(\"input_height\", 0),\n        \"input_temp_path\": temp_image_path,\n    }\n\n\ndef _validate_pixels(min_p, max_p):\n    \"\"\"Coerce pixel parameters. Do NOT auto-swap; semantic errors are handled by pre-validation.\"\"\"\n    try:\n        min_p = int(min_p)\n    except Exception:\n        min_p = DEFAULT_CONFIG[\"min_pixels\"]\n    try:\n        max_p = int(max_p)\n    except Exception:\n        max_p = DEFAULT_CONFIG[\"max_pixels\"]\n    if min_p <= 0:\n        min_p = DEFAULT_CONFIG[\"min_pixels\"]\n    if max_p <= 0:\n        max_p = DEFAULT_CONFIG[\"max_pixels\"]\n    return min_p, max_p\n\n\ndef _set_parser_config(server_ip, server_port, min_pixels, max_pixels):\n    min_pixels, max_pixels = _validate_pixels(min_pixels, max_pixels)\n    current_config.update(\n        {\n            \"ip\": server_ip,\n            \"port_vllm\": int(server_port),\n            \"min_pixels\": min_pixels,\n            \"max_pixels\": max_pixels,\n        }\n    )\n    dots_parser.ip = server_ip\n    dots_parser.port = int(server_port)\n    dots_parser.min_pixels = min_pixels\n    dots_parser.max_pixels = max_pixels\n\n\ndef purge_queue(rid):\n    \"\"\"Best-effort remove tasks matching rid from queue.\"\"\"\n    pending = []\n    try:\n        while True:\n            task = TASK_QUEUE.get_nowait()\n            if task and isinstance(task, tuple):\n                if task[0] != rid:\n                    pending.append(task)\n            TASK_QUEUE.task_done()\n    except queue.Empty:\n        pass\n    for t in pending:\n        TASK_QUEUE.put(t)\n\n\n# ---------------- Export helpers ----------------\ndef export_one_rid(rid):\n    st = RESULTS_CACHE.get(rid)\n    if not st:\n        return None\n    temp_dir = st.get(\"temp_dir\")\n    if not temp_dir or not os.path.isdir(temp_dir):\n        return None\n    out_dir, _sess = create_temp_session_dir()\n    zip_path = os.path.join(out_dir, f\"export_{rid}.zip\")\n    with zipfile.ZipFile(zip_path, \"w\", zipfile.ZIP_DEFLATED) as zf:\n        for rt, _, files in os.walk(temp_dir):\n            for f in files:\n                src = os.path.join(rt, f)\n                rel = os.path.relpath(src, temp_dir)\n                zf.write(src, os.path.join(f\"result_{rid}\", rel))\n    return zip_path\n\n\ndef ensure_export_ready(rid):\n    \"\"\"Create and cache export zip path if not present.\"\"\"\n    st = RESULTS_CACHE.get(rid) or {}\n    if not st or st.get(\"status\") != \"done\":\n        return None\n    path = st.get(\"export_path\")\n    if path and os.path.exists(path):\n        return path\n    path = export_one_rid(rid)\n    if path:\n        st[\"export_path\"] = path\n        RESULTS_CACHE[rid] = st\n    return path\n\n\n# ---------------- Script API & execution ----------------\nclass ExportBuilder:\n    def __init__(self, name=None):\n        root, sid = create_temp_session_dir()\n        sub = f\"script_export_{sid}\"\n        if name:\n            sub = f\"{name}_{sid}\"\n        self.root_dir = os.path.join(root, sub)\n        os.makedirs(self.root_dir, exist_ok=True)\n        self._final_zip = None\n\n    def _abspath(self, rel_path: str):\n        rel_path = rel_path.lstrip(\"/\\\\\")\n        return os.path.join(self.root_dir, rel_path)\n\n    def mkdir(self, rel_dir: str):\n        p = self._abspath(rel_dir)\n        os.makedirs(p, exist_ok=True)\n        return p\n\n    def add_text(self, rel_path: str, content: str, encoding: str = \"utf-8\"):\n        p = self._abspath(rel_path)\n        os.makedirs(os.path.dirname(p), exist_ok=True)\n        with open(p, \"w\", encoding=encoding) as f:\n            f.write(\"\" if content is None else str(content))\n        return p\n\n    def add_bytes(self, rel_path: str, data: bytes):\n        p = self._abspath(rel_path)\n        os.makedirs(os.path.dirname(p), exist_ok=True)\n        with open(p, \"wb\") as f:\n            f.write(data or b\"\")\n        return p\n\n    def add_file(self, src_path: str, dest_rel_path: str = None):\n        if not src_path or not os.path.exists(src_path):\n            return None\n        dest_rel_path = dest_rel_path or os.path.basename(src_path)\n        p = self._abspath(dest_rel_path)\n        os.makedirs(os.path.dirname(p), exist_ok=True)\n        shutil.copy2(src_path, p)\n        return p\n\n    def finalize(self, zip_name: str = None):\n        if self._final_zip and os.path.exists(self._final_zip):\n            return self._final_zip\n        out_dir, sid = create_temp_session_dir()\n        zip_name = zip_name or f\"script_export_{sid}.zip\"\n        zip_path = os.path.join(out_dir, zip_name)\n        with zipfile.ZipFile(zip_path, \"w\", zipfile.ZIP_DEFLATED) as zf:\n            for rt, _, files in os.walk(self.root_dir):\n                for f in files:\n                    src = os.path.join(rt, f)\n                    rel = os.path.relpath(src, self.root_dir)\n                    zf.write(src, rel)\n        self._final_zip = zip_path\n        return zip_path\n\n\nclass ScriptAPI:\n    def __init__(self, ids_snapshot):\n        self._ids = list(ids_snapshot or [])\n\n    def get_ids(self):\n        return list(self._ids)\n\n    def get_status(self, rid: str):\n        st = dict(RESULTS_CACHE.get(rid) or {})\n        ui = dict(st.get(\"ui\") or {})\n        return {\n            \"status\": st.get(\"status\", \"pending\"),\n            \"ui\": {\n                \"tab\": ui.get(\"tab\", \"md\"),\n                \"nohf\": bool(ui.get(\"nohf\", False)),\n                \"source\": ui.get(\"source\", \"源码\"),\n            },\n            \"filtered\": bool(st.get(\"filtered\", False)),\n            \"input_width\": int(st.get(\"input_width\", 0) or 0),\n            \"input_height\": int(st.get(\"input_height\", 0) or 0),\n        }\n\n    def get_texts(self, rid: str):\n        st = dict(RESULTS_CACHE.get(rid) or {})\n        edits = dict(st.get(\"edits\") or {})\n        return {\n            \"md\": st.get(\"md_content\") or \"\",\n            \"md_nohf\": st.get(\"md_content_nohf\") or \"\",\n            \"json\": st.get(\"json_code\") or \"\",\n            \"md_edit\": edits.get(\"md\"),\n            \"md_nohf_edit\": edits.get(\"nohf\"),\n            \"json_edit\": edits.get(\"json\"),\n        }\n\n    def choose_texts(\n        self,\n        rid: str,\n        prefer_ui: bool = True,\n        prefer_edit: bool = True,\n        prefer_nohf: bool | None = None,\n    ):\n        st = dict(RESULTS_CACHE.get(rid) or {})\n        ui = dict(st.get(\"ui\") or {})\n        # UI 指示\n        ui_nohf = bool(ui.get(\"nohf\", False))\n        ui_source_is_edit = str(ui.get(\"source\", \"源码\")) == \"编辑源码\"\n        # 选择 nohf\n        use_nohf = ui_nohf if prefer_nohf is None else bool(prefer_nohf)\n        # 选择是否优先编辑\n        prefer_edit_final = bool(prefer_edit or (prefer_ui and ui_source_is_edit))\n        t = self.get_texts(rid)\n        # Markdown\n        md_orig = t[\"md_nohf\"] if use_nohf else t[\"md\"]\n        md_edit = t[\"md_nohf_edit\"] if use_nohf else t[\"md_edit\"]\n        md = (md_edit if (prefer_edit_final and md_edit is not None) else md_orig) or \"\"\n        # JSON\n        json_text = (\n            t[\"json_edit\"]\n            if (prefer_edit_final and t.get(\"json_edit\") is not None)\n            else t[\"json\"]\n        ) or \"\"\n        return {\"md\": md, \"json\": json_text}\n\n    def list_paths(self, rid: str):\n        st = dict(RESULTS_CACHE.get(rid) or {})\n        rp = dict(st.get(\"result_paths\") or {})\n        md_p = rp.get(\"md_content_path\")\n        nohf_p = rp.get(\"md_content_nohf_path\")\n        json_p = rp.get(\"layout_info_path\") or rp.get(\"json_path\")\n        image_p = rp.get(\"layout_image_path\") or None\n        # 编辑路径（若存在）\n        edited_md = None\n        edited_nohf = None\n        edited_json = None\n        try:\n            edited_md = _edited_filepath(st, \"md\")\n            if not os.path.exists(edited_md):\n                edited_md = None\n        except Exception:\n            edited_md = None\n        try:\n            edited_nohf = _edited_filepath(st, \"nohf\")\n            if not os.path.exists(edited_nohf):\n                edited_nohf = None\n        except Exception:\n            edited_nohf = None\n        try:\n            edited_json = _edited_filepath(st, \"json\")\n            if not os.path.exists(edited_json):\n                edited_json = None\n        except Exception:\n            edited_json = None\n        return {\n            \"temp_dir\": st.get(\"temp_dir\"),\n            \"session_id\": st.get(\"session_id\"),\n            \"result\": {\n                \"md\": md_p if (md_p and os.path.exists(md_p)) else None,\n                \"md_nohf\": nohf_p if (nohf_p and os.path.exists(nohf_p)) else None,\n                \"json\": json_p if (json_p and os.path.exists(json_p)) else None,\n                \"layout\": image_p if (image_p and os.path.exists(image_p)) else None,\n                \"input_image\": (\n                    st.get(\"input_temp_path\")\n                    if (\n                        st.get(\"input_temp_path\")\n                        and os.path.exists(st.get(\"input_temp_path\"))\n                    )\n                    else None\n                ),\n            },\n            \"edited\": {\n                \"md\": edited_md,\n                \"md_nohf\": edited_nohf,\n                \"json\": edited_json,\n            },\n        }\n\n    def path_exists(self, p: str) -> bool:\n        try:\n            return bool(p) and os.path.exists(p)\n        except Exception:\n            return False\n\n    def build_export(self, name: str | None = None):\n        return ExportBuilder(name=name)\n\n\ndef _safe_builtins():\n    base = (\n        __builtins__\n        if isinstance(__builtins__, dict)\n        else getattr(__builtins__, \"__dict__\", {})\n    )\n    allow = [\n        \"abs\",\n        \"min\",\n        \"max\",\n        \"sum\",\n        \"len\",\n        \"range\",\n        \"enumerate\",\n        \"map\",\n        \"filter\",\n        \"zip\",\n        \"list\",\n        \"dict\",\n        \"set\",\n        \"tuple\",\n        \"str\",\n        \"int\",\n        \"float\",\n        \"bool\",\n        \"print\",\n        \"any\",\n        \"all\",\n        \"sorted\",\n    ]\n    return {k: base[k] for k in allow if k in base}\n\n\ndef run_user_script(script_code: str, ids_snapshot):\n    \"\"\"\n    非流式执行用户脚本，捕获标准输出并返回（zip_path, logs）。\n    \"\"\"\n    api = ScriptAPI(ids_snapshot)\n    ns = {\n        \"__builtins__\": _safe_builtins(),\n        \"api\": api,\n        \"json\": json,\n        \"re\": re,\n        \"math\": math,\n        \"datetime\": datetime,\n        \"Path\": Path,\n        \"io\": io,\n        \"ExportBuilder\": ExportBuilder,\n    }\n    import contextlib\n    from io import StringIO\n\n    buf = StringIO()\n    zip_path = None\n    try:\n        code = script_code or \"\"\n        with contextlib.redirect_stdout(buf):\n            exec(code, ns, ns)\n            result = None\n            main_fn = ns.get(\"main\")\n            if callable(main_fn):\n                result = main_fn(api)\n            else:\n                result = ns.get(\"RESULT\") or ns.get(\"OUTPUT_PATH\")\n            if isinstance(result, ExportBuilder):\n                zip_path = result.finalize()\n            elif isinstance(result, str) and result:\n                if os.path.isdir(result):\n                    eb = ExportBuilder(\"script_dir_export\")\n                    for rt, _, files in os.walk(result):\n                        for f in files:\n                            src = os.path.join(rt, f)\n                            rel = os.path.relpath(src, result)\n                            eb.add_file(src, rel)\n                    zip_path = eb.finalize()\n                elif os.path.exists(result):\n                    zip_path = result\n            if not zip_path:\n                exp = ns.get(\"export\")\n                if isinstance(exp, ExportBuilder):\n                    zip_path = exp.finalize()\n    except Exception as e:\n        err = f\"[Script Error] {type(e).__name__}: {e}\"\n        return None, (buf.getvalue() + \"\\n\" + err)\n    return (\n        zip_path if (zip_path and os.path.exists(zip_path)) else None\n    ), buf.getvalue()\n\n\ndef run_user_script_stream(script_code: str, ids_snapshot):\n    \"\"\"生成器：实时输出日志，并在结束时返回下载地址与完成状态。\"\"\"\n    # 日志队列\n    log_q = queue.Queue()\n\n    def _emit(kind, payload=None):\n        log_q.put((kind, payload))\n\n    def debug(*args, **kwargs):\n        text = \" \".join(str(a) for a in args)\n        if text:\n            _emit(\"log\", text)\n\n    # 准备脚本命名空间（与非流式版本一致，但覆盖 print/debug）\n    api = ScriptAPI(ids_snapshot)\n    ns = {\n        \"__builtins__\": _safe_builtins(),\n        \"api\": api,\n        \"json\": json,\n        \"re\": re,\n        \"math\": math,\n        \"datetime\": datetime,\n        \"Path\": Path,\n        \"io\": io,\n        \"ExportBuilder\": ExportBuilder,\n        # 专用日志函数\n        \"debug\": debug,\n        \"print\": debug,\n    }\n\n    result_holder = {\"zip_path\": None, \"error\": None}\n\n    def _worker():\n        try:\n            code = script_code or \"\"\n            exec(code, ns, ns)\n            res = None\n            main_fn = ns.get(\"main\")\n            if callable(main_fn):\n                res = main_fn(api)\n            else:\n                res = ns.get(\"RESULT\") or ns.get(\"OUTPUT_PATH\")\n            zip_path = None\n            if isinstance(res, ExportBuilder):\n                zip_path = res.finalize()\n            elif isinstance(res, str) and res:\n                if os.path.isdir(res):\n                    eb = ExportBuilder(\"script_dir_export\")\n                    for rt, _, files in os.walk(res):\n                        for f in files:\n                            src = os.path.join(rt, f)\n                            rel = os.path.relpath(src, res)\n                            eb.add_file(src, rel)\n                    zip_path = eb.finalize()\n                elif os.path.exists(res):\n                    zip_path = res\n            if not zip_path:\n                exp = ns.get(\"export\")\n                if isinstance(exp, ExportBuilder):\n                    zip_path = exp.finalize()\n            result_holder[\"zip_path\"] = (\n                zip_path if (zip_path and os.path.exists(zip_path)) else None\n            )\n        except Exception as e:\n            result_holder[\"error\"] = f\"[Script Error] {type(e).__name__}: {e}\"\n        finally:\n            _emit(\"done\", None)\n\n    # 启动脚本线程\n    t = threading.Thread(target=_worker, daemon=True)\n    t.start()\n\n    # 初始状态显示\n    spinner_html = (\n        \"<div style='display:flex;align-items:center;gap:8px;'>\"\n        \"<svg width='18' height='18' viewBox='0 0 50 50' style='animation:spin 1s linear infinite'>\"\n        \"<circle cx='25' cy='25' r='20' stroke='#FF576D' stroke-width='4' fill='none' stroke-linecap='round' \"\n        \"stroke-dasharray='31.4 31.4'>\"  # dash pattern for arc\n        \"</circle></svg>\"\n        \"<style>@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}</style>\"\n        \"<span>脚本运行中…</span></div>\"\n    )\n    log_buf_lines = []\n    # 初始仅显示运行中动画，日志区域留空\n    yield None, spinner_html, \"\"\n\n    # 实时拉取日志并渲染\n    while True:\n        try:\n            kind, payload = log_q.get(timeout=0.2)\n        except queue.Empty:\n            if not t.is_alive():\n                # 线程已结束但没有新的事件，跳到收尾\n                break\n            else:\n                continue\n\n        if kind == \"log\":\n            # 追加日志并推送更新\n            if isinstance(payload, str):\n                for line in payload.splitlines() or [payload]:\n                    if line.strip() == \"\":\n                        continue\n                    log_buf_lines.append(line)\n            yield None, spinner_html, \"```\\n\" + \"\\n\".join(\n                log_buf_lines[-200:]\n            ) + \"\\n```\"  # 限制最后200行\n        elif kind == \"done\":\n            break\n\n    # 收尾：根据结果/错误输出最终状态\n    if result_holder.get(\"error\"):\n        log_buf_lines.append(result_holder[\"error\"])\n        status_html = (\n            \"<div style='display:flex;align-items:center;gap:8px;color:#fca5a5'>\"\n            \"<span>❌ 脚本执行失败</span></div>\"\n        )\n        yield None, status_html, \"```\\n\" + \"\\n\".join(log_buf_lines[-500:]) + \"\\n```\"\n    else:\n        status_html = (\n            \"<div style='display:flex;align-items:center;gap:8px;color:#86efac'>\"\n            \"<span>✅ 脚本执行完成</span></div>\"\n        )\n        if result_holder.get(\"zip_path\"):\n            yield result_holder[\"zip_path\"], status_html, \"```\\n\" + \"\\n\".join(\n                log_buf_lines[-500:]\n            ) + \"\\n```\"\n        else:\n            log_buf_lines.append(\n                \"(无可下载文件返回，若需导出请返回 ExportBuilder 或目录/文件路径)\"\n            )\n            yield None, status_html, \"```\\n\" + \"\\n\".join(log_buf_lines[-500:]) + \"\\n```\"\n    \"\"\"\n    执行用户脚本，返回 (zip_path or None, log_text)\n    \"\"\"\n    api = ScriptAPI(ids_snapshot)\n    ns = {\n        \"__builtins__\": _safe_builtins(),\n        \"api\": api,\n        # 常用库（只读注入）\n        \"json\": json,\n        \"re\": re,\n        \"math\": math,\n        \"datetime\": datetime,\n        \"Path\": Path,\n        \"io\": io,\n        # 导出构建器类型（如需构造）\n        \"ExportBuilder\": ExportBuilder,\n    }\n    import contextlib\n    from io import StringIO\n\n    buf = StringIO()\n    zip_path = None\n    try:\n        code = script_code or \"\"\n        with contextlib.redirect_stdout(buf):\n            exec(code, ns, ns)\n            result = None\n            main_fn = ns.get(\"main\")\n            if callable(main_fn):\n                result = main_fn(api)\n            else:\n                result = ns.get(\"RESULT\") or ns.get(\"OUTPUT_PATH\")\n            # 结果归档处理\n            if isinstance(result, ExportBuilder):\n                zip_path = result.finalize()\n            elif isinstance(result, str) and result:\n                if os.path.isdir(result):\n                    eb = ExportBuilder(\"script_dir_export\")\n                    for rt, _, files in os.walk(result):\n                        for f in files:\n                            src = os.path.join(rt, f)\n                            rel = os.path.relpath(src, result)\n                            eb.add_file(src, rel)\n                    zip_path = eb.finalize()\n                elif os.path.exists(result):\n                    zip_path = result\n            if not zip_path:\n                exp = ns.get(\"export\")\n                if isinstance(exp, ExportBuilder):\n                    zip_path = exp.finalize()\n    except Exception as e:\n        err = f\"[Script Error] {type(e).__name__}: {e}\"\n        return None, (buf.getvalue() + \"\\n\" + err)\n    return (\n        zip_path if (zip_path and os.path.exists(zip_path)) else None\n    ), buf.getvalue()\n\n\ndef export_selected_rids(ids, selected_labels):\n    \"\"\"\n    Build a combined zip for multiple selected results based on their current images (no reupload).\n    Only includes items with status == 'done'.\n    \"\"\"\n    if not ids or not selected_labels:\n        return None\n    # Map labels \"Result N\" -> indices\n    sel_indices = []\n    for label in selected_labels:\n        try:\n            idx = int(str(label).split()[-1]) - 1\n            if 0 <= idx < len(ids):\n                sel_indices.append(idx)\n        except Exception:\n            continue\n    if not sel_indices:\n        return None\n\n    out_dir, session_id = create_temp_session_dir()\n    zip_path = os.path.join(out_dir, f\"export_selected_{session_id}.zip\")\n    with zipfile.ZipFile(zip_path, \"w\", zipfile.ZIP_DEFLATED) as zf:\n        for i in sel_indices:\n            rid = ids[i]\n            st = RESULTS_CACHE.get(rid) or {}\n            if st.get(\"status\") != \"done\":\n                continue\n            temp_dir = st.get(\"temp_dir\")\n            if not temp_dir or not os.path.isdir(temp_dir):\n                # fallback: ensure individual export then include that zip\n                single_zip = ensure_export_ready(rid)\n                if single_zip and os.path.exists(single_zip):\n                    zf.write(single_zip, os.path.join(f\"result_{i+1}_{rid}.zip\"))\n                continue\n            base_dir = f\"result_{i+1}_{rid}\"\n            for rt, _, files in os.walk(temp_dir):\n                for f in files:\n                    src = os.path.join(rt, f)\n                    rel = os.path.relpath(src, temp_dir)\n                    zf.write(src, os.path.join(base_dir, rel))\n    return zip_path if os.path.exists(zip_path) else None\n\n\n# --------- Edited sources helpers ----------\ndef _get_base_name_from_result(st: dict):\n    \"\"\"Infer base filename like 'demo_xxx' from result paths or session id.\"\"\"\n    rp = st.get(\"result_paths\") or {}\n    for key in (\"md_content_path\", \"md_content_nohf_path\", \"layout_info_path\"):\n        p = rp.get(key)\n        if p and isinstance(p, str):\n            base = os.path.splitext(os.path.basename(p))[0]\n            if key == \"md_content_nohf_path\" and base.endswith(\"_nohf\"):\n                base = base[: -len(\"_nohf\")]\n            return base\n    sid = st.get(\"session_id\")\n    if sid:\n        return f\"demo_{sid}\"\n    return f\"demo_{uuid.uuid4().hex[:8]}\"\n\n\ndef _edited_dir_for(st: dict):\n    temp_dir = st.get(\"temp_dir\")\n    if not temp_dir:\n        temp_dir, _ = create_temp_session_dir()\n        st[\"temp_dir\"] = temp_dir\n    d = os.path.join(temp_dir, \"edited\")\n    os.makedirs(d, exist_ok=True)\n    return d\n\n\ndef _edited_filepath(st: dict, which: str):\n    \"\"\"\n    which in {'md','nohf','json'}\n    \"\"\"\n    base = _get_base_name_from_result(st)\n    if which == \"md\":\n        name = f\"{base}.md\"\n    elif which == \"nohf\":\n        name = f\"{base}_nohf.md\"\n    elif which == \"json\":\n        name = f\"{base}.json\"\n    else:\n        raise ValueError(f\"unknown edited type: {which}\")\n    return os.path.join(_edited_dir_for(st), name)\n\n\ndef _save_edited_to_disk(st: dict, which: str, content: str):\n    path = _edited_filepath(st, which)\n    with open(path, \"w\", encoding=\"utf-8\") as f:\n        f.write(content if content is not None else \"\")\n    return path\n\n\ndef _delete_edited_from_disk(st: dict, which: str):\n    try:\n        path = _edited_filepath(st, which)\n        if os.path.exists(path):\n            os.remove(path)\n    except Exception:\n        pass\n\n\ndef _invalidate_export_zip(rid: str):\n    st = RESULTS_CACHE.get(rid) or {}\n    old = st.get(\"export_path\")\n    if old and isinstance(old, str) and os.path.exists(old):\n        try:\n            os.remove(old)\n        except Exception:\n            pass\n    if \"export_path\" in st:\n        st[\"export_path\"] = None\n    RESULTS_CACHE[rid] = st\n\n\n# ---------------- UI state helpers (per-card) ----------------\ndef _default_ui_state():\n    # 增加 source: '源码' 或 '编辑源码'\n    return {\"preview\": True, \"nohf\": False, \"tab\": \"md\", \"source\": \"源码\"}\n\n\ndef _ensure_ui_state(rid):\n    st = RESULTS_CACHE.get(rid) or {}\n    ui = st.get(\"ui\")\n    if not isinstance(ui, dict):\n        ui = _default_ui_state()\n        st[\"ui\"] = ui\n        RESULTS_CACHE[rid] = st\n    else:\n        # 兼容旧状态缺少新字段\n        if \"source\" not in ui:\n            ui[\"source\"] = \"源码\"\n        if \"tab\" not in ui:\n            ui[\"tab\"] = \"md\"\n        if \"preview\" not in ui:\n            ui[\"preview\"] = True\n        if \"nohf\" not in ui:\n            ui[\"nohf\"] = False\n        RESULTS_CACHE[rid] = st\n    return ui\n\n\n# ---------------- Background worker ----------------\ndef background_processor():\n    while True:\n        try:\n            task = TASK_QUEUE.get(timeout=1)\n        except queue.Empty:\n            continue\n        if task is None:\n            # Important: mark done for sentinel to keep queue counters balanced\n            try:\n                TASK_QUEUE.task_done()\n            finally:\n                pass\n            break\n        rid, filepath, prompt_mode, server_ip, server_port, min_p, max_p, fitz_flag = (\n            task\n        )\n        image = None\n        try:\n            # Build parser instance for this task\n            local_parser = DotsOCRParser(\n                ip=server_ip,\n                port=int(server_port),\n                dpi=200,\n                min_pixels=min_p,\n                max_pixels=max_p,\n            )\n\n            # Read image\n            try:\n                fp_lower = str(filepath).lower() if isinstance(filepath, str) else \"\"\n                if fitz_flag or fp_lower.endswith(\".pdf\"):\n                    try:\n                        import fitz as _fitz\n\n                        doc = _fitz.open(filepath)\n                        page = doc.load_page(0)\n                        pix = page.get_pixmap()\n                        mode = \"RGBA\" if pix.alpha else \"RGB\"\n                        image = Image.frombytes(\n                            mode, (pix.width, pix.height), pix.samples\n                        )\n                        doc.close()\n                    except Exception:\n                        image = read_image_v2(filepath)\n                else:\n                    image = read_image_v2(filepath)\n            except Exception as e:\n                raise RuntimeError(f\"Failed to read input {filepath}: {e}\")\n\n            # Parse\n            result = parse_image_with_high_level_api(\n                local_parser, image, prompt_mode, fitz_preprocess=fitz_flag\n            )\n            result[\"status\"] = \"done\"\n\n            # Preserve source/input path but prefer prev.source_path if available\n            prev = RESULTS_CACHE.get(rid) or {}\n\n            # Preserve UI state across re-parses/results\n            prev_ui = prev.get(\"ui\") if isinstance(prev, dict) else None\n            result[\"ui\"] = prev_ui if isinstance(prev_ui, dict) else _default_ui_state()\n\n            if isinstance(prev, dict) and isinstance(prev.get(\"edits\"), dict):\n                result[\"edits\"] = dict(prev.get(\"edits\"))\n\n            if isinstance(prev, dict) and prev.get(\"source_path\"):\n                result[\"source_path\"] = prev.get(\"source_path\")\n            else:\n                if isinstance(filepath, str) and os.path.exists(filepath):\n                    result[\"source_path\"] = filepath\n                else:\n                    result[\"source_path\"] = result.get(\"input_temp_path\")\n\n            if isinstance(prev, dict) and prev.get(\"input_path\"):\n                result[\"input_path\"] = prev.get(\"input_path\")\n\n            # Commit result\n            RESULTS_CACHE[rid] = result\n\n            # Pre-build export zip for first-click download\n            try:\n                zip_path = ensure_export_ready(rid)\n                if zip_path:\n                    result = RESULTS_CACHE.get(rid, result)\n                    result[\"export_path\"] = zip_path\n                    RESULTS_CACHE[rid] = result\n            except Exception:\n                pass\n\n        except Exception as e:\n            # Auto-retry for transient backend errors (e.g., server down temporarily)\n            if _is_transient_backend_error(e):\n                attempts = RETRY_COUNTS.get(rid, 0)\n                if attempts < MAX_AUTO_RETRIES:\n                    RETRY_COUNTS[rid] = attempts + 1\n                    delay = min(10.0, (RETRY_BACKOFF_BASE**attempts))\n                    # keep state pending, annotate attempts\n                    prev = RESULTS_CACHE.get(rid, {}) or {}\n                    pend_state = dict(prev)\n                    pend_state.update(\n                        {\n                            \"status\": \"pending\",\n                            \"retry_attempts\": attempts + 1,\n                        }\n                    )\n                    RESULTS_CACHE[rid] = pend_state\n\n                    # Re-enqueue after delay on a timer to avoid blocking worker\n                    def _requeue_later():\n                        TASK_QUEUE.put(\n                            (\n                                rid,\n                                filepath,\n                                prompt_mode,\n                                server_ip,\n                                int(server_port),\n                                min_p,\n                                max_p,\n                                fitz_flag,\n                            )\n                        )\n\n                    threading.Timer(delay, _requeue_later).start()\n                    # Do not mark error; move on\n                    continue\n\n            # Build a rich error state that preserves re-parse materials\n            prev = RESULTS_CACHE.get(rid, {}) or {}\n            err_state = dict(prev)  # preserve input_path etc.\n            err_state[\"status\"] = \"error\"\n            err_state[\"md_content\"] = classify_parse_failure(e, min_p, max_p)\n\n            # Save a temporary PNG for re-parse if we have an image in memory\n            if isinstance(image, Image.Image):\n                try:\n                    tmp_dir, _sid = create_temp_session_dir()\n                    tmp_path = os.path.join(tmp_dir, f\"error_input_{rid}.png\")\n                    image.save(tmp_path, \"PNG\")\n                    err_state[\"original_image\"] = image\n                    err_state[\"input_temp_path\"] = tmp_path\n                    err_state[\"temp_dir\"] = tmp_dir\n                except Exception:\n                    err_state[\"original_image\"] = image\n            if isinstance(filepath, str) and filepath:\n                err_state.setdefault(\"source_path\", filepath)\n\n            # Preserve UI state if missing\n            if not isinstance(err_state.get(\"ui\"), dict):\n                err_state[\"ui\"] = _default_ui_state()\n\n            RESULTS_CACHE[rid] = err_state\n        finally:\n            # Mark the non-sentinel task as done\n            try:\n                # If previous branch already marked sentinel done, skip double mark\n                if task is not None:\n                    TASK_QUEUE.task_done()\n            except Exception:\n                pass\n\n\ndef _stop_all_workers():\n    \"\"\"Stop all worker threads gracefully by sending sentinels and joining.\"\"\"\n    global WORKER_THREADS\n    with THREAD_LOCK:\n        n = len(WORKER_THREADS)\n        if n == 0:\n            return\n        # Send one sentinel per worker\n        for _ in range(n):\n            TASK_QUEUE.put(None)\n        # Join all workers\n        for t in WORKER_THREADS:\n            try:\n                t.join(timeout=5.0)\n            except Exception:\n                pass\n        WORKER_THREADS = []\n\n\ndef _start_workers(count: int):\n    \"\"\"Start exactly `count` worker threads if not already running.\"\"\"\n    global WORKER_THREADS\n    with THREAD_LOCK:\n        running = len(WORKER_THREADS)\n        need = max(0, int(count) - running)\n        for _ in range(need):\n            t = threading.Thread(target=background_processor, daemon=True)\n            t.start()\n            WORKER_THREADS.append(t)\n\n\ndef start_background_processor():\n    \"\"\"Ensure at least one worker is running (used by legacy calls).\"\"\"\n    _start_workers(max(1, MAX_CONCURRENCY))\n\n\ndef set_max_concurrency(n: int):\n    \"\"\"Restart worker pool to match desired concurrency.\"\"\"\n    global MAX_CONCURRENCY\n    n = int(n) if isinstance(n, (int, float)) else 1\n    if n <= 0:\n        n = 1\n    MAX_CONCURRENCY = n\n    # Restart workers to apply new concurrency\n    _stop_all_workers()\n    _start_workers(MAX_CONCURRENCY)\n\n\n# ---------------- Queueing / task helpers ----------------\ndef _pixel_reasons(min_p, max_p):\n    reasons = []\n    if min_p < ABS_MIN_PIXELS:\n        reasons.append(f\"Min Pixels 过小：{min_p}，必须 >= {ABS_MIN_PIXELS}。\")\n    if max_p > ABS_MAX_PIXELS:\n        reasons.append(f\"Max Pixels 过大：{max_p}，必须 <= {ABS_MAX_PIXELS}。\")\n    if min_p >= max_p:\n        reasons.append(\n            f\"像素参数不合法：Min Pixels({min_p}) >= Max Pixels({max_p})，必须满足 Min Pixels < Max Pixels。\"\n        )\n    return reasons\n\n\ndef add_tasks_to_queue(\n    file_list, prompt_mode, server_ip, server_port, min_p, max_p, fitz, cur_ids\n):\n    \"\"\"Queue uploaded file paths (expects file_list of local file paths or tuples (parse_path, source_path)).\"\"\"\n    if not file_list:\n        return cur_ids, \"No images uploaded.\"\n\n    min_p, max_p = _validate_pixels(min_p, max_p)\n    start_background_processor()\n\n    ids = list(cur_ids or [])\n    skipped = 0\n    queued = 0\n\n    for fp in file_list:\n        # Normalize: support tuple (parse_path, source_path)\n        parse_fp = None\n        source_fp = None\n        if isinstance(fp, (list, tuple)) and len(fp) >= 1:\n            parse_fp = fp[0]\n            # If tuple contains original source as second element, use it\n            source_fp = fp[1] if len(fp) >= 2 else fp[0]\n        else:\n            parse_fp = fp\n            source_fp = fp\n\n        if isinstance(parse_fp, (list, tuple)):\n            parse_fp = parse_fp[0] if len(parse_fp) > 0 else None\n\n        rid = uuid.uuid4().hex[:8]\n        ids.append(rid)\n\n        # placeholder with input_path so re-parse works even before parse\n        RESULTS_CACHE[rid] = {\n            \"status\": \"pending\",\n            \"input_path\": parse_fp,\n            \"source_path\": source_fp,\n            \"ui\": _default_ui_state(),  # 初始化每项的独立 UI 状态\n        }\n\n        reason = _pixel_reasons(min_p, max_p)\n        if reason:\n            RESULTS_CACHE[rid] = {\n                \"status\": \"error\",\n                \"md_content\": \"参数越界，未开始解析：\\n\"\n                + \"\\n\".join(f\"- {r}\" for r in reason)\n                + f\"\\n(当前参数：min_pixels={min_p}, max_pixels={max_p})\",\n                \"input_path\": parse_fp,\n                \"source_path\": source_fp,\n                \"ui\": _default_ui_state(),\n            }\n            skipped += 1\n            continue\n\n        TASK_QUEUE.put(\n            (\n                rid,\n                parse_fp,\n                prompt_mode,\n                server_ip,\n                int(server_port),\n                min_p,\n                max_p,\n                fitz,\n            )\n        )\n        queued += 1\n\n    info = f\"Queued {queued} item(s).\"\n    if skipped:\n        info += f\" Skipped {skipped} due to invalid pixel limits.\"\n    return ids, info\n\n\ndef enqueue_single_reparse(\n    rid, reupload_path, prompt_mode, server_ip, server_port, min_p, max_p, fitz\n):\n    \"\"\"\n    Enqueue a reparse for single result id.\n    Path selection priority:\n      reupload_path -> result.source_path -> result.input_temp_path -> result.input_path -> result.original_image (dump to temp PNG)\n    \"\"\"\n    min_p, max_p = _validate_pixels(min_p, max_p)\n    start_background_processor()\n    st = RESULTS_CACHE.get(rid, {}) or {}\n\n    # Pixel constraints: if invalid, set error state and return (do not enqueue)\n    reason = _pixel_reasons(min_p, max_p)\n    if reason:\n        new_state = st.copy()\n        new_state.update(\n            {\n                \"status\": \"error\",\n                \"md_content\": \"参数越界，未开始解析：\\n\"\n                + \"\\n\".join(f\"- {r}\" for r in reason)\n                + f\"\\n(当前参数：min_pixels={min_p}, max_pixels={max_p})\",\n            }\n        )\n        # 保留 UI 状态\n        if \"ui\" not in new_state:\n            new_state[\"ui\"] = _default_ui_state()\n        RESULTS_CACHE[rid] = new_state\n        return\n\n    if isinstance(reupload_path, (tuple, list)):\n        reupload_path = reupload_path[0] if len(reupload_path) > 0 else None\n\n    filepath = None\n    if reupload_path:\n        filepath = reupload_path\n    elif st.get(\"source_path\"):\n        filepath = st.get(\"source_path\")\n    elif st.get(\"input_temp_path\"):\n        filepath = st.get(\"input_temp_path\")\n    elif st.get(\"input_path\"):\n        filepath = st.get(\"input_path\")\n    else:\n        img = st.get(\"original_image\")\n        if isinstance(img, Image.Image):\n            tmp_dir, _ = create_temp_session_dir()\n            tmp_path = os.path.join(tmp_dir, f\"reparse_{rid}.png\")\n            try:\n                img.save(tmp_path, \"PNG\")\n                filepath = tmp_path\n            except Exception:\n                filepath = None\n\n    if not filepath:\n        new_state = st.copy()\n        new_state.update(\n            {\n                \"status\": \"error\",\n                \"md_content\": \"重解析失败：未找到可用的图片来源。请重新上传图片或检查缓存目录。\",\n            }\n        )\n        if \"ui\" not in new_state:\n            new_state[\"ui\"] = _default_ui_state()\n        RESULTS_CACHE[rid] = new_state\n        return\n\n    new_state = st.copy()\n    new_state.update(\n        {\n            \"status\": \"pending\",\n            \"input_path\": filepath,\n            \"last_used_config\": {\n                \"ip\": server_ip,\n                \"port\": int(server_port),\n                \"min_pixels\": min_p,\n                \"max_pixels\": max_p,\n                \"prompt_mode\": prompt_mode,\n            },\n        }\n    )\n    # 保留 UI 状态\n    if \"ui\" not in new_state:\n        new_state[\"ui\"] = _default_ui_state()\n    RESULTS_CACHE[rid] = new_state\n    TASK_QUEUE.put(\n        (rid, filepath, prompt_mode, server_ip, int(server_port), min_p, max_p, fitz)\n    )\n\n\ndef delete_one(ids, rid, tick):\n    new_ids = [x for x in (ids or []) if x != rid]\n    st = RESULTS_CACHE.get(rid)\n    temp_dir = st.get(\"temp_dir\") if st else None\n    if rid in RESULTS_CACHE:\n        del RESULTS_CACHE[rid]\n    if rid in RETRY_COUNTS:\n        del RETRY_COUNTS[rid]\n    purge_queue(rid)\n    if temp_dir and os.path.exists(temp_dir):\n        threading.Thread(\n            target=lambda: shutil.rmtree(temp_dir, ignore_errors=True), daemon=True\n        ).start()\n    return new_ids, int(tick or 0) + 1\n\n\n# ---------------- Gradio UI ----------------\ndef create_gradio_interface():\n    css = \"\"\"\n    /* basic theme */\n    :root { --bg:#0b1220; --card:#111827; --muted:#9ca3af; --accent:#FF576D; --text:#e5e7eb; }\n    body, .gradio-container { background: var(--bg) !important; color: var(--text) !important; }\n    .result-card { background: var(--card); border:1px solid #1f2937; border-radius:8px; padding:10px; margin-bottom:12px; }\n    .muted { color: var(--muted); font-size:0.9em; }\n\n    /* skeleton shimmer */\n    .skeleton { position:relative; overflow:hidden; background:#0f172a; border-radius:6px; }\n    .skeleton::after {\n      content:\"\"; position:absolute; inset:0; transform:translateX(-100%);\n      background:linear-gradient(90deg, rgba(255,255,255,0), rgba(255,255,255,0.06), rgba(255,255,255,0));\n      animation:shimmer 1.2s infinite;\n    }\n    @keyframes shimmer { 100% { transform:translateX(100%);} }\n\n    /* Hide unwanted footer/buttons (robust selectors) */\n    footer, .footer, #footer, footer[role=\"contentinfo\"] { display:none !important; }\n    [aria-label=\"Use via API\"], [aria-label*=\"API\"], [title*=\"API\"], a[href*=\"/api\"], a[href*=\"api_docs\"], a[href*=\"gradio.app\"] { display:none !important; }\n    button[aria-label=\"Settings\"], button[aria-label*=\"设置\"], [aria-label=\"Built with Gradio\"] { display:none !important; }\n\n        /* Script log area: single inner scrollbar on <pre>, outer container hidden overflow */\n        .script-log { max-height: 260px; overflow: hidden; border:1px solid #1f2937; border-radius:6px; padding:0; }\n        .script-log pre {\n            max-height: 260px;\n            overflow: auto;\n            margin: 0;\n            padding: 6px;\n            background: transparent;\n            scrollbar-width: thin; /* Firefox */\n            scrollbar-color: rgba(255,255,255,0.2) transparent;\n        }\n        .script-log pre::-webkit-scrollbar { width: 6px; height: 6px; }\n        .script-log pre::-webkit-scrollbar-track { background: transparent; }\n        .script-log pre::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.12); border-radius: 4px; }\n        .script-log pre:hover::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.25); }\n    \"\"\"\n\n    with gr.Blocks(css=css, title=\"dots.ocr\") as demo:\n        # Left column controls\n        with gr.Row():\n            with gr.Column(scale=1):\n                file_input = gr.File(\n                    label=\"Upload Multiple Images\",\n                    type=\"filepath\",\n                    file_count=\"multiple\",\n                    file_types=[\".jpg\", \".jpeg\", \".png\", \".pdf\"],\n                )\n                # Filter out the unwanted 'prompt_grounding_ocr' mode\n                allowed_modes = [\n                    m\n                    for m in dict_promptmode_to_prompt.keys()\n                    if m != \"prompt_grounding_ocr\"\n                ]\n                if not allowed_modes:\n                    allowed_modes = list(dict_promptmode_to_prompt.keys())\n                prompt_mode = gr.Dropdown(\n                    label=\"Prompt Mode\",\n                    choices=allowed_modes,\n                    value=allowed_modes[0],\n                )\n                prompt_display = gr.Textbox(\n                    label=\"Prompt Preview\",\n                    value=dict_promptmode_to_prompt[allowed_modes[0]],\n                    interactive=False,\n                    lines=4,\n                )\n\n                with gr.Row():\n                    parse_btn = gr.Button(\"🔍 Parse\", variant=\"primary\")\n                    clear_btn = gr.Button(\"🗑️ Clear\")\n\n                with gr.Accordion(\"Advanced Config\", open=False):\n                    fitz_preprocess = gr.Checkbox(label=\"fitz_preprocess\", value=True)\n                    server_ip = gr.Textbox(\n                        label=\"Server IP\", value=DEFAULT_CONFIG[\"ip\"]\n                    )\n                    server_port = gr.Number(\n                        label=\"Port\", value=DEFAULT_CONFIG[\"port_vllm\"], precision=0\n                    )\n                    min_pixels = gr.Number(\n                        label=\"Min Pixels\", value=DEFAULT_CONFIG[\"min_pixels\"]\n                    )\n                    max_pixels = gr.Number(\n                        label=\"Max Pixels\", value=DEFAULT_CONFIG[\"max_pixels\"]\n                    )\n                    concurrency = gr.Number(\n                        label=\"Max Concurrency\",\n                        value=MAX_CONCURRENCY,  # 与实际生效的后台并发保持一致（支持刷新后保持）\n                        precision=0,\n                        interactive=True,\n                    )\n                    confirm_delete = gr.Checkbox(\n                        label=\"删除前确认（推荐）\", value=True, interactive=True\n                    )\n\n            # Right column: results & actions\n            with gr.Column(scale=5):\n                info_display = gr.Markdown(\"Waiting...\", elem_id=\"info_box\")\n                ids_state = gr.State(value=[])\n                store_tick = gr.State(value=0)\n                render_bump = gr.State(value=0)  # 仅用于在状态变化时触发结果重渲染\n                confirm_delete_state = gr.State(value=True)\n                confirm_delete.change(\n                    lambda v: v, inputs=[confirm_delete], outputs=[confirm_delete_state]\n                )\n\n                progress_timer = gr.Timer(1.0)\n\n                # Actions 面板（多选）\n                with gr.Accordion(\"Actions\", open=False):\n                    selected_group = gr.CheckboxGroup(\n                        label=\"Select Items\", choices=[], value=[], interactive=True\n                    )\n                    with gr.Row():\n                        select_all_btn = gr.Button(\"全选\")\n                        clear_sel_btn = gr.Button(\"清空选择\")\n                    with gr.Row():\n                        bulk_reparse_btn = gr.Button(\"🔁 重解析所选\")\n                        delete_selected_btn = gr.Button(\"🗑️ 删除所选\", variant=\"stop\")\n                        export_selected_btn = gr.DownloadButton(\"📦 导出所选\")\n                    # 高级脚本导出\n                    with gr.Accordion(\"高级脚本\", open=False):\n                        gr.Markdown(\n                            \"在下方编辑并运行自定义 Python 脚本以自由处理当前解析结果并导出为任意目录/文件结构。\"\n                            \"<br/>脚本将在受限环境中执行，可通过 api 对象访问只读数据与构建导出压缩包。\",\n                            elem_classes=[\"muted\"],\n                        )\n                        script_code = gr.Code(\n                            label=\"Python 脚本\",\n                            language=\"python\",\n                            value=DEFAULT_SCRIPT_TEMPLATE,\n                            lines=24,\n                            interactive=True,\n                        )\n                        with gr.Row():\n                            run_script_btn = gr.Button(\"▶ 运行脚本\", variant=\"primary\")\n                            script_download_btn = gr.DownloadButton(\"📦 下载脚本输出\")\n                        script_status = gr.HTML(\"\")\n                        script_log = gr.Markdown(\n                            \"\", elem_id=\"script_log\", elem_classes=[\"script-log\"]\n                        )\n\n                        # 流式执行脚本：实时打印日志与运行状态，并在完成后绑定下载按钮\n                        run_script_btn.click(\n                            run_user_script_stream,\n                            inputs=[script_code, ids_state],\n                            outputs=[script_download_btn, script_status, script_log],\n                            show_progress=\"hidden\",\n                        )\n                    # 批量删除确认面板\n                    with gr.Row(visible=False) as bulk_delete_confirm_panel:\n                        gr.Markdown(\n                            \"确认删除所选结果？该操作不可恢复。\",\n                            elem_classes=[\"muted\"],\n                        )\n                        bulk_confirm_delete_btn = gr.Button(\"确认删除\", variant=\"stop\")\n                        bulk_cancel_delete_btn = gr.Button(\"取消\")\n\n                # Render results dynamically\n                @gr.render(inputs=[ids_state, render_bump])\n                def render_results(ids, _bump):\n                    if not ids:\n                        return gr.Markdown(\"No results yet.\")\n                    with gr.Column():\n                        for idx, rid in enumerate(ids):\n                            data = RESULTS_CACHE.get(rid, {}) or {}\n                            status = data.get(\"status\", \"pending\")\n\n                            # 确保每张卡都有独立 UI 状态（并写回缓存，保证后续使用）\n                            ui = _ensure_ui_state(rid)\n                            preview_on = bool(ui.get(\"preview\", True))\n                            nohf_on = bool(ui.get(\"nohf\", False))\n                            active_tab = ui.get(\"tab\", \"md\")\n                            if active_tab not in (\"md\", \"json\"):\n                                active_tab = \"md\"\n                            source_sel = ui.get(\"source\", \"源码\")\n                            if source_sel not in (\"源码\", \"编辑源码\"):\n                                source_sel = \"源码\"\n\n                            with gr.Column(\n                                elem_classes=[\"result-card\"], elem_id=f\"card-{rid}\"\n                            ):\n                                with gr.Row():\n                                    gr.Markdown(\n                                        f\"### Result {idx+1} <span class='muted'>RID: {rid}</span>\"\n                                    )\n\n                                if status == \"error\":\n                                    gr.Markdown(\n                                        f\"⚠️ 解析失败：\\n\\n{data.get('md_content','Unknown error')}\",\n                                        elem_classes=[\"muted\"],\n                                    )\n\n                                if status == \"done\":\n                                    orig_img = data.get(\"original_image\")\n                                    layout_img = data.get(\"layout_image\")\n                                    with gr.Row():\n                                        gr.Image(\n                                            value=orig_img, label=\"Original\", height=300\n                                        )\n                                        gr.Image(\n                                            value=layout_img, label=\"Layout\", height=300\n                                        )\n                                elif status == \"pending\":\n                                    with gr.Row():\n                                        gr.HTML(\n                                            \"<div class='skeleton' style='width:100%;height:300px;'></div>\"\n                                        )\n                                        gr.HTML(\n                                            \"<div class='skeleton' style='width:100%;height:300px;'></div>\"\n                                        )\n\n                                # badges\n                                with gr.Row():\n                                    badge_md = gr.HTML(\n                                        f\"<span class='muted'>MD: {'Preview' if preview_on else 'Source'}</span>\"\n                                    )\n                                    badge_nohf = gr.HTML(\n                                        f\"<span class='muted'>NOHF: {'On' if nohf_on else 'Off'}</span>\"\n                                    )\n\n                                # controls\n                                with gr.Row():\n                                    rid_box = gr.Textbox(value=rid, visible=False)\n                                    preview_cb = gr.Checkbox(\n                                        label=\"Preview Markdown\",\n                                        value=preview_on,\n                                    )\n                                    nohf_cb = gr.Checkbox(label=\"NOHF\", value=nohf_on)\n\n                                # 视图切换\n                                selected_label = (\n                                    \"Markdown\" if active_tab == \"md\" else \"JSON\"\n                                )\n                                with gr.Row():\n                                    view_radio = gr.Radio(\n                                        label=\"视图\",\n                                        choices=[\"Markdown\", \"JSON\"],\n                                        value=selected_label,\n                                    )\n\n                                # 内容来源（仅完成状态可用）\n                                with gr.Row():\n                                    source_radio = gr.Radio(\n                                        label=\"内容来源\",\n                                        choices=[\"源码\", \"编辑源码\"],\n                                        value=source_sel,\n                                        interactive=True,\n                                        visible=(status == \"done\"),\n                                    )\n\n                                # 内容获取助手\n                                def _get_texts(rid_value, nohf_flag):\n                                    st = RESULTS_CACHE.get(rid_value, {}) or {}\n                                    md_orig = st.get(\"md_content\") or \"\"\n                                    md_nohf_orig = st.get(\"md_content_nohf\") or \"\"\n                                    md_current_orig = (\n                                        md_nohf_orig if nohf_flag else md_orig\n                                    )\n                                    edits = st.get(\"edits\") or {}\n                                    md_edit = (\n                                        edits.get(\"nohf\")\n                                        if nohf_flag\n                                        else edits.get(\"md\")\n                                    )\n                                    if md_edit is None:\n                                        md_edit = md_current_orig\n                                    json_orig = st.get(\"json_code\") or \"\"\n                                    json_edit = edits.get(\"json\")\n                                    if json_edit is None:\n                                        json_edit = json_orig\n                                    return (\n                                        md_current_orig,\n                                        md_edit,\n                                        json_orig,\n                                        json_edit,\n                                    )\n\n                                (\n                                    md_orig_val,\n                                    md_edit_val,\n                                    json_orig_val,\n                                    json_edit_val,\n                                ) = _get_texts(rid, nohf_on)\n                                is_md_init = selected_label == \"Markdown\"\n                                use_edit_init = source_sel == \"编辑源码\"\n\n                                # 单一预览组件（Markdown 用）\n                                md_preview = gr.Markdown(\n                                    value=(\n                                        md_edit_val if use_edit_init else md_orig_val\n                                    ),\n                                    visible=(\n                                        status == \"done\" and is_md_init and preview_on\n                                    ),\n                                )\n                                # 原始源码（只读）\n                                md_code_orig = gr.Code(\n                                    language=\"markdown\",\n                                    value=md_orig_val,\n                                    interactive=False,\n                                    visible=(\n                                        status == \"done\"\n                                        and is_md_init\n                                        and (not preview_on)\n                                        and (not use_edit_init)\n                                    ),\n                                )\n                                # 编辑源码（可编辑、自动保存）\n                                md_code_edit = gr.Code(\n                                    language=\"markdown\",\n                                    value=md_edit_val,\n                                    interactive=True,\n                                    visible=(\n                                        status == \"done\"\n                                        and is_md_init\n                                        and (not preview_on)\n                                        and use_edit_init\n                                    ),\n                                )\n\n                                # JSON（原始与编辑）\n                                json_code_orig = gr.Code(\n                                    language=\"json\",\n                                    value=json_orig_val,\n                                    interactive=False,\n                                    visible=(\n                                        status == \"done\"\n                                        and (not is_md_init)\n                                        and (not use_edit_init)\n                                    ),\n                                )\n                                json_code_edit = gr.Code(\n                                    language=\"json\",\n                                    value=json_edit_val,\n                                    interactive=True,\n                                    visible=(\n                                        status == \"done\"\n                                        and (not is_md_init)\n                                        and use_edit_init\n                                    ),\n                                )\n\n                                # 仅编辑模式显示\n                                restore_btn = gr.Button(\n                                    \"还原当前内容\",\n                                    visible=(status == \"done\" and use_edit_init),\n                                )\n\n                                # 统一可见性/内容更新\n                                def _apply_all(\n                                    preview, use_nohf, view_label, src_label, rid_value\n                                ):\n                                    preview = bool(preview)\n                                    use_nohf = bool(use_nohf)\n                                    is_md = str(view_label) == \"Markdown\"\n                                    use_edit = str(src_label) == \"编辑源码\"\n\n                                    # 写回 UI 状态\n                                    st = RESULTS_CACHE.get(rid_value, {}) or {}\n                                    ui0 = dict(st.get(\"ui\") or _default_ui_state())\n                                    ui0[\"preview\"] = preview\n                                    ui0[\"nohf\"] = use_nohf\n                                    ui0[\"tab\"] = \"md\" if is_md else \"json\"\n                                    ui0[\"source\"] = \"编辑源码\" if use_edit else \"源码\"\n                                    st[\"ui\"] = ui0\n                                    RESULTS_CACHE[rid_value] = st\n\n                                    md_o, md_e, j_o, j_e = _get_texts(\n                                        rid_value, use_nohf\n                                    )\n                                    return (\n                                        gr.update(\n                                            value=f\"<span class='muted'>MD: {'Preview' if preview else 'Source'}</span>\"\n                                        ),\n                                        gr.update(\n                                            value=f\"<span class='muted'>NOHF: {'On' if use_nohf else 'Off'}</span>\"\n                                        ),\n                                        gr.update(\n                                            value=(md_e if use_edit else md_o),\n                                            visible=(is_md and preview),\n                                        ),\n                                        gr.update(\n                                            value=md_o,\n                                            visible=(\n                                                is_md\n                                                and (not preview)\n                                                and (not use_edit)\n                                            ),\n                                        ),\n                                        gr.update(\n                                            value=md_e,\n                                            visible=(\n                                                is_md and (not preview) and use_edit\n                                            ),\n                                        ),\n                                        gr.update(\n                                            value=j_o,\n                                            visible=(not is_md and (not use_edit)),\n                                        ),\n                                        gr.update(\n                                            value=j_e, visible=(not is_md and use_edit)\n                                        ),\n                                        gr.update(visible=use_edit),\n                                    )\n\n                                # 绑定控制项变化：预览、NOHF、视图、来源\n                                preview_cb.change(\n                                    _apply_all,\n                                    inputs=[\n                                        preview_cb,\n                                        nohf_cb,\n                                        view_radio,\n                                        source_radio,\n                                        rid_box,\n                                    ],\n                                    outputs=[\n                                        badge_md,\n                                        badge_nohf,\n                                        md_preview,\n                                        md_code_orig,\n                                        md_code_edit,\n                                        json_code_orig,\n                                        json_code_edit,\n                                        restore_btn,\n                                    ],\n                                    show_progress=\"hidden\",\n                                )\n                                nohf_cb.change(\n                                    _apply_all,\n                                    inputs=[\n                                        preview_cb,\n                                        nohf_cb,\n                                        view_radio,\n                                        source_radio,\n                                        rid_box,\n                                    ],\n                                    outputs=[\n                                        badge_md,\n                                        badge_nohf,\n                                        md_preview,\n                                        md_code_orig,\n                                        md_code_edit,\n                                        json_code_orig,\n                                        json_code_edit,\n                                        restore_btn,\n                                    ],\n                                    show_progress=\"hidden\",\n                                )\n\n                                def _on_view_change(\n                                    view_label,\n                                    rid_value,\n                                    preview_flag,\n                                    nohf_flag,\n                                    src_label,\n                                ):\n                                    st = RESULTS_CACHE.get(rid_value, {}) or {}\n                                    ui0 = dict(st.get(\"ui\") or _default_ui_state())\n                                    ui0[\"tab\"] = (\n                                        \"md\"\n                                        if str(view_label) == \"Markdown\"\n                                        else \"json\"\n                                    )\n                                    st[\"ui\"] = ui0\n                                    RESULTS_CACHE[rid_value] = st\n                                    return _apply_all(\n                                        preview_flag,\n                                        nohf_flag,\n                                        view_label,\n                                        src_label,\n                                        rid_value,\n                                    )\n\n                                view_radio.change(\n                                    _on_view_change,\n                                    inputs=[\n                                        view_radio,\n                                        rid_box,\n                                        preview_cb,\n                                        nohf_cb,\n                                        source_radio,\n                                    ],\n                                    outputs=[\n                                        badge_md,\n                                        badge_nohf,\n                                        md_preview,\n                                        md_code_orig,\n                                        md_code_edit,\n                                        json_code_orig,\n                                        json_code_edit,\n                                        restore_btn,\n                                    ],\n                                    show_progress=\"hidden\",\n                                )\n\n                                def _on_source_change(\n                                    src_label,\n                                    rid_value,\n                                    preview_flag,\n                                    nohf_flag,\n                                    view_label,\n                                ):\n                                    st = RESULTS_CACHE.get(rid_value, {}) or {}\n                                    ui0 = dict(st.get(\"ui\") or _default_ui_state())\n                                    ui0[\"source\"] = (\n                                        \"编辑源码\"\n                                        if str(src_label) == \"编辑源码\"\n                                        else \"源码\"\n                                    )\n                                    st[\"ui\"] = ui0\n                                    RESULTS_CACHE[rid_value] = st\n                                    return _apply_all(\n                                        preview_flag,\n                                        nohf_flag,\n                                        view_label,\n                                        src_label,\n                                        rid_value,\n                                    )\n\n                                source_radio.change(\n                                    _on_source_change,\n                                    inputs=[\n                                        source_radio,\n                                        rid_box,\n                                        preview_cb,\n                                        nohf_cb,\n                                        view_radio,\n                                    ],\n                                    outputs=[\n                                        badge_md,\n                                        badge_nohf,\n                                        md_preview,\n                                        md_code_orig,\n                                        md_code_edit,\n                                        json_code_orig,\n                                        json_code_edit,\n                                        restore_btn,\n                                    ],\n                                    show_progress=\"hidden\",\n                                )\n\n                                # Action buttons per-card\n                                with gr.Row():\n                                    reparse_btn = gr.Button(\n                                        \"🔁 重新解析\",\n                                        interactive=(status in (\"done\", \"error\")),\n                                    )\n                                    export_btn = gr.DownloadButton(\n                                        \"📦 导出\",\n                                        interactive=(status == \"done\"),\n                                        value=(\n                                            data.get(\"export_path\")\n                                            if status == \"done\"\n                                            else None\n                                        ),\n                                    )\n                                    delete_btn = gr.Button(\"🗑️ 删除\", variant=\"stop\")\n\n                                # 自动保存（编辑器变更即写盘 + 刷新导出 + 可能的 Markdown 预览）\n                                def _save_md_edit(\n                                    val,\n                                    rid_value,\n                                    nohf_flag,\n                                    preview_flag,\n                                    view_label,\n                                    src_label,\n                                    ids,\n                                    selected_labels,\n                                ):\n                                    st = RESULTS_CACHE.get(rid_value, {}) or {}\n                                    if st.get(\"status\") != \"done\":\n                                        # 同步“导出所选”以防其它项在编辑（极少见）\n                                        path_sel = export_selected_rids(\n                                            ids, selected_labels\n                                        )\n                                        return (\n                                            gr.update(),\n                                            gr.update(),\n                                            gr.update(value=path_sel),\n                                        )\n                                    which = \"nohf\" if bool(nohf_flag) else \"md\"\n                                    edits = dict(st.get(\"edits\") or {})\n                                    edits[which] = val or \"\"\n                                    st[\"edits\"] = edits\n                                    RESULTS_CACHE[rid_value] = st\n                                    try:\n                                        _save_edited_to_disk(st, which, val or \"\")\n                                    except Exception:\n                                        pass\n                                    _invalidate_export_zip(rid_value)\n                                    new_zip = ensure_export_ready(rid_value)\n\n                                    # 刷新“导出所选”\n                                    path_sel = export_selected_rids(\n                                        ids, selected_labels\n                                    )\n\n                                    # 若当前正处于 Markdown/预览/编辑模式，则更新预览内容\n                                    is_md = str(view_label) == \"Markdown\"\n                                    use_edit = str(src_label) == \"编辑源码\"\n                                    if is_md and use_edit and bool(preview_flag):\n                                        return (\n                                            gr.update(value=val or \"\"),\n                                            gr.update(value=new_zip),\n                                            gr.update(value=path_sel),\n                                        )\n                                    return (\n                                        gr.update(),\n                                        gr.update(value=new_zip),\n                                        gr.update(value=path_sel),\n                                    )\n\n                                md_code_edit.change(\n                                    _save_md_edit,\n                                    inputs=[\n                                        md_code_edit,\n                                        rid_box,\n                                        nohf_cb,\n                                        preview_cb,\n                                        view_radio,\n                                        source_radio,\n                                        ids_state,\n                                        selected_group,\n                                    ],\n                                    outputs=[\n                                        md_preview,\n                                        export_btn,\n                                        export_selected_btn,\n                                    ],\n                                    show_progress=\"hidden\",\n                                )\n\n                                def _save_json_edit(\n                                    val, rid_value, ids, selected_labels\n                                ):\n                                    st = RESULTS_CACHE.get(rid_value, {}) or {}\n                                    if st.get(\"status\") != \"done\":\n                                        path_sel = export_selected_rids(\n                                            ids, selected_labels\n                                        )\n                                        return gr.update(), gr.update(value=path_sel)\n                                    edits = dict(st.get(\"edits\") or {})\n                                    edits[\"json\"] = val or \"\"\n                                    st[\"edits\"] = edits\n                                    RESULTS_CACHE[rid_value] = st\n                                    try:\n                                        _save_edited_to_disk(st, \"json\", val or \"\")\n                                    except Exception:\n                                        pass\n                                    _invalidate_export_zip(rid_value)\n                                    new_zip = ensure_export_ready(rid_value)\n                                    path_sel = export_selected_rids(\n                                        ids, selected_labels\n                                    )\n                                    return gr.update(value=new_zip), gr.update(\n                                        value=path_sel\n                                    )\n\n                                json_code_edit.change(\n                                    _save_json_edit,\n                                    inputs=[\n                                        json_code_edit,\n                                        rid_box,\n                                        ids_state,\n                                        selected_group,\n                                    ],\n                                    outputs=[export_btn, export_selected_btn],\n                                    show_progress=\"hidden\",\n                                )\n\n                                # 还原当前内容\n                                def _restore_current(\n                                    src_label,\n                                    rid_value,\n                                    nohf_flag,\n                                    preview_flag,\n                                    view_label,\n                                    ids,\n                                    selected_labels,\n                                ):\n                                    st = RESULTS_CACHE.get(rid_value, {}) or {}\n                                    which = (\n                                        \"json\"\n                                        if str(view_label) == \"JSON\"\n                                        else (\"nohf\" if bool(nohf_flag) else \"md\")\n                                    )\n                                    # 删除编辑版\n                                    edits = dict(st.get(\"edits\") or {})\n                                    if which in edits:\n                                        edits.pop(which, None)\n                                        st[\"edits\"] = edits\n                                    RESULTS_CACHE[rid_value] = st\n                                    try:\n                                        _delete_edited_from_disk(st, which)\n                                    except Exception:\n                                        pass\n                                    # 重新取原始内容\n                                    md_o, md_e, j_o, j_e = _get_texts(\n                                        rid_value, bool(nohf_flag)\n                                    )\n                                    # 刷新导出\n                                    _invalidate_export_zip(rid_value)\n                                    new_zip = ensure_export_ready(rid_value)\n                                    path_sel = export_selected_rids(\n                                        ids, selected_labels\n                                    )\n                                    # 更新编辑器与预览\n                                    up_md_editor = (\n                                        gr.update(value=md_o)\n                                        if which in (\"md\", \"nohf\")\n                                        else gr.update()\n                                    )\n                                    up_json_editor = (\n                                        gr.update(value=j_o)\n                                        if which == \"json\"\n                                        else gr.update()\n                                    )\n                                    is_md = str(view_label) == \"Markdown\"\n                                    use_edit = str(src_label) == \"编辑源码\"\n                                    up_preview = (\n                                        gr.update(value=(md_e if use_edit else md_o))\n                                        if is_md and bool(preview_flag)\n                                        else gr.update()\n                                    )\n                                    return (\n                                        up_md_editor,\n                                        up_json_editor,\n                                        up_preview,\n                                        gr.update(value=new_zip),\n                                        gr.update(value=path_sel),\n                                    )\n\n                                restore_btn.click(\n                                    _restore_current,\n                                    inputs=[\n                                        source_radio,\n                                        rid_box,\n                                        nohf_cb,\n                                        preview_cb,\n                                        view_radio,\n                                        ids_state,\n                                        selected_group,\n                                    ],\n                                    outputs=[\n                                        md_code_edit,\n                                        json_code_edit,\n                                        md_preview,\n                                        export_btn,\n                                        export_selected_btn,\n                                    ],\n                                    show_progress=\"hidden\",\n                                )\n\n                                # Reparse panel (collapsed)\n                                with gr.Column(visible=False) as reparse_panel:\n                                    gr.Markdown(\"**重解析**\")\n                                    with gr.Row():\n                                        reparse_current_btn = gr.Button(\n                                            \"基于当前图片直接重解析\", variant=\"primary\"\n                                        )\n\n                                # Delete confirm panel (collapsed)\n                                with gr.Row(visible=False) as delete_confirm_panel:\n                                    gr.Markdown(\n                                        \"确认删除该结果？该操作不可恢复。\",\n                                        elem_classes=[\"muted\"],\n                                    )\n                                    confirm_delete_btn = gr.Button(\n                                        \"确认删除\", variant=\"stop\"\n                                    )\n                                    cancel_delete_btn = gr.Button(\"取消\")\n\n                                # 绑定其他交互\n                                reparse_btn.click(\n                                    lambda: gr.update(visible=True),\n                                    outputs=[reparse_panel],\n                                    show_progress=\"hidden\",\n                                )\n\n                                def _start_reparse_current(\n                                    rid_value,\n                                    p_mode,\n                                    ip_addr,\n                                    port_val,\n                                    minp,\n                                    maxp,\n                                    fitz_flag,\n                                    tick,\n                                    ids,\n                                    selected_labels,\n                                ):\n                                    try:\n                                        enqueue_single_reparse(\n                                            rid_value,\n                                            None,\n                                            p_mode,\n                                            ip_addr,\n                                            int(port_val),\n                                            int(minp),\n                                            int(maxp),\n                                            fitz_flag,\n                                        )\n                                        # 重建“导出所选”\n                                        path_sel = export_selected_rids(\n                                            ids, selected_labels\n                                        )\n                                        return (\n                                            int(tick or 0) + 1,\n                                            gr.update(visible=False),\n                                            gr.update(value=path_sel),\n                                        )\n                                    except Exception as e:\n                                        RESULTS_CACHE[rid_value] = {\n                                            \"status\": \"error\",\n                                            \"md_content\": f\"Reparse error: {e}\",\n                                            # 保留 UI 状态\n                                            \"ui\": _ensure_ui_state(rid_value),\n                                        }\n                                        path_sel = export_selected_rids(\n                                            ids, selected_labels\n                                        )\n                                        return (\n                                            int(tick or 0) + 1,\n                                            gr.update(visible=False),\n                                            gr.update(value=path_sel),\n                                        )\n\n                                reparse_current_btn.click(\n                                    _start_reparse_current,\n                                    inputs=[\n                                        rid_box,\n                                        prompt_mode,\n                                        server_ip,\n                                        server_port,\n                                        min_pixels,\n                                        max_pixels,\n                                        fitz_preprocess,\n                                        store_tick,\n                                        ids_state,\n                                        selected_group,\n                                    ],\n                                    outputs=[\n                                        store_tick,\n                                        reparse_panel,\n                                        export_selected_btn,\n                                    ],\n                                    show_progress=\"hidden\",\n                                )\n\n                                def _on_delete_click(\n                                    rid_value, ids, need_confirm, tick\n                                ):\n                                    # 如果需要确认，仅展开确认面板，不修改选择框/导出按钮\n                                    if need_confirm:\n                                        return (\n                                            gr.update(visible=True),\n                                            ids,\n                                            tick,\n                                            gr.update(),  # selected_group 不变\n                                            gr.update(),  # export button 不变\n                                        )\n                                    # 直接删除：更新 ids/tick，并同步 Actions 的选择项与导出按钮\n                                    new_ids, new_tick = delete_one(ids, rid_value, tick)\n                                    choices = [\n                                        f\"Result {i+1}\"\n                                        for i in range(len(new_ids or []))\n                                    ]\n                                    return (\n                                        gr.update(visible=False),\n                                        new_ids,\n                                        new_tick,\n                                        gr.update(choices=choices, value=[]),\n                                        gr.update(value=None),  # 清空导出\n                                    )\n\n                                # 单卡删除输出同步 selected_group 与 export_selected_btn\n                                delete_btn.click(\n                                    _on_delete_click,\n                                    inputs=[\n                                        rid_box,\n                                        ids_state,\n                                        confirm_delete_state,\n                                        store_tick,\n                                    ],\n                                    outputs=[\n                                        delete_confirm_panel,\n                                        ids_state,\n                                        store_tick,\n                                        selected_group,\n                                        export_selected_btn,\n                                    ],\n                                    show_progress=\"hidden\",\n                                )\n\n                                def _confirm_delete(rid_value, ids, tick):\n                                    new_ids, new_tick = delete_one(ids, rid_value, tick)\n                                    choices = [\n                                        f\"Result {i+1}\"\n                                        for i in range(len(new_ids or []))\n                                    ]\n                                    return (\n                                        new_ids,\n                                        new_tick,\n                                        gr.update(visible=False),\n                                        gr.update(choices=choices, value=[]),\n                                        gr.update(value=None),\n                                    )\n\n                                # 确认删除后同步 selected_group 与 export_selected_btn\n                                confirm_delete_btn.click(\n                                    _confirm_delete,\n                                    inputs=[rid_box, ids_state, store_tick],\n                                    outputs=[\n                                        ids_state,\n                                        store_tick,\n                                        delete_confirm_panel,\n                                        selected_group,\n                                        export_selected_btn,\n                                    ],\n                                    show_progress=\"hidden\",\n                                )\n                                cancel_delete_btn.click(\n                                    lambda: gr.update(visible=False),\n                                    outputs=[delete_confirm_panel],\n                                    show_progress=\"hidden\",\n                                )\n\n                # Top-level events\n                def _on_prompt_mode_change(m):\n                    return dict_promptmode_to_prompt.get(m, \"\")\n\n                prompt_mode.change(\n                    fn=_on_prompt_mode_change,\n                    inputs=[prompt_mode],\n                    outputs=[prompt_display],\n                    show_progress=\"hidden\",\n                )\n\n                def process_images_simple(\n                    file_list,\n                    p_mode,\n                    server_ip_val,\n                    server_port_val,\n                    min_p_val,\n                    max_p_val,\n                    fitz_val,\n                    cur_ids,\n                    tick,\n                ):\n                    \"\"\"\n                    Process images with selected prompt mode. Grounding mode is removed; all files go through normal path.\n                    \"\"\"\n                    minp, maxp = _validate_pixels(min_p_val, max_p_val)\n                    _set_parser_config(server_ip_val, server_port_val, minp, maxp)\n\n                    # normalize file_list (gradio file element may pass nested lists)\n                    files = []\n                    if not file_list:\n                        return (\n                            gr.update(value=None),\n                            gr.update(value=\"No files uploaded.\"),\n                            cur_ids,\n                            tick,\n                            gr.update(choices=[], value=[]),\n                            gr.update(value=None),  # 清空导出\n                        )\n\n                    # build normalized list\n                    for f in file_list:\n                        if isinstance(f, (list, tuple)):\n                            files.append(f[0] if len(f) > 0 else None)\n                        else:\n                            files.append(f)\n\n                    # Normal path: queue originals\n                    new_ids, info = add_tasks_to_queue(\n                        files,\n                        p_mode,\n                        server_ip_val,\n                        server_port_val,\n                        minp,\n                        maxp,\n                        fitz_val,\n                        cur_ids,\n                    )\n                    # Update checkbox group choices\n                    choices = [f\"Result {i+1}\" for i in range(len(new_ids or []))]\n                    return (\n                        gr.update(value=None),\n                        gr.update(value=info),\n                        new_ids,\n                        int(tick or 0) + 1,\n                        gr.update(choices=choices, value=[]),\n                        gr.update(value=None),  # 清空导出\n                    )\n\n                parse_btn.click(\n                    fn=process_images_simple,\n                    inputs=[\n                        file_input,\n                        prompt_mode,\n                        server_ip,\n                        server_port,\n                        min_pixels,\n                        max_pixels,\n                        fitz_preprocess,\n                        ids_state,\n                        store_tick,\n                    ],\n                    outputs=[\n                        file_input,\n                        info_display,\n                        ids_state,\n                        store_tick,\n                        selected_group,\n                        export_selected_btn,\n                    ],\n                    show_progress=\"hidden\",\n                )\n\n                # Concurrency change handler: apply immediately\n                def _on_concurrency_change(n):\n                    try:\n                        set_max_concurrency(int(n))\n                        return gr.update(value=f\"并发已设置为 {int(n)}。\")\n                    except Exception as e:\n                        return gr.update(value=f\"设置并发失败：{e}\")\n\n                concurrency.change(\n                    _on_concurrency_change,\n                    inputs=[concurrency],\n                    outputs=[info_display],\n                    show_progress=\"hidden\",\n                )\n\n                # 会话加载时同步 UI 与当前真实并发（解决刷新后 UI 值与实际不一致）\n                def _sync_concurrency_on_session_load():\n                    try:\n                        # 如有需要，补齐 worker 到目标并发数（不会减少已有线程）\n                        _start_workers(max(1, MAX_CONCURRENCY))\n                        return (\n                            gr.update(value=int(MAX_CONCURRENCY)),\n                            gr.update(\n                                value=f\"已同步当前并发为 {int(MAX_CONCURRENCY)}。\"\n                            ),\n                        )\n                    except Exception as e:\n                        return (\n                            gr.update(value=int(MAX_CONCURRENCY)),\n                            gr.update(value=f\"同步并发时发生异常：{e}\"),\n                        )\n\n                demo.load(\n                    _sync_concurrency_on_session_load,\n                    inputs=None,\n                    outputs=[concurrency, info_display],\n                )\n\n                # 生成导出 ZIP（基于当前选择），用于首次点击即可下载\n                def _update_export_for_selection(ids, selected_labels):\n                    path = export_selected_rids(ids, selected_labels)\n                    return gr.update(\n                        value=path if path and os.path.exists(path) else None\n                    )\n\n                # Actions: 全选/清空\n                def _select_all(ids):\n                    choices = [f\"Result {i+1}\" for i in range(len(ids or []))]\n                    # 预生成 zip\n                    path = export_selected_rids(ids, choices)\n                    return (\n                        gr.update(choices=choices, value=choices),\n                        gr.update(\n                            value=path if path and os.path.exists(path) else None\n                        ),\n                    )\n\n                def _clear_selection(ids):\n                    choices = [f\"Result {i+1}\" for i in range(len(ids or []))]\n                    return (\n                        gr.update(choices=choices, value=[]),\n                        gr.update(value=None),\n                    )\n\n                select_all_btn.click(\n                    _select_all,\n                    inputs=[ids_state],\n                    outputs=[selected_group, export_selected_btn],\n                    show_progress=\"hidden\",\n                )\n                clear_sel_btn.click(\n                    _clear_selection,\n                    inputs=[ids_state],\n                    outputs=[selected_group, export_selected_btn],\n                    show_progress=\"hidden\",\n                )\n\n                # 当用户手动变更选择时，预构建导出 zip 并绑定到按钮\n                selected_group.change(\n                    _update_export_for_selection,\n                    inputs=[ids_state, selected_group],\n                    outputs=[export_selected_btn],\n                    show_progress=\"hidden\",\n                )\n\n                # Actions: 批量重解析（基于当前图片）\n                def bulk_reparse(\n                    selected_labels, ids, p_mode, ip, port, minp, maxp, fitz, tick\n                ):\n                    if not ids or not selected_labels:\n                        path_sel = export_selected_rids(ids, selected_labels)\n                        return (\n                            gr.update(value=\"未选择任何结果。\"),\n                            int(tick or 0),\n                            gr.update(value=path_sel),\n                        )\n                    # Map labels -> rids\n                    count = 0\n                    for label in selected_labels:\n                        try:\n                            idx = int(str(label).split()[-1]) - 1\n                            rid = ids[idx]\n                            enqueue_single_reparse(\n                                rid,\n                                None,\n                                p_mode,\n                                ip,\n                                int(port),\n                                int(minp),\n                                int(maxp),\n                                fitz,\n                            )\n                            count += 1\n                        except Exception:\n                            continue\n                    path_sel = export_selected_rids(ids, selected_labels)\n                    return (\n                        gr.update(value=f\"已触发 {count} 个重解析任务。\"),\n                        int(tick or 0) + 1,\n                        gr.update(value=path_sel),\n                    )\n\n                bulk_reparse_btn.click(\n                    bulk_reparse,\n                    inputs=[\n                        selected_group,\n                        ids_state,\n                        prompt_mode,\n                        server_ip,\n                        server_port,\n                        min_pixels,\n                        max_pixels,\n                        fitz_preprocess,\n                        store_tick,\n                    ],\n                    outputs=[info_display, store_tick, export_selected_btn],\n                    show_progress=\"hidden\",\n                )\n\n                # Actions: 删除所选（尊重“删除前确认”）\n                def delete_selected_action(ids, selected_labels, tick):\n                    # 先从“原始 ids 列表”解析出要删除的 rid 列表，避免索引随删除而错位\n                    if not ids or not selected_labels:\n                        choices = [f\"Result {i+1}\" for i in range(len(ids or []))]\n                        return (\n                            ids,\n                            int(tick or 0),\n                            gr.update(choices=choices, value=[]),\n                            gr.update(value=None),\n                        )\n                    # 解析 label -> index（去重、过滤非法）\n                    sel_indices = []\n                    for label in selected_labels:\n                        try:\n                            idx = int(str(label).split()[-1]) - 1\n                            if 0 <= idx < len(ids):\n                                sel_indices.append(idx)\n                        except Exception:\n                            continue\n                    if not sel_indices:\n                        choices = [f\"Result {i+1}\" for i in range(len(ids or []))]\n                        return (\n                            ids,\n                            int(tick or 0),\n                            gr.update(choices=choices, value=[]),\n                            gr.update(value=None),\n                        )\n                    sel_indices = sorted(set(sel_indices))\n                    rids_to_delete = [ids[i] for i in sel_indices]\n\n                    new_ids = list(ids)\n                    new_tick = int(tick or 0)\n                    # 基于 rid 删除，避免受索引变化影响\n                    for rid in rids_to_delete:\n                        new_ids, new_tick = delete_one(new_ids, rid, new_tick)\n\n                    choices = [f\"Result {i+1}\" for i in range(len(new_ids or []))]\n                    return (\n                        new_ids,\n                        new_tick,\n                        gr.update(choices=choices, value=[]),\n                        gr.update(value=None),\n                    )\n\n                def _on_bulk_delete_click(ids, selected_labels, need_confirm, tick):\n                    if need_confirm:\n                        # 展示确认面板，不改动任何选择与导出\n                        return (\n                            gr.update(visible=True),\n                            ids,\n                            tick,\n                            gr.update(),\n                            gr.update(),\n                        )\n                    # 直接删除并隐藏确认面板\n                    new_ids, new_tick, sel_update, export_update = (\n                        delete_selected_action(ids, selected_labels, tick)\n                    )\n                    return (\n                        gr.update(visible=False),\n                        new_ids,\n                        new_tick,\n                        sel_update,\n                        export_update,\n                    )\n\n                delete_selected_btn.click(\n                    _on_bulk_delete_click,\n                    inputs=[\n                        ids_state,\n                        selected_group,\n                        confirm_delete_state,\n                        store_tick,\n                    ],\n                    outputs=[\n                        bulk_delete_confirm_panel,\n                        ids_state,\n                        store_tick,\n                        selected_group,\n                        export_selected_btn,\n                    ],\n                    show_progress=\"hidden\",\n                )\n\n                def _bulk_confirm_delete(ids, selected_labels, tick):\n                    new_ids, new_tick, sel_update, export_update = (\n                        delete_selected_action(ids, selected_labels, tick)\n                    )\n                    return (\n                        new_ids,\n                        new_tick,\n                        sel_update,\n                        export_update,\n                        gr.update(visible=False),\n                    )\n\n                bulk_confirm_delete_btn.click(\n                    _bulk_confirm_delete,\n                    inputs=[ids_state, selected_group, store_tick],\n                    outputs=[\n                        ids_state,\n                        store_tick,\n                        selected_group,\n                        export_selected_btn,\n                        bulk_delete_confirm_panel,\n                    ],\n                    show_progress=\"hidden\",\n                )\n                bulk_cancel_delete_btn.click(\n                    lambda: gr.update(visible=False),\n                    outputs=[bulk_delete_confirm_panel],\n                    show_progress=\"hidden\",\n                )\n\n                # 进度信息\n                def update_progress_info(ids, tick, bump):\n                    if not ids:\n                        return (\n                            gr.update(value=\"Waiting...\"),\n                            tick,\n                            int(bump or 0),\n                        )\n                    pending = 0\n                    done = 0\n                    errors = 0\n                    status_signature = []\n                    for rid in ids:\n                        st = RESULTS_CACHE.get(rid, {})\n                        status = st.get(\"status\", \"pending\")\n                        status_signature.append((rid, status))\n                        if status == \"done\":\n                            done += 1\n                        elif status == \"error\":\n                            errors += 1\n                        else:\n                            pending += 1\n                    qsize = TASK_QUEUE.qsize()\n                    running = max(0, pending - qsize)\n\n                    # Info text\n                    if pending == 0:\n                        info = (\n                            f\"进度：完成 {done}\"\n                            + (\"\" if errors == 0 else f\"，错误 {errors}\")\n                            + \"。\"\n                        )\n                    else:\n                        info = f\"进度：完成 {done}，错误 {errors}，正在解析 {running}，排队 {qsize}，待处理合计 {pending}。\"\n\n                    # Only bump render when any item's status changed\n                    sig_tuple = tuple(status_signature)\n                    last_sig = getattr(update_progress_info, \"_last_status_sig\", None)\n                    bump_out = int(bump or 0)\n                    if last_sig != sig_tuple:\n                        setattr(update_progress_info, \"_last_status_sig\", sig_tuple)\n                        bump_out = bump_out + 1\n\n                    # Only tick when coarse counts change (avoid unnecessary churn)\n                    key = f\"{done}_{errors}_{pending}\"\n                    last_key = getattr(update_progress_info, \"_last_counts_key\", None)\n                    new_tick = int(tick or 0)\n                    if last_key != key:\n                        setattr(update_progress_info, \"_last_counts_key\", key)\n                        new_tick = new_tick + 1\n\n                    return (\n                        gr.update(value=info),\n                        new_tick,\n                        bump_out,\n                    )\n\n                # 计时器不再触达 selected_group，杜绝与用户交互竞争导致选择重置/计时停止\n                progress_timer.tick(\n                    fn=update_progress_info,\n                    inputs=[ids_state, store_tick, render_bump],\n                    outputs=[info_display, store_tick, render_bump],\n                    show_progress=\"hidden\",\n                )\n\n                # Clear all\n                def clear_all():\n                    global RESULTS_CACHE\n                    while not TASK_QUEUE.empty():\n                        try:\n                            TASK_QUEUE.get_nowait()\n                            TASK_QUEUE.task_done()\n                        except queue.Empty:\n                            break\n                    RESULTS_CACHE = {}\n                    RETRY_COUNTS.clear()\n                    # Do not stop workers; keep them alive\n                    return (\n                        [],\n                        0,\n                        gr.update(value=\"Waiting...\"),\n                        0,\n                        gr.update(choices=[], value=[]),\n                        gr.update(value=None),\n                    )\n\n                clear_btn.click(\n                    clear_all,\n                    inputs=None,\n                    outputs=[\n                        ids_state,\n                        store_tick,\n                        info_display,\n                        render_bump,\n                        selected_group,\n                        export_selected_btn,\n                    ],\n                    show_progress=\"hidden\",\n                )\n\n    return demo\n\n\n# ---------------- main ----------------\ndef _queue_compat(blocks: gr.Blocks):\n    \"\"\"\n    Gradio version compatibility layer for Blocks.queue:\n    - Try Gradio 4.x: default_concurrency_limit + status_update_rate\n    - Fallback to Gradio 3.x: concurrency_count + status_update_rate\n    - Final fallback: no-arg queue()\n    \"\"\"\n    try:\n        # Gradio 4.x path\n        return blocks.queue(default_concurrency_limit=20, status_update_rate=0.2)\n    except TypeError:\n        try:\n            # Gradio 3.x path\n            return blocks.queue(concurrency_count=16, status_update_rate=0.2)\n        except TypeError:\n            # Minimal fallback\n            return blocks.queue()\n\n\ndef _launch_compat(app: gr.Blocks, port: int):\n    \"\"\"\n    Gradio version compatibility for launch parameters.\n    \"\"\"\n    try:\n        app.launch(\n            server_name=\"0.0.0.0\",\n            server_port=port,\n            debug=True,\n            show_api=False,  # 3.x/部分4.x可用\n        )\n    except TypeError:\n        # Fallback without show_api\n        app.launch(\n            server_name=\"0.0.0.0\",\n            server_port=port,\n            debug=True,\n        )\n\n\nif __name__ == \"__main__\":\n    import sys\n\n    port = int(sys.argv[1]) if len(sys.argv) > 1 else 7860\n    demo = create_gradio_interface()\n    app = _queue_compat(demo)\n    _launch_compat(app, port)\n"
  },
  {
    "path": "demo/demo_hf.py",
    "content": "import os\nif \"LOCAL_RANK\" not in os.environ:\n    os.environ[\"LOCAL_RANK\"] = \"0\"\n\nimport torch\nfrom transformers import AutoModelForCausalLM, AutoProcessor, AutoTokenizer\nfrom qwen_vl_utils import process_vision_info\nfrom dots_ocr.utils import dict_promptmode_to_prompt\n\ndef inference(image_path, prompt, model, processor):\n    # image_path = \"demo/demo_image1.jpg\"\n    messages = [\n        {\n            \"role\": \"user\",\n            \"content\": [\n                {\n                    \"type\": \"image\",\n                    \"image\": image_path\n                },\n                {\"type\": \"text\", \"text\": prompt}\n            ]\n        }\n    ]\n\n\n    # Preparation for inference\n    text = processor.apply_chat_template(\n        messages, \n        tokenize=False, \n        add_generation_prompt=True\n    )\n    image_inputs, video_inputs = process_vision_info(messages)\n    inputs = processor(\n        text=[text],\n        images=image_inputs,\n        videos=video_inputs,\n        padding=True,\n        return_tensors=\"pt\",\n    )\n\n    inputs = inputs.to(\"cuda\")\n\n    # Inference: Generation of the output\n    generated_ids = model.generate(**inputs, max_new_tokens=24000)\n    generated_ids_trimmed = [\n        out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)\n    ]\n    output_text = processor.batch_decode(\n        generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False\n    )\n    print(output_text)\n\n\n\nif __name__ == \"__main__\":\n    # We recommend enabling flash_attention_2 for better acceleration and memory saving, especially in multi-image and video scenarios.\n    model_path = \"./weights/DotsOCR\"\n    model = AutoModelForCausalLM.from_pretrained(\n        model_path,\n        attn_implementation=\"flash_attention_2\",\n        torch_dtype=torch.bfloat16,\n        device_map=\"auto\",\n        trust_remote_code=True\n    )\n    processor = AutoProcessor.from_pretrained(model_path,  trust_remote_code=True)\n\n    image_path = \"demo/demo_image1.jpg\"\n    for prompt_mode, prompt in dict_promptmode_to_prompt.items():\n        print(f\"prompt: {prompt}\")\n        inference(image_path, prompt, model, processor)\n    "
  },
  {
    "path": "demo/demo_streamlit.py",
    "content": "\"\"\"\nLayout Inference Web Application\n\nA Streamlit-based layout inference tool that supports image uploads and multiple backend inference engines.\n\"\"\"\n\nimport streamlit as st\nimport json\nimport os\nimport io\nimport tempfile\nfrom PIL import Image\nimport requests\n\n# Local utility imports\n\n# from utils import infer\n\nfrom dots_ocr.utils import dict_promptmode_to_prompt\nfrom dots_ocr.utils.format_transformer import layoutjson2md\nfrom dots_ocr.utils.layout_utils import draw_layout_on_image, post_process_cells\nfrom dots_ocr.utils.image_utils import get_input_dimensions, get_image_by_fitz_doc\nfrom dots_ocr.model.inference import inference_with_vllm\nfrom dots_ocr.utils.consts import MIN_PIXELS, MAX_PIXELS\n\nimport os\nfrom PIL import Image\nfrom dots_ocr.utils.demo_utils.display import read_image\n\n\n\n# ==================== Configuration ====================\nDEFAULT_CONFIG = {\n    'ip': \"127.0.0.1\",\n    'port_vllm': 8000,\n    'min_pixels': MIN_PIXELS,\n    'max_pixels': MAX_PIXELS,\n    'test_images_dir': \"./assets/showcase_origin\",\n}\n\n# ==================== Utility Functions ====================\n\n\n@st.cache_resource\ndef read_image_v2(img: str):\n    if img.startswith((\"http://\", \"https://\")):\n        with requests.get(img, stream=True) as response:\n            response.raise_for_status()\n            img = Image.open(io.BytesIO(response.content))\n\n    if isinstance(img, str):\n        # img = transform_image_path(img)\n        img, _, _ = read_image(img, use_native=True)\n    elif isinstance(img, Image.Image):\n        pass\n    else:\n        raise ValueError(f\"Invalid image type: {type(img)}\")\n    return img\n\n\n# ==================== UI Components ====================\ndef create_config_sidebar():\n    \"\"\"Create configuration sidebar\"\"\"\n    st.sidebar.header(\"Configuration Parameters\")\n    \n    config = {}\n    config['prompt_key'] = st.sidebar.selectbox(\"Prompt Mode\", list(dict_promptmode_to_prompt.keys()))\n    config['ip'] = st.sidebar.text_input(\"Server IP\", DEFAULT_CONFIG['ip'])\n    config['port'] = st.sidebar.number_input(\"Port\", min_value=1000, max_value=9999, value=DEFAULT_CONFIG['port_vllm'])\n    # config['eos_word'] = st.sidebar.text_input(\"EOS Word\", DEFAULT_CONFIG['eos_word'])\n    \n    # Image configuration\n    st.sidebar.subheader(\"Image Configuration\")\n    config['min_pixels'] = st.sidebar.number_input(\"Min Pixels\", value=DEFAULT_CONFIG['min_pixels'])\n    config['max_pixels'] = st.sidebar.number_input(\"Max Pixels\", value=DEFAULT_CONFIG['max_pixels'])\n    \n    return config\n\ndef get_image_input():\n    \"\"\"Get image input\"\"\"\n    st.markdown(\"#### Image Input\")\n    \n    input_mode = st.pills(label=\"Select input method\", options=[\"Upload Image\", \"Enter Image URL/Path\", \"Select Test Image\"], key=\"input_mode\", label_visibility=\"collapsed\")\n\n    if input_mode == \"Upload Image\":\n        # File uploader\n        uploaded_file = st.file_uploader(\"Upload Image\", type=[\"png\", \"jpg\", \"jpeg\"])\n        if uploaded_file is not None:\n            with tempfile.NamedTemporaryFile(delete=False, suffix='.png') as tmp_file:\n                tmp_file.write(uploaded_file.getvalue())\n                return tmp_file.name\n    elif input_mode == 'Enter Image URL/Path':\n        # URL input\n        img_url_input = st.text_input(\"Enter Image URL/Path\")\n        return img_url_input\n\n    elif input_mode == 'Select Test Image':\n        # Test image selection\n        test_images = []\n        test_dir = DEFAULT_CONFIG['test_images_dir']\n        if os.path.exists(test_dir):\n            test_images = [os.path.join(test_dir, name) for name in os.listdir(test_dir)]\n        img_url_test = st.selectbox(\"Select Test Image\", [\"\"] + test_images)\n        return img_url_test\n    else:\n        raise ValueError(f\"Invalid input mode: {input_mode}\")\n\n    return None\n\n\n\ndef process_and_display_results(output: str, image: Image.Image, config: dict):\n    \"\"\"Process and display inference results\"\"\"\n    prompt, response = output['prompt'], output['response']\n    \n    try:\n        col1, col2 = st.columns(2)\n        # st.markdown('---')\n        cells = json.loads(response)\n        # image = Image.open(img_url)\n        \n        # Post-processing\n        cells = post_process_cells(\n            image, cells,\n            image.width, image.height,\n            min_pixels=config['min_pixels'],\n            max_pixels=config['max_pixels']\n        )\n        \n        # Calculate input dimensions\n        input_width, input_height = get_input_dimensions(\n            image,\n            min_pixels=config['min_pixels'],\n            max_pixels=config['max_pixels']\n        )\n        st.markdown('---')\n        st.write(f'Input Dimensions: {input_width} x {input_height}')\n        # st.write(f'Prompt: {prompt}')\n        # st.markdown(f'模型原始输出: <span style=\"color:blue\">{result}</span>', unsafe_allow_html=True)\n        # st.write('模型原始输出：')\n        # st.write(response)\n        # st.write('后处理结果:', str(cells))\n        st.text_area('Original Model Output', response, height=200)\n        st.text_area('Post-processed Result', str(cells), height=200)\n        # 显示结果\n        # st.title(\"Layout推理结果\")\n        \n        with col1:\n            # st.markdown(\"##### 可视化结果\")\n            new_image = draw_layout_on_image(\n                image, cells, \n                resized_height=None, resized_width=None,\n                # text_key='text', \n                fill_bbox=True, draw_bbox=True\n            )\n            st.markdown('##### Visualization Result')\n            st.image(new_image, width=new_image.width)\n            # st.write(f\"尺寸: {new_image.width} x {new_image.height}\")\n        \n        with col2:\n            # st.markdown(\"##### Markdown格式\")\n            md_code = layoutjson2md(image, cells, text_key='text')\n            # md_code = fix_streamlit_formula(md_code)\n            st.markdown('##### Markdown Format')\n            st.markdown(md_code, unsafe_allow_html=True)\n            \n    except json.JSONDecodeError:\n        st.error(\"Model output is not a valid JSON format\")\n    except Exception as e:\n        st.error(f\"Error processing results: {e}\")\n\n# ==================== Main Application ====================\ndef main():\n    \"\"\"Main application function\"\"\"\n    st.set_page_config(page_title=\"Layout Inference Tool\", layout=\"wide\")\n    st.title(\"🔍 Layout Inference Tool\")\n    \n    # Configuration\n    config = create_config_sidebar()\n    prompt = dict_promptmode_to_prompt[config['prompt_key']]\n    st.sidebar.info(f\"Current Prompt: {prompt}\")\n    \n    # Image input\n    img_url = get_image_input()\n    start_button = st.button('🚀 Start Inference', type=\"primary\")\n    \n    if img_url is not None and img_url.strip() != \"\":\n        try:\n            # processed_image = read_image_v2(img_url)\n            origin_image = read_image_v2(img_url)\n            st.write(f\"Original Dimensions: {origin_image.width} x {origin_image.height}\")\n            # processed_image = get_image_by_fitz_doc(origin_image, target_dpi=200)\n            processed_image = origin_image\n        except Exception as e:\n            st.error(f\"Failed to read image: {e}\")\n            return\n    else:\n        st.info(\"Please enter an image URL/path or upload an image\")\n        return\n\n    output = None\n    # Inference button\n    if start_button:\n        with st.spinner(f\"Inferring... Server: {config['ip']}:{config['port']}\"):\n            \n            response = inference_with_vllm(\n                processed_image, prompt, config['ip'], config['port'],\n                # config['min_pixels'], config['max_pixels']\n            )\n            output = {\n                'prompt': prompt,\n                'response': response,\n            }\n    else:\n        st.image(processed_image, width=500)\n\n    # Process results\n    if output:\n        process_and_display_results(output, processed_image, config)\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "demo/demo_vllm.py",
    "content": "import argparse\n\nfrom openai import OpenAI\nfrom transformers.utils.versions import require_version\nfrom PIL import Image\nfrom dots_ocr.utils import dict_promptmode_to_prompt\nfrom dots_ocr.model.inference import inference_with_vllm\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--ip\", type=str, default=\"localhost\")\nparser.add_argument(\"--port\", type=str, default=\"8000\")\nparser.add_argument(\"--model_name\", type=str, default=\"rednote-hilab/dots.ocr-1.5\")\nparser.add_argument(\"--image_path\", type=str, default=\"demo/demo_image1.jpg\")\nparser.add_argument(\"--prompt_mode\", type=str, default=\"prompt_layout_all_en\",help=(\n        \"Choose a task prompt: \"\n        \"prompt_layout_all_en=full document layout+OCR to JSON/MD; \"\n        \"prompt_layout_only_en=layout detection only; \"\n        \"prompt_grounding_ocr=OCR within a given bbox; \"\n        \"prompt_web_parsing=parse webpage screenshot layout into JSON; \"\n        \"prompt_scene_spotting=detect+recognize scene text (OCR boxes+texts); \"\n        \"prompt_image_to_svg=generate SVG code to reconstruct the image.\")\n)\n\nargs = parser.parse_args()\n\nrequire_version(\"openai>=1.5.0\", \"To fix: pip install openai>=1.5.0\")\n\n\ndef main():\n    addr = f\"http://{args.ip}:{args.port}/v1\"\n    image_path = args.image_path\n    prompt = dict_promptmode_to_prompt[args.prompt_mode]\n    image = Image.open(image_path)\n    response = inference_with_vllm(\n        image,\n        prompt, \n        ip=args.ip,\n        port=args.port,\n        temperature=0.1,\n        top_p=0.9,\n        model_name=args.model_name,\n    )\n    print(f\"response: {response}\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "demo/demo_vllm_general.py",
    "content": "import argparse\n\nfrom openai import OpenAI\nfrom transformers.utils.versions import require_version\nfrom PIL import Image\nfrom dots_ocr.utils import dict_promptmode_to_prompt\nfrom dots_ocr.model.inference import inference_with_vllm\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--ip\", type=str, default=\"localhost\")\nparser.add_argument(\"--port\", type=str, default=\"8000\")\nparser.add_argument(\"--model_name\", type=str, default=\"rednote-hilab/dots.ocr-1.5\")\nparser.add_argument(\"--custom_prompt\", type=str, default=\"Please describe the content of this image.\")\n\nargs = parser.parse_args()\n\nrequire_version(\"openai>=1.5.0\", \"To fix: pip install openai>=1.5.0\")\n\n\ndef main():\n    addr = f\"http://{args.ip}:{args.port}/v1\"\n    image_path = \"demo/demo_image3.jpg\"\n    prompt = args.custom_prompt\n    image = Image.open(image_path)\n    response = inference_with_vllm(\n        image,\n        prompt, \n        ip=args.ip,\n        port=args.port,\n        temperature=0.1,\n        top_p=0.9,\n        model_name=args.model_name,\n        system_prompt=\"You are a helpful assistant.\", #general tasks need system_prompt\n    )\n    print(f\"response: {response}\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "demo/demo_vllm_svg.py",
    "content": "import argparse\n\nfrom openai import OpenAI\nfrom transformers.utils.versions import require_version\nfrom PIL import Image\nfrom dots_ocr.utils import dict_promptmode_to_prompt\nfrom dots_ocr.model.inference import inference_with_vllm\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--ip\", type=str, default=\"localhost\")\nparser.add_argument(\"--port\", type=str, default=\"8000\")\nparser.add_argument(\"--model_name\", type=str, default=\"rednote-hilab/dots.ocr-1.5-svg\")\nparser.add_argument(\"--prompt_mode\", type=str, default=\"prompt_image_to_svg\")\n\nargs = parser.parse_args()\n\nrequire_version(\"openai>=1.5.0\", \"To fix: pip install openai>=1.5.0\")\n\n\ndef main():\n    addr = f\"http://{args.ip}:{args.port}/v1\"\n    image_path = \"demo/demo_image2.png\"\n    image = Image.open(image_path)\n    prompt = dict_promptmode_to_prompt[args.prompt_mode]\n\n    #prompt = Please generate the SVG code based on the image.viewBox=\"0 0 {img_width} {img_height}\"\n    prompt = prompt.replace(\"{width}\", str(image.width)).replace(\"{height}\", str(image.height))\n\n    response = inference_with_vllm(\n        image,\n        prompt, \n        ip=args.ip,\n        port=args.port,\n        temperature=0.9,           # SVG: low temperature often causes repetitive/looping output\n        top_p=1.0,\n        model_name=args.model_name,\n    )\n    print(f\"response: {response}\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "demo/launch_model_vllm.sh",
    "content": "# download model to /path/to/model\nif [ -z \"$NODOWNLOAD\" ]; then\n    python3 tools/download_model.py\nfi\n\n# register model to vllm\nhf_model_path=./weights/DotsOCR  # Path to your downloaded model weights\nexport PYTHONPATH=$(dirname \"$hf_model_path\"):$PYTHONPATH\nsed -i '/^from vllm\\.entrypoints\\.cli\\.main import main$/a\\\nfrom DotsOCR import modeling_dots_ocr_vllm' `which vllm`\n\n# launch vllm server\nmodel_name=model\nCUDA_VISIBLE_DEVICES=0 vllm serve ${hf_model_path} --tensor-parallel-size 1 --gpu-memory-utilization 0.95  --chat-template-content-format string --served-model-name ${model_name} --trust-remote-code\n\n# # run python demo after launch vllm server\n# python demo/demo_vllm.py"
  },
  {
    "path": "docker/Dockerfile",
    "content": "# Dots OCR has been officially integrated into vLLM since v0.11.0\n# Below is the dockerfile for out-of-tree model registration support based on v0.9.1\nfrom vllm/vllm-openai:v0.9.1\n\nRUN pip3 install flash_attn==2.8.0.post2\nRUN pip3 install transformers==4.51.3\n"
  },
  {
    "path": "docker/docker-compose.yml",
    "content": "version: '3.8'\r\n\r\nservices:\r\n  dots-ocr-server:\r\n    image: dots-ocr:latest\r\n    container_name: dots-ocr-container\r\n    ports:\r\n      - \"8000:8000\"\r\n    volumes:\r\n      #download model to local，model url：https://www.modelscope.cn/models/rednote-hilab/dots.ocr\r\n      - ./model/dots.ocr:/workspace/weights/DotsOCR\r\n    environment:\r\n      - PYTHONPATH=/workspace/weights:$PYTHONPATH\r\n    deploy:\r\n      resources:\r\n        reservations:\r\n          devices:\r\n            - capabilities: [gpu]\r\n              device_ids: ['0']\r\n    entrypoint: /bin/bash\r\n    command:\r\n      - -c\r\n      - |\r\n        set -ex;\r\n        echo '--- Starting setup and server ---';\r\n        echo 'Modifying vllm entrypoint...';\r\n        # This sed command patches the vllm entrypoint script to import the custom modeling code.\r\n        sed -i '/^from vllm\\.entrypoints\\.cli\\.main import main/a from DotsOCR import modeling_dots_ocr_vllm' $(which vllm) && \\\r\n        echo 'vllm script after patch:';\r\n        # Show the patched part of the vllm script for verification.\r\n        grep -A 1 'from vllm.entrypoints.cli.main import main' $(which vllm) && \\\r\n        echo 'Starting server...';\r\n        # Use 'exec' to replace the current shell process with the vllm server,\r\n        # ensuring logs are properly forwarded to Docker's standard output.\r\n        exec vllm serve /workspace/weights/DotsOCR \\\r\n            --tensor-parallel-size 1 \\\r\n            --gpu-memory-utilization 0.8 \\\r\n            --chat-template-content-format string \\\r\n            --served-model-name dotsocr-model \\\r\n            --trust-remote-code\r\n\r\n\r\n\r\n\r\n"
  },
  {
    "path": "dots.ocr LICENSE AGREEMENT",
    "content": "dots.ocr LICENSE AGREEMENT\n\nEffective Date: [ August 8, 2025]\n\nCopyright Holder: [Xingyin Information Technology (Shanghai) Co., Ltd]\n\nThis License Agreement (“Agreement”) governs Your use, reproduction, modification, and distribution of dots.ocr (the \"Model Materials\"). This Agreement is designed to maximize the openness and use of the Model Materials while addressing the unique legal, ethical, and technical challenges posed by large language models.\n\nWHEREAS, Licensor has developed the dots.ocr document parsing model and intends to distribute the Model Materials under an open‑source framework;\nWHEREAS, traditional open-source licenses (e.g., the MIT License) may not fully address the complexity inherent complexities of document parsing models, namely their multiple components (code, weights, training data), potential ethical risks, data‑governance issues, and intellectual‑property and liability questions regarding AI‑generated content;\nWHEREAS, Licensor seeks to provide a legal framework that ensures maximum access to and use of the Model Materials while clearly defining the rights, obligations, and liabilities of Licensee;\n\nTHEREFORE, the parties agree that, subject to the MIT License, they shall be bound by the following terms and conditions:\n\n1. Definitions and Interpretation\nPurpose: To define key terms used in this Agreement, particularly \"Model Materials,\" ensuring clarity of the license scope beyond traditional software code. To clarify the order of precedence between this Agreement and the MIT License to avoid conflict.\n\n1.1 “Licensor” shall mean the entity providing the Model Materials under this Agreement, namely [Xingyin Information Technology (Shanghai) Co., Ltd].\n\n1.2 “Licensee” or \"You\" shall mean any individual or entity exercising permissions granted by this Agreement.\n\n1.3 “Model Materials” shall mean all materials provided by Licensor under this Agreement, including but not limited to:\n        (a) one or more machine‑learning models, including architecture and trained parameters (i.e., model weights);\n        (b) all associated preprocessing, training, inference, and fine‑tuning code;\n        (c) training datasets and evaluation scripts (or their detailed descriptions and access mechanisms); and\n        (d) any accompanying documentation, metadata, and tools.\nThe above Model Materials shall be subject to the content published on the Licensor’s website or GitHub repository at https://github.com/rednote-hilab/dots.ocr.\n\n1.4 “Outputs” shall mean any content generated through the use of the Model Materials, such as text, tables, code,layout information, and formulas extracted from documents.\n\n1.5 “MIT License” shall mean The MIT Open Source License published by the Massachusetts Institute of Technology.\n\n1.6   Priority of Agreement. In the event of any conflict or inconsistency between this Agreement and the MIT License, the terms of the MIT License shall prevail. However, if the terms of the MIT License are ambiguous or silent on a particular matter, the provisions of this Agreement shall apply and supplement the MIT License.\n\n2. Grant of Rights and Scope of Use\n\nPurpose: To grant broad, permissive rights to the Licensee for the Model Materials—including code, weights, data, and documentation—to ensure maximum openness and flexibility while clarifying the free use of model-generated content. Additionally, it clarifies the feasibility of transitioning from open-source to commercial‑use and the use of OpenAPI interfaces.\n\n2.1   Grant of Copyright License. Subject to Licensee's compliance with this Agreement, Licensor hereby grants Licensee a perpetual, worldwide, non‑exclusive, no-charge, royalty‑free copyright license to use (run or test), reproduce, modify, create derivative works of, merge, publish, distribute the Model Materials; sublicense and/or sell copies of the Model Materials or any derivative works thereof; and incorporate the unmodified or modified Model Materials into proprietary products or services, including for commercial purposes, software‑as‑a‑service (SaaS) offerings, or via OpenAPI or other interfaces.\n\n2.2   Fundamental Capabilities. The Model Materials only provide the fundamental model’s capabilities. Licensees may develop derivative AI applications or undertake task‑specific training thereon.\n\n2.3   From Open Source to Commercial Use. The open-source release does not preclude Licensor’s commercial exploitation of the Model Materials, in whole or in part. Any such commercial use shall, at that time, be subject to license agreements between Licensor and applicable users.\n\n2.4   API‑Service Exception. Licensees who access the Model Materials through API calls or provide model services via API interfaces(without directly distributing model weights )shall not be subject to this Agreement unless otherwise expressly agreed. Instead, such use shall be governed by the API terms of use published by Licensor (if any).\n\n3. Acceptable Use Policy and Prohibited Uses\n\n3.1   Responsible Use. Licensee must use the Model Materials in a responsible, ethical, and lawful manner, in compliance with all applicable laws, regulations, industry standards, and best practices.\n\n3.2   Enterprise On‑Premises Deployment. The Licensee may deploy the Model Materials in closed‑source, on‑premises enterprise environments.\n\n3.3   Prohibited Uses. Any breach of the prohibitions below will result in the automatic termination of all licenses granted under this Agreement. Licensee agrees not to use the Model Materials or any derivative works thereof, in connection with:\n(a) Identification and Utilization of Illegal/Harmful Content:Includes identifying graphic/text materials used for counterfeiting certificates/invoices, perpetrating fraud, or launching cyberattacks; or processing images containing illegal content such as violence, criminal activities, disinformation, or child exploitation.\n(b) Privacy Infringement and Discriminatory Practices:Extracting personal sensitive information (e.g., ID numbers, medical records, biometric data) or protected characteristics (e.g., race, gender) from images without legal authorization or consent, for purposes of privacy violation, automated discriminatory decision-making, or harassment.\n(c) Copyright Restrictions:Licensees shall not use the tool for unauthorized digitization of publications/document scanning or bulk scraping of content. Any use involving publications or other copyright-protected materials must first obtain relevant permissions.\n\n4. Intellectual Property Ownership and Contributions\n\n4.1   Licensor's Copyright Reservation. Licensor reserves all right, title, and interest in and to the Model Materials (including the model architecture, parameters, code, and original training data), except as expressly licensed herein. The original copyright of the Model Materials belongs to the Licensor.\n\n4.2   Patent License. Subject to the terms and conditions of this Agreement, Licensor hereby grants Licensee a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Model Materials, where such license applies only to those patent claims licensable by the Lisensor that are necessarily infringed by its contribution(s). \nIf Licensee institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Model Materials constitute direct or contributory patent infringement, then any patent licenses granted under this License for the Model Materials shall terminate as of the date such litigation is asserted or filed.\n\n4.3   Outputs: The Outputs generated through the use of the Model Materials generally refer to text, tables, layouts, and other content extracted from documents or images. The extracted content itself does not generate new intellectual property rights, and all intellectual property remains with the original authors or copyright holders. The Licensee is responsible for due diligence regarding the legality of the Outputs, particularly where the content extracted by the OCR model may be substantially similar to existing copyrighted works, which could present intellectual property infringement risks. The Licensor assumes no liability for such infringements.\n4.4   Trademarks. Nothing in this License permits Licensee to make use of Licensor’s trademarks, trade names, logos (e.g., “rednote,” “Xiaohongshu,” “dots.ocr”) or to otherwise suggest endorsement or misrepresent the relationship between the parties, unless Licensor’s prior written approval is granted.\n\n5. Data Governance, Privacy, and Security\n \n5.1   Data Quality and Bias. Licensee shall use training data from lawful sources and is encouraged to conduct due diligence before deploying the Model Materials and to take reasonable steps to mitigate any known biases in its training data or applications.\n\n5.2   Privacy Protection.\n        (a) Sensitive‑Data Restrictions. It is prohibited to use the Model Materials to process,or extract infer sensitive personal data protected under specific laws (such as GDPR or HIPAA), particularly when dealing with documents containing personally identifiable information (such as ID numbers, health data, financial information, etc.), unless Licensee has obtained all necessary consents, lawful basis, or authorizations, and has implemented adequate anonymization, pseudonymization, or other privacy-enhancing technologies.\n        (b) Data Minimization and Purpose Limitation. The Licensee shall follow the principle of data minimization when using the OCR Model, processing only the user data necessary for specific, explicit, and lawful purposes. Specifically, the OCR Model should avoid processing unnecessary sensitive data and ensure compliance with applicable privacy protection laws during data handling.\n        (c) Transparency. Licensee shall provide clear and transparent privacy policies and terms of use when processing user data, particularly during document scanning and information extraction. . \n\n5.3   Security Measures. Licensee shall implement appropriate technical and administrative safeguards to protect the Model Materials and any associated data against unauthorized access, disclosure, alteration, or destruction. Such measures may include, but are not limited to, encryption, access controls, logging, and audit trails.\n\n5.4   Further Training. Licensee may only use user‑provided input or Outputs for training, fine-tuning, or improving other AI models if it has obtained the specific and informed consent of data subjects.\n\n6. Disclaimer of Warranty and Limitation of Liability\n\n6.1 “AS IS” Basis. Unless required by applicable law, the Model Materials are provided 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. Licensee is solely responsible for determining the appropriateness of using or redistributing the Model Materials and assume any risks associated with the exercise of permissions under this License. Licensor does not provide any warranty of non-infringement but represents that no infringing code has been knowingly included.\n\n6.2   Outputs Disclaimer. As a neutral technology, Licensor disclaims all liability for the accuracy, completeness, reliability, safety, legality, or suitability of any Outputs. The Licensee is solely responsible for verifying the accuracy and appropriateness of AI-generated content and shall provide appropriate disclosures when publishing or relying upon such content.\n\n6.3   Limitation of Liability and Recourse. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall Licensor or contributors be liable for any claims, 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 Materials (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 Licensor has been advised of the possibility of such damages. If such losses are incurred, recourse may be sought against the Licensee responsible for causing the loss.\n\n6.4   Content‑Filtering Disclaimer. Although the Model Materials may include content‑filtering mechanisms, Licensor makes no warranties of any kind regarding the stability, quality, accuracy, completeness, or any specific outcome of Outputs. Licensee is solely responsible for reviewing, verifying, and performing quality control on Outputs and assumes all associated risks and liabilities.\n\n7. Attribution and License Reservation\n\n7.1   License. When distributing or redistributing the Model Materials, Licensee must give any other recipients of the Model Materials a copy of this Agreement.\n\n7.2   Copyright and Notices. When distributing any part of the Model Materials, Licensee must retain all copyright, patent, trademark, and attribution notices included in the Model Materials.\n\n7.3   Attribution. Licensee is encouraged to prominently display the name of Licensor and the Model Materials in any public statements, products, or services that contain the Model Materials (or any derivative works thereof), to promote transparency and community trust. If Licensee distributes modified weights or fine‑tuned models based on the Model Materials, Licensee must prominently display the following statement in the related website or documentation: “Built with dots.ocr.”\n\n8. Governing Law and Dispute Resolution\n\n8.1   Governing Law. This Agreement shall be governed by and construed in accordance with the laws of the People’s Republic of China, without regard to its conflict of laws principles.\n\n8.2   Dispute Resolution. Any dispute claim, or disagreement arising out of or relating to this Agreement shall first be resolved through amicable consultation. If such consultation fails, the dispute shall be submitted to the Hangzhou Arbitration Commission for arbitration. The arbitration shall be conducted in accordance with the laws of China, and the place of arbitration shall be [Hangzhou, China]. The arbitral award shall be final and binding upon both parties.\n\n9. Regulatory Compliance Amendments\nIn the event that any part of this Agreement becomes invalid or requires adjustment due to changes in applicable laws or regulations, Licensor reserves the right to issue a revised version of this Agreement. Licensee shall migrate to the new version within [e.g., ninety (90)] days of its release; otherwise, all rights granted under this Agreement shall automatically terminate.\n\n10. Security Reporting\nLicensee discovering any security vulnerability in the Model Materials may report it to Licensor via: dots-feedback@xiaohongshu.com. Licensee shall not disclose vulnerability details until Licensor issues an official remediation, unless otherwise required by law."
  },
  {
    "path": "dots_ocr/__init__.py",
    "content": "from .parser import DotsOCRParser"
  },
  {
    "path": "dots_ocr/model/inference.py",
    "content": "import requests\nfrom dots_ocr.utils.image_utils import PILimage_to_base64\nfrom openai import OpenAI\nimport os\n\n\ndef inference_with_vllm(\n        image,\n        prompt, \n        protocol=\"http\",\n        ip=\"localhost\",\n        port=8000,\n        temperature=0.1,\n        top_p=0.9,\n        max_completion_tokens=32768,\n        model_name='rednote-hilab/dots.ocr',\n        system_prompt=None,\n        ):\n    \n    addr = f\"{protocol}://{ip}:{port}/v1\"\n    client = OpenAI(api_key=\"{}\".format(os.environ.get(\"API_KEY\", \"0\")), base_url=addr)\n    messages = []\n    if system_prompt:\n        messages.append({\"role\": \"system\", \"content\": system_prompt})\n    messages.append(\n        {\n            \"role\": \"user\",\n            \"content\": [\n                {\n                    \"type\": \"image_url\",\n                    \"image_url\": {\"url\":  PILimage_to_base64(image)},\n                },\n                {\"type\": \"text\", \"text\": f\"<|img|><|imgpad|><|endofimg|>{prompt}\"}  # if no \"<|img|><|imgpad|><|endofimg|>\" here,vllm v1 will add \"\\n\" here\n            ],\n        }\n    )\n    try:\n        response = client.chat.completions.create(\n            messages=messages, \n            model=model_name, \n            max_completion_tokens=max_completion_tokens,\n            temperature=temperature,\n            top_p=top_p)\n        response = response.choices[0].message.content\n        return response\n    except requests.exceptions.RequestException as e:\n        print(f\"request error: {e}\")\n        return None\n\n"
  },
  {
    "path": "dots_ocr/parser.py",
    "content": "import os\nimport json\nfrom tqdm import tqdm\nfrom multiprocessing.pool import ThreadPool, Pool\nimport argparse\n\n\nfrom dots_ocr.model.inference import inference_with_vllm\nfrom dots_ocr.utils.consts import image_extensions, MIN_PIXELS, MAX_PIXELS\nfrom dots_ocr.utils.image_utils import get_image_by_fitz_doc, fetch_image, smart_resize\nfrom dots_ocr.utils.doc_utils import fitz_doc_to_image, load_images_from_pdf\nfrom dots_ocr.utils.prompts import dict_promptmode_to_prompt\nfrom dots_ocr.utils.layout_utils import post_process_output, draw_layout_on_image, pre_process_bboxes\nfrom dots_ocr.utils.format_transformer import layoutjson2md\n\n\nclass DotsOCRParser:\n    \"\"\"\n    parse image or pdf file\n    \"\"\"\n    \n    def __init__(self, \n            protocol='http',\n            ip='localhost',\n            port=8000,\n            model_name='model',\n            temperature=0.1,\n            top_p=1.0,\n            max_completion_tokens=16384,\n            num_thread=64,\n            dpi = 200, \n            output_dir=\"./output\", \n            min_pixels=None,\n            max_pixels=None,\n            use_hf=False,\n        ):\n        self.dpi = dpi\n\n        # default args for vllm server\n        self.protocol = protocol\n        self.ip = ip\n        self.port = port\n        self.model_name = model_name\n        # default args for inference\n        self.temperature = temperature\n        self.top_p = top_p\n        self.max_completion_tokens = max_completion_tokens\n        self.num_thread = num_thread\n        self.output_dir = output_dir\n        self.min_pixels = min_pixels\n        self.max_pixels = max_pixels\n\n        self.use_hf = use_hf\n        if self.use_hf:\n            self._load_hf_model()\n            print(f\"use hf model, num_thread will be set to 1\")\n        else:\n            print(f\"use vllm model, num_thread will be set to {self.num_thread}\")\n        assert self.min_pixels is None or self.min_pixels >= MIN_PIXELS\n        assert self.max_pixels is None or self.max_pixels <= MAX_PIXELS\n\n    def _load_hf_model(self):\n        import torch\n        from transformers import AutoModelForCausalLM, AutoProcessor, AutoTokenizer\n        from qwen_vl_utils import process_vision_info\n\n        model_path = \"./weights/DotsOCR\"\n        self.model = AutoModelForCausalLM.from_pretrained(\n            model_path,\n            attn_implementation=\"flash_attention_2\",\n            torch_dtype=torch.bfloat16,\n            device_map=\"auto\",\n            trust_remote_code=True\n        )\n        self.processor = AutoProcessor.from_pretrained(model_path,  trust_remote_code=True,use_fast=True)\n        self.process_vision_info = process_vision_info\n\n    def _inference_with_hf(self, image, prompt):\n        messages = [\n            {\n                \"role\": \"user\",\n                \"content\": [\n                    {\n                        \"type\": \"image\",\n                        \"image\": image\n                    },\n                    {\"type\": \"text\", \"text\": prompt}\n                ]\n            }\n        ]\n\n        # Preparation for inference\n        text = self.processor.apply_chat_template(\n            messages, \n            tokenize=False, \n            add_generation_prompt=True\n        )\n        image_inputs, video_inputs = self.process_vision_info(messages)\n        inputs = self.processor(\n            text=[text],\n            images=image_inputs,\n            videos=video_inputs,\n            padding=True,\n            return_tensors=\"pt\",\n        )\n\n        inputs = inputs.to(\"cuda\")\n\n        # Inference: Generation of the output\n        generated_ids = self.model.generate(**inputs, max_new_tokens=24000)\n        generated_ids_trimmed = [\n            out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)\n        ]\n        response = self.processor.batch_decode(\n            generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False\n        )[0]\n        return response\n\n    def _inference_with_vllm(self, image, prompt):\n        response = inference_with_vllm(\n            image,\n            prompt, \n            model_name=self.model_name,\n            protocol=self.protocol,\n            ip=self.ip,\n            port=self.port,\n            temperature=self.temperature,\n            top_p=self.top_p,\n            max_completion_tokens=self.max_completion_tokens,\n        )\n        return response\n\n    def get_prompt(self, prompt_mode, bbox=None, origin_image=None, image=None, min_pixels=None, max_pixels=None):\n        prompt = dict_promptmode_to_prompt[prompt_mode]\n        if prompt_mode == 'prompt_grounding_ocr':\n            assert bbox is not None\n            bboxes = [bbox]\n            bbox = pre_process_bboxes(origin_image, bboxes, input_width=image.width, input_height=image.height, min_pixels=min_pixels, max_pixels=max_pixels)[0]\n            prompt = prompt + str(bbox)\n        return prompt\n\n    # def post_process_results(self, response, prompt_mode, save_dir, save_name, origin_image, image, min_pixels, max_pixels)\n    def _parse_single_image(\n        self, \n        origin_image, \n        prompt_mode, \n        save_dir, \n        save_name, \n        source=\"image\", \n        page_idx=0, \n        bbox=None,\n        fitz_preprocess=False,\n        ):\n        min_pixels, max_pixels = self.min_pixels, self.max_pixels\n        if prompt_mode == \"prompt_grounding_ocr\":\n            min_pixels = min_pixels or MIN_PIXELS  # preprocess image to the final input\n            max_pixels = max_pixels or MAX_PIXELS\n        if min_pixels is not None: assert min_pixels >= MIN_PIXELS, f\"min_pixels should >= {MIN_PIXELS}\"\n        if max_pixels is not None: assert max_pixels <= MAX_PIXELS, f\"max_pixels should <= {MAX_PIXELS}\"\n\n        if source == 'image' and fitz_preprocess:\n            image = get_image_by_fitz_doc(origin_image, target_dpi=self.dpi)\n            image = fetch_image(image, min_pixels=min_pixels, max_pixels=max_pixels)\n        else:\n            image = fetch_image(origin_image, min_pixels=min_pixels, max_pixels=max_pixels)\n        input_height, input_width = smart_resize(image.height, image.width)\n        prompt = self.get_prompt(prompt_mode, bbox, origin_image, image, min_pixels=min_pixels, max_pixels=max_pixels)\n        if self.use_hf:\n            response = self._inference_with_hf(image, prompt)\n        else:\n            response = self._inference_with_vllm(image, prompt)\n        result = {'page_no': page_idx,\n            \"input_height\": input_height,\n            \"input_width\": input_width\n        }\n        if source == 'pdf':\n            save_name = f\"{save_name}_page_{page_idx}\"\n        if prompt_mode in ['prompt_layout_all_en', 'prompt_layout_only_en', 'prompt_grounding_ocr']:\n            cells, filtered = post_process_output(\n                response, \n                prompt_mode, \n                origin_image, \n                image,\n                min_pixels=min_pixels, \n                max_pixels=max_pixels,\n                )\n            if filtered and prompt_mode != 'prompt_layout_only_en':  # model output json failed, use filtered process\n                json_file_path = os.path.join(save_dir, f\"{save_name}.json\")\n                with open(json_file_path, 'w', encoding=\"utf-8\") as w:\n                    json.dump(response, w, ensure_ascii=False)\n\n                image_layout_path = os.path.join(save_dir, f\"{save_name}.jpg\")\n                origin_image.save(image_layout_path)\n                result.update({\n                    'layout_info_path': json_file_path,\n                    'layout_image_path': image_layout_path,\n                })\n\n                md_file_path = os.path.join(save_dir, f\"{save_name}.md\")\n                with open(md_file_path, \"w\", encoding=\"utf-8\") as md_file:\n                    md_file.write(cells)\n                result.update({\n                    'md_content_path': md_file_path\n                })\n                result.update({\n                    'filtered': True\n                })\n            else:\n                try:\n                    image_with_layout = draw_layout_on_image(origin_image, cells)\n                except Exception as e:\n                    print(f\"Error drawing layout on image: {e}\")\n                    image_with_layout = origin_image\n\n                json_file_path = os.path.join(save_dir, f\"{save_name}.json\")\n                with open(json_file_path, 'w', encoding=\"utf-8\") as w:\n                    json.dump(cells, w, ensure_ascii=False)\n\n                image_layout_path = os.path.join(save_dir, f\"{save_name}.jpg\")\n                image_with_layout.save(image_layout_path)\n                result.update({\n                    'layout_info_path': json_file_path,\n                    'layout_image_path': image_layout_path,\n                })\n                if prompt_mode != \"prompt_layout_only_en\":  # no text md when detection only\n                    md_content = layoutjson2md(origin_image, cells, text_key='text')\n                    md_content_no_hf = layoutjson2md(origin_image, cells, text_key='text', no_page_hf=True) # used for clean output or metric of omnidocbench、olmbench \n                    md_file_path = os.path.join(save_dir, f\"{save_name}.md\")\n                    with open(md_file_path, \"w\", encoding=\"utf-8\") as md_file:\n                        md_file.write(md_content)\n                    md_nohf_file_path = os.path.join(save_dir, f\"{save_name}_nohf.md\")\n                    with open(md_nohf_file_path, \"w\", encoding=\"utf-8\") as md_file:\n                        md_file.write(md_content_no_hf)\n                    result.update({\n                        'md_content_path': md_file_path,\n                        'md_content_nohf_path': md_nohf_file_path,\n                    })\n        else:\n            image_layout_path = os.path.join(save_dir, f\"{save_name}.jpg\")\n            origin_image.save(image_layout_path)\n            result.update({\n                'layout_image_path': image_layout_path,\n            })\n\n            md_content = response\n            md_file_path = os.path.join(save_dir, f\"{save_name}.md\")\n            with open(md_file_path, \"w\", encoding=\"utf-8\") as md_file:\n                md_file.write(md_content)\n            result.update({\n                'md_content_path': md_file_path,\n            })\n\n        return result\n    \n    def parse_image(self, input_path, filename, prompt_mode, save_dir, bbox=None, fitz_preprocess=False):\n        origin_image = fetch_image(input_path)\n        result = self._parse_single_image(origin_image, prompt_mode, save_dir, filename, source=\"image\", bbox=bbox, fitz_preprocess=fitz_preprocess)\n        result['file_path'] = input_path\n        return [result]\n        \n    def parse_pdf(self, input_path, filename, prompt_mode, save_dir):\n        print(f\"loading pdf: {input_path}\")\n        images_origin = load_images_from_pdf(input_path, dpi=self.dpi)\n        total_pages = len(images_origin)\n        tasks = [\n            {\n                \"origin_image\": image,\n                \"prompt_mode\": prompt_mode,\n                \"save_dir\": save_dir,\n                \"save_name\": filename,\n                \"source\":\"pdf\",\n                \"page_idx\": i,\n            } for i, image in enumerate(images_origin)\n        ]\n\n        def _execute_task(task_args):\n            return self._parse_single_image(**task_args)\n\n        if self.use_hf:\n            num_thread =  1\n        else:\n            num_thread = min(total_pages, self.num_thread)\n        print(f\"Parsing PDF with {total_pages} pages using {num_thread} threads...\")\n\n        results = []\n        with ThreadPool(num_thread) as pool:\n            with tqdm(total=total_pages, desc=\"Processing PDF pages\") as pbar:\n                for result in pool.imap_unordered(_execute_task, tasks):\n                    results.append(result)\n                    pbar.update(1)\n\n        results.sort(key=lambda x: x[\"page_no\"])\n        for i in range(len(results)):\n            results[i]['file_path'] = input_path\n        return results\n\n    def parse_file(self, \n        input_path, \n        output_dir=\"\", \n        prompt_mode=\"prompt_layout_all_en\",\n        bbox=None,\n        fitz_preprocess=False\n        ):\n        output_dir = output_dir or self.output_dir\n        output_dir = os.path.abspath(output_dir)\n        filename, file_ext = os.path.splitext(os.path.basename(input_path))\n        save_dir = os.path.join(output_dir, filename)\n        os.makedirs(save_dir, exist_ok=True)\n\n        if file_ext == '.pdf':\n            results = self.parse_pdf(input_path, filename, prompt_mode, save_dir)\n        elif file_ext in image_extensions:\n            results = self.parse_image(input_path, filename, prompt_mode, save_dir, bbox=bbox, fitz_preprocess=fitz_preprocess)\n        else:\n            raise ValueError(f\"file extension {file_ext} not supported, supported extensions are {image_extensions} and pdf\")\n        \n        print(f\"Parsing finished, results saving to {save_dir}\")\n        with open(os.path.join(output_dir, os.path.basename(filename)+'.jsonl'), 'w', encoding=\"utf-8\") as w:\n            for result in results:\n                w.write(json.dumps(result, ensure_ascii=False) + '\\n')\n\n        return results\n\n\n\ndef main():\n    prompts = list(dict_promptmode_to_prompt.keys())\n    parser = argparse.ArgumentParser(\n        description=\"dots.ocr Multilingual Document Layout Parser\",\n    )\n    \n    parser.add_argument(\n        \"input_path\", type=str,\n        help=\"Input PDF/image file path\"\n    )\n    \n    parser.add_argument(\n        \"--output\", type=str, default=\"./output\",\n        help=\"Output directory (default: ./output)\"\n    )\n    \n    parser.add_argument(\n        \"--prompt\", choices=prompts, type=str, default=\"prompt_layout_all_en\",\n        help=\"prompt to query the model, different prompts for different tasks\"\n    )\n    parser.add_argument(\n        '--bbox', \n        type=int, \n        nargs=4, \n        metavar=('x1', 'y1', 'x2', 'y2'),\n        help='should give this argument if you want to prompt_grounding_ocr'\n    )\n    parser.add_argument(\n        \"--protocol\", type=str, choices=['http', 'https'], default=\"http\",\n        help=\"\"\n    )\n    parser.add_argument(\n        \"--ip\", type=str, default=\"localhost\",\n        help=\"\"\n    )\n    parser.add_argument(\n        \"--port\", type=int, default=8000,\n        help=\"\"\n    )\n    parser.add_argument(\n        \"--model_name\", type=str, default=\"model\",\n        help=\"\"\n    )\n    parser.add_argument(\n        \"--temperature\", type=float, default=0.1,\n        help=\"\"\n    )\n    parser.add_argument(\n        \"--top_p\", type=float, default=1.0,\n        help=\"\"\n    )\n    parser.add_argument(\n        \"--dpi\", type=int, default=200,\n        help=\"\"\n    )\n    parser.add_argument(\n        \"--max_completion_tokens\", type=int, default=16384,\n        help=\"\"\n    )\n    parser.add_argument(\n        \"--num_thread\", type=int, default=16,\n        help=\"\"\n    )\n    parser.add_argument(\n        \"--no_fitz_preprocess\", action='store_true',\n        help=\"False will use tikz dpi upsample pipeline, good for images which has been render with low dpi, but maybe result in higher computational costs\"\n    )\n    parser.add_argument(\n        \"--min_pixels\", type=int, default=None,\n        help=\"\"\n    )\n    parser.add_argument(\n        \"--max_pixels\", type=int, default=None,\n        help=\"\"\n    )\n    parser.add_argument(\n        \"--use_hf\", type=bool, default=False,\n        help=\"\"\n    )\n    args = parser.parse_args()\n\n    dots_ocr_parser = DotsOCRParser(\n        protocol=args.protocol,\n        ip=args.ip,\n        port=args.port,\n        model_name=args.model_name,\n        temperature=args.temperature,\n        top_p=args.top_p,\n        max_completion_tokens=args.max_completion_tokens,\n        num_thread=args.num_thread,\n        dpi=args.dpi,\n        output_dir=args.output, \n        min_pixels=args.min_pixels,\n        max_pixels=args.max_pixels,\n        use_hf=args.use_hf,\n    )\n\n    fitz_preprocess = not args.no_fitz_preprocess\n    if fitz_preprocess:\n        print(f\"Using fitz preprocess for image input, check the change of the image pixels\")\n    result = dots_ocr_parser.parse_file(\n        args.input_path, \n        prompt_mode=args.prompt,\n        bbox=args.bbox,\n        fitz_preprocess=fitz_preprocess,\n        )\n    \n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "dots_ocr/utils/__init__.py",
    "content": "from .prompts import dict_promptmode_to_prompt"
  },
  {
    "path": "dots_ocr/utils/consts.py",
    "content": "MIN_PIXELS=3136\nMAX_PIXELS=11289600\nIMAGE_FACTOR=28\n\nimage_extensions = {'.jpg', '.jpeg', '.png'}\n"
  },
  {
    "path": "dots_ocr/utils/demo_utils/display.py",
    "content": "import os\nfrom PIL import Image\n\n\ndef is_valid_image_path(image_path):\n    \"\"\"\n    Checks if the image path is valid.\n\n    Args:\n        image_path: The path to the image.\n\n    Returns:\n        bool: True if the path is valid, False otherwise.\n    \"\"\"\n    if not os.path.exists(image_path):\n        return False\n\n    # Check if the file extension is one of the common image formats.\n    image_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp']\n    _, extension = os.path.splitext(image_path)\n    if extension.lower() in image_extensions:\n        return True\n    else:\n        return False\n\n\ndef read_image(image_path, use_native=False):\n    \"\"\"\n    Reads an image and resizes it while maintaining aspect ratio.\n\n    Args:\n        image_path: The path to the image.\n        use_native: If True, the max dimension of the original image is used as the max size. \n                    If False, max size is set to 1024.\n\n    Returns:\n        tuple: (resized_image, original_width, original_height)\n    \"\"\"\n    # Create a default 512x512 blue image as a fallback.\n    image = Image.new('RGB', (512, 512), color=(0, 0, 255))\n\n    if is_valid_image_path(image_path):\n        image = Image.open(image_path)\n    else:\n        raise FileNotFoundError(f\"{image_path}: Image path does not exist\")\n\n    w, h = image.size\n    if use_native:\n        max_size = max(w, h)\n    else:\n        max_size = 1024\n        \n    if w > h:\n        new_w = max_size\n        new_h = int(h * max_size / w)\n    else:\n        new_h = max_size\n        new_w = int(w * max_size / h)\n        \n    image = image.resize((new_w, new_h))\n    return image, w, h\n"
  },
  {
    "path": "dots_ocr/utils/doc_utils.py",
    "content": "import fitz\nimport numpy as np\nimport enum\nfrom pydantic import BaseModel, Field\nfrom PIL import Image\n\n\nclass SupportedPdfParseMethod(enum.Enum):\n    OCR = 'ocr'\n    TXT = 'txt'\n\n\nclass PageInfo(BaseModel):\n    \"\"\"The width and height of page\n    \"\"\"\n    w: float = Field(description='the width of page')\n    h: float = Field(description='the height of page')\n\n\ndef fitz_doc_to_image(doc, target_dpi=200, origin_dpi=None) -> dict:\n    \"\"\"Convert fitz.Document to image, Then convert the image to numpy array.\n\n    Args:\n        doc (_type_): pymudoc page\n        dpi (int, optional): reset the dpi of dpi. Defaults to 200.\n\n    Returns:\n        dict:  {'img': numpy array, 'width': width, 'height': height }\n    \"\"\"\n    from PIL import Image\n    mat = fitz.Matrix(target_dpi / 72, target_dpi / 72)\n    pm = doc.get_pixmap(matrix=mat, alpha=False)\n\n    if pm.width > 4500 or pm.height > 4500:\n        mat = fitz.Matrix(72 / 72, 72 / 72)  # use fitz default dpi\n        pm = doc.get_pixmap(matrix=mat, alpha=False)\n\n    image = Image.frombytes('RGB', (pm.width, pm.height), pm.samples)\n    return image\n\n\ndef load_images_from_pdf(pdf_file, dpi=200, start_page_id=0, end_page_id=None) -> list:\n    images = []\n    with fitz.open(pdf_file) as doc:\n        pdf_page_num = doc.page_count\n        end_page_id = (\n            end_page_id\n            if end_page_id is not None and end_page_id >= 0\n            else pdf_page_num - 1\n        )\n        if end_page_id > pdf_page_num - 1:\n            print('end_page_id is out of range, use images length')\n            end_page_id = pdf_page_num - 1\n\n        for index in range(0, doc.page_count):\n            if start_page_id <= index <= end_page_id:\n                page = doc[index]\n                img = fitz_doc_to_image(page, target_dpi=dpi)\n                images.append(img)\n    return images"
  },
  {
    "path": "dots_ocr/utils/format_transformer.py",
    "content": "import os\nimport sys\nimport json\nimport re\n\nfrom PIL import Image\nfrom dots_ocr.utils.image_utils import PILimage_to_base64\n\n\ndef has_latex_markdown(text: str) -> bool:\n    \"\"\"\n    Checks if a string contains LaTeX markdown patterns.\n    \n    Args:\n        text (str): The string to check.\n        \n    Returns:\n        bool: True if LaTeX markdown is found, otherwise False.\n    \"\"\"\n    if not isinstance(text, str):\n        return False\n    \n    # Define regular expression patterns for LaTeX markdown\n    latex_patterns = [\n        r'\\$\\$.*?\\$\\$',           # Block-level math formula $$...$$\n        r'\\$[^$\\n]+?\\$',          # Inline math formula $...$\n        r'\\\\begin\\{.*?\\}.*?\\\\end\\{.*?\\}',  # LaTeX environment \\begin{...}...\\end{...}\n        r'\\\\[a-zA-Z]+\\{.*?\\}',    # LaTeX command \\command{...}\n        r'\\\\[a-zA-Z]+',           # Simple LaTeX command \\command\n        r'\\\\\\[.*?\\\\\\]',           # Display math formula \\[...\\]\n        r'\\\\\\(.*?\\\\\\)',           # Inline math formula \\(...\\)\n    ]\n    \n    # Check if any of the patterns match\n    for pattern in latex_patterns:\n        if re.search(pattern, text, re.DOTALL):\n            return True\n    \n    return False\n\n\ndef clean_latex_preamble(latex_text: str) -> str:\n    \"\"\"\n    Removes LaTeX preamble commands like document class and package imports.\n    \n    Args:\n        latex_text (str): The original LaTeX text.\n\n    Returns:\n        str: The cleaned LaTeX text without preamble commands.\n    \"\"\"\n    # Define patterns to be removed\n    patterns = [\n        r'\\\\documentclass\\{[^}]+\\}',  # \\documentclass{...}\n        r'\\\\usepackage\\{[^}]+\\}',    # \\usepackage{...}\n        r'\\\\usepackage\\[[^\\]]*\\]\\{[^}]+\\}',  # \\usepackage[options]{...}\n        r'\\\\begin\\{document\\}',       # \\begin{document}\n        r'\\\\end\\{document\\}',         # \\end{document}\n    ]\n    \n    # Apply each pattern to clean the text\n    cleaned_text = latex_text\n    for pattern in patterns:\n        cleaned_text = re.sub(pattern, '', cleaned_text, flags=re.IGNORECASE)\n    \n    return cleaned_text\n    \n\ndef get_formula_in_markdown(text: str) -> str:\n    \"\"\"\n    Formats a string containing a formula into a standard Markdown block.\n    \n    Args:\n        text (str): The input string, potentially containing a formula.\n\n    Returns:\n        str: The formatted string, ready for Markdown rendering.\n    \"\"\"\n    # Remove leading/trailing whitespace\n    text = text.strip()\n    \n    # Check if it's already enclosed in $$\n    if text.startswith('$$') and text.endswith('$$'):\n        text_new = text[2:-2].strip()\n        if not '$' in text_new:\n            return f\"$$\\n{text_new}\\n$$\"\n        else:\n            return text\n\n    # Handle \\[...\\] format, convert to $$...$$\n    if text.startswith('\\\\[') and text.endswith('\\\\]'):\n        inner_content = text[2:-2].strip()\n        return f\"$$\\n{inner_content}\\n$$\"\n        \n    # Check if it's enclosed in \\[ \\]\n    if len(re.findall(r'.*\\\\\\[.*\\\\\\].*', text)) > 0:\n        return text\n\n    # Handle inline formulas ($...$)\n    pattern = r'\\$([^$]+)\\$'\n    matches = re.findall(pattern, text)\n    if len(matches) > 0:\n        # It's an inline formula, return it as is\n        return text  \n\n    # If no LaTeX markdown syntax is present, return directly\n    if not has_latex_markdown(text):  \n        return text\n\n    # Handle unnecessary LaTeX formatting like \\usepackage\n    if 'usepackage' in text:\n        text = clean_latex_preamble(text)\n\n    if text[0] == '`' and text[-1] == '`':\n        text = text[1:-1]\n\n    # Enclose the final text in a $$ block with newlines\n    text = f\"$$\\n{text}\\n$$\"\n    return text \n\n\ndef clean_text(text: str) -> str:\n    \"\"\"\n    Cleans text by removing extra whitespace.\n    \n    Args:\n        text: The original text.\n        \n    Returns:\n        str: The cleaned text.\n    \"\"\"\n    if not text:\n        return \"\"\n    \n    # Remove leading and trailing whitespace\n    text = text.strip()\n    \n    # Replace multiple consecutive whitespace characters with a single space\n    if text[:2] == '`$' and text[-2:] == '$`':\n        text = text[1:-1]\n    \n    return text\n\n\ndef layoutjson2md(image: Image.Image, cells: list, text_key: str = 'text', no_page_hf: bool = False) -> str:\n    \"\"\"\n    Converts a layout JSON format to Markdown.\n    \n    In the layout JSON, formulas are LaTeX, tables are HTML, and text is Markdown.\n    \n    Args:\n        image: A PIL Image object.\n        cells: A list of dictionaries, each representing a layout cell.\n        text_key: The key for the text field in the cell dictionary.\n        no_page_header_footer: If True, skips page headers and footers.\n        \n    Returns:\n        str: The text in Markdown format.\n    \"\"\"\n    text_items = []\n\n    for i, cell in enumerate(cells):\n        x1, y1, x2, y2 = [int(coord) for coord in cell['bbox']]\n        text = cell.get(text_key, \"\")\n        \n        if no_page_hf and cell['category'] in ['Page-header', 'Page-footer']:\n            continue\n        \n        if cell['category'] == 'Picture':\n            image_crop = image.crop((x1, y1, x2, y2))\n            image_base64 = PILimage_to_base64(image_crop)\n            text_items.append(f\"![]({image_base64})\")\n        elif cell['category'] == 'Formula':\n            text_items.append(get_formula_in_markdown(text))\n        else:            \n            text = clean_text(text)\n            text_items.append(f\"{text}\")\n\n    markdown_text = '\\n\\n'.join(text_items)\n    return markdown_text\n\n\ndef fix_streamlit_formulas(md: str) -> str:\n    \"\"\"\n    Fixes the format of formulas in Markdown to ensure they display correctly in Streamlit.\n    It adds a newline after the opening $$ and before the closing $$ if they don't already exist.\n    \n    Args:\n        md_text (str): The Markdown text to fix.\n        \n    Returns:\n        str: The fixed Markdown text.\n    \"\"\"\n    \n    # This inner function will be used by re.sub to perform the replacement\n    def replace_formula(match):\n        content = match.group(1)\n        # If the content already has surrounding newlines, don't add more.\n        if content.startswith('\\n'):\n            content = content[1:]\n        if content.endswith('\\n'):\n            content = content[:-1]\n        return f'$$\\n{content}\\n$$'\n    \n    # Use regex to find all $$....$$ patterns and replace them using the helper function.\n    return re.sub(r'\\$\\$(.*?)\\$\\$', replace_formula, md, flags=re.DOTALL)\n"
  },
  {
    "path": "dots_ocr/utils/image_utils.py",
    "content": "import math\nimport base64\nfrom PIL import Image\nfrom typing import Tuple\nimport os\nfrom dots_ocr.utils.consts import IMAGE_FACTOR, MIN_PIXELS, MAX_PIXELS\nfrom dots_ocr.utils.doc_utils import fitz_doc_to_image\nfrom io import BytesIO\nimport fitz\nimport requests\nimport copy\n\n\ndef round_by_factor(number: int, factor: int) -> int:\n    \"\"\"Returns the closest integer to 'number' that is divisible by 'factor'.\"\"\"\n    return round(number / factor) * factor\n\n\ndef ceil_by_factor(number: int, factor: int) -> int:\n    \"\"\"Returns the smallest integer greater than or equal to 'number' that is divisible by 'factor'.\"\"\"\n    return math.ceil(number / factor) * factor\n\n\ndef floor_by_factor(number: int, factor: int) -> int:\n    \"\"\"Returns the largest integer less than or equal to 'number' that is divisible by 'factor'.\"\"\"\n    return math.floor(number / factor) * factor\n\n\ndef smart_resize(\n    height: int,\n    width: int,\n    factor: int = 28,\n    min_pixels: int = 3136,\n    max_pixels: int = 11289600,\n):\n    \"\"\"Rescales the image so that the following conditions are met:\n\n    1. Both dimensions (height and width) are divisible by 'factor'.\n\n    2. The total number of pixels is within the range ['min_pixels', 'max_pixels'].\n\n    3. The aspect ratio of the image is maintained as closely as possible.\n\n    \"\"\"\n    if max(height, width) / min(height, width) > 200:\n        raise ValueError(\n            f\"absolute aspect ratio must be smaller than 200, got {max(height, width) / min(height, width)}\"\n        )\n    h_bar = max(factor, round_by_factor(height, factor))\n    w_bar = max(factor, round_by_factor(width, factor))\n    if h_bar * w_bar > max_pixels:\n        beta = math.sqrt((height * width) / max_pixels)\n        h_bar = max(factor, floor_by_factor(height / beta, factor))\n        w_bar = max(factor, floor_by_factor(width / beta, factor))\n    elif h_bar * w_bar < min_pixels:\n        beta = math.sqrt(min_pixels / (height * width))\n        h_bar = ceil_by_factor(height * beta, factor)\n        w_bar = ceil_by_factor(width * beta, factor)\n        if h_bar * w_bar > max_pixels:  # max_pixels first to control the token length \n            beta = math.sqrt((h_bar * w_bar) / max_pixels)\n            h_bar = max(factor, floor_by_factor(h_bar / beta, factor))\n            w_bar = max(factor, floor_by_factor(w_bar / beta, factor))\n    return h_bar, w_bar\n\n\n\ndef PILimage_to_base64(image, format='PNG'):\n    buffered = BytesIO()\n    image.save(buffered, format=format)\n    base64_str = base64.b64encode(buffered.getvalue()).decode('utf-8')\n    return f\"data:image/{format.lower()};base64,{base64_str}\"\n\n\ndef to_rgb(pil_image: Image.Image) -> Image.Image:\n    if pil_image.mode == 'RGBA':\n        white_background = Image.new(\"RGB\", pil_image.size, (255, 255, 255))\n        white_background.paste(pil_image, mask=pil_image.split()[3])  # Use alpha channel as mask\n        return white_background\n    else:\n        return pil_image.convert(\"RGB\")\n\n\n# copy from https://github.com/QwenLM/Qwen2.5-VL/blob/main/qwen-vl-utils/src/qwen_vl_utils/vision_process.py\ndef fetch_image(\n        image, \n        min_pixels=None,\n        max_pixels=None,\n        resized_height=None,\n        resized_width=None,\n    ) -> Image.Image:\n    assert image is not None, f\"image not found, maybe input format error: {image}\"\n    image_obj = None\n    if isinstance(image, Image.Image):\n        image_obj = image\n    elif image.startswith(\"http://\") or image.startswith(\"https://\"):\n        # fix memory leak issue while using BytesIO\n        with requests.get(image, stream=True) as response:\n            response.raise_for_status()\n            with BytesIO(response.content) as bio:\n                image_obj = copy.deepcopy(Image.open(bio))\n    elif image.startswith(\"file://\"):\n        image_obj = Image.open(image[7:])\n    elif image.startswith(\"data:image\"):\n        if \"base64,\" in image:\n            _, base64_data = image.split(\"base64,\", 1)\n            data = base64.b64decode(base64_data)\n            # fix memory leak issue while using BytesIO\n            with BytesIO(data) as bio:\n                image_obj = copy.deepcopy(Image.open(bio))\n    else:\n        image_obj = Image.open(image)\n    if image_obj is None:\n        raise ValueError(f\"Unrecognized image input, support local path, http url, base64 and PIL.Image, got {image}\")\n    image = to_rgb(image_obj)\n    ## resize\n    if resized_height and resized_width:\n        resized_height, resized_width = smart_resize(\n            resized_height,\n            resized_width,\n            factor=IMAGE_FACTOR,\n        )\n        assert resized_height>0 and resized_width>0, f\"resized_height: {resized_height}, resized_width: {resized_width}, min_pixels: {min_pixels}, max_pixels:{max_pixels}, width: {width}, height:{height}, \"\n        image = image.resize((resized_width, resized_height))\n    elif min_pixels or max_pixels:\n        width, height = image.size\n        if not min_pixels:\n            min_pixels = MIN_PIXELS\n        if not max_pixels:\n            max_pixels = MAX_PIXELS\n        resized_height, resized_width = smart_resize(\n            height,\n            width,\n            factor=IMAGE_FACTOR,\n            min_pixels=min_pixels,\n            max_pixels=max_pixels,\n        )\n        assert resized_height>0 and resized_width>0, f\"resized_height: {resized_height}, resized_width: {resized_width}, min_pixels: {min_pixels}, max_pixels:{max_pixels}, width: {width}, height:{height}, \"\n        image = image.resize((resized_width, resized_height))\n\n    return image\n\ndef get_input_dimensions(\n    image: Image.Image,\n    min_pixels: int,\n    max_pixels: int,\n    factor: int = 28\n) -> Tuple[int, int]:\n    \"\"\"\n    Gets the resized dimensions of the input image.\n    \n    Args:\n        image: The original image.\n        min_pixels: The minimum number of pixels.\n        max_pixels: The maximum number of pixels.\n        factor: The resizing factor.\n        \n    Returns:\n        The resized (width, height).\n    \"\"\"\n    input_height, input_width = smart_resize(\n        image.height, \n        image.width,\n        factor=factor,\n        min_pixels=min_pixels,\n        max_pixels=max_pixels\n    )\n    return input_width, input_height\n\n\ndef get_image_by_fitz_doc(image, target_dpi=200):\n    # get image through fitz, to get target dpi image, mainly for higher image\n    if not isinstance(image, Image.Image):\n        assert isinstance(image, str)\n        _, file_ext = os.path.splitext(image)\n        assert file_ext in {'.jpg', '.jpeg', '.png'}\n\n        if image.startswith(\"http://\") or image.startswith(\"https://\"):\n            with requests.get(image, stream=True) as response:\n                response.raise_for_status()\n                data_bytes = response.content\n        else:\n            with open(image, 'rb') as f:\n                data_bytes = f.read()\n\n        image = Image.open(BytesIO(data_bytes))\n    else:\n        data_bytes = BytesIO()\n        image.save(data_bytes, format='PNG')\n\n    origin_dpi = image.info.get('dpi', None)\n    pdf_bytes = fitz.open(stream=data_bytes).convert_to_pdf()\n    doc = fitz.open('pdf', pdf_bytes)\n    page = doc[0]\n    image_fitz = fitz_doc_to_image(page, target_dpi=target_dpi, origin_dpi=origin_dpi)\n\n    return image_fitz\n"
  },
  {
    "path": "dots_ocr/utils/layout_utils.py",
    "content": "from PIL import Image\nfrom typing import Dict, List\n\nimport fitz\nfrom io import BytesIO\nimport json\n\nfrom dots_ocr.utils.image_utils import smart_resize\nfrom dots_ocr.utils.consts import MIN_PIXELS, MAX_PIXELS\nfrom dots_ocr.utils.output_cleaner import OutputCleaner\n\n\n# Define a color map (using RGBA format)\ndict_layout_type_to_color = {\n    \"Text\": (0, 128, 0, 256),  # Green, translucent\n    \"Picture\": (255, 0, 255, 256),  # Magenta, translucent\n    \"Caption\": (255, 165, 0, 256),  # Orange, translucent\n    \"Section-header\": (0, 255, 255, 256),  # Cyan, translucent\n    \"Footnote\": (0, 128, 0, 256),  # Green, translucent\n    \"Formula\": (128, 128, 128, 256),  # Gray, translucent\n    \"Table\": (255, 192, 203, 256),  # Pink, translucent\n    \"Title\": (255, 0, 0, 256),  # Red, translucent\n    \"List-item\": (0, 0, 255, 256),  # Blue, translucent\n    \"Page-header\": (0, 128, 0, 256),  # Green, translucent\n    \"Page-footer\":  (128, 0, 128, 256),  # Purple, translucent\n    \"Other\": (165, 42, 42, 256),  # Brown, translucent\n    \"Unknown\": (0, 0, 0, 0),\n}\n\n\ndef draw_layout_on_image(image, cells, resized_height=None, resized_width=None, fill_bbox=True, draw_bbox=True):\n    \"\"\"\n    Draw transparent boxes on an image.\n    \n    Args:\n        image: The source PIL Image.\n        cells: A list of cells containing bounding box information.\n        resized_height: The resized height.\n        resized_width: The resized width.\n        fill_bbox: Whether to fill the bounding box.\n        draw_bbox: Whether to draw the bounding box.\n        \n    Returns:\n        PIL.Image: The image with drawings.\n    \"\"\"\n    # origin_image = Image.open(image_path)\n    original_width, original_height = image.size\n        \n    # Create a new PDF document\n    doc = fitz.open()\n    \n    # Get image information\n    img_bytes = BytesIO()\n    image.save(img_bytes, format='PNG')\n    # pix = fitz.Pixmap(image_path)\n    pix = fitz.Pixmap(img_bytes)\n    \n    # Create a page\n    page = doc.new_page(width=pix.width, height=pix.height)\n    page.insert_image(\n        fitz.Rect(0, 0, pix.width, pix.height), \n        # filename=image_path\n        pixmap=pix\n        )\n\n    for i, cell in enumerate(cells):\n        bbox = cell['bbox']\n        layout_type = cell['category']\n        order = i\n        \n        top_left = (bbox[0], bbox[1])\n        down_right = (bbox[2], bbox[3])\n        if resized_height and resized_width:\n            scale_x = resized_width / original_width\n            scale_y = resized_height / original_height\n            top_left = (int(bbox[0] / scale_x), int(bbox[1] / scale_y))\n            down_right = (int(bbox[2] / scale_x), int(bbox[3] / scale_y))\n            \n        color = dict_layout_type_to_color.get(layout_type, (0, 128, 0, 256))\n        color = [col/255 for col in color[:3]]\n\n        x0, y0, x1, y1 = top_left[0], top_left[1], down_right[0], down_right[1]\n        rect_coords = fitz.Rect(x0, y0, x1, y1)\n        if draw_bbox:\n            if fill_bbox:\n                page.draw_rect(\n                    rect_coords,\n                    color=None,\n                    fill=color,\n                    fill_opacity=0.3,\n                    width=0.5,\n                    overlay=True,\n                )  # Draw the rectangle\n            else:\n                page.draw_rect(\n                    rect_coords,\n                    color=color,\n                    fill=None,\n                    fill_opacity=1,\n                    width=0.5,\n                    overlay=True,\n                )  # Draw the rectangle\n        order_cate = f\"{order}_{layout_type}\"\n        page.insert_text(\n            (x1, y0 + 20), order_cate, fontsize=20, color=color\n        )  # Insert the index in the top left corner of the rectangle\n\n    # Convert to a Pixmap (maintaining original dimensions)\n    mat = fitz.Matrix(1.0, 1.0)\n    pix = page.get_pixmap(matrix=mat)\n\n    return Image.frombytes(\"RGB\", [pix.width, pix.height], pix.samples)\n\n\ndef pre_process_bboxes(\n    origin_image,\n    bboxes,\n    input_width,\n    input_height,\n    factor: int = 28,\n    min_pixels: int = 3136, \n    max_pixels: int = 11289600\n):\n    assert isinstance(bboxes, list) and len(bboxes) > 0 and isinstance(bboxes[0], list)\n    min_pixels = min_pixels or MIN_PIXELS\n    max_pixels = max_pixels or MAX_PIXELS\n    original_width, original_height = origin_image.size\n\n    input_height, input_width = smart_resize(input_height, input_width, min_pixels=min_pixels, max_pixels=max_pixels)\n    \n    scale_x = original_width / input_width\n    scale_y = original_height / input_height\n\n    bboxes_out = []\n    for bbox in bboxes:\n        bbox_resized = [\n            int(float(bbox[0]) / scale_x), \n            int(float(bbox[1]) / scale_y),\n            int(float(bbox[2]) / scale_x), \n            int(float(bbox[3]) / scale_y)\n        ]\n        bboxes_out.append(bbox_resized)\n    \n    return bboxes_out\n\ndef post_process_cells(\n    origin_image: Image.Image, \n    cells: List[Dict], \n    input_width,  # server input width, also has smart_resize in server\n    input_height,\n    factor: int = 28,\n    min_pixels: int = 3136, \n    max_pixels: int = 11289600\n) -> List[Dict]:\n    \"\"\"\n    Post-processes cell bounding boxes, converting coordinates from the resized dimensions back to the original dimensions.\n    \n    Args:\n        origin_image: The original PIL Image.\n        cells: A list of cells containing bounding box information.\n        input_width: The width of the input image sent to the server.\n        input_height: The height of the input image sent to the server.\n        factor: Resizing factor.\n        min_pixels: Minimum number of pixels.\n        max_pixels: Maximum number of pixels.\n        \n    Returns:\n        A list of post-processed cells.\n    \"\"\"\n    assert isinstance(cells, list) and len(cells) > 0 and isinstance(cells[0], dict)\n    min_pixels = min_pixels or MIN_PIXELS\n    max_pixels = max_pixels or MAX_PIXELS\n    original_width, original_height = origin_image.size\n\n    input_height, input_width = smart_resize(input_height, input_width, min_pixels=min_pixels, max_pixels=max_pixels)\n    \n    scale_x = input_width / original_width\n    scale_y = input_height / original_height\n    \n    cells_out = []\n    for cell in cells:\n        bbox = cell['bbox']\n        bbox_resized = [\n            int(float(bbox[0]) / scale_x), \n            int(float(bbox[1]) / scale_y),\n            int(float(bbox[2]) / scale_x), \n            int(float(bbox[3]) / scale_y)\n        ]\n        cell_copy = cell.copy()\n        cell_copy['bbox'] = bbox_resized\n        cells_out.append(cell_copy)\n    \n    return cells_out\n\ndef is_legal_bbox(cells):\n    for cell in cells:\n        bbox = cell['bbox']\n        if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]:\n            return False\n    return True\n\ndef post_process_output(response, prompt_mode, origin_image, input_image, min_pixels=None, max_pixels=None):\n    if prompt_mode in [\"prompt_ocr\", \"prompt_table_html\", \"prompt_table_latex\", \"prompt_formula_latex\"]:\n        return response\n\n    json_load_failed = False\n    cells = response\n    try:\n        cells = json.loads(cells)\n        cells = post_process_cells(\n            origin_image, \n            cells,\n            input_image.width,\n            input_image.height,\n            min_pixels=min_pixels,\n            max_pixels=max_pixels\n        )\n        return cells, False\n    except Exception as e:\n        print(f\"cells post process error: {e}, when using {prompt_mode}\")\n        json_load_failed = True\n\n    if json_load_failed:\n        cleaner = OutputCleaner()\n        response_clean = cleaner.clean_model_output(cells)\n        if isinstance(response_clean, list):\n            response_clean = \"\\n\\n\".join([cell['text'] for cell in response_clean if 'text' in cell])\n        return response_clean, True\n"
  },
  {
    "path": "dots_ocr/utils/output_cleaner.py",
    "content": "#!/usr/bin/env python3\n\"\"\"\nData Cleaning Script - Cleans all data using a simplified regex method and saves the results\n\nFeatures:\n1. Cleans all cases using a simplified regex method.\n2. Saves the cleaned data for each case.\n3. Ensures the relative order of dicts remains unchanged.\n4. Generates a before-and-after cleaning report.\n\"\"\"\n\nimport json\nimport re\nimport os\nfrom typing import Dict, List, Tuple, Optional, Any\nfrom dataclasses import dataclass\nfrom collections import Counter\nimport traceback\n\n\n@dataclass\nclass CleanedData:\n    \"\"\"Data structure for cleaned data\"\"\"\n    case_id: int\n    original_type: str  # 'list' or 'str'\n    original_length: int\n    cleaned_data: List[Dict]\n    cleaning_operations: Dict[str, Any]  # Records the cleaning operations performed\n    success: bool\n\n\nclass OutputCleaner:\n    \"\"\"Data Cleaner - Based on a simplified regex method\"\"\"\n    \n    def __init__(self):\n        # Simplified regular expression patterns\n        self.dict_pattern = re.compile(r'\\{[^{}]*?\"bbox\"\\s*:\\s*\\[[^\\]]*?\\][^{}]*?\\}', re.DOTALL)\n        self.bbox_pattern = re.compile(r'\"bbox\"\\s*:\\s*\\[([^\\]]+)\\]')\n        self.missing_delimiter_pattern = re.compile(r'\\}\\s*\\{(?!\")')\n        \n        self.cleaned_results: List[CleanedData] = []\n    \n    def clean_list_data(self, data: List[Dict], case_id: int) -> CleanedData:\n        \"\"\"Cleans list-type data\"\"\"\n        \n        print(f\"🔧 Cleaning List data - Case {case_id}\")\n        print(f\"  Original items: {len(data)}\")\n        \n        cleaned_data = []\n        operations = {\n            'type': 'list',\n            'bbox_fixes': 0,\n            'removed_items': 0,\n            'original_count': len(data)\n        }\n        \n        for i, item in enumerate(data):\n            if not isinstance(item, dict):\n                operations['removed_items'] += 1\n                continue\n                \n            # Check the bbox field\n            if 'bbox' in item:\n                bbox = item['bbox']\n                \n                # Check bbox length - core logic\n                if isinstance(bbox, list) and len(bbox) == 3:\n                    print(f\"  ⚠️ Item {i}: bbox has only 3 coordinates. Removing bbox, keeping category and text.\")\n                    # Keep only category and text, ensuring order is preserved\n                    new_item = {}\n                    if 'category' in item:\n                        new_item['category'] = item['category']\n                    if 'text' in item:\n                        new_item['text'] = item['text']\n                    if new_item:  # Add only if there is valid content\n                        cleaned_data.append(new_item)\n                        operations['bbox_fixes'] += 1\n                    else:\n                        operations['removed_items'] += 1\n                    continue\n                elif isinstance(bbox, list) and len(bbox) == 4:\n                    # bbox is normal, add directly, preserving original order\n                    cleaned_data.append(item.copy())\n                    continue\n                else:\n                    print(f\"  ❌ Item {i}: Abnormal bbox format, skipping.\")\n                    operations['removed_items'] += 1\n                    continue\n            else:\n                # No bbox field, keep if category exists\n                if 'category' in item:\n                    cleaned_data.append(item.copy())\n                    continue\n                else:\n                    operations['removed_items'] += 1\n        \n        operations['final_count'] = len(cleaned_data)\n        print(f\"  ✅ Cleaning complete: {len(cleaned_data)} items, {operations['bbox_fixes']} bbox fixes, {operations['removed_items']} items removed\")\n        \n        return CleanedData(\n            case_id=case_id,\n            original_type='list',\n            original_length=len(data),\n            cleaned_data=cleaned_data,\n            cleaning_operations=operations,\n            success=True\n        )\n    \n    def clean_string_data(self, data_str: str, case_id: int) -> CleanedData:\n        \"\"\"Cleans string-type data\"\"\"\n        \n        print(f\"🔧 Cleaning String data - Case {case_id}\")\n        print(f\"  Original length: {len(data_str):,}\")\n        \n        operations = {\n            'type': 'str',\n            'original_length': len(data_str),\n            'delimiter_fixes': 0,\n            'tail_truncated': False,\n            'truncated_length': 0,\n            'duplicate_dicts_removed': 0,\n            'final_objects': 0\n        }\n        \n        try:\n            # Step 1: Detect and fix missing delimiters\n            data_str, delimiter_fixes = self._fix_missing_delimiters(data_str)\n            operations['delimiter_fixes'] = delimiter_fixes\n            \n            # Step 2: Truncate the last incomplete element\n            data_str, tail_truncated = self._truncate_last_incomplete_element(data_str)\n            operations['tail_truncated'] = tail_truncated\n            operations['truncated_length'] = len(data_str)\n            \n            # Step 3: Remove duplicate complete dict objects, preserving order\n            data_str, duplicate_removes = self._remove_duplicate_complete_dicts_preserve_order(data_str)\n            operations['duplicate_dicts_removed'] = duplicate_removes\n            \n            # Step 4: Ensure correct JSON format\n            data_str = self._ensure_json_format(data_str)\n            \n            # Step 5: Try to parse the final result\n            final_data = self._parse_final_json(data_str)\n            \n            if final_data is not None:\n                operations['final_objects'] = len(final_data)\n                print(f\"  ✅ Cleaning complete: {len(final_data)} objects\")\n                \n                return CleanedData(\n                    case_id=case_id,\n                    original_type='str',\n                    original_length=operations['original_length'],\n                    cleaned_data=final_data,\n                    cleaning_operations=operations,\n                    success=True\n                )\n            else:\n                raise Exception(\"Could not parse the cleaned data\")\n                \n        except Exception as e:\n            print(f\"  ❌ Cleaning failed: {e}\")\n            return CleanedData(\n                case_id=case_id,\n                original_type='str',\n                original_length=operations['original_length'],\n                cleaned_data=[],\n                cleaning_operations=operations,\n                success=False\n            )\n    \n    def _fix_missing_delimiters(self, text: str) -> Tuple[str, int]:\n        \"\"\"Fixes missing delimiters\"\"\"\n        \n        fixes = 0\n        \n        def replace_delimiter(match):\n            nonlocal fixes\n            fixes += 1\n            return '},{'\n        \n        text = self.missing_delimiter_pattern.sub(replace_delimiter, text)\n        \n        if fixes > 0:\n            print(f\"    ✅ Fixed {fixes} missing delimiters\")\n        \n        return text, fixes\n    \n    def _truncate_last_incomplete_element(self, text: str) -> Tuple[str, bool]:\n        \"\"\"Truncates the last incomplete element\"\"\"\n        \n        # For very long text (>50k) or text not ending with ']', directly truncate the last '{\"bbox\":'\n        needs_truncation = (\n            len(text) > 50000 or \n            not text.strip().endswith(']')\n        )\n        \n        if needs_truncation:\n            # Check how many dict objects there are\n            bbox_count = text.count('{\"bbox\":')\n            \n            # If there is only one dict object, do not truncate to avoid deleting the only object\n            if bbox_count <= 1:\n                print(f\"    ⚠️ Only {bbox_count} dict objects found, skipping truncation to avoid deleting all content\")\n                return text, False\n            \n            # Find the position of the last '{\"bbox\":'\n            last_bbox_pos = text.rfind('{\"bbox\":')\n            \n            if last_bbox_pos > 0:\n                # Truncate before this position\n                truncated_text = text[:last_bbox_pos].rstrip()\n                \n                # Remove trailing comma\n                if truncated_text.endswith(','):\n                    truncated_text = truncated_text[:-1]\n                \n                print(f\"    ✂️ Truncated the last incomplete element, length reduced from {len(text):,} to {len(truncated_text):,}\")\n                return truncated_text, True\n        \n        return text, False\n    \n    def _remove_duplicate_complete_dicts_preserve_order(self, text: str) -> Tuple[str, int]:\n        \"\"\"Removes duplicate complete dict objects, preserving original order\"\"\"\n        \n        # Extract all dict objects, preserving order\n        dict_matches = list(self.dict_pattern.finditer(text))\n        \n        if not dict_matches:\n            return text, 0\n        \n        print(f\"    📊 Found {len(dict_matches)} dict objects\")\n        \n        # Deduplication while preserving order: only keep the first occurrence of a dict\n        unique_dicts = []\n        seen_dict_strings = set()\n        total_duplicates = 0\n        \n        for match in dict_matches:\n            dict_str = match.group()\n            \n            if dict_str not in seen_dict_strings:\n                unique_dicts.append(dict_str)\n                seen_dict_strings.add(dict_str)\n            else:\n                total_duplicates += 1\n        \n        if total_duplicates > 0:\n            # Reconstruct the JSON array, preserving the original order\n            new_text = '[' + ', '.join(unique_dicts) + ']'\n            print(f\"    ✅ Removed {total_duplicates} duplicate dicts, keeping {len(unique_dicts)} unique dicts (order preserved)\")\n            return new_text, total_duplicates\n        else:\n            print(f\"    ✅ No duplicate dict objects found\")\n            return text, 0\n    \n    def _ensure_json_format(self, text: str) -> str:\n        \"\"\"Ensures correct JSON format\"\"\"\n        \n        text = text.strip()\n        \n        if not text.startswith('['):\n            text = '[' + text\n        \n        if not text.endswith(']'):\n            # Remove trailing comma\n            text = text.rstrip(',').rstrip()\n            text += ']'\n        \n        return text\n    \n    def _parse_final_json(self, text: str) -> Optional[List[Dict]]:\n        \"\"\"Tries to parse the final JSON\"\"\"\n        \n        try:\n            data = json.loads(text)\n            if isinstance(data, list):\n                return data\n        except json.JSONDecodeError as e:\n            print(f\"    ❌ JSON parsing failed: {e}\")\n            \n            # fallback1: Extract valid dict objects\n            valid_dicts = []\n            \n            for match in self.dict_pattern.finditer(text):\n                dict_str = match.group()\n                try:\n                    dict_obj = json.loads(dict_str)\n                    valid_dicts.append(dict_obj)\n                except:\n                    continue\n            \n            if valid_dicts:\n                print(f\"    ✅ Extracted {len(valid_dicts)} valid dicts\")\n                return valid_dicts\n            \n            # fallback2: Special handling for a single incomplete dict\n            return self._handle_single_incomplete_dict(text)\n        \n        return None\n    \n    def _handle_single_incomplete_dict(self, text: str) -> Optional[List[Dict]]:\n        \"\"\"Handles the special case of a single incomplete dict\"\"\"\n        \n        # Check if it's a single incomplete dict case\n        if not text.strip().startswith('[{\"bbox\":'):\n            return None\n        \n        try:\n            # Try to extract bbox coordinates\n            bbox_match = re.search(r'\"bbox\"\\s*:\\s*\\[([^\\]]+)\\]', text)\n            if not bbox_match:\n                return None\n            \n            bbox_str = bbox_match.group(1)\n            bbox_coords = [int(x.strip()) for x in bbox_str.split(',')]\n            \n            if len(bbox_coords) != 4:\n                return None\n            \n            # Try to extract category\n            category_match = re.search(r'\"category\"\\s*:\\s*\"([^\"]+)\"', text)\n            category = category_match.group(1) if category_match else \"Text\"\n            \n            # Try to extract the beginning of the text (first 10000 characters)\n            text_match = re.search(r'\"text\"\\s*:\\s*\"([^\"]{0,10000})', text)\n            if text_match:\n                text_content = text_match.group(1)\n            else:\n                text_content = \"\"\n            \n            # Construct the fixed dict\n            fixed_dict = {\n                \"bbox\": bbox_coords,\n                \"category\": category\n            }\n            \n            if text_content:\n                fixed_dict[\"text\"] = text_content\n            \n            print(f\"    🔧 Special fix: single incomplete dict → {fixed_dict}\")\n            return [fixed_dict]\n            \n        except Exception as e:\n            print(f\"    ❌ Special fix failed: {e}\")\n            return None\n    \n    def remove_duplicate_category_text_pairs_and_bbox(self, data_list: List[dict], case_id: int) -> List[dict]:\n        \"\"\"Removes duplicate category-text pairs and duplicate bboxes\"\"\"\n        \n        if not data_list or len(data_list) <= 1:\n            print(f\"    📊 Data length {len(data_list)} <= 1, skipping deduplication check\")\n            return data_list\n        \n        print(f\"    📊 Original data length: {len(data_list)}\")\n        \n        # 1. Count occurrences and positions of each category-text pair\n        category_text_pairs = {}\n        for i, item in enumerate(data_list):\n            if isinstance(item, dict) and 'category' in item and 'text' in item:\n                pair_key = (item.get('category', ''), item.get('text', ''))\n                if pair_key not in category_text_pairs:\n                    category_text_pairs[pair_key] = []\n                category_text_pairs[pair_key].append(i)\n        \n        # 2. Count occurrences and positions of each bbox\n        bbox_pairs = {}\n        for i, item in enumerate(data_list):\n            if isinstance(item, dict) and 'bbox' in item:\n                bbox = item.get('bbox')\n                if isinstance(bbox, list) and len(bbox) > 0:\n                    bbox_key = tuple(bbox)  # Convert to tuple to use as a dictionary key\n                    if bbox_key not in bbox_pairs:\n                        bbox_pairs[bbox_key] = []\n                    bbox_pairs[bbox_key].append(i)\n        \n        # 3. Identify items to be removed\n        duplicates_to_remove = set()\n        \n        # 3a. Process category-text pairs that appear 5 or more times\n        for pair_key, positions in category_text_pairs.items():\n            if len(positions) >= 5:\n                category, text = pair_key\n                # Keep the first occurrence, remove subsequent duplicates\n                positions_to_remove = positions[1:]\n                duplicates_to_remove.update(positions_to_remove)\n                \n                print(f\"    🔍 Found duplicate category-text pair: category='{category}', first 50 chars of text='{text[:50]}...'\")\n                print(f\"        Count: {len(positions)}, removing at positions: {positions_to_remove}\")\n        \n        # 3b. Process bboxes that appear 2 or more times\n        for bbox_key, positions in bbox_pairs.items():\n            if len(positions) >= 2:\n                # Keep the first occurrence, remove subsequent duplicates\n                positions_to_remove = positions[1:]\n                duplicates_to_remove.update(positions_to_remove)\n                \n                print(f\"    🔍 Found duplicate bbox: {list(bbox_key)}\")\n                print(f\"        Count: {len(positions)}, removing at positions: {positions_to_remove}\")\n        \n        if not duplicates_to_remove:\n            print(f\"    ✅ No category-text pairs or bboxes found exceeding the duplication threshold\")\n            return data_list\n        \n        # 4. Remove duplicate items from the original data (preserving order)\n        cleaned_data = []\n        removed_count = 0\n        for i, item in enumerate(data_list):\n            if i not in duplicates_to_remove:\n                cleaned_data.append(item)\n            else:\n                removed_count += 1\n        \n        print(f\"    ✅ Deduplication complete: Removed {removed_count} duplicate items\")\n        print(f\"    📊 Cleaned data length: {len(cleaned_data)}\")\n        \n        return cleaned_data\n\n    def clean_model_output(self, model_output: str):\n        try:\n            # Select cleaning method based on data type\n            if isinstance(model_output, list):\n                result = self.clean_list_data(model_output, case_id=0)\n            else:\n                result = self.clean_string_data(str(model_output), case_id=0)\n            \n            # Add deduplication step: remove duplicate category-text pairs and bboxes\n            if result and hasattr(result, 'success') and result.success and result.cleaned_data:\n                original_data = result.cleaned_data\n                deduplicated_data = self.remove_duplicate_category_text_pairs_and_bbox(original_data, case_id=0)\n                # Update the cleaned_data in the CleanedData object\n                result.cleaned_data = deduplicated_data\n            return result.cleaned_data\n        except Exception as e:\n            print(f\"❌ Case cleaning failed: {e}\")\n            return model_output\n    \n    def clean_all_data(self, jsonl_path: str) -> List[CleanedData]:\n        \"\"\"Cleans all data from a JSONL file\"\"\"\n        \n        print(f\"🚀 Starting to clean JSONL file: {jsonl_path}\")\n        \n        with open(jsonl_path, 'r', encoding='utf-8') as f:\n            lines = f.readlines()\n        \n        datas = []\n        for i, line in enumerate(lines):\n            if line.strip():\n                try:\n                    data = json.loads(line)\n                    predict_field = data.get('predict')\n                    case_id = i + 1\n                    \n                    print(f\"\\n{'='*50}\")\n                    print(f\"🎯 Cleaning Case {case_id}\")\n                    print(f\"{'='*50}\")\n                    \n                    # Select cleaning method based on data type\n                    if isinstance(predict_field, list):\n                        print(\"📊 Data type: List\")\n                        result = self.clean_list_data(predict_field, case_id)\n                    else:\n                        print(\"📊 Data type: String\")\n                        result = self.clean_string_data(str(predict_field), case_id)\n                    \n                    # Add deduplication step: remove duplicate category-text pairs and bboxes\n                    if result and hasattr(result, 'success') and result.success and result.cleaned_data:\n                        print(\"🔄 Checking for and removing duplicate category-text pairs and bboxes...\")\n                        original_data = result.cleaned_data\n                        deduplicated_data = self.remove_duplicate_category_text_pairs_and_bbox(original_data, case_id)\n                        # Update the cleaned_data in the CleanedData object\n                        result.cleaned_data = deduplicated_data\n                    data['predict_resized'] = result.cleaned_data\n\n                    datas.append(data)\n                    self.cleaned_results.append(result)\n                    \n                except Exception as e:\n                    print(f\"❌ Case {i+1} cleaning failed: {e}\")\n                    traceback.print_exc()\n        \n        save_path = jsonl_path.replace('.jsonl', '_filtered.jsonl')\n        with open(save_path, 'w') as w:\n            for data in datas:\n                w.write(json.dumps(data, ensure_ascii=False) + '\\n')\n        print(f\"✅ Saved cleaned data to: {save_path}\")\n\n        return self.cleaned_results\n    \n    def save_cleaned_data(self, output_dir: str):\n        \"\"\"Saves the cleaned data\"\"\"\n        \n        print(f\"\\n💾 Saving cleaned data to: {output_dir}\")\n        os.makedirs(output_dir, exist_ok=True)\n        \n        # 1. Save cleaned data for each case\n        for result in self.cleaned_results:\n            case_filename = f\"cleaned_case_{result.case_id:02d}.json\"\n            case_filepath = os.path.join(output_dir, case_filename)\n            \n            # Save the cleaned data\n            with open(case_filepath, 'w', encoding='utf-8') as f:\n                json.dump(result.cleaned_data, f, ensure_ascii=False, indent=2)\n            \n            print(f\"  ✅ Case {result.case_id}: {len(result.cleaned_data)} objects → {case_filename}\")\n        \n        # 2. Save all cleaned data to a single file\n        all_cleaned_data = []\n        for result in self.cleaned_results:\n            all_cleaned_data.append({\n                'case_id': result.case_id,\n                'original_type': result.original_type,\n                'original_length': result.original_length,\n                'cleaned_objects_count': len(result.cleaned_data),\n                'success': result.success,\n                'cleaning_operations': result.cleaning_operations,\n                'cleaned_data': result.cleaned_data\n            })\n        \n        all_data_filepath = os.path.join(output_dir, \"all_cleaned_data.json\")\n        with open(all_data_filepath, 'w', encoding='utf-8') as f:\n            json.dump(all_cleaned_data, f, ensure_ascii=False, indent=2)\n        \n        print(f\"  📁 All data: {len(all_cleaned_data)} cases → all_cleaned_data.json\")\n        \n        # 3. Generate a cleaning report\n        self._generate_cleaning_report(output_dir)\n    \n    def _generate_cleaning_report(self, output_dir: str):\n        \"\"\"Generates a cleaning report\"\"\"\n        \n        report = []\n        report.append(\"📊 Data Cleaning Report\")\n        report.append(\"=\" * 60)\n        import datetime\n        report.append(f\"Processing Time: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\")\n        report.append(\"\")\n        \n        # Overall statistics\n        total_cases = len(self.cleaned_results)\n        successful_cases = sum(1 for r in self.cleaned_results if r.success)\n        total_objects = sum(len(r.cleaned_data) for r in self.cleaned_results)\n        \n        report.append(\"📈 Overall Statistics:\")\n        report.append(f\"  Total Cases: {total_cases}\")\n        report.append(f\"  Successfully Cleaned: {successful_cases}\")\n        report.append(f\"  Success Rate: {successful_cases/total_cases*100:.1f}%\")\n        report.append(f\"  Total Recovered Objects: {total_objects}\")\n        report.append(\"\")\n        \n        # Detailed statistics\n        list_results = [r for r in self.cleaned_results if r.original_type == 'list']\n        str_results = [r for r in self.cleaned_results if r.original_type == 'str']\n        \n        if list_results:\n            report.append(\"📋 List Type Cleaning Statistics:\")\n            for r in list_results:\n                ops = r.cleaning_operations\n                report.append(f\"  Case {r.case_id}: {ops['original_count']} → {ops['final_count']} objects\")\n                if ops['bbox_fixes'] > 0:\n                    report.append(f\"    - bbox fixes: {ops['bbox_fixes']}\")\n                if ops['removed_items'] > 0:\n                    report.append(f\"    - invalid items removed: {ops['removed_items']}\")\n            report.append(\"\")\n        \n        if str_results:\n            report.append(\"📝 String Type Cleaning Statistics:\")\n            for r in str_results:\n                ops = r.cleaning_operations\n                status = \"✅\" if r.success else \"❌\"\n                report.append(f\"  Case {r.case_id} {status}: {ops['original_length']:,} chars → {ops['final_objects']} objects\")\n                details = []\n                if ops['delimiter_fixes'] > 0:\n                    details.append(f\"Delimiter fixes: {ops['delimiter_fixes']}\")\n                if ops['tail_truncated']:\n                    reduction = ops['original_length'] - ops['truncated_length']\n                    details.append(f\"Tail truncation: -{reduction:,} chars\")\n                if ops['duplicate_dicts_removed'] > 0:\n                    details.append(f\"Duplicates removed: {ops['duplicate_dicts_removed']}\")\n                if details:\n                    report.append(f\"    - {', '.join(details)}\")\n            report.append(\"\")\n        \n        # Note on data order\n        report.append(\"🔄 Data Order Guarantee:\")\n        report.append(\"  ✅ The relative order of all dict objects is preserved during cleaning.\")\n        report.append(\"  ✅ When deduplicating, the first occurrence of a dict is kept, and subsequent duplicates are removed.\")\n        report.append(\"  ✅ The order of items in List-type data is fully preserved.\")\n        \n        # Save the report\n        report_filepath = os.path.join(output_dir, \"cleaning_report.txt\")\n        with open(report_filepath, 'w', encoding='utf-8') as f:\n            f.write('\\n'.join(report))\n        \n        print(f\"  📋 Cleaning report: cleaning_report.txt\")\n        \n        # Also print to console\n        print(f\"\\n{chr(10).join(report)}\")\n\n\ndef main():\n    \"\"\"Main function\"\"\"\n    \n    # Create a data cleaner instance\n    cleaner = OutputCleaner()\n    \n    # Input file\n    jsonl_path = \"output_with_failcase.jsonl\"\n    \n    # Output directory\n    output_dir = \"output_with_failcase_cleaned\"\n    \n    # Clean all data\n    results = cleaner.clean_all_data(jsonl_path)\n    \n    # Save the cleaned data\n    cleaner.save_cleaned_data(output_dir)\n    \n    print(f\"\\n🎉 Data cleaning complete!\")\n    print(f\"📁 Cleaned data saved in: {output_dir}\")\n\n\nif __name__ == \"__main__\":\n    main() "
  },
  {
    "path": "dots_ocr/utils/prompts.py",
    "content": "dict_promptmode_to_prompt = {\n    # prompt_layout_all_en: parse all layout info in json format.\n    \"prompt_layout_all_en\": \"\"\"Please output the layout information from the PDF image, including each layout element's bbox, its category, and the corresponding text content within the bbox.\n\n1. Bbox format: [x1, y1, x2, y2]\n\n2. Layout Categories: The possible categories are ['Caption', 'Footnote', 'Formula', 'List-item', 'Page-footer', 'Page-header', 'Picture', 'Section-header', 'Table', 'Text', 'Title'].\n\n3. Text Extraction & Formatting Rules:\n    - Picture: For the 'Picture' category, the text field should be omitted.\n    - Formula: Format its text as LaTeX.\n    - Table: Format its text as HTML.\n    - All Others (Text, Title, etc.): Format their text as Markdown.\n\n4. Constraints:\n    - The output text must be the original text from the image, with no translation.\n    - All layout elements must be sorted according to human reading order.\n\n5. Final Output: The entire output must be a single JSON object.\n\"\"\",\n\n    # prompt_layout_only_en: layout detection\n    \"prompt_layout_only_en\": \"\"\"Please output the layout information from this PDF image, including each layout's bbox and its category. The bbox should be in the format [x1, y1, x2, y2]. The layout categories for the PDF document include ['Caption', 'Footnote', 'Formula', 'List-item', 'Page-footer', 'Page-header', 'Picture', 'Section-header', 'Table', 'Text', 'Title']. Do not output the corresponding text. The layout result should be in JSON format.\"\"\",\n\n    # prompt_ocr: parse ocr text except the Page-header and Page-footer\n    \"prompt_ocr\": \"\"\"Extract the text content from this image.\"\"\",\n\n    # prompt_grounding_ocr: extract text content in the given bounding box\n    \"prompt_grounding_ocr\": \"\"\"Extract text from the given bounding box on the image (format: [x1, y1, x2, y2]).\\nBounding Box:\\n\"\"\",\n\n    # prompt_web_parsing: parse all webpage layout info in json format.\n    \"prompt_web_parsing\": \"\"\"Parsing the layout info of this webpage image with format json:\\n\"\"\",\n\n    # prompt_scene_spotting: scene spotting\n    \"prompt_scene_spotting\": \"\"\"Detect and recognize the text in the image.\"\"\",\n    \n    # prompt_img2svg: generate the SVG code of the image\n    \"prompt_image_to_svg\": \"\"\"Please generate the SVG code based on the image.viewBox=\"0 0 {width} {height}\\\"\"\"\",\n\n    # prompt_free_qa: general prompt \n    \"prompt_general\": \"\"\" \"\"\",\n\n    # \"prompt_table_html\": \"\"\"Convert the table in this image to HTML.\"\"\",\n    # \"prompt_table_latex\": \"\"\"Convert the table in this image to LaTeX.\"\"\",\n    # \"prompt_formula_latex\": \"\"\"Convert the formula in this image to LaTeX.\"\"\",\n}\n"
  },
  {
    "path": "requirements.txt",
    "content": "# streamlit \ngradio\ngradio_image_annotation\nPyMuPDF\nopenai\nqwen_vl_utils\ntransformers==4.56.1\nhuggingface_hub\nmodelscope\n# flash-attn==2.8.0.post2  # to speed up inference need flash-attn\naccelerate\ncairosvg"
  },
  {
    "path": "setup.py",
    "content": "from setuptools import setup, find_packages\n\n# 从requirements.txt文件读取依赖\ndef parse_requirements(filename):\n    with open(filename, 'r', encoding='utf-8') as f:\n        return f.read().splitlines()\n        \nsetup(\n    name='dots_ocr',  \n    version='1.0', \n    packages=find_packages(),  \n    include_package_data=True,  \n    install_requires=parse_requirements('requirements.txt'),  \n    description='dots.ocr: Multilingual Document Layout Parsing in one Vision-Language Model',\n    url=\"https://github.com/rednote-hilab/dots.ocr\",\n    python_requires=\">=3.10\",\n)"
  },
  {
    "path": "tools/download_model.py",
    "content": "from argparse import ArgumentParser\nimport os\n\n\nif __name__ == '__main__':\n    parser = ArgumentParser()\n    parser.add_argument('--type', '-t', type=str, default=\"huggingface\")\n    parser.add_argument('--name', '-n', type=str, default=\"rednote-hilab/dots.ocr-1.5\")\n    args = parser.parse_args()\n    script_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n    print(f\"Attention: The model save dir dots.ocr should be replace by a name without `.` like DotsOCR, util we merge our code to transformers.\")\n    model_dir = os.path.join(script_dir, \"weights/DotsOCR_1_5\")\n    if not os.path.exists(model_dir):\n        os.makedirs(model_dir)\n    if args.type == \"huggingface\":\n        from huggingface_hub import snapshot_download\n        snapshot_download(repo_id=args.name, local_dir=model_dir, local_dir_use_symlinks=False, resume_download=True)\n    elif args.type == \"modelscope\":\n        from modelscope import snapshot_download\n        snapshot_download(repo_id=args.name, local_dir=model_dir)\n    else:\n        raise ValueError(f\"Invalid type: {args.type}\")\n    \n    print(f\"model downloaded to {model_dir}\")\n"
  },
  {
    "path": "tools/elo_score_prompt.py",
    "content": "def construct_prompt(c1_text, c2_text):\n    \"\"\"\n    Constructs the complete Prompt sent to Gemini (English Version).\n    c1_text: Markdown text from Model 1\n    c2_text: Markdown text from Model 2\n    \"\"\"\n    \n    prompt = f\"\"\"You are an expert in evaluating OCR content accuracy. Please compare the model outputs with the original image, focusing heavily on **content accuracy** while ignoring formatting and layout differences.\n\n【Evaluation Focus - Focus ONLY on Content Accuracy】\n1. **Text Accuracy**:\n   - Typos: Character recognition errors (e.g., \"test\" recognized as \"tost\").\n   - Omissions: Missing characters or words present in the original text.\n   - Hallucinations: Adding characters that do not exist in the original text.\n\n2. **Table Accuracy**:\n   - Correctness of data and text within the table.\n   - Completeness of cell content.\n   - Correct row/column alignment.\n\n3. **Formula Accuracy** (Evaluate based on):\n   - **Correctness**: Are mathematical symbols, variables, and operators preserved accurately?\n   - **Completeness**: Are all parts of the formula present without omission?\n   - **Semantic Equivalence**: Does the extracted formula convey the exact same mathematical meaning?\n\n【Tie Judgment Criteria - Important】\nYou must judge as a **tie** in the following cases:\n- Text content is identical, differing only in Markdown formatting.\n- Table data is identical, differing only in Markdown table syntax.\n- Formula content is semantically equivalent, differing only in LaTeX representation.\n- Both models correctly identified the core content; minor differences do not affect information retrieval.\n- Both models share the same minor errors or are both perfect.\n- **Image/Figure processing differs** (one extracts text, one gives bbox, one ignores it), but the main text is accurate.\n\n【Items to Ignore - Do NOT factor into scoring】\n- Markdown formatting differences (e.g., `# Header` vs `## Header`, `*` vs `-` for lists).\n- Layout and typesetting differences (newlines, indentation, alignment).\n- Recognition differences in non-body text like Headers, Footers, and Page Numbers.\n- Text wrapping and paragraph segmentation nuances.\n- Table border styles (e.g., `|---|---|` vs `|:--|--:|`).\n- Different but equivalent LaTeX representations for formulas.\n- **Image/Figure Processing Differences (ABSOLUTELY IGNORE)**: \n  - How the model parses image/figure regions is **completely excluded** from the scoring standard.\n  - Whether it parses as a `figure` field, outputs bbox coordinates, extracts text inside the image, provides a caption, describes the image content, or **completely ignores/skips the image**, these are all considered equivalent.\n  - Do NOT declare a winner based on image handling.\n\n【Model 1 Output】:\n```markdown\n{c1_text} \n```\n\n【Model 2 Output】:\n```markdown\n{c2_text}\n```\n\n【Evaluation Process】\n1. Carefully compare the text content against the original image.\n2. Identify errors, omissions, or additions in text recognition for both models.\n3. Check the accuracy of table data.\n4. Evaluate the correctness, completeness, and semantic equivalence of mathematical formulas.\n5. **Ignore image regions**: Confirm that differences in image/figure parsing are not used for scoring.\n6. Important: If the substance is the same and only the format differs, judge as a tie.\n7. Only declare a winner if there is a significant difference in **content accuracy**.\n\n【Examples of Ties】\n- Model 1: \"# Title\", Model 2: \"## Title\" (Same content, different level).\n- Model 1: \"* Item\", Model 2: \"- Item\" (Same content, different bullet).\n- Formula: Model 1 \"$x^2$\", Model 2 \"$x*x$\" (Different LaTeX, same meaning).\n- Table data is identical, but column alignment syntax differs.\n- Identification is identical, but one model parsed the footer while the other didn't (Judge as Tie).\n- **Image handling**: Model 1 outputs an image bbox, Model 2 outputs an image description, Model 3 ignores the image. As long as the main text is accurate, this is a **Tie**.\n\n【Output Requirement】 Please strictly return the result in the following JSON format:\n\n{{\"winner\": \"tie\", \"reason\": \"Detailed explanation of the judgment, specifically noting the logic for a tie\"}}\n\nThe value of \"winner\" must be one of:\n- \"1\": Model 1 is clearly better in content accuracy.\n- \"2\": Model 2 is clearly better in content accuracy.\n- \"tie\": Both models perform equally in content accuracy (including cases of identical content but different formatting/image handling).\n\nIn the \"reason\" field, specifically explain:\n- If a tie: Explain the consistency of the content and explicitly mention which formatting or image handling differences were ignored.\n- If a winner: Specifically point out the accuracy differences (typos, missing words, table/formula errors).\n- **Note**: It is better to judge a tie than to incorrectly determine a winner based on minor formatting or image parsing differences. **Content accuracy of the main text is the ONLY standard.**\n\"\"\"\n    \n    return prompt"
  },
  {
    "path": "tools/eval_omnidocbench.md",
    "content": "Here is the step-by-step doc to reproduce OmniDocBench benchmark results.\n\n## 1. Model Env\nHere, we use [Docker Image](https://hub.docker.com/r/rednotehilab/dots.ocr) for setup.\n\n## 2. Model Launch\n```shell\n# dots.ocr parser env\ngit clone https://github.com/rednote-hilab/dots.ocr.git\ncd dots.ocr\npip install -e .\n \n# model setup and register\npython3 tools/download_model.py\nexport hf_model_path=./weights/DotsOCR  # Path to your downloaded model weights, Please use a directory name without periods (e.g., `DotsOCR` instead of `dots.ocr`) for the model save path. This is a temporary workaround pending our integration with Transformers.\nexport PYTHONPATH=$(dirname \"$hf_model_path\"):$PYTHONPATH\nsed -i '/^from vllm\\.entrypoints\\.cli\\.main import main$/a\\\nfrom DotsOCR import modeling_dots_ocr_vllm' `which vllm`  # If you downloaded model weights by yourself, please replace `DotsOCR` by your model saved directory name, and remember to use a directory name without periods (e.g., `DotsOCR` instead of `dots.ocr`) \n \n# launch vllm server\nCUDA_VISIBLE_DEVICES=0 vllm serve ${hf_model_path} --tensor-parallel-size 1 --gpu-memory-utilization 0.95  --chat-template-content-format string --served-model-name model --trust-remote-code\n```\n\n\n## 3. Model Inference\n\n```python\n\nfrom tqdm import tqdm\nimport json\nimport argparse\nfrom multiprocessing.pool import ThreadPool, Pool\nimport shutil\nimport os\n\n\nif __name__==\"__main__\":\n    from dots_ocr import DotsOCRParser\n    parser = argparse.ArgumentParser(\n        description=\"dots.ocr Multilingual Document Layout Parser\",\n    )\n    \n    parser.add_argument(\n        '--bbox', \n        type=int, \n        nargs=4, \n        metavar=('x1', 'y1', 'x2', 'y2'),\n        help='should give this argument if you want to prompt_grounding_ocr'\n    )\n    parser.add_argument(\n        \"--ip\", type=str, default=\"localhost\",\n        help=\"\"\n    )\n    parser.add_argument(\n        \"--port\", type=int, default=8000,\n        help=\"\"\n    )\n    parser.add_argument(\n        \"--model_name\", type=str, default=\"model\",\n        help=\"\"\n    )\n    parser.add_argument(\n        \"--temperature\", type=float, default=0.1,\n        help=\"\"\n    )\n    parser.add_argument(\n        \"--top_p\", type=float, default=1.0,\n        help=\"\"\n    )\n    parser.add_argument(\n        \"--dpi\", type=int, default=200,\n        help=\"\"\n    )\n    parser.add_argument(\n        \"--max_completion_tokens\", type=int, default=16384,\n        help=\"\"\n    )\n    parser.add_argument(\n        \"--num_thread\", type=int, default=128,\n        help=\"\"\n    )\n    # parser.add_argument(\n    #     \"--fitz_preprocess\", type=bool, default=False,\n    #     help=\"False will use tikz dpi upsample pipeline, good for images which has been render with low dpi, but maybe result in higher computational costs\"\n    # )\n    parser.add_argument(\n        \"--min_pixels\", type=int, default=None,\n        help=\"\"\n    )\n    parser.add_argument(\n        \"--max_pixels\", type=int, default=None,\n        help=\"\"\n    )\n    args = parser.parse_args()\n\n    dots_ocr_parser = DotsOCRParser(\n        ip=args.ip,\n        port=args.port,\n        model_name=args.model_name,\n        temperature=args.temperature,\n        top_p=args.top_p,\n        max_completion_tokens=args.max_completion_tokens,\n        num_thread=args.num_thread,\n        dpi=args.dpi,\n        # output_dir=args.output, \n        min_pixels=args.min_pixels,\n        max_pixels=args.max_pixels,\n    )\n\n    filepath = \"/path/to/OmniDocBench.jsonl\"  # download OmniDocBench datasets from https://huggingface.co/datasets/opendatalab/OmniDocBench, reformat it to input the images into model\n    with open(filepath, 'r') as f:\n        list_items = [json.loads(line) for line in f]\n    \n    results = []\n    output_path = \"./output_omni.jsonl\"\n    f_out = open(output_path, 'w')\n\n    tasks = [[item['file_path'], f_out] for item in list_items]\n\n    def _excute(task):\n        image_path, f_out = task\n        result = dots_ocr_parser.parse_file(\n            image_path, \n            prompt_mode=\"prompt_layout_all_en\",\n            # prompt_mode=\"prompt_ocr\",\n            fitz_preprocess=True,\n            )\n        results.append(result)\n        f_out.write(f\"{json.dumps(result, ensure_ascii=False)}\\n\")\n        f_out.flush()\n\n    with ThreadPool(128) as pool:\n        with tqdm(total=len(tasks)) as pbar:\n            for result in pool.imap(_excute, tasks):\n                pbar.update(1)\n        pool.close()\n        pool.join()   \n\n    f_out.close()\n\n    eval_result_save_dir = \"./output_omni/\"\n    os.makedirs(eval_result_save_dir, exist_ok=True)\n\n    with open(output_path, \"r\") as f:\n        for line in f.readlines():\n            item = json.loads(line)[0]\n            if 'md_content_nohf_path' in item:\n                file_name = os.path.basename(item['md_content_nohf_path']).replace(\"_nohf\", \"\")\n                shutil.copy2(item['md_content_nohf_path'], os.path.join(eval_result_save_dir, file_name))\n            else:\n                shutil.copy2(item['md_content_path'], eval_result_save_dir)\n\n    print(f\"md results saved to {eval_result_save_dir}\")\n```\n\n\n## 4. Evaluation\nWe use [OmniDocBench](https://github.com/opendatalab/OmniDocBench) to evaluate the performance. Prepare the omnidocbench env by yourself, follow the official steps.\n\n```shell\ngit clone https://github.com/opendatalab/OmniDocBench.git\ncd /OmniDocBench\n\n# Follow https://github.com/opendatalab/OmniDocBench?tab=readme-ov-file#environment-setup-and-running\nconda create -n omnidocbench python=3.10\nconda activate omnidocbench\npip install -r requirements.txt\n\n# Eval. Change the gt&pred path in end2end.yaml to your own, here by our inference steps, prediction data_path set as: /path/to/dots.ocr/output_omni/\npython pdf_validation.py --config ./end2end.yaml > evaluation_output.log\n \ncat evaluation_output.log\n```\n\n./end2end.yaml like:\n```yaml\nend2end_eval:\n  metrics:\n    text_block:\n      metric:\n        - Edit_dist\n    display_formula:\n      metric:\n        - Edit_dist\n        - CDM\n    table:\n      metric:\n        - TEDS\n        - Edit_dist\n    reading_order:\n      metric:\n        - Edit_dist\n  dataset:\n    dataset_name: end2end_dataset\n    ground_truth:\n      data_path: ./OmniDocBench.json  # change to omnidocbench official gt\n    prediction:\n      data_path: /path/to/dots.ocr/output_omni/  # change to your own output dir\n    match_method: quick_match\n```\n\nEval results as follow:\n```shell\nDATASET_REGISTRY:  ['recogition_text_dataset', 'omnidocbench_single_module_dataset', 'recogition_formula_dataset', 'recogition_table_dataset', 'end2end_dataset', 'recogition_end2end_base_dataset', 'recogition_end2end_table_dataset', 'detection_dataset', 'detection_dataset_simple_format', 'md2md_dataset']\nMETRIC_REGISTRY:  ['TEDS', 'BLEU', 'METEOR', 'Edit_dist', 'CDM']\nEVAL_TASK_REGISTRY:  ['detection_eval', 'end2end_eval', 'recogition_eval']\n###### Process:  _quick_match\n【Overall】\ndisplay_formula CDM is not found\ndisplay_formula CDM is not found\n----------------------------  --------------------\ntext_block_Edit_dist_EN       0.031039851583834904\ntext_block_Edit_dist_CH       0.0643426705744435\ndisplay_formula_Edit_dist_EN  0.32843522681423176\ndisplay_formula_Edit_dist_CH  0.42557920974720154\ndisplay_formula_CDM_EN        -\ndisplay_formula_CDM_CH        -\ntable_TEDS_EN                 88.91012727754615\ntable_TEDS_CH                 89.0531009325606\ntable_Edit_dist_EN            0.0943878061222165\ntable_Edit_dist_CH            0.09173810770062703\nreading_order_Edit_dist_EN    0.04079293927450415\nreading_order_Edit_dist_CH    0.06625588944827145\noverall_EN                    0.12366395594869685\noverall_CH                    0.16197896936763587\n----------------------------  --------------------\n\n\n【PDF types】\n--------------------------------  ---------\ndata_source: book                 0.0183191\ndata_source: PPT2PDF              0.0470068\ndata_source: research_report      0.0107441\ndata_source: colorful_textbook    0.0710044\ndata_source: exam_paper           0.0763102\ndata_source: magazine             0.0278807\ndata_source: academic_literature  0.0279\ndata_source: note                 0.112103\ndata_source: newspaper            0.0787516\nALL                               0.055183\n--------------------------------  ---------\n\n\n【Layout】\nLayout                      Mean         Var\n---------------------  ---------  ----------\nlayout: single_column  0.0267498  0.0187775\nlayout: double_column  0.0789817  0.0283393\nlayout: three_column   0.0738766  0.00154036\nlayout: other_layout   0.115941   0.0336075\n\n\n【Text Attribute】\n--------------------------------------  ---------\ntext_language: text_english             0.0296053\ntext_language: text_simplified_chinese  0.106577\ntext_language: text_en_ch_mixed         0.0888106\ntext_background: white                  0.0880222\ntext_background: single_colored         0.0752833\ntext_background: multi_colored          0.0723353\n--------------------------------------  ---------\n\n\n【Table Attribute】\n----------------------------------  --------\nlanguage: table_en                  0.876843\nlanguage: table_simplified_chinese  0.872133\nlanguage: table_en_ch_mixed         0.941139\nline: full_line                     0.895071\nline: less_line                     0.897401\nline: fewer_line                    0.842987\nline: wireless_line                 0.847398\nwith_span: True                     0.865542\nwith_span: False                    0.881582\ninclude_equation: True              0.839543\ninclude_equation: False             0.884461\ninclude_background: True            0.886555\ninclude_background: False           0.8707\ntable_layout: vertical              0.884036\ntable_layout: horizontal            0.875826\n----------------------------------  --------\n\n```\n\n> **Notes:** \n> - The metrics reported in the README.md are the average of 5 runs. Each run may show a variance of ±0.005 for the overall_EN and overall_ZH scores."
  }
]