Full Code of opendatalab/PDF-Extract-Kit for AI

main fdb25fd4bd90 cached
143 files
459.0 KB
118.3k tokens
364 symbols
1 requests
Download .txt
Showing preview only (497K chars total). Download the full file or copy to clipboard to get everything.
Repository: opendatalab/PDF-Extract-Kit
Branch: main
Commit: fdb25fd4bd90
Files: 143
Total size: 459.0 KB

Directory structure:
gitextract_dsl5uwwk/

├── .gitignore
├── .readthedocs.yaml
├── .vscode/
│   └── launch.json
├── LICENSE.md
├── README.md
├── README_zh-CN.md
├── configs/
│   ├── config.yaml
│   ├── formula_detection.yaml
│   ├── formula_recognition.yaml
│   ├── layout_detection.yaml
│   ├── layout_detection_layoutlmv3.yaml
│   ├── layout_detection_yolo.yaml
│   ├── ocr.yaml
│   └── table_parsing.yaml
├── docs/
│   ├── en/
│   │   ├── .readthedocs.yaml
│   │   ├── Makefile
│   │   ├── algorithm/
│   │   │   ├── formula_detection.rst
│   │   │   ├── formula_recognition.rst
│   │   │   ├── layout_detection.rst
│   │   │   ├── ocr.rst
│   │   │   ├── reading_order.rst
│   │   │   └── table_recognition.rst
│   │   ├── conf copy.py
│   │   ├── conf.bak
│   │   ├── conf.py
│   │   ├── evaluation/
│   │   │   ├── formula_detection.rst
│   │   │   ├── formula_recognition.rst
│   │   │   ├── layout_detection.rst
│   │   │   ├── ocr.rst
│   │   │   ├── pdf_extract.rst
│   │   │   ├── reading_order.rst
│   │   │   └── table_recognition.rst
│   │   ├── get_started/
│   │   │   ├── installation.rst
│   │   │   ├── pretrained_model.rst
│   │   │   └── quickstart.rst
│   │   ├── index.rst
│   │   ├── make.bat
│   │   ├── models/
│   │   │   └── supported.md
│   │   ├── notes/
│   │   │   └── changelog.md
│   │   ├── project/
│   │   │   ├── doc_translate.rst
│   │   │   ├── pdf_extract.rst
│   │   │   └── speed_up.rst
│   │   ├── switch_language.md
│   │   └── task_extend/
│   │       ├── code.rst
│   │       ├── doc.rst
│   │       └── evaluation.rst
│   ├── requirements.txt
│   └── zh_cn/
│       ├── .readthedocs.yaml
│       ├── Makefile
│       ├── algorithm/
│       │   ├── formula_detection.rst
│       │   ├── formula_recognition.rst
│       │   ├── layout_detection.rst
│       │   ├── ocr.rst
│       │   ├── reading_order.rst
│       │   └── table_recognition.rst
│       ├── conf.py
│       ├── evaluation/
│       │   ├── formula_detection.rst
│       │   ├── formula_recognition.rst
│       │   ├── layout_detection.rst
│       │   ├── ocr.rst
│       │   ├── pdf_extract.rst
│       │   ├── reading_order.rst
│       │   └── table_recognition.rst
│       ├── get_started/
│       │   ├── installation.rst
│       │   ├── pretrained_model.rst
│       │   └── quickstart.rst
│       ├── index.rst
│       ├── make.bat
│       ├── models/
│       │   └── supported.md
│       ├── notes/
│       │   └── changelog.md
│       ├── project/
│       │   ├── doc_translate.rst
│       │   ├── pdf_extract.rst
│       │   └── speed_up.rst
│       ├── switch_language.md
│       └── task_extend/
│           ├── code.rst
│           ├── doc.rst
│           └── evaluation.rst
├── pdf_extract_kit/
│   ├── __init__.py
│   ├── configs/
│   │   └── unimernet.yaml
│   ├── dataset/
│   │   ├── __init__.py
│   │   └── dataset.py
│   ├── registry/
│   │   ├── __init__.py
│   │   └── registry.py
│   ├── tasks/
│   │   ├── __init__.py
│   │   ├── base_task.py
│   │   ├── formula_detection/
│   │   │   ├── __init__.py
│   │   │   ├── models/
│   │   │   │   └── yolo.py
│   │   │   └── task.py
│   │   ├── formula_recognition/
│   │   │   ├── __init__.py
│   │   │   ├── models/
│   │   │   │   └── unimernet.py
│   │   │   └── task.py
│   │   ├── layout_detection/
│   │   │   ├── __init__.py
│   │   │   ├── models/
│   │   │   │   ├── __init__.py
│   │   │   │   ├── layoutlmv3.py
│   │   │   │   ├── layoutlmv3_util/
│   │   │   │   │   ├── backbone.py
│   │   │   │   │   ├── beit.py
│   │   │   │   │   ├── deit.py
│   │   │   │   │   ├── layoutlmft/
│   │   │   │   │   │   ├── __init__.py
│   │   │   │   │   │   ├── data/
│   │   │   │   │   │   │   ├── __init__.py
│   │   │   │   │   │   │   ├── cord.py
│   │   │   │   │   │   │   ├── data_collator.py
│   │   │   │   │   │   │   ├── funsd.py
│   │   │   │   │   │   │   ├── image_utils.py
│   │   │   │   │   │   │   └── xfund.py
│   │   │   │   │   │   └── models/
│   │   │   │   │   │       ├── __init__.py
│   │   │   │   │   │       └── layoutlmv3/
│   │   │   │   │   │           ├── __init__.py
│   │   │   │   │   │           ├── configuration_layoutlmv3.py
│   │   │   │   │   │           ├── modeling_layoutlmv3.py
│   │   │   │   │   │           ├── tokenization_layoutlmv3.py
│   │   │   │   │   │           └── tokenization_layoutlmv3_fast.py
│   │   │   │   │   ├── layoutlmv3_base_inference.yaml
│   │   │   │   │   ├── model_init.py
│   │   │   │   │   ├── rcnn_vl.py
│   │   │   │   │   └── visualizer.py
│   │   │   │   └── yolo.py
│   │   │   └── task.py
│   │   ├── ocr/
│   │   │   ├── __init__.py
│   │   │   ├── models/
│   │   │   │   └── paddle_ocr.py
│   │   │   └── task.py
│   │   └── table_parsing/
│   │       ├── __init__.py
│   │       ├── models/
│   │       │   └── struct_eqtable.py
│   │       └── task.py
│   ├── utils/
│   │   ├── __init__.py
│   │   ├── config_loader.py
│   │   ├── data_preprocess.py
│   │   ├── merge_blocks_and_spans.py
│   │   ├── pdf_utils.py
│   │   └── visualization.py
│   └── version.py
├── project/
│   └── pdf2markdown/
│       ├── README.md
│       ├── configs/
│       │   └── pdf2markdown.yaml
│       └── scripts/
│           ├── pdf2markdown.py
│           └── run_project.py
├── pyproject.toml
├── requirements/
│   └── docs.txt
├── requirements-cpu.txt
├── requirements.txt
└── scripts/
    ├── formula_detection.py
    ├── formula_recognition.py
    ├── layout_detection.py
    ├── ocr.py
    ├── run_task.py
    └── table_parsing.py

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
*.ipynb*
*.ipynb

# local data
outputs/*
data/*
temp*
test*

# python
.ipynb_checkpoints
*.ipynb
**/__pycache__/

# logs
*.log
*.out

models/*

# Sphinx documentation
docs/*/_build/


================================================
FILE: .readthedocs.yaml
================================================
version: 2

build:
  os: ubuntu-22.04
  tools:
    python: "3.10"

formats:
  - epub

python:
  install:
    - requirements: requirements/docs.txt

sphinx:
  configuration: docs/zh_cn/conf.py


================================================
FILE: .vscode/launch.json
================================================
{
    // 使用 IntelliSense 了解相关属性。 
    // 悬停以查看现有属性的描述。
    // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "run_mfd",
            "type": "debugpy",
            "request": "launch",
            "program": "${workspaceFolder}/scripts/run_mfd.py",
            "console": "integratedTerminal",
            "args": [
                "--config",
                "configs/config_mfd.yaml" 
            ],
            "env": {
                "PYTHONPATH": "/Users/bin/anaconda3/envs/mfd_test"
            }
        },
        {
            "name": "run_formula_recognition",
            "type": "debugpy",
            "request": "launch",
            "program": "${workspaceFolder}/scripts/formula_recognition.py",
            "console": "integratedTerminal",
            "args": [
                "--config",
                "configs/formula_recognition.yaml"
            ],
            "env": {
                "PYTHONPATH": "/Users/bin/anaconda3/envs/mfd_test"
            }
        },
        {
            "name": "run_ocr",
            "type": "debugpy",
            "request": "launch",
            "program": "${workspaceFolder}/scripts/ocr.py",
            "console": "integratedTerminal",
            "args": [
                "--config",
                "configs/ocr.yaml"
            ],
            "env": {
                "PYTHONPATH": "/Users/bin/anaconda3/envs/mfd_test"
            }
        },
        {
            "name": "run_formula_detection",
            "type": "debugpy",
            "request": "launch",
            "program": "${workspaceFolder}/scripts/formula_detection.py",
            "console": "integratedTerminal",
            "args": [
                "--config",
                "configs/formula_detection.yaml"
            ],
            "env": {
                "PYTHONPATH": "/Users/bin/anaconda3/envs/mfd_test"
            }
        },
        {
            "name": "run_layout_detection",
            "type": "debugpy",
            "request": "launch",
            "program": "${workspaceFolder}/scripts/layout_detection.py",
            "console": "integratedTerminal",
            "args": [
                "--config",
                "configs/layout_detection.yaml"
            ],
            "env": {
                "PYTHONPATH": "/Users/bin/anaconda3/envs/mfd_test"
            }
        },
        {
            "name": "run_layout_detection_layoutlmv3",
            "type": "debugpy",
            "request": "launch",
            "program": "${workspaceFolder}/scripts/layout_detection.py",
            "console": "integratedTerminal",
            "args": [
                "--config",
                "configs/layout_detection_layoutlmv3.yaml"
            ],
            "env": {
                "PYTHONPATH": "/Users/bin/anaconda3/envs/mfd_test"
            }
        }
    ]
}

================================================
FILE: LICENSE.md
================================================
                    GNU AFFERO GENERAL PUBLIC LICENSE
                       Version 3, 19 November 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.

  A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate.  Many developers of free software are heartened and
encouraged by the resulting cooperation.  However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.

  The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community.  It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server.  Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.

  An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals.  This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU Affero General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Remote Network Interaction; Use with the GNU General Public License.

  Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software.  This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time.  Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published
    by the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source.  For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code.  There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

================================================
FILE: README.md
================================================

<p align="center">
  <img src="assets/readme/pdf-extract-kit_logo.png" width="220px" style="vertical-align:middle;">
</p>

<div align="center">

English | [简体中文](./README_zh-CN.md)

[PDF-Extract-Kit-1.0 Tutorial](https://pdf-extract-kit.readthedocs.io/en/latest/get_started/pretrained_model.html)

[[Models (🤗Hugging Face)]](https://huggingface.co/opendatalab/PDF-Extract-Kit-1.0) | [[Models(<img src="./assets/readme/modelscope_logo.png" width="20px">ModelScope)]](https://www.modelscope.cn/models/OpenDataLab/PDF-Extract-Kit-1.0) 
 
🔥🔥🔥 [MinerU: Efficient Document Content Extraction Tool Based on PDF-Extract-Kit](https://github.com/opendatalab/MinerU)

</div>

<p align="center">
    👋 join us on <a href="https://discord.gg/Tdedn9GTXq" target="_blank">Discord</a> and <a href="https://r.vansin.top/?r=MinerU" target="_blank">WeChat</a>
</p>


## Overview

`PDF-Extract-Kit` is a powerful open-source toolkit designed to efficiently extract high-quality content from complex and diverse PDF documents. Here are its main features and advantages:

- **Integration of Leading Document Parsing Models**: Incorporates state-of-the-art models for layout detection, formula detection, formula recognition, OCR, and other core document parsing tasks.
- **High-Quality Parsing Across Diverse Documents**: Fine-tuned with diverse document annotation data to deliver high-quality results across various complex document types.
- **Modular Design**: The flexible modular design allows users to easily combine and construct various applications by modifying configuration files and minimal code, making application building as straightforward as stacking blocks.
- **Comprehensive Evaluation Benchmarks**: Provides diverse and comprehensive PDF evaluation benchmarks, enabling users to choose the most suitable model based on evaluation results.

**Experience PDF-Extract-Kit now and unlock the limitless potential of PDF documents!**

> **Note:** PDF-Extract-Kit is designed for high-quality document processing and functions as a model toolbox.    
> If you are interested in extracting high-quality document content (e.g., converting PDFs to Markdown), please use [MinerU](https://github.com/opendatalab/MinerU), which combines the high-quality predictions from PDF-Extract-Kit with specialized engineering optimizations for more convenient and efficient content extraction.    
> If you're a developer looking to create engaging applications such as document translation, document Q&A, or document assistants, you'll find it very convenient to build your own projects using PDF-Extract-Kit. In particular, we will periodically update the PDF-Extract-Kit/project directory with interesting applications, so stay tuned!

**We welcome researchers and engineers from the community to contribute outstanding models and innovative applications by submitting PRs to become contributors to the PDF-Extract-Kit project.**

## Model Overview

| **Task Type**     | **Description**                                                                 | **Models**                    |
|-------------------|---------------------------------------------------------------------------------|-------------------------------|
| **Layout Detection** | Locate different elements in a document: including images, tables, text, titles, formulas | `DocLayout-YOLO_ft`, `YOLO-v10_ft`, `LayoutLMv3_ft` | 
| **Formula Detection** | Locate formulas in documents: including inline and block formulas            | `YOLOv8_ft`                   |  
| **Formula Recognition** | Recognize formula images into LaTeX source code                             | `UniMERNet`                   |  
| **OCR**           | Extract text content from images (including location and recognition)            | `PaddleOCR`                   | 
| **Table Recognition** | Recognize table images into corresponding source code (LaTeX/HTML/Markdown)   | `PaddleOCR+TableMaster`, `StructEqTable` |  
| **Reading Order** | Sort and concatenate discrete text paragraphs                                    | Coming Soon!                  | 

## News and Updates
- `2024.10.22` 🎉🎉🎉 We are excited to announce that table recognition model [StructTable-InternVL2-1B](https://huggingface.co/U4R/StructTable-InternVL2-1B), which supports output LaTeX, HTML and MarkdDown formats has been officially integrated into `PDF-Extract-Kit 1.0`. Please refer to the [table recognition algorithm documentation](https://pdf-extract-kit.readthedocs.io/en/latest/algorithm/table_recognition.html) for usage instructions!
- `2024.10.17` 🎉🎉🎉 We are excited to announce that the more accurate and faster layout detection model, [DocLayout-YOLO](https://github.com/opendatalab/DocLayout-YOLO), has been officially integrated into `PDF-Extract-Kit 1.0`. Please refer to the [layout detection algorithm documentation](https://pdf-extract-kit.readthedocs.io/en/latest/algorithm/layout_detection.html) for usage instructions!
- `2024.10.10` 🎉🎉🎉 The official release of `PDF-Extract-Kit 1.0`, rebuilt with modularity for more convenient and flexible model usage! Please switch to the [release/0.1.1](https://github.com/opendatalab/PDF-Extract-Kit/tree/release/0.1.1) branch for the old version.
- `2024.08.01` 🎉🎉🎉 Added the [StructEqTable](demo/TabRec/StructEqTable/README_TABLE.md) module for table content extraction. Welcome to use it!
- `2024.07.01` 🎉🎉🎉 We released `PDF-Extract-Kit`, a comprehensive toolkit for high-quality PDF content extraction, including `Layout Detection`, `Formula Detection`, `Formula Recognition`, and `OCR`.

## Performance Demonstration

Many current open-source SOTA models are trained and evaluated on academic datasets, achieving high-quality results only on single document types. To enable models to achieve stable and robust high-quality results on diverse documents, we constructed diverse fine-tuning datasets and fine-tuned some SOTA models to obtain practical parsing models. Below are some visual results of the models.

### Layout Detection

We trained robust `Layout Detection` models using diverse PDF document annotations. Our fine-tuned models achieve accurate extraction results on diverse PDF documents such as papers, textbooks, research reports, and financial reports, and demonstrate high robustness to challenges like blurring and watermarks. The visualization example below shows the inference results of the fine-tuned LayoutLMv3 model.
 
![](assets/readme/layout_example.png)

### Formula Detection

Similarly, we collected and annotated documents containing formulas in both English and Chinese, and fine-tuned advanced formula detection models. The visualization result below shows the inference results of the fine-tuned YOLO formula detection model:

![](assets/readme/mfd_example.png)

### Formula Recognition

[UniMERNet](https://github.com/opendatalab/UniMERNet) is an algorithm designed for diverse formula recognition in real-world scenarios. By constructing large-scale training data and carefully designed results, it achieves excellent recognition performance for complex long formulas, handwritten formulas, and noisy screenshot formulas.

### Table Recognition

[StructEqTable](https://github.com/UniModal4Reasoning/StructEqTable-Deploy) is a high efficiency toolkit that can converts table images into LaTeX/HTML/MarkDown. The latest version, powered by the InternVL2-1B foundation model,  improves Chinese recognition accuracy and expands multi-format output options.

#### For more visual and inference results of the models, please refer to the [PDF-Extract-Kit tutorial documentation](xxx).

## Evaluation Metrics

Coming Soon!

## Usage Guide

### Environment Setup

```bash
conda create -n pdf-extract-kit-1.0 python=3.10
conda activate pdf-extract-kit-1.0
pip install -r requirements.txt
```
> **Note:** If your device does not support GPU, please install the CPU version dependencies using `requirements-cpu.txt` instead of `requirements.txt`.

> **Note:** Current Doclayout-YOLO only supports installation from pypi,if error raises during DocLayout-YOLO installation,please install through `pip3 install doclayout-yolo==0.0.2 --extra-index-url=https://pypi.org/simple` .

### Model Download

Please refer to the [Model Weights Download Tutorial](https://pdf-extract-kit.readthedocs.io/en/latest/get_started/pretrained_model.html) to download the required model weights. Note: You can choose to download all the weights or select specific ones. For detailed instructions, please refer to the tutorial.

### Running Demos

#### Layout Detection Model

```bash 
python scripts/layout_detection.py --config=configs/layout_detection.yaml
```
Layout detection models support **DocLayout-YOLO** (default model), YOLO-v10, and LayoutLMv3. For YOLO-v10 and LayoutLMv3, please refer to [Layout Detection Algorithm](https://pdf-extract-kit.readthedocs.io/en/latest/algorithm/layout_detection.html). You can view the layout detection results in the `outputs/layout_detection` folder.

#### Formula Detection Model

```bash 
python scripts/formula_detection.py --config=configs/formula_detection.yaml
```
You can view the formula detection results in the `outputs/formula_detection` folder.

#### OCR Model

```bash 
python scripts/ocr.py --config=configs/ocr.yaml
```
You can view the OCR results in the `outputs/ocr` folder.

#### Formula Recognition Model

```bash 
python scripts/formula_recognition.py --config=configs/formula_recognition.yaml
```
You can view the formula recognition results in the `outputs/formula_recognition` folder.

#### Table Recognition Model

```bash 
python scripts/table_parsing.py --config configs/table_parsing.yaml
```
You can view the table recognition results in the `outputs/table_parsing` folder.

> **Note:** For more details on using the model, please refer to the[PDF-Extract-Kit-1.0 Tutorial](https://pdf-extract-kit.readthedocs.io/en/latest/get_started/pretrained_model.html).

> This project focuses on using models for `high-quality` content extraction from `diverse` documents and does not involve reconstructing extracted content into new documents, such as PDF to Markdown. For such needs, please refer to our other GitHub project: [MinerU](https://github.com/opendatalab/MinerU).

## To-Do List

- [x] **Table Parsing**: Develop functionality to convert table images into corresponding LaTeX/Markdown format source code.
- [ ] **Chemical Equation Detection**: Implement automatic detection of chemical equations.
- [ ] **Chemical Equation/Diagram Recognition**: Develop models to recognize and parse chemical equations and diagrams.
- [ ] **Reading Order Sorting Model**: Build a model to determine the correct reading order of text in documents.

**PDF-Extract-Kit** aims to provide high-quality PDF content extraction capabilities. We encourage the community to propose specific and valuable needs and welcome everyone to participate in continuously improving the PDF-Extract-Kit tool to advance research and industry development.

## License

This project is open-sourced under the [AGPL-3.0](LICENSE) license.

Since this project uses YOLO code and PyMuPDF for file processing, these components require compliance with the AGPL-3.0 license. Therefore, to ensure adherence to the licensing requirements of these dependencies, this repository as a whole adopts the AGPL-3.0 license.

## Acknowledgement

   - [LayoutLMv3](https://github.com/microsoft/unilm/tree/master/layoutlmv3): Layout detection model
   - [UniMERNet](https://github.com/opendatalab/UniMERNet): Formula recognition model
   - [StructEqTable](https://github.com/UniModal4Reasoning/StructEqTable-Deploy): Table recognition model
   - [YOLO](https://github.com/ultralytics/ultralytics): Formula detection model
   - [PaddleOCR](https://github.com/PaddlePaddle/PaddleOCR): OCR model
   - [DocLayout-YOLO](https://github.com/opendatalab/DocLayout-YOLO): Layout detection model

## Citation
If you find our models / code / papers useful in your research, please consider giving ⭐ and citations 📝, thx :)  
```bibtex
@article{wang2024mineru,
  title={MinerU: An Open-Source Solution for Precise Document Content Extraction},
  author={Wang, Bin and Xu, Chao and Zhao, Xiaomeng and Ouyang, Linke and Wu, Fan and Zhao, Zhiyuan and Xu, Rui and Liu, Kaiwen and Qu, Yuan and Shang, Fukai and others},
  journal={arXiv preprint arXiv:2409.18839},
  year={2024}
}

@misc{zhao2024doclayoutyoloenhancingdocumentlayout,
      title={DocLayout-YOLO: Enhancing Document Layout Analysis through Diverse Synthetic Data and Global-to-Local Adaptive Perception}, 
      author={Zhiyuan Zhao and Hengrui Kang and Bin Wang and Conghui He},
      year={2024},
      eprint={2410.12628},
      archivePrefix={arXiv},
      primaryClass={cs.CV},
      url={https://arxiv.org/abs/2410.12628}, 
}

@misc{wang2024unimernet,
      title={UniMERNet: A Universal Network for Real-World Mathematical Expression Recognition}, 
      author={Bin Wang and Zhuangcheng Gu and Chao Xu and Bo Zhang and Botian Shi and Conghui He},
      year={2024},
      eprint={2404.15254},
      archivePrefix={arXiv},
      primaryClass={cs.CV}
}

@article{he2024opendatalab,
  title={Opendatalab: Empowering general artificial intelligence with open datasets},
  author={He, Conghui and Li, Wei and Jin, Zhenjiang and Xu, Chao and Wang, Bin and Lin, Dahua},
  journal={arXiv preprint arXiv:2407.13773},
  year={2024}
}
```

## Star History

<a>
 <picture>
   <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=opendatalab/PDF-Extract-Kit&type=Date&theme=dark" />
   <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=opendatalab/PDF-Extract-Kit&type=Date" />
   <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=opendatalab/PDF-Extract-Kit&type=Date" />
 </picture>
</a>

## Related Links
- [UniMERNet (Real-World Formula Recognition Algorithm)](https://github.com/opendatalab/UniMERNet)
- [LabelU (Lightweight Multimodal Annotation Tool)](https://github.com/opendatalab/labelU)
- [LabelLLM (Open Source LLM Dialogue Annotation Platform)](https://github.com/opendatalab/LabelLLM)
- [MinerU (One-Stop High-Quality Data Extraction Tool)](https://github.com/opendatalab/MinerU)


================================================
FILE: README_zh-CN.md
================================================

<p align="center">
  <img src="assets/readme/pdf-extract-kit_logo.png" width="220px" style="vertical-align:middle;">
</p>

<div align="center">

[English](./README.md) | 简体中文

[PDF-Extract-Kit-1.0中文教程](https://pdf-extract-kit.readthedocs.io/zh-cn/latest/get_started/pretrained_model.html)

[[Models (🤗Hugging Face)]](https://huggingface.co/opendatalab/PDF-Extract-Kit-1.0) | [[Models(<img src="./assets/readme/modelscope_logo.png" width="20px">ModelScope)]](https://www.modelscope.cn/models/OpenDataLab/PDF-Extract-Kit-1.0) 
 
🔥🔥🔥 [MinerU:基于PDF-Extract-Kit的高效文档内容提取工具](https://github.com/opendatalab/MinerU)
</div>

<p align="center">
    👋 join us on <a href="https://discord.gg/JYsXDXXN" target="_blank">Discord</a> and <a href="https://r.vansin.top/?r=MinerU" target="_blank">WeChat</a>
</p>


## 整体介绍

`PDF-Extract-Kit` 是一款功能强大的开源工具箱,旨在从复杂多样的 PDF 文档中高效提取高质量内容。以下是其主要功能和优势:

- **集成文档解析主流模型**:汇聚布局检测、公式检测、公式识别、OCR等文档解析核心任务的众多SOTA模型;
- **多样性文档下高质量解析结果**:结合多样性文档标注数据在进行模型微调,在复杂多样的文档下提供高质量解析结果;
- **模块化设计**:模块化设计使用户可以通过修改配置文件及少量代码即可自由组合构建各种应用,让应用构建像搭积木一样简便;  
- **全面评测基准**:提供多样性全面的PDF评测基准,用户可根据评测结果选择最适合自己的模型。  

**立即体验 PDF-Extract-Kit,解锁 PDF 文档的无限潜力!** 

> **注意:** PDF-Extract-Kit 专注于高质量文档处理,适合作为模型工具箱使用。
> 如果你想提取高质量文档内容(PDF转Markdown),请直接使用[MinerU](https://github.com/opendatalab/MinerU),MinerU结合PDF-Extract-Kit的高质量预测结果,进行了专门的工程优化,使得PDF文档内容提取更加便捷高效;  
> 如果你是一位开发者,希望搭建更多有意思的应用(如文档翻译,文档问答,文档助手等),基于PDF-Extract-Kit自行进行DIY将会十分便捷。特别地,我们会在`PDF-Extract-Kit/project`下面不定期更新一些有趣的应用,敬请期待!  

**我们欢迎社区研究员和工程师贡献优秀模型和创新应用,通过提交 PR 成为 PDF-Extract-Kit 的贡献者。**


## 模型概览

| **任务类型** | **任务描述**                                                                    | **模型**                     |
|--------------|---------------------------------------------------------------------------------|------------------------------|
| **布局检测** | 定位文档中不同元素位置:包含图像、表格、文本、标题、公式等 | `DocLayout-YOLO_ft`, `YOLO-v10_ft`, `LayoutLMv3_ft` |
| **公式检测** | 定位文档中公式位置:包含行内公式和行间公式                                      | `YOLOv8_ft`                       |
| **公式识别** | 识别公式图像为latex源码                                                         | `UniMERNet`                  |
|    **OCR**   | 提取图像中的文本内容(包括定位和识别)                                          | `PaddleOCR`                  |
| **表格识别** | 识别表格图像为对应源码(Latex/HTML/Markdown)                                   | `PaddleOCR+TableMaster`,`StructEqTable`  |
| **阅读顺序** | 将离散的文本段落进行排序拼接                                                    |  Coming Soon !                            |



## 新闻和更新
- `2024.10.22` 🎉🎉🎉 支持LaTex和HTML等多种输出格式的表格模型[StructTable-InternVL2-1B](https://huggingface.co/U4R/StructTable-InternVL2-1B)正式接入`PDF-Extract-Kit 1.0`,请参考[表格识别算法文档](https://pdf-extract-kit.readthedocs.io/zh-cn/latest/algorithm/table_recognition.html)进行使用!
- `2024.10.17` 🎉🎉🎉 检测结果更准确,速度更快的布局检测模型`DocLayout-YOLO`正式接入`PDF-Extract-Kit 1.0`,请参考[布局检测算法文档](https://pdf-extract-kit.readthedocs.io/zh-cn/latest/algorithm/layout_detection.html)进行使用!
- `2024.10.10` 🎉🎉🎉 基于模块化重构的`PDF-Extract-Kit 1.0`正式版本正式发布,模型使用更加便捷灵活!老版本请切换至[release/0.1.1](https://github.com/opendatalab/PDF-Extract-Kit/tree/release/0.1.1)分支进行使用。
- `2024.08.01` 🎉🎉🎉 新增了[StructEqTable](demo/TabRec/StructEqTable/README_TABLE.md)表格识别模块用于表格内容提取,欢迎使用!
- `2024.07.01` 🎉🎉🎉 我们发布了`PDF-Extract-Kit`,一个用于高质量PDF内容提取的综合工具包,包括`布局检测`、`公式检测`、`公式识别`和`OCR`。



## 效果展示

当前的一些开源SOTA模型多基于学术数据集进行训练评测,仅能在单一的文档类型上获取高质量结果。为了使得模型能够在多样性文档上也能获得稳定鲁棒的高质量结果,我们构建多样性的微调数据集,并在一些SOTA模型上微调已得到可实用解析模型。下边是一些模型的可视化结果。

### 布局检测

结合多样性PDF文档标注,我们训练了鲁棒的`布局检测`模型。在论文、教材、研报、财报等多样性的PDF文档上,我们微调后的模型都能得到准确的提取结果,对于扫描模糊、水印等情况也有较高鲁棒性。下面可视化示例是经过微调后的LayoutLMv3模型的推理结果。

![](assets/readme/layout_example.png)


### 公式检测

同样的,我们收集了包含公式的中英文文档进行标注,基于先进的公式检测模型进行微调,下面可视化结果是微调后的YOLO公式检测模型的推理结果:

![](assets/readme/mfd_example.png)


### 公式识别

[UniMERNet](https://github.com/opendatalab/UniMERNet)是针对真实场景下多样性公式识别的算法,通过构建大规模训练数据及精心设计的结果,使得其可以对复杂长公式、手写公式、含噪声的截图公式均有不错的识别效果。

### 表格识别

[StructEqTable](https://github.com/UniModal4Reasoning/StructEqTable-Deploy)是一个高效表格内容提取工具,能够将表格图像转换为LaTeX/HTML/Markdown格式,最新版本使用InternVL2-1B基础模型,提高了中文识别准确度并增加了多格式输出能力。

#### 更多模型的可视化结果及推理结果可以参考[PDF-Extract-Kit教程文档](xxx)


## 评测指标

Coming Soon! 

## 使用教程

### 环境安装

```bash
conda create -n pdf-extract-kit-1.0 python=3.10
conda activate pdf-extract-kit-1.0
pip install -r requirements.txt
```
> **注意:** 如果你的设备不支持 GPU,请使用 `requirements-cpu.txt` 安装 CPU 版本的依赖。

> **注意:** 目前doclayout-yolo仅支持从pypi源安装,如果出现doclayout-yolo无法安装,请通过 `pip3 install doclayout-yolo==0.0.2 --extra-index-url=https://pypi.org/simple` 安装。

### 模型下载

参考[模型权重下载教程](https://pdf-extract-kit.readthedocs.io/zh-cn/latest/get_started/pretrained_model.html)下载所需模型权重。注:可以选择全部下载,也可以选择部分下载,具体操作参考教程。


### Demo运行

#### 布局检测模型

```bash 
python scripts/layout_detection.py --config=configs/layout_detection.yaml
```
布局检测模型支持**DocLayout-YOLO**(默认模型),YOLO-v10,以及LayoutLMv3。对于YOLO-v10和LayoutLMv3的布局检测,请参考[Layout Detection Algorithm](https://pdf-extract-kit.readthedocs.io/zh-cn/latest/algorithm/layout_detection.html)。你可以在 `outputs/layout_detection` 文件夹下查看布局检测结果。

#### 公式检测模型

```bash 
python scripts/formula_detection.py --config=configs/formula_detection.yaml
```
你可以在 `outputs/formula_detection` 文件夹下查看公式检测结果。


#### 文本识别(OCR)模型

```bash 
python scripts/ocr.py --config=configs/ocr.yaml
```
你可以在 `outputs/ocr` 文件夹下查看OCR结果。


#### 公式识别模型

```bash 
python scripts/formula_recognition.py --config=configs/formula_recognition.yaml
```
你可以在 `outputs/formula_recognition` 文件夹下查看公式识别结果。


#### 表格识别模型

```bash 
python scripts/table_parsing.py --config configs/table_parsing.yaml
```
你可以在 `outputs/table_parsing` 文件夹下查看表格内容识别结果。


> **注意:** 更多模型使用细节请查看[PDF-Extract-Kit-1.0 中文教程](https://pdf-extract-kit.readthedocs.io/zh-cn/latest/get_started/pretrained_model.html).

> 本项目专注使用模型对`多样性`文档进行`高质量`内容提取,不涉及提取后内容拼接成新文档,如PDF转Markdown。如果有此类需求,请参考我们另一个Github项目: [MinerU](https://github.com/opendatalab/MinerU)


## 待办事项

- [x] **表格解析**:开发能够将表格图像转换成对应的LaTeX/Markdown格式源码的功能。  
- [ ] **化学方程式检测**:实现对化学方程式的自动检测。  
- [ ] **化学方程式/图解识别**:开发识别并解析化学方程式的模型。  
- [ ] **阅读顺序排序模型**:构建模型以确定文档中文本的正确阅读顺序。  

**PDF-Extract-Kit** 旨在提供高质量PDF文件的提取能力。我们鼓励社区提出具体且有价值的需求,并欢迎大家共同参与,以不断改进PDF-Extract-Kit工具,推动科研及产业发展。


## 协议

本项目采用 [AGPL-3.0](LICENSE) 协议开源。

由于本项目中使用了 YOLO 代码和 PyMuPDF 进行文件处理,这些组件都需要遵循 AGPL-3.0 协议。因此,为了确保遵守这些依赖项的许可证要求,本仓库整体采用 AGPL-3.0 协议。


## 致谢

   - [LayoutLMv3](https://github.com/microsoft/unilm/tree/master/layoutlmv3): 布局检测模型
   - [UniMERNet](https://github.com/opendatalab/UniMERNet): 公式识别模型
   - [StructEqTable](https://github.com/UniModal4Reasoning/StructEqTable-Deploy): 表格识别模型
   - [YOLO](https://github.com/ultralytics/ultralytics): 公式检测模型
   - [PaddleOCR](https://github.com/PaddlePaddle/PaddleOCR): OCR模型
   - [DocLayout-YOLO](https://github.com/opendatalab/DocLayout-YOLO): 布局检测模型


## Citation

如果你觉得我们模型/代码/技术报告对你有帮助,请给我们⭐和引用📝,谢谢 :)  
```bibtex
@article{wang2024mineru,
  title={MinerU: An Open-Source Solution for Precise Document Content Extraction},
  author={Wang, Bin and Xu, Chao and Zhao, Xiaomeng and Ouyang, Linke and Wu, Fan and Zhao, Zhiyuan and Xu, Rui and Liu, Kaiwen and Qu, Yuan and Shang, Fukai and others},
  journal={arXiv preprint arXiv:2409.18839},
  year={2024}
}

@misc{wang2024unimernet,
      title={UniMERNet: A Universal Network for Real-World Mathematical Expression Recognition}, 
      author={Bin Wang and Zhuangcheng Gu and Chao Xu and Bo Zhang and Botian Shi and Conghui He},
      year={2024},
      eprint={2404.15254},
      archivePrefix={arXiv},
      primaryClass={cs.CV}
}

@misc{zhao2024doclayoutyoloenhancingdocumentlayout,
      title={DocLayout-YOLO: Enhancing Document Layout Analysis through Diverse Synthetic Data and Global-to-Local Adaptive Perception}, 
      author={Zhiyuan Zhao and Hengrui Kang and Bin Wang and Conghui He},
      year={2024},
      eprint={2410.12628},
      archivePrefix={arXiv},
      primaryClass={cs.CV},
      url={https://arxiv.org/abs/2410.12628}, 
}

@article{he2024opendatalab,
  title={Opendatalab: Empowering general artificial intelligence with open datasets},
  author={He, Conghui and Li, Wei and Jin, Zhenjiang and Xu, Chao and Wang, Bin and Lin, Dahua},
  journal={arXiv preprint arXiv:2407.13773},
  year={2024}
}
```


## Star历史

<a>
 <picture>
   <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=opendatalab/PDF-Extract-Kit&type=Date&theme=dark" />
   <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=opendatalab/PDF-Extract-Kit&type=Date" />
   <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=opendatalab/PDF-Extract-Kit&type=Date" />
 </picture>
</a>

## 友情链接
- [UniMERNet(真实场景公式识别算法)](https://github.com/opendatalab/UniMERNet)
- [LabelU(轻量级多模态标注工具)](https://github.com/opendatalab/labelU)
- [LabelLLM(开源LLM对话标注平台)](https://github.com/opendatalab/LabelLLM)
- [MinerU(一站式高质量数据提取工具)](https://github.com/opendatalab/MinerU)

================================================
FILE: configs/config.yaml
================================================
inputs: assets/demo/formula_detection_pdfs
outputs: outputs/formula_detection_pdfs
tasks:
  formula_detection:
    model: formula_detection_yolo
    model_config:
      img_size: 1280
      conf_thres: 0.25
      iou_thres: 0.45
      model_path: models/MFD/weights.pt
      visualize: True
  formula_recognition:
    model: formula_recognition_unimernet
    model_config:
      cfg_path: pdf_extract_kit/configs/unimernet.yaml
      model_path: models/MFR/UniMERNet
      visualize: True

================================================
FILE: configs/formula_detection.yaml
================================================
inputs: assets/demo/formula_detection
outputs: outputs/formula_detection
tasks:
  formula_detection:
    model: formula_detection_yolo
    model_config:
      img_size: 1280
      conf_thres: 0.25
      iou_thres: 0.45
      batch_size: 1
      model_path: models/MFD/YOLO/yolo_v8_ft.pt
      visualize: True

================================================
FILE: configs/formula_recognition.yaml
================================================
inputs: assets/demo/formula_recognition
outputs: outputs/formula_recognition
tasks:
  formula_recognition:
    model: formula_recognition_unimernet
    model_config:
      cfg_path: pdf_extract_kit/configs/unimernet.yaml
      model_path: models/MFR/unimernet_tiny
      visualize: False

================================================
FILE: configs/layout_detection.yaml
================================================
inputs: assets/demo/layout_detection
outputs: outputs/layout_detection
tasks:
  layout_detection:
    model: layout_detection_yolo
    model_config:
      img_size: 1024
      conf_thres: 0.25
      iou_thres: 0.45
      model_path: models/Layout/YOLO/doclayout_yolo_ft.pt
      visualize: True

================================================
FILE: configs/layout_detection_layoutlmv3.yaml
================================================
inputs: assets/demo/layout_detection
outputs: outputs/layout_detection
tasks:
  layout_detection:
    model: layout_detection_layoutlmv3
    model_config:
      model_path: models/Layout/LayoutLMv3/model_final.pth

================================================
FILE: configs/layout_detection_yolo.yaml
================================================
inputs: assets/demo/layout_detection
outputs: outputs/layout_detection
tasks:
  layout_detection:
    model: layout_detection_yolo
    model_config:
      img_size: 1024
      conf_thres: 0.25
      iou_thres: 0.45
      model_path: models/Layout/YOLO/doclayout_yolo_ft.pt
      visualize: True
      device: 0

================================================
FILE: configs/ocr.yaml
================================================
inputs: assets/demo/ocr
outputs: outputs/ocr
visualize: True
tasks:
  ocr:
    model: ocr_ppocr
    model_config:
      lang: ch
      show_log: True
      det_model_dir: models/OCR/PaddleOCR/det/ch_PP-OCRv4_det
      rec_model_dir: models/OCR/PaddleOCR/rec/ch_PP-OCRv4_rec
      det_db_box_thresh: 0.3

================================================
FILE: configs/table_parsing.yaml
================================================
inputs: assets/demo/table_parsing
outputs: outputs/table_parsing
tasks:
  table_parsing:
    model: table_parsing_struct_eqtable
    model_config:
      model_path: models/TabRec/StructEqTable
      max_new_tokens: 1024
      max_time: 30
      output_format: latex
      lmdeploy: False
      flash_atten: True

================================================
FILE: docs/en/.readthedocs.yaml
================================================
version: 2

build:
  os: ubuntu-22.04
  tools:
    python: "3.10"

formats:
  - epub

python:
  install:
    - requirements: requirements/docs.txt

sphinx:
  configuration: docs/en/conf.py


================================================
FILE: docs/en/Makefile
================================================
# Minimal makefile for Sphinx documentation
#

# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS    ?=
SPHINXBUILD   ?= sphinx-build
SOURCEDIR     = .
BUILDDIR      = _build

# Put it first so that "make" without argument is like "make help".
help:
	@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

.PHONY: help Makefile

# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option.  $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
	@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)


================================================
FILE: docs/en/algorithm/formula_detection.rst
================================================
..  _algorithm_formula_detection:

====================
Formula Detection Algorithm
====================

Introduction
====================

Formula detection involves identifying the positions of all formulas (including inline and block formulas) in a given input image.

.. note::

   Formula detection is technically a subtask of layout detection. However, due to its complexity, we recommend using a dedicated formula detection model to decouple it. This approach typically makes data annotation easier and improves detection performance.

Model Usage
====================

With the environment properly set up, simply run the layout detection algorithm script by executing ``scripts/formula_detection.py``.

.. code:: shell

   $ python scripts/formula_detection.py --config configs/formula_detection.yaml

Model Configuration
--------------------

.. code:: yaml

   inputs: assets/demo/formula_detection
   outputs: outputs/formula_detection
   tasks:
      formula_detection:
         model: formula_detection_yolo
         model_config:
            img_size: 1280
            conf_thres: 0.25
            iou_thres: 0.45
            batch_size: 1
            model_path: models/MFD/yolov8/weights.pt
            visualize: True

- inputs/outputs: Define the input file path and the visualization output directory, respectively.
- tasks: Define the task type, currently only a formula detection task is included.
- model: Define the specific model type: currently, only the YOLO formula detection model is available.
- model_config: Define the model configuration.
- img_size: Define the image's longer side size; the shorter side will be scaled proportionally.
- conf_thres: Define the confidence threshold; only targets above this threshold will be detected.
- iou_thres: Define the IoU threshold to remove targets with an overlap greater than this value.
- batch_size: Define the batch size; the number of images inferred simultaneously. Generally, the larger the batch size, the faster the inference speed. A better GPU allows for a larger batch size.
- model_path: Path to the model weights.
- visualize: Whether to visualize the model results. Visualized results will be saved in the outputs directory.

Diverse Input Support
--------------------

The formula detection script in PDF-Extract-Kit supports various input formats such as ``a single image``, ``a directory of image files``, ``a single PDF file``, and ``a directory of PDF files``.

.. note:: 

   Modify the ``inputs`` path in ``configs/formula_detection.yaml`` according to your actual data format:
   - Single image: path/to/image  
   - Image directory: path/to/images  
   - Single PDF file: path/to/pdf  
   - PDF directory: path/to/pdfs  

.. note::

   When using a PDF as input, you need to change ``predict_images`` to ``predict_pdfs`` in ``formula_detection.py``.

   .. code:: python

      # for image detection
      detection_results = model_formula_detection.predict_images(input_data, result_path)
   
   Change to:

   .. code:: python

      # for pdf detection
      detection_results = model_formula_detection.predict_pdfs(input_data, result_path)


Viewing Visualization Results
--------------------

When the ``visualize`` option in the config file is set to ``True``, visualization results will be saved in the ``outputs/formula_detection`` directory.

.. note::

   Visualization facilitates the analysis of model results. However, for large-scale tasks, it is recommended to disable visualization (set ``visualize`` to ``False`` ) to reduce memory and disk usage.

================================================
FILE: docs/en/algorithm/formula_recognition.rst
================================================
..  _algorithm_formula_recognition:

============
Formula Recognition Algorithm
============

Introduction
=================

Formula detection involves recognizing the content of a given input formula image and converting it to ``LaTeX`` format.

Model Usage
=================

With the environment properly configured, you can run the layout detection algorithm script by executing ``scripts/formula_recognition.py``.

.. code:: shell

   $ python scripts/formula_recognition.py --config configs/formula_recognition.yaml

Model Configuration
-----------------

.. code:: yaml

   inputs: assets/demo/formula_recognition
   outputs: outputs/formula_recognition
   tasks:
      formula_recognition:
         model: formula_recognition_unimernet
         model_config:
            cfg_path: pdf_extract_kit/configs/unimernet.yaml
            model_path: models/MFR/unimernet_tiny
            visualize: False

- inputs/outputs: Define the input file path and the directory for LaTeX prediction results, respectively.
- tasks: Define the task type, currently only containing a formula recognition task.
- model: Define the specific model type: Currently, only the `UniMERNet <https://github.com/opendatalab/UniMERNet>`_ formula recognition model is provided.
- model_config: Define the model configuration.
- cfg_path: Path to the UniMERNet configuration file.
- model_path: Path to the model weights.
- visualize: Whether to visualize the model results. Visualized results will be saved in the outputs directory.

Support for Diverse Inputs
-----------------

The formula detection script in PDF-Extract-Kit supports ``single formula images`` and ``document images with corresponding formula regions``.

Viewing Visualization Results
-----------------

When the visualize setting in the config file is set to True, ``LaTeX`` prediction results will be saved in the outputs directory.

================================================
FILE: docs/en/algorithm/layout_detection.rst
================================================
.. _algorithm_layout_detection:

=================
Layout Detection Algorithm
=================

Introduction
=================

Layout detection is a fundamental task in document content extraction, aiming to locate different types of regions on a page, such as images, tables, text, and headings, to facilitate high-quality content extraction. For text and heading regions, OCR models can be used for text recognition, while table regions can be converted using table recognition models.

Model Usage
=================

Layout detection supports following models:

.. raw:: html

    <style type="text/css">
    .tg  {border-collapse:collapse;border-color:#9ABAD9;border-spacing:0;}
    .tg td{background-color:#EBF5FF;border-color:#9ABAD9;border-style:solid;border-width:1px;color:#444;
      font-family:Arial, sans-serif;font-size:14px;overflow:hidden;padding:10px 5px;word-break:normal;}
    .tg th{background-color:#409cff;border-color:#9ABAD9;border-style:solid;border-width:1px;color:#fff;
      font-family:Arial, sans-serif;font-size:14px;font-weight:normal;overflow:hidden;padding:10px 5px;word-break:normal;}
    .tg .tg-f8tz{background-color:#409cff;border-color:inherit;text-align:left;vertical-align:top}
    .tg .tg-0lax{text-align:left;vertical-align:top}
    .tg .tg-0pky{border-color:inherit;text-align:left;vertical-align:top}
    </style>
    <table class="tg"><thead>
      <tr>
        <th class="tg-0lax">Model</th>
        <th class="tg-f8tz">Description</th>
        <th class="tg-f8tz">Characteristics</th>
        <th class="tg-f8tz">Model weight</th>
        <th class="tg-f8tz">Config file</th>
      </tr></thead>
    <tbody>
      <tr>
        <td class="tg-0lax">DocLayout-YOLO</td>
        <td class="tg-0pky">Improved based on YOLO-v10:<br>1. Generate diverse pre-training data,enhance generalization ability across multiple document types<br>2. Model architecture improvement, improve perception ability on scale-varing instances<br>Details in <a href="https://github.com/opendatalab/DocLayout-YOLO" target="_blank" rel="noopener noreferrer">DocLayout-YOLO</a></td>
        <td class="tg-0pky">Speed:Fast, Accuracy:High</td>
        <td class="tg-0pky"><a href="https://huggingface.co/opendatalab/PDF-Extract-Kit-1.0/blob/main/models/Layout/YOLO/doclayout_yolo_ft.pt" target="_blank" rel="noopener noreferrer">doclayout_yolo_ft.pt</a></td>
        <td class="tg-0pky">layout_detection.yaml</td>
      </tr>
      <tr>
        <td class="tg-0lax">YOLO-v10</td>
        <td class="tg-0pky">Base YOLO-v10 model</td>
        <td class="tg-0pky">Speed:Fast, Accuracy:Moderate</td>
        <td class="tg-0pky"><a href="https://huggingface.co/opendatalab/PDF-Extract-Kit-1.0/blob/main/models/Layout/YOLO/yolov10l_ft.pt" target="_blank" rel="noopener noreferrer">yolov10l_ft.pt</a></td>
        <td class="tg-0pky">layout_detection_yolo.yaml</td>
      </tr>
      <tr>
        <td class="tg-0lax">LayoutLMv3</td>
        <td class="tg-0pky">Base LayoutLMv3 model</td>
        <td class="tg-0pky">Speed:Slow, Accuracy:High</td>
        <td class="tg-0pky"><a href="https://huggingface.co/opendatalab/PDF-Extract-Kit-1.0/tree/main/models/Layout/LayoutLMv3" target="_blank" rel="noopener noreferrer">layoutlmv3_ft</a></td>
        <td class="tg-0pky">layout_detection_layoutlmv3.yaml</td>
      </tr>
    </tbody></table>

Once enciroment is setup, you can perform layout detection by executing ``scripts/layout_detection.py`` directly.

**Run demo**

.. code:: shell

   $ python scripts/layout_detection.py --config configs/layout_detection.yaml

Model Configuration
-----------------

**1. DocLayout-YOLO / YOLO-v10**

.. code:: yaml

    inputs: assets/demo/layout_detection
    outputs: outputs/layout_detection
    tasks:
      layout_detection:
        model: layout_detection_yolo
        model_config:
          img_size: 1024
          conf_thres: 0.25
          iou_thres: 0.45
          model_path: path/to/doclayout_yolo_model
          visualize: True

- inputs/outputs: Define the input file path and the directory for visualization output.
- tasks: Define the task type, currently only a layout detection task is included.
- model: Specify the specific model type, e.g., layout_detection_yolo.
- model_config: Define the model configuration.
- img_size: Define the image long edge size; the short edge will be scaled proportionally based on the long edge, with the default long edge being 1024.
- conf_thres: Define the confidence threshold, detecting only targets above this threshold.
- iou_thres: Define the IoU threshold, removing targets with an overlap greater than this threshold.
- model_path: Path to the model weights.
- visualize: Whether to visualize the model results; visualized results will be saved in the outputs directory.


**2. layoutlmv3**

.. note::
   
   LayoutLMv3 cannot run directly by default. Please follow the steps below to modify the configuration:

   1. **Detectron2 Environment Setup**

   .. code-block:: bash

      # For Linux
      pip install https://wheels-1251341229.cos.ap-shanghai.myqcloud.com/assets/whl/detectron2/detectron2-0.6-cp310-cp310-linux_x86_64.whl

      # For macOS
      pip install https://wheels-1251341229.cos.ap-shanghai.myqcloud.com/assets/whl/detectron2/detectron2-0.6-cp310-cp310-macosx_10_9_universal2.whl

      # For Windows
      pip install https://wheels-1251341229.cos.ap-shanghai.myqcloud.com/assets/whl/detectron2/detectron2-0.6-cp310-cp310-win_amd64.whl

   2. **Enable LayoutLMv3 Registration Code**

   Uncomment the lines at the following links:
   
   - `line 2 <https://github.com/opendatalab/PDF-Extract-Kit/blob/main/pdf_extract_kit/tasks/layout_detection/__init__.py#L2>`_
   - `line 8 <https://github.com/opendatalab/PDF-Extract-Kit/blob/main/pdf_extract_kit/tasks/layout_detection/__init__.py#L8>`_

   .. code-block:: python

      from pdf_extract_kit.tasks.layout_detection.models.yolo import LayoutDetectionYOLO
      from pdf_extract_kit.tasks.layout_detection.models.layoutlmv3 import LayoutDetectionLayoutlmv3
      from pdf_extract_kit.registry.registry import MODEL_REGISTRY

      __all__ = [
         "LayoutDetectionYOLO",
         "LayoutDetectionLayoutlmv3",
      ]


.. code:: yaml

    inputs: assets/demo/layout_detection
    outputs: outputs/layout_detection
    tasks:
      layout_detection:
        model: layout_detection_layoutlmv3
        model_config:
          model_path: path/to/layoutlmv3_model

- inputs/outputs: Define the input file path and the directory for visualization output.
- tasks: Define the task type, currently only a layout detection task is included.
- model: Specify the specific model type, e.g., layout_detection_layoutlmv3.
- model_config: Define the model configuration.
- model_path: Path to the model weights.



Diverse Input Support
-----------------

The layout detection script in PDF-Extract-Kit supports input formats such as a ``single image``, a ``directory containing only image files``, a ``single PDF file``, and a ``directory containing only PDF files``.

.. note::

   Modify the path to inputs in configs/layout_detection.yaml according to your actual data format:
   - Single image: path/to/image  
   - Image directory: path/to/images  
   - Single PDF file: path/to/pdf  
   - PDF directory: path/to/pdfs  

.. note::
   When using PDF as input, you need to change ``predict_images`` to ``predict_pdfs`` in ``layout_detection.py``.

   .. code:: python

      # for image detection
      detection_results = model_layout_detection.predict_images(input_data, result_path)

   Change to:

   .. code:: python

      # for pdf detection
      detection_results = model_layout_detection.predict_pdfs(input_data, result_path)

Viewing Visualization Results
-----------------

When ``visualize`` is set to ``True`` in the config file, the visualization results will be saved in the ``outputs`` directory.

.. note::

   Visualization is helpful for analyzing model results, but for large-scale tasks, it is recommended to turn off visualization (set ``visualize`` to ``False`` ) to reduce memory and disk usage.

================================================
FILE: docs/en/algorithm/ocr.rst
================================================
..  _algorithm_ocr:
==========================
OCR (Optical Character Recognition) Algorithm
==========================

Introduction
====================

OCR(Optical Character Recognition) involves identifying the positions ajnd contents of all text blocks in pictures.


Model Usage
====================

With the environment properly set up, simply run the ocr algorithm script by executing ``scripts/ocr.py`` .

.. code:: shell

   $ python scripts/ocr.py --config configs/ocr.yaml


Model Configuration
--------------------

.. code:: yaml

   inputs: assets/demo/ocr
   outputs: outputs/ocr
   visualize: True
   tasks:
      ocr:
         model: ocr_ppocr
         model_config:
            lang: ch
            show_log: True
            det_model_dir: models/OCR/PaddleOCR/det/ch_PP-OCRv4_det
            rec_model_dir: models/OCR/PaddleOCR/rec/ch_PP-OCRv4_rec
            det_db_box_thresh: 0.3

- inputs/outputs: Define the input path and the output path, respectively.
- visualize: Whether to visualize the model results. Visualized results will be saved in the outputs directory.
- tasks: Define the task type, currently only a OCR task is included.
- model: Define the specific model type, currently, only the PaddleOCR model is available.
- model_config: Define the model configuration.
- lang: Define the language, default language ch supports both english and chinese.
- show_log: Whether to print running logs.
- det_model_dir: Define the path of PaddleOCR' detection model, If the specified path does not exist, the model weight will be automatically downloaded to the path.
- rec_model_dir: Define the path of PaddleOCR' recognize model, If the specified path does not exist, the model weight will be automatically downloaded to the path.
- det_db_box_thresh: Confidence filter threshold, bounding boxes whose confidence is lower than the threshold are discarded.


Diverse Input Support
--------------------

The OCR script in PDF-Extract-Kit supports various input formats such as ``a single image/PDF``, ``a directory of image/PDF files``.


Viewing Visualization Results
--------------------

When the ``visualize`` option in the config file is set to ``True``, visualization results will be saved in the ``outputs`` directory.

.. note::

   Visualization facilitates the analysis of model results. However, for large-scale tasks, it is recommended to disable visualization (set ``visualize`` to ``False`` ) to reduce memory and disk usage.

================================================
FILE: docs/en/algorithm/reading_order.rst
================================================
..  _algorithm_reading_oder:
==============
Reading Order Algorithm
==============

Comming soon.

================================================
FILE: docs/en/algorithm/table_recognition.rst
================================================
..  _algorithm_table_recognition:

========================
Table Recognition Algorithm
========================

Introduction
=================

Table recognition refers to the process of inputting a table image, identifying the table structure and content, and converting it into formats such as ``LaTeX`` or ``HTML``.

Model Usage
=================

With the environment properly configured, you can run the table recognition algorithm script by directly executing ``scripts/table_parsing.py``.

.. code:: shell

   $ python scripts/table_parsing.py --config configs/table_parsing.yaml

Model Configuration
-----------------

.. code:: yaml

    inputs: assets/demo/table_parsing
    outputs: outputs/table_parsing
    tasks:
      table_parsing:
        model: table_parsing_struct_eqtable
        model_config:
          model_path: models/TabRec/StructEqTable
          max_new_tokens: 1024
          max_time: 30
          output_format: latex
          lmdeploy: False
          flash_attn: True

- inputs/outputs: Define the input file path and table recognition result directory respectively
- tasks: Define the task type, currently only including one table recognition task
- model: Define the specific model type: currently using the `StructEqTable <https://github.com/UniModal4Reasoning/StructEqTable-Deploy>`_ table recognition model
- model_config: Define the model configuration
- model_path: Path to the model weights
- max_new_tokens: Maximum number of tokens to generate, default is 1024, maximum supported is 4096
- max_time: Maximum runtime for the model (in seconds)
- output_format: Output format, default is set to ``latex``, options include ``html`` and ``markdown``
- lmdeploy: Whether to use LMDeploy for deployment, currently set to False
- flash_attn: Whether to use flash attention, only available for Ampere GPUs

Diverse Input Support
-----------------

The table recognition script in PDF-Extract-Kit supports ``single table images`` and ``multiple table images`` as input.

.. note::

   The StructEqTable model only supports running on GPU devices

.. note::
    
    Adjust ``max_new_tokens`` and ``max_time`` according to the table content, defaults are 1024 and 30 respectively.

.. note::
    
    lmdeploy is an option for accelerated inference. If set to True, it will use LMDeploy for accelerated inference deployment.
    To use LMDeploy deployment, you need to install LMDeploy. For installation methods, refer to `LMDeploy <https://github.com/InternLM/lmdeploy>`_.

================================================
FILE: docs/en/conf copy.py
================================================
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html

# -- Path setup --------------------------------------------------------------

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.

import os
import subprocess
import sys

# def install(package):
#     subprocess.check_call([sys.executable, "-m", "pip", "install", package])

# # 安装 requirements.txt 中的依赖项
# requirements_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'requirements.txt'))
# if os.path.exists(requirements_path):
#     with open(requirements_path) as f:
#         packages = f.readlines()
#     for package in packages:
#         install(package.strip())

from sphinx.ext import autodoc

sys.path.insert(0, os.path.abspath('../..'))

# -- Project information -----------------------------------------------------

project = 'PDF-Extract-Kit'
copyright = '2024, OpenDataLab'
author = 'PDF-Extract-Kit Contributors'

# The full version, including alpha/beta/rc tags
version_file = '../../pdf_extract_kit/version.py'
with open(version_file) as f:
    exec(compile(f.read(), version_file, 'exec'))
__version__ = locals()['__version__']
# The short X.Y version
version = __version__
# The full version, including alpha/beta/rc tags
release = __version__

# -- General configuration ---------------------------------------------------

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    'sphinx.ext.napoleon',
    'sphinx.ext.viewcode',
    'sphinx.ext.intersphinx',
    'sphinx_copybutton',
    'sphinx.ext.autodoc',
    'sphinx.ext.autosummary',
    'myst_parser',
    'sphinxarg.ext',
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']

# Exclude the prompt "$" when copying code
copybutton_prompt_text = r'\$ '
copybutton_prompt_is_regexp = True

language = 'zh_CN'

# -- Options for HTML output -------------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_book_theme'
html_logo = '_static/image/logo.png'
html_theme_options = {
    'path_to_docs': 'docs/zh_cn',
    'repository_url': 'https://github.com/opendatalab/PDF-Extract-Kit',
    'use_repository_button': True,
}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# html_static_path = ['_static']

# Mock out external dependencies here.
autodoc_mock_imports = [
    'cpuinfo',
    'torch',
    'transformers',
    'psutil',
    'prometheus_client',
    'sentencepiece',
    'vllm.cuda_utils',
    'vllm._C',
    'numpy',
    'tqdm',
]


class MockedClassDocumenter(autodoc.ClassDocumenter):
    """Remove note about base class when a class is derived from object."""

    def add_line(self, line: str, source: str, *lineno: int) -> None:
        if line == '   Bases: :py:class:`object`':
            return
        super().add_line(line, source, *lineno)


autodoc.ClassDocumenter = MockedClassDocumenter

navigation_with_keys = False


================================================
FILE: docs/en/conf.bak
================================================
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html

# -- Path setup --------------------------------------------------------------

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.

import os
import sys

from sphinx.ext import autodoc

sys.path.insert(0, os.path.abspath('../..'))

# -- Project information -----------------------------------------------------

project = 'PDF-Extract-Kit'
copyright = '2024, PDF-Extract-Kit Contributors'
author = 'PDF-Extract-Kit Contributors'

# The full version, including alpha/beta/rc tags
version_file = '../../pdf_extract_kit/version.py'
with open(version_file) as f:
    exec(compile(f.read(), version_file, 'exec'))
__version__ = locals()['__version__']
# The short X.Y version
version = __version__
# The full version, including alpha/beta/rc tags
release = __version__

# -- General configuration ---------------------------------------------------

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    'sphinx.ext.napoleon',
    'sphinx.ext.viewcode',
    'sphinx.ext.intersphinx',
    'sphinx_copybutton',
    'sphinx.ext.autodoc',
    'sphinx.ext.autosummary',
    'myst_parser',
    'sphinxarg.ext',
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']

# Exclude the prompt "$" when copying code
copybutton_prompt_text = r'\$ '
copybutton_prompt_is_regexp = True

language = 'en'

# -- Options for HTML output -------------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_book_theme'
html_logo = '_static/image/logo.png'
html_theme_options = {
    'path_to_docs': 'docs/en',
    'repository_url': 'https://github.com/opendatalab/PDF-Extract-Kit',
    'use_repository_button': True,
}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# html_static_path = ['_static']

# Mock out external dependencies here.
autodoc_mock_imports = [
    'cpuinfo',
    'torch',
    'transformers',
    'psutil',
    'prometheus_client',
    'sentencepiece',
    'vllm.cuda_utils',
    'vllm._C',
    'numpy',
    'tqdm',
]


class MockedClassDocumenter(autodoc.ClassDocumenter):
    """Remove note about base class when a class is derived from object."""

    def add_line(self, line: str, source: str, *lineno: int) -> None:
        if line == '   Bases: :py:class:`object`':
            return
        super().add_line(line, source, *lineno)


autodoc.ClassDocumenter = MockedClassDocumenter

navigation_with_keys = False


================================================
FILE: docs/en/conf.py
================================================
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html

# -- Path setup --------------------------------------------------------------

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.

import os
import subprocess
import sys

def install(package):
    subprocess.check_call([sys.executable, "-m", "pip", "install", package])

# 安装 requirements.txt 中的依赖项
requirements_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'requirements.txt'))
if os.path.exists(requirements_path):
    with open(requirements_path) as f:
        packages = f.readlines()
    for package in packages:
        install(package.strip())
        
from sphinx.ext import autodoc
sys.path.insert(0, os.path.abspath('../..'))

# -- Project information -----------------------------------------------------

project = 'PDF-Extract-Kit'
copyright = '2024, PDF-Extract-Kit Contributors'
author = 'OpenDataLab'

# The full version, including alpha/beta/rc tags
version_file = '../../pdf_extract_kit/version.py'
with open(version_file) as f:
    exec(compile(f.read(), version_file, 'exec'))
__version__ = locals()['__version__']
# The short X.Y version
version = __version__
# The full version, including alpha/beta/rc tags
release = __version__

# -- General configuration ---------------------------------------------------

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    'sphinx.ext.napoleon',
    'sphinx.ext.viewcode',
    'sphinx.ext.intersphinx',
    'sphinx_copybutton',
    'sphinx.ext.autodoc',
    'sphinx.ext.autosummary',
    'myst_parser',
    'sphinxarg.ext',
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']

# Exclude the prompt "$" when copying code
copybutton_prompt_text = r'\$ '
copybutton_prompt_is_regexp = True

language = 'en'

# -- Options for HTML output -------------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_book_theme'
html_logo = '_static/image/logo.png'
html_theme_options = {
    'path_to_docs': 'docs/en',
    'repository_url': 'https://github.com/opendatalab/PDF-Extract-Kit',
    'use_repository_button': True,
}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# html_static_path = ['_static']

# Mock out external dependencies here.
autodoc_mock_imports = [
    'cpuinfo',
    'torch',
    'transformers',
    'psutil',
    'prometheus_client',
    'sentencepiece',
    'vllm.cuda_utils',
    'vllm._C',
    'numpy',
    'tqdm',
]


class MockedClassDocumenter(autodoc.ClassDocumenter):
    """Remove note about base class when a class is derived from object."""

    def add_line(self, line: str, source: str, *lineno: int) -> None:
        if line == '   Bases: :py:class:`object`':
            return
        super().add_line(line, source, *lineno)


autodoc.ClassDocumenter = MockedClassDocumenter

navigation_with_keys = False

================================================
FILE: docs/en/evaluation/formula_detection.rst
================================================
=====================
Formula Detection Evaluation
=====================

XXX

================================================
FILE: docs/en/evaluation/formula_recognition.rst
================================================
=====================
Formula Recognition Evaluation
=====================

XXX

================================================
FILE: docs/en/evaluation/layout_detection.rst
================================================
=====================
Layout Detection Evaluation
=====================

XXX

================================================
FILE: docs/en/evaluation/ocr.rst
================================================
=====================
OCR Evaluation
=====================

XXX

================================================
FILE: docs/en/evaluation/pdf_extract.rst
================================================
=====================
PDF Content Extraction Evaluation [End-to-End]
=====================

XXX

================================================
FILE: docs/en/evaluation/reading_order.rst
================================================
=====================
Reading Order Evaluation
=====================

XXX

================================================
FILE: docs/en/evaluation/table_recognition.rst
================================================
=====================
Table Recognition Evaluation
=====================

XXX


================================================
FILE: docs/en/get_started/installation.rst
================================================
==================================
Installation
==================================

In this section, we will demonstrate how to install PDF-Extract-Kit.

Best Practices
==============

We recommend users follow our best practices for installing PDF-Extract-Kit. It is recommended to use a Python 3.10 conda virtual environment for the installation.

**Step 1.** Create a Python 3.10 virtual environment using conda.

.. code-block:: console

    $ conda create -n pdf-extract-kit-1.0 python=3.10 -y
    $ conda activate pdf-extract-kit-1.0

**Step 2.** Install the dependencies for PDF-Extract-Kit.

.. code-block:: console

    $ # For GPU devices
    $ pip install -r requirements.txt
    $ # For CPU-only devices
    $ pip install -r requirements-cpu.txt

.. note::

    For the convenience of user environment configuration, requirements.txt only includes the environment needed for the current best models, which currently include:
   
    - Layout Detection: YOLO series (YOLOv10, DocLayout-YOLO)  
    - Formula Detection: YOLO series (YOLOv8)  
    - Formula Recognition: UniMERNet  
    - OCR: PaddleOCR  

    For other models, such as LayoutLMv3, additional environment setup is required. For details, see \ :ref:`Layout Detection Algorithms <algorithm_layout_detection>`.

================================================
FILE: docs/en/get_started/pretrained_model.rst
================================================
==================================
Model Weights Download
==================================

Before using the PDF-Extract-Kit, we need to download the required model weights. You can download all models or specific model files (e.g., formula detection MFD) according to your needs.

[Recommended] Method 1: ``snapshot_download``
========================================

HuggingFace
------------

``huggingface_hub.snapshot_download`` supports downloading specific model weights from the HuggingFace Hub and allows multithreading. You can use the following code to download model weights in parallel:

.. code:: python

   from huggingface_hub import snapshot_download

   snapshot_download(repo_id='opendatalab/pdf-extract-kit-1.0', local_dir='./', max_workers=20)

If you want to download a single algorithm model (e.g., the YOLO model for the formula detection task), use the following code:

.. code:: python

   from huggingface_hub import snapshot_download

   snapshot_download(repo_id='opendatalab/pdf-extract-kit-1.0', local_dir='./', allow_patterns='models/MFD/YOLO/*') 

.. note::

   Here, ``repo_id`` represents the name of the model on HuggingFace Hub, ``local_dir`` indicates the desired local storage path, ``max_workers`` specifies the maximum number of parallel downloads, and ``allow_patterns`` specifies the files you want to download.

.. tip::

   If ``local_dir`` is not specified, it will be downloaded to the default cache path of HuggingFace (``~/.cache/huggingface/hub``). To change the default cache path, modify the relevant environment variables:

   .. code:: console

      $ # Default is `~/.cache/huggingface/`
      $ export HF_HOME=Comming soon!

.. tip::
   
   If the download speed is slow (e.g., unable to reach maximum bandwidth), try setting ``export HF_HUB_ENABLE_HF_TRANSFER=1`` for higher download speeds.

ModelScope
-----------

``modelscope.snapshot_download`` supports downloading specified model weights. You can use the following command to download the model:

.. code:: python

   from modelscope import snapshot_download

   snapshot_download(model_id='opendatalab/pdf-extract-kit-1.0', cache_dir='./')

If you want to download a single algorithm model (e.g., the YOLO model for the formula detection task), use the following code:

.. code:: python

   from modelscope import snapshot_download

   snapshot_download(repo_id='opendatalab/pdf-extract-kit-1.0', local_dir='./', allow_patterns='models/MFD/YOLO/*') 


.. note::
   Here, ``model_id`` represents the name of the model in the ModelScope library, ``cache_dir`` indicates the desired local storage path, and ``allow_patterns`` specifies the files you want to download.

.. note::
   ``modelscope.snapshot_download`` does not support multithreaded parallel downloads.

.. tip::

   If ``cache_dir`` is not specified, it will be downloaded to the default cache path of ModelScope (``~/.cache/huggingface/hub``).

   To change the default cache path, modify the relevant environment variables:

   .. code:: console

      $ # Default is ~/.cache/modelscope/hub/
      $ export MODELSCOPE_CACHE=XXXX



Method 2: Git LFS
===================

The remote model repositories of HuggingFace and ModelScope are Git repositories managed by Git LFS. Therefore, we can use ``git clone`` to download the weights:

.. code:: console

   $ git lfs install
   $ # From HuggingFace
   $ git lfs clone https://huggingface.co/opendatalab/pdf-extract-kit-1.0
   $ # From ModelScope
   $ git clone https://www.modelscope.cn/opendatalab/pdf-extract-kit-1.0.git

================================================
FILE: docs/en/get_started/quickstart.rst
================================================
==================================
Quick Start
==================================

Once the PDF-Extract-Kit environment is set up and the models are downloaded, we can start using PDF-Extract-Kit.

Layout Detection Example
==============

Layout detection offers several models: ``LayoutLMv3``, ``YOLOv10``, and ``DocLayout-YOLO``. Compared to ``LayoutLMv3``, ``YOLOv10`` is faster. ``DocLayout-YOLO`` is based on YOLOv10 and includes diverse document pre-training and model optimization, offering both speed and high accuracy.

**1. Using Layout Detection Models**

.. code-block:: console

    $ python scripts/layout_detection.py --config configs/layout_detection.yaml

After execution, we can view the detection results in the `outputs/layout_detection` directory.

.. note::   

    The ``layout_detection.yaml`` file sets the input, output, and model configuration. For a more detailed tutorial on layout detection, see :ref:`Layout Detection Algorithm <algorithm_layout_detection>`.

Formula Detection Example
==============

.. code-block:: console

    $ python scripts/formula_detection.py --config configs/formula_detection.yaml

After execution, we can view the detection results in the `outputs/formula_detection` directory.

.. note::   

    The ``formula_detection.yaml`` file sets the input, output, and model configuration. For a more detailed tutorial on formula detection, see :ref:`Formula Detection Algorithm <algorithm_formula_detection>`.

================================================
FILE: docs/en/index.rst
================================================
.. xtuner documentation master file, created by
   sphinx-quickstart on Tue Jan  9 16:33:06 2024.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to the PDF-Extract-Kit Documentation
==============================================

.. figure:: ./_static/image/logo.png
  :align: center
  :alt: pdf-extract-kit
  :class: no-scaled-link

.. raw:: html

   <p style="text-align:center">
   <strong>High-Quality Document Parsing Toolkit
   </strong>
   </p>

   <p style="text-align:center">
   <script async defer src="https://buttons.github.io/buttons.js"></script>
   <a class="github-button" href="https://github.com/opendatalab/PDF-Extract-Kit" data-show-count="true" data-size="large" aria-label="Star">Star</a>
   <a class="github-button" href="https://github.com/opendatalab/PDF-Extract-Kit/subscription" data-icon="octicon-eye" data-size="large" aria-label="Watch">Watch</a>
   <a class="github-button" href="https://github.com/opendatalab/PDF-Extract-Kit/fork" data-icon="octicon-repo-forked" data-size="large" aria-label="Fork">Fork</a>
   </p>


Tutorial
-------------
.. toctree::
   :maxdepth: 2
   :caption: Getting Started

   get_started/installation.rst
   get_started/pretrained_model.rst
   get_started/quickstart.rst

.. toctree::
   :maxdepth: 2
   :caption: Core Algorithm Modules

   algorithm/layout_detection.rst
   algorithm/formula_detection.rst
   algorithm/formula_recognition.rst
   algorithm/ocr.rst
   algorithm/table_recognition.rst
   algorithm/reading_order.rst

.. toctree::
   :maxdepth: 2
   :caption: Task Extensions

   task_extend/code.rst
   task_extend/doc.rst
   task_extend/evaluation.rst

.. toctree::
   :maxdepth: 2
   :caption: Supported Models

   models/supported.md


.. toctree::
   :maxdepth: 2
   :caption: Model Performance Evaluation

   evaluation/layout_detection.rst
   evaluation/formula_detection.rst
   evaluation/formula_recognition.rst
   evaluation/ocr.rst
   evaluation/table_recognition.rst
   evaluation/reading_order.rst
   evaluation/pdf_extract.rst

.. toctree::
   :maxdepth: 2
   :caption: PDF Projects

   project/pdf_extract.md
   project/doc_translate.md
   project/speed_up.md

================================================
FILE: docs/en/make.bat
================================================
@ECHO OFF

pushd %~dp0

REM Command file for Sphinx documentation

if "%SPHINXBUILD%" == "" (
	set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=.
set BUILDDIR=_build

%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
	echo.
	echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
	echo.installed, then set the SPHINXBUILD environment variable to point
	echo.to the full path of the 'sphinx-build' executable. Alternatively you
	echo.may add the Sphinx directory to PATH.
	echo.
	echo.If you don't have Sphinx installed, grab it from
	echo.https://www.sphinx-doc.org/
	exit /b 1
)

if "%1" == "" goto help

%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
goto end

:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%

:end
popd


================================================
FILE: docs/en/models/supported.md
================================================
# The Supported Models



================================================
FILE: docs/en/notes/changelog.md
================================================
<!--

## vX.X.X (YYYY.MM.DD)

### 亮点

### 新功能和改进

### Bug 修复

### 贡献者

-->

# Changelog

## v1.0.0 (2024-10-10)

The PDF-Extract-Kit-1.0 has been refactored with a more streamlined and user-friendly modular design! 🔥🔥🔥

## v0.1.0 (2024-07-01)

Official release of PDF-Extract-Kit! 🔥🔥🔥

### Highlights

- PDF-Extract-Kit-1.0 offers a high-quality layout detection model, DocLayout-YOLO.

================================================
FILE: docs/en/project/doc_translate.rst
================================================
=================
Document Translation Project
=================

XXXX
XXXX

================================================
FILE: docs/en/project/pdf_extract.rst
================================================
=================
Document Content Extraction Project
=================

Introduction
====================

Document content extraction aiming to extract all information of document file and convert it to computer readable result(such as markdown file). It's subtasks including layout detection, formula detection, formula recognition, OCR and other tasks.


Project Usage
====================

With the environment properly set up, simply run the project by executing ``project/pdf2markdown/scripts/run_project.py`` .

.. code:: shell

   $ python project/pdf2markdown/scripts/run_project.py --config project/pdf2markdown/configs/pdf2markdown.yaml


Project Configuration
--------------------

.. code:: yaml

    inputs: assets/demo/formula_detection
    outputs: outputs/pdf2markdown
    visualize: True
    merge2markdown: True
    tasks:
        layout_detection:
            model: layout_detection_yolo
            model_config:
                img_size: 1024
                conf_thres: 0.25
                iou_thres: 0.45
                model_path: models/Layout/YOLO/doclayout_yolo_ft.pt
        formula_detection:
            model: formula_detection_yolo
            model_config:
                img_size: 1280
                conf_thres: 0.25
                iou_thres: 0.45
                batch_size: 1
                model_path: models/MFD/YOLO/yolo_v8_ft.pt
        formula_recognition:
            model: formula_recognition_unimernet
            model_config:
                batch_size: 128
                cfg_path: pdf_extract_kit/configs/unimernet.yaml
                model_path: models/MFR/unimernet_tiny
        ocr:
            model: ocr_ppocr
            model_config:
                lang: ch
                show_log: True
                det_model_dir: models/OCR/PaddleOCR/det/ch_PP-OCRv4_det
                rec_model_dir: models/OCR/PaddleOCR/rec/ch_PP-OCRv4_rec
                det_db_box_thresh: 0.3

- inputs/outputs: Define the input path and the output path, respectively.
- visualize: Whether to visualize the project results. Visualized results will be saved in the outputs directory.
- merge2markdown: Whether to merge the results into markdown documents. Only simple single-column text is supported. For markdown conversion of more complex layout documents, please refer to `MinerU <https://github.com/opendatalab/MinerU>`_ .
- tasks: Define the task types, PDF document extraction includes layout detection, formula detection, formula recognition, and OCR tasks.
- For details about the parameter meanings of each task and model, see the tutorial documentation of each task.


Diverse Input Support
--------------------

The Document content extraction script in PDF-Extract-Kit supports various input formats such as ``a single image/PDF``, ``a directory of image/PDF files``.


Output result
--------------------

The extracted results of PDF documents are stored in the outputs path in the form of json. The format of json is as follows:

.. code:: json

    [
        {
            "layout_dets": [
                {
                    "category_type": "text",
                    "poly": [
                        380.6792698635707,
                        159.85058512958923,
                        765.1419999999998,
                        159.85058512958923,
                        765.1419999999998,
                        192.51073013642917,
                        380.6792698635707,
                        192.51073013642917
                    ],
                    "text": "this is an example text",
                    "score": 0.97
                },
                ...
            ], 
            "page_info": {
                "page_no": 0,
                "height": 2339,
                "width": 1654,
            }
        },
        ...
    ]

- layout_dets: Single page of PDF or image content extraction results
- category_type: The attribution of a single piece of content, such as headings, images, inline formulas, and so on
- poly: The location coordinates of a single content block
- text: Text content of a single content block
- score: Confidence score
- page_info: Page information, including page number and page size
- page_no: Page number, counting from 0
- height: Page size: height
- width: Page size: width

If the ``merge2markdown`` parameter is True, an additional markdown file will be saved.

================================================
FILE: docs/en/project/speed_up.rst
================================================
=================
Model Acceleration Project
=================

XXXX
XXXX

================================================
FILE: docs/en/switch_language.md
================================================
## <a href='https://pdf-extract-kit.readthedocs.io/en/latest/'>English</a>

## <a href='https://pdf-extract-kit.readthedocs.io/zh_CN/latest/'>简体中文</a>


================================================
FILE: docs/en/task_extend/code.rst
================================================
==================================
Code Implementation
==================================

The core code of the PDF-Extract-Kit project is implemented in the `pdf_extract_kit` directory, which contains the following modules:

- configs: Configuration files for specific modules, such as `pdf_extract_kit/configs/unimernet.yaml`. If the configuration is simple, it is recommended to define it in the `yaml` file's `model_config` in `repo_root/configs` for easier user modification.

- dataset: A custom `ImageDataset` class used for loading and preprocessing image data. It supports various input types and can perform unified preprocessing operations on images (such as resizing, converting to tensors, etc.) to accelerate subsequent model inference.

- evaluation: A module for evaluating model results, supporting evaluations for various task types such as `layout detection`, `formula detection`, `formula recognition`, etc., allowing users to fairly compare different tasks and models.

- registry: The `Registry` class is a generic registry class that provides functions for registering, retrieving, and listing registered items. Users can use this class to create different types of registries, such as task registries, model registries, etc.

- tasks: The core task module contains many different types of tasks, such as `layout detection`, `formula detection`, `formula recognition`, etc. Users typically only need to add code here to add new tasks and models.

.. note::
    Based on the above modular design, users generally only need to implement their new task class and corresponding model in `tasks` to extend new modules (in most cases, only the corresponding model needs to be implemented, as the task is already defined), and then register it in `registry`.

Below we take adding a YOLO-based `layout detection` model as an example to introduce how to add new tasks and models.

Task Definition and Registration
==============

First, we add a `layout_detection` directory under `tasks`, and then add a `task.py` file in that directory to define the layout detection task class, as follows:

.. code-block:: python

    from pdf_extract_kit.registry.registry import TASK_REGISTRY
    from pdf_extract_kit.tasks.base_task import BaseTask

    @TASK_REGISTRY.register("layout_detection")
    class LayoutDetectionTask(BaseTask):
        def __init__(self, model):
            super().__init__(model)

        def predict_images(self, input_data, result_path):
            """
            Predict layouts in images.

            Args:
                input_data (str): Path to a single image file or a directory containing image files.
                result_path (str): Path to save the prediction results.

            Returns:
                list: List of prediction results.
            """
            images = self.load_images(input_data)
            # Perform detection
            return self.model.predict(images, result_path)

        def predict_pdfs(self, input_data, result_path):
            """
            Predict layouts in PDF files.

            Args:
                input_data (str): Path to a single PDF file or a directory containing PDF files.
                result_path (str): Path to save the prediction results.

            Returns:
                list: List of prediction results.
            """
            pdf_images = self.load_pdf_images(input_data)
            # Perform detection
            return self.model.predict(list(pdf_images.values()), result_path, list(pdf_images.keys()))

As you can see, the task definition includes the following key points:

* Use the `@TASK_REGISTRY.register("layout_detection")` syntax to directly register the layout task class under `TASK_REGISTRY`.
* The `__init__` initialization function takes `model` as an argument, specifically referring to the `BaseTask` class.
* Implement inference functions. Considering that layout detection usually processes images and PDF files, two functions `predict_images` and `predict_pdfs` are provided for users to choose flexibly.

Model Definition and Registration
==============

Next, we implement the specific model by creating a `models` directory under `task` and adding `yolo.py` for YOLO model definition, as follows:

.. code-block:: python

    import os
    import cv2
    import torch
    from torch.utils.data import DataLoader, Dataset
    from ultralytics import YOLO
    from pdf_extract_kit.registry import MODEL_REGISTRY
    from pdf_extract_kit.utils.visualization import  visualize_bbox
    from pdf_extract_kit.dataset.dataset import ImageDataset
    import torchvision.transforms as transforms

    @MODEL_REGISTRY.register('layout_detection_yolo')
    class LayoutDetectionYOLO:
        def __init__(self, config):
            """
            Initialize the LayoutDetectionYOLO class.

            Args:
                config (dict): Configuration dictionary containing model parameters.
            """
            # Mapping from class IDs to class names
            self.id_to_names = {
                0: 'title', 
                1: 'plain text',
                2: 'abandon', 
                3: 'figure', 
                4: 'figure_caption', 
                5: 'table', 
                6: 'table_caption', 
                7: 'table_footnote', 
                8: 'isolate_formula', 
                9: 'formula_caption'
            }

            # Load the YOLO model from the specified path
            self.model = YOLO(config['model_path'])

            # Set model parameters
            self.img_size = config.get('img_size', 1280)
            self.pdf_dpi = config.get('pdf_dpi', 200)
            self.conf_thres = config.get('conf_thres', 0.25)
            self.iou_thres = config.get('iou_thres', 0.45)
            self.visualize = config.get('visualize', False)
            self.device = config.get('device', 'cuda' if torch.cuda.is_available() else 'cpu')
            self.batch_size = config.get('batch_size', 1)

        def predict(self, images, result_path, image_ids=None):
            """
            Predict layouts in images.

            Args:
                images (list): List of images to be predicted.
                result_path (str): Path to save the prediction results.
                image_ids (list, optional): List of image IDs corresponding to the images.

            Returns:
                list: List of prediction results.
            """
            results = []
            for idx, image in enumerate(images):
                result = self.model.predict(image, imgsz=self.img_size, conf=self.conf_thres, iou=self.iou_thres, verbose=False)[0]
                if self.visualize:
                    if not os.path.exists(result_path):
                        os.makedirs(result_path)
                    boxes = result.__dict__['boxes'].xyxy
                    classes = result.__dict__['boxes'].cls
                    vis_result = visualize_bbox(image, boxes, classes, self.id_to_names)

                    # Determine the base name of the image
                    if image_ids:
                        base_name = image_ids[idx]
                    else:
                        base_name = os.path.basename(image)
                    
                    result_name = f"{base_name}_MFD.png"
                    
                    # Save the visualized result                
                    cv2.imwrite(os.path.join(result_path, result_name), vis_result)
                results.append(result)
            return results

As you can see, the model definition includes the following key points:

* Use the `@MODEL_REGISTRY.register('layout_detection_yolo')` syntax to directly register the YOLO layout model under `MODEL_REGISTRY`.
* The initialization function needs to implement:
    + The `id_to_names` category mapping for visualization.
    + Model parameter configuration.
    + Model initialization.
* The model inference function needs to implement various types of model inference: it supports image lists and `PIL.Image` class, allowing users to perform inference directly based on image paths or image streams.

After implementing the above class definition, add `LayoutDetectionYOLO` to the `__all__` in `__init__.py` under the `layout_detection` task.

.. code-block:: python

    from pdf_extract_kit.tasks.layout_detection.models.yolo import LayoutDetectionYOLO
    from pdf_extract_kit.registry.registry import MODEL_REGISTRY

    __all__ = [
        "LayoutDetectionYOLO",
    ]

.. note:: 
    For the same task, we support multiple models. Users can choose which one to use based on evaluation results, considering model `accuracy`, `speed`, and `scenario adaptability`.

After implementing the tasks and models, you can add a script program `layout_detection.py` under `repo_root/scripts`.

Example Script
==============

.. code-block:: python

    import os
    import sys
    import os.path as osp
    import argparse

    sys.path.append(osp.join(os.path.dirname(os.path.abspath(__file__)), '..'))
    from pdf_extract_kit.utils.config_loader import load_config, initialize_tasks_and_models
    import pdf_extract_kit.tasks  # Ensure all task modules are imported

    TASK_NAME = 'layout_detection'

    def parse_args():
        parser = argparse.ArgumentParser(description="Run a task with a given configuration file.")
        parser.add_argument('--config', type=str, required=True, help='Path to the configuration file.')
        return parser.parse_args()

    def main(config_path):
        config = load_config(config_path)
        task_instances = initialize_tasks_and_models(config)

        # get input and output path from config
        input_data = config.get('inputs', None)
        result_path = config.get('outputs', 'outputs'+'/'+TASK_NAME)

        # layout_detection_task
        model_layout_detection = task_instances[TASK_NAME]

        # for image detection
        detection_results = model_layout_detection.predict_images(input_data, result_path)

        # for pdf detection
        # detection_results = model_layout_detection.predict_pdfs(input_data, result_path)

        # print(detection_results)
        print(f'The predicted results can be found at {result_path}')

    if __name__ == "__main__":
        args = parse_args()
        main(args.config)

Support Type Extension
==============

Batch Processing Extension
==============

================================================
FILE: docs/en/task_extend/doc.rst
================================================
==================================
Documentation Supplement
==================================



================================================
FILE: docs/en/task_extend/evaluation.rst
================================================
==================================
Model Performance Evaluation
==================================



================================================
FILE: docs/requirements.txt
================================================
sphinx
sphinx_rtd_theme
myst-parser
sphinx-copybutton
sphinx-argparse
sphinx-book-theme

================================================
FILE: docs/zh_cn/.readthedocs.yaml
================================================
version: 2

build:
  os: ubuntu-22.04
  tools:
    python: "3.10"

formats:
  - epub

python:
  install:
    - requirements: requirements/docs.txt

sphinx:
  configuration: docs/zh_cn/conf.py


================================================
FILE: docs/zh_cn/Makefile
================================================
# Minimal makefile for Sphinx documentation
#

# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS    ?=
SPHINXBUILD   ?= sphinx-build
SOURCEDIR     = .
BUILDDIR      = _build

# Put it first so that "make" without argument is like "make help".
help:
	@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

.PHONY: help Makefile

# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option.  $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
	@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)


================================================
FILE: docs/zh_cn/algorithm/formula_detection.rst
================================================
..  _algorithm_formula_detection:

====================
公式检测算法
====================

简介
====================

公式检测是针对给定的输入图像,检测出图像中所有包含公式的位置(包含行内公式和行间公式)

.. note::

   公式检测实际上属于布局检测子任务,但由于公式检查的复杂性,我们建议使用单独的公式检测模型解耦。
   这样通常使得数据标注更加方便,且公式检测效果也更好。

模型使用
====================

在配置好环境的情况下,直接执行 ``scripts/formula_detection.py`` 即可运行布局检测算法脚本。

.. code:: shell

   $ python scripts/formula_detection.py --config configs/formula_detection.yaml

模型配置
--------------------

.. code:: yaml

   inputs: assets/demo/formula_detection
   outputs: outputs/formula_detection
   tasks:
      formula_detection:
         model: formula_detection_yolo
         model_config:
            img_size: 1280
            conf_thres: 0.25
            iou_thres: 0.45
            batch_size: 1
            model_path: models/MFD/yolov8/weights.pt
            visualize: True

- inputs/outputs: 分别定义输入文件路径和可视化输出目录
- tasks: 定义任务类型,当前只包含一个公式检测任务
- model: 定义具体模型类型: 当前仅提供YOLO公式检测模型
- model_config: 定义模型配置
- img_size: 定义图像长边大小,短边会根据长边等比例缩放
- conf_thres: 定义置信度阈值,仅检测大于该阈值的目标
- iou_thres: 定义IoU阈值,去除重叠度大于该阈值的目标
- batch_size: 定义批量大小,推理时每次同时推理的图像数,一般情况下越大推理速度越快,显卡越好该数值可以设置的越大
- model_path: 模型权重路径
- visualize: 是否对模型结果进行可视化,可视化结果会保存在outputs目录下。

多样化输入支持
--------------------

PDF-Extract-Kit中的公式检测脚本支持 ``单个图像`` 、 ``只包含图像文件的目录`` 、 ``单个PDF文件`` 、 ``只包含PDF文件的目录`` 等输入形式。

.. note:: 

   根据自己实际数据形式,修改 ``configs/formula_detection.yaml`` 中 ``inputs`` 的路径即可
   - 单个图像: path/to/image  
   - 图像文件夹: path/to/images  
   - 单个PDF文件: path/to/pdf  
   - PDF文件夹: path/to/pdfs  

.. note::

   当使用PDF作为输入时,需要将 ``formula_detection.py`` 中的 ``predict_images`` 修改为 ``predict_pdfs`` 。


   .. code:: python

      # for image detection
      detection_results = model_formula_detection.predict_images(input_data, result_path)
   

   .. code:: python

      # for pdf detection
      detection_results = model_formula_detection.predict_pdfs(input_data, result_path)


可视化结果查看
--------------------

当config文件中 ``visualize`` 设置为 ``True`` 时,可视化结果会保存在 ``outputs/formula_detection`` 目录下。

.. note::

   可视化可以方便对模型结果进行分析,但当进行大批量任务时,建议关掉可视化(设置 ``visualize`` 为 ``False`` ),减少内存和磁盘占用。

================================================
FILE: docs/zh_cn/algorithm/formula_recognition.rst
================================================
..  _algorithm_formula_recognition:

============
公式识别算法
============

简介
=================

公式检测是指给定输入公式图像,识别公式图像内容并转为 ``LaTeX`` 格式。

模型使用
=================

在配置好环境的情况下,直接执行 ``scripts/formula_recognition.py`` 即可运行布局检测算法脚本。

.. code:: shell

   $ python scripts/formula_recognition.py --config configs/formula_recognition.yaml

模型配置
-----------------

.. code:: yaml

   inputs: assets/demo/formula_recognition
   outputs: outputs/formula_recognition
   tasks:
      formula_recognition:
         model: formula_recognition_unimernet
         model_config:
            cfg_path: pdf_extract_kit/configs/unimernet.yaml
            model_path: models/MFR/unimernet_tiny
            visualize: False

- inputs/outputs: 分别定义输入文件路径和LaTeX预测结果目录
- tasks: 定义任务类型,当前只包含一个公式识别任务
- model: 定义具体模型类型: 当前仅提供 `UniMERNet <https://github.com/opendatalab/UniMERNet>`_ 公式识别模型
- model_config: 定义模型配置
- cfg_path: UniMERNet配置文件路径
- model_path: 模型权重路径
- visualize: 是否对模型结果进行可视化,可视化结果会保存在outputs目录下。

多样化输入支持
-----------------

PDF-Extract-Kit中的公式检测脚本支持 ``单个公式图像`` 、 ``文档图像及对应公式区域``

可视化结果查看
-----------------

当config文件中visualize设置为True时, ``LaTeX`` 预测结果会保存在outputs目录下。

================================================
FILE: docs/zh_cn/algorithm/layout_detection.rst
================================================
.. _algorithm_layout_detection:

=================
布局检测算法
=================

简介
=================

``布局检测`` 是文档内容提取的基础任务,目标对页面中不同类型的区域进行定位:如 ``图像`` 、 ``表格`` 、 ``文本`` 、 ``标题`` 等,方便后续高质量内容提取。对于 ``文本`` 、 ``标题`` 等区域,可以基于 ``OCR模型`` 进行文字识别,对于表格区域可以基于表格识别模型进行转换。

模型使用
=================

布局检测模型支持以下模型:

.. raw:: html

    <style type="text/css">
    .tg  {border-collapse:collapse;border-color:#9ABAD9;border-spacing:0;}
    .tg td{background-color:#EBF5FF;border-color:#9ABAD9;border-style:solid;border-width:1px;color:#444;
      font-family:Arial, sans-serif;font-size:14px;overflow:hidden;padding:10px 5px;word-break:normal;}
    .tg th{background-color:#409cff;border-color:#9ABAD9;border-style:solid;border-width:1px;color:#fff;
      font-family:Arial, sans-serif;font-size:14px;font-weight:normal;overflow:hidden;padding:10px 5px;word-break:normal;}
    .tg .tg-f8tz{background-color:#409cff;border-color:inherit;text-align:left;vertical-align:top}
    .tg .tg-0lax{text-align:left;vertical-align:top}
    .tg .tg-0pky{border-color:inherit;text-align:left;vertical-align:top}
    </style>
    <table class="tg"><thead>
      <tr>
        <th class="tg-0lax">模型</th>
        <th class="tg-f8tz">简述</th>
        <th class="tg-f8tz">特点</th>
        <th class="tg-f8tz">模型权重</th>
        <th class="tg-f8tz">配置文件</th>
      </tr></thead>
    <tbody>
      <tr>
        <td class="tg-0lax">DocLayout-YOLO</td>
        <td class="tg-0pky">基于YOLO-v10模型改进:<br>1. 生成多样性预训练数据,提升对多种类型文档泛化性<br>2. 模型结构改进,提升对多尺度目标感知能力<br>详见<a href="https://github.com/opendatalab/DocLayout-YOLO" target="_blank" rel="noopener noreferrer">DocLayout-YOLO</a></td>
        <td class="tg-0pky">速度快、精度高</td>
        <td class="tg-0pky"><a href="https://huggingface.co/opendatalab/PDF-Extract-Kit-1.0/blob/main/models/Layout/YOLO/doclayout_yolo_ft.pt" target="_blank" rel="noopener noreferrer">doclayout_yolo_ft.pt</a></td>
        <td class="tg-0pky">layout_detection.yaml</td>
      </tr>
      <tr>
        <td class="tg-0lax">YOLO-v10</td>
        <td class="tg-0pky">基础YOLO-v10模型</td>
        <td class="tg-0pky">速度快,精度一般</td>
        <td class="tg-0pky"><a href="https://huggingface.co/opendatalab/PDF-Extract-Kit-1.0/blob/main/models/Layout/YOLO/yolov10l_ft.pt" target="_blank" rel="noopener noreferrer">yolov10l_ft.pt</a></td>
        <td class="tg-0pky">layout_detection_yolo.yaml</td>
      </tr>
      <tr>
        <td class="tg-0lax">LayoutLMv3</td>
        <td class="tg-0pky">基础LayoutLMv3模型</td>
        <td class="tg-0pky">速度慢,精度较好</td>
        <td class="tg-0pky"><a href="https://huggingface.co/opendatalab/PDF-Extract-Kit-1.0/tree/main/models/Layout/LayoutLMv3" target="_blank" rel="noopener noreferrer">layoutlmv3_ft</a></td>
        <td class="tg-0pky">layout_detection_layoutlmv3.yaml</td>
      </tr>
    </tbody></table>


在配置好环境的情况下,直接执行 ``scripts/layout_detection.py`` 即可运行布局检测算法脚本。


**执行布局检测程序**

.. code:: shell

   $ python scripts/layout_detection.py --config configs/layout_detection.yaml

模型配置
-----------------

**1. DocLayout-YOLO / YOLO-v10**

.. code:: yaml

    inputs: assets/demo/layout_detection
    outputs: outputs/layout_detection
    tasks:
      layout_detection:
        model: layout_detection_yolo
        model_config:
          img_size: 1024
          conf_thres: 0.25
          iou_thres: 0.45
          model_path: path/to/doclayout_yolo_model
          visualize: True

- inputs/outputs: 分别定义输入文件路径和可视化输出目录
- tasks: 定义任务类型,当前只包含一个布局检测任务
- model: 定义具体模型类型,例如 ``layout_detection_yolo``
- model_config: 定义模型配置
- img_size: 定义图像长边大小,短边会根据长边等比例缩放,默认长边保持1024
- conf_thres: 定义置信度阈值,仅检测大于该阈值的目标
- iou_thres: 定义IoU阈值,去除重叠度大于该阈值的目标
- model_path: 模型权重路径
- visualize: 是否对模型结果进行可视化,可视化结果会保存在outputs目录下


**2. LayoutLMv3**

.. note::

   LayoutLMv3 默认情况下不能直接运行。运行时请将配置文件修改为configs/layout_detection_layoutlmv3.yaml,并且请按照以下步骤进行配置修改:

   1. **Detectron2 环境配置**

   .. code-block:: bash

      # 对于 Linux
      pip install https://wheels-1251341229.cos.ap-shanghai.myqcloud.com/assets/whl/detectron2/detectron2-0.6-cp310-cp310-linux_x86_64.whl

      # 对于 macOS
      pip install https://wheels-1251341229.cos.ap-shanghai.myqcloud.com/assets/whl/detectron2/detectron2-0.6-cp310-cp310-macosx_10_9_universal2.whl

      # 对于 Windows
      pip install https://wheels-1251341229.cos.ap-shanghai.myqcloud.com/assets/whl/detectron2/detectron2-0.6-cp310-cp310-win_amd64.whl

   2. **启用 LayoutLMv3 注册代码**

   请取消注释以下链接中的代码行:
   
   - `第2行 <https://github.com/opendatalab/PDF-Extract-Kit/blob/main/pdf_extract_kit/tasks/layout_detection/__init__.py#L2>`_
   - `第8行 <https://github.com/opendatalab/PDF-Extract-Kit/blob/main/pdf_extract_kit/tasks/layout_detection/__init__.py#L8>`_

   .. code-block:: python

      from pdf_extract_kit.tasks.layout_detection.models.yolo import LayoutDetectionYOLO
      from pdf_extract_kit.tasks.layout_detection.models.layoutlmv3 import LayoutDetectionLayoutlmv3
      from pdf_extract_kit.registry.registry import MODEL_REGISTRY

      __all__ = [
         "LayoutDetectionYOLO",
         "LayoutDetectionLayoutlmv3",
      ]

.. code:: yaml

    inputs: assets/demo/layout_detection
    outputs: outputs/layout_detection
    tasks:
      layout_detection:
        model: layout_detection_layoutlmv3
        model_config:
          model_path: path/to/layoutlmv3_model

- inputs/outputs: 分别定义输入文件路径和可视化输出目录
- tasks: 定义任务类型,当前只包含一个布局检测任务
- model: 定义具体模型类型,例如layout_detection_layoutlmv3
- model_config: 定义模型配置
- model_path: 模型权重路径


多样化输入支持
-----------------

PDF-Extract-Kit中的布局检测脚本支持 ``单个图像`` 、 ``只包含图像文件的目录`` 、 ``单个PDF文件`` 、 ``只包含PDF文件的目录`` 等输入形式。

.. note::

   根据自己实际数据形式,修改configs/layout_detection.yaml中inputs的路径即可
   - 单个图像: path/to/image  
   - 图像文件夹: path/to/images  
   - 单个PDF文件: path/to/pdf  
   - PDF文件夹: path/to/pdfs  

.. note::
   当使用PDF作为输入时,需要将 ``layout_detection.py``

   .. code:: python

      # for image detection
      detection_results = model_layout_detection.predict_images(input_data, result_path)

   中的 ``predict_images`` 修改为 ``predict_pdfs`` 。

   .. code:: python

      # for pdf detection
      detection_results = model_layout_detection.predict_pdfs(input_data, result_path)

可视化结果查看
-----------------

当config文件中 ``visualize`` 设置为 ``True`` 时,可视化结果会保存在 ``outputs`` 目录下。

.. note::

   可视化可以方便对模型结果进行分析,但当进行大批量任务时,建议关掉可视化(设置 ``visualize`` 为 ``False`` ),减少内存和磁盘占用。

================================================
FILE: docs/zh_cn/algorithm/ocr.rst
================================================
..  _algorithm_ocr:
==========================
光学字符识别(OCR)算法
==========================

简介
====================

光学字符识别(OCR)是指对图片中的文字块进行检测和识别。


模型使用
====================

在配置好环境的情况下,直接执行 ``scripts/ocr.py`` 即可运行OCR算法脚本。

.. code:: shell

   $ python scripts/ocr.py --config configs/ocr.yaml


模型配置
--------------------

.. code:: yaml

   inputs: assets/demo/ocr
   outputs: outputs/ocr
   visualize: True
   tasks:
      ocr:
         model: ocr_ppocr
         model_config:
            lang: ch
            show_log: True
            det_model_dir: models/OCR/PaddleOCR/det/ch_PP-OCRv4_det
            rec_model_dir: models/OCR/PaddleOCR/rec/ch_PP-OCRv4_rec
            det_db_box_thresh: 0.3

- inputs/outputs: 分别定义输入文件路径和输出路径
- visualize: 是否对模型结果进行可视化,可视化结果会保存在outputs目录下。
- tasks: 定义任务类型,当前只包含一个OCR任务
- model: 定义具体模型类型, 当前仅提供PaddleOCR模型
- model_config: 定义模型配置
- lang: 定义语种,默认语种ch支持中英文文字的检测和识别
- show_log: 是否打印检测识别过程的日志
- det_model_dir: 定义PaddleOCR检测模型的路径,指定路径不存在时,会自动下载模型权重到该路径
- rec_model_dir: 定义PaddleOCR识别模型的路径,指定路径不存在时,会自动下载模型权重到该路径
- det_db_box_thresh: 检测框筛选阈值,置信度低于该阈值的框会被舍弃


多样化输入支持
--------------------

PDF-Extract-Kit中的OCR脚本支持 ``单个图像/PDF文件`` 、 ``包含图像/PDF文件的目录`` 等输入形式。


可视化结果查看
--------------------

当config文件中 ``visualize`` 设置为 ``True`` 时,可视化结果会保存在 ``outputs`` 参数指定的目录下。

.. note::

   可视化可以方便对模型结果进行分析,但当进行大批量任务时,建议关掉可视化(设置 ``visualize`` 为 ``False`` ),减少内存和磁盘占用。

================================================
FILE: docs/zh_cn/algorithm/reading_order.rst
================================================
..  _algorithm_reading_oder:
==============
阅读顺序算法
==============

Comming soon.

================================================
FILE: docs/zh_cn/algorithm/table_recognition.rst
================================================
..  _algorithm_table_recognition:

============
表格识别算法
============

简介
=================

表格识别是指输入表格图像,识别表格结构和内容,并将其转换为 ``LaTeX`` 或 ``HTML`` 等格式。

模型使用
=================

在配置好环境的情况下,直接执行 ``scripts/table_parsing.py`` 即可运行表格识别算法脚本。

.. code:: shell

   $ python scripts/table_parsing.py --config configs/table_parsing.yaml

模型配置
-----------------

.. code:: yaml

    inputs: assets/demo/table_parsing
    outputs: outputs/table_parsing
    tasks:
      table_parsing:
        model: table_parsing_struct_eqtable
        model_config:
          model_path: models/TabRec/StructEqTable
          max_new_tokens: 1024
          max_time: 30
          output_format: latex
          lmdeploy: False
          flash_attn: True

- inputs/outputs: 分别定义输入文件路径和表格识别结果目录
- tasks: 定义任务类型,当前只包含一个表格识别任务
- model: 定义具体模型类型: 当前使用 `StructEqTable  <https://github.com/UniModal4Reasoning/StructEqTable-Deploy>`_ 表格识别模型
- model_config: 定义模型配置
- model_path: 模型权重路径
- max_new_tokens: 生成的最大token数量, 默认为1024, 最大支持4096
- max_time: 模型运行的最大时间(秒)
- output_format: 输出格式,默认设置为 ``latex``, 可选有 ``html`` 和 ``markdown``
- lmdeploy: 是否使用 LMDeploy 进行部署,当前设置为 False
- flash_attn: 是否使用flash attention,仅适用于Ampere GPU


多样化输入支持
-----------------

PDF-Extract-Kit中的表格识别脚本支持 ``单个表格图像`` 和 ``多个表格图像`` 作为输入。

.. note::

   StructEqTable表格模型仅支持GPU设备下运行

.. note::
    
    根据表格内容调整 ``max_new_tokens`` 和 ``max_time``, 默认分别为1024和30。

.. note::
    
    lmdeploy为加速推理的选项,如果设置为True,将使用LMDeploy进行加速推理部署。
    使用LMDeploy部署需要安装LMDeploy,安装方法参考 `LMDeploy <https://github.com/InternLM/lmdeploy>`_ 。



================================================
FILE: docs/zh_cn/conf.py
================================================
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html

# -- Path setup --------------------------------------------------------------

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.

import os
import subprocess
import sys

def install(package):
    subprocess.check_call([sys.executable, "-m", "pip", "install", package])

# 安装 requirements.txt 中的依赖项
requirements_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'requirements.txt'))
if os.path.exists(requirements_path):
    with open(requirements_path) as f:
        packages = f.readlines()
    for package in packages:
        install(package.strip())

from sphinx.ext import autodoc
sys.path.insert(0, os.path.abspath('../..'))

# -- Project information -----------------------------------------------------

project = 'PDF-Extract-Kit'
copyright = '2024, OpenDataLab'
author = 'PDF-Extract-Kit Contributors'

# The full version, including alpha/beta/rc tags
version_file = '../../pdf_extract_kit/version.py'
with open(version_file) as f:
    exec(compile(f.read(), version_file, 'exec'))
__version__ = locals()['__version__']
# The short X.Y version
version = __version__
# The full version, including alpha/beta/rc tags
release = __version__

# -- General configuration ---------------------------------------------------

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    'sphinx.ext.napoleon',
    'sphinx.ext.viewcode',
    'sphinx.ext.intersphinx',
    'sphinx_copybutton',
    'sphinx.ext.autodoc',
    'sphinx.ext.autosummary',
    'myst_parser',
    'sphinxarg.ext',
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']

# Exclude the prompt "$" when copying code
copybutton_prompt_text = r'\$ '
copybutton_prompt_is_regexp = True

language = 'zh_CN'

# -- Options for HTML output -------------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_book_theme'
html_logo = '_static/image/logo.png'
html_theme_options = {
    'path_to_docs': 'docs/zh_cn',
    'repository_url': 'https://github.com/opendatalab/PDF-Extract-Kit',
    'use_repository_button': True,
}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# html_static_path = ['_static']

# Mock out external dependencies here.
autodoc_mock_imports = [
    'cpuinfo',
    'torch',
    'transformers',
    'psutil',
    'prometheus_client',
    'sentencepiece',
    'vllm.cuda_utils',
    'vllm._C',
    'numpy',
    'tqdm',
]


class MockedClassDocumenter(autodoc.ClassDocumenter):
    """Remove note about base class when a class is derived from object."""

    def add_line(self, line: str, source: str, *lineno: int) -> None:
        if line == '   Bases: :py:class:`object`':
            return
        super().add_line(line, source, *lineno)


autodoc.ClassDocumenter = MockedClassDocumenter

navigation_with_keys = False

================================================
FILE: docs/zh_cn/evaluation/formula_detection.rst
================================================
=====================
公式检测算法评测
=====================

XXX

================================================
FILE: docs/zh_cn/evaluation/formula_recognition.rst
================================================
=====================
公式识别算法评测
=====================

Comming soon!

================================================
FILE: docs/zh_cn/evaluation/layout_detection.rst
================================================
=====================
布局检测算法评测
=====================

Comming soon!

================================================
FILE: docs/zh_cn/evaluation/ocr.rst
================================================
=====================
OCR算法评测
=====================

Comming soon!

================================================
FILE: docs/zh_cn/evaluation/pdf_extract.rst
================================================
=====================
PDF内容提取评测【端到端】
=====================

Comming soon!

================================================
FILE: docs/zh_cn/evaluation/reading_order.rst
================================================
=====================
阅读顺序算法评测
=====================

XXX

================================================
FILE: docs/zh_cn/evaluation/table_recognition.rst
================================================
=====================
表格识别算法评测
=====================

Comming soon!


================================================
FILE: docs/zh_cn/get_started/installation.rst
================================================
==================================
安装
==================================

本节中,我们将演示如何安装 PDF-Extract-Kit。

最佳实践
========

我们推荐用户参照我们的最佳实践安装 PDF-Extract-Kit。
推荐使用 Python-3.10 的 conda 虚拟环境安装 PDF-Extract-Kit。

**步骤 1.** 使用 conda 先构建一个 Python-3.10 的虚拟环境

.. code-block:: console

    $ conda create -n pdf-extract-kit-1.0 python=3.10 -y
    $ conda activate pdf-extract-kit-1.0

**步骤 2.** 安装 PDF-Extract-Kit 的依赖项

.. code-block:: console

    $ # 对于GPU设备
    $ pip install -r requirements.txt
    $ # 对于CPU设备
    $ pip install -r requirements-cpu.txt

.. note::

    考虑到用户环境配置的便捷性,我们在requirements.txt只包含当前最好模型需要的环境,目前包含  

    - 布局检测:YOLO系列(YOLOv10, DocLayout-YOLO)  
    - 公式检测:YOLO系列 (YOLOv8)  
    - 公式识别:UniMERNet  
    - OCR: PaddleOCR  

    对于其他模型请,如LayoutLMv3需要单独安装环境,具体见\ :ref:`布局检测算法 <algorithm_layout_detection>`

================================================
FILE: docs/zh_cn/get_started/pretrained_model.rst
================================================
==================================
模型权重下载
==================================

在使用PDF-Extract-Kit前,我们需要下载所需要的模型权重。可以根据自己需求下载全部模型或者特定的模型文件(如公式检测MFD)

[推荐] 方法 1:``snapshot_download``
========================================

HuggingFace
------------

``huggingface_hub.snapshot_download`` 支持下载特定的 HuggingFace Hub
模型权重,并且允许多线程。您可以利用下列代码并行下载模型权重:

.. code:: python

   from huggingface_hub import snapshot_download

   snapshot_download(repo_id='opendatalab/pdf-extract-kit-1.0', local_dir='./', max_workers=20)

如果想仅下载单个算法模型(如公式检测任务的YOLO模型),可以使用如下代码:

.. code:: python

   from huggingface_hub import snapshot_download

   snapshot_download(repo_id='opendatalab/pdf-extract-kit-1.0', local_dir='./', allow_patterns='models/MFD/YOLO/*') 

.. note::

   其中,\ ``repo_id`` 表示模型在 HuggingFace Hub 的名字、\ ``local_dir`` 表示期望存储到的本地路径、\ ``max_workers`` 表示下载的最大并行数,\ ``allow_patterns`` 表示想要现在的文件。

.. tip::

   如果未指定 ``local_dir``\ ,则将下载至 HuggingFace 的默认 cache 路径中(\ ``~/.cache/huggingface/hub``\ )。若要修改默认 cache 路径,需要修改相关环境变量:

   .. code:: console

      $ # 默认为 ~/.cache/huggingface/
      $ export HF_HOME=Comming soon!

.. tip::
   
   如果觉得下载较慢(例如无法达到最大带宽等情况),可以尝试设置\ ``export HF_HUB_ENABLE_HF_TRANSFER=1`` 以获得更高的下载速度。

ModelScope
-----------

``modelscope.snapshot_download``
支持下载指定的模型权重,您可以利用下列命令下载模型:

.. code:: python

   from modelscope import snapshot_download

   snapshot_download(model_id='opendatalab/pdf-extract-kit-1.0', cache_dir='./')

如果想仅下载单个算法模型(如公式检测任务的YOLO模型),可以使用如下代码:

.. code:: python

   from modelscope import snapshot_download

   snapshot_download(repo_id='opendatalab/pdf-extract-kit-1.0', local_dir='./', allow_patterns='models/MFD/YOLO/*') 


.. note::
   其中,\ ``model_id`` 表示模型在 ModelScope 模型库的名字,\ ``cache_dir`` 表示期望存储到的本地路径, \ ``allow_patterns`` 表示想要现在的文件。


.. note::
   ``modelscope.snapshot_download`` 不支持多线程并行下载。

.. tip::

   如果未指定 ``cache_dir``\ ,则将下载至 ModelScope 的默认 cache 路径中(\ ``~/.cache/huggingface/hub``\ )。

   若要修改默认 cache 路径,需要修改相关环境变量:

   .. code:: console

      $ # 默认为 ~/.cache/modelscope/hub/
      $ export MODELSCOPE_CACHE=XXXX



方法 2: Git LFS
===================

HuggingFace 和 ModelScope 的远程模型仓库就是一个由 Git LFS 管理的 Git
仓库。因此,我们可以利用 ``git clone`` 完成权重的下载:

.. code:: console

   $ git lfs install
   $ # From HuggingFace
   $ git lfs clone https://huggingface.co/opendatalab/pdf-extract-kit-1.0
   $ # From ModelScope
   $ git clone https://www.modelscope.cn/opendatalab/pdf-extract-kit-1.0.git


================================================
FILE: docs/zh_cn/get_started/quickstart.rst
================================================
==================================
快速开始
==================================

配置好PDF-Extract-Kit环境,并下载好模型后,我们可以开始使用PDF-Extract-Kit了。



布局检测示例
==============

布局检测提供了多种模型: ``LayoutLMv3``、 ``YOLOv10``、  ``DocLayout-YOLO``, 相比与 ``LayoutLMv3``, ``YOLOv10`` 速度更快, ``DocLayout-YOLO`` 则是基于 ``YOLOv10`` 的基础上进行多样性文档预训练及模型优化,速度快,精度高。

**1. 使用布局检测模型**

.. code-block:: console

    $ python scripts/layout_detection.py --config configs/layout_detection.yaml

执行完之后,我们可以在 ``outpus/layout_detection`` 目录下查看检测结果。

.. note::   

    ``layout_detection.yaml`` 设置输入、输出及模型配置,布局检测更详细教程见\ :ref:`布局检测算法 <algorithm_layout_detection>` \ 。


公式检测示例
==============


.. code-block:: console

    $ python scripts/formula_detection.py --config configs/formula_detection.yaml

执行完之后,我们可以在 ``outpus/formula_detection`` 目录下查看检测结果。

.. note::   

    ``formula_detection.yaml`` 设置输入、输出及模型配置,公式检测更详细教程见 \ :ref:`公式检测算法 <algorithm_formula_detection>` \ 。


================================================
FILE: docs/zh_cn/index.rst
================================================
.. xtuner documentation master file, created by
   sphinx-quickstart on Tue Jan  9 16:33:06 2024.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

欢迎来到 PDF-Extract-Kit 的中文文档
==============================================

.. figure:: ./_static/image/logo.png
  :align: center
  :alt: pdf-extract-kit
  :class: no-scaled-link

.. raw:: html

   <p style="text-align:center">
   <strong>高质量文档解析工具箱
   </strong>
   </p>

   <p style="text-align:center">
   <script async defer src="https://buttons.github.io/buttons.js"></script>
   <a class="github-button" href="https://github.com/opendatalab/PDF-Extract-Kit" data-show-count="true" data-size="large" aria-label="Star">Star</a>
   <a class="github-button" href="https://github.com/opendatalab/PDF-Extract-Kit/subscription" data-icon="octicon-eye" data-size="large" aria-label="Watch">Watch</a>
   <a class="github-button" href="https://github.com/opendatalab/PDF-Extract-Kit/fork" data-icon="octicon-repo-forked" data-size="large" aria-label="Fork">Fork</a>
   </p>


文档
-------------
.. toctree::
   :maxdepth: 2
   :caption: 快速上手

   get_started/installation.rst
   get_started/pretrained_model.rst
   get_started/quickstart.rst

.. toctree::
   :maxdepth: 2
   :caption: 基础算法模块

   algorithm/layout_detection.rst
   algorithm/formula_detection.rst
   algorithm/formula_recognition.rst
   algorithm/ocr.rst
   algorithm/table_recognition.rst
   algorithm/reading_order.rst

.. toctree::
   :maxdepth: 2
   :caption: 新任务拓展

   task_extend/code.rst
   task_extend/doc.rst
   task_extend/evaluation.rst

.. toctree::
   :maxdepth: 2
   :caption: 支持的模型列表

   models/supported.md


.. toctree::
   :maxdepth: 2
   :caption: 模型性能评测

   evaluation/layout_detection.rst
   evaluation/formula_detection.rst
   evaluation/formula_recognition.rst
   evaluation/ocr.rst
   evaluation/table_recognition.rst
   evaluation/reading_order.rst
   evaluation/pdf_extract.rst

.. toctree::
   :maxdepth: 2
   :caption: PDF项目

   project/pdf_extract.md
   project/doc_translate.md
   project/speed_up.md

================================================
FILE: docs/zh_cn/make.bat
================================================
@ECHO OFF

pushd %~dp0

REM Command file for Sphinx documentation

if "%SPHINXBUILD%" == "" (
	set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=.
set BUILDDIR=_build

%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
	echo.
	echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
	echo.installed, then set the SPHINXBUILD environment variable to point
	echo.to the full path of the 'sphinx-build' executable. Alternatively you
	echo.may add the Sphinx directory to PATH.
	echo.
	echo.If you don't have Sphinx installed, grab it from
	echo.https://www.sphinx-doc.org/
	exit /b 1
)

if "%1" == "" goto help

%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
goto end

:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%

:end
popd


================================================
FILE: docs/zh_cn/models/supported.md
================================================
# 已支持的模型

Comming soon!

================================================
FILE: docs/zh_cn/notes/changelog.md
================================================
<!--

## vX.X.X (YYYY.MM.DD)

### 亮点

### 新功能和改进

### Bug 修复

### 贡献者

-->

# 变更日志


## v0.2.0 (2024.09.30)

PDF-Extract-Kit 代码重构,模块化设计更加简洁易用! 🔥🔥🔥

## v0.1.0 (2024.07.01)

PDF-Extract-Kit 正式发布!🔥🔥🔥

### 亮点

- PDF-Extract-Kit提供高质量布局检测模型 DocLayout-YOLO
- PDF-Extract-Kit提供高质量公式检测模型 YOLOv8

================================================
FILE: docs/zh_cn/project/doc_translate.rst
================================================
=================
文档翻译项目
=================

Comming soon!

================================================
FILE: docs/zh_cn/project/pdf_extract.rst
================================================
=================
文档内容提取项目
=================

简介
====================

文档内容提取是利用布局检测,公式检测,公式识别,OCR等模型,提取文档中的信息,并转换为markdown文本。


项目使用
====================

在配置好环境的情况下,直接执行 ``project/pdf2markdown/scripts/run_project.py`` 即可运行文档内容提取项目。

.. code:: shell

   $ python project/pdf2markdown/scripts/run_project.py --config project/pdf2markdown/configs/pdf2markdown.yaml


项目配置
--------------------

.. code:: yaml

    inputs: assets/demo/formula_detection
    outputs: outputs/pdf2markdown
    visualize: True
    merge2markdown: True
    tasks:
        layout_detection:
            model: layout_detection_yolo
            model_config:
                img_size: 1024
                conf_thres: 0.25
                iou_thres: 0.45
                model_path: models/Layout/YOLO/doclayout_yolo_ft.pt
        formula_detection:
            model: formula_detection_yolo
            model_config:
                img_size: 1280
                conf_thres: 0.25
                iou_thres: 0.45
                batch_size: 1
                model_path: models/MFD/YOLO/yolo_v8_ft.pt
        formula_recognition:
            model: formula_recognition_unimernet
            model_config:
                batch_size: 128
                cfg_path: pdf_extract_kit/configs/unimernet.yaml
                model_path: models/MFR/unimernet_tiny
        ocr:
            model: ocr_ppocr
            model_config:
                lang: ch
                show_log: True
                det_model_dir: models/OCR/PaddleOCR/det/ch_PP-OCRv4_det
                rec_model_dir: models/OCR/PaddleOCR/rec/ch_PP-OCRv4_rec
                det_db_box_thresh: 0.3

- inputs/outputs: 分别定义输入文件路径和输出路径
- visualize: 是否对模型结果进行可视化,可视化结果会保存在outputs目录下。
- merge2markdown: 是否将结果合并为markdown文档,这里只支持简单的单栏文本从上往下进行拼接,更复杂布局文档的markdown转换请参考 `MinerU <https://github.com/opendatalab/MinerU>`_
- tasks: 定义任务类型,PDF文档提取包含了布局检测、公式检测、公式识别、OCR等任务
- 具体每个任务和模型的参数含义请参考各任务的教程文档


多样化输入支持
--------------------

PDF文档内容提取支持 ``单个图像/PDF文件`` 、 ``包含图像/PDF文件的目录`` 等输入形式。


输出结果
--------------------

PDF文档提取的结果以json形式保存在 ``outputs`` 路径下,json的格式如下所示:

.. code:: json

    [
        {
            "layout_dets": [
                {
                    "category_type": "text",
                    "poly": [
                        380.6792698635707,
                        159.85058512958923,
                        765.1419999999998,
                        159.85058512958923,
                        765.1419999999998,
                        192.51073013642917,
                        380.6792698635707,
                        192.51073013642917
                    ],
                    "text": "this is an example text",
                    "score": 0.97
                },
                ...
            ], 
            "page_info": {
                "page_no": 0,
                "height": 2339,
                "width": 1654,
            }
        },
        ...
    ]

- layout_dets: 单页PDF或图片的内容提取结果
- category_type: 单个内容块的所属内别,比如标题、图片、行内公式等等
- poly: 单个内容块的位置坐标
- text: 该文本块的文本内容
- score: 检测的置信度
- page_info: 页面信息,包含页码和页面尺寸
- page_no: 页码,从0开始计数
- height: 页面尺寸: 高
- width: 页面尺寸: 宽

如果 ``merge2markdown`` 参数为True的话,则会额外保存一个markdown文件。

================================================
FILE: docs/zh_cn/project/speed_up.rst
================================================
=================
模型加速项目
=================

Comming soon!

================================================
FILE: docs/zh_cn/switch_language.md
================================================
## <a href='https://pdf-extract-kit.readthedocs.io/en/latest/'>English</a>

## <a href='https://pdf-extract-kit.readthedocs.io/zh_CN/latest/'>简体中文</a>


================================================
FILE: docs/zh_cn/task_extend/code.rst
================================================
==================================
代码实现
==================================

PDF-Extract-Kit项目的核心代码实现在pdf_extract_kit目录下,该路径下包含下述几个模块:

- configs: 特定模块的配置文件,如 ``pdf_extract_kit/configs/unimernet.yaml`` ,如果本身配置简单,建议放在 ``repo_root/configs`` 的 ``yaml`` 文件中的 ``model_config`` 里进行定义,方便用户修改。

- dataset: 自定义的 ``ImageDataset`` 类,用于加载和预处理图像数据。它支持多种输入类型,并且可以对图像进行统一的预处理操作(如调整大小、转换为张量等),以便于后续的模型推理加速。

- evaluation: 模型结果评测模块,支持多种任务类型评测,如 ``布局检测`` 、 ``公式检测`` 、 ``公式识别`` 等等,方便用户对不同任务、不同模型进行公平对比。

- registry: ``Registry`` 类是一个通用的注册表类,提供了注册、获取和列出注册项的功能。用户可以使用该类创建不同类型的注册表,例如任务注册表、模型注册表等。

- tasks: 最核心的任务模块,包含了许多不同类型的任务,如 ``布局检测`` 、 ``公式检测`` 、 ``公式识别`` 等等,用户添加新任务和新模型一般仅需要在这里进行代码添加。


.. note::
    基于上述的模块化设计,用户拓展新模块一般只需要在tasks里实现自己的新任务类及对应模型(更多情况下仅需要实现对应模型,任务已经定义好),然后在registry里注册即可。


下面我们以添加基于 ``YOLO``的 ``布局检测`` 模型为例,介绍如何添加新任务和新模型.

任务定义及注册
==============

首先我们在 ``tasks`` 下添加一个 ``layout_detection`` 目录,然后在该目录下添加一个 ``task.py`` 文件用于定义布局检测任务类,具体如下:

.. code-block:: python

    from pdf_extract_kit.registry.registry import TASK_REGISTRY
    from pdf_extract_kit.tasks.base_task import BaseTask


    @TASK_REGISTRY.register("layout_detection")
    class LayoutDetectionTask(BaseTask):
        def __init__(self, model):
            super().__init__(model)

        def predict_images(self, input_data, result_path):
            """
            Predict layouts in images.

            Args:
                input_data (str): Path to a single image file or a directory containing image files.
                result_path (str): Path to save the prediction results.

            Returns:
                list: List of prediction results.
            """
            images = self.load_images(input_data)
            # Perform detection
            return self.model.predict(images, result_path)

        def predict_pdfs(self, input_data, result_path):
            """
            Predict layouts in PDF files.

            Args:
                input_data (str): Path to a single PDF file or a directory containing PDF files.
                result_path (str): Path to save the prediction results.

            Returns:
                list: List of prediction results.
            """
            pdf_images = self.load_pdf_images(input_data)
            # Perform detection
            return self.model.predict(list(pdf_images.values()), result_path, list(pdf_images.keys()))

可以看到,任务定义包含下面几个要点:

* 使用 ``@TASK_REGISTRY.register("layout_detection")`` 语法直接将布局任务类注册到 ``TASK_REGISTRY`` 下 ;
* ``__init__`` 初始化函数传入 ``model`` , 具体参考 ``BaseTask`` 类
* 实现推理函数,这里考虑到布局检测通常会处理图像类及PDF文件,所以提供了两个函数 ``predict_images`` 和 ``predict_pdfs`` ,方便用户灵活选择。

模型定义及注册
==============

接下来我们实现具体模型,在task下面新建models目录,并添加yolo.py用于YOLO模型定义,具体定义如下:

.. code-block:: python

    import os
    import cv2
    import torch
    from torch.utils.data import DataLoader, Dataset
    from ultralytics import YOLO
    from pdf_extract_kit.registry import MODEL_REGISTRY
    from pdf_extract_kit.utils.visualization import  visualize_bbox
    from pdf_extract_kit.dataset.dataset import ImageDataset
    import torchvision.transforms as transforms


    @MODEL_REGISTRY.register('layout_detection_yolo')
    class LayoutDetectionYOLO:
        def __init__(self, config):
            """
            Initialize the LayoutDetectionYOLO class.

            Args:
                config (dict): Configuration dictionary containing model parameters.
            """
            # Mapping from class IDs to class names
            self.id_to_names = {
                0: 'title', 
                1: 'plain text',
                2: 'abandon', 
                3: 'figure', 
                4: 'figure_caption', 
                5: 'table', 
                6: 'table_caption', 
                7: 'table_footnote', 
                8: 'isolate_formula', 
                9: 'formula_caption'
            }

            # Load the YOLO model from the specified path
            self.model = YOLO(config['model_path'])

            # Set model parameters
            self.img_size = config.get('img_size', 1280)
            self.pdf_dpi = config.get('pdf_dpi', 200)
            self.conf_thres = config.get('conf_thres', 0.25)
            self.iou_thres = config.get('iou_thres', 0.45)
            self.visualize = config.get('visualize', False)
            self.device = config.get('device', 'cuda' if torch.cuda.is_available() else 'cpu')
            self.batch_size = config.get('batch_size', 1)

        def predict(self, images, result_path, image_ids=None):
            """
            Predict layouts in images.

            Args:
                images (list): List of images to be predicted.
                result_path (str): Path to save the prediction results.
                image_ids (list, optional): List of image IDs corresponding to the images.

            Returns:
                list: List of prediction results.
            """
            results = []
            for idx, image in enumerate(images):
                result = self.model.predict(image, imgsz=self.img_size, conf=self.conf_thres, iou=self.iou_thres, verbose=False)[0]
                if self.visualize:
                    if not os.path.exists(result_path):
                        os.makedirs(result_path)
                    boxes = result.__dict__['boxes'].xyxy
                    classes = result.__dict__['boxes'].cls
                    vis_result = visualize_bbox(image, boxes, classes, self.id_to_names)

                    # Determine the base name of the image
                    if image_ids:
                        base_name = image_ids[idx]
                    else:
                        base_name = os.path.basename(image)
                    
                    result_name = f"{base_name}_MFD.png"
                    
                    # Save the visualized result                
                    cv2.imwrite(os.path.join(result_path, result_name), vis_result)
                results.append(result)
            return results


可以看到,模型定义包含下面几个要点:

* 使用 ``@MODEL_REGISTRY.register('layout_detection_yolo')`` 语法直接将yolo布局模型注册到 ``MODEL_REGISTRY`` 下;
* 初始化函数需要实现:
    + id_to_names的类别映射,用于可视化展示
    + 模型参数配置
    + 模型初始化
* 模型推理函数需要实现多种类型的模型推理:这里支持图像列表和PIL.Image类,可以方便用户直接基于图像路径或者图像流进行推理。

实现上述类定义后,将 ``LayoutDetectionYOLO`` 添加到 ``layout_detection`` 任务下 ``__init__.py`` 的 ``__all__`` 中即可。

.. code-block:: python

    from pdf_extract_kit.tasks.layout_detection.models.yolo import LayoutDetectionYOLO
    from pdf_extract_kit.registry.registry import MODEL_REGISTRY


    __all__ = [
        "LayoutDetectionYOLO",
    ]


.. note:: 
    对于同一个任务,我们支持多种模型,用户具体选择哪个可以根据评测结果进行选择,结合模型 ``精度`` 、 ``速度`` 和 ``场景适配程度`` 进行选择。


实现了任务和模型后,可以在 repo_root/scripts下添加脚本程序 ``layout_detection.py``

示例脚本
==============

.. code-block:: python

    import os
    import sys
    import os.path as osp
    import argparse

    sys.path.append(osp.join(os.path.dirname(os.path.abspath(__file__)), '..'))
    from pdf_extract_kit.utils.config_loader import load_config, initialize_tasks_and_models
    import pdf_extract_kit.tasks  # 确保所有任务模块被导入

    TASK_NAME = 'layout_detection'


    def parse_args():
        parser = argparse.ArgumentParser(description="Run a task with a given configuration file.")
        parser.add_argument('--config', type=str, required=True, help='Path to the configuration file.')
        return parser.parse_args()

    def main(config_path):
        config = load_config(config_path)
        task_instances = initialize_tasks_and_models(config)

        # get input and output path from config
        input_data = config.get('inputs', None)
        result_path = config.get('outputs', 'outputs'+'/'+TASK_NAME)

        # layout_detection_task
        model_layout_detection = task_instances[TASK_NAME]

        # for image detection
        detection_results = model_layout_detection.predict_images(input_data, result_path)

        # for pdf detection
        # detection_results = model_layout_detection.predict_pdfs(input_data, result_path)

        # print(detection_results)
        print(f'The predicted results can be found at {result_path}')


    if __name__ == "__main__":
        args = parse_args()
        main(args.config)

支持类型拓展
==============


批处理拓展
==============


================================================
FILE: docs/zh_cn/task_extend/doc.rst
================================================
==================================
文档补充
==================================

在实现新的任务和模块后,需要在文档中补充相关内容,以便用户了解如何使用。

具体可以参考布局检测任务使用文档:\ :ref:`布局检测算法 <algorithm_layout_detection>` 


主要补充下述几个部分:

* 任务简介  
* 模型使用方式  
* 配置文件解释  
* 多样化输入支持(如果有)  
* 可视化结果查看  

================================================
FILE: docs/zh_cn/task_extend/evaluation.rst
================================================
==================================
模型评测
==================================

Comming soon!

================================================
FILE: pdf_extract_kit/__init__.py
================================================
import os
import sys

current_dir = os.path.dirname(os.path.abspath(__file__))

root_dir = os.path.abspath(os.path.join(current_dir, '..'))

if root_dir not in sys.path:
    sys.path.insert(0, root_dir)

================================================
FILE: pdf_extract_kit/configs/unimernet.yaml
================================================
model:
  arch: unimernet
  model_type: unimernet
  model_config:
    model_name: ./models/unimernet_tiny
    max_seq_len: 1536

  load_pretrained: True
  pretrained: './models/unimernet_tiny/pytorch_model.pth'
  tokenizer_config:
    path: ./models/unimernet_tiny

datasets:
  formula_rec_eval:
    vis_processor:
      eval:
        name: "formula_image_eval"
        image_size:
          - 192
          - 672
   
run:
  runner: runner_iter
  task: unimernet_train

  batch_size_train: 64
  batch_size_eval: 64
  num_workers: 1

  iters_per_inner_epoch: 2000
  max_iters: 60000

  seed: 42
  output_dir: "../output/demo"

  evaluate: True
  test_splits: [ "eval" ]

  device: "cuda"
  world_size: 1
  dist_url: "env://"
  distributed: True
  distributed_type: ddp  # or fsdp when train llm

  generate_cfg:
    temperature: 0.0

================================================
FILE: pdf_extract_kit/dataset/__init__.py
================================================


================================================
FILE: pdf_extract_kit/dataset/dataset.py
================================================
import numpy as np
import torch
from PIL import Image
from torch.utils.data import Dataset
import torchvision.transforms as transforms


class ResizeLongestSide:
    def __init__(self, size):
        self.size = size

    def __call__(self, img):
        # Get the original dimensions
        width, height = img.size
        # Determine the scaling factor
        if width > height:
            new_width = self.size
            new_height = int(height * (self.size / float(width)))
        else:
            new_height = self.size
            new_width = int(width * (self.size / float(height)))
        # Resize the image
        return img.resize((new_width, new_height), Image.BILINEAR)


class ImageDataset(Dataset):
    def __init__(self, images, image_ids=None, img_size=1280):
        """
        Initialize the ImageDataset class.
        
        Args:
        - images (list): List of image paths or PIL.Image.Image objects.
        - image_ids (list, optional): List of corresponding image IDs. If None, assumes images are paths.
        - img_size (int): Size to which images' longest side will be resized.
        """
        self.images = images
        self.image_ids = image_ids if image_ids is not None else images
        self.img_size = img_size
        self.transform = transforms.Compose([
            ResizeLongestSide(self.img_size),
            transforms.ToTensor()
        ])

    def __len__(self):
        """
        Return the size of the dataset.
        
        Returns:
        int: Number of images in the dataset.
        """
        return len(self.images)

    def __getitem__(self, idx):
        """
        Get an image and its corresponding ID by index.
        
        Args:
        - idx (int): Index of the image to retrieve.
        
        Returns:
        tuple: Transformed image tensor and corresponding image ID.
        """
        image = self.images[idx]
        image_id = self.image_ids[idx]

        # Check if the image is a path or a PIL.Image object
        if isinstance(image, str):
            image = Image.open(image).convert('RGB')
        elif isinstance(image, Image.Image):
            image = image.convert('RGB')
        else:
            raise ValueError("Image must be a file path or a PIL.Image object")

        # Apply transformations
        image = self.transform(image)

        return image, image_id
    
    
class MathDataset(Dataset):
    def __init__(self, image_paths, transform=None):
        self.image_paths = image_paths
        self.transform = transform

    def __len__(self):
        return len(self.image_paths)

    def __getitem__(self, idx):
        # if not pil image, then convert to pil image
        if isinstance(self.image_paths[idx], str):
            raw_image = Image.open(self.image_paths[idx])
        else:
            raw_image = self.image_paths[idx]
        if self.transform:
            image = self.transform(raw_image)
        return image


================================================
FILE: pdf_extract_kit/registry/__init__.py
================================================
from .registry import TASK_REGISTRY, MODEL_REGISTRY

================================================
FILE: pdf_extract_kit/registry/registry.py
================================================
class Registry:
    def __init__(self):
        self._registry = {}

    def register(self, name):
        def decorator(item):
            if name in self._registry:
                raise ValueError(f"Item {name} already registered.")
            self._registry[name] = item
            return item
        return decorator

    def get(self, name):
        if name not in self._registry:
            raise ValueError(f"Item {name} not found in registry.")
        return self._registry[name]

    def list_items(self):
        return list(self._registry.keys())

# Create global registries for tasks and models
TASK_REGISTRY = Registry()
MODEL_REGISTRY = Registry()

================================================
FILE: pdf_extract_kit/tasks/__init__.py
================================================
from pdf_extract_kit.tasks.base_task import BaseTask
from pdf_extract_kit.tasks.formula_detection.task import FormulaDetectionTask
from pdf_extract_kit.tasks.formula_recognition.task import FormulaRecognitionTask
from pdf_extract_kit.tasks.layout_detection.task import LayoutDetectionTask
from pdf_extract_kit.tasks.ocr.task import OCRTask
from pdf_extract_kit.tasks.table_parsing.task import TableParsingTask

from pdf_extract_kit.registry.registry import TASK_REGISTRY

__all__ = [
    "BaseTask",
    "LayoutDetectionTask",
    "FormulaRecognitionTask",
    "LayoutDetectionTask",
    "OCRTask",
    "TableParsingTask",
]

def load_task(name, cfg=None):
    """
    Example

    >>> task = load_task("formula_detection", cfg=None)
    """
    task_class = TASK_REGISTRY.get(name)
    task_instance = task_class(cfg)

    return task_instance


================================================
FILE: pdf_extract_kit/tasks/base_task.py
================================================
import os
from pdf_extract_kit.utils.data_preprocess import load_pdf


class BaseTask:
    def __init__(self, model):
        self.model = model

    def load_images(self, input_data):
        """
        Loads images from a single image path or a directory containing multiple images.

        Args:
            input_data (str): Path to a single image file or a directory containing image files.

        Returns:
            list: List of paths to all images to be predicted.
        """
        images = []

        if os.path.isdir(input_data):
            # If input_data is a directory, check for nested directories
            for root, dirs, files in os.walk(input_data):
                if dirs:
                    raise ValueError("Input directory should not contain nested directories: {}".format(input_data))
                for file in files:
                    if file.lower().endswith(('.png', '.jpg', '.jpeg')):
                        image_path = os.path.join(root, file)
                        images.append(image_path)
                images = sorted(images)
                break  # Only process the top-level directory
        else:
            # Determine the type of input data and process accordingly
            if input_data.lower().endswith(('.png', '.jpg', '.jpeg')):
                # If input is a single image file
                images = [input_data]
            else:
                raise ValueError("Unsupported input data format: {}".format(input_data))

        return images

    def load_pdf_images(self, input_data):
        """
        Loads images from a single PDF file or directory containing multiple PDF files.

        Args:
            input_data (str): Path to a single PDF file or a directory containing PDF files.

        Returns:
            dict: Dictionary with image IDs (formed by PDF path and page number) as keys and corresponding PIL.Image objects as values.
                  Note: Loading multiple PDFs at once is not recommended due to high memory consumption. Consider processing one PDF at a time externally using loops or multithreading.
        """
        pdf_images = {}

        if os.path.isdir(input_data):
            # If input_data is a directory, check for nested directories
            for root, dirs, files in os.walk(input_data):
                if dirs:
                    raise ValueError("Input directory should not contain nested directories: {}".format(input_data))
                for file in files:
                    if file.lower().endswith(('.pdf')):
                        pdf_path = os.path.join(root, file)
                        images = load_pdf(pdf_path)
                        for i, img in enumerate(images):
                            img_id = f"{os.path.splitext(file)[0]}_page_{i+1:04d}"
                            pdf_images[img_id] = img
                # images = sorted(images)
                break  # Only process the top-level directory
        else:
            # Determine the type of input data and process accordingly
            if input_data.lower().endswith(('.pdf')):
                # If input is a single image file
                images = load_pdf(input_data)
                for i, img in enumerate(images):
                    img_id = f"{os.path.splitext(os.path.basename(input_data))[0]}_page_{i+1:04d}"
                    pdf_images[img_id] = img
            else:
                raise ValueError("Unsupported input data format: {}".format(input_data))

        return pdf_images

================================================
FILE: pdf_extract_kit/tasks/formula_detection/__init__.py
================================================
from pdf_extract_kit.tasks.formula_detection.models.yolo import FormulaDetectionYOLO

from pdf_extract_kit.registry.registry import MODEL_REGISTRY

__all__ = [
    "FurmulaDetectionYOLO",
]


================================================
FILE: pdf_extract_kit/tasks/formula_detection/models/yolo.py
================================================
import os
import cv2
import torch
from torch.utils.data import DataLoader, Dataset
from ultralytics import YOLO
from pdf_extract_kit.registry import MODEL_REGISTRY
from pdf_extract_kit.utils.visualization import visualize_bbox
from pdf_extract_kit.dataset.dataset import ImageDataset
import torchvision.transforms as transforms


@MODEL_REGISTRY.register('formula_detection_yolo')
class FormulaDetectionYOLO:
    def __init__(self, config):
        """
        Initialize the FormulaDetectionYOLO class.

        Args:
            config (dict): Configuration dictionary containing model parameters.
        """
        # Mapping from class IDs to class names
        self.id_to_names = {
            0: 'inline',
            1: 'isolated'
        }

        # Load the YOLO model from the specified path
        self.model = YOLO(config['model_path'])

        # Set model parameters
        self.img_size = config.get('img_size', 1280)
        self.pdf_dpi = config.get('pdf_dpi', 200)
        self.conf_thres = config.get('conf_thres', 0.25)
        self.iou_thres = config.get('iou_thres', 0.45)
        self.visualize = config.get('visualize', False)
        self.device = config.get('device', 'cuda' if torch.cuda.is_available() else 'cpu')
        self.batch_size = config.get('batch_size', 1)

    def predict(self, images, result_path, image_ids=None):
        """
        Predict formulas in images.

        Args:
            images (list): List of images to be predicted.
            result_path (str): Path to save the prediction results.
            image_ids (list, optional): List of image IDs corresponding to the images.

        Returns:
            list: List of prediction results.
        """
        results = []
        for idx, image in enumerate(images):
            result = self.model.predict(image, imgsz=self.img_size, conf=self.conf_thres, iou=self.iou_thres, verbose=False)[0]
            if self.visualize:
                if not os.path.exists(result_path):
                    os.makedirs(result_path)
                boxes = result.__dict__['boxes'].xyxy
                classes = result.__dict__['boxes'].cls
                scores = result.__dict__['boxes'].conf
                
                vis_result = visualize_bbox(image, boxes, classes, scores, self.id_to_names)

                # Determine the base name of the image
                if image_ids:
                    base_name = image_ids[idx]
                else:
                    # base_name = os.path.basename(image)                    
                    base_name = os.path.splitext(os.path.basename(image))[0]  # Remove file extension

                
                result_name = f"{base_name}_MFD.png"
                
                # Save the visualized result                
                cv2.imwrite(os.path.join(result_path, result_name), vis_result)
            results.append(result)
        return results

================================================
FILE: pdf_extract_kit/tasks/formula_detection/task.py
================================================
from pdf_extract_kit.registry.registry import TASK_REGISTRY
from pdf_extract_kit.tasks.base_task import BaseTask

@TASK_REGISTRY.register("formula_detection")
class FormulaDetectionTask(BaseTask):
    def __init__(self, model):
        super().__init__(model)

    def predict_images(self, input_data, result_path):
        """
        Predict formulas in images.

        Args:
            input_data (str): Path to a single image file or a directory containing image files.
            result_path (str): Path to save the prediction results.

        Returns:
            list: List of prediction results.
        """
        images = self.load_images(input_data)
        # Perform detection
        return self.model.predict(images, result_path)

    def predict_pdfs(self, input_data, result_path):
        """
        Predict formulas in PDF files.

        Args:
            input_data (str): Path to a single PDF file or a directory containing PDF files.
            result_path (str): Path to save the prediction results.

        Returns:
            list: List of prediction results.
        """
        pdf_images = self.load_pdf_images(input_data)
        # Perform detection
        return self.model.predict(list(pdf_images.values()), result_path, list(pdf_images.keys()))

================================================
FILE: pdf_extract_kit/tasks/formula_recognition/__init__.py
================================================
from pdf_extract_kit.tasks.formula_recognition.models.unimernet import FormulaRecognitionUniMERNet

from pdf_extract_kit.registry.registry import MODEL_REGISTRY

__all__ = [
    "FurmulaRecognitionUniMERNet",
]


================================================
FILE: pdf_extract_kit/tasks/formula_recognition/models/unimernet.py
================================================
import os
import logging
import argparse

import cv2
import torch
import numpy as np
from PIL import Image
import unimernet.tasks as tasks
from unimernet.common.config import Config
from unimernet.processors import load_processor

from pdf_extract_kit.registry import MODEL_REGISTRY


@MODEL_REGISTRY.register('formula_recognition_unimernet')
class FormulaRecognitionUniMERNet:
    def __init__(self, config):
        """
        Initialize the FormulaRecognitionUniMERNet class.

        Args:
            config (dict): Configuration dictionary containing model parameters.
        """
        self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        self.model_dir = config['model_path']
        self.cfg_path = config.get('cfg_path', "pdf_extract_kit/configs/unimernet.yaml")
        self.batch_size = config.get('batch_size', 1)

        # Load the UniMERNet model
        self.model, self.vis_processor = self.load_model_and_processor()

    def load_model_and_processor(self):
        try:
            args = argparse.Namespace(cfg_path=self.cfg_path, options=None)
            cfg = Config(args)
            cfg.config.model.pretrained = os.path.join(self.model_dir, "pytorch_model.pth")
            cfg.config.model.model_config.model_name = self.model_dir
            cfg.config.model.tokenizer_config.path = self.model_dir
            task = tasks.setup_task(cfg)
            model = task.build_model(cfg).to(self.device)
            vis_processor = load_processor('formula_image_eval', cfg.config.datasets.formula_rec_eval.vis_processor.eval)
            return model, vis_processor
        except Exception as e:
            logging.error(f"Error loading model and processor: {e}")
            raise
    
    def predict(self, images, result_path):
        results = []
        for image_path in images:
            # Read the image using OpenCV
            open_cv_image = cv2.imread(image_path)
            if open_cv_image is None:
                logging.error(f"Error: Unable to open image at {image_path}")
                continue
            # Convert the OpenCV image to PIL.Image format
            raw_image = Image.fromarray(cv2.cvtColor(open_cv_image, cv2.COLOR_BGR2RGB))

            try:
                # Process the image using the visual processor and prepare it for the model
                image = self.vis_processor(raw_image).unsqueeze(0).to(self.device)

                # Generate the prediction using the model
                output = self.model.generate({"image": image})
                pred = output["pred_str"][0]
                logging.info(f'Prediction for {image_path}:\n{pred}')

                # cv2.imshow('Original Image', open_cv_image)
                # cv2.waitKey(0)
                # cv2.destroyAllWindows()

                results.append(pred)
            except Exception as e:
                logging.error(f"Error processing image {image_path}: {e}")
    
        return results

================================================
FILE: pdf_extract_kit/tasks/formula_recognition/task.py
================================================
from pdf_extract_kit.registry.registry import TASK_REGISTRY
from pdf_extract_kit.tasks.base_task import BaseTask


@TASK_REGISTRY.register("formula_recognition")
class FormulaRecognitionTask(BaseTask):
    def __init__(self, model):
        super().__init__(model)

    def predict(self, input_data, result_path, bboxes=None):
        images = self.load_images(input_data)
        # Perform recognition
        return self.model.predict(images, result_path)

================================================
FILE: pdf_extract_kit/tasks/layout_detection/__init__.py
================================================
from pdf_extract_kit.tasks.layout_detection.models.yolo import LayoutDetectionYOLO
# from pdf_extract_kit.tasks.layout_detection.models.layoutlmv3 import LayoutDetectionLayoutlmv3
from pdf_extract_kit.registry.registry import MODEL_REGISTRY


__all__ = [
    "LayoutDetectionYOLO",
    # "LayoutDetectionLayoutlmv3",
]


================================================
FILE: pdf_extract_kit/tasks/layout_detection/models/__init__.py
================================================


================================================
FILE: pdf_extract_kit/tasks/layout_detection/models/layoutlmv3.py
================================================
import os
import cv2
import numpy as np
from PIL import Image

from pdf_extract_kit.registry.registry import MODEL_REGISTRY
from pdf_extract_kit.utils.visualization import visualize_bbox

from .layoutlmv3_util.model_init import Layoutlmv3_Predictor

@MODEL_REGISTRY.register("layout_detection_layoutlmv3")
class LayoutDetectionLayoutlmv3:
    def __init__(self, config):
        """
        Initialize the LayoutDetectionYOLO class.

        Args:
            config (dict): Configuration dictionary containing model parameters.
        """
        # Mapping from class IDs to class names
        self.id_to_names = {
            0: 'title', 
            1: 'plain text',
            2: 'abandon', 
            3: 'figure', 
            4: 'figure_caption', 
            5: 'table', 
            6: 'table_caption', 
            7: 'table_footnote', 
            8: 'isolate_formula', 
            9: 'formula_caption'
        }
        self.model = Layoutlmv3_Predictor(config.get('model_path', None))
        self.visualize = config.get('visualize', False)

    def predict(self, images, result_path, image_ids=None):
        """
        Predict layouts in images.

        Args:
            images (list): List of images to be predicted.
            result_path (str): Path to save the prediction results.
            image_ids (list, optional): List of image IDs corresponding to the images.

        Returns:
            list: List of prediction results.
        """
        if not os.path.exists(result_path):
            os.makedirs(result_path)
        
        results = []
        for idx, im_file in enumerate(images):
            if isinstance(im_file, Image.Image):
                im = im_file.convert("RGB")  # extracted PDF pages
            elif isinstance(im_file, str):
                im = Image.open(im_file).convert("RGB")  # image path
            layout_res = self.model(np.array(im), ignore_catids=[])
            poly = np.array([det["poly"] for det in layout_res["layout_dets"]])
            boxes = poly[:, [0,1,4,5]] 
            scores = np.array([det["score"] for det in layout_res["layout_dets"]])
            classes = np.array([det["category_id"] for det in layout_res["layout_dets"]])
            
            if self.visualize:
                vis_result = visualize_bbox(im_file, boxes, classes, scores, self.id_to_names)
                # Determine the base name of the image
                if image_ids:
                    base_name = image_ids[idx]
                else:
                    base_name = os.path.splitext(os.path.basename(im_file))[0]  # Remove file extension
                result_name = f"{base_name}_layout.png"
                # Save the visualized result                
                cv2.imwrite(os.path.join(result_path, result_name), vis_result)

            # append result
            results.append({
                "im_path": im_file,
                "boxes": boxes,
                "scores": scores,
                "classes": classes,
            })
        return results


================================================
FILE: pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/backbone.py
================================================
# --------------------------------------------------------------------------------
# VIT: Multi-Path Vision Transformer for Dense Prediction
# Copyright (c) 2022 Electronics and Telecommunications Research Institute (ETRI).
# All Rights Reserved.
# Written by Youngwan Lee
# This source code is licensed(Dual License(GPL3.0 & Commercial)) under the license found in the
# LICENSE file in the root directory of this source tree.
# --------------------------------------------------------------------------------
# References:
# timm: https://github.com/rwightman/pytorch-image-models/tree/master/timm
# CoaT: https://github.com/mlpc-ucsd/CoaT
# --------------------------------------------------------------------------------


import torch

from detectron2.layers import (
    ShapeSpec,
)
from detectron2.modeling import Backbone, BACKBONE_REGISTRY, FPN
from detectron2.modeling.backbone.fpn import LastLevelP6P7, LastLevelMaxPool

from .beit import beit_base_patch16, dit_base_patch16, dit_large_patch16, beit_large_patch16
from .deit import deit_base_patch16, mae_base_patch16
from .layoutlmft.models.layoutlmv3 import LayoutLMv3Model
from transformers import AutoConfig

__all__ = [
    "build_vit_fpn_backbone",
]


class VIT_Backbone(Backbone):
    """
    Implement VIT backbone.
    """

    def __init__(self, name, out_features, drop_path, img_size, pos_type, model_kwargs,
                 config_path=None, image_only=False, cfg=None):
        super().__init__()
        self._out_features = out_features
        if 'base' in name:
            self._out_feature_strides = {"layer3": 4, "layer5": 8, "layer7": 16, "layer11": 32}
            self._out_feature_channels = {"layer3": 768, "layer5": 768, "layer7": 768, "layer11": 768}
        else:
            self._out_feature_strides = {"layer7": 4, "layer11": 8, "layer15": 16, "layer23": 32}
            self._out_feature_channels = {"layer7": 1024, "layer11": 1024, "layer15": 1024, "layer23": 1024}

        if name == 'beit_base_patch16':
            model_func = beit_base_patch16
        elif name == 'dit_base_patch16':
            model_func = dit_base_patch16
        elif name == "deit_base_patch16":
            model_func = deit_base_patch16
        elif name == "mae_base_patch16":
            model_func = mae_base_patch16
        elif name == "dit_large_patch16":
            model_func = dit_large_patch16
        elif name == "beit_large_patch16":
            model_func = beit_large_patch16

        if 'beit' in name or 'dit' in name:
            if pos_type == "abs":
                self.backbone = model_func(img_size=img_size,
                                           out_features=out_features,
                                           drop_path_rate=drop_path,
                                           use_abs_pos_emb=True,
                                           **model_kwargs)
            elif pos_type == "shared_rel":
                self.backbone = model_func(img_size=img_size,
                                           out_features=out_features,
                                           drop_path_rate=drop_path,
                                           use_shared_rel_pos_bias=True,
                                           **model_kwargs)
            elif pos_type == "rel":
                self.backbone = model_func(img_size=img_size,
                                           out_features=out_features,
                                           drop_path_rate=drop_path,
                                           use_rel_pos_bias=True,
                                           **model_kwargs)
            else:
                raise ValueError()
        elif "layoutlmv3" in name:
            config = AutoConfig.from_pretrained(config_path)
            # disable relative bias as DiT
            config.has_spatial_attention_bias = False
            config.has_relative_attention_bias = False
            self.backbone = LayoutLMv3Model(config, detection=True,
                                               out_features=out_features, image_only=image_only)
        else:
            self.backbone = model_func(img_size=img_size,
                                       out_features=out_features,
                                       drop_path_rate=drop_path,
                                       **model_kwargs)
        self.name = name

    def forward(self, x):
        """
        Args:
            x: Tensor of shape (N,C,H,W). H, W must be a multiple of ``self.size_divisibility``.

        Returns:
            dict[str->Tensor]: names and the corresponding features
        """
        if "layoutlmv3" in self.name:
            return self.backbone.forward(
                input_ids=x["input_ids"] if "input_ids" in x else None,
                bbox=x["bbox"] if "bbox" in x else None,
                images=x["images"] if "images" in x else None,
                attention_mask=x["attention_mask"] if "attention_mask" in x else None,
                # output_hidden_states=True,
            )
        assert x.dim() == 4, f"VIT takes an input of shape (N, C, H, W). Got {x.shape} instead!"
        return self.backbone.forward_features(x)

    def output_shape(self):
        return {
            name: ShapeSpec(
                channels=self._out_feature_channels[name], stride=self._out_feature_strides[name]
            )
            for name in self._out_features
        }


def build_VIT_backbone(cfg):
    """
    Create a VIT instance from config.

    Args:
        cfg: a detectron2 CfgNode

    Returns:
        A VIT backbone instance.
    """
    # fmt: off
    name = cfg.MODEL.VIT.NAME
    out_features = cfg.MODEL.VIT.OUT_FEATURES
    drop_path = cfg.MODEL.VIT.DROP_PATH
    img_size = cfg.MODEL.VIT.IMG_SIZE
    pos_type = cfg.MODEL.VIT.POS_TYPE

    model_kwargs = eval(str(cfg.MODEL.VIT.MODEL_KWARGS).replace("`", ""))

    if 'layoutlmv3' in name:
        if cfg.MODEL.CONFIG_PATH != '':
            config_path = cfg.MODEL.CONFIG_PATH
        else:
            config_path = cfg.MODEL.WEIGHTS.replace('pytorch_model.bin', '')  # layoutlmv3 pre-trained models
            config_path = config_path.replace('model_final.pth', '')  # detection fine-tuned models
    else:
        config_path = None

    return VIT_Backbone(name, out_features, drop_path, img_size, pos_type, model_kwargs,
                        config_path=config_path, image_only=cfg.MODEL.IMAGE_ONLY, cfg=cfg)


@BACKBONE_REGISTRY.register()
def build_vit_fpn_backbone(cfg, input_shape: ShapeSpec):
    """
    Create a VIT w/ FPN backbone.

    Args:
        cfg: a detectron2 CfgNode

    Returns:
        backbone (Backbone): backbone module, must be a subclass of :class:`Backbone`.
    """
    bottom_up = build_VIT_backbone(cfg)
    in_features = cfg.MODEL.FPN.IN_FEATURES
    out_channels = cfg.MODEL.FPN.OUT_CHANNELS
    backbone = FPN(
        bottom_up=bottom_up,
        in_features=in_features,
        out_channels=out_channels,
        norm=cfg.MODEL.FPN.NORM,
        top_block=LastLevelMaxPool(),
        fuse_type=cfg.MODEL.FPN.FUSE_TYPE,
    )
    return backbone


================================================
FILE: pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/beit.py
================================================
""" Vision Transformer (ViT) in PyTorch

A PyTorch implement of Vision Transformers as described in
'An Image Is Worth 16 x 16 Words: Transformers for Image Recognition at Scale' - https://arxiv.org/abs/2010.11929

The official jax code is released and available at https://github.com/google-research/vision_transformer

Status/TODO:
* Models updated to be compatible with official impl. Args added to support backward compat for old PyTorch weights.
* Weights ported from official jax impl for 384x384 base and small models, 16x16 and 32x32 patches.
* Trained (supervised on ImageNet-1k) my custom 'small' patch model to 77.9, 'base' to 79.4 top-1 with this code.
* Hopefully find time and GPUs for SSL or unsupervised pretraining on OpenImages w/ ImageNet fine-tune in future.

Acknowledgments:
* The paper authors for releasing code and weights, thanks!
* I fixed my class token impl based on Phil Wang's https://github.com/lucidrains/vit-pytorch ... check it out
for some einops/einsum fun
* Simple transformer style inspired by Andrej Karpathy's https://github.com/karpathy/minGPT
* Bert reference code checks against Huggingface Transformers and Tensorflow Bert

Hacked together by / Copyright 2020 Ross Wightman
"""
import warnings
import math
import torch
from functools import partial
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as checkpoint
from timm.models.layers import drop_path, to_2tuple, trunc_normal_


def _cfg(url='', **kwargs):
    return {
        'url': url,
        'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': None,
        'crop_pct': .9, 'interpolation': 'bicubic',
        'mean': (0.5, 0.5, 0.5), 'std': (0.5, 0.5, 0.5),
        **kwargs
    }


class DropPath(nn.Module):
    """Drop paths (Stochastic Depth) per sample  (when applied in main path of residual blocks).
    """

    def __init__(self, drop_prob=None):
        super(DropPath, self).__init__()
        self.drop_prob = drop_prob

    def forward(self, x):
        return drop_path(x, self.drop_prob, self.training)

    def extra_repr(self) -> str:
        return 'p={}'.format(self.drop_prob)


class Mlp(
Download .txt
gitextract_dsl5uwwk/

├── .gitignore
├── .readthedocs.yaml
├── .vscode/
│   └── launch.json
├── LICENSE.md
├── README.md
├── README_zh-CN.md
├── configs/
│   ├── config.yaml
│   ├── formula_detection.yaml
│   ├── formula_recognition.yaml
│   ├── layout_detection.yaml
│   ├── layout_detection_layoutlmv3.yaml
│   ├── layout_detection_yolo.yaml
│   ├── ocr.yaml
│   └── table_parsing.yaml
├── docs/
│   ├── en/
│   │   ├── .readthedocs.yaml
│   │   ├── Makefile
│   │   ├── algorithm/
│   │   │   ├── formula_detection.rst
│   │   │   ├── formula_recognition.rst
│   │   │   ├── layout_detection.rst
│   │   │   ├── ocr.rst
│   │   │   ├── reading_order.rst
│   │   │   └── table_recognition.rst
│   │   ├── conf copy.py
│   │   ├── conf.bak
│   │   ├── conf.py
│   │   ├── evaluation/
│   │   │   ├── formula_detection.rst
│   │   │   ├── formula_recognition.rst
│   │   │   ├── layout_detection.rst
│   │   │   ├── ocr.rst
│   │   │   ├── pdf_extract.rst
│   │   │   ├── reading_order.rst
│   │   │   └── table_recognition.rst
│   │   ├── get_started/
│   │   │   ├── installation.rst
│   │   │   ├── pretrained_model.rst
│   │   │   └── quickstart.rst
│   │   ├── index.rst
│   │   ├── make.bat
│   │   ├── models/
│   │   │   └── supported.md
│   │   ├── notes/
│   │   │   └── changelog.md
│   │   ├── project/
│   │   │   ├── doc_translate.rst
│   │   │   ├── pdf_extract.rst
│   │   │   └── speed_up.rst
│   │   ├── switch_language.md
│   │   └── task_extend/
│   │       ├── code.rst
│   │       ├── doc.rst
│   │       └── evaluation.rst
│   ├── requirements.txt
│   └── zh_cn/
│       ├── .readthedocs.yaml
│       ├── Makefile
│       ├── algorithm/
│       │   ├── formula_detection.rst
│       │   ├── formula_recognition.rst
│       │   ├── layout_detection.rst
│       │   ├── ocr.rst
│       │   ├── reading_order.rst
│       │   └── table_recognition.rst
│       ├── conf.py
│       ├── evaluation/
│       │   ├── formula_detection.rst
│       │   ├── formula_recognition.rst
│       │   ├── layout_detection.rst
│       │   ├── ocr.rst
│       │   ├── pdf_extract.rst
│       │   ├── reading_order.rst
│       │   └── table_recognition.rst
│       ├── get_started/
│       │   ├── installation.rst
│       │   ├── pretrained_model.rst
│       │   └── quickstart.rst
│       ├── index.rst
│       ├── make.bat
│       ├── models/
│       │   └── supported.md
│       ├── notes/
│       │   └── changelog.md
│       ├── project/
│       │   ├── doc_translate.rst
│       │   ├── pdf_extract.rst
│       │   └── speed_up.rst
│       ├── switch_language.md
│       └── task_extend/
│           ├── code.rst
│           ├── doc.rst
│           └── evaluation.rst
├── pdf_extract_kit/
│   ├── __init__.py
│   ├── configs/
│   │   └── unimernet.yaml
│   ├── dataset/
│   │   ├── __init__.py
│   │   └── dataset.py
│   ├── registry/
│   │   ├── __init__.py
│   │   └── registry.py
│   ├── tasks/
│   │   ├── __init__.py
│   │   ├── base_task.py
│   │   ├── formula_detection/
│   │   │   ├── __init__.py
│   │   │   ├── models/
│   │   │   │   └── yolo.py
│   │   │   └── task.py
│   │   ├── formula_recognition/
│   │   │   ├── __init__.py
│   │   │   ├── models/
│   │   │   │   └── unimernet.py
│   │   │   └── task.py
│   │   ├── layout_detection/
│   │   │   ├── __init__.py
│   │   │   ├── models/
│   │   │   │   ├── __init__.py
│   │   │   │   ├── layoutlmv3.py
│   │   │   │   ├── layoutlmv3_util/
│   │   │   │   │   ├── backbone.py
│   │   │   │   │   ├── beit.py
│   │   │   │   │   ├── deit.py
│   │   │   │   │   ├── layoutlmft/
│   │   │   │   │   │   ├── __init__.py
│   │   │   │   │   │   ├── data/
│   │   │   │   │   │   │   ├── __init__.py
│   │   │   │   │   │   │   ├── cord.py
│   │   │   │   │   │   │   ├── data_collator.py
│   │   │   │   │   │   │   ├── funsd.py
│   │   │   │   │   │   │   ├── image_utils.py
│   │   │   │   │   │   │   └── xfund.py
│   │   │   │   │   │   └── models/
│   │   │   │   │   │       ├── __init__.py
│   │   │   │   │   │       └── layoutlmv3/
│   │   │   │   │   │           ├── __init__.py
│   │   │   │   │   │           ├── configuration_layoutlmv3.py
│   │   │   │   │   │           ├── modeling_layoutlmv3.py
│   │   │   │   │   │           ├── tokenization_layoutlmv3.py
│   │   │   │   │   │           └── tokenization_layoutlmv3_fast.py
│   │   │   │   │   ├── layoutlmv3_base_inference.yaml
│   │   │   │   │   ├── model_init.py
│   │   │   │   │   ├── rcnn_vl.py
│   │   │   │   │   └── visualizer.py
│   │   │   │   └── yolo.py
│   │   │   └── task.py
│   │   ├── ocr/
│   │   │   ├── __init__.py
│   │   │   ├── models/
│   │   │   │   └── paddle_ocr.py
│   │   │   └── task.py
│   │   └── table_parsing/
│   │       ├── __init__.py
│   │       ├── models/
│   │       │   └── struct_eqtable.py
│   │       └── task.py
│   ├── utils/
│   │   ├── __init__.py
│   │   ├── config_loader.py
│   │   ├── data_preprocess.py
│   │   ├── merge_blocks_and_spans.py
│   │   ├── pdf_utils.py
│   │   └── visualization.py
│   └── version.py
├── project/
│   └── pdf2markdown/
│       ├── README.md
│       ├── configs/
│       │   └── pdf2markdown.yaml
│       └── scripts/
│           ├── pdf2markdown.py
│           └── run_project.py
├── pyproject.toml
├── requirements/
│   └── docs.txt
├── requirements-cpu.txt
├── requirements.txt
└── scripts/
    ├── formula_detection.py
    ├── formula_recognition.py
    ├── layout_detection.py
    ├── ocr.py
    ├── run_task.py
    └── table_parsing.py
Download .txt
SYMBOL INDEX (364 symbols across 47 files)

FILE: docs/en/conf copy.py
  class MockedClassDocumenter (line 110) | class MockedClassDocumenter(autodoc.ClassDocumenter):
    method add_line (line 113) | def add_line(self, line: str, source: str, *lineno: int) -> None:

FILE: docs/en/conf.py
  function install (line 17) | def install(package):
  class MockedClassDocumenter (line 109) | class MockedClassDocumenter(autodoc.ClassDocumenter):
    method add_line (line 112) | def add_line(self, line: str, source: str, *lineno: int) -> None:

FILE: docs/zh_cn/conf.py
  function install (line 17) | def install(package):
  class MockedClassDocumenter (line 109) | class MockedClassDocumenter(autodoc.ClassDocumenter):
    method add_line (line 112) | def add_line(self, line: str, source: str, *lineno: int) -> None:

FILE: pdf_extract_kit/dataset/dataset.py
  class ResizeLongestSide (line 8) | class ResizeLongestSide:
    method __init__ (line 9) | def __init__(self, size):
    method __call__ (line 12) | def __call__(self, img):
  class ImageDataset (line 26) | class ImageDataset(Dataset):
    method __init__ (line 27) | def __init__(self, images, image_ids=None, img_size=1280):
    method __len__ (line 44) | def __len__(self):
    method __getitem__ (line 53) | def __getitem__(self, idx):
  class MathDataset (line 80) | class MathDataset(Dataset):
    method __init__ (line 81) | def __init__(self, image_paths, transform=None):
    method __len__ (line 85) | def __len__(self):
    method __getitem__ (line 88) | def __getitem__(self, idx):

FILE: pdf_extract_kit/registry/registry.py
  class Registry (line 1) | class Registry:
    method __init__ (line 2) | def __init__(self):
    method register (line 5) | def register(self, name):
    method get (line 13) | def get(self, name):
    method list_items (line 18) | def list_items(self):

FILE: pdf_extract_kit/tasks/__init__.py
  function load_task (line 19) | def load_task(name, cfg=None):

FILE: pdf_extract_kit/tasks/base_task.py
  class BaseTask (line 5) | class BaseTask:
    method __init__ (line 6) | def __init__(self, model):
    method load_images (line 9) | def load_images(self, input_data):
    method load_pdf_images (line 42) | def load_pdf_images(self, input_data):

FILE: pdf_extract_kit/tasks/formula_detection/models/yolo.py
  class FormulaDetectionYOLO (line 13) | class FormulaDetectionYOLO:
    method __init__ (line 14) | def __init__(self, config):
    method predict (line 39) | def predict(self, images, result_path, image_ids=None):

FILE: pdf_extract_kit/tasks/formula_detection/task.py
  class FormulaDetectionTask (line 5) | class FormulaDetectionTask(BaseTask):
    method __init__ (line 6) | def __init__(self, model):
    method predict_images (line 9) | def predict_images(self, input_data, result_path):
    method predict_pdfs (line 24) | def predict_pdfs(self, input_data, result_path):

FILE: pdf_extract_kit/tasks/formula_recognition/models/unimernet.py
  class FormulaRecognitionUniMERNet (line 17) | class FormulaRecognitionUniMERNet:
    method __init__ (line 18) | def __init__(self, config):
    method load_model_and_processor (line 33) | def load_model_and_processor(self):
    method predict (line 48) | def predict(self, images, result_path):

FILE: pdf_extract_kit/tasks/formula_recognition/task.py
  class FormulaRecognitionTask (line 6) | class FormulaRecognitionTask(BaseTask):
    method __init__ (line 7) | def __init__(self, model):
    method predict (line 10) | def predict(self, input_data, result_path, bboxes=None):

FILE: pdf_extract_kit/tasks/layout_detection/models/layoutlmv3.py
  class LayoutDetectionLayoutlmv3 (line 12) | class LayoutDetectionLayoutlmv3:
    method __init__ (line 13) | def __init__(self, config):
    method predict (line 36) | def predict(self, images, result_path, image_ids=None):

FILE: pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/backbone.py
  class VIT_Backbone (line 33) | class VIT_Backbone(Backbone):
    method __init__ (line 38) | def __init__(self, name, out_features, drop_path, img_size, pos_type, ...
    method forward (line 97) | def forward(self, x):
    method output_shape (line 116) | def output_shape(self):
  function build_VIT_backbone (line 125) | def build_VIT_backbone(cfg):
  function build_vit_fpn_backbone (line 158) | def build_vit_fpn_backbone(cfg, input_shape: ShapeSpec):

FILE: pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/beit.py
  function _cfg (line 33) | def _cfg(url='', **kwargs):
  class DropPath (line 43) | class DropPath(nn.Module):
    method __init__ (line 47) | def __init__(self, drop_prob=None):
    method forward (line 51) | def forward(self, x):
    method extra_repr (line 54) | def extra_repr(self) -> str:
  class Mlp (line 58) | class Mlp(nn.Module):
    method __init__ (line 59) | def __init__(self, in_features, hidden_features=None, out_features=Non...
    method forward (line 68) | def forward(self, x):
  class Attention (line 78) | class Attention(nn.Module):
    method __init__ (line 79) | def __init__(
    method forward (line 135) | def forward(self, x, rel_pos_bias=None, training_window_size=None):
  class Block (line 209) | class Block(nn.Module):
    method __init__ (line 211) | def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_sc...
    method forward (line 231) | def forward(self, x, rel_pos_bias=None, training_window_size=None):
  class PatchEmbed (line 243) | class PatchEmbed(nn.Module):
    method __init__ (line 247) | def __init__(self, img_size=[224, 224], patch_size=16, in_chans=3, emb...
    method forward (line 262) | def forward(self, x, position_embedding=None, **kwargs):
  class HybridEmbed (line 280) | class HybridEmbed(nn.Module):
    method __init__ (line 285) | def __init__(self, backbone, img_size=[224, 224], feature_size=None, i...
    method forward (line 309) | def forward(self, x):
  class RelativePositionBias (line 316) | class RelativePositionBias(nn.Module):
    method __init__ (line 318) | def __init__(self, window_size, num_heads):
    method forward (line 348) | def forward(self, training_window_size):
  class BEiT (line 398) | class BEiT(nn.Module):
    method __init__ (line 402) | def __init__(self,
    method fix_init_weight (line 506) | def fix_init_weight(self):
    method _init_weights (line 514) | def _init_weights(self, m):
    method get_num_layers (line 557) | def get_num_layers(self):
    method no_weight_decay (line 561) | def no_weight_decay(self):
    method forward_features (line 564) | def forward_features(self, x):
    method forward (line 601) | def forward(self, x):
  function beit_base_patch16 (line 606) | def beit_base_patch16(pretrained=False, **kwargs):
  function beit_large_patch16 (line 620) | def beit_large_patch16(pretrained=False, **kwargs):
  function dit_base_patch16 (line 634) | def dit_base_patch16(pretrained=False, **kwargs):
  function dit_large_patch16 (line 648) | def dit_large_patch16(pretrained=False, **kwargs):

FILE: pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/deit.py
  function _cfg (line 15) | def _cfg(url='', **kwargs):
  class DropPath (line 24) | class DropPath(nn.Module):
    method __init__ (line 28) | def __init__(self, drop_prob=None):
    method forward (line 32) | def forward(self, x):
    method extra_repr (line 35) | def extra_repr(self) -> str:
  class Mlp (line 39) | class Mlp(nn.Module):
    method __init__ (line 40) | def __init__(self, in_features, hidden_features=None, out_features=Non...
    method forward (line 49) | def forward(self, x):
  class Attention (line 58) | class Attention(nn.Module):
    method __init__ (line 59) | def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, at...
    method forward (line 71) | def forward(self, x):
  class Block (line 86) | class Block(nn.Module):
    method __init__ (line 88) | def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_sc...
    method forward (line 102) | def forward(self, x):
  class PatchEmbed (line 108) | class PatchEmbed(nn.Module):
    method __init__ (line 112) | def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=...
    method forward (line 128) | def forward(self, x):
  class HybridEmbed (line 133) | class HybridEmbed(nn.Module):
    method __init__ (line 138) | def __init__(self, backbone, img_size=224, feature_size=None, in_chans...
    method forward (line 163) | def forward(self, x):
  class ViT (line 170) | class ViT(nn.Module):
    method __init__ (line 174) | def __init__(self,
    method fix_init_weight (line 298) | def fix_init_weight(self):
    method _init_weights (line 306) | def _init_weights(self, m):
    method get_num_layers (line 336) | def get_num_layers(self):
    method no_weight_decay (line 340) | def no_weight_decay(self):
    method _conv_filter (line 343) | def _conv_filter(self, state_dict, patch_size=16):
    method to_2D (line 352) | def to_2D(self, x):
    method to_1D (line 358) | def to_1D(self, x):
    method interpolate_pos_encoding (line 363) | def interpolate_pos_encoding(self, x, w, h):
    method prepare_tokens (line 389) | def prepare_tokens(self, x, mask=None):
    method forward_features (line 414) | def forward_features(self, x):
    method forward (line 441) | def forward(self, x):
  function deit_base_patch16 (line 446) | def deit_base_patch16(pretrained=False, **kwargs):
  function mae_base_patch16 (line 462) | def mae_base_patch16(pretrained=False, **kwargs):

FILE: pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/layoutlmft/data/cord.py
  function quad_to_box (line 24) | def quad_to_box(quad):
  function _get_drive_url (line 46) | def _get_drive_url(url):
  class CordConfig (line 61) | class CordConfig(datasets.BuilderConfig):
    method __init__ (line 63) | def __init__(self, **kwargs):
  class Cord (line 70) | class Cord(datasets.GeneratorBasedBuilder):
    method _info (line 75) | def _info(self):
    method _split_generators (line 97) | def _split_generators(self, dl_manager):
    method get_line_bbox (line 122) | def get_line_bbox(self, bboxs):
    method _generate_examples (line 132) | def _generate_examples(self, filepath):

FILE: pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/layoutlmft/data/data_collator.py
  function pre_calc_rel_mat (line 15) | def pre_calc_rel_mat(segment_ids):
  class DataCollatorForKeyValueExtraction (line 25) | class DataCollatorForKeyValueExtraction(DataCollatorMixin):
    method __call__ (line 56) | def __call__(self, features):

FILE: pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/layoutlmft/data/funsd.py
  class FunsdConfig (line 32) | class FunsdConfig(datasets.BuilderConfig):
    method __init__ (line 35) | def __init__(self, **kwargs):
  class Funsd (line 44) | class Funsd(datasets.GeneratorBasedBuilder):
    method _info (line 51) | def _info(self):
    method _split_generators (line 73) | def _split_generators(self, dl_manager):
    method get_line_bbox (line 85) | def get_line_bbox(self, bboxs):
    method _generate_examples (line 95) | def _generate_examples(self, filepath):

FILE: pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/layoutlmft/data/image_utils.py
  function normalize_bbox (line 12) | def normalize_bbox(bbox, size):
  function load_image (line 21) | def load_image(image_path):
  function crop (line 30) | def crop(image, i, j, h, w, boxes=None):
  function resize (line 46) | def resize(image, size, interpolation, boxes=None):
  function clamp (line 63) | def clamp(num, min_value, max_value):
  function get_bb (line 67) | def get_bb(bb, page_size):
  class ToNumpy (line 91) | class ToNumpy:
    method __call__ (line 93) | def __call__(self, pil_img):
  class ToTensor (line 101) | class ToTensor:
    method __init__ (line 103) | def __init__(self, dtype=torch.float32):
    method __call__ (line 106) | def __call__(self, pil_img):
  function _pil_interp (line 124) | def _pil_interp(method):
  class Compose (line 136) | class Compose:
    method __init__ (line 164) | def __init__(self, transforms):
    method __call__ (line 167) | def __call__(self, img, augmentation=False, box=None):
  class RandomResizedCropAndInterpolationWithTwoPic (line 173) | class RandomResizedCropAndInterpolationWithTwoPic:
    method __init__ (line 186) | def __init__(self, size, second_size=None, scale=(0.08, 1.0), ratio=(3...
    method get_params (line 208) | def get_params(img, scale, ratio):
    method __call__ (line 248) | def __call__(self, img, augmentation=False, box=None):
    method __repr__ (line 264) | def __repr__(self):
  function pil_loader (line 280) | def pil_loader(path: str) -> Image.Image:

FILE: pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/layoutlmft/data/xfund.py
  class xfund_dataset (line 21) | class xfund_dataset(Dataset):
    method box_norm (line 22) | def box_norm(self, box, width, height):
    method get_segment_ids (line 35) | def get_segment_ids(self, bboxs):
    method get_position_ids (line 47) | def get_position_ids(self, segment_ids):
    method load_data (line 59) | def load_data(
    method __init__ (line 147) | def __init__(
    method __len__ (line 179) | def __len__(self):
    method __getitem__ (line 182) | def __getitem__(self, index):
  function pil_loader (line 209) | def pil_loader(path: str) -> Image.Image:

FILE: pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/layoutlmft/models/layoutlmv3/configuration_layoutlmv3.py
  class LayoutLMv3Config (line 15) | class LayoutLMv3Config(BertConfig):
    method __init__ (line 18) | def __init__(

FILE: pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/layoutlmft/models/layoutlmv3/modeling_layoutlmv3.py
  class PatchEmbed (line 50) | class PatchEmbed(nn.Module):
    method __init__ (line 53) | def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=...
    method forward (line 64) | def forward(self, x, position_embedding=None):
  class LayoutLMv3Embeddings (line 77) | class LayoutLMv3Embeddings(nn.Module):
    method __init__ (line 83) | def __init__(self, config):
    method _calc_spatial_position_embeddings (line 105) | def _calc_spatial_position_embeddings(self, bbox):
    method create_position_ids_from_input_ids (line 132) | def create_position_ids_from_input_ids(self, input_ids, padding_idx, p...
    method forward (line 147) | def forward(
    method create_position_ids_from_inputs_embeds (line 188) | def create_position_ids_from_inputs_embeds(self, inputs_embeds):
  class LayoutLMv3PreTrainedModel (line 206) | class LayoutLMv3PreTrainedModel(PreTrainedModel):
    method _init_weights (line 216) | def _init_weights(self, module):
  class LayoutLMv3SelfAttention (line 233) | class LayoutLMv3SelfAttention(nn.Module):
    method __init__ (line 234) | def __init__(self, config):
    method transpose_for_scores (line 254) | def transpose_for_scores(self, x):
    method cogview_attn (line 259) | def cogview_attn(self, attention_scores, alpha=32):
    method forward (line 274) | def forward(
  class LayoutLMv3Attention (line 357) | class LayoutLMv3Attention(nn.Module):
    method __init__ (line 358) | def __init__(self, config):
    method prune_heads (line 364) | def prune_heads(self, heads):
    method forward (line 382) | def forward(
  class LayoutLMv3Layer (line 410) | class LayoutLMv3Layer(nn.Module):
    method __init__ (line 411) | def __init__(self, config):
    method forward (line 421) | def forward(
    method feed_forward_chunk (line 455) | def feed_forward_chunk(self, attention_output):
  class LayoutLMv3Encoder (line 461) | class LayoutLMv3Encoder(nn.Module):
    method __init__ (line 462) | def __init__(self, config, detection=False, out_features=None):
    method relative_position_bucket (line 507) | def relative_position_bucket(self, relative_position, bidirectional=Tr...
    method _cal_1d_pos_emb (line 530) | def _cal_1d_pos_emb(self, hidden_states, position_ids, valid_span):
    method _cal_2d_pos_emb (line 555) | def _cal_2d_pos_emb(self, hidden_states, bbox):
    method forward (line 579) | def forward(
  class LayoutLMv3Model (line 699) | class LayoutLMv3Model(LayoutLMv3PreTrainedModel):
    method __init__ (line 706) | def __init__(self, config, detection=False, out_features=None, image_o...
    method get_input_embeddings (line 746) | def get_input_embeddings(self):
    method set_input_embeddings (line 749) | def set_input_embeddings(self, value):
    method _prune_heads (line 752) | def _prune_heads(self, heads_to_prune):
    method _init_visual_bbox (line 760) | def _init_visual_bbox(self, img_size=(14, 14), max_len=1000):
    method _calc_visual_bbox (line 778) | def _calc_visual_bbox(self, device, dtype, bsz):  # , img_size=(14, 14...
    method forward_image (line 783) | def forward_image(self, x):
    method forward (line 803) | def forward(
  class LayoutLMv3ClassificationHead (line 986) | class LayoutLMv3ClassificationHead(nn.Module):
    method __init__ (line 992) | def __init__(self, config, pool_feature=False):
    method forward (line 1005) | def forward(self, x):
  class LayoutLMv3ForTokenClassification (line 1015) | class LayoutLMv3ForTokenClassification(LayoutLMv3PreTrainedModel):
    method __init__ (line 1019) | def __init__(self, config):
    method forward (line 1032) | def forward(
  class LayoutLMv3ForQuestionAnswering (line 1101) | class LayoutLMv3ForQuestionAnswering(LayoutLMv3PreTrainedModel):
    method __init__ (line 1105) | def __init__(self, config):
    method forward (line 1115) | def forward(
  class LayoutLMv3ForSequenceClassification (line 1196) | class LayoutLMv3ForSequenceClassification(LayoutLMv3PreTrainedModel):
    method __init__ (line 1199) | def __init__(self, config):
    method forward (line 1208) | def forward(

FILE: pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/layoutlmft/models/layoutlmv3/tokenization_layoutlmv3.py
  class LayoutLMv3Tokenizer (line 28) | class LayoutLMv3Tokenizer(RobertaTokenizer):

FILE: pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/layoutlmft/models/layoutlmv3/tokenization_layoutlmv3_fast.py
  class LayoutLMv3TokenizerFast (line 29) | class LayoutLMv3TokenizerFast(RobertaTokenizerFast):

FILE: pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/model_init.py
  function add_vit_config (line 11) | def add_vit_config(cfg):
  function setup (line 63) | def setup(args):
  class DotDict (line 86) | class DotDict(dict):
    method __init__ (line 87) | def __init__(self, *args, **kwargs):
    method __getattr__ (line 90) | def __getattr__(self, key):
    method __setattr__ (line 98) | def __setattr__(self, key, value):
  class Layoutlmv3_Predictor (line 101) | class Layoutlmv3_Predictor(object):
    method __init__ (line 102) | def __init__(self, weights):
    method __call__ (line 120) | def __call__(self, image, ignore_catids=[]):

FILE: pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/rcnn_vl.py
  class VLGeneralizedRCNN (line 23) | class VLGeneralizedRCNN(GeneralizedRCNN):
    method forward (line 31) | def forward(self, batched_inputs: List[Dict[str, torch.Tensor]]):
    method inference (line 85) | def inference(
    method get_batch (line 133) | def get_batch(self, examples, images):
    method _batch_inference (line 139) | def _batch_inference(self, batched_inputs, detected_instances=None):

FILE: pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/visualizer.py
  class ColorMode (line 40) | class ColorMode(Enum):
  class GenericMask (line 62) | class GenericMask:
    method __init__ (line 70) | def __init__(self, mask_or_polygons, height, width):
    method mask (line 102) | def mask(self):
    method polygons (line 108) | def polygons(self):
    method has_holes (line 114) | def has_holes(self):
    method mask_to_polygons (line 122) | def mask_to_polygons(self, mask):
    method polygons_to_mask (line 141) | def polygons_to_mask(self, polygons):
    method area (line 146) | def area(self):
    method bbox (line 149) | def bbox(self):
  class _PanopticPrediction (line 158) | class _PanopticPrediction:
    method __init__ (line 163) | def __init__(self, panoptic_seg, segments_info, metadata=None):
    method non_empty_mask (line 199) | def non_empty_mask(self):
    method semantic_masks (line 215) | def semantic_masks(self):
    method instance_masks (line 223) | def instance_masks(self):
  function _create_text_labels (line 233) | def _create_text_labels(classes, scores, class_names, is_crowd=None):
  class VisImage (line 262) | class VisImage:
    method __init__ (line 263) | def __init__(self, img, scale=1.0):
    method _setup_figure (line 274) | def _setup_figure(self, img):
    method reset_image (line 299) | def reset_image(self, img):
    method save (line 307) | def save(self, filepath):
    method get_image (line 315) | def get_image(self):
  class Visualizer (line 336) | class Visualizer:
    method __init__ (line 362) | def __init__(self, img_rgb, metadata=None, scale=1.0, instance_mode=Co...
    method draw_instance_predictions (line 388) | def draw_instance_predictions(self, predictions):
    method draw_sem_seg (line 441) | def draw_sem_seg(self, sem_seg, area_threshold=None, alpha=0.8):
    method draw_panoptic_seg (line 477) | def draw_panoptic_seg(self, panoptic_seg, segments_info, area_threshol...
    method draw_dataset_dict (line 543) | def draw_dataset_dict(self, dic):
    method overlay_instances (line 612) | def overlay_instances(
    method overlay_rotated_instances (line 755) | def overlay_rotated_instances(self, boxes=None, labels=None, assigned_...
    method draw_and_connect_keypoints (line 793) | def draw_and_connect_keypoints(self, keypoints):
    method draw_text (line 855) | def draw_text(
    method draw_box (line 902) | def draw_box(self, box_coord, alpha=0.5, edge_color="g", line_style="-"):
    method draw_rotated_box_with_label (line 936) | def draw_rotated_box_with_label(
    method draw_circle (line 991) | def draw_circle(self, circle_coord, color, radius=3):
    method draw_line (line 1009) | def draw_line(self, x_data, y_data, color, linestyle="-", linewidth=No...
    method draw_binary_mask (line 1040) | def draw_binary_mask(
    method draw_polygon (line 1101) | def draw_polygon(self, segment, color, edge_color=None, alpha=0.5):
    method _jitter (line 1137) | def _jitter(self, color):
    method _create_grayscale_image (line 1156) | def _create_grayscale_image(self, mask=None):
    method _change_color_brightness (line 1167) | def _change_color_brightness(self, color, brightness_factor):
    method _convert_boxes (line 1192) | def _convert_boxes(self, boxes):
    method _convert_masks (line 1201) | def _convert_masks(self, masks_or_polygons):
    method _convert_keypoints (line 1224) | def _convert_keypoints(self, keypoints):
    method get_output (line 1230) | def get_output(self):

FILE: pdf_extract_kit/tasks/layout_detection/models/yolo.py
  class LayoutDetectionYOLO (line 9) | class LayoutDetectionYOLO:
    method __init__ (line 10) | def __init__(self, config):
    method predict (line 52) | def predict(self, images, result_path, image_ids=None):

FILE: pdf_extract_kit/tasks/layout_detection/task.py
  class LayoutDetectionTask (line 6) | class LayoutDetectionTask(BaseTask):
    method __init__ (line 7) | def __init__(self, model):
    method predict_images (line 10) | def predict_images(self, input_data, result_path):
    method predict_pdfs (line 25) | def predict_pdfs(self, input_data, result_path):

FILE: pdf_extract_kit/tasks/ocr/models/paddle_ocr.py
  function img_decode (line 17) | def img_decode(content: bytes):
  function check_img (line 21) | def check_img(img):
  function sorted_boxes (line 57) | def sorted_boxes(dt_boxes):
  function __is_overlaps_y_exceeds_threshold (line 81) | def __is_overlaps_y_exceeds_threshold(bbox1, bbox2, overlap_ratio_thresh...
  function bbox_to_points (line 94) | def bbox_to_points(bbox):
  function points_to_bbox (line 100) | def points_to_bbox(points):
  function merge_intervals (line 108) | def merge_intervals(intervals):
  function remove_intervals (line 125) | def remove_intervals(original, masks):
  function update_det_boxes (line 156) | def update_det_boxes(dt_boxes, mfd_res):
  function merge_spans_to_line (line 175) | def merge_spans_to_line(spans):
  function merge_overlapping_spans (line 213) | def merge_overlapping_spans(spans):
  function merge_det_boxes (line 250) | def merge_det_boxes(dt_boxes):
  class ModifiedPaddleOCR (line 292) | class ModifiedPaddleOCR(PaddleOCR):
    method __init__ (line 293) | def __init__(self, config):
    method predict (line 296) | def predict(self, img, **kwargs):
    method ocr (line 310) | def ocr(self, img, det=True, rec=True, cls=True, bin=False, inv=False,...
    method __call__ (line 388) | def __call__(self, img, cls=True, mfd_res=None):

FILE: pdf_extract_kit/tasks/ocr/task.py
  class OCRTask (line 11) | class OCRTask(BaseTask):
    method __init__ (line 12) | def __init__(self, model):
    method predict_image (line 20) | def predict_image(self, image):
    method prepare_input_files (line 51) | def prepare_input_files(self, input_path):
    method process (line 58) | def process(self, input_path, save_dir=None, visualize=False):
    method visualize_image (line 88) | def visualize_image(self, image, ocr_res, save_path="", cate2color={}):
    method save_json_result (line 106) | def save_json_result(self, ocr_res, save_path):

FILE: pdf_extract_kit/tasks/table_parsing/models/struct_eqtable.py
  class TableParsingStructEqTable (line 9) | class TableParsingStructEqTable:
    method __init__ (line 10) | def __init__(self, config):
    method predict (line 38) | def predict(self, images, result_path, output_format=None, **kwargs):

FILE: pdf_extract_kit/tasks/table_parsing/task.py
  class TableParsingTask (line 6) | class TableParsingTask(BaseTask):
    method __init__ (line 7) | def __init__(self, model):
    method predict (line 10) | def predict(self, input_data, result_path, **kwargs):

FILE: pdf_extract_kit/utils/config_loader.py
  function load_config (line 6) | def load_config(config_path):
  function initialize_tasks_and_models (line 31) | def initialize_tasks_and_models(config):

FILE: pdf_extract_kit/utils/data_preprocess.py
  function load_pdf_page (line 5) | def load_pdf_page(page, dpi):
  function load_pdf (line 13) | def load_pdf(pdf_path, dpi=144):

FILE: pdf_extract_kit/utils/merge_blocks_and_spans.py
  function __is_overlaps_y_exceeds_threshold (line 7) | def __is_overlaps_y_exceeds_threshold(bbox1, bbox2, overlap_ratio_thresh...
  function merge_spans_to_line (line 19) | def merge_spans_to_line(spans):
  function line_sort_spans_by_left_to_right (line 54) | def line_sort_spans_by_left_to_right(lines):
  function fix_text_block (line 71) | def fix_text_block(block):
  function fix_interline_block (line 83) | def fix_interline_block(block):
  function calculate_overlap_area_in_bbox1_area_ratio (line 90) | def calculate_overlap_area_in_bbox1_area_ratio(bbox1, bbox2):
  function fill_spans_in_blocks (line 111) | def fill_spans_in_blocks(blocks, spans, radio):
  function fix_block_spans (line 157) | def fix_block_spans(block_with_spans):
  function detect_lang (line 195) | def detect_lang(string):
  function ocr_escape_special_markdown_char (line 207) | def ocr_escape_special_markdown_char(content):
  function merge_para_with_text (line 228) | def merge_para_with_text(para_block):

FILE: pdf_extract_kit/utils/pdf_utils.py
  function load_pdf (line 3) | def load_pdf(pdf_path):

FILE: pdf_extract_kit/utils/visualization.py
  function colormap (line 5) | def colormap(N=256, normalized=False):
  function visualize_bbox (line 45) | def visualize_bbox(image_path, bboxes, classes, scores, id_to_names, alp...

FILE: pdf_extract_kit/version.py
  function parse_version_info (line 8) | def parse_version_info(version_str: str) -> Tuple:

FILE: project/pdf2markdown/scripts/pdf2markdown.py
  function latex_rm_whitespace (line 23) | def latex_rm_whitespace(s: str):
  function crop_img (line 41) | def crop_img(input_res, input_pil_img, padding_x=0, padding_y=0):
  class PDF2MARKDOWN (line 57) | class PDF2MARKDOWN(OCRTask):
    method __init__ (line 58) | def __init__(self, layout_model, mfd_model, mfr_model, ocr_model):
    method convert_format (line 83) | def convert_format(self, yolo_res, id_to_names, ):
    method process_single_pdf (line 99) | def process_single_pdf(self, image_list):
    method order_blocks (line 262) | def order_blocks(self, blocks):
    method convert2md (line 268) | def convert2md(self, extract_res):
    method process (line 326) | def process(self, input_path, save_dir=None, visualize=False, merge2ma...

FILE: project/pdf2markdown/scripts/run_project.py
  function parse_args (line 14) | def parse_args():
  function main (line 19) | def main(config_path):

FILE: scripts/formula_detection.py
  function parse_args (line 13) | def parse_args():
  function main (line 18) | def main(config_path):

FILE: scripts/formula_recognition.py
  function parse_args (line 13) | def parse_args():
  function main (line 18) | def main(config_path):

FILE: scripts/layout_detection.py
  function parse_args (line 13) | def parse_args():
  function main (line 18) | def main(config_path):

FILE: scripts/ocr.py
  function parse_args (line 13) | def parse_args():
  function main (line 18) | def main(config_path):

FILE: scripts/run_task.py
  function parse_args (line 11) | def parse_args():
  function main (line 16) | def main(config_path):

FILE: scripts/table_parsing.py
  function parse_args (line 13) | def parse_args():
  function main (line 18) | def main(config_path):
Condensed preview — 143 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (496K chars).
[
  {
    "path": ".gitignore",
    "chars": 182,
    "preview": "*.ipynb*\n*.ipynb\n\n# local data\noutputs/*\ndata/*\ntemp*\ntest*\n\n# python\n.ipynb_checkpoints\n*.ipynb\n**/__pycache__/\n\n# logs"
  },
  {
    "path": ".readthedocs.yaml",
    "chars": 192,
    "preview": "version: 2\n\nbuild:\n  os: ubuntu-22.04\n  tools:\n    python: \"3.10\"\n\nformats:\n  - epub\n\npython:\n  install:\n    - requireme"
  },
  {
    "path": ".vscode/launch.json",
    "chars": 2916,
    "preview": "{\n    // 使用 IntelliSense 了解相关属性。 \n    // 悬停以查看现有属性的描述。\n    // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=83038"
  },
  {
    "path": "LICENSE.md",
    "chars": 34522,
    "preview": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C)"
  },
  {
    "path": "README.md",
    "chars": 14233,
    "preview": "\n<p align=\"center\">\n  <img src=\"assets/readme/pdf-extract-kit_logo.png\" width=\"220px\" style=\"vertical-align:middle;\">\n</"
  },
  {
    "path": "README_zh-CN.md",
    "chars": 8865,
    "preview": "\n<p align=\"center\">\n  <img src=\"assets/readme/pdf-extract-kit_logo.png\" width=\"220px\" style=\"vertical-align:middle;\">\n</"
  },
  {
    "path": "configs/config.yaml",
    "chars": 488,
    "preview": "inputs: assets/demo/formula_detection_pdfs\noutputs: outputs/formula_detection_pdfs\ntasks:\n  formula_detection:\n    model"
  },
  {
    "path": "configs/formula_detection.yaml",
    "chars": 308,
    "preview": "inputs: assets/demo/formula_detection\noutputs: outputs/formula_detection\ntasks:\n  formula_detection:\n    model: formula_"
  },
  {
    "path": "configs/formula_recognition.yaml",
    "chars": 287,
    "preview": "inputs: assets/demo/formula_recognition\noutputs: outputs/formula_recognition\ntasks:\n  formula_recognition:\n    model: fo"
  },
  {
    "path": "configs/layout_detection.yaml",
    "chars": 294,
    "preview": "inputs: assets/demo/layout_detection\noutputs: outputs/layout_detection\ntasks:\n  layout_detection:\n    model: layout_dete"
  },
  {
    "path": "configs/layout_detection_layoutlmv3.yaml",
    "chars": 213,
    "preview": "inputs: assets/demo/layout_detection\noutputs: outputs/layout_detection\ntasks:\n  layout_detection:\n    model: layout_dete"
  },
  {
    "path": "configs/layout_detection_yolo.yaml",
    "chars": 310,
    "preview": "inputs: assets/demo/layout_detection\noutputs: outputs/layout_detection\ntasks:\n  layout_detection:\n    model: layout_dete"
  },
  {
    "path": "configs/ocr.yaml",
    "chars": 302,
    "preview": "inputs: assets/demo/ocr\noutputs: outputs/ocr\nvisualize: True\ntasks:\n  ocr:\n    model: ocr_ppocr\n    model_config:\n      "
  },
  {
    "path": "configs/table_parsing.yaml",
    "chars": 311,
    "preview": "inputs: assets/demo/table_parsing\noutputs: outputs/table_parsing\ntasks:\n  table_parsing:\n    model: table_parsing_struct"
  },
  {
    "path": "docs/en/.readthedocs.yaml",
    "chars": 189,
    "preview": "version: 2\n\nbuild:\n  os: ubuntu-22.04\n  tools:\n    python: \"3.10\"\n\nformats:\n  - epub\n\npython:\n  install:\n    - requireme"
  },
  {
    "path": "docs/en/Makefile",
    "chars": 634,
    "preview": "# Minimal makefile for Sphinx documentation\n#\n\n# You can set these variables from the command line, and also\n# from the "
  },
  {
    "path": "docs/en/algorithm/formula_detection.rst",
    "chars": 3565,
    "preview": "..  _algorithm_formula_detection:\n\n====================\nFormula Detection Algorithm\n====================\n\nIntroduction\n="
  },
  {
    "path": "docs/en/algorithm/formula_recognition.rst",
    "chars": 1882,
    "preview": "..  _algorithm_formula_recognition:\n\n============\nFormula Recognition Algorithm\n============\n\nIntroduction\n============="
  },
  {
    "path": "docs/en/algorithm/layout_detection.rst",
    "chars": 8104,
    "preview": ".. _algorithm_layout_detection:\n\n=================\nLayout Detection Algorithm\n=================\n\nIntroduction\n=========="
  },
  {
    "path": "docs/en/algorithm/ocr.rst",
    "chars": 2466,
    "preview": "..  _algorithm_ocr:\n==========================\nOCR (Optical Character Recognition) Algorithm\n==========================\n"
  },
  {
    "path": "docs/en/algorithm/reading_order.rst",
    "chars": 97,
    "preview": "..  _algorithm_reading_oder:\n==============\nReading Order Algorithm\n==============\n\nComming soon."
  },
  {
    "path": "docs/en/algorithm/table_recognition.rst",
    "chars": 2509,
    "preview": "..  _algorithm_table_recognition:\n\n========================\nTable Recognition Algorithm\n========================\n\nIntrod"
  },
  {
    "path": "docs/en/conf copy.py",
    "chars": 3869,
    "preview": "# Configuration file for the Sphinx documentation builder.\n#\n# This file only contains a selection of the most common op"
  },
  {
    "path": "docs/en/conf.bak",
    "chars": 3440,
    "preview": "# Configuration file for the Sphinx documentation builder.\n#\n# This file only contains a selection of the most common op"
  },
  {
    "path": "docs/en/conf.py",
    "chars": 3851,
    "preview": "# Configuration file for the Sphinx documentation builder.\n#\n# This file only contains a selection of the most common op"
  },
  {
    "path": "docs/en/evaluation/formula_detection.rst",
    "chars": 77,
    "preview": "=====================\nFormula Detection Evaluation\n=====================\n\nXXX"
  },
  {
    "path": "docs/en/evaluation/formula_recognition.rst",
    "chars": 79,
    "preview": "=====================\nFormula Recognition Evaluation\n=====================\n\nXXX"
  },
  {
    "path": "docs/en/evaluation/layout_detection.rst",
    "chars": 76,
    "preview": "=====================\nLayout Detection Evaluation\n=====================\n\nXXX"
  },
  {
    "path": "docs/en/evaluation/ocr.rst",
    "chars": 63,
    "preview": "=====================\nOCR Evaluation\n=====================\n\nXXX"
  },
  {
    "path": "docs/en/evaluation/pdf_extract.rst",
    "chars": 95,
    "preview": "=====================\nPDF Content Extraction Evaluation [End-to-End]\n=====================\n\nXXX"
  },
  {
    "path": "docs/en/evaluation/reading_order.rst",
    "chars": 73,
    "preview": "=====================\nReading Order Evaluation\n=====================\n\nXXX"
  },
  {
    "path": "docs/en/evaluation/table_recognition.rst",
    "chars": 78,
    "preview": "=====================\nTable Recognition Evaluation\n=====================\n\nXXX\n"
  },
  {
    "path": "docs/en/get_started/installation.rst",
    "chars": 1283,
    "preview": "==================================\nInstallation\n==================================\n\nIn this section, we will demonstrate"
  },
  {
    "path": "docs/en/get_started/pretrained_model.rst",
    "chars": 3553,
    "preview": "==================================\nModel Weights Download\n==================================\n\nBefore using the PDF-Extra"
  },
  {
    "path": "docs/en/get_started/quickstart.rst",
    "chars": 1462,
    "preview": "==================================\nQuick Start\n==================================\n\nOnce the PDF-Extract-Kit environment "
  },
  {
    "path": "docs/en/index.rst",
    "chars": 2229,
    "preview": ".. xtuner documentation master file, created by\n   sphinx-quickstart on Tue Jan  9 16:33:06 2024.\n   You can adapt this "
  },
  {
    "path": "docs/en/make.bat",
    "chars": 765,
    "preview": "@ECHO OFF\n\npushd %~dp0\n\nREM Command file for Sphinx documentation\n\nif \"%SPHINXBUILD%\" == \"\" (\n\tset SPHINXBUILD=sphinx-bu"
  },
  {
    "path": "docs/en/models/supported.md",
    "chars": 24,
    "preview": "# The Supported Models\n\n"
  },
  {
    "path": "docs/en/notes/changelog.md",
    "chars": 385,
    "preview": "<!--\n\n## vX.X.X (YYYY.MM.DD)\n\n### 亮点\n\n### 新功能和改进\n\n### Bug 修复\n\n### 贡献者\n\n-->\n\n# Changelog\n\n## v1.0.0 (2024-10-10)\n\nThe PDF"
  },
  {
    "path": "docs/en/project/doc_translate.rst",
    "chars": 75,
    "preview": "=================\nDocument Translation Project\n=================\n\nXXXX\nXXXX"
  },
  {
    "path": "docs/en/project/pdf_extract.rst",
    "chars": 4390,
    "preview": "=================\nDocument Content Extraction Project\n=================\n\nIntroduction\n====================\n\nDocument con"
  },
  {
    "path": "docs/en/project/speed_up.rst",
    "chars": 73,
    "preview": "=================\nModel Acceleration Project\n=================\n\nXXXX\nXXXX"
  },
  {
    "path": "docs/en/switch_language.md",
    "chars": 151,
    "preview": "## <a href='https://pdf-extract-kit.readthedocs.io/en/latest/'>English</a>\n\n## <a href='https://pdf-extract-kit.readthed"
  },
  {
    "path": "docs/en/task_extend/code.rst",
    "chars": 10404,
    "preview": "==================================\nCode Implementation\n==================================\n\nThe core code of the PDF-Extr"
  },
  {
    "path": "docs/en/task_extend/doc.rst",
    "chars": 96,
    "preview": "==================================\nDocumentation Supplement\n==================================\n\n"
  },
  {
    "path": "docs/en/task_extend/evaluation.rst",
    "chars": 100,
    "preview": "==================================\nModel Performance Evaluation\n==================================\n\n"
  },
  {
    "path": "docs/requirements.txt",
    "chars": 87,
    "preview": "sphinx\nsphinx_rtd_theme\nmyst-parser\nsphinx-copybutton\nsphinx-argparse\nsphinx-book-theme"
  },
  {
    "path": "docs/zh_cn/.readthedocs.yaml",
    "chars": 192,
    "preview": "version: 2\n\nbuild:\n  os: ubuntu-22.04\n  tools:\n    python: \"3.10\"\n\nformats:\n  - epub\n\npython:\n  install:\n    - requireme"
  },
  {
    "path": "docs/zh_cn/Makefile",
    "chars": 634,
    "preview": "# Minimal makefile for Sphinx documentation\n#\n\n# You can set these variables from the command line, and also\n# from the "
  },
  {
    "path": "docs/zh_cn/algorithm/formula_detection.rst",
    "chars": 2118,
    "preview": "..  _algorithm_formula_detection:\n\n====================\n公式检测算法\n====================\n\n简介\n====================\n\n公式检测是针对给定的"
  },
  {
    "path": "docs/zh_cn/algorithm/formula_recognition.rst",
    "chars": 1145,
    "preview": "..  _algorithm_formula_recognition:\n\n============\n公式识别算法\n============\n\n简介\n=================\n\n公式检测是指给定输入公式图像,识别公式图像内容并转为 "
  },
  {
    "path": "docs/zh_cn/algorithm/layout_detection.rst",
    "chars": 6322,
    "preview": ".. _algorithm_layout_detection:\n\n=================\n布局检测算法\n=================\n\n简介\n=================\n\n``布局检测`` 是文档内容提取的基础任务"
  },
  {
    "path": "docs/zh_cn/algorithm/ocr.rst",
    "chars": 1382,
    "preview": "..  _algorithm_ocr:\n==========================\n光学字符识别(OCR)算法\n==========================\n\n简介\n====================\n\n光学字符识别"
  },
  {
    "path": "docs/zh_cn/algorithm/reading_order.rst",
    "chars": 80,
    "preview": "..  _algorithm_reading_oder:\n==============\n阅读顺序算法\n==============\n\nComming soon."
  },
  {
    "path": "docs/zh_cn/algorithm/table_recognition.rst",
    "chars": 1544,
    "preview": "..  _algorithm_table_recognition:\n\n============\n表格识别算法\n============\n\n简介\n=================\n\n表格识别是指输入表格图像,识别表格结构和内容,并将其转换为"
  },
  {
    "path": "docs/zh_cn/conf.py",
    "chars": 3849,
    "preview": "# Configuration file for the Sphinx documentation builder.\n#\n# This file only contains a selection of the most common op"
  },
  {
    "path": "docs/zh_cn/evaluation/formula_detection.rst",
    "chars": 57,
    "preview": "=====================\n公式检测算法评测\n=====================\n\nXXX"
  },
  {
    "path": "docs/zh_cn/evaluation/formula_recognition.rst",
    "chars": 67,
    "preview": "=====================\n公式识别算法评测\n=====================\n\nComming soon!"
  },
  {
    "path": "docs/zh_cn/evaluation/layout_detection.rst",
    "chars": 67,
    "preview": "=====================\n布局检测算法评测\n=====================\n\nComming soon!"
  },
  {
    "path": "docs/zh_cn/evaluation/ocr.rst",
    "chars": 66,
    "preview": "=====================\nOCR算法评测\n=====================\n\nComming soon!"
  },
  {
    "path": "docs/zh_cn/evaluation/pdf_extract.rst",
    "chars": 73,
    "preview": "=====================\nPDF内容提取评测【端到端】\n=====================\n\nComming soon!"
  },
  {
    "path": "docs/zh_cn/evaluation/reading_order.rst",
    "chars": 57,
    "preview": "=====================\n阅读顺序算法评测\n=====================\n\nXXX"
  },
  {
    "path": "docs/zh_cn/evaluation/table_recognition.rst",
    "chars": 68,
    "preview": "=====================\n表格识别算法评测\n=====================\n\nComming soon!\n"
  },
  {
    "path": "docs/zh_cn/get_started/installation.rst",
    "chars": 818,
    "preview": "==================================\n安装\n==================================\n\n本节中,我们将演示如何安装 PDF-Extract-Kit。\n\n最佳实践\n========\n"
  },
  {
    "path": "docs/zh_cn/get_started/pretrained_model.rst",
    "chars": 2437,
    "preview": "==================================\n模型权重下载\n==================================\n\n在使用PDF-Extract-Kit前,我们需要下载所需要的模型权重。可以根据自己需"
  },
  {
    "path": "docs/zh_cn/get_started/quickstart.rst",
    "chars": 921,
    "preview": "==================================\n快速开始\n==================================\n\n配置好PDF-Extract-Kit环境,并下载好模型后,我们可以开始使用PDF-Ext"
  },
  {
    "path": "docs/zh_cn/index.rst",
    "chars": 2103,
    "preview": ".. xtuner documentation master file, created by\n   sphinx-quickstart on Tue Jan  9 16:33:06 2024.\n   You can adapt this "
  },
  {
    "path": "docs/zh_cn/make.bat",
    "chars": 765,
    "preview": "@ECHO OFF\n\npushd %~dp0\n\nREM Command file for Sphinx documentation\n\nif \"%SPHINXBUILD%\" == \"\" (\n\tset SPHINXBUILD=sphinx-bu"
  },
  {
    "path": "docs/zh_cn/models/supported.md",
    "chars": 23,
    "preview": "# 已支持的模型\n\nComming soon!"
  },
  {
    "path": "docs/zh_cn/notes/changelog.md",
    "chars": 285,
    "preview": "<!--\n\n## vX.X.X (YYYY.MM.DD)\n\n### 亮点\n\n### 新功能和改进\n\n### Bug 修复\n\n### 贡献者\n\n-->\n\n# 变更日志\n\n\n## v0.2.0 (2024.09.30)\n\nPDF-Extract"
  },
  {
    "path": "docs/zh_cn/project/doc_translate.rst",
    "chars": 57,
    "preview": "=================\n文档翻译项目\n=================\n\nComming soon!"
  },
  {
    "path": "docs/zh_cn/project/pdf_extract.rst",
    "chars": 3188,
    "preview": "=================\n文档内容提取项目\n=================\n\n简介\n====================\n\n文档内容提取是利用布局检测,公式检测,公式识别,OCR等模型,提取文档中的信息,并转换为markd"
  },
  {
    "path": "docs/zh_cn/project/speed_up.rst",
    "chars": 57,
    "preview": "=================\n模型加速项目\n=================\n\nComming soon!"
  },
  {
    "path": "docs/zh_cn/switch_language.md",
    "chars": 151,
    "preview": "## <a href='https://pdf-extract-kit.readthedocs.io/en/latest/'>English</a>\n\n## <a href='https://pdf-extract-kit.readthed"
  },
  {
    "path": "docs/zh_cn/task_extend/code.rst",
    "chars": 8253,
    "preview": "==================================\n代码实现\n==================================\n\nPDF-Extract-Kit项目的核心代码实现在pdf_extract_kit目录下,"
  },
  {
    "path": "docs/zh_cn/task_extend/doc.rst",
    "chars": 251,
    "preview": "==================================\n文档补充\n==================================\n\n在实现新的任务和模块后,需要在文档中补充相关内容,以便用户了解如何使用。\n\n具体可以参考"
  },
  {
    "path": "docs/zh_cn/task_extend/evaluation.rst",
    "chars": 89,
    "preview": "==================================\n模型评测\n==================================\n\nComming soon!"
  },
  {
    "path": "pdf_extract_kit/__init__.py",
    "chars": 202,
    "preview": "import os\nimport sys\n\ncurrent_dir = os.path.dirname(os.path.abspath(__file__))\n\nroot_dir = os.path.abspath(os.path.join("
  },
  {
    "path": "pdf_extract_kit/configs/unimernet.yaml",
    "chars": 830,
    "preview": "model:\n  arch: unimernet\n  model_type: unimernet\n  model_config:\n    model_name: ./models/unimernet_tiny\n    max_seq_len"
  },
  {
    "path": "pdf_extract_kit/dataset/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "pdf_extract_kit/dataset/dataset.py",
    "chars": 2960,
    "preview": "import numpy as np\nimport torch\nfrom PIL import Image\nfrom torch.utils.data import Dataset\nimport torchvision.transforms"
  },
  {
    "path": "pdf_extract_kit/registry/__init__.py",
    "chars": 51,
    "preview": "from .registry import TASK_REGISTRY, MODEL_REGISTRY"
  },
  {
    "path": "pdf_extract_kit/registry/registry.py",
    "chars": 667,
    "preview": "class Registry:\n    def __init__(self):\n        self._registry = {}\n\n    def register(self, name):\n        def decorator"
  },
  {
    "path": "pdf_extract_kit/tasks/__init__.py",
    "chars": 845,
    "preview": "from pdf_extract_kit.tasks.base_task import BaseTask\nfrom pdf_extract_kit.tasks.formula_detection.task import FormulaDet"
  },
  {
    "path": "pdf_extract_kit/tasks/base_task.py",
    "chars": 3519,
    "preview": "import os\nfrom pdf_extract_kit.utils.data_preprocess import load_pdf\n\n\nclass BaseTask:\n    def __init__(self, model):\n  "
  },
  {
    "path": "pdf_extract_kit/tasks/formula_detection/__init__.py",
    "chars": 190,
    "preview": "from pdf_extract_kit.tasks.formula_detection.models.yolo import FormulaDetectionYOLO\n\nfrom pdf_extract_kit.registry.regi"
  },
  {
    "path": "pdf_extract_kit/tasks/formula_detection/models/yolo.py",
    "chars": 2932,
    "preview": "import os\nimport cv2\nimport torch\nfrom torch.utils.data import DataLoader, Dataset\nfrom ultralytics import YOLO\nfrom pdf"
  },
  {
    "path": "pdf_extract_kit/tasks/formula_detection/task.py",
    "chars": 1286,
    "preview": "from pdf_extract_kit.registry.registry import TASK_REGISTRY\nfrom pdf_extract_kit.tasks.base_task import BaseTask\n\n@TASK_"
  },
  {
    "path": "pdf_extract_kit/tasks/formula_recognition/__init__.py",
    "chars": 211,
    "preview": "from pdf_extract_kit.tasks.formula_recognition.models.unimernet import FormulaRecognitionUniMERNet\n\nfrom pdf_extract_kit"
  },
  {
    "path": "pdf_extract_kit/tasks/formula_recognition/models/unimernet.py",
    "chars": 2967,
    "preview": "import os\nimport logging\nimport argparse\n\nimport cv2\nimport torch\nimport numpy as np\nfrom PIL import Image\nimport unimer"
  },
  {
    "path": "pdf_extract_kit/tasks/formula_recognition/task.py",
    "chars": 457,
    "preview": "from pdf_extract_kit.registry.registry import TASK_REGISTRY\nfrom pdf_extract_kit.tasks.base_task import BaseTask\n\n\n@TASK"
  },
  {
    "path": "pdf_extract_kit/tasks/layout_detection/__init__.py",
    "chars": 319,
    "preview": "from pdf_extract_kit.tasks.layout_detection.models.yolo import LayoutDetectionYOLO\n# from pdf_extract_kit.tasks.layout_d"
  },
  {
    "path": "pdf_extract_kit/tasks/layout_detection/models/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "pdf_extract_kit/tasks/layout_detection/models/layoutlmv3.py",
    "chars": 3048,
    "preview": "import os\nimport cv2\nimport numpy as np\nfrom PIL import Image\n\nfrom pdf_extract_kit.registry.registry import MODEL_REGIS"
  },
  {
    "path": "pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/backbone.py",
    "chars": 7106,
    "preview": "# --------------------------------------------------------------------------------\n# VIT: Multi-Path Vision Transformer "
  },
  {
    "path": "pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/beit.py",
    "chars": 30378,
    "preview": "\"\"\" Vision Transformer (ViT) in PyTorch\n\nA PyTorch implement of Vision Transformers as described in\n'An Image Is Worth 1"
  },
  {
    "path": "pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/deit.py",
    "chars": 17000,
    "preview": "\"\"\"\nMostly copy-paste from DINO and timm library:\nhttps://github.com/facebookresearch/dino\nhttps://github.com/rwightman/"
  },
  {
    "path": "pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/layoutlmft/__init__.py",
    "chars": 186,
    "preview": "from .models import (\n    LayoutLMv3Config,\n    LayoutLMv3ForTokenClassification,\n    LayoutLMv3ForQuestionAnswering,\n  "
  },
  {
    "path": "pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/layoutlmft/data/__init__.py",
    "chars": 76,
    "preview": "# flake8: noqa\nfrom .data_collator import DataCollatorForKeyValueExtraction\n"
  },
  {
    "path": "pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/layoutlmft/data/cord.py",
    "chars": 8151,
    "preview": "'''\nReference: https://huggingface.co/datasets/pierresi/cord/blob/main/cord.py\n'''\n\n\nimport json\nimport os\nfrom pathlib "
  },
  {
    "path": "pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/layoutlmft/data/data_collator.py",
    "chars": 6279,
    "preview": "import torch\nfrom dataclasses import dataclass\nfrom typing import Any, Dict, List, Optional, Tuple, Union\n\nfrom transfor"
  },
  {
    "path": "pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/layoutlmft/data/funsd.py",
    "chars": 5212,
    "preview": "# coding=utf-8\n'''\nReference: https://huggingface.co/datasets/nielsr/funsd/blob/main/funsd.py\n'''\nimport json\nimport os\n"
  },
  {
    "path": "pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/layoutlmft/data/image_utils.py",
    "chars": 10334,
    "preview": "import torchvision.transforms.functional as F\nimport warnings\nimport math\nimport random\nimport numpy as np\nfrom PIL impo"
  },
  {
    "path": "pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/layoutlmft/data/xfund.py",
    "chars": 8270,
    "preview": "import os\nimport json\n\nimport torch\nfrom torch.utils.data.dataset import Dataset\nfrom torchvision import transforms\nfrom"
  },
  {
    "path": "pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/layoutlmft/models/__init__.py",
    "chars": 190,
    "preview": "from .layoutlmv3 import (\n    LayoutLMv3Config,\n    LayoutLMv3ForTokenClassification,\n    LayoutLMv3ForQuestionAnswering"
  },
  {
    "path": "pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/layoutlmft/models/layoutlmv3/__init__.py",
    "chars": 1216,
    "preview": "from transformers import AutoConfig, AutoModel, AutoModelForTokenClassification, \\\n    AutoModelForQuestionAnswering, Au"
  },
  {
    "path": "pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/layoutlmft/models/layoutlmv3/configuration_layoutlmv3.py",
    "chars": 2150,
    "preview": "# coding=utf-8\nfrom transformers.models.bert.configuration_bert import BertConfig\nfrom transformers.utils import logging"
  },
  {
    "path": "pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/layoutlmft/models/layoutlmv3/modeling_layoutlmv3.py",
    "chars": 54627,
    "preview": "# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.\n# Copyright (c) 2018,"
  },
  {
    "path": "pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/layoutlmft/models/layoutlmv3/tokenization_layoutlmv3.py",
    "chars": 1197,
    "preview": "# coding=utf-8\n# Copyright 2018 The Open AI Team Authors and The HuggingFace Inc. team.\n#\n# Licensed under the Apache Li"
  },
  {
    "path": "pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/layoutlmft/models/layoutlmv3/tokenization_layoutlmv3_fast.py",
    "chars": 1372,
    "preview": "# coding=utf-8\n# Copyright 2018 The Open AI Team Authors and The HuggingFace Inc. team.\n#\n# Licensed under the Apache Li"
  },
  {
    "path": "pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/layoutlmv3_base_inference.yaml",
    "chars": 6109,
    "preview": "AUG:\n  DETR: true\nCACHE_DIR: ~/cache/huggingface\nCUDNN_BENCHMARK: false\nDATALOADER:\n  ASPECT_RATIO_GROUPING: true\n  FILT"
  },
  {
    "path": "pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/model_init.py",
    "chars": 4461,
    "preview": "from .visualizer import Visualizer\nfrom .rcnn_vl import *\nfrom .backbone import *\n\nfrom detectron2.config import get_cfg"
  },
  {
    "path": "pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/rcnn_vl.py",
    "chars": 6649,
    "preview": "# Copyright (c) Facebook, Inc. and its affiliates.\nimport logging\nimport numpy as np\nfrom typing import Dict, List, Opti"
  },
  {
    "path": "pdf_extract_kit/tasks/layout_detection/models/layoutlmv3_util/visualizer.py",
    "chars": 49797,
    "preview": "# Copyright (c) Facebook, Inc. and its affiliates.\nimport colorsys\nimport logging\nimport math\nimport numpy as np\nfrom en"
  },
  {
    "path": "pdf_extract_kit/tasks/layout_detection/models/yolo.py",
    "chars": 3797,
    "preview": "import os\nimport cv2\nimport torch\nfrom pdf_extract_kit.registry import MODEL_REGISTRY\nfrom pdf_extract_kit.utils.visuali"
  },
  {
    "path": "pdf_extract_kit/tasks/layout_detection/task.py",
    "chars": 1283,
    "preview": "from pdf_extract_kit.registry.registry import TASK_REGISTRY\nfrom pdf_extract_kit.tasks.base_task import BaseTask\n\n\n@TASK"
  },
  {
    "path": "pdf_extract_kit/tasks/ocr/__init__.py",
    "chars": 178,
    "preview": "from pdf_extract_kit.tasks.ocr.models.paddle_ocr import ModifiedPaddleOCR\n# from pdf_extract_kit.registry.registry impor"
  },
  {
    "path": "pdf_extract_kit/tasks/ocr/models/paddle_ocr.py",
    "chars": 16858,
    "preview": "import time\nimport copy\nimport logging\nimport base64\nimport cv2\nimport numpy as np\nfrom io import BytesIO\nfrom PIL impor"
  },
  {
    "path": "pdf_extract_kit/tasks/ocr/task.py",
    "chars": 4676,
    "preview": "import os\nimport json\nimport random\nfrom PIL import Image, ImageDraw\nfrom pdf_extract_kit.registry.registry import TASK_"
  },
  {
    "path": "pdf_extract_kit/tasks/table_parsing/__init__.py",
    "chars": 206,
    "preview": "from pdf_extract_kit.tasks.table_parsing.models.struct_eqtable import TableParsingStructEqTable\n\nfrom pdf_extract_kit.re"
  },
  {
    "path": "pdf_extract_kit/tasks/table_parsing/models/struct_eqtable.py",
    "chars": 1813,
    "preview": "import torch\n\nfrom PIL import Image\nfrom struct_eqtable import build_model\nfrom pdf_extract_kit.registry.registry import"
  },
  {
    "path": "pdf_extract_kit/tasks/table_parsing/task.py",
    "chars": 471,
    "preview": "from pdf_extract_kit.registry.registry import TASK_REGISTRY\nfrom pdf_extract_kit.tasks.base_task import BaseTask\n\n\n@TASK"
  },
  {
    "path": "pdf_extract_kit/utils/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "pdf_extract_kit/utils/config_loader.py",
    "chars": 1299,
    "preview": "import yaml\nimport warnings\nfrom pdf_extract_kit.registry.registry import TASK_REGISTRY, MODEL_REGISTRY\n\n\ndef load_confi"
  },
  {
    "path": "pdf_extract_kit/utils/data_preprocess.py",
    "chars": 629,
    "preview": "import fitz\nfrom PIL import Image\n\n\ndef load_pdf_page(page, dpi):\n    pix = page.get_pixmap(matrix=fitz.Matrix(dpi/72, d"
  },
  {
    "path": "pdf_extract_kit/utils/merge_blocks_and_spans.py",
    "chars": 8778,
    "preview": "# revised from https://github.com/opendatalab/MinerU/blob/7f0fe20004af7416db886f4b75c116bcc1c986b4/magic_pdf/pdf_parse_u"
  },
  {
    "path": "pdf_extract_kit/utils/pdf_utils.py",
    "chars": 124,
    "preview": "from pdf2image import convert_from_path\n\ndef load_pdf(pdf_path):\n    images = convert_from_path(pdf_path)\n    return ima"
  },
  {
    "path": "pdf_extract_kit/utils/visualization.py",
    "chars": 3078,
    "preview": "import numpy as np\nimport cv2\nfrom PIL import Image\n\ndef colormap(N=256, normalized=False):\n    \"\"\"\n    Generate the col"
  },
  {
    "path": "pdf_extract_kit/version.py",
    "chars": 771,
    "preview": "# Copyright (c) OpenMMLab. All rights reserved.\nfrom typing import Tuple\n\n__version__ = '0.1.0'\nshort_version = __versio"
  },
  {
    "path": "project/pdf2markdown/README.md",
    "chars": 965,
    "preview": "# PDF2Markdown\n\n**Demo:(left: input image; right: rendered markdown.)**\n\n![demo](demo.png)\n\n\n1. Extract PDF features by "
  },
  {
    "path": "project/pdf2markdown/configs/pdf2markdown.yaml",
    "chars": 955,
    "preview": "inputs: assets/demo/formula_detection\noutputs: outputs/pdf2markdown\nvisualize: True\nmerge2markdown: True\ntasks:\n  layout"
  },
  {
    "path": "project/pdf2markdown/scripts/pdf2markdown.py",
    "chars": 15655,
    "preview": "import os\nimport re\nimport gc\nimport sys\nimport time\nimport torch\nfrom PIL import Image, ImageDraw\nfrom torchvision impo"
  },
  {
    "path": "project/pdf2markdown/scripts/run_project.py",
    "chars": 1775,
    "preview": "import os\nimport sys\nimport os.path as osp\nimport argparse\nfrom pdf2markdown import PDF2MARKDOWN\n\nsys.path.append(osp.jo"
  },
  {
    "path": "pyproject.toml",
    "chars": 834,
    "preview": "[build-system]\nrequires = [\"setuptools>=42\", \"wheel\"]\nbuild-backend = \"setuptools.build_meta\"\n\n[project]\nname = \"pdf-ext"
  },
  {
    "path": "requirements/docs.txt",
    "chars": 88,
    "preview": "myst-parser\nsphinx\nsphinx-book-theme\nsphinx-copybutton\nsphinx-tabs\nsphinxcontrib-mermaid"
  },
  {
    "path": "requirements-cpu.txt",
    "chars": 133,
    "preview": "omegaconf\nmatplotlib\nPyMuPDF\nultralytics>=8.2.85\ndoclayout-yolo==0.0.2\nunimernet==0.2.1\npaddlepaddle\npaddleocr==2.7.3\nst"
  },
  {
    "path": "requirements.txt",
    "chars": 146,
    "preview": "omegaconf\nmatplotlib\nPyMuPDF\nultralytics>=8.2.85\ndoclayout-yolo==0.0.2\nunimernet==0.2.1\npaddlepaddle-gpu\npaddleocr==2.7."
  },
  {
    "path": "scripts/formula_detection.py",
    "chars": 1295,
    "preview": "import os\nimport sys\nimport os.path as osp\nimport argparse\n\nsys.path.append(osp.join(os.path.dirname(os.path.abspath(__f"
  },
  {
    "path": "scripts/formula_recognition.py",
    "chars": 1224,
    "preview": "import os\nimport sys\nimport os.path as osp\nimport argparse\n\nsys.path.append(osp.join(os.path.dirname(os.path.abspath(__f"
  },
  {
    "path": "scripts/layout_detection.py",
    "chars": 1290,
    "preview": "import os\nimport sys\nimport os.path as osp\nimport argparse\n\nsys.path.append(osp.join(os.path.dirname(os.path.abspath(__f"
  },
  {
    "path": "scripts/ocr.py",
    "chars": 1139,
    "preview": "import os\nimport sys\nimport os.path as osp\nimport argparse\n\nsys.path.append(osp.join(os.path.dirname(os.path.abspath(__f"
  },
  {
    "path": "scripts/run_task.py",
    "chars": 1385,
    "preview": "import os\nimport sys\nimport os.path as osp\nimport argparse\n\nsys.path.append(osp.join(os.path.dirname(os.path.abspath(__f"
  },
  {
    "path": "scripts/table_parsing.py",
    "chars": 1201,
    "preview": "import os\nimport sys\nimport os.path as osp\nimport argparse\n\nsys.path.append(osp.join(os.path.dirname(os.path.abspath(__f"
  }
]

About this extraction

This page contains the full source code of the opendatalab/PDF-Extract-Kit GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 143 files (459.0 KB), approximately 118.3k tokens, and a symbol index with 364 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!