@ -1,5 +1,6 @@
|
|||||||
venv
|
venv
|
||||||
*.pdf
|
*.pdf
|
||||||
|
*.PDF
|
||||||
.vscode
|
.vscode
|
||||||
visual_images/*.jpg
|
visual_images/*.jpg
|
||||||
__pycache__
|
__pycache__
|
@ -1,18 +0,0 @@
|
|||||||
from magic_pdf.model.doc_analyze_by_custom_model import doc_analyze
|
|
||||||
from magic_pdf.data.read_api import read_local_images
|
|
||||||
from markdownify import markdownify as md
|
|
||||||
import re
|
|
||||||
|
|
||||||
|
|
||||||
# proc
|
|
||||||
## Create Dataset Instance
|
|
||||||
input_file = "/mnt/research/PaddleOCR/pdf2md_pipeline/s4_content_recognition/all_layouts/207.jpg"
|
|
||||||
|
|
||||||
ds = read_local_images(input_file)[0]
|
|
||||||
|
|
||||||
x = ds.apply(doc_analyze, ocr=True)
|
|
||||||
x = x.pipe_ocr_mode(None)
|
|
||||||
html = x.get_markdown(None)
|
|
||||||
content = md(html)
|
|
||||||
content = re.sub(r'\\([#*_`])', r'\1', content)
|
|
||||||
print(content)
|
|
@ -0,0 +1,179 @@
|
|||||||
|
private.py
|
||||||
|
.DS_Store
|
||||||
|
local.env
|
||||||
|
experiments
|
||||||
|
test_data
|
||||||
|
training
|
||||||
|
wandb
|
||||||
|
*.dat
|
||||||
|
report.json
|
||||||
|
benchmark_data
|
||||||
|
debug_data
|
||||||
|
temp.md
|
||||||
|
temp
|
||||||
|
conversion_results
|
||||||
|
uploads
|
||||||
|
/cache
|
||||||
|
|
||||||
|
# Byte-compiled / optimized / DLL files
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*$py.class
|
||||||
|
|
||||||
|
# C extensions
|
||||||
|
*.so
|
||||||
|
|
||||||
|
# Distribution / packaging
|
||||||
|
.Python
|
||||||
|
build/
|
||||||
|
develop-eggs/
|
||||||
|
dist/
|
||||||
|
downloads/
|
||||||
|
eggs/
|
||||||
|
.eggs/
|
||||||
|
lib/
|
||||||
|
lib64/
|
||||||
|
parts/
|
||||||
|
sdist/
|
||||||
|
var/
|
||||||
|
wheels/
|
||||||
|
share/python-wheels/
|
||||||
|
*.egg-info/
|
||||||
|
.installed.cfg
|
||||||
|
*.egg
|
||||||
|
MANIFEST
|
||||||
|
|
||||||
|
# PyInstaller
|
||||||
|
# Usually these files are written by a python script from a template
|
||||||
|
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||||
|
*.manifest
|
||||||
|
*.spec
|
||||||
|
|
||||||
|
# Installer logs
|
||||||
|
pip-log.txt
|
||||||
|
pip-delete-this-directory.txt
|
||||||
|
|
||||||
|
# Unit test / coverage reports
|
||||||
|
htmlcov/
|
||||||
|
.tox/
|
||||||
|
.nox/
|
||||||
|
.coverage
|
||||||
|
.coverage.*
|
||||||
|
.cache
|
||||||
|
nosetests.xml
|
||||||
|
coverage.xml
|
||||||
|
*.cover
|
||||||
|
*.py,cover
|
||||||
|
.hypothesis/
|
||||||
|
.pytest_cache/
|
||||||
|
cover/
|
||||||
|
|
||||||
|
# Translations
|
||||||
|
*.mo
|
||||||
|
*.pot
|
||||||
|
|
||||||
|
# Django stuff:
|
||||||
|
*.log
|
||||||
|
local_settings.py
|
||||||
|
db.sqlite3
|
||||||
|
db.sqlite3-journal
|
||||||
|
|
||||||
|
# Flask stuff:
|
||||||
|
instance/
|
||||||
|
.webassets-cache
|
||||||
|
|
||||||
|
# Scrapy stuff:
|
||||||
|
.scrapy
|
||||||
|
|
||||||
|
# Sphinx documentation
|
||||||
|
docs/_build/
|
||||||
|
|
||||||
|
# PyBuilder
|
||||||
|
.pybuilder/
|
||||||
|
target/
|
||||||
|
|
||||||
|
# Jupyter Notebook
|
||||||
|
.ipynb_checkpoints
|
||||||
|
|
||||||
|
# IPython
|
||||||
|
profile_default/
|
||||||
|
ipython_config.py
|
||||||
|
|
||||||
|
# pyenv
|
||||||
|
# For a library or package, you might want to ignore these files since the code is
|
||||||
|
# intended to run in multiple environments; otherwise, check them in:
|
||||||
|
# .python-version
|
||||||
|
|
||||||
|
# pipenv
|
||||||
|
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||||
|
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||||
|
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||||
|
# install all needed dependencies.
|
||||||
|
#Pipfile.lock
|
||||||
|
|
||||||
|
# poetry
|
||||||
|
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||||
|
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||||
|
# commonly ignored for libraries.
|
||||||
|
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||||
|
#poetry.lock
|
||||||
|
|
||||||
|
# pdm
|
||||||
|
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||||
|
#pdm.lock
|
||||||
|
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
||||||
|
# in version control.
|
||||||
|
# https://pdm.fming.dev/#use-with-ide
|
||||||
|
.pdm.toml
|
||||||
|
|
||||||
|
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||||
|
__pypackages__/
|
||||||
|
|
||||||
|
# Celery stuff
|
||||||
|
celerybeat-schedule
|
||||||
|
celerybeat.pid
|
||||||
|
|
||||||
|
# SageMath parsed files
|
||||||
|
*.sage.py
|
||||||
|
|
||||||
|
# Environments
|
||||||
|
.env
|
||||||
|
.venv
|
||||||
|
env/
|
||||||
|
venv/
|
||||||
|
ENV/
|
||||||
|
env.bak/
|
||||||
|
venv.bak/
|
||||||
|
|
||||||
|
# Spyder project settings
|
||||||
|
.spyderproject
|
||||||
|
.spyproject
|
||||||
|
|
||||||
|
# Rope project settings
|
||||||
|
.ropeproject
|
||||||
|
|
||||||
|
# mkdocs documentation
|
||||||
|
/site
|
||||||
|
|
||||||
|
# mypy
|
||||||
|
.mypy_cache/
|
||||||
|
.dmypy.json
|
||||||
|
dmypy.json
|
||||||
|
|
||||||
|
# Pyre type checker
|
||||||
|
.pyre/
|
||||||
|
|
||||||
|
# pytype static type analyzer
|
||||||
|
.pytype/
|
||||||
|
|
||||||
|
# Cython debug symbols
|
||||||
|
cython_debug/
|
||||||
|
|
||||||
|
# PyCharm
|
||||||
|
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||||
|
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||||
|
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||||
|
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||||
|
.idea/
|
||||||
|
|
||||||
|
.vscode/
|
@ -0,0 +1,12 @@
|
|||||||
|
repos:
|
||||||
|
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||||
|
# Ruff version.
|
||||||
|
rev: v0.9.10
|
||||||
|
hooks:
|
||||||
|
# Run the linter.
|
||||||
|
- id: ruff
|
||||||
|
types_or: [ python, pyi ]
|
||||||
|
args: [ --fix ]
|
||||||
|
# Run the formatter.
|
||||||
|
- id: ruff-format
|
||||||
|
types_or: [ python, pyi ]
|
@ -0,0 +1,24 @@
|
|||||||
|
Marker Contributor Agreement
|
||||||
|
|
||||||
|
This Marker Contributor Agreement ("MCA") applies to any contribution that you make to any product or project managed by us (the "project"), and sets out the intellectual property rights you grant to us in the contributed materials. The term "us" shall mean Endless Labs, Inc. The term "you" shall mean the person or entity identified below.
|
||||||
|
|
||||||
|
If you agree to be bound by these terms, sign by writing "I have read the CLA document and I hereby sign the CLA" in response to the CLA bot Github comment. Read this agreement carefully before signing. These terms and conditions constitute a binding legal agreement.
|
||||||
|
|
||||||
|
1. The term 'contribution' or 'contributed materials' means any source code, object code, patch, tool, sample, graphic, specification, manual, documentation, or any other material posted or submitted by you to the project.
|
||||||
|
2. With respect to any worldwide copyrights, or copyright applications and registrations, in your contribution:
|
||||||
|
- you hereby assign to us joint ownership, and to the extent that such assignment is or becomes invalid, ineffective or unenforceable, you hereby grant to us a perpetual, irrevocable, non-exclusive, worldwide, no-charge, royalty free, unrestricted license to exercise all rights under those copyrights. This includes, at our option, the right to sublicense these same rights to third parties through multiple levels of sublicensees or other licensing arrangements, including dual-license structures for commercial customers;
|
||||||
|
- you agree that each of us can do all things in relation to your contribution as if each of us were the sole owners, and if one of us makes a derivative work of your contribution, the one who makes the derivative work (or has it made will be the sole owner of that derivative work;
|
||||||
|
- you agree that you will not assert any moral rights in your contribution against us, our licensees or transferees;
|
||||||
|
- you agree that we may register a copyright in your contribution and exercise all ownership rights associated with it; and
|
||||||
|
- you agree that neither of us has any duty to consult with, obtain the consent of, pay or render an accounting to the other for any use or distribution of vour contribution.
|
||||||
|
3. With respect to any patents you own, or that you can license without payment to any third party, you hereby grant to us a perpetual, irrevocable, non-exclusive, worldwide, no-charge, royalty-free license to:
|
||||||
|
- make, have made, use, sell, offer to sell, import, and otherwise transfer your contribution in whole or in part, alone or in combination with or included in any product, work or materials arising out of the project to which your contribution was submitted, and
|
||||||
|
- at our option, to sublicense these same rights to third parties through multiple levels of sublicensees or other licensing arrangements.
|
||||||
|
If you or your affiliates institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the contribution or any project it was submitted to constitutes direct or contributory patent infringement, then any patent licenses granted to you under this agreement for that contribution shall terminate as of the date such litigation is filed.
|
||||||
|
4. Except as set out above, you keep all right, title, and interest in your contribution. The rights that you grant to us under these terms are effective on the date you first submitted a contribution to us, even if your submission took place before the date you sign these terms. Any contribution we make available under any license will also be made available under a suitable FSF (Free Software Foundation) or OSI (Open Source Initiative) approved license.
|
||||||
|
5. You covenant, represent, warrant and agree that:
|
||||||
|
- each contribution that you submit is and shall be an original work of authorship and you can legally grant the rights set out in this MCA;
|
||||||
|
- to the best of your knowledge, each contribution will not violate any third party's copyrights, trademarks, patents, or other intellectual property rights; and
|
||||||
|
- each contribution shall be in compliance with U.S. export control laws and other applicable export and import laws.
|
||||||
|
You agree to notify us if you become aware of any circumstance which would make any of the foregoing representations inaccurate in any respect. Endless Labs, Inc. may publicly disclose your participation in the project, including the fact that you have signed the MCA.
|
||||||
|
6. This MCA is governed by the laws of the State of California and applicable U.S. Federal law. Any choice of law rules will not apply.
|
@ -0,0 +1,674 @@
|
|||||||
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 29 June 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 General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
the GNU General Public License is intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users. We, the Free Software Foundation, use the
|
||||||
|
GNU General Public License for most of our software; it applies also to
|
||||||
|
any other work released this way by its authors. You can apply it to
|
||||||
|
your programs, too.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to prevent others from denying you
|
||||||
|
these rights or asking you to surrender the rights. Therefore, you have
|
||||||
|
certain responsibilities if you distribute copies of the software, or if
|
||||||
|
you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
|
For example, if you distribute copies of such a program, whether
|
||||||
|
gratis or for a fee, you must pass on to the recipients the same
|
||||||
|
freedoms that you received. You must make sure that they, too, receive
|
||||||
|
or can get the source code. And you must show them these terms so they
|
||||||
|
know their rights.
|
||||||
|
|
||||||
|
Developers that use the GNU GPL protect your rights with two steps:
|
||||||
|
(1) assert copyright on the software, and (2) offer you this License
|
||||||
|
giving you legal permission to copy, distribute and/or modify it.
|
||||||
|
|
||||||
|
For the developers' and authors' protection, the GPL clearly explains
|
||||||
|
that there is no warranty for this free software. For both users' and
|
||||||
|
authors' sake, the GPL requires that modified versions be marked as
|
||||||
|
changed, so that their problems will not be attributed erroneously to
|
||||||
|
authors of previous versions.
|
||||||
|
|
||||||
|
Some devices are designed to deny users access to install or run
|
||||||
|
modified versions of the software inside them, although the manufacturer
|
||||||
|
can do so. This is fundamentally incompatible with the aim of
|
||||||
|
protecting users' freedom to change the software. The systematic
|
||||||
|
pattern of such abuse occurs in the area of products for individuals to
|
||||||
|
use, which is precisely where it is most unacceptable. Therefore, we
|
||||||
|
have designed this version of the GPL to prohibit the practice for those
|
||||||
|
products. If such problems arise substantially in other domains, we
|
||||||
|
stand ready to extend this provision to those domains in future versions
|
||||||
|
of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
|
Finally, every program is threatened constantly by software patents.
|
||||||
|
States should not allow patents to restrict development and use of
|
||||||
|
software on general-purpose computers, but in those that do, we wish to
|
||||||
|
avoid the special danger that patents applied to a free program could
|
||||||
|
make it effectively proprietary. To prevent this, the GPL assures that
|
||||||
|
patents cannot be used to render the program non-free.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Use with the GNU Affero General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU Affero General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the special requirements of the GNU Affero General Public License,
|
||||||
|
section 13, concerning interaction through a network will apply to the
|
||||||
|
combination as such.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU General Public License from time to time. Such new versions will
|
||||||
|
be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
Marker pdf to markdown converter
|
||||||
|
Copyright (C) 2023 Vikas Paruchuri
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program does terminal interaction, make it output a short
|
||||||
|
notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
|
Marker Copyright (C) 2023 Vikas Paruchuri
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||||
|
parts of the General Public License. Of course, your program's commands
|
||||||
|
might be different; for a GUI interface, you would use an "about box".
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU GPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
The GNU General Public License does not permit incorporating your program
|
||||||
|
into proprietary programs. If your program is a subroutine library, you
|
||||||
|
may consider it more useful to permit linking proprietary applications with
|
||||||
|
the library. If this is what you want to do, use the GNU Lesser General
|
||||||
|
Public License instead of this License. But first, please read
|
||||||
|
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
@ -0,0 +1,511 @@
|
|||||||
|
# Marker
|
||||||
|
|
||||||
|
Marker converts documents to markdown, JSON, and HTML quickly and accurately.
|
||||||
|
|
||||||
|
- Converts PDF, image, PPTX, DOCX, XLSX, HTML, EPUB files in all languages
|
||||||
|
- Formats tables, forms, equations, inline math, links, references, and code blocks
|
||||||
|
- Extracts and saves images
|
||||||
|
- Removes headers/footers/other artifacts
|
||||||
|
- Extensible with your own formatting and logic
|
||||||
|
- Optionally boost accuracy with LLMs
|
||||||
|
- Works on GPU, CPU, or MPS
|
||||||
|
|
||||||
|
## Performance
|
||||||
|
|
||||||
|
<img src="data/images/overall.png" width="800px"/>
|
||||||
|
|
||||||
|
Marker benchmarks favorably compared to cloud services like Llamaparse and Mathpix, as well as other open source tools.
|
||||||
|
|
||||||
|
The above results are running single PDF pages serially. Marker is significantly faster when running in batch mode, with a projected throughput of 122 pages/second on an H100 (.18 seconds per page across 22 processes).
|
||||||
|
|
||||||
|
See [below](#benchmarks) for detailed speed and accuracy benchmarks, and instructions on how to run your own benchmarks.
|
||||||
|
|
||||||
|
## Hybrid Mode
|
||||||
|
|
||||||
|
For the highest accuracy, pass the `--use_llm` flag to use an LLM alongside marker. This will do things like merge tables across pages, handle inline math, format tables properly, and extract values from forms. It can use any gemini or ollama model. By default, it uses `gemini-2.0-flash`. See [below](#llm-services) for details.
|
||||||
|
|
||||||
|
Here is a table benchmark comparing marker, gemini flash alone, and marker with use_llm:
|
||||||
|
|
||||||
|
<img src="data/images/table.png" width="400px"/>
|
||||||
|
|
||||||
|
As you can see, the use_llm mode offers higher accuracy than marker or gemini alone.
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
| PDF | File type | Markdown | JSON |
|
||||||
|
|-----|-----------|------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------|
|
||||||
|
| [Think Python](https://greenteapress.com/thinkpython/thinkpython.pdf) | Textbook | [View](https://github.com/VikParuchuri/marker/blob/master/data/examples/markdown/thinkpython/thinkpython.md) | [View](https://github.com/VikParuchuri/marker/blob/master/data/examples/json/thinkpython.json) |
|
||||||
|
| [Switch Transformers](https://arxiv.org/pdf/2101.03961.pdf) | arXiv paper | [View](https://github.com/VikParuchuri/marker/blob/master/data/examples/markdown/switch_transformers/switch_trans.md) | [View](https://github.com/VikParuchuri/marker/blob/master/data/examples/json/switch_trans.json) |
|
||||||
|
| [Multi-column CNN](https://arxiv.org/pdf/1804.07821.pdf) | arXiv paper | [View](https://github.com/VikParuchuri/marker/blob/master/data/examples/markdown/multicolcnn/multicolcnn.md) | [View](https://github.com/VikParuchuri/marker/blob/master/data/examples/json/multicolcnn.json) |
|
||||||
|
|
||||||
|
# Commercial usage
|
||||||
|
|
||||||
|
I want marker to be as widely accessible as possible, while still funding my development/training costs. Research and personal usage is always okay, but there are some restrictions on commercial usage.
|
||||||
|
|
||||||
|
The weights for the models are licensed `cc-by-nc-sa-4.0`, but I will waive that for any organization under \$5M USD in gross revenue in the most recent 12-month period AND under $5M in lifetime VC/angel funding raised. You also must not be competitive with the [Datalab API](https://www.datalab.to/). If you want to remove the GPL license requirements (dual-license) and/or use the weights commercially over the revenue limit, check out the options [here](https://www.datalab.to).
|
||||||
|
|
||||||
|
# Hosted API
|
||||||
|
|
||||||
|
There's a hosted API for marker available [here](https://www.datalab.to/):
|
||||||
|
|
||||||
|
- Supports PDFs, word documents, and powerpoints
|
||||||
|
- 1/4th the price of leading cloud-based competitors
|
||||||
|
- High uptime (99.99%), quality, and speed (around 15 seconds to convert a 250 page PDF)
|
||||||
|
|
||||||
|
# Community
|
||||||
|
|
||||||
|
[Discord](https://discord.gg//KuZwXNGnfH) is where we discuss future development.
|
||||||
|
|
||||||
|
# Installation
|
||||||
|
|
||||||
|
You'll need python 3.10+ and PyTorch. You may need to install the CPU version of torch first if you're not using a Mac or a GPU machine. See [here](https://pytorch.org/get-started/locally/) for more details.
|
||||||
|
|
||||||
|
Install with:
|
||||||
|
|
||||||
|
```shell
|
||||||
|
pip install marker-pdf
|
||||||
|
```
|
||||||
|
|
||||||
|
If you want to use marker on documents other than PDFs, you will need to install additional dependencies with:
|
||||||
|
|
||||||
|
```shell
|
||||||
|
pip install marker-pdf[full]
|
||||||
|
```
|
||||||
|
|
||||||
|
# Usage
|
||||||
|
|
||||||
|
First, some configuration:
|
||||||
|
|
||||||
|
- Your torch device will be automatically detected, but you can override this. For example, `TORCH_DEVICE=cuda`.
|
||||||
|
- Some PDFs, even digital ones, have bad text in them. Set the `force_ocr` flag to ensure your PDF runs through OCR, or the `strip_existing_ocr` to keep all digital text, and strip out any existing OCR text.
|
||||||
|
|
||||||
|
## Interactive App
|
||||||
|
|
||||||
|
I've included a streamlit app that lets you interactively try marker with some basic options. Run it with:
|
||||||
|
|
||||||
|
```shell
|
||||||
|
pip install streamlit
|
||||||
|
marker_gui
|
||||||
|
```
|
||||||
|
|
||||||
|
## Convert a single file
|
||||||
|
|
||||||
|
```shell
|
||||||
|
marker_single /path/to/file.pdf
|
||||||
|
```
|
||||||
|
|
||||||
|
You can pass in PDFs or images.
|
||||||
|
|
||||||
|
Options:
|
||||||
|
- `--output_dir PATH`: Directory where output files will be saved. Defaults to the value specified in settings.OUTPUT_DIR.
|
||||||
|
- `--output_format [markdown|json|html]`: Specify the format for the output results.
|
||||||
|
- `--paginate_output`: Paginates the output, using `\n\n{PAGE_NUMBER}` followed by `-` * 48, then `\n\n`
|
||||||
|
- `--use_llm`: Uses an LLM to improve accuracy. You must set your Gemini API key using the `GOOGLE_API_KEY` env var.
|
||||||
|
- `--redo_inline_math`: If you want the highest quality inline math conversion, use this along with `--use_llm`.
|
||||||
|
- `--disable_image_extraction`: Don't extract images from the PDF. If you also specify `--use_llm`, then images will be replaced with a description.
|
||||||
|
- `--page_range TEXT`: Specify which pages to process. Accepts comma-separated page numbers and ranges. Example: `--page_range "0,5-10,20"` will process pages 0, 5 through 10, and page 20.
|
||||||
|
- `--force_ocr`: Force OCR processing on the entire document, even for pages that might contain extractable text.
|
||||||
|
- `--strip_existing_ocr`: Remove all existing OCR text in the document and re-OCR with surya.
|
||||||
|
- `--debug`: Enable debug mode for additional logging and diagnostic information.
|
||||||
|
- `--processors TEXT`: Override the default processors by providing their full module paths, separated by commas. Example: `--processors "module1.processor1,module2.processor2"`
|
||||||
|
- `--config_json PATH`: Path to a JSON configuration file containing additional settings.
|
||||||
|
- `--languages TEXT`: Optionally specify which languages to use for OCR processing. Accepts a comma-separated list. Example: `--languages "en,fr,de"` for English, French, and German.
|
||||||
|
- `config --help`: List all available builders, processors, and converters, and their associated configuration. These values can be used to build a JSON configuration file for additional tweaking of marker defaults.
|
||||||
|
- `--converter_cls`: One of `marker.converters.pdf.PdfConverter` (default) or `marker.converters.table.TableConverter`. The `PdfConverter` will convert the whole PDF, the `TableConverter` will only extract and convert tables.
|
||||||
|
- `--llm_service`: Which llm service to use if `--use_llm` is passed. This defaults to `marker.services.gemini.GoogleGeminiService`.
|
||||||
|
- `--help`: see all of the flags that can be passed into marker. (it supports many more options then are listed above)
|
||||||
|
|
||||||
|
The list of supported languages for surya OCR is [here](https://github.com/VikParuchuri/surya/blob/master/surya/recognition/languages.py). If you don't need OCR, marker can work with any language.
|
||||||
|
|
||||||
|
## Convert multiple files
|
||||||
|
|
||||||
|
```shell
|
||||||
|
marker /path/to/input/folder --workers 4
|
||||||
|
```
|
||||||
|
|
||||||
|
- `marker` supports all the same options from `marker_single` above.
|
||||||
|
- `--workers` is the number of conversion workers to run simultaneously. This is set to 5 by default, but you can increase it to increase throughput, at the cost of more CPU/GPU usage. Marker will use 5GB of VRAM per worker at the peak, and 3.5GB average.
|
||||||
|
|
||||||
|
## Convert multiple files on multiple GPUs
|
||||||
|
|
||||||
|
```shell
|
||||||
|
NUM_DEVICES=4 NUM_WORKERS=15 marker_chunk_convert ../pdf_in ../md_out
|
||||||
|
```
|
||||||
|
|
||||||
|
- `NUM_DEVICES` is the number of GPUs to use. Should be `2` or greater.
|
||||||
|
- `NUM_WORKERS` is the number of parallel processes to run on each GPU.
|
||||||
|
|
||||||
|
## Use from python
|
||||||
|
|
||||||
|
See the `PdfConverter` class at `marker/converters/pdf.py` function for additional arguments that can be passed.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from marker.converters.pdf import PdfConverter
|
||||||
|
from marker.models import create_model_dict
|
||||||
|
from marker.output import text_from_rendered
|
||||||
|
|
||||||
|
converter = PdfConverter(
|
||||||
|
artifact_dict=create_model_dict(),
|
||||||
|
)
|
||||||
|
rendered = converter("FILEPATH")
|
||||||
|
text, _, images = text_from_rendered(rendered)
|
||||||
|
```
|
||||||
|
|
||||||
|
`rendered` will be a pydantic basemodel with different properties depending on the output type requested. With markdown output (default), you'll have the properties `markdown`, `metadata`, and `images`. For json output, you'll have `children`, `block_type`, and `metadata`.
|
||||||
|
|
||||||
|
### Custom configuration
|
||||||
|
|
||||||
|
You can pass configuration using the `ConfigParser`. To see all available options, do `marker_single --help`.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from marker.converters.pdf import PdfConverter
|
||||||
|
from marker.models import create_model_dict
|
||||||
|
from marker.config.parser import ConfigParser
|
||||||
|
|
||||||
|
config = {
|
||||||
|
"output_format": "json",
|
||||||
|
"ADDITIONAL_KEY": "VALUE"
|
||||||
|
}
|
||||||
|
config_parser = ConfigParser(config)
|
||||||
|
|
||||||
|
converter = PdfConverter(
|
||||||
|
config=config_parser.generate_config_dict(),
|
||||||
|
artifact_dict=create_model_dict(),
|
||||||
|
processor_list=config_parser.get_processors(),
|
||||||
|
renderer=config_parser.get_renderer(),
|
||||||
|
llm_service=config_parser.get_llm_service()
|
||||||
|
)
|
||||||
|
rendered = converter("FILEPATH")
|
||||||
|
```
|
||||||
|
|
||||||
|
### Extract blocks
|
||||||
|
|
||||||
|
Each document consists of one or more pages. Pages contain blocks, which can themselves contain other blocks. It's possible to programmatically manipulate these blocks.
|
||||||
|
|
||||||
|
Here's an example of extracting all forms from a document:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from marker.converters.pdf import PdfConverter
|
||||||
|
from marker.models import create_model_dict
|
||||||
|
from marker.schema import BlockTypes
|
||||||
|
|
||||||
|
converter = PdfConverter(
|
||||||
|
artifact_dict=create_model_dict(),
|
||||||
|
)
|
||||||
|
document = converter.build_document("FILEPATH")
|
||||||
|
forms = document.contained_blocks((BlockTypes.Form,))
|
||||||
|
```
|
||||||
|
|
||||||
|
Look at the processors for more examples of extracting and manipulating blocks.
|
||||||
|
|
||||||
|
## Other converters
|
||||||
|
|
||||||
|
You can also use other converters that define different conversion pipelines:
|
||||||
|
|
||||||
|
### Extract tables
|
||||||
|
|
||||||
|
The `TableConverter` will only convert and extract tables:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from marker.converters.table import TableConverter
|
||||||
|
from marker.models import create_model_dict
|
||||||
|
from marker.output import text_from_rendered
|
||||||
|
|
||||||
|
converter = TableConverter(
|
||||||
|
artifact_dict=create_model_dict(),
|
||||||
|
)
|
||||||
|
rendered = converter("FILEPATH")
|
||||||
|
text, _, images = text_from_rendered(rendered)
|
||||||
|
```
|
||||||
|
|
||||||
|
This takes all the same configuration as the PdfConverter. You can specify the configuration `force_layout_block=Table` to avoid layout detection and instead assume every page is a table. Set `output_format=json` to also get cell bounding boxes.
|
||||||
|
|
||||||
|
You can also run this via the CLI with
|
||||||
|
```shell
|
||||||
|
marker_single FILENAME --use_llm --force_layout_block Table --converter_cls marker.converters.table.TableConverter --output_format json
|
||||||
|
```
|
||||||
|
|
||||||
|
# Output Formats
|
||||||
|
|
||||||
|
## Markdown
|
||||||
|
|
||||||
|
Markdown output will include:
|
||||||
|
|
||||||
|
- image links (images will be saved in the same folder)
|
||||||
|
- formatted tables
|
||||||
|
- embedded LaTeX equations (fenced with `$$`)
|
||||||
|
- Code is fenced with triple backticks
|
||||||
|
- Superscripts for footnotes
|
||||||
|
|
||||||
|
## HTML
|
||||||
|
|
||||||
|
HTML output is similar to markdown output:
|
||||||
|
|
||||||
|
- Images are included via `img` tags
|
||||||
|
- equations are fenced with `<math>` tags
|
||||||
|
- code is in `pre` tags
|
||||||
|
|
||||||
|
## JSON
|
||||||
|
|
||||||
|
JSON output will be organized in a tree-like structure, with the leaf nodes being blocks. Examples of leaf nodes are a single list item, a paragraph of text, or an image.
|
||||||
|
|
||||||
|
The output will be a list, with each list item representing a page. Each page is considered a block in the internal marker schema. There are different types of blocks to represent different elements.
|
||||||
|
|
||||||
|
Pages have the keys:
|
||||||
|
|
||||||
|
- `id` - unique id for the block.
|
||||||
|
- `block_type` - the type of block. The possible block types can be seen in `marker/schema/__init__.py`. As of this writing, they are ["Line", "Span", "FigureGroup", "TableGroup", "ListGroup", "PictureGroup", "Page", "Caption", "Code", "Figure", "Footnote", "Form", "Equation", "Handwriting", "TextInlineMath", "ListItem", "PageFooter", "PageHeader", "Picture", "SectionHeader", "Table", "Text", "TableOfContents", "Document"]
|
||||||
|
- `html` - the HTML for the page. Note that this will have recursive references to children. The `content-ref` tags must be replaced with the child content if you want the full html. You can see an example of this at `marker/output.py:json_to_html`. That function will take in a single block from the json output, and turn it into HTML.
|
||||||
|
- `polygon` - the 4-corner polygon of the page, in (x1,y1), (x2,y2), (x3, y3), (x4, y4) format. (x1,y1) is the top left, and coordinates go clockwise.
|
||||||
|
- `children` - the child blocks.
|
||||||
|
|
||||||
|
The child blocks have two additional keys:
|
||||||
|
|
||||||
|
- `section_hierarchy` - indicates the sections that the block is part of. `1` indicates an h1 tag, `2` an h2, and so on.
|
||||||
|
- `images` - base64 encoded images. The key will be the block id, and the data will be the encoded image.
|
||||||
|
|
||||||
|
Note that child blocks of pages can have their own children as well (a tree structure).
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"id": "/page/10/Page/366",
|
||||||
|
"block_type": "Page",
|
||||||
|
"html": "<content-ref src='/page/10/SectionHeader/0'></content-ref><content-ref src='/page/10/SectionHeader/1'></content-ref><content-ref src='/page/10/Text/2'></content-ref><content-ref src='/page/10/Text/3'></content-ref><content-ref src='/page/10/Figure/4'></content-ref><content-ref src='/page/10/SectionHeader/5'></content-ref><content-ref src='/page/10/SectionHeader/6'></content-ref><content-ref src='/page/10/TextInlineMath/7'></content-ref><content-ref src='/page/10/TextInlineMath/8'></content-ref><content-ref src='/page/10/Table/9'></content-ref><content-ref src='/page/10/SectionHeader/10'></content-ref><content-ref src='/page/10/Text/11'></content-ref>",
|
||||||
|
"polygon": [[0.0, 0.0], [612.0, 0.0], [612.0, 792.0], [0.0, 792.0]],
|
||||||
|
"children": [
|
||||||
|
{
|
||||||
|
"id": "/page/10/SectionHeader/0",
|
||||||
|
"block_type": "SectionHeader",
|
||||||
|
"html": "<h1>Supplementary Material for <i>Subspace Adversarial Training</i> </h1>",
|
||||||
|
"polygon": [
|
||||||
|
[217.845703125, 80.630859375], [374.73046875, 80.630859375],
|
||||||
|
[374.73046875, 107.0],
|
||||||
|
[217.845703125, 107.0]
|
||||||
|
],
|
||||||
|
"children": null,
|
||||||
|
"section_hierarchy": {
|
||||||
|
"1": "/page/10/SectionHeader/1"
|
||||||
|
},
|
||||||
|
"images": {}
|
||||||
|
},
|
||||||
|
...
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
## Metadata
|
||||||
|
|
||||||
|
All output formats will return a metadata dictionary, with the following fields:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"table_of_contents": [
|
||||||
|
{
|
||||||
|
"title": "Introduction",
|
||||||
|
"heading_level": 1,
|
||||||
|
"page_id": 0,
|
||||||
|
"polygon": [...]
|
||||||
|
}
|
||||||
|
], // computed PDF table of contents
|
||||||
|
"page_stats": [
|
||||||
|
{
|
||||||
|
"page_id": 0,
|
||||||
|
"text_extraction_method": "pdftext",
|
||||||
|
"block_counts": [("Span", 200), ...]
|
||||||
|
},
|
||||||
|
...
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
# LLM Services
|
||||||
|
|
||||||
|
When running with the `--use_llm` flag, you have a choice of services you can use:
|
||||||
|
|
||||||
|
- `Gemini` - this will use the Gemini developer API by default. You'll need to pass `--gemini_api_key` to configuration.
|
||||||
|
- `Google Vertex` - this will use vertex, which can be more reliable. You'll need to pass `--vertex_project_id`. To use it, set `--llm_service=marker.services.vertex.GoogleVertexService`.
|
||||||
|
- `Ollama` - this will use local models. You can configure `--ollama_base_url` and `--ollama_model`. To use it, set `--llm_service=marker.services.ollama.OllamaService`.
|
||||||
|
- `Claude` - this will use the anthropic API. You can configure `--claude_api_key`, and `--claude_model_name`. To use it, set `--llm_service=marker.services.claude.ClaudeService`.
|
||||||
|
- `OpenAI` - this supports any openai-like endpoint. You can configure `--openai_api_key`, `--openai_model`, and `--openai_base_url`. To use it, set `--llm_service=marker.services.openai.OpenAIService`.
|
||||||
|
|
||||||
|
These services may have additional optional configuration as well - you can see it by viewing the classes.
|
||||||
|
|
||||||
|
# Internals
|
||||||
|
|
||||||
|
Marker is easy to extend. The core units of marker are:
|
||||||
|
|
||||||
|
- `Providers`, at `marker/providers`. These provide information from a source file, like a PDF.
|
||||||
|
- `Builders`, at `marker/builders`. These generate the initial document blocks and fill in text, using info from the providers.
|
||||||
|
- `Processors`, at `marker/processors`. These process specific blocks, for example the table formatter is a processor.
|
||||||
|
- `Renderers`, at `marker/renderers`. These use the blocks to render output.
|
||||||
|
- `Schema`, at `marker/schema`. The classes for all the block types.
|
||||||
|
- `Converters`, at `marker/converters`. They run the whole end to end pipeline.
|
||||||
|
|
||||||
|
To customize processing behavior, override the `processors`. To add new output formats, write a new `renderer`. For additional input formats, write a new `provider.`
|
||||||
|
|
||||||
|
Processors and renderers can be directly passed into the base `PDFConverter`, so you can specify your own custom processing easily.
|
||||||
|
|
||||||
|
## API server
|
||||||
|
|
||||||
|
There is a very simple API server you can run like this:
|
||||||
|
|
||||||
|
```shell
|
||||||
|
pip install -U uvicorn fastapi python-multipart
|
||||||
|
marker_server --port 8001
|
||||||
|
```
|
||||||
|
|
||||||
|
This will start a fastapi server that you can access at `localhost:8001`. You can go to `localhost:8001/docs` to see the endpoint options.
|
||||||
|
|
||||||
|
You can send requests like this:
|
||||||
|
|
||||||
|
```
|
||||||
|
import requests
|
||||||
|
import json
|
||||||
|
|
||||||
|
post_data = {
|
||||||
|
'filepath': 'FILEPATH',
|
||||||
|
# Add other params here
|
||||||
|
}
|
||||||
|
|
||||||
|
requests.post("http://localhost:8001/marker", data=json.dumps(post_data)).json()
|
||||||
|
```
|
||||||
|
|
||||||
|
Note that this is not a very robust API, and is only intended for small-scale use. If you want to use this server, but want a more robust conversion option, you can use the hosted [Datalab API](https://www.datalab.to/plans).
|
||||||
|
|
||||||
|
# Troubleshooting
|
||||||
|
|
||||||
|
There are some settings that you may find useful if things aren't working the way you expect:
|
||||||
|
|
||||||
|
- If you have issues with accuracy, try setting `--use_llm` to use an LLM to improve quality. You must set `GOOGLE_API_KEY` to a Gemini API key for this to work.
|
||||||
|
- Make sure to set `force_ocr` if you see garbled text - this will re-OCR the document.
|
||||||
|
- `TORCH_DEVICE` - set this to force marker to use a given torch device for inference.
|
||||||
|
- If you're getting out of memory errors, decrease worker count. You can also try splitting up long PDFs into multiple files.
|
||||||
|
|
||||||
|
## Debugging
|
||||||
|
|
||||||
|
Pass the `debug` option to activate debug mode. This will save images of each page with detected layout and text, as well as output a json file with additional bounding box information.
|
||||||
|
|
||||||
|
# Benchmarks
|
||||||
|
|
||||||
|
## Overall PDF Conversion
|
||||||
|
|
||||||
|
We created a [benchmark set](https://huggingface.co/datasets/datalab-to/marker_benchmark) by extracting single PDF pages from common crawl. We scored based on a heuristic that aligns text with ground truth text segments, and an LLM as a judge scoring method.
|
||||||
|
|
||||||
|
| Method | Avg Time | Heuristic Score | LLM Score |
|
||||||
|
|------------|----------|-----------------|-----------|
|
||||||
|
| marker | 2.83837 | 95.6709 | 4.23916 |
|
||||||
|
| llamaparse | 23.348 | 84.2442 | 3.97619 |
|
||||||
|
| mathpix | 6.36223 | 86.4281 | 4.15626 |
|
||||||
|
| docling | 3.69949 | 86.7073 | 3.70429 |
|
||||||
|
|
||||||
|
Benchmarks were run on an H100 for markjer and docling - llamaparse and mathpix used their cloud services. We can also look at it by document type:
|
||||||
|
|
||||||
|
<img src="data/images/per_doc.png" width="1000px"/>
|
||||||
|
|
||||||
|
| Document Type | Marker heuristic | Marker LLM | Llamaparse Heuristic | Llamaparse LLM | Mathpix Heuristic | Mathpix LLM | Docling Heuristic | Docling LLM |
|
||||||
|
|----------------------|------------------|------------|----------------------|----------------|-------------------|-------------|-------------------|-------------|
|
||||||
|
| Scientific paper | 96.6737 | 4.34899 | 87.1651 | 3.96421 | 91.2267 | 4.46861 | 92.135 | 3.72422 |
|
||||||
|
| Book page | 97.1846 | 4.16168 | 90.9532 | 4.07186 | 93.8886 | 4.35329 | 90.0556 | 3.64671 |
|
||||||
|
| Other | 95.1632 | 4.25076 | 81.1385 | 4.01835 | 79.6231 | 4.00306 | 83.8223 | 3.76147 |
|
||||||
|
| Form | 88.0147 | 3.84663 | 66.3081 | 3.68712 | 64.7512 | 3.33129 | 68.3857 | 3.40491 |
|
||||||
|
| Presentation | 95.1562 | 4.13669 | 81.2261 | 4 | 83.6737 | 3.95683 | 84.8405 | 3.86331 |
|
||||||
|
| Financial document | 95.3697 | 4.39106 | 82.5812 | 4.16111 | 81.3115 | 4.05556 | 86.3882 | 3.8 |
|
||||||
|
| Letter | 98.4021 | 4.5 | 93.4477 | 4.28125 | 96.0383 | 4.45312 | 92.0952 | 4.09375 |
|
||||||
|
| Engineering document | 93.9244 | 4.04412 | 77.4854 | 3.72059 | 80.3319 | 3.88235 | 79.6807 | 3.42647 |
|
||||||
|
| Legal document | 96.689 | 4.27759 | 86.9769 | 3.87584 | 91.601 | 4.20805 | 87.8383 | 3.65552 |
|
||||||
|
| Newspaper page | 98.8733 | 4.25806 | 84.7492 | 3.90323 | 96.9963 | 4.45161 | 92.6496 | 3.51613 |
|
||||||
|
| Magazine page | 98.2145 | 4.38776 | 87.2902 | 3.97959 | 93.5934 | 4.16327 | 93.0892 | 4.02041 |
|
||||||
|
|
||||||
|
## Throughput
|
||||||
|
|
||||||
|
We benchmarked throughput using a [single long PDF](https://www.greenteapress.com/thinkpython/thinkpython.pdf).
|
||||||
|
|
||||||
|
| Method | Time per page | Time per document | VRAM used |
|
||||||
|
|---------|---------------|-------------------|---------- |
|
||||||
|
| marker | 0.18 | 43.42 | 3.17GB |
|
||||||
|
|
||||||
|
The projected throughput is 122 pages per second on an H100 - we can run 22 individual processes given the VRAM used.
|
||||||
|
|
||||||
|
## Table Conversion
|
||||||
|
|
||||||
|
Marker can extract tables from PDFs using `marker.converters.table.TableConverter`. The table extraction performance is measured by comparing the extracted HTML representation of tables against the original HTML representations using the test split of [FinTabNet](https://developer.ibm.com/exchanges/data/all/fintabnet/). The HTML representations are compared using a tree edit distance based metric to judge both structure and content. Marker detects and identifies the structure of all tables in a PDF page and achieves these scores:
|
||||||
|
|
||||||
|
| Method | Avg score | Total tables |
|
||||||
|
|------------------|-----------|--------------|
|
||||||
|
| marker | 0.816 | 99 |
|
||||||
|
| marker w/use_llm | 0.907 | 99 |
|
||||||
|
| gemini | 0.829 | 99 |
|
||||||
|
|
||||||
|
The `--use_llm` flag can significantly improve table recognition performance, as you can see.
|
||||||
|
|
||||||
|
We filter out tables that we cannot align with the ground truth, since fintabnet and our layout model have slightly different detection methods (this results in some tables being split/merged).
|
||||||
|
|
||||||
|
## Running your own benchmarks
|
||||||
|
|
||||||
|
You can benchmark the performance of marker on your machine. Install marker manually with:
|
||||||
|
|
||||||
|
```shell
|
||||||
|
git clone https://github.com/VikParuchuri/marker.git
|
||||||
|
poetry install
|
||||||
|
```
|
||||||
|
|
||||||
|
### Overall PDF Conversion
|
||||||
|
|
||||||
|
Download the benchmark data [here](https://drive.google.com/file/d/1ZSeWDo2g1y0BRLT7KnbmytV2bjWARWba/view?usp=sharing) and unzip. Then run the overall benchmark like this:
|
||||||
|
|
||||||
|
```shell
|
||||||
|
python benchmarks/overall.py --methods marker --scores heuristic,llm
|
||||||
|
```
|
||||||
|
|
||||||
|
Options:
|
||||||
|
|
||||||
|
- `--use_llm` use an llm to improve the marker results.
|
||||||
|
- `--max_rows` how many rows to process for the benchmark.
|
||||||
|
- `--methods` can be `llamaparse`, `mathpix`, `docling`, `marker`. Comma separated.
|
||||||
|
- `--scores` which scoring functions to use, can be `llm`, `heuristic`. Comma separated.
|
||||||
|
|
||||||
|
### Table Conversion
|
||||||
|
The processed FinTabNet dataset is hosted [here](https://huggingface.co/datasets/datalab-to/fintabnet-test) and is automatically downloaded. Run the benchmark with:
|
||||||
|
|
||||||
|
```shell
|
||||||
|
python benchmarks/table/table.py --max_rows 100
|
||||||
|
```
|
||||||
|
|
||||||
|
Options:
|
||||||
|
|
||||||
|
- `--use_llm` uses an llm with marker to improve accuracy.
|
||||||
|
- `--use_gemini` also benchmarks gemini 2.0 flash.
|
||||||
|
|
||||||
|
# How it works
|
||||||
|
|
||||||
|
Marker is a pipeline of deep learning models:
|
||||||
|
|
||||||
|
- Extract text, OCR if necessary (heuristics, [surya](https://github.com/VikParuchuri/surya))
|
||||||
|
- Detect page layout and find reading order ([surya](https://github.com/VikParuchuri/surya))
|
||||||
|
- Clean and format each block (heuristics, [texify](https://github.com/VikParuchuri/texify), [surya](https://github.com/VikParuchuri/surya))
|
||||||
|
- Optionally use an LLM to improve quality
|
||||||
|
- Combine blocks and postprocess complete text
|
||||||
|
|
||||||
|
It only uses models where necessary, which improves speed and accuracy.
|
||||||
|
|
||||||
|
# Limitations
|
||||||
|
|
||||||
|
PDF is a tricky format, so marker will not always work perfectly. Here are some known limitations that are on the roadmap to address:
|
||||||
|
|
||||||
|
- Very complex layouts, with nested tables and forms, may not work
|
||||||
|
- Forms may not be rendered well
|
||||||
|
|
||||||
|
Note: Passing the `--use_llm` flag will mostly solve these issues.
|
||||||
|
|
||||||
|
# Thanks
|
||||||
|
|
||||||
|
This work would not have been possible without amazing open source models and datasets, including (but not limited to):
|
||||||
|
|
||||||
|
- Surya
|
||||||
|
- Texify
|
||||||
|
- Pypdfium2/pdfium
|
||||||
|
- DocLayNet from IBM
|
||||||
|
|
||||||
|
Thank you to the authors of these models and datasets for making them available to the community!
|
@ -0,0 +1,53 @@
|
|||||||
|
import json
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
import datasets
|
||||||
|
from tqdm import tqdm
|
||||||
|
|
||||||
|
from benchmarks.overall.registry import METHOD_REGISTRY
|
||||||
|
from benchmarks.overall.schema import FullResult
|
||||||
|
|
||||||
|
|
||||||
|
def build_dataset(bench_dataset: datasets.Dataset, result: FullResult, score_types: List[str], max_rows: int | None = None) -> datasets.Dataset:
|
||||||
|
rows = []
|
||||||
|
for idx, sample in tqdm(enumerate(bench_dataset), desc="Building dataset"):
|
||||||
|
if idx not in result["markdown"]:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if max_rows is not None and idx >= max_rows:
|
||||||
|
break
|
||||||
|
|
||||||
|
row = {
|
||||||
|
"uuid": sample["uuid"],
|
||||||
|
"classification": sample["classification"],
|
||||||
|
"language": sample["language"],
|
||||||
|
"img": sample["img"],
|
||||||
|
}
|
||||||
|
for method in result["markdown"][idx]:
|
||||||
|
if method == "gt":
|
||||||
|
continue
|
||||||
|
|
||||||
|
method_cls = METHOD_REGISTRY[method]()
|
||||||
|
md = result["markdown"][idx][method]
|
||||||
|
try:
|
||||||
|
method_img = method_cls.render(result["markdown"][idx][method])
|
||||||
|
except Exception as e:
|
||||||
|
# This can happen when the markdown is None
|
||||||
|
method_img = PIL.Image.new("RGB", (200, 200))
|
||||||
|
|
||||||
|
row[f"{method}_md"] = md
|
||||||
|
row[f"{method}_img"] = method_img
|
||||||
|
|
||||||
|
for score_type in score_types:
|
||||||
|
try:
|
||||||
|
row[f"{method}_{score_type}"] = result["scores"][idx][method][score_type]["score"]
|
||||||
|
except KeyError:
|
||||||
|
row[f"{method}_{score_type}"] = -1.0 # Missing score
|
||||||
|
try:
|
||||||
|
row[f"{method}_{score_type}_detail"] = json.dumps(result["scores"][idx][method][score_type]["specific_scores"])
|
||||||
|
except KeyError:
|
||||||
|
row[f"{method}_{score_type}_detail"] = "" # Missing detail
|
||||||
|
rows.append(row)
|
||||||
|
ds = datasets.Dataset.from_list(rows)
|
||||||
|
return ds
|
||||||
|
|
@ -0,0 +1,68 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
from typing import Dict, List
|
||||||
|
|
||||||
|
import tabulate
|
||||||
|
|
||||||
|
from benchmarks.overall.schema import FullResult
|
||||||
|
|
||||||
|
def write_table(title: str, rows: list, headers: list, out_path: Path, filename: str):
|
||||||
|
table = tabulate.tabulate(rows, headers=headers, tablefmt="github")
|
||||||
|
with open(out_path / filename, "w", encoding="utf-8") as f:
|
||||||
|
f.write(f"# {title}\n")
|
||||||
|
f.write(table)
|
||||||
|
print(title)
|
||||||
|
print(table)
|
||||||
|
|
||||||
|
|
||||||
|
def print_scores(result: FullResult, out_path: Path, methods: List[str], score_types: List[str], default_score_type="heuristic", default_method="marker"):
|
||||||
|
document_types = list(result["averages_by_type"][default_method][default_score_type].keys())
|
||||||
|
headers = ["Document Type"]
|
||||||
|
for method in methods:
|
||||||
|
for score_type in score_types:
|
||||||
|
headers.append(f"{method} {score_type}")
|
||||||
|
|
||||||
|
document_rows = [[k] for k in document_types]
|
||||||
|
for i, doc_type in enumerate(document_types):
|
||||||
|
for method in methods:
|
||||||
|
for score_type in score_types:
|
||||||
|
avg_score = sum(result["averages_by_type"][method][score_type][doc_type]) / max(1, len(result["averages_by_type"][method][score_type][doc_type]))
|
||||||
|
document_rows[i].append(avg_score)
|
||||||
|
|
||||||
|
write_table("Document Types", document_rows, headers, out_path, "document_types.md")
|
||||||
|
|
||||||
|
headers = ["Block Type"]
|
||||||
|
block_types = list(result["averages_by_block_type"][default_method][default_score_type].keys()) # all possible blocks
|
||||||
|
block_score_types = list(result["averages_by_block_type"][default_method].keys())
|
||||||
|
for method in methods:
|
||||||
|
for score_type in block_score_types:
|
||||||
|
headers.append(f"{method} {score_type}")
|
||||||
|
|
||||||
|
block_rows = [[k] for k in block_types]
|
||||||
|
for i, block_type in enumerate(block_types):
|
||||||
|
for method in methods:
|
||||||
|
for score_type in block_score_types:
|
||||||
|
avg_score = sum(result["averages_by_block_type"][method][score_type][block_type]) / max(1, len(result["averages_by_block_type"][method][score_type][block_type]))
|
||||||
|
block_rows[i].append(avg_score)
|
||||||
|
|
||||||
|
write_table("Block types", block_rows, headers, out_path, "block_types.md")
|
||||||
|
|
||||||
|
headers = ["Method", "Avg Time"] + score_types
|
||||||
|
inference_rows = [[k] for k in methods]
|
||||||
|
all_raw_scores = [result["scores"][i] for i in result["scores"]]
|
||||||
|
for i, method in enumerate(methods):
|
||||||
|
avg_time = sum(result["average_times"][method]) / max(1, len(result["average_times"][method]))
|
||||||
|
inference_rows[i].append(avg_time)
|
||||||
|
for score_type in score_types:
|
||||||
|
scores_lst = []
|
||||||
|
for ar in all_raw_scores:
|
||||||
|
try:
|
||||||
|
# Sometimes a few llm scores are missing
|
||||||
|
scores_lst.append(ar[method][score_type]["score"])
|
||||||
|
except KeyError:
|
||||||
|
continue
|
||||||
|
avg_score = sum(scores_lst) / max(1, len(scores_lst))
|
||||||
|
inference_rows[i].append(avg_score)
|
||||||
|
|
||||||
|
write_table("Overall Results", inference_rows, headers, out_path, "overall.md")
|
||||||
|
|
||||||
|
print("Scores computed by aligning ground truth markdown blocks with predicted markdown for each method. The scores are 0-100 based on edit distance.")
|
@ -0,0 +1,63 @@
|
|||||||
|
import json
|
||||||
|
from json import JSONDecodeError
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import datasets
|
||||||
|
from tqdm import tqdm
|
||||||
|
|
||||||
|
|
||||||
|
class Downloader:
|
||||||
|
cache_path: Path = Path("cache")
|
||||||
|
service: str
|
||||||
|
|
||||||
|
def __init__(self, api_key, app_id, max_rows: int = 2200):
|
||||||
|
self.cache_path.mkdir(exist_ok=True)
|
||||||
|
self.max_rows = max_rows
|
||||||
|
self.api_key = api_key
|
||||||
|
self.app_id = app_id
|
||||||
|
self.ds = datasets.load_dataset("datalab-to/marker_benchmark", split="train")
|
||||||
|
|
||||||
|
def get_html(self, pdf_bytes):
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def upload_ds(self):
|
||||||
|
rows = []
|
||||||
|
for file in self.cache_path.glob("*.json"):
|
||||||
|
with open(file, "r") as f:
|
||||||
|
data = json.load(f)
|
||||||
|
rows.append(data)
|
||||||
|
|
||||||
|
out_ds = datasets.Dataset.from_list(rows, features=datasets.Features({
|
||||||
|
"md": datasets.Value("string"),
|
||||||
|
"uuid": datasets.Value("string"),
|
||||||
|
"time": datasets.Value("float"),
|
||||||
|
}))
|
||||||
|
out_ds.push_to_hub(f"datalab-to/marker_benchmark_{self.service}", private=True)
|
||||||
|
|
||||||
|
def generate_data(self):
|
||||||
|
max_rows = self.max_rows
|
||||||
|
for idx, sample in tqdm(enumerate(self.ds), desc=f"Saving {self.service} results"):
|
||||||
|
cache_file = self.cache_path / f"{idx}.json"
|
||||||
|
if cache_file.exists():
|
||||||
|
continue
|
||||||
|
|
||||||
|
pdf_bytes = sample["pdf"] # This is a single page PDF
|
||||||
|
try:
|
||||||
|
out_data = self.get_html(pdf_bytes)
|
||||||
|
except JSONDecodeError as e:
|
||||||
|
print(f"Error with sample {idx}: {e}")
|
||||||
|
continue
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error with sample {idx}: {e}")
|
||||||
|
continue
|
||||||
|
out_data["uuid"] = sample["uuid"]
|
||||||
|
|
||||||
|
with cache_file.open("w") as f:
|
||||||
|
json.dump(out_data, f)
|
||||||
|
|
||||||
|
if idx >= max_rows:
|
||||||
|
break
|
||||||
|
|
||||||
|
def __call__(self):
|
||||||
|
self.generate_data()
|
||||||
|
self.upload_ds()
|
@ -0,0 +1,63 @@
|
|||||||
|
import io
|
||||||
|
import time
|
||||||
|
|
||||||
|
import requests
|
||||||
|
|
||||||
|
from benchmarks.overall.download.base import Downloader
|
||||||
|
|
||||||
|
|
||||||
|
class LlamaParseDownloader(Downloader):
|
||||||
|
service = "llamaparse"
|
||||||
|
|
||||||
|
def get_html(self, pdf_bytes):
|
||||||
|
rand_name = str(time.time()) + ".pdf"
|
||||||
|
start = time.time()
|
||||||
|
buff = io.BytesIO(pdf_bytes)
|
||||||
|
md = upload_and_parse_file(self.api_key, rand_name, buff)
|
||||||
|
end = time.time()
|
||||||
|
if isinstance(md, bytes):
|
||||||
|
md = md.decode("utf-8")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"md": md,
|
||||||
|
"time": end - start,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def upload_and_parse_file(api_key: str, fname: str, buff, max_retries: int = 180, delay: int = 1):
|
||||||
|
headers = {
|
||||||
|
"Authorization": f"Bearer {api_key}",
|
||||||
|
"Accept": "application/json"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Upload file
|
||||||
|
files = {
|
||||||
|
'file': (fname, buff, 'application/pdf')
|
||||||
|
}
|
||||||
|
response = requests.post(
|
||||||
|
'https://api.cloud.llamaindex.ai/api/v1/parsing/upload',
|
||||||
|
headers=headers,
|
||||||
|
files=files
|
||||||
|
)
|
||||||
|
response.raise_for_status()
|
||||||
|
job_id = response.json()['id']
|
||||||
|
|
||||||
|
# Poll for completion
|
||||||
|
for _ in range(max_retries):
|
||||||
|
status_response = requests.get(
|
||||||
|
f'https://api.cloud.llamaindex.ai/api/v1/parsing/job/{job_id}',
|
||||||
|
headers=headers
|
||||||
|
)
|
||||||
|
status_response.raise_for_status()
|
||||||
|
if status_response.json()['status'] == 'SUCCESS':
|
||||||
|
# Get results
|
||||||
|
result_response = requests.get(
|
||||||
|
f'https://api.cloud.llamaindex.ai/api/v1/parsing/job/{job_id}/result/markdown',
|
||||||
|
headers=headers
|
||||||
|
)
|
||||||
|
result_response.raise_for_status()
|
||||||
|
return result_response.json()['markdown']
|
||||||
|
|
||||||
|
time.sleep(delay)
|
||||||
|
|
||||||
|
raise TimeoutError("Job did not complete within the maximum retry attempts")
|
@ -0,0 +1,25 @@
|
|||||||
|
import click
|
||||||
|
|
||||||
|
from benchmarks.overall.download.llamaparse import LlamaParseDownloader
|
||||||
|
from benchmarks.overall.download.mathpix import MathpixDownloader
|
||||||
|
from benchmarks.overall.download.mistral import MistralDownloader
|
||||||
|
|
||||||
|
|
||||||
|
@click.command("Download data from inference services")
|
||||||
|
@click.argument("service", type=click.Choice(["mathpix", "llamaparse", "mistral"]))
|
||||||
|
@click.option("--max_rows", type=int, default=2200)
|
||||||
|
@click.option("--api_key", type=str, default=None)
|
||||||
|
@click.option("--app_id", type=str, default=None)
|
||||||
|
def main(service: str, max_rows: int, api_key: str, app_id: str):
|
||||||
|
registry = {
|
||||||
|
"mathpix": MathpixDownloader,
|
||||||
|
"llamaparse": LlamaParseDownloader,
|
||||||
|
"mistral": MistralDownloader,
|
||||||
|
}
|
||||||
|
downloader = registry[service](api_key, app_id, max_rows=max_rows)
|
||||||
|
|
||||||
|
# Generate data and upload to hub
|
||||||
|
downloader()
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
@ -0,0 +1,80 @@
|
|||||||
|
import json
|
||||||
|
import time
|
||||||
|
|
||||||
|
import requests
|
||||||
|
|
||||||
|
from benchmarks.overall.download.base import Downloader
|
||||||
|
|
||||||
|
|
||||||
|
class MathpixDownloader(Downloader):
|
||||||
|
service = "mathpix"
|
||||||
|
|
||||||
|
def get_html(self, pdf_bytes):
|
||||||
|
headers = {
|
||||||
|
"app_id": self.app_id,
|
||||||
|
"app_key": self.api_key,
|
||||||
|
}
|
||||||
|
start = time.time()
|
||||||
|
pdf_id = mathpix_request(pdf_bytes, headers)
|
||||||
|
status = mathpix_status(pdf_id, headers)
|
||||||
|
if status in ["processing", "error"]:
|
||||||
|
md = ""
|
||||||
|
else:
|
||||||
|
md = mathpix_results(pdf_id, headers)
|
||||||
|
end = time.time()
|
||||||
|
if isinstance(md, bytes):
|
||||||
|
md = md.decode("utf-8")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"md": md,
|
||||||
|
"time": end - start
|
||||||
|
}
|
||||||
|
|
||||||
|
def mathpix_request(buffer, headers):
|
||||||
|
response = requests.post("https://api.mathpix.com/v3/pdf",
|
||||||
|
headers=headers,
|
||||||
|
data={
|
||||||
|
"options_json": json.dumps(
|
||||||
|
{
|
||||||
|
"conversion_formats": {
|
||||||
|
"md": True,
|
||||||
|
"html": True
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
},
|
||||||
|
files={
|
||||||
|
"file": buffer
|
||||||
|
}
|
||||||
|
)
|
||||||
|
data = response.json()
|
||||||
|
pdf_id = data["pdf_id"]
|
||||||
|
return pdf_id
|
||||||
|
|
||||||
|
def mathpix_status(pdf_id, headers):
|
||||||
|
max_iters = 120
|
||||||
|
i = 0
|
||||||
|
status = "processing"
|
||||||
|
status2 = "processing"
|
||||||
|
while i < max_iters:
|
||||||
|
time.sleep(1)
|
||||||
|
response = requests.get(f"https://api.mathpix.com/v3/converter/{pdf_id}",
|
||||||
|
headers=headers
|
||||||
|
)
|
||||||
|
status_resp = response.json()
|
||||||
|
if "conversion_status" not in status_resp:
|
||||||
|
continue
|
||||||
|
status = status_resp["conversion_status"]["md"]["status"]
|
||||||
|
status2 = status_resp["conversion_status"]["html"]["status"]
|
||||||
|
if status == "completed" and status2 == "completed":
|
||||||
|
break
|
||||||
|
elif status == "error" or status2 == "error":
|
||||||
|
break
|
||||||
|
out_status = "completed" if status == "completed" and status2 == "completed" else "error"
|
||||||
|
return out_status
|
||||||
|
|
||||||
|
def mathpix_results(pdf_id, headers, ext="md"):
|
||||||
|
response = requests.get(f"https://api.mathpix.com/v3/converter/{pdf_id}.{ext}",
|
||||||
|
headers=headers
|
||||||
|
)
|
||||||
|
return response.content
|
@ -0,0 +1,73 @@
|
|||||||
|
import io
|
||||||
|
import time
|
||||||
|
import requests
|
||||||
|
|
||||||
|
from benchmarks.overall.download.base import Downloader
|
||||||
|
|
||||||
|
|
||||||
|
class MistralDownloader(Downloader):
|
||||||
|
service = "mistral"
|
||||||
|
|
||||||
|
def get_html(self, pdf_bytes):
|
||||||
|
rand_name = str(time.time()) + ".pdf"
|
||||||
|
start = time.time()
|
||||||
|
buff = io.BytesIO(pdf_bytes)
|
||||||
|
md = upload_and_process_file(self.api_key, rand_name, buff)
|
||||||
|
end = time.time()
|
||||||
|
if isinstance(md, bytes):
|
||||||
|
md = md.decode("utf-8")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"md": md,
|
||||||
|
"time": end - start,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def upload_and_process_file(api_key: str, fname: str, buff):
|
||||||
|
headers = {
|
||||||
|
"Authorization": f"Bearer {api_key}"
|
||||||
|
}
|
||||||
|
|
||||||
|
upload_headers = headers.copy()
|
||||||
|
files = {
|
||||||
|
'file': (fname, buff, 'application/pdf'),
|
||||||
|
'purpose': (None, 'ocr')
|
||||||
|
}
|
||||||
|
|
||||||
|
upload_response = requests.post(
|
||||||
|
'https://api.mistral.ai/v1/files',
|
||||||
|
headers=upload_headers,
|
||||||
|
files=files
|
||||||
|
)
|
||||||
|
upload_response.raise_for_status()
|
||||||
|
file_id = upload_response.json()['id']
|
||||||
|
|
||||||
|
url_headers = headers.copy()
|
||||||
|
url_headers["Accept"] = "application/json"
|
||||||
|
|
||||||
|
url_response = requests.get(
|
||||||
|
f'https://api.mistral.ai/v1/files/{file_id}/url?expiry=24',
|
||||||
|
headers=url_headers
|
||||||
|
)
|
||||||
|
url_response.raise_for_status()
|
||||||
|
signed_url = url_response.json()['url']
|
||||||
|
|
||||||
|
ocr_headers = headers.copy()
|
||||||
|
ocr_headers["Content-Type"] = "application/json"
|
||||||
|
|
||||||
|
ocr_data = {
|
||||||
|
"model": "mistral-ocr-latest",
|
||||||
|
"document": {
|
||||||
|
"type": "document_url",
|
||||||
|
"document_url": signed_url
|
||||||
|
},
|
||||||
|
"include_image_base64": True
|
||||||
|
}
|
||||||
|
ocr_response = requests.post(
|
||||||
|
'https://api.mistral.ai/v1/ocr',
|
||||||
|
headers=ocr_headers,
|
||||||
|
json=ocr_data
|
||||||
|
)
|
||||||
|
ocr_response.raise_for_status()
|
||||||
|
result = ocr_response.json()
|
||||||
|
return result["pages"][0]["markdown"]
|
@ -0,0 +1,221 @@
|
|||||||
|
import json
|
||||||
|
import random
|
||||||
|
import time
|
||||||
|
import os
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import List, Dict, Tuple, Literal
|
||||||
|
from PIL import Image
|
||||||
|
from collections import defaultdict
|
||||||
|
import tabulate
|
||||||
|
|
||||||
|
import click
|
||||||
|
import datasets
|
||||||
|
from google import genai
|
||||||
|
from google.genai.errors import APIError
|
||||||
|
from pydantic import BaseModel
|
||||||
|
from tqdm import tqdm
|
||||||
|
|
||||||
|
from marker.settings import settings
|
||||||
|
|
||||||
|
rating_prompt = """
|
||||||
|
You're a document analysis expert who is comparing two different markdown samples to an image to see which one represents the content of the image better. The markdown will be called version A and version B.
|
||||||
|
|
||||||
|
Here are some notes on the image and markdown:
|
||||||
|
- Some parts of the page may have been recognized as images and linked from the markdown, like ``.
|
||||||
|
- Tables will be formatted as Github flavored markdown.
|
||||||
|
- Block equations will be in LaTeX.
|
||||||
|
- The image and markdown may be in any language.
|
||||||
|
- The markdown is based on the text extracted from the document, and sometimes the document may have had bad OCR applied to it, resulting in gibberish text.
|
||||||
|
|
||||||
|
The markdown should fully capture the meaning and formatting of the text in the image. You'll evaluate the markdown based on the image provided.
|
||||||
|
|
||||||
|
**Instructions**
|
||||||
|
Follow this process to evaluate the markdown:
|
||||||
|
1. Carefully examine the image.
|
||||||
|
2. Carefully examine the first markdown input provided.
|
||||||
|
3. Describe how well version a represents the image.
|
||||||
|
4. Carefully examine the second markdown input provided.
|
||||||
|
5. Describe how well version B represents the image.
|
||||||
|
6. Compare version A and version B.
|
||||||
|
7. Decide which markdown representation is better, based on the criteria below. Output version_a if version a is better, and version_b if version b is better.
|
||||||
|
|
||||||
|
Use these criteria when judging the markdown:
|
||||||
|
- Overall - the overall quality of the markdown as compared to the image.
|
||||||
|
- Text quality - the quality of the text extraction from the image.
|
||||||
|
- Formatting quality - the quality of the formatting applied to the markdown, as compared to the image.
|
||||||
|
- Tables - how effectively the tables have been extracted and formatted.
|
||||||
|
- Forms - how effectively the forms have extracted and formatted.
|
||||||
|
- Equations - how effectively block equations have been converted to LaTeX.
|
||||||
|
- Lists - if the lists have been properly extracted and formatted.
|
||||||
|
- Images - if images are identified and placed correctly.
|
||||||
|
|
||||||
|
Notes on scoring:
|
||||||
|
- Perfect markdown will include all of the important text from the image, and the formatting will be correct (minor mistakes okay). It's okay to omit some text that isn't important to the meaning, like page numbers and chapter headings. If the entire page is an image, it's okay if the markdown is just a link to the image, unless the image would be better represented as text.
|
||||||
|
- Bad markdown will have major missing text segments from the markdown or completely unreadable formatting. It may also have key values that are different from the values in the image.
|
||||||
|
|
||||||
|
Output json, like in the example below.
|
||||||
|
|
||||||
|
**Example**
|
||||||
|
Version A
|
||||||
|
```markdown
|
||||||
|
# *Section 1*
|
||||||
|
This is some *markdown* extracted from a document. Here is a block equation:
|
||||||
|
$$\frac{ab \cdot x^5 + x^2 + 2 \cdot x + 123}{t}$$
|
||||||
|
```
|
||||||
|
Version B
|
||||||
|
```markdown
|
||||||
|
# Section 1
|
||||||
|
This is some markdown extracted from a document. Here is a block equation:
|
||||||
|
$$\frac{ab \cdot x^5 + x^2 + 2 \cdot x + 124}{t}$$
|
||||||
|
```
|
||||||
|
Output
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"image_description": "In the image, there is a section header 'Section 1', followed by some text and a block equation.",
|
||||||
|
"version_a_description": "In the markdown, there is a section header 'Section 1', followed by some text and a block equation.",
|
||||||
|
"version_b_description": "In the markdown, there is a section header 'Section 1', followed by some text and a block equation. The formatting in version b is slightly different from the image. The value 124 is also different from the image.",
|
||||||
|
"comparison": "Version A is better than version B. The text and formatting in version A matches the image better than version B. Version B also has an incorrect value.",
|
||||||
|
"winner": "version_a",
|
||||||
|
}
|
||||||
|
```
|
||||||
|
**Input**
|
||||||
|
Version A
|
||||||
|
```markdown
|
||||||
|
{{version_a}}
|
||||||
|
```
|
||||||
|
Version B
|
||||||
|
```markdown
|
||||||
|
{{version_b}}
|
||||||
|
```
|
||||||
|
**Output**
|
||||||
|
"""
|
||||||
|
|
||||||
|
class ComparerSchema(BaseModel):
|
||||||
|
image_description: str
|
||||||
|
version_a_description: str
|
||||||
|
version_b_description: str
|
||||||
|
comparison: str
|
||||||
|
winner: Literal["version_a", "version_b"]
|
||||||
|
|
||||||
|
|
||||||
|
class Comparer:
|
||||||
|
def __init__(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def __call__(
|
||||||
|
self,
|
||||||
|
img: Image.Image,
|
||||||
|
version_a: str,
|
||||||
|
version_b: str
|
||||||
|
) -> str | None:
|
||||||
|
if version_a is None and version_b is not None:
|
||||||
|
return "version_b"
|
||||||
|
elif version_b is None and version_a is not None:
|
||||||
|
return "version_a"
|
||||||
|
|
||||||
|
hydrated_prompt = rating_prompt.replace("{{version_a}}", version_a).replace("{{version_b}}", version_b)
|
||||||
|
try:
|
||||||
|
rating = self.llm_rater(img, hydrated_prompt)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error: {e}")
|
||||||
|
return
|
||||||
|
return rating
|
||||||
|
|
||||||
|
|
||||||
|
def llm_rater(self, img: Image.Image, prompt: str):
|
||||||
|
response = self.llm_response_wrapper(
|
||||||
|
[img, prompt],
|
||||||
|
ComparerSchema
|
||||||
|
)
|
||||||
|
assert "winner" in response, f"Response missing 'winner' key: {response}"
|
||||||
|
return response["winner"]
|
||||||
|
|
||||||
|
def llm_response_wrapper(
|
||||||
|
self,
|
||||||
|
prompt,
|
||||||
|
response_schema,
|
||||||
|
):
|
||||||
|
client = genai.Client(
|
||||||
|
http_options={"timeout": 60000},
|
||||||
|
vertexai=True,
|
||||||
|
project=os.getenv("VERTEX_PROJECT_ID"),
|
||||||
|
location=os.getenv("VERTEX_LOCATION"),
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
responses = client.models.generate_content(
|
||||||
|
model="gemini-2.0-flash-001",
|
||||||
|
contents=prompt,
|
||||||
|
config={
|
||||||
|
"temperature": 0,
|
||||||
|
"response_schema": response_schema,
|
||||||
|
"response_mime_type": "application/json",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
output = responses.candidates[0].content.parts[0].text
|
||||||
|
return json.loads(output)
|
||||||
|
except APIError as e:
|
||||||
|
print(f"Hit Gemini rate limit")
|
||||||
|
return
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error: {e}")
|
||||||
|
return
|
||||||
|
|
||||||
|
|
||||||
|
def display_win_rates_table(win_rates: dict):
|
||||||
|
table = []
|
||||||
|
headers = ["Method A", "Method B", "Wins", "Losses", "Win %"]
|
||||||
|
for method_a, method_b_dict in win_rates.items():
|
||||||
|
row = [method_a]
|
||||||
|
for method_b, results in method_b_dict.items():
|
||||||
|
row = [method_a, method_b, results["win"], results["loss"], (results["win"] / (results["win"] + results["loss"])) * 100]
|
||||||
|
table.append(row)
|
||||||
|
print(tabulate.tabulate(table, headers=headers, tablefmt="pretty"))
|
||||||
|
|
||||||
|
|
||||||
|
@click.command("Calculate win rates for document conversion methods")
|
||||||
|
@click.argument("dataset", type=str)
|
||||||
|
@click.option("--methods", type=str, help="List of methods to compare: comma separated like marker,mathpix")
|
||||||
|
@click.option("--row_samples", type=int, default=2, help="Number of samples per row")
|
||||||
|
@click.option("--max_rows", type=int, default=None, help="Maximum number of rows to process")
|
||||||
|
def main(
|
||||||
|
dataset: str,
|
||||||
|
methods: str,
|
||||||
|
row_samples: int,
|
||||||
|
max_rows: int
|
||||||
|
):
|
||||||
|
ds = datasets.load_dataset(dataset, split="train")
|
||||||
|
method_lst = methods.split(",")
|
||||||
|
win_rates = {m: defaultdict(lambda: defaultdict(int)) for m in method_lst}
|
||||||
|
comparer = Comparer()
|
||||||
|
max_rows = max_rows or len(ds)
|
||||||
|
|
||||||
|
for i in tqdm(range(max_rows), desc="Calculating win rates..."):
|
||||||
|
row = ds[i]
|
||||||
|
# Avoid any bias in ordering
|
||||||
|
random.shuffle(method_lst)
|
||||||
|
|
||||||
|
for j, method_a in enumerate(method_lst[:-1]):
|
||||||
|
for z, method_b in enumerate(method_lst[j:]):
|
||||||
|
if method_a == method_b:
|
||||||
|
continue
|
||||||
|
|
||||||
|
method_a_md = row[f"{method_a}_md"]
|
||||||
|
method_b_md = row[f"{method_b}_md"]
|
||||||
|
winner = comparer(row["img"], method_a_md, method_b_md)
|
||||||
|
if not winner:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if winner == "version_a":
|
||||||
|
win_rates[method_a][method_b]["win"] += 1
|
||||||
|
win_rates[method_b][method_a]["loss"] += 1
|
||||||
|
else:
|
||||||
|
win_rates[method_b][method_a]["win"] += 1
|
||||||
|
win_rates[method_a][method_b]["loss"] += 1
|
||||||
|
if i % 10 == 0:
|
||||||
|
display_win_rates_table(win_rates)
|
||||||
|
|
||||||
|
display_win_rates_table(win_rates)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
@ -0,0 +1,100 @@
|
|||||||
|
import io
|
||||||
|
import random
|
||||||
|
import re
|
||||||
|
from typing import Tuple
|
||||||
|
|
||||||
|
import markdown2
|
||||||
|
from PIL import Image
|
||||||
|
from playwright.sync_api import sync_playwright
|
||||||
|
|
||||||
|
from benchmarks.overall.methods.schema import BenchmarkResult
|
||||||
|
from marker.renderers.markdown import MarkdownRenderer
|
||||||
|
|
||||||
|
|
||||||
|
class BaseMethod:
|
||||||
|
def __init__(self, **kwargs):
|
||||||
|
for kwarg in kwargs:
|
||||||
|
if hasattr(self, kwarg):
|
||||||
|
setattr(self, kwarg, kwargs[kwarg])
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def convert_to_md(html: str):
|
||||||
|
md = MarkdownRenderer()
|
||||||
|
markdown = md.md_cls.convert(html)
|
||||||
|
return markdown
|
||||||
|
|
||||||
|
def __call__(self, sample) -> BenchmarkResult:
|
||||||
|
raise NotImplementedError()
|
||||||
|
|
||||||
|
def render(self, markdown: str):
|
||||||
|
return self.html_to_image(self.convert_to_html(markdown))
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def convert_to_html(md: str):
|
||||||
|
block_placeholders = []
|
||||||
|
inline_placeholders = []
|
||||||
|
|
||||||
|
# Add placeholders for the math
|
||||||
|
def block_sub(match):
|
||||||
|
content = match.group(1)
|
||||||
|
placeholder = f"1BLOCKMATH{len(block_placeholders)}1"
|
||||||
|
block_placeholders.append((placeholder, f"$${content}$$"))
|
||||||
|
return placeholder
|
||||||
|
|
||||||
|
def inline_sub(match):
|
||||||
|
content = match.group(1)
|
||||||
|
placeholder = f"1INLINEMATH{len(inline_placeholders)}1"
|
||||||
|
inline_placeholders.append((placeholder, f"${content}$"))
|
||||||
|
return placeholder
|
||||||
|
|
||||||
|
md = re.sub(r'\${2}(.*?)\${2}', block_sub, md, flags=re.DOTALL)
|
||||||
|
md = re.sub(r'\$(.*?)\$', inline_sub, md)
|
||||||
|
|
||||||
|
html = markdown2.markdown(md, extras=['tables'])
|
||||||
|
|
||||||
|
# Replace placeholders
|
||||||
|
for placeholder, math_str in block_placeholders:
|
||||||
|
html = html.replace(placeholder, math_str)
|
||||||
|
for placeholder, math_str in inline_placeholders:
|
||||||
|
html = html.replace(placeholder, math_str)
|
||||||
|
|
||||||
|
return html
|
||||||
|
|
||||||
|
def html_to_image(self, html: str) -> Image.Image:
|
||||||
|
with sync_playwright() as p:
|
||||||
|
browser = p.chromium.launch()
|
||||||
|
page = browser.new_page()
|
||||||
|
html_str = f"""
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.21/dist/katex.min.css" integrity="sha384-zh0CIslj+VczCZtlzBcjt5ppRcsAmDnRem7ESsYwWwg3m/OaJ2l4x7YBZl9Kxxib" crossorigin="anonymous">
|
||||||
|
<!-- The loading of KaTeX is deferred to speed up page rendering -->
|
||||||
|
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.21/dist/katex.min.js" integrity="sha384-Rma6DA2IPUwhNxmrB/7S3Tno0YY7sFu9WSYMCuulLhIqYSGZ2gKCJWIqhBWqMQfh" crossorigin="anonymous"></script>
|
||||||
|
<!-- To automatically render math in text elements, include the auto-render extension: -->
|
||||||
|
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.21/dist/contrib/auto-render.min.js" integrity="sha384-hCXGrW6PitJEwbkoStFjeJxv+fSOOQKOPbJxSfM6G5sWZjAyWhXiTIIAmQqnlLlh" crossorigin="anonymous"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
{html}
|
||||||
|
<script>
|
||||||
|
document.addEventListener("DOMContentLoaded", function() {{
|
||||||
|
renderMathInElement(document.body, {{
|
||||||
|
delimiters: [
|
||||||
|
{{left: '$$', right: '$$', display: true}},
|
||||||
|
{{left: '$', right: '$', display: false}}
|
||||||
|
],
|
||||||
|
throwOnError : false
|
||||||
|
}});
|
||||||
|
}});
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
""".strip()
|
||||||
|
page.set_viewport_size({"width": 1200, "height": 800})
|
||||||
|
page.set_content(html_str)
|
||||||
|
page.wait_for_load_state("domcontentloaded")
|
||||||
|
page.wait_for_timeout(500) # Wait for KaTeX to render
|
||||||
|
screenshot_bytes = page.screenshot(full_page=True)
|
||||||
|
browser.close()
|
||||||
|
|
||||||
|
return Image.open(io.BytesIO(screenshot_bytes))
|
@ -0,0 +1,26 @@
|
|||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
|
||||||
|
from benchmarks.overall.methods import BaseMethod, BenchmarkResult
|
||||||
|
|
||||||
|
|
||||||
|
class DoclingMethod(BaseMethod):
|
||||||
|
model_dict: dict = None
|
||||||
|
use_llm: bool = False
|
||||||
|
|
||||||
|
def __call__(self, sample) -> BenchmarkResult:
|
||||||
|
from docling.document_converter import DocumentConverter
|
||||||
|
pdf_bytes = sample["pdf"] # This is a single page PDF
|
||||||
|
converter = DocumentConverter()
|
||||||
|
|
||||||
|
with tempfile.NamedTemporaryFile(suffix=".pdf", mode="wb") as f:
|
||||||
|
f.write(pdf_bytes)
|
||||||
|
start = time.time()
|
||||||
|
result = converter.convert(f.name)
|
||||||
|
total = time.time() - start
|
||||||
|
|
||||||
|
return {
|
||||||
|
"markdown": result.document.export_to_markdown(),
|
||||||
|
"time": total
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,29 @@
|
|||||||
|
from typing import List
|
||||||
|
import json
|
||||||
|
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from benchmarks.overall.methods import BaseMethod, BenchmarkResult
|
||||||
|
|
||||||
|
|
||||||
|
class GTMethod(BaseMethod):
|
||||||
|
def __call__(self, sample) -> BenchmarkResult:
|
||||||
|
gt_blocks = json.loads(sample["gt_blocks"])
|
||||||
|
gt_html = [block["html"] for block in gt_blocks if len(block["html"]) > 0]
|
||||||
|
gt_markdown = [self.convert_to_md(block) for block in gt_html]
|
||||||
|
return {
|
||||||
|
"markdown": gt_markdown,
|
||||||
|
"time": 0
|
||||||
|
}
|
||||||
|
|
||||||
|
def render(self, html: List[str]) -> Image.Image:
|
||||||
|
joined = "\n\n".join(html)
|
||||||
|
html = f"""
|
||||||
|
<html>
|
||||||
|
<head></head>
|
||||||
|
<body>
|
||||||
|
{joined}
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
""".strip()
|
||||||
|
return self.html_to_image(html)
|
@ -0,0 +1,22 @@
|
|||||||
|
import datasets
|
||||||
|
|
||||||
|
from benchmarks.overall.methods import BaseMethod, BenchmarkResult
|
||||||
|
|
||||||
|
|
||||||
|
class LlamaParseMethod(BaseMethod):
|
||||||
|
llamaparse_ds: datasets.Dataset = None
|
||||||
|
|
||||||
|
def __call__(self, sample) -> BenchmarkResult:
|
||||||
|
uuid = sample["uuid"]
|
||||||
|
data = None
|
||||||
|
for row in self.llamaparse_ds:
|
||||||
|
if str(row["uuid"]) == str(uuid):
|
||||||
|
data = row
|
||||||
|
break
|
||||||
|
if not data:
|
||||||
|
raise ValueError(f"Could not find data for uuid {uuid}")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"markdown": data["md"],
|
||||||
|
"time": data["time"]
|
||||||
|
}
|
@ -0,0 +1,41 @@
|
|||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
|
||||||
|
from benchmarks.overall.methods import BaseMethod, BenchmarkResult
|
||||||
|
from marker.config.parser import ConfigParser
|
||||||
|
from marker.converters.pdf import PdfConverter
|
||||||
|
|
||||||
|
|
||||||
|
class MarkerMethod(BaseMethod):
|
||||||
|
model_dict: dict = None
|
||||||
|
use_llm: bool = False
|
||||||
|
|
||||||
|
def __call__(self, sample) -> BenchmarkResult:
|
||||||
|
pdf_bytes = sample["pdf"] # This is a single page PDF
|
||||||
|
parser = ConfigParser({
|
||||||
|
"page_range": "0",
|
||||||
|
"disable_tqdm": True,
|
||||||
|
"use_llm": self.use_llm,
|
||||||
|
"redo_inline_math": self.use_llm,
|
||||||
|
"llm_service": "marker.services.vertex.GoogleVertexService",
|
||||||
|
"vertex_project_id": os.getenv("VERTEX_PROJECT_ID"),
|
||||||
|
})
|
||||||
|
|
||||||
|
block_converter = PdfConverter(
|
||||||
|
artifact_dict=self.model_dict,
|
||||||
|
config=parser.generate_config_dict(),
|
||||||
|
llm_service=parser.get_llm_service()
|
||||||
|
)
|
||||||
|
|
||||||
|
with tempfile.NamedTemporaryFile(suffix=".pdf", mode="wb") as f:
|
||||||
|
f.write(pdf_bytes)
|
||||||
|
start = time.time()
|
||||||
|
rendered = block_converter(f.name)
|
||||||
|
total = time.time() - start
|
||||||
|
|
||||||
|
return {
|
||||||
|
"markdown": rendered.markdown,
|
||||||
|
"time": total
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,22 @@
|
|||||||
|
import datasets
|
||||||
|
|
||||||
|
from benchmarks.overall.methods import BaseMethod, BenchmarkResult
|
||||||
|
|
||||||
|
|
||||||
|
class MathpixMethod(BaseMethod):
|
||||||
|
mathpix_ds: datasets.Dataset = None
|
||||||
|
|
||||||
|
def __call__(self, sample) -> BenchmarkResult:
|
||||||
|
uuid = sample["uuid"]
|
||||||
|
data = None
|
||||||
|
for row in self.mathpix_ds:
|
||||||
|
if str(row["uuid"]) == str(uuid):
|
||||||
|
data = row
|
||||||
|
break
|
||||||
|
if not data:
|
||||||
|
raise ValueError(f"Could not find data for uuid {uuid}")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"markdown": data["md"],
|
||||||
|
"time": data["time"]
|
||||||
|
}
|
@ -0,0 +1,22 @@
|
|||||||
|
import datasets
|
||||||
|
|
||||||
|
from benchmarks.overall.methods import BaseMethod, BenchmarkResult
|
||||||
|
|
||||||
|
|
||||||
|
class MistralMethod(BaseMethod):
|
||||||
|
mistral_ds: datasets.Dataset = None
|
||||||
|
|
||||||
|
def __call__(self, sample) -> BenchmarkResult:
|
||||||
|
uuid = sample["uuid"]
|
||||||
|
data = None
|
||||||
|
for row in self.mistral_ds:
|
||||||
|
if str(row["uuid"]) == str(uuid):
|
||||||
|
data = row
|
||||||
|
break
|
||||||
|
if not data:
|
||||||
|
raise ValueError(f"Could not find data for uuid {uuid}")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"markdown": data["md"],
|
||||||
|
"time": data["time"]
|
||||||
|
}
|
@ -0,0 +1,91 @@
|
|||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
from io import BytesIO
|
||||||
|
|
||||||
|
import torch
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from benchmarks.overall.methods import BaseMethod, BenchmarkResult
|
||||||
|
|
||||||
|
|
||||||
|
def convert_single_page(filename: str, model, processor, device):
|
||||||
|
from olmocr.data.renderpdf import render_pdf_to_base64png
|
||||||
|
from olmocr.prompts import build_finetuning_prompt
|
||||||
|
from olmocr.prompts.anchor import get_anchor_text
|
||||||
|
|
||||||
|
image_base64 = render_pdf_to_base64png(filename, 1, target_longest_image_dim=1024)
|
||||||
|
|
||||||
|
# Build the prompt, using document metadata
|
||||||
|
anchor_text = get_anchor_text(filename, 1, pdf_engine="pdfreport", target_length=4000)
|
||||||
|
prompt = build_finetuning_prompt(anchor_text)
|
||||||
|
|
||||||
|
# Build the full prompt
|
||||||
|
messages = [
|
||||||
|
{
|
||||||
|
"role": "user",
|
||||||
|
"content": [
|
||||||
|
{"type": "text", "text": prompt},
|
||||||
|
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{image_base64}"}},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
# Apply the chat template and processor
|
||||||
|
text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
||||||
|
main_image = Image.open(BytesIO(base64.b64decode(image_base64)))
|
||||||
|
|
||||||
|
inputs = processor(
|
||||||
|
text=[text],
|
||||||
|
images=[main_image],
|
||||||
|
padding=True,
|
||||||
|
return_tensors="pt",
|
||||||
|
)
|
||||||
|
inputs = {key: value.to(device) for (key, value) in inputs.items()}
|
||||||
|
|
||||||
|
# Generate the output
|
||||||
|
output = model.generate(
|
||||||
|
**inputs,
|
||||||
|
temperature=0.8,
|
||||||
|
max_new_tokens=8192,
|
||||||
|
num_return_sequences=1,
|
||||||
|
do_sample=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Decode the output
|
||||||
|
prompt_length = inputs["input_ids"].shape[1]
|
||||||
|
new_tokens = output[:, prompt_length:]
|
||||||
|
text_output = processor.tokenizer.batch_decode(
|
||||||
|
new_tokens, skip_special_tokens=True
|
||||||
|
)[0]
|
||||||
|
|
||||||
|
try:
|
||||||
|
text_output = json.loads(text_output)
|
||||||
|
text = text_output["natural_text"]
|
||||||
|
except Exception:
|
||||||
|
try:
|
||||||
|
text = text_output.split("natural_text")[1].strip()
|
||||||
|
except Exception:
|
||||||
|
text = ""
|
||||||
|
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
class OlmOCRMethod(BaseMethod):
|
||||||
|
olmocr_model: dict = None
|
||||||
|
use_llm: bool = False
|
||||||
|
|
||||||
|
def __call__(self, sample) -> BenchmarkResult:
|
||||||
|
pdf_bytes = sample["pdf"] # This is a single page PDF
|
||||||
|
|
||||||
|
with tempfile.NamedTemporaryFile(suffix=".pdf", mode="wb") as f:
|
||||||
|
f.write(pdf_bytes)
|
||||||
|
start = time.time()
|
||||||
|
result = convert_single_page(f.name, self.olmocr_model["model"], self.olmocr_model["processor"], self.olmocr_model["model"].device)
|
||||||
|
total = time.time() - start
|
||||||
|
|
||||||
|
return {
|
||||||
|
"markdown": result,
|
||||||
|
"time": total
|
||||||
|
}
|
@ -0,0 +1,6 @@
|
|||||||
|
from typing import TypedDict, List
|
||||||
|
|
||||||
|
|
||||||
|
class BenchmarkResult(TypedDict):
|
||||||
|
markdown: str | List[str]
|
||||||
|
time: float | None
|
@ -0,0 +1,178 @@
|
|||||||
|
import json
|
||||||
|
import os
|
||||||
|
import traceback
|
||||||
|
from collections import defaultdict
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
import click
|
||||||
|
import datasets
|
||||||
|
import torch
|
||||||
|
from tqdm import tqdm
|
||||||
|
|
||||||
|
from benchmarks.overall.display.dataset import build_dataset
|
||||||
|
from benchmarks.overall.registry import SCORE_REGISTRY, METHOD_REGISTRY
|
||||||
|
from benchmarks.overall.schema import FullResult
|
||||||
|
from marker.logger import configure_logging
|
||||||
|
from marker.models import create_model_dict
|
||||||
|
from marker.settings import settings
|
||||||
|
from benchmarks.overall.display.table import print_scores
|
||||||
|
|
||||||
|
configure_logging()
|
||||||
|
|
||||||
|
|
||||||
|
def get_method_scores(benchmark_dataset: datasets.Dataset, methods: List[str], score_types: List[str], artifacts: dict, max_rows=None) -> FullResult:
|
||||||
|
bench_scores = {}
|
||||||
|
averages_by_type = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))
|
||||||
|
averages_by_block_type = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))
|
||||||
|
average_times = defaultdict(list)
|
||||||
|
markdown_by_method = defaultdict(dict)
|
||||||
|
total_rows = len(benchmark_dataset)
|
||||||
|
if max_rows:
|
||||||
|
total_rows = min(max_rows, total_rows)
|
||||||
|
for idx, sample in tqdm(enumerate(benchmark_dataset), desc="Running benchmark", total=total_rows):
|
||||||
|
if max_rows is not None and idx >= max_rows:
|
||||||
|
break
|
||||||
|
|
||||||
|
doc_type = sample["classification"]
|
||||||
|
gt_cls = METHOD_REGISTRY["gt"]
|
||||||
|
gt_blocks = json.loads(sample["gt_blocks"])
|
||||||
|
gt_md = gt_cls(**artifacts)(sample)["markdown"]
|
||||||
|
markdown_by_method[idx]["gt"] = gt_md
|
||||||
|
|
||||||
|
out_data = defaultdict(dict)
|
||||||
|
|
||||||
|
try:
|
||||||
|
for method in methods:
|
||||||
|
method_cls = METHOD_REGISTRY[method](**artifacts)
|
||||||
|
method_info = method_cls(sample)
|
||||||
|
method_md = method_info["markdown"]
|
||||||
|
if method_md is None:
|
||||||
|
method_md = "" # Avoid None values
|
||||||
|
|
||||||
|
average_times[method].append(method_info["time"])
|
||||||
|
markdown_by_method[idx][method] = method_md
|
||||||
|
|
||||||
|
for score_type in score_types:
|
||||||
|
score_cls = SCORE_REGISTRY[score_type]()
|
||||||
|
try:
|
||||||
|
scores = score_cls(sample, gt_md, method_md)
|
||||||
|
except Exception as e:
|
||||||
|
# Some scorers can fail, like the LLM one
|
||||||
|
print(f"Failed to score {method} with {score_type}: {e}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
out_data[method][score_type] = scores
|
||||||
|
|
||||||
|
averages_by_type[method][score_type][doc_type].append(scores["score"])
|
||||||
|
|
||||||
|
if "by_block" in scores["specific_scores"]: # Not all scorers support this
|
||||||
|
for score, gt_block in zip(scores["specific_scores"]["by_block"], gt_blocks):
|
||||||
|
averages_by_block_type[method][score_type][gt_block["block_type"]].append(score)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Failed to process {idx}: {e}")
|
||||||
|
traceback.print_exc()
|
||||||
|
if idx in markdown_by_method:
|
||||||
|
del markdown_by_method[idx]
|
||||||
|
continue
|
||||||
|
|
||||||
|
bench_scores[idx] = out_data
|
||||||
|
|
||||||
|
return {
|
||||||
|
"scores": bench_scores,
|
||||||
|
"markdown": markdown_by_method,
|
||||||
|
"averages_by_type": averages_by_type,
|
||||||
|
"averages_by_block_type": averages_by_block_type,
|
||||||
|
"average_times": average_times,
|
||||||
|
}
|
||||||
|
|
||||||
|
@click.command(help="Benchmark PDF to MD conversion.")
|
||||||
|
@click.option("--dataset", type=str, help="Path to the benchmark dataset", default="datalab-to/marker_benchmark")
|
||||||
|
@click.option("--out_dataset", type=str, help="Path to the output dataset", default=None)
|
||||||
|
@click.option("--methods", type=str, help="Comma separated list of other methods to compare against. Possible values: marker,mathpix,llamaparse,docling,mistral", default="marker")
|
||||||
|
@click.option("--scores", type=str, help="Comma separated list of scoring functions to use. Possible values: heuristic,llm", default="heuristic")
|
||||||
|
@click.option("--result_path", type=str, default=os.path.join(settings.OUTPUT_DIR, "benchmark", "overall"), help="Output path for results.")
|
||||||
|
@click.option("--max_rows", type=int, default=None, help="Maximum number of rows to process.")
|
||||||
|
@click.option("--use_llm", is_flag=True, help="Use the LLM model for better marker quality.")
|
||||||
|
@click.option("--languages", type=str, help="Comma separated list of languages to use for LLM", default=None)
|
||||||
|
def main(
|
||||||
|
dataset: str,
|
||||||
|
out_dataset: str,
|
||||||
|
methods: str,
|
||||||
|
scores: str,
|
||||||
|
result_path: str,
|
||||||
|
max_rows: int,
|
||||||
|
use_llm: bool,
|
||||||
|
languages: str
|
||||||
|
):
|
||||||
|
out_path = Path(result_path)
|
||||||
|
out_path.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
methods = methods.split(",")
|
||||||
|
for method in methods:
|
||||||
|
if method not in METHOD_REGISTRY:
|
||||||
|
raise ValueError(f"Method {method} not allowed. Allowed methods are {METHOD_REGISTRY.keys()}")
|
||||||
|
|
||||||
|
# Ensure marker is always first
|
||||||
|
all_methods = list(set(methods))
|
||||||
|
methods = ["marker"] if "marker" in all_methods else []
|
||||||
|
methods += [m for m in all_methods if m != "marker"]
|
||||||
|
|
||||||
|
score_types = scores.split(",")
|
||||||
|
for score_type in score_types:
|
||||||
|
if score_type not in SCORE_REGISTRY:
|
||||||
|
raise ValueError(f"Score type {score_type} not allowed. Allowed types are {SCORE_REGISTRY.keys()}")
|
||||||
|
|
||||||
|
if languages:
|
||||||
|
languages = languages.split(",")
|
||||||
|
else:
|
||||||
|
languages = None
|
||||||
|
|
||||||
|
benchmark_dataset = datasets.load_dataset(dataset, split="train")
|
||||||
|
if languages:
|
||||||
|
benchmark_dataset = benchmark_dataset.filter(lambda x: x["language"] in languages)
|
||||||
|
|
||||||
|
artifacts = {
|
||||||
|
"model_dict": create_model_dict(),
|
||||||
|
"use_llm": use_llm,
|
||||||
|
"mathpix_ds": None,
|
||||||
|
"llamaparse_ds": None,
|
||||||
|
}
|
||||||
|
|
||||||
|
if "mathpix" in methods:
|
||||||
|
artifacts["mathpix_ds"] = datasets.load_dataset("datalab-to/marker_benchmark_mathpix", split="train")
|
||||||
|
|
||||||
|
if "llamaparse" in methods:
|
||||||
|
artifacts["llamaparse_ds"] = datasets.load_dataset("datalab-to/marker_benchmark_llamaparse", split="train")
|
||||||
|
|
||||||
|
if "mistral" in methods:
|
||||||
|
artifacts["mistral_ds"] = datasets.load_dataset("datalab-to/marker_benchmark_mistral", split="train")
|
||||||
|
|
||||||
|
if "olmocr" in methods:
|
||||||
|
from transformers import AutoProcessor, Qwen2VLForConditionalGeneration
|
||||||
|
model = Qwen2VLForConditionalGeneration.from_pretrained("allenai/olmOCR-7B-0225-preview",
|
||||||
|
torch_dtype=torch.bfloat16).eval()
|
||||||
|
processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
|
||||||
|
model.to(torch.device("cuda" if torch.cuda.is_available() else "cpu"))
|
||||||
|
artifacts["olmocr_model"] = {"model": model, "processor": processor}
|
||||||
|
|
||||||
|
print(f"Running benchmark with methods: {methods} and scores: {score_types}")
|
||||||
|
result = get_method_scores(benchmark_dataset, methods, score_types, artifacts, max_rows=max_rows)
|
||||||
|
|
||||||
|
# Display benchmark scoring tables
|
||||||
|
print_scores(result, out_path, methods, score_types, default_method=methods[0], default_score_type=score_types[0])
|
||||||
|
|
||||||
|
# Write to json
|
||||||
|
with open(out_path / "result.json", "w") as f:
|
||||||
|
json.dump(result, f)
|
||||||
|
|
||||||
|
if out_dataset:
|
||||||
|
if use_llm:
|
||||||
|
out_dataset += "_llm"
|
||||||
|
dataset = build_dataset(benchmark_dataset, result, score_types, max_rows=max_rows)
|
||||||
|
dataset.push_to_hub(out_dataset, private=True)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
|
|
@ -0,0 +1,24 @@
|
|||||||
|
from benchmarks.overall.methods.docling import DoclingMethod
|
||||||
|
from benchmarks.overall.methods.gt import GTMethod
|
||||||
|
from benchmarks.overall.methods.llamaparse import LlamaParseMethod
|
||||||
|
from benchmarks.overall.methods.marker import MarkerMethod
|
||||||
|
from benchmarks.overall.methods.mathpix import MathpixMethod
|
||||||
|
from benchmarks.overall.methods.mistral import MistralMethod
|
||||||
|
from benchmarks.overall.methods.olmocr import OlmOCRMethod
|
||||||
|
from benchmarks.overall.scorers.heuristic import HeuristicScorer
|
||||||
|
from benchmarks.overall.scorers.llm import LLMScorer
|
||||||
|
|
||||||
|
SCORE_REGISTRY = {
|
||||||
|
"heuristic": HeuristicScorer,
|
||||||
|
"llm": LLMScorer
|
||||||
|
}
|
||||||
|
|
||||||
|
METHOD_REGISTRY = {
|
||||||
|
"marker": MarkerMethod,
|
||||||
|
"gt": GTMethod,
|
||||||
|
"mathpix": MathpixMethod,
|
||||||
|
"llamaparse": LlamaParseMethod,
|
||||||
|
"docling": DoclingMethod,
|
||||||
|
"olmocr": OlmOCRMethod,
|
||||||
|
"mistral": MistralMethod
|
||||||
|
}
|
@ -0,0 +1,12 @@
|
|||||||
|
from typing import TypedDict, List, Dict
|
||||||
|
|
||||||
|
from benchmarks.overall.scorers.schema import BlockScores
|
||||||
|
|
||||||
|
AVG_TYPE = Dict[str, Dict[str, Dict[str, List[float]]]]
|
||||||
|
|
||||||
|
class FullResult(TypedDict):
|
||||||
|
scores: Dict[int, Dict[str, Dict[str, BlockScores]]]
|
||||||
|
averages_by_type: AVG_TYPE
|
||||||
|
averages_by_block_type: AVG_TYPE
|
||||||
|
average_times: Dict[str, List[float]]
|
||||||
|
markdown: Dict[int, Dict[str, str]]
|
@ -0,0 +1,11 @@
|
|||||||
|
from typing import List
|
||||||
|
|
||||||
|
from benchmarks.overall.scorers.schema import BlockScores
|
||||||
|
|
||||||
|
|
||||||
|
class BaseScorer:
|
||||||
|
def __init__(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def __call__(self, sample, gt_markdown: List[str], method_markdown: str) -> BlockScores:
|
||||||
|
raise NotImplementedError()
|
@ -0,0 +1,113 @@
|
|||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
import tempfile
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import latex2mathml.converter
|
||||||
|
|
||||||
|
class MarkdownCleaner:
|
||||||
|
def __init__(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def __call__(self, markdown):
|
||||||
|
markdown = self.normalize_markdown(markdown) # Use pandoc to normalize
|
||||||
|
|
||||||
|
# Replace math expressions with latexml
|
||||||
|
pattern = r'(?<!\\)\$(?:\$([^$]+)\$\$|\s*([^$\n]+?)\s*\$)'
|
||||||
|
markdown = re.sub(pattern, self.standardize_math, markdown)
|
||||||
|
|
||||||
|
# Replace image urls with a generic tag
|
||||||
|
pattern = r'!\[(.*?)\]\((https?://[^\s\)]+)\)'
|
||||||
|
markdown = re.sub(pattern, r'![link]', markdown)
|
||||||
|
|
||||||
|
# Clean up stray html tags
|
||||||
|
markdown = markdown.replace("<br>", "\n")
|
||||||
|
markdown = re.sub(r"<sub>(.*?)</sub>", r"\1", markdown)
|
||||||
|
markdown = re.sub(r"<sup>(.*?)</sup>", r"\1", markdown)
|
||||||
|
markdown = re.sub(r"<span.*?>(.*?)</span>", r"\1", markdown) # Remove span tags and keep content
|
||||||
|
|
||||||
|
# Clean up markdown formatting
|
||||||
|
markdown = re.sub(r"\s+", " ", markdown)
|
||||||
|
markdown = re.sub(r"\n+", "\n", markdown)
|
||||||
|
markdown = re.sub("\\.+", ".",
|
||||||
|
markdown) # Replace repeated periods with a single period, like in table of contents
|
||||||
|
markdown = re.sub("#+", "#", markdown) # Replace repeated headers with a single header
|
||||||
|
markdown = markdown.encode().decode('unicode-escape', errors="ignore") # Decode unicode characters properly
|
||||||
|
return markdown.strip().lower()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def normalize_markdown(md_text: str) -> str:
|
||||||
|
with tempfile.TemporaryDirectory() as tmp_dir:
|
||||||
|
dirpath = Path(tmp_dir)
|
||||||
|
input_file = dirpath / 'input.md'
|
||||||
|
input_file.write_text(md_text, encoding='utf-8')
|
||||||
|
|
||||||
|
# Markdown to HTML
|
||||||
|
html_file = dirpath / 'temp.html'
|
||||||
|
subprocess.run(
|
||||||
|
[
|
||||||
|
'pandoc',
|
||||||
|
str(input_file),
|
||||||
|
'-f', 'markdown+tex_math_dollars',
|
||||||
|
'-t', 'html',
|
||||||
|
'-o', str(html_file),
|
||||||
|
'--quiet'
|
||||||
|
],
|
||||||
|
check=True
|
||||||
|
)
|
||||||
|
|
||||||
|
# HTML to Markdown
|
||||||
|
output_file = dirpath / 'output.md'
|
||||||
|
subprocess.run(
|
||||||
|
[
|
||||||
|
'pandoc',
|
||||||
|
str(html_file),
|
||||||
|
'-f', 'html',
|
||||||
|
'-t', 'markdown+tex_math_dollars',
|
||||||
|
'-o', str(output_file),
|
||||||
|
'--quiet'
|
||||||
|
],
|
||||||
|
check=True
|
||||||
|
)
|
||||||
|
|
||||||
|
# Read back the normalized Markdown
|
||||||
|
normalized_md = output_file.read_text(encoding='utf-8')
|
||||||
|
|
||||||
|
return normalized_md
|
||||||
|
|
||||||
|
def standardize_math(self, match):
|
||||||
|
try:
|
||||||
|
delim = "$$" if match.group(0).startswith('$$') else "$"
|
||||||
|
math_content = match.group(1) or match.group(2)
|
||||||
|
if delim == "$$":
|
||||||
|
math_content = latex2mathml.converter.convert(math_content)
|
||||||
|
else:
|
||||||
|
math_content = self.clean_latex(math_content)
|
||||||
|
return f'{delim}{math_content}{delim}'
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Failed to standardize math expression: {match.group(0)} with error: {e}")
|
||||||
|
return match.group(0)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def clean_latex(latex_str):
|
||||||
|
latex_str = re.sub(r'\s+', ' ', latex_str.strip())
|
||||||
|
for tag in [r'\\text', r'\\mathrm', r'\\mathbf', r'\\textbf']:
|
||||||
|
latex_str = re.sub(tag + r'\{([^}]+)\}', r'\1', latex_str)
|
||||||
|
|
||||||
|
replacements = {
|
||||||
|
'\\times': '*',
|
||||||
|
'\\cdot': '*',
|
||||||
|
'\\div': '/',
|
||||||
|
'\\le': '<=',
|
||||||
|
'\\ge': '>=',
|
||||||
|
'\\neq': '!=',
|
||||||
|
'\\to': '\\rightarrow',
|
||||||
|
}
|
||||||
|
|
||||||
|
for old, new in replacements.items():
|
||||||
|
latex_str = latex_str.replace(old, new)
|
||||||
|
|
||||||
|
return latex_str
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -0,0 +1,105 @@
|
|||||||
|
from typing import List
|
||||||
|
|
||||||
|
from rapidfuzz import fuzz
|
||||||
|
|
||||||
|
from benchmarks.overall.scorers.clean import MarkdownCleaner
|
||||||
|
from benchmarks.overall.scorers.schema import BlockScores
|
||||||
|
from benchmarks.overall.scorers import BaseScorer
|
||||||
|
|
||||||
|
|
||||||
|
class HeuristicScorer(BaseScorer):
|
||||||
|
def __call__(self, sample, gt_markdown: List[str], method_markdown: str) -> BlockScores:
|
||||||
|
if not method_markdown:
|
||||||
|
return {
|
||||||
|
"score": 0,
|
||||||
|
"specific_scores": {
|
||||||
|
"order": 0,
|
||||||
|
"by_block": [0] * len(gt_markdown)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Standardize inputs
|
||||||
|
gt_markdown = [self.clean_input(block) for block in gt_markdown]
|
||||||
|
method_markdown = self.clean_input(method_markdown)
|
||||||
|
|
||||||
|
alignments = self.find_fuzzy_alignments(method_markdown, gt_markdown)
|
||||||
|
scores = [alignment["score"] for alignment in alignments]
|
||||||
|
|
||||||
|
# Find order score
|
||||||
|
orders = [alignment["start"] for alignment in alignments]
|
||||||
|
correct_order = list(range(len(gt_markdown)))
|
||||||
|
actual_order = sorted(range(len(gt_markdown)), key=lambda x: orders[x])
|
||||||
|
order_score = self.kendall_tau(correct_order, actual_order)
|
||||||
|
|
||||||
|
# Weight score by sequence length
|
||||||
|
gt_weights = [len(g) for g in gt_markdown]
|
||||||
|
weighted_scores = [score * weight for score, weight in zip(scores, gt_weights)]
|
||||||
|
|
||||||
|
# Weight the score by sequence length
|
||||||
|
overall_score = sum(weighted_scores) / max(1, sum(gt_weights))
|
||||||
|
overall_score = overall_score * 0.8 + order_score * 0.2
|
||||||
|
return {
|
||||||
|
"score": overall_score,
|
||||||
|
"specific_scores": {
|
||||||
|
"order": order_score,
|
||||||
|
"by_block": scores
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def kendall_tau(correct_order: List[int], actual_order: List[int]) -> float:
|
||||||
|
n = len(correct_order)
|
||||||
|
concordant = 0
|
||||||
|
discordant = 0
|
||||||
|
|
||||||
|
if n <= 1:
|
||||||
|
return 100
|
||||||
|
|
||||||
|
for i in range(n):
|
||||||
|
for j in range(i + 1, n):
|
||||||
|
correct_sign = correct_order[i] - correct_order[j]
|
||||||
|
actual_sign = actual_order[i] - actual_order[j]
|
||||||
|
|
||||||
|
if (correct_sign > 0 and actual_sign > 0) or (correct_sign < 0 and actual_sign < 0):
|
||||||
|
concordant += 1
|
||||||
|
elif (correct_sign < 0 and actual_sign > 0) or (correct_sign > 0 and actual_sign < 0):
|
||||||
|
discordant += 1
|
||||||
|
|
||||||
|
total_pairs = (n * (n - 1)) // 2
|
||||||
|
tau = (concordant - discordant) / total_pairs
|
||||||
|
tau = (tau + 1) / 2 # 0-1 scale
|
||||||
|
return tau * 100 # 0-100 scale
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def find_fuzzy_alignments(
|
||||||
|
main_string: str,
|
||||||
|
substrings: List[str],
|
||||||
|
threshold: int = 70
|
||||||
|
) -> List[dict]:
|
||||||
|
alignments = []
|
||||||
|
|
||||||
|
for idx, substr in enumerate(substrings):
|
||||||
|
result = fuzz.partial_ratio_alignment(substr, main_string, score_cutoff=threshold)
|
||||||
|
|
||||||
|
score = 0
|
||||||
|
dest_start = 0
|
||||||
|
dest_end = 0
|
||||||
|
if result:
|
||||||
|
score = result.score
|
||||||
|
dest_start = result.dest_start
|
||||||
|
dest_end = result.dest_end
|
||||||
|
|
||||||
|
alignments.append({
|
||||||
|
"string": substr,
|
||||||
|
"start": dest_start,
|
||||||
|
"end": dest_end,
|
||||||
|
"score": score,
|
||||||
|
"idx": idx
|
||||||
|
})
|
||||||
|
return alignments
|
||||||
|
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def clean_input(md: str):
|
||||||
|
cleaner = MarkdownCleaner()
|
||||||
|
return cleaner(md)
|
@ -0,0 +1,160 @@
|
|||||||
|
import json
|
||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
from PIL import Image
|
||||||
|
from google.genai.errors import APIError
|
||||||
|
from google import genai
|
||||||
|
import pypdfium2 as pdfium
|
||||||
|
|
||||||
|
from benchmarks.overall.scorers import BaseScorer, BlockScores
|
||||||
|
from marker.settings import settings
|
||||||
|
|
||||||
|
rating_prompt = """
|
||||||
|
You're a document analysis expert who is comparing some markdown to an image to make sure the markdown is correct. You're rating how effectively the provided markdown represents the full text and formatting in the image provided.
|
||||||
|
You're given an image, along with the extracted markdown:
|
||||||
|
- Some parts of the page may have been recognized as images and linked from the markdown, like ``.
|
||||||
|
- Tables will be formatted as Github flavored markdown.
|
||||||
|
- Block equations will be in LaTeX.
|
||||||
|
- The image and markdown may be in any language.
|
||||||
|
- The markdown is based on the text extracted from the document, and sometimes the document may have had bad OCR applied to it, resulting in gibberish text.
|
||||||
|
|
||||||
|
The markdown should fully capture the meaning and formatting of the text in the image. You'll evaluate the markdown based on the image provided.
|
||||||
|
|
||||||
|
**Instructions**
|
||||||
|
Follow this process to evaluate the markdown:
|
||||||
|
1. Carefully examine the image.
|
||||||
|
2. Carefully examine the markdown input provided.
|
||||||
|
3. Compare the image to the markdown representation. Does the markdown representation properly represent the important text and formatting in the image?
|
||||||
|
4. Assign component scores, as described below.
|
||||||
|
|
||||||
|
These are the primary scores:
|
||||||
|
- Overall - the overall quality of the markdown as compared to the image.
|
||||||
|
- Text quality - the quality of the text extraction from the image.
|
||||||
|
- Formatting quality - the quality of the formatting applied to the markdown, as compared to the image.
|
||||||
|
|
||||||
|
Depending on which elements are present in the markdown, you will assign element-specific scores.
|
||||||
|
- Tables - how effectively the tables have been extracted and formatted.
|
||||||
|
- Forms - how effectively the forms have extracted and formatted.
|
||||||
|
- Equations - how effectively block equations have been converted to LaTeX.
|
||||||
|
- Section headers - if all of the section headers have been detected, and the right levels set.
|
||||||
|
- Lists - if the lists have been properly extracted and formatted.
|
||||||
|
- Images - if images are identified and placed correctly.
|
||||||
|
|
||||||
|
Notes on scoring:
|
||||||
|
- To get a 5/5, all of the important text from the image must appear in the markdown, and the formatting should be correct (minor mistakes okay). It's okay to omit some text that isn't important to the meaning, like page numbers and chapter headings. If the entire page is an image, it's okay if the markdown is just a link to the image, unless the image would be better represented as text.
|
||||||
|
- A 3/5 may have small missing text elements from the markdown and/or moderate formatting issues.
|
||||||
|
- A 1/5 will have major missing text segments from the markdown or completely unreadable formatting.
|
||||||
|
- Use 0/5 if a field isn't applicable, like if the image doesn't contain a table.
|
||||||
|
|
||||||
|
If text that is important to the meaning of the document is missing, do not score higher than 3/5.
|
||||||
|
|
||||||
|
Output json, like in the example below.
|
||||||
|
|
||||||
|
**Example**
|
||||||
|
Input
|
||||||
|
```markdown
|
||||||
|
# Section 1
|
||||||
|
This is some *markdown* extracted from a document. Here is a block equation:
|
||||||
|
$$\frac{ab \cdot x^5 + x^2 + 2 \cdot x + 123}{t}$$
|
||||||
|
```
|
||||||
|
Output
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"image_description": "In the image, there is a section header 'Section 1', followed by some text and a block equation.",
|
||||||
|
"markdown_description": "In the markdown, there is a section header 'Section 1', followed by some text and a block equation.",
|
||||||
|
"comparison": "The text and formatting matches the image. There are no formatting or text extraction issues. The equations and section headers are correct.",
|
||||||
|
"overall": 5,
|
||||||
|
"text": 5,
|
||||||
|
"formatting": 5,
|
||||||
|
"section_headers": 5,
|
||||||
|
"tables": 0,
|
||||||
|
"forms": 0,
|
||||||
|
"equations": 5,
|
||||||
|
"lists": 0,
|
||||||
|
"images": 0
|
||||||
|
}
|
||||||
|
```
|
||||||
|
**Input**
|
||||||
|
```markdown
|
||||||
|
{{markdown}}
|
||||||
|
```
|
||||||
|
**Output**
|
||||||
|
"""
|
||||||
|
|
||||||
|
comparison_keys = ["comparison"]
|
||||||
|
description_keys = ["image_description", "markdown_description"]
|
||||||
|
text_keys = comparison_keys + description_keys
|
||||||
|
score_keys = ["overall", "text", "formatting", "section_headers", "tables", "forms", "equations",
|
||||||
|
"lists", "images"]
|
||||||
|
|
||||||
|
|
||||||
|
class LLMScorer(BaseScorer):
|
||||||
|
def __call__(self, sample, gt_markdown: List[str], markdown: str) -> BlockScores:
|
||||||
|
pdf_bytes = sample["pdf"]
|
||||||
|
with tempfile.NamedTemporaryFile(suffix=".pdf") as f:
|
||||||
|
f.write(pdf_bytes)
|
||||||
|
f.flush()
|
||||||
|
f.seek(0)
|
||||||
|
doc = pdfium.PdfDocument(f.name)
|
||||||
|
img = doc[0].render(scale=96/72).to_pil()
|
||||||
|
doc.close()
|
||||||
|
|
||||||
|
return self.llm_rater(img, markdown)
|
||||||
|
|
||||||
|
|
||||||
|
def llm_rater(self, img: Image.Image, markdown: str) -> BlockScores:
|
||||||
|
if not markdown:
|
||||||
|
null_scores = {k: 1 for k in score_keys}
|
||||||
|
text_scores = {k: "" for k in text_keys}
|
||||||
|
null_scores.update(text_scores)
|
||||||
|
return {
|
||||||
|
"score": 1,
|
||||||
|
"specific_scores": null_scores
|
||||||
|
}
|
||||||
|
req_keys = text_keys + score_keys
|
||||||
|
properties = {}
|
||||||
|
for key in req_keys:
|
||||||
|
content_type = "INTEGER" if key in score_keys else "STRING"
|
||||||
|
properties[key] = {"type": content_type}
|
||||||
|
|
||||||
|
response_schema = {
|
||||||
|
"required": req_keys,
|
||||||
|
"properties": properties,
|
||||||
|
"type": "OBJECT"
|
||||||
|
}
|
||||||
|
prompt = rating_prompt.replace("{{markdown}}", markdown)
|
||||||
|
response = self.llm_response_wrapper([img, prompt], response_schema)
|
||||||
|
assert all([k in response for k in req_keys]), f"Missing keys in response: {response}"
|
||||||
|
return {
|
||||||
|
"score": response["overall"],
|
||||||
|
"specific_scores": response,
|
||||||
|
}
|
||||||
|
|
||||||
|
def llm_response_wrapper(self, prompt, response_schema, depth=0):
|
||||||
|
client = genai.Client(
|
||||||
|
http_options={"timeout": 60000},
|
||||||
|
vertexai=True,
|
||||||
|
project=os.getenv("VERTEX_PROJECT_ID"),
|
||||||
|
location=os.getenv("VERTEX_LOCATION"),
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
responses = client.models.generate_content(
|
||||||
|
model="gemini-2.0-flash-001",
|
||||||
|
contents=prompt,
|
||||||
|
config={
|
||||||
|
"temperature": 0,
|
||||||
|
"response_schema": response_schema,
|
||||||
|
"response_mime_type": "application/json",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
output = responses.candidates[0].content.parts[0].text
|
||||||
|
return json.loads(output)
|
||||||
|
except APIError as e:
|
||||||
|
print(f"Hit Gemini rate limit, waiting 120 seconds")
|
||||||
|
time.sleep(120)
|
||||||
|
if depth > 2:
|
||||||
|
raise e
|
||||||
|
return self.llm_response_wrapper(prompt, response_schema, depth + 1)
|
@ -0,0 +1,6 @@
|
|||||||
|
from typing import TypedDict, List, Optional, Dict
|
||||||
|
|
||||||
|
|
||||||
|
class BlockScores(TypedDict):
|
||||||
|
score: float
|
||||||
|
specific_scores: Dict[str, float | List[float]]
|
@ -0,0 +1,48 @@
|
|||||||
|
import json
|
||||||
|
from PIL import Image
|
||||||
|
from google import genai
|
||||||
|
from google.genai import types
|
||||||
|
from io import BytesIO
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
from marker.settings import settings
|
||||||
|
|
||||||
|
prompt = """
|
||||||
|
You're an expert document analyst who is good at turning tables in documents into HTML. Analyze the provided image, and convert it to a faithful HTML representation.
|
||||||
|
|
||||||
|
Guidelines:
|
||||||
|
- Keep the HTML simple and concise.
|
||||||
|
- Only include the <table> tag and contents.
|
||||||
|
- Only use <table>, <tr>, and <td> tags. Only use the colspan and rowspan attributes if necessary. Do not use <tbody>, <thead>, or <th> tags.
|
||||||
|
- Make sure the table is as faithful to the image as possible with the given tags.
|
||||||
|
|
||||||
|
**Instructions**
|
||||||
|
1. Analyze the image, and determine the table structure.
|
||||||
|
2. Convert the table image to HTML, following the guidelines above.
|
||||||
|
3. Output only the HTML for the table, starting with the <table> tag and ending with the </table> tag.
|
||||||
|
""".strip()
|
||||||
|
|
||||||
|
class TableSchema(BaseModel):
|
||||||
|
table_html: str
|
||||||
|
|
||||||
|
def gemini_table_rec(image: Image.Image):
|
||||||
|
client = genai.Client(
|
||||||
|
api_key=settings.GOOGLE_API_KEY,
|
||||||
|
http_options={"timeout": 60000}
|
||||||
|
)
|
||||||
|
|
||||||
|
image_bytes = BytesIO()
|
||||||
|
image.save(image_bytes, format="PNG")
|
||||||
|
|
||||||
|
responses = client.models.generate_content(
|
||||||
|
model="gemini-2.0-flash",
|
||||||
|
contents=[types.Part.from_bytes(data=image_bytes.getvalue(), mime_type="image/png"), prompt], # According to gemini docs, it performs better if the image is the first element
|
||||||
|
config={
|
||||||
|
"temperature": 0,
|
||||||
|
"response_schema": TableSchema,
|
||||||
|
"response_mime_type": "application/json",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
output = responses.candidates[0].content.parts[0].text
|
||||||
|
return json.loads(output)["table_html"]
|
@ -0,0 +1,182 @@
|
|||||||
|
from typing import List
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
from bs4 import BeautifulSoup
|
||||||
|
import pypdfium2 as pdfium
|
||||||
|
from tqdm import tqdm
|
||||||
|
import base64
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
from benchmarks.table.gemini import gemini_table_rec
|
||||||
|
from marker.config.parser import ConfigParser
|
||||||
|
from marker.converters.table import TableConverter
|
||||||
|
from marker.models import create_model_dict
|
||||||
|
from marker.processors.llm.llm_table import LLMTableProcessor
|
||||||
|
from marker.processors.table import TableProcessor
|
||||||
|
from marker.renderers.json import JSONBlockOutput
|
||||||
|
from marker.schema.polygon import PolygonBox
|
||||||
|
from marker.util import matrix_intersection_area
|
||||||
|
|
||||||
|
|
||||||
|
def extract_tables(children: List[JSONBlockOutput]):
|
||||||
|
tables = []
|
||||||
|
for child in children:
|
||||||
|
if child.block_type == 'Table':
|
||||||
|
tables.append(child)
|
||||||
|
elif child.children:
|
||||||
|
tables.extend(extract_tables(child.children))
|
||||||
|
return tables
|
||||||
|
|
||||||
|
def fix_table_html(table_html: str) -> str:
|
||||||
|
marker_table_soup = BeautifulSoup(table_html, 'html.parser')
|
||||||
|
tbody = marker_table_soup.find('tbody')
|
||||||
|
if tbody:
|
||||||
|
tbody.unwrap()
|
||||||
|
for th_tag in marker_table_soup.find_all('th'):
|
||||||
|
th_tag.name = 'td'
|
||||||
|
for br_tag in marker_table_soup.find_all('br'):
|
||||||
|
br_tag.replace_with(marker_table_soup.new_string(''))
|
||||||
|
|
||||||
|
marker_table_html = str(marker_table_soup)
|
||||||
|
marker_table_html = marker_table_html.replace("\n", " ") # Fintabnet uses spaces instead of newlines
|
||||||
|
return marker_table_html
|
||||||
|
|
||||||
|
|
||||||
|
def inference_tables(dataset, use_llm: bool, table_rec_batch_size: int | None, max_rows: int, use_gemini: bool):
|
||||||
|
models = create_model_dict()
|
||||||
|
config_parser = ConfigParser({'output_format': 'json', "use_llm": use_llm, "table_rec_batch_size": table_rec_batch_size, "disable_tqdm": True})
|
||||||
|
total_unaligned = 0
|
||||||
|
results = []
|
||||||
|
|
||||||
|
iterations = len(dataset)
|
||||||
|
if max_rows is not None:
|
||||||
|
iterations = min(max_rows, len(dataset))
|
||||||
|
|
||||||
|
for i in tqdm(range(iterations), desc='Converting Tables'):
|
||||||
|
try:
|
||||||
|
row = dataset[i]
|
||||||
|
pdf_binary = base64.b64decode(row['pdf'])
|
||||||
|
gt_tables = row['tables'] # Already sorted by reading order, which is what marker returns
|
||||||
|
|
||||||
|
# Only use the basic table processors
|
||||||
|
converter = TableConverter(
|
||||||
|
config=config_parser.generate_config_dict(),
|
||||||
|
artifact_dict=models,
|
||||||
|
processor_list=[
|
||||||
|
"marker.processors.table.TableProcessor",
|
||||||
|
"marker.processors.llm.llm_table.LLMTableProcessor",
|
||||||
|
],
|
||||||
|
renderer=config_parser.get_renderer()
|
||||||
|
)
|
||||||
|
|
||||||
|
with tempfile.NamedTemporaryFile(suffix=".pdf", mode="wb") as temp_pdf_file:
|
||||||
|
temp_pdf_file.write(pdf_binary)
|
||||||
|
temp_pdf_file.seek(0)
|
||||||
|
marker_json = converter(temp_pdf_file.name).children
|
||||||
|
|
||||||
|
doc = pdfium.PdfDocument(temp_pdf_file.name)
|
||||||
|
page_image = doc[0].render(scale=96/72).to_pil()
|
||||||
|
doc.close()
|
||||||
|
|
||||||
|
if len(marker_json) == 0 or len(gt_tables) == 0:
|
||||||
|
print(f'No tables detected, skipping...')
|
||||||
|
total_unaligned += len(gt_tables)
|
||||||
|
continue
|
||||||
|
|
||||||
|
marker_tables = extract_tables(marker_json)
|
||||||
|
marker_table_boxes = [table.bbox for table in marker_tables]
|
||||||
|
page_bbox = marker_json[0].bbox
|
||||||
|
|
||||||
|
if len(marker_tables) != len(gt_tables):
|
||||||
|
print(f'Number of tables do not match, skipping...')
|
||||||
|
total_unaligned += len(gt_tables)
|
||||||
|
continue
|
||||||
|
|
||||||
|
table_images = [
|
||||||
|
page_image.crop(
|
||||||
|
PolygonBox.from_bbox(bbox)
|
||||||
|
.rescale(
|
||||||
|
(page_bbox[2], page_bbox[3]), (page_image.width, page_image.height)
|
||||||
|
).bbox
|
||||||
|
)
|
||||||
|
for bbox
|
||||||
|
in marker_table_boxes
|
||||||
|
]
|
||||||
|
|
||||||
|
# Normalize the bboxes
|
||||||
|
for bbox in marker_table_boxes:
|
||||||
|
bbox[0] = bbox[0] / page_bbox[2]
|
||||||
|
bbox[1] = bbox[1] / page_bbox[3]
|
||||||
|
bbox[2] = bbox[2] / page_bbox[2]
|
||||||
|
bbox[3] = bbox[3] / page_bbox[3]
|
||||||
|
|
||||||
|
gt_boxes = [table['normalized_bbox'] for table in gt_tables]
|
||||||
|
gt_areas = [(bbox[2] - bbox[0]) * (bbox[3] - bbox[1]) for bbox in gt_boxes]
|
||||||
|
marker_areas = [(bbox[2] - bbox[0]) * (bbox[3] - bbox[1]) for bbox in marker_table_boxes]
|
||||||
|
table_alignments = matrix_intersection_area(gt_boxes, marker_table_boxes)
|
||||||
|
|
||||||
|
aligned_tables = []
|
||||||
|
used_tables = set()
|
||||||
|
unaligned_tables = set()
|
||||||
|
for table_idx, alignment in enumerate(table_alignments):
|
||||||
|
try:
|
||||||
|
max_area = np.max(alignment)
|
||||||
|
aligned_idx = np.argmax(alignment)
|
||||||
|
except ValueError:
|
||||||
|
# No alignment found
|
||||||
|
unaligned_tables.add(table_idx)
|
||||||
|
continue
|
||||||
|
|
||||||
|
if max_area <= .01:
|
||||||
|
# No alignment found
|
||||||
|
unaligned_tables.add(table_idx)
|
||||||
|
continue
|
||||||
|
|
||||||
|
if aligned_idx in used_tables:
|
||||||
|
# Marker table already aligned with another gt table
|
||||||
|
unaligned_tables.add(table_idx)
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Gt table doesn't align well with any marker table
|
||||||
|
gt_table_pct = gt_areas[table_idx] / max_area
|
||||||
|
if not .85 < gt_table_pct < 1.15:
|
||||||
|
unaligned_tables.add(table_idx)
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Marker table doesn't align with gt table
|
||||||
|
marker_table_pct = marker_areas[aligned_idx] / max_area
|
||||||
|
if not .85 < marker_table_pct < 1.15:
|
||||||
|
unaligned_tables.add(table_idx)
|
||||||
|
continue
|
||||||
|
|
||||||
|
gemini_html = ""
|
||||||
|
if use_gemini:
|
||||||
|
try:
|
||||||
|
gemini_html = gemini_table_rec(table_images[aligned_idx])
|
||||||
|
except Exception as e:
|
||||||
|
print(f'Gemini failed: {e}')
|
||||||
|
|
||||||
|
aligned_tables.append(
|
||||||
|
(marker_tables[aligned_idx], gt_tables[table_idx], gemini_html)
|
||||||
|
)
|
||||||
|
used_tables.add(aligned_idx)
|
||||||
|
|
||||||
|
total_unaligned += len(unaligned_tables)
|
||||||
|
|
||||||
|
for marker_table, gt_table, gemini_table in aligned_tables:
|
||||||
|
gt_table_html = gt_table['html']
|
||||||
|
|
||||||
|
# marker wraps the table in <tbody> which fintabnet data doesn't
|
||||||
|
# Fintabnet doesn't use th tags, need to be replaced for fair comparison
|
||||||
|
marker_table_html = fix_table_html(marker_table.html)
|
||||||
|
gemini_table_html = fix_table_html(gemini_table)
|
||||||
|
|
||||||
|
results.append({
|
||||||
|
"marker_table": marker_table_html,
|
||||||
|
"gt_table": gt_table_html,
|
||||||
|
"gemini_table": gemini_table_html
|
||||||
|
})
|
||||||
|
except pdfium.PdfiumError:
|
||||||
|
print('Broken PDF, Skipping...')
|
||||||
|
continue
|
||||||
|
return results, total_unaligned
|
@ -0,0 +1,109 @@
|
|||||||
|
""""
|
||||||
|
TEDS Code Adapted from https://github.com/ibm-aur-nlp/EDD
|
||||||
|
"""
|
||||||
|
|
||||||
|
import distance
|
||||||
|
from apted import APTED, Config
|
||||||
|
from apted.helpers import Tree
|
||||||
|
from lxml import html
|
||||||
|
from collections import deque
|
||||||
|
|
||||||
|
def wrap_table_html(table_html:str)->str:
|
||||||
|
return f'<html><body>{table_html}</body></html>'
|
||||||
|
|
||||||
|
class TableTree(Tree):
|
||||||
|
def __init__(self, tag, colspan=None, rowspan=None, content=None, *children):
|
||||||
|
self.tag = tag
|
||||||
|
self.colspan = colspan
|
||||||
|
self.rowspan = rowspan
|
||||||
|
self.content = content
|
||||||
|
|
||||||
|
# Sets self.name and self.children
|
||||||
|
super().__init__(tag, *children)
|
||||||
|
|
||||||
|
def bracket(self):
|
||||||
|
"""Show tree using brackets notation"""
|
||||||
|
if self.tag == 'td':
|
||||||
|
result = '"tag": %s, "colspan": %d, "rowspan": %d, "text": %s' % \
|
||||||
|
(self.tag, self.colspan, self.rowspan, self.content)
|
||||||
|
else:
|
||||||
|
result = '"tag": %s' % self.tag
|
||||||
|
for child in self.children:
|
||||||
|
result += child.bracket()
|
||||||
|
return "{{{}}}".format(result)
|
||||||
|
|
||||||
|
class CustomConfig(Config):
|
||||||
|
@staticmethod
|
||||||
|
def maximum(*sequences):
|
||||||
|
return max(map(len, sequences))
|
||||||
|
|
||||||
|
def normalized_distance(self, *sequences):
|
||||||
|
return float(distance.levenshtein(*sequences)) / self.maximum(*sequences)
|
||||||
|
|
||||||
|
def rename(self, node1, node2):
|
||||||
|
if (node1.tag != node2.tag) or (node1.colspan != node2.colspan) or (node1.rowspan != node2.rowspan):
|
||||||
|
return 1.
|
||||||
|
if node1.tag == 'td':
|
||||||
|
if node1.content or node2.content:
|
||||||
|
return self.normalized_distance(node1.content, node2.content)
|
||||||
|
return 0.
|
||||||
|
|
||||||
|
def tokenize(node):
|
||||||
|
"""
|
||||||
|
Tokenizes table cells
|
||||||
|
"""
|
||||||
|
global __tokens__
|
||||||
|
__tokens__.append('<%s>' % node.tag)
|
||||||
|
if node.text is not None:
|
||||||
|
__tokens__ += list(node.text)
|
||||||
|
for n in node.getchildren():
|
||||||
|
tokenize(n)
|
||||||
|
if node.tag != 'unk':
|
||||||
|
__tokens__.append('</%s>' % node.tag)
|
||||||
|
if node.tag != 'td' and node.tail is not None:
|
||||||
|
__tokens__ += list(node.tail)
|
||||||
|
|
||||||
|
def tree_convert_html(node, convert_cell=False, parent=None):
|
||||||
|
"""
|
||||||
|
Converts HTML tree to the format required by apted
|
||||||
|
"""
|
||||||
|
global __tokens__
|
||||||
|
if node.tag == 'td':
|
||||||
|
if convert_cell:
|
||||||
|
__tokens__ = []
|
||||||
|
tokenize(node)
|
||||||
|
cell = __tokens__[1:-1].copy()
|
||||||
|
else:
|
||||||
|
cell = []
|
||||||
|
new_node = TableTree(node.tag,
|
||||||
|
int(node.attrib.get('colspan', '1')),
|
||||||
|
int(node.attrib.get('rowspan', '1')),
|
||||||
|
cell, *deque())
|
||||||
|
else:
|
||||||
|
new_node = TableTree(node.tag, None, None, None, *deque())
|
||||||
|
if parent is not None:
|
||||||
|
parent.children.append(new_node)
|
||||||
|
if node.tag != 'td':
|
||||||
|
for n in node.getchildren():
|
||||||
|
tree_convert_html(n, convert_cell, new_node)
|
||||||
|
if parent is None:
|
||||||
|
return new_node
|
||||||
|
|
||||||
|
def similarity_eval_html(pred, true, structure_only=False):
|
||||||
|
"""
|
||||||
|
Computes TEDS score between the prediction and the ground truth of a given samples
|
||||||
|
"""
|
||||||
|
pred, true = html.fromstring(pred), html.fromstring(true)
|
||||||
|
if pred.xpath('body/table') and true.xpath('body/table'):
|
||||||
|
pred = pred.xpath('body/table')[0]
|
||||||
|
true = true.xpath('body/table')[0]
|
||||||
|
n_nodes_pred = len(pred.xpath(".//*"))
|
||||||
|
n_nodes_true = len(true.xpath(".//*"))
|
||||||
|
tree_pred = tree_convert_html(pred, convert_cell=not structure_only)
|
||||||
|
tree_true = tree_convert_html(true, convert_cell=not structure_only)
|
||||||
|
n_nodes = max(n_nodes_pred, n_nodes_true)
|
||||||
|
distance = APTED(tree_pred, tree_true, CustomConfig()).compute_edit_distance()
|
||||||
|
return 1.0 - (float(distance) / n_nodes)
|
||||||
|
else:
|
||||||
|
return 0.0
|
||||||
|
|
@ -0,0 +1,97 @@
|
|||||||
|
import os
|
||||||
|
os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" # Transformers uses .isin for an op, which is not supported on MPS
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
from itertools import repeat
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
import time
|
||||||
|
import datasets
|
||||||
|
from tqdm import tqdm
|
||||||
|
import click
|
||||||
|
from tabulate import tabulate
|
||||||
|
import json
|
||||||
|
from concurrent.futures import ProcessPoolExecutor
|
||||||
|
|
||||||
|
from marker.settings import settings
|
||||||
|
from benchmarks.table.inference import inference_tables
|
||||||
|
|
||||||
|
from scoring import wrap_table_html, similarity_eval_html
|
||||||
|
|
||||||
|
def update_teds_score(result, prefix: str = "marker"):
|
||||||
|
prediction, ground_truth = result[f'{prefix}_table'], result['gt_table']
|
||||||
|
prediction, ground_truth = wrap_table_html(prediction), wrap_table_html(ground_truth)
|
||||||
|
score = similarity_eval_html(prediction, ground_truth)
|
||||||
|
result.update({f'{prefix}_score':score})
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@click.command(help="Benchmark Table to HTML Conversion")
|
||||||
|
@click.option("--result_path", type=str, default=os.path.join(settings.OUTPUT_DIR, "benchmark", "table"), help="Output path for results.")
|
||||||
|
@click.option("--dataset", type=str, default="datalab-to/fintabnet_bench_marker", help="Dataset to use")
|
||||||
|
@click.option("--max_rows", type=int, default=None, help="Maximum number of PDFs to process")
|
||||||
|
@click.option("--max_workers", type=int, default=16, help="Maximum number of workers to use")
|
||||||
|
@click.option("--use_llm", is_flag=True, help="Use LLM for improving table recognition.")
|
||||||
|
@click.option("--table_rec_batch_size", type=int, default=None, help="Batch size for table recognition.")
|
||||||
|
@click.option("--use_gemini", is_flag=True, help="Evaluate Gemini for table recognition.")
|
||||||
|
def main(
|
||||||
|
result_path: str,
|
||||||
|
dataset: str,
|
||||||
|
max_rows: int,
|
||||||
|
max_workers: int,
|
||||||
|
use_llm: bool,
|
||||||
|
table_rec_batch_size: int | None,
|
||||||
|
use_gemini: bool = False
|
||||||
|
):
|
||||||
|
start = time.time()
|
||||||
|
|
||||||
|
|
||||||
|
dataset = datasets.load_dataset(dataset, split='train')
|
||||||
|
dataset = dataset.shuffle(seed=0)
|
||||||
|
|
||||||
|
results, total_unaligned = inference_tables(dataset, use_llm, table_rec_batch_size, max_rows, use_gemini)
|
||||||
|
|
||||||
|
print(f"Total time: {time.time() - start}.")
|
||||||
|
print(f"Could not align {total_unaligned} tables from fintabnet.")
|
||||||
|
|
||||||
|
with ProcessPoolExecutor(max_workers=max_workers) as executor:
|
||||||
|
marker_results = list(
|
||||||
|
tqdm(
|
||||||
|
executor.map(update_teds_score, results), desc='Computing alignment scores', total=len(results)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
avg_score = sum([r["marker_score"] for r in marker_results]) / len(marker_results)
|
||||||
|
headers = ["Avg score", "Total tables"]
|
||||||
|
data = [f"{avg_score:.3f}", len(marker_results)]
|
||||||
|
gemini_results = None
|
||||||
|
if use_gemini:
|
||||||
|
with ProcessPoolExecutor(max_workers=max_workers) as executor:
|
||||||
|
gemini_results = list(
|
||||||
|
tqdm(
|
||||||
|
executor.map(update_teds_score, results, repeat("gemini")), desc='Computing Gemini scores',
|
||||||
|
total=len(results)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
avg_gemini_score = sum([r["gemini_score"] for r in gemini_results]) / len(gemini_results)
|
||||||
|
headers.append("Avg Gemini score")
|
||||||
|
data.append(f"{avg_gemini_score:.3f}")
|
||||||
|
|
||||||
|
table = tabulate([data], headers=headers, tablefmt="github")
|
||||||
|
print(table)
|
||||||
|
print("Avg score computed by comparing marker predicted HTML with original HTML")
|
||||||
|
|
||||||
|
results = {
|
||||||
|
"marker": marker_results,
|
||||||
|
"gemini": gemini_results
|
||||||
|
}
|
||||||
|
|
||||||
|
out_path = Path(result_path)
|
||||||
|
out_path.mkdir(parents=True, exist_ok=True)
|
||||||
|
with open(out_path / "table.json", "w+") as f:
|
||||||
|
json.dump(results, f, indent=2)
|
||||||
|
|
||||||
|
print(f"Results saved to {out_path}.")
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
@ -0,0 +1,40 @@
|
|||||||
|
import time
|
||||||
|
import torch
|
||||||
|
|
||||||
|
import click
|
||||||
|
import pypdfium2 as pdfium
|
||||||
|
from tqdm import tqdm
|
||||||
|
|
||||||
|
from marker.converters.pdf import PdfConverter
|
||||||
|
from marker.models import create_model_dict
|
||||||
|
|
||||||
|
|
||||||
|
@click.command(help="Benchmark PDF to MD conversion throughput.")
|
||||||
|
@click.argument("pdf_path", type=str)
|
||||||
|
def main(pdf_path):
|
||||||
|
print(f"Converting {pdf_path} to markdown...")
|
||||||
|
pdf = pdfium.PdfDocument(pdf_path)
|
||||||
|
page_count = len(pdf)
|
||||||
|
pdf.close()
|
||||||
|
model_dict = create_model_dict()
|
||||||
|
torch.cuda.reset_peak_memory_stats()
|
||||||
|
|
||||||
|
times = []
|
||||||
|
for i in tqdm(range(10), desc="Benchmarking"):
|
||||||
|
block_converter = PdfConverter(
|
||||||
|
artifact_dict=model_dict,
|
||||||
|
config={"disable_tqdm": True}
|
||||||
|
)
|
||||||
|
start = time.time()
|
||||||
|
block_converter(pdf_path)
|
||||||
|
total = time.time() - start
|
||||||
|
times.append(total)
|
||||||
|
|
||||||
|
max_gpu_vram = torch.cuda.max_memory_allocated() / 1024 ** 3
|
||||||
|
|
||||||
|
print(f"Converted {page_count} pages in {sum(times)/len(times):.2f} seconds.")
|
||||||
|
print(f"Max GPU VRAM: {max_gpu_vram:.2f} GB")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
@ -0,0 +1,33 @@
|
|||||||
|
import json
|
||||||
|
import argparse
|
||||||
|
|
||||||
|
|
||||||
|
def verify_scores(file_path):
|
||||||
|
with open(file_path, 'r') as file:
|
||||||
|
data = json.load(file)
|
||||||
|
|
||||||
|
raw_scores = [data["scores"][k] for k in data["scores"]]
|
||||||
|
marker_scores = [r["marker"]["heuristic"]["score"] for r in raw_scores]
|
||||||
|
marker_score = sum(marker_scores) / len(marker_scores)
|
||||||
|
if marker_score < 90:
|
||||||
|
raise ValueError("Marker score below 90")
|
||||||
|
|
||||||
|
|
||||||
|
def verify_table_scores(file_path):
|
||||||
|
with open(file_path, 'r') as file:
|
||||||
|
data = json.load(file)
|
||||||
|
|
||||||
|
avg = sum([r["marker_score"] for r in data["marker"]]) / len(data)
|
||||||
|
if avg < 0.7:
|
||||||
|
raise ValueError("Average score is below the required threshold of 0.7")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
parser = argparse.ArgumentParser(description="Verify benchmark scores")
|
||||||
|
parser.add_argument("file_path", type=str, help="Path to the json file")
|
||||||
|
parser.add_argument("--type", type=str, help="Type of file to verify", default="marker")
|
||||||
|
args = parser.parse_args()
|
||||||
|
if args.type == "marker":
|
||||||
|
verify_scores(args.file_path)
|
||||||
|
elif args.type == "table":
|
||||||
|
verify_table_scores(args.file_path)
|
@ -0,0 +1,4 @@
|
|||||||
|
from marker.scripts.chunk_convert import chunk_convert_cli
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
chunk_convert_cli()
|
@ -0,0 +1,4 @@
|
|||||||
|
from marker.scripts.convert import convert_cli
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
convert_cli()
|
@ -0,0 +1,4 @@
|
|||||||
|
from marker.scripts.convert_single import convert_single_cli
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
convert_single_cli()
|
@ -0,0 +1,3 @@
|
|||||||
|
latex
|
||||||
|
pdfs
|
||||||
|
references
|
After Width: | Height: | Size: 78 KiB |
After Width: | Height: | Size: 20 KiB |
After Width: | Height: | Size: 60 KiB |
After Width: | Height: | Size: 50 KiB |
@ -0,0 +1,955 @@
|
|||||||
|
{
|
||||||
|
"table_of_contents": [
|
||||||
|
{
|
||||||
|
"title": "An Aggregated Multicolumn Dilated Convolution Network\nfor Perspective-Free Counting",
|
||||||
|
"heading_level": null,
|
||||||
|
"page_id": 0,
|
||||||
|
"polygon": [
|
||||||
|
[
|
||||||
|
117.5888671875,
|
||||||
|
105.9219970703125
|
||||||
|
],
|
||||||
|
[
|
||||||
|
477.371826171875,
|
||||||
|
105.9219970703125
|
||||||
|
],
|
||||||
|
[
|
||||||
|
477.371826171875,
|
||||||
|
138.201171875
|
||||||
|
],
|
||||||
|
[
|
||||||
|
117.5888671875,
|
||||||
|
138.201171875
|
||||||
|
]
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "Abstract",
|
||||||
|
"heading_level": null,
|
||||||
|
"page_id": 0,
|
||||||
|
"polygon": [
|
||||||
|
[
|
||||||
|
144.1845703125,
|
||||||
|
232.4891357421875
|
||||||
|
],
|
||||||
|
[
|
||||||
|
190.48028564453125,
|
||||||
|
232.4891357421875
|
||||||
|
],
|
||||||
|
[
|
||||||
|
190.48028564453125,
|
||||||
|
244.4443359375
|
||||||
|
],
|
||||||
|
[
|
||||||
|
144.1845703125,
|
||||||
|
244.4443359375
|
||||||
|
]
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "1. Introduction",
|
||||||
|
"heading_level": null,
|
||||||
|
"page_id": 0,
|
||||||
|
"polygon": [
|
||||||
|
[
|
||||||
|
50.016357421875,
|
||||||
|
512.06591796875
|
||||||
|
],
|
||||||
|
[
|
||||||
|
128.49609375,
|
||||||
|
512.06591796875
|
||||||
|
],
|
||||||
|
[
|
||||||
|
128.49609375,
|
||||||
|
524.0211181640625
|
||||||
|
],
|
||||||
|
[
|
||||||
|
50.016357421875,
|
||||||
|
524.0211181640625
|
||||||
|
]
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "2. Related Work",
|
||||||
|
"heading_level": null,
|
||||||
|
"page_id": 0,
|
||||||
|
"polygon": [
|
||||||
|
[
|
||||||
|
307.1953125,
|
||||||
|
621.7747497558594
|
||||||
|
],
|
||||||
|
[
|
||||||
|
392.0625,
|
||||||
|
621.7747497558594
|
||||||
|
],
|
||||||
|
[
|
||||||
|
392.0625,
|
||||||
|
633.7299499511719
|
||||||
|
],
|
||||||
|
[
|
||||||
|
307.1953125,
|
||||||
|
633.7299499511719
|
||||||
|
]
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "3. Method",
|
||||||
|
"heading_level": null,
|
||||||
|
"page_id": 2,
|
||||||
|
"polygon": [
|
||||||
|
[
|
||||||
|
49.4560546875,
|
||||||
|
371.27313232421875
|
||||||
|
],
|
||||||
|
[
|
||||||
|
101.91387939453125,
|
||||||
|
371.27313232421875
|
||||||
|
],
|
||||||
|
[
|
||||||
|
101.91387939453125,
|
||||||
|
383.22833251953125
|
||||||
|
],
|
||||||
|
[
|
||||||
|
49.4560546875,
|
||||||
|
383.22833251953125
|
||||||
|
]
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "3.1. Dilated Convolutions for Multicolumn Net-\nworks",
|
||||||
|
"heading_level": null,
|
||||||
|
"page_id": 2,
|
||||||
|
"polygon": [
|
||||||
|
[
|
||||||
|
49.53076171875,
|
||||||
|
391.4488220214844
|
||||||
|
],
|
||||||
|
[
|
||||||
|
287.173828125,
|
||||||
|
391.4488220214844
|
||||||
|
],
|
||||||
|
[
|
||||||
|
287.173828125,
|
||||||
|
414.3627014160156
|
||||||
|
],
|
||||||
|
[
|
||||||
|
49.53076171875,
|
||||||
|
414.3627014160156
|
||||||
|
]
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "3.2. Experiments",
|
||||||
|
"heading_level": null,
|
||||||
|
"page_id": 3,
|
||||||
|
"polygon": [
|
||||||
|
[
|
||||||
|
49.119873046875,
|
||||||
|
263.935546875
|
||||||
|
],
|
||||||
|
[
|
||||||
|
128.95028686523438,
|
||||||
|
263.935546875
|
||||||
|
],
|
||||||
|
[
|
||||||
|
128.95028686523438,
|
||||||
|
274.936767578125
|
||||||
|
],
|
||||||
|
[
|
||||||
|
49.119873046875,
|
||||||
|
274.936767578125
|
||||||
|
]
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "3.2.1 UCF50 Crowd Counting",
|
||||||
|
"heading_level": null,
|
||||||
|
"page_id": 3,
|
||||||
|
"polygon": [
|
||||||
|
[
|
||||||
|
307.79296875,
|
||||||
|
339.732421875
|
||||||
|
],
|
||||||
|
[
|
||||||
|
443.4609375,
|
||||||
|
339.732421875
|
||||||
|
],
|
||||||
|
[
|
||||||
|
443.4609375,
|
||||||
|
350.13201904296875
|
||||||
|
],
|
||||||
|
[
|
||||||
|
307.79296875,
|
||||||
|
350.13201904296875
|
||||||
|
]
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "3.2.2 TRANCOS Traffic Counting",
|
||||||
|
"heading_level": null,
|
||||||
|
"page_id": 3,
|
||||||
|
"polygon": [
|
||||||
|
[
|
||||||
|
308.689453125,
|
||||||
|
624.1640625
|
||||||
|
],
|
||||||
|
[
|
||||||
|
461.689453125,
|
||||||
|
624.1640625
|
||||||
|
],
|
||||||
|
[
|
||||||
|
461.689453125,
|
||||||
|
634.7828826904297
|
||||||
|
],
|
||||||
|
[
|
||||||
|
308.689453125,
|
||||||
|
634.7828826904297
|
||||||
|
]
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "3.2.3 UCSD Crowd Counting",
|
||||||
|
"heading_level": null,
|
||||||
|
"page_id": 4,
|
||||||
|
"polygon": [
|
||||||
|
[
|
||||||
|
49.38134765625,
|
||||||
|
314.06341552734375
|
||||||
|
],
|
||||||
|
[
|
||||||
|
182.28515625,
|
||||||
|
314.06341552734375
|
||||||
|
],
|
||||||
|
[
|
||||||
|
182.28515625,
|
||||||
|
324.0260009765625
|
||||||
|
],
|
||||||
|
[
|
||||||
|
49.38134765625,
|
||||||
|
324.0260009765625
|
||||||
|
]
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "3.2.4 WorldExpo '10 Crowd Counting",
|
||||||
|
"heading_level": null,
|
||||||
|
"page_id": 4,
|
||||||
|
"polygon": [
|
||||||
|
[
|
||||||
|
308.86199951171875,
|
||||||
|
259.17828369140625
|
||||||
|
],
|
||||||
|
[
|
||||||
|
477.4889221191406,
|
||||||
|
259.17828369140625
|
||||||
|
],
|
||||||
|
[
|
||||||
|
477.4889221191406,
|
||||||
|
269.140869140625
|
||||||
|
],
|
||||||
|
[
|
||||||
|
308.86199951171875,
|
||||||
|
269.140869140625
|
||||||
|
]
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "4. Results",
|
||||||
|
"heading_level": null,
|
||||||
|
"page_id": 5,
|
||||||
|
"polygon": [
|
||||||
|
[
|
||||||
|
49.343994140625,
|
||||||
|
231.4151611328125
|
||||||
|
],
|
||||||
|
[
|
||||||
|
100.5556640625,
|
||||||
|
231.4151611328125
|
||||||
|
],
|
||||||
|
[
|
||||||
|
100.5556640625,
|
||||||
|
243.370361328125
|
||||||
|
],
|
||||||
|
[
|
||||||
|
49.343994140625,
|
||||||
|
243.370361328125
|
||||||
|
]
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "4.1. UCF Crowd Counting",
|
||||||
|
"heading_level": null,
|
||||||
|
"page_id": 5,
|
||||||
|
"polygon": [
|
||||||
|
[
|
||||||
|
49.418701171875,
|
||||||
|
251.10882568359375
|
||||||
|
],
|
||||||
|
[
|
||||||
|
173.4697265625,
|
||||||
|
251.10882568359375
|
||||||
|
],
|
||||||
|
[
|
||||||
|
173.4697265625,
|
||||||
|
262.0677490234375
|
||||||
|
],
|
||||||
|
[
|
||||||
|
49.418701171875,
|
||||||
|
262.0677490234375
|
||||||
|
]
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "4.2. TRANCOS Traffic Counting",
|
||||||
|
"heading_level": null,
|
||||||
|
"page_id": 5,
|
||||||
|
"polygon": [
|
||||||
|
[
|
||||||
|
49.68017578125,
|
||||||
|
455.92767333984375
|
||||||
|
],
|
||||||
|
[
|
||||||
|
203.80078125,
|
||||||
|
455.92767333984375
|
||||||
|
],
|
||||||
|
[
|
||||||
|
203.80078125,
|
||||||
|
466.8865661621094
|
||||||
|
],
|
||||||
|
[
|
||||||
|
49.68017578125,
|
||||||
|
466.8865661621094
|
||||||
|
]
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "4.3. UCSD Crowd Counting",
|
||||||
|
"heading_level": null,
|
||||||
|
"page_id": 5,
|
||||||
|
"polygon": [
|
||||||
|
[
|
||||||
|
49.941650390625,
|
||||||
|
553.1486358642578
|
||||||
|
],
|
||||||
|
[
|
||||||
|
181.08984375,
|
||||||
|
553.1486358642578
|
||||||
|
],
|
||||||
|
[
|
||||||
|
181.08984375,
|
||||||
|
564.1075286865234
|
||||||
|
],
|
||||||
|
[
|
||||||
|
49.941650390625,
|
||||||
|
564.1075286865234
|
||||||
|
]
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "4.4. WorldExpo '10 Crowd Counting",
|
||||||
|
"heading_level": null,
|
||||||
|
"page_id": 5,
|
||||||
|
"polygon": [
|
||||||
|
[
|
||||||
|
308.689453125,
|
||||||
|
318.3517761230469
|
||||||
|
],
|
||||||
|
[
|
||||||
|
480.814453125,
|
||||||
|
318.3517761230469
|
||||||
|
],
|
||||||
|
[
|
||||||
|
480.814453125,
|
||||||
|
329.3106689453125
|
||||||
|
],
|
||||||
|
[
|
||||||
|
308.689453125,
|
||||||
|
329.3106689453125
|
||||||
|
]
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "4.5. Ablation Studies",
|
||||||
|
"heading_level": null,
|
||||||
|
"page_id": 5,
|
||||||
|
"polygon": [
|
||||||
|
[
|
||||||
|
308.689453125,
|
||||||
|
475.50469970703125
|
||||||
|
],
|
||||||
|
[
|
||||||
|
405.6838684082031,
|
||||||
|
475.50469970703125
|
||||||
|
],
|
||||||
|
[
|
||||||
|
405.6838684082031,
|
||||||
|
486.4635925292969
|
||||||
|
],
|
||||||
|
[
|
||||||
|
308.689453125,
|
||||||
|
486.4635925292969
|
||||||
|
]
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "5. Conclusion",
|
||||||
|
"heading_level": null,
|
||||||
|
"page_id": 6,
|
||||||
|
"polygon": [
|
||||||
|
[
|
||||||
|
48.48486328125,
|
||||||
|
594.6561584472656
|
||||||
|
],
|
||||||
|
[
|
||||||
|
119.20110321044922,
|
||||||
|
594.6561584472656
|
||||||
|
],
|
||||||
|
[
|
||||||
|
119.20110321044922,
|
||||||
|
607.1484375
|
||||||
|
],
|
||||||
|
[
|
||||||
|
48.48486328125,
|
||||||
|
607.1484375
|
||||||
|
]
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "5.1. Summary",
|
||||||
|
"heading_level": null,
|
||||||
|
"page_id": 6,
|
||||||
|
"polygon": [
|
||||||
|
[
|
||||||
|
49.194580078125,
|
||||||
|
619.6148376464844
|
||||||
|
],
|
||||||
|
[
|
||||||
|
115.55853271484375,
|
||||||
|
619.6148376464844
|
||||||
|
],
|
||||||
|
[
|
||||||
|
115.55853271484375,
|
||||||
|
630.73828125
|
||||||
|
],
|
||||||
|
[
|
||||||
|
49.194580078125,
|
||||||
|
630.73828125
|
||||||
|
]
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "5.2. Future Work",
|
||||||
|
"heading_level": null,
|
||||||
|
"page_id": 7,
|
||||||
|
"polygon": [
|
||||||
|
[
|
||||||
|
49.269287109375,
|
||||||
|
611.3048095703125
|
||||||
|
],
|
||||||
|
[
|
||||||
|
130.67086791992188,
|
||||||
|
611.3048095703125
|
||||||
|
],
|
||||||
|
[
|
||||||
|
130.67086791992188,
|
||||||
|
622.2637023925781
|
||||||
|
],
|
||||||
|
[
|
||||||
|
49.269287109375,
|
||||||
|
622.2637023925781
|
||||||
|
]
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "Acknowledgment",
|
||||||
|
"heading_level": null,
|
||||||
|
"page_id": 7,
|
||||||
|
"polygon": [
|
||||||
|
[
|
||||||
|
308.86199951171875,
|
||||||
|
446.23602294921875
|
||||||
|
],
|
||||||
|
[
|
||||||
|
398.337890625,
|
||||||
|
446.23602294921875
|
||||||
|
],
|
||||||
|
[
|
||||||
|
398.337890625,
|
||||||
|
458.19122314453125
|
||||||
|
],
|
||||||
|
[
|
||||||
|
308.86199951171875,
|
||||||
|
458.19122314453125
|
||||||
|
]
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "References",
|
||||||
|
"heading_level": null,
|
||||||
|
"page_id": 7,
|
||||||
|
"polygon": [
|
||||||
|
[
|
||||||
|
308.86199951171875,
|
||||||
|
571.0409851074219
|
||||||
|
],
|
||||||
|
[
|
||||||
|
365.16796875,
|
||||||
|
571.0409851074219
|
||||||
|
],
|
||||||
|
[
|
||||||
|
365.16796875,
|
||||||
|
582.9961853027344
|
||||||
|
],
|
||||||
|
[
|
||||||
|
308.86199951171875,
|
||||||
|
582.9961853027344
|
||||||
|
]
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"page_stats": [
|
||||||
|
{
|
||||||
|
"page_id": 0,
|
||||||
|
"text_extraction_method": "pdftext",
|
||||||
|
"block_counts": [
|
||||||
|
[
|
||||||
|
"Span",
|
||||||
|
176
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Line",
|
||||||
|
84
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Text",
|
||||||
|
10
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"SectionHeader",
|
||||||
|
4
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"PageHeader",
|
||||||
|
1
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"PageFooter",
|
||||||
|
1
|
||||||
|
]
|
||||||
|
],
|
||||||
|
"block_metadata": {
|
||||||
|
"llm_request_count": 0,
|
||||||
|
"llm_error_count": 0,
|
||||||
|
"llm_tokens_used": 0
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"page_id": 1,
|
||||||
|
"text_extraction_method": "pdftext",
|
||||||
|
"block_counts": [
|
||||||
|
[
|
||||||
|
"Span",
|
||||||
|
201
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Line",
|
||||||
|
74
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Text",
|
||||||
|
5
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Figure",
|
||||||
|
1
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Caption",
|
||||||
|
1
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"FigureGroup",
|
||||||
|
1
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Reference",
|
||||||
|
1
|
||||||
|
]
|
||||||
|
],
|
||||||
|
"block_metadata": {
|
||||||
|
"llm_request_count": 0,
|
||||||
|
"llm_error_count": 0,
|
||||||
|
"llm_tokens_used": 0
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"page_id": 2,
|
||||||
|
"text_extraction_method": "pdftext",
|
||||||
|
"block_counts": [
|
||||||
|
[
|
||||||
|
"Span",
|
||||||
|
327
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Line",
|
||||||
|
96
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Text",
|
||||||
|
10
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Reference",
|
||||||
|
3
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"SectionHeader",
|
||||||
|
2
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Equation",
|
||||||
|
2
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Picture",
|
||||||
|
1
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Caption",
|
||||||
|
1
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"TextInlineMath",
|
||||||
|
1
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Footnote",
|
||||||
|
1
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"PictureGroup",
|
||||||
|
1
|
||||||
|
]
|
||||||
|
],
|
||||||
|
"block_metadata": {
|
||||||
|
"llm_request_count": 2,
|
||||||
|
"llm_error_count": 0,
|
||||||
|
"llm_tokens_used": 4608
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"page_id": 3,
|
||||||
|
"text_extraction_method": "pdftext",
|
||||||
|
"block_counts": [
|
||||||
|
[
|
||||||
|
"Span",
|
||||||
|
337
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Line",
|
||||||
|
109
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Text",
|
||||||
|
8
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"SectionHeader",
|
||||||
|
3
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Equation",
|
||||||
|
1
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"TextInlineMath",
|
||||||
|
1
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Reference",
|
||||||
|
1
|
||||||
|
]
|
||||||
|
],
|
||||||
|
"block_metadata": {
|
||||||
|
"llm_request_count": 1,
|
||||||
|
"llm_error_count": 0,
|
||||||
|
"llm_tokens_used": 3057
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"page_id": 4,
|
||||||
|
"text_extraction_method": "pdftext",
|
||||||
|
"block_counts": [
|
||||||
|
[
|
||||||
|
"Span",
|
||||||
|
505
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Line",
|
||||||
|
121
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Text",
|
||||||
|
6
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"TextInlineMath",
|
||||||
|
6
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Equation",
|
||||||
|
2
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"SectionHeader",
|
||||||
|
2
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Reference",
|
||||||
|
1
|
||||||
|
]
|
||||||
|
],
|
||||||
|
"block_metadata": {
|
||||||
|
"llm_request_count": 2,
|
||||||
|
"llm_error_count": 0,
|
||||||
|
"llm_tokens_used": 3814
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"page_id": 5,
|
||||||
|
"text_extraction_method": "pdftext",
|
||||||
|
"block_counts": [
|
||||||
|
[
|
||||||
|
"Span",
|
||||||
|
332
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"TableCell",
|
||||||
|
113
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Line",
|
||||||
|
100
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Text",
|
||||||
|
7
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"SectionHeader",
|
||||||
|
6
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Reference",
|
||||||
|
3
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Table",
|
||||||
|
2
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Caption",
|
||||||
|
2
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"TableGroup",
|
||||||
|
2
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"TextInlineMath",
|
||||||
|
1
|
||||||
|
]
|
||||||
|
],
|
||||||
|
"block_metadata": {
|
||||||
|
"llm_request_count": 3,
|
||||||
|
"llm_error_count": 0,
|
||||||
|
"llm_tokens_used": 7669
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"page_id": 6,
|
||||||
|
"text_extraction_method": "pdftext",
|
||||||
|
"block_counts": [
|
||||||
|
[
|
||||||
|
"Span",
|
||||||
|
229
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"TableCell",
|
||||||
|
180
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Line",
|
||||||
|
37
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Caption",
|
||||||
|
4
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"SectionHeader",
|
||||||
|
2
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Text",
|
||||||
|
2
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Reference",
|
||||||
|
2
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Figure",
|
||||||
|
1
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Table",
|
||||||
|
1
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"FigureGroup",
|
||||||
|
1
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"TableGroup",
|
||||||
|
1
|
||||||
|
]
|
||||||
|
],
|
||||||
|
"block_metadata": {
|
||||||
|
"llm_request_count": 2,
|
||||||
|
"llm_error_count": 0,
|
||||||
|
"llm_tokens_used": 7459
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"page_id": 7,
|
||||||
|
"text_extraction_method": "pdftext",
|
||||||
|
"block_counts": [
|
||||||
|
[
|
||||||
|
"Span",
|
||||||
|
145
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Line",
|
||||||
|
68
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"TableCell",
|
||||||
|
32
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Text",
|
||||||
|
5
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Reference",
|
||||||
|
5
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"SectionHeader",
|
||||||
|
3
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"ListItem",
|
||||||
|
3
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Caption",
|
||||||
|
2
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Figure",
|
||||||
|
1
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Table",
|
||||||
|
1
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"FigureGroup",
|
||||||
|
1
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"TableGroup",
|
||||||
|
1
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"ListGroup",
|
||||||
|
1
|
||||||
|
]
|
||||||
|
],
|
||||||
|
"block_metadata": {
|
||||||
|
"llm_request_count": 1,
|
||||||
|
"llm_error_count": 0,
|
||||||
|
"llm_tokens_used": 2613
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"page_id": 8,
|
||||||
|
"text_extraction_method": "pdftext",
|
||||||
|
"block_counts": [
|
||||||
|
[
|
||||||
|
"Span",
|
||||||
|
312
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Line",
|
||||||
|
101
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"ListItem",
|
||||||
|
24
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Reference",
|
||||||
|
24
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"ListGroup",
|
||||||
|
2
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Text",
|
||||||
|
1
|
||||||
|
]
|
||||||
|
],
|
||||||
|
"block_metadata": {
|
||||||
|
"llm_request_count": 0,
|
||||||
|
"llm_error_count": 0,
|
||||||
|
"llm_tokens_used": 0
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"page_id": 9,
|
||||||
|
"text_extraction_method": "pdftext",
|
||||||
|
"block_counts": [
|
||||||
|
[
|
||||||
|
"Span",
|
||||||
|
26
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Line",
|
||||||
|
7
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Text",
|
||||||
|
1
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"ListItem",
|
||||||
|
1
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Reference",
|
||||||
|
1
|
||||||
|
]
|
||||||
|
],
|
||||||
|
"block_metadata": {
|
||||||
|
"llm_request_count": 0,
|
||||||
|
"llm_error_count": 0,
|
||||||
|
"llm_tokens_used": 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"debug_data_path": "debug_data/multicolcnn"
|
||||||
|
}
|
After Width: | Height: | Size: 44 KiB |
After Width: | Height: | Size: 38 KiB |
After Width: | Height: | Size: 46 KiB |
After Width: | Height: | Size: 64 KiB |
After Width: | Height: | Size: 23 KiB |
After Width: | Height: | Size: 54 KiB |
After Width: | Height: | Size: 53 KiB |
After Width: | Height: | Size: 58 KiB |
After Width: | Height: | Size: 39 KiB |
After Width: | Height: | Size: 44 KiB |
After Width: | Height: | Size: 31 KiB |
After Width: | Height: | Size: 41 KiB |
After Width: | Height: | Size: 56 KiB |
After Width: | Height: | Size: 59 KiB |
After Width: | Height: | Size: 16 KiB |
After Width: | Height: | Size: 6.6 KiB |
After Width: | Height: | Size: 9.8 KiB |
After Width: | Height: | Size: 17 KiB |
After Width: | Height: | Size: 24 KiB |
After Width: | Height: | Size: 11 KiB |
After Width: | Height: | Size: 15 KiB |
After Width: | Height: | Size: 6.2 KiB |
After Width: | Height: | Size: 13 KiB |
After Width: | Height: | Size: 5.9 KiB |
After Width: | Height: | Size: 42 KiB |
After Width: | Height: | Size: 30 KiB |
After Width: | Height: | Size: 6.5 KiB |
After Width: | Height: | Size: 5.1 KiB |
After Width: | Height: | Size: 11 KiB |
After Width: | Height: | Size: 17 KiB |
After Width: | Height: | Size: 16 KiB |
After Width: | Height: | Size: 16 KiB |
After Width: | Height: | Size: 9.3 KiB |
After Width: | Height: | Size: 32 KiB |