├── .github
└── workflows
│ ├── cla.yml
│ ├── publish.yml
│ └── tests.yml
├── .gitignore
├── CLA.md
├── LICENSE
├── README.md
├── benchmarks
├── benchmark.py
└── scoring.py
├── extract.py
├── poetry.lock
├── pyproject.toml
├── run_table_app.py
├── scripts
└── verify_benchmark_scores.py
├── static
└── images
│ └── table_example.png
├── table_app.py
└── tabled
├── assignment.py
├── extract.py
├── fileinput.py
├── formats
├── __init__.py
├── common.py
├── csv.py
├── html.py
└── markdown.py
├── heuristics
├── __init__.py
└── cells.py
├── inference
├── detection.py
├── models.py
└── recognition.py
├── schema.py
└── settings.py
/.github/workflows/cla.yml:
--------------------------------------------------------------------------------
1 | name: "Tabled CLA Assistant"
2 | on:
3 | issue_comment:
4 | types: [created]
5 | pull_request_target:
6 | types: [opened,closed,synchronize]
7 |
8 | # explicitly configure permissions, in case your GITHUB_TOKEN workflow permissions are set to read-only in repository settings
9 | permissions:
10 | actions: write
11 | contents: write
12 | pull-requests: write
13 | statuses: write
14 |
15 | jobs:
16 | CLAAssistant:
17 | runs-on: ubuntu-latest
18 | steps:
19 | - name: "Tabled CLA Assistant"
20 | if: (github.event.comment.body == 'recheck' || github.event.comment.body == 'I have read the CLA Document and I hereby sign the CLA') || github.event_name == 'pull_request_target'
21 | uses: contributor-assistant/github-action@v2.3.0
22 | env:
23 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
24 | # the below token should have repo scope and must be manually added by you in the repository's secret
25 | # This token is required only if you have configured to store the signatures in a remote repository/organization
26 | PERSONAL_ACCESS_TOKEN: ${{ secrets.PERSONAL_ACCESS_TOKEN }}
27 | with:
28 | path-to-signatures: 'signatures/version1/cla.json'
29 | path-to-document: 'https://github.com/VikParuchuri/tabled/blob/master/CLA.md'
30 | # branch should not be protected
31 | branch: 'master'
32 | allowlist: VikParuchuri
--------------------------------------------------------------------------------
/.github/workflows/publish.yml:
--------------------------------------------------------------------------------
1 | name: Python package
2 | on:
3 | push:
4 | tags:
5 | - "v*.*.*"
6 | jobs:
7 | build:
8 | runs-on: ubuntu-latest
9 | steps:
10 | - uses: actions/checkout@v3
11 | - name: Set up Python 3.11
12 | uses: actions/setup-python@v4
13 | with:
14 | python-version: 3.11
15 | - name: Install python dependencies
16 | run: |
17 | pip install poetry
18 | poetry install
19 | - name: Build package
20 | run: |
21 | poetry build
22 | - name: Publish package
23 | env:
24 | PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
25 | run: |
26 | poetry config pypi-token.pypi "$PYPI_TOKEN"
27 | poetry publish
28 |
--------------------------------------------------------------------------------
/.github/workflows/tests.yml:
--------------------------------------------------------------------------------
1 | name: Integration test
2 |
3 | on: [push]
4 |
5 | env:
6 | TORCH_DEVICE: "cpu"
7 |
8 | jobs:
9 | build:
10 | runs-on: ubuntu-latest
11 | steps:
12 | - uses: actions/checkout@v3
13 | - name: Set up Python 3.11
14 | uses: actions/setup-python@v4
15 | with:
16 | python-version: 3.11
17 | - name: Install apt dependencies
18 | run: |
19 | sudo apt-get update
20 | - name: Install python dependencies
21 | run: |
22 | pip install poetry
23 | poetry install
24 | poetry run pip uninstall torch -y
25 | poetry run pip install torch --index-url https://download.pytorch.org/whl/cpu
26 | - name: Run benchmark test
27 | run: |
28 | poetry run python benchmarks/benchmark.py --max 5 temp.json
29 | poetry run python scripts/verify_benchmark_scores.py temp.json
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | private.py
2 | .DS_Store
3 | local.env
4 | notebooks
5 | results
6 |
7 | # Byte-compiled / optimized / DLL files
8 | __pycache__/
9 | *.py[cod]
10 | *$py.class
11 |
12 | # C extensions
13 | *.so
14 |
15 | # Distribution / packaging
16 | .Python
17 | build/
18 | develop-eggs/
19 | dist/
20 | downloads/
21 | eggs/
22 | .eggs/
23 | lib/
24 | lib64/
25 | parts/
26 | sdist/
27 | var/
28 | wheels/
29 | share/python-wheels/
30 | *.egg-info/
31 | .installed.cfg
32 | *.egg
33 | MANIFEST
34 |
35 | # PyInstaller
36 | # Usually these files are written by a python script from a template
37 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
38 | *.manifest
39 | *.spec
40 |
41 | # Installer logs
42 | pip-log.txt
43 | pip-delete-this-directory.txt
44 |
45 | # Unit test / coverage reports
46 | htmlcov/
47 | .tox/
48 | .nox/
49 | .coverage
50 | .coverage.*
51 | .cache
52 | nosetests.xml
53 | coverage.xml
54 | *.cover
55 | *.py,cover
56 | .hypothesis/
57 | .pytest_cache/
58 | cover/
59 |
60 | # Translations
61 | *.mo
62 | *.pot
63 |
64 | # Django stuff:
65 | *.log
66 | local_settings.py
67 | db.sqlite3
68 | db.sqlite3-journal
69 |
70 | # Flask stuff:
71 | instance/
72 | .webassets-cache
73 |
74 | # Scrapy stuff:
75 | .scrapy
76 |
77 | # Sphinx documentation
78 | docs/_build/
79 |
80 | # PyBuilder
81 | .pybuilder/
82 | target/
83 |
84 | # Jupyter Notebook
85 | .ipynb_checkpoints
86 |
87 | # IPython
88 | profile_default/
89 | ipython_config.py
90 |
91 | # pyenv
92 | # For a library or package, you might want to ignore these files since the code is
93 | # intended to run in multiple environments; otherwise, check them in:
94 | # .python-version
95 |
96 | # pipenv
97 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
98 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
99 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
100 | # install all needed dependencies.
101 | #Pipfile.lock
102 |
103 | # poetry
104 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105 | # This is especially recommended for binary packages to ensure reproducibility, and is more
106 | # commonly ignored for libraries.
107 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108 | #poetry.lock
109 |
110 | # pdm
111 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
112 | #pdm.lock
113 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
114 | # in version control.
115 | # https://pdm.fming.dev/#use-with-ide
116 | .pdm.toml
117 |
118 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
119 | __pypackages__/
120 |
121 | # Celery stuff
122 | celerybeat-schedule
123 | celerybeat.pid
124 |
125 | # SageMath parsed files
126 | *.sage.py
127 |
128 | # Environments
129 | .env
130 | .venv
131 | env/
132 | venv/
133 | ENV/
134 | env.bak/
135 | venv.bak/
136 |
137 | # Spyder project settings
138 | .spyderproject
139 | .spyproject
140 |
141 | # Rope project settings
142 | .ropeproject
143 |
144 | # mkdocs documentation
145 | /site
146 |
147 | # mypy
148 | .mypy_cache/
149 | .dmypy.json
150 | dmypy.json
151 |
152 | # Pyre type checker
153 | .pyre/
154 |
155 | # pytype static type analyzer
156 | .pytype/
157 |
158 | # Cython debug symbols
159 | cython_debug/
160 |
161 | # PyCharm
162 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
163 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
164 | # and can be added to the global gitignore or merged into this file. For a more nuclear
165 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
166 | .idea/
--------------------------------------------------------------------------------
/CLA.md:
--------------------------------------------------------------------------------
1 | Tabled Contributor Agreement
2 |
3 | This Tabled Contributor Agreement ("TCA") 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.
4 |
5 | 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.
6 |
7 | 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.
8 | 2. With respect to any worldwide copyrights, or copyright applications and registrations, in your contribution:
9 | - 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;
10 | - 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;
11 | - you agree that you will not assert any moral rights in your contribution against us, our licensees or transferees;
12 | - you agree that we may register a copyright in your contribution and exercise all ownership rights associated with it; and
13 | - 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.
14 | 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:
15 | - 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
16 | - at our option, to sublicense these same rights to third parties through multiple levels of sublicensees or other licensing arrangements.
17 | 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.
18 | 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.
19 | 5. You covenant, represent, warrant and agree that:
20 | - 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 SCA;
21 | - to the best of your knowledge, each contribution will not violate any third party's copyrights, trademarks, patents, or other intellectual property rights; and
22 | - each contribution shall be in compliance with U.S. export control laws and other applicable export and import laws.
23 | 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 TCA.
24 | 6. This TCA is governed by the laws of the State of California and applicable U.S. Federal law. Any choice of law rules will not apply.
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | Tabled table extractor
635 | Copyright (C) 2024 Vikas Paruchuri
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Tabled Copyright (C) 2024 Vikas Paruchuri
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | > [!IMPORTANT]
2 | > Tabled is now deprecated. The functionality here has been migrated to [marker](https://github.com/vikParuchuri/marker).
3 | > To extract tables from a PDF with marker, you can run `python convert_single.py FILENAME --converter_cls marker.converters.table.TableConverter`
4 | > Read more, and see other CLI options [here](https://github.com/vikParuchuri/marker?tab=readme-ov-file#extract-tables).
5 |
6 | # Tabled
7 |
8 | Tabled is a small library for detecting and extracting tables. It uses [surya](https://www.github.com/VikParuchuri/surya) to find all the tables in a PDF, identifies the rows/columns, and formats cells into markdown, csv, or html.
9 |
10 | ## Example
11 |
12 | 
13 |
14 |
15 | | Characteristic | | | Population | | | | Change from 2016 to 2060 | |
16 | |--------------------|-------|-------|--------------|-------|-------|-------|------------------------------|---------|
17 | | | 2016 | 2020 | 2030 | 2040 | 2050 | 2060 | Number | Percent |
18 | | Total population | 323.1 | 332.6 | 355.1 | 373.5 | 388.9 | 404.5 | 81.4 | 25.2 |
19 | | Under 18 years | 73.6 | 74.0 | 75.7 | 77.1 | 78.2 | 80.1 | 6.5 | 8.8 |
20 | | 18 to 44 years | 116.0 | 119.2 | 125.0 | 126.4 | 129.6 | 132.7 | 16.7 | 14.4 |
21 | | 45 to 64 years | 84.3 | 83.4 | 81.3 | 89.1 | 95.4 | 97.0 | 12.7 | 15.1 |
22 | | 65 years and over | 49.2 | 56.1 | 73.1 | 80.8 | 85.7 | 94.7 | 45.4 | 92.3 |
23 | | 85 years and over | 6.4 | 6.7 | 9.1 | 14.4 | 18.6 | 19.0 | 12.6 | 198.1 |
24 | | 100 years and over | 0.1 | 0.1 | 0.1 | 0.2 | 0.4 | 0.6 | 0.5 | 618.3 |
25 |
26 |
27 | ## Community
28 |
29 | [Discord](https://discord.gg//KuZwXNGnfH) is where we discuss future development.
30 |
31 | # Hosted API
32 |
33 | There is a hosted API for tabled available [here](https://www.datalab.to/):
34 |
35 | - Works with PDF, images, word docs, and powerpoints
36 | - Consistent speed, with no latency spikes
37 | - High reliability and uptime
38 |
39 | # Commercial usage
40 |
41 | I want tabled 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.
42 |
43 | 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).
44 |
45 | # Installation
46 |
47 | 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.
48 |
49 | Install with:
50 |
51 | ```shell
52 | pip install tabled-pdf
53 | ```
54 |
55 | Post-install:
56 |
57 | - Inspect the settings in `tabled/settings.py`. You can override any settings with environment variables.
58 | - Your torch device will be automatically detected, but you can override this. For example, `TORCH_DEVICE=cuda`.
59 | - Model weights will automatically download the first time you run tabled.
60 |
61 | # Usage
62 |
63 | ```shell
64 | tabled DATA_PATH
65 | ```
66 |
67 | - `DATA_PATH` can be an image, pdf, or folder of images/pdfs
68 | - `--format` specifies output format for each table (`markdown`, `html`, or `csv`)
69 | - `--save_json` saves additional row and column information in a json file
70 | - `--save_debug_images` saves images showing the detected rows and columns
71 | - `--skip_detection` means that the images you pass in are all cropped tables and don't need any table detection.
72 | - `--detect_cell_boxes` by default, tabled will attempt to pull cell information out of the pdf. If you instead want cells to be detected by a detection model, specify this (usually you only need this with pdfs that have bad embedded text).
73 | - `--save_images` specifies that images of detected rows/columns and cells should be saved.
74 |
75 | After running the script, the output directory will contain folders with the same basenames as the input filenames. Inside those folders will be the markdown files for each table in the source documents. There will also optionally be images of the tables.
76 |
77 | There will also be a `results.json` file in the root of the output directory. The file will contain a json dictionary where the keys are the input filenames without extensions. Each value will be a list of dictionaries, one per table in the document. Each table dictionary contains:
78 |
79 | - `cells` - the detected text and bounding boxes for each table cell.
80 | - `bbox` - bbox of the cell within the table bbox
81 | - `text` - the text of the cell
82 | - `row_ids` - ids of rows the cell belongs to
83 | - `col_ids` - ids of columns the cell belongs to
84 | - `order` - order of this cell within its assigned row/column cell. (sort by row, then column, then order)
85 | - `rows` - bboxes of the detected rows
86 | - `bbox` - bbox of the row in (x1, x2, y1, y2) format
87 | - `row_id` - unique id of the row
88 | - `cols` - bboxes of detected columns
89 | - `bbox` - bbox of the column in (x1, x2, y1, y2) format
90 | - `col_id` - unique id of the column
91 | - `image_bbox` - the bbox for the image in (x1, y1, x2, y2) format. (x1, y1) is the top left corner, and (x2, y2) is the bottom right corner. The table bbox is relative to this.
92 | - `bbox` - the bounding box of the table within the image bbox.
93 | - `pnum` - page number within the document
94 | - `tnum` - table index on the page
95 |
96 | ## Interactive App
97 |
98 | I've included a streamlit app that lets you interactively try tabled on images or PDF files. Run it with:
99 |
100 | ```shell
101 | pip install streamlit
102 | tabled_gui
103 | ```
104 |
105 | ## From python
106 |
107 | ```python
108 | from tabled.extract import extract_tables
109 | from tabled.fileinput import load_pdfs_images
110 | from tabled.inference.models import load_detection_models, load_recognition_models, load_layout_models
111 |
112 | det_models, rec_models, layout_models = load_detection_models(), load_recognition_models(), load_layout_models()
113 | images, highres_images, names, text_lines = load_pdfs_images(IN_PATH)
114 |
115 | page_results = extract_tables(images, highres_images, text_lines, det_models, layout_models, rec_models)
116 | ```
117 |
118 | # Benchmarks
119 |
120 | | Avg score | Time per table | Total tables |
121 | |-------------|------------------|----------------|
122 | | 0.847 | 0.029 | 688 |
123 |
124 | ## Quality
125 |
126 | Getting good ground truth data for tables is hard, since you're either constrained to simple layouts that can be heuristically parsed and rendered, or you need to use LLMs, which make mistakes. I chose to use GPT-4 table predictions as a pseudo-ground-truth.
127 |
128 | Tabled gets a `.847` alignment score when compared to GPT-4, which indicates alignment between the text in table rows/cells. Some of the misalignments are due to GPT-4 mistakes, or small inconsistencies in what GPT-4 considered the borders of the table. In general, extraction quality is quite high.
129 |
130 | ## Performance
131 |
132 | Running on an A10G with 10GB of VRAM usage and batch size `64`, tabled takes `.029` seconds per table.
133 |
134 | ## Running the benchmark
135 |
136 | Run the benchmark with:
137 |
138 | ```shell
139 | python benchmarks/benchmark.py out.json
140 | ```
141 |
142 | # Acknowledgements
143 |
144 | - Thank you to [Peter Jansen](https://cognitiveai.org/) for the benchmarking dataset, and for discussion about table parsing.
145 | - Huggingface for inference code and model hosting
146 | - PyTorch for training/inference
--------------------------------------------------------------------------------
/benchmarks/benchmark.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | import json
3 | import time
4 |
5 | import click
6 | import datasets
7 | from surya.input.pdflines import get_table_blocks
8 | from tabulate import tabulate
9 | from tqdm import tqdm
10 | from scoring import score_table
11 | from tabled.assignment import assign_rows_columns
12 |
13 | from tabled.formats import formatter
14 | from tabled.inference.models import load_recognition_models
15 | from tabled.inference.recognition import recognize_tables
16 |
17 |
18 | @click.command()
19 | @click.argument("out_file", type=str)
20 | @click.option("--dataset", type=str, default="vikp/table_bench2", help="Dataset to use")
21 | @click.option("--max", type=int, default=None, help="Max number of tables to process")
22 | def main(out_file, dataset, max):
23 | ds = datasets.load_dataset(dataset, split="train")
24 |
25 | rec_models = load_recognition_models()
26 |
27 | results = []
28 | table_imgs = []
29 | table_blocks = []
30 | image_sizes = []
31 | iterations = len(ds)
32 | if max is not None:
33 | iterations = min(max, len(ds))
34 | for i in range(iterations):
35 | row = ds[i]
36 | line_data = json.loads(row["text_lines"])
37 | table_bbox = row["table_bbox"]
38 | image_size = row["page_size"]
39 | table_img = row["table_image"]
40 |
41 | table_block = get_table_blocks([table_bbox], line_data, image_size)[0]
42 | table_imgs.append(table_img)
43 | table_blocks.append(table_block)
44 | image_sizes.append(image_size)
45 |
46 | start = time.time()
47 | table_rec = recognize_tables(table_imgs, table_blocks, [False] * len(table_imgs), rec_models)
48 | total_time = time.time() - start
49 | cells = [assign_rows_columns(tr, im_size) for tr, im_size in zip(table_rec, image_sizes)]
50 |
51 | for i in range(iterations):
52 | row = ds[i]
53 | table_cells = cells[i]
54 | table_bbox = row["table_bbox"]
55 | gpt4_table = json.loads(row["gpt_4_table"])["markdown_table"]
56 |
57 | table_markdown, _ = formatter("markdown", table_cells)
58 |
59 | results.append({
60 | "score": score_table(table_markdown, gpt4_table),
61 | "arxiv_id": row["arxiv_id"],
62 | "page_idx": row["page_idx"],
63 | "marker_table": table_markdown,
64 | "gpt4_table": gpt4_table,
65 | "table_bbox": table_bbox
66 | })
67 |
68 | avg_score = sum([r["score"] for r in results]) / len(results)
69 | headers = ["Avg score", "Time per table", "Total tables"]
70 | data = [f"{avg_score:.3f}", f"{total_time / len(ds):.3f}", len(ds)]
71 |
72 | table = tabulate([data], headers=headers, tablefmt="github")
73 | print(table)
74 | print("Avg score computed by aligning table cell text with GPT-4 table cell text.")
75 |
76 | with open(out_file, "w+") as f:
77 | json.dump(results, f, indent=2)
78 |
79 |
80 | if __name__ == "__main__":
81 | main()
--------------------------------------------------------------------------------
/benchmarks/scoring.py:
--------------------------------------------------------------------------------
1 | from rapidfuzz import fuzz
2 | import re
3 |
4 |
5 | def split_to_cells(table):
6 | table = table.strip()
7 | table = re.sub(r" {2,}", "", table)
8 | table_rows = table.split("\n")
9 | table_rows = [t for t in table_rows if t.strip()]
10 | table_cells = [[c.strip() for c in r.split("|")] for r in table_rows]
11 | return table_cells
12 |
13 |
14 | def align_rows(hypothesis, ref_row):
15 | best_alignment = []
16 | best_alignment_score = 0
17 | for j in range(0, len(hypothesis)):
18 | alignments = []
19 | for i in range(len(ref_row)):
20 | if i >= len(hypothesis[j]):
21 | alignments.append(0)
22 | continue
23 | alignment = fuzz.ratio(hypothesis[j][i], ref_row[i], score_cutoff=30) / 100
24 | alignments.append(alignment)
25 | if len(alignments) == 0:
26 | continue
27 | alignment_score = sum(alignments) / len(alignments)
28 | if alignment_score >= best_alignment_score:
29 | best_alignment = alignments
30 | best_alignment_score = alignment_score
31 | return best_alignment
32 |
33 |
34 | def score_table(hypothesis, reference):
35 | hypothesis = split_to_cells(hypothesis)
36 | reference = split_to_cells(reference)
37 |
38 | alignments = []
39 | for i in range(0, len(reference)):
40 | alignments.extend(align_rows(hypothesis, reference[i]))
41 | return sum(alignments) / max(len(alignments), 1)
--------------------------------------------------------------------------------
/extract.py:
--------------------------------------------------------------------------------
1 | import json
2 | from collections import defaultdict
3 |
4 | import copy
5 | import os
6 |
7 | import click
8 | from surya.postprocessing.heatmap import draw_bboxes_on_image
9 |
10 | from tabled.extract import extract_tables
11 | from tabled.formats import formatter
12 | from tabled.fileinput import load_pdfs_images
13 | from tabled.inference.models import load_detection_models, load_recognition_models, load_layout_models
14 |
15 |
16 | @click.command(help="Extract tables from PDFs")
17 | @click.argument("in_path", type=click.Path(exists=True))
18 | @click.argument("out_folder", type=click.Path())
19 | @click.option("--save_json", is_flag=True, help="Save row/column/cell information in json format")
20 | @click.option("--save_debug_images", is_flag=True, help="Save images for debugging")
21 | @click.option("--skip_detection", is_flag=True, help="Skip table detection")
22 | @click.option("--detect_cell_boxes", is_flag=True, help="Detect table cell boxes vs extract from PDF. Will also run OCR.")
23 | @click.option("--format", type=click.Choice(["markdown", "csv", "html"]), default="markdown")
24 | def main(in_path, out_folder, save_json, save_debug_images, skip_detection, detect_cell_boxes, format):
25 | os.makedirs(out_folder, exist_ok=True)
26 | images, highres_images, names, text_lines = load_pdfs_images(in_path)
27 | pnums = []
28 | prev_name = None
29 | for i, name in enumerate(names):
30 | if prev_name is None or prev_name != name:
31 | pnums.append(0)
32 | else:
33 | pnums.append(pnums[-1] + 1)
34 |
35 | prev_name = name
36 |
37 | det_models = load_detection_models()
38 | rec_models = load_recognition_models()
39 | layout_models = load_layout_models()
40 |
41 | page_results = extract_tables(images, highres_images, text_lines, det_models, layout_models, rec_models, skip_detection=skip_detection, detect_boxes=detect_cell_boxes)
42 |
43 | out_json = defaultdict(list)
44 | for name, pnum, result in zip(names, pnums, page_results):
45 | for i in range(result.total):
46 | page_cells = result.cells[i]
47 | page_rc = result.rows_cols[i]
48 | img = result.table_imgs[i]
49 |
50 | base_path = os.path.join(out_folder, name)
51 | os.makedirs(base_path, exist_ok=True)
52 |
53 | formatted_result, ext = formatter(format, page_cells)
54 | base_name = f"page{pnum}_table{i}"
55 | with open(os.path.join(base_path, f"{base_name}.{ext}"), "w+", encoding="utf-8") as f:
56 | f.write(formatted_result)
57 |
58 | img.save(os.path.join(base_path, f"{base_name}.png"))
59 |
60 | res = {
61 | "cells": [c.model_dump() for c in page_cells],
62 | "rows": [r.model_dump() for r in page_rc.rows],
63 | "cols": [c.model_dump() for c in page_rc.cols],
64 | "bbox": result.bboxes[i].bbox,
65 | "image_bbox": result.image_bboxes[i].bbox,
66 | "pnum": pnum,
67 | "tnum": i
68 | }
69 | out_json[name].append(res)
70 |
71 | if save_debug_images:
72 | boxes = [l.bbox for l in page_cells]
73 | labels = [l.label for l in page_cells]
74 | bbox_image = draw_bboxes_on_image(boxes, copy.deepcopy(img), labels=labels, label_font_size=20)
75 | bbox_image.save(os.path.join(base_path, f"{base_name}_cells.png"))
76 |
77 | rows = [l.bbox for l in page_rc.rows]
78 | cols = [l.bbox for l in page_rc.cols]
79 | row_labels = [f"Row {l.row_id}" for l in page_rc.rows]
80 | col_labels = [f"Col {l.col_id}" for l in page_rc.cols]
81 |
82 | rc_image = copy.deepcopy(img)
83 | rc_image = draw_bboxes_on_image(rows, rc_image, labels=row_labels, label_font_size=20, color="blue")
84 | rc_image = draw_bboxes_on_image(cols, rc_image, labels=col_labels, label_font_size=20, color="red")
85 | rc_image.save(os.path.join(base_path, f"{base_name}_rc.png"))
86 |
87 | if save_json:
88 | with open(os.path.join(out_folder, "result.json"), "w+", encoding="utf-8") as f:
89 | json.dump(out_json, f, ensure_ascii=False)
90 |
91 |
92 | if __name__ == "__main__":
93 | main()
94 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [tool.poetry]
2 | name = "tabled-pdf"
3 | version = "0.2.0"
4 | description = "Detect and recognize tables in PDFs and images."
5 | authors = ["Vik Paruchuri "]
6 | readme = "README.md"
7 | license = "GPL-3.0-or-later"
8 | repository = "https://github.com/VikParuchuri/tabled"
9 | keywords = ["table", "table-recognition", "ocr", "pdf"]
10 | packages = [
11 | {include = "tabled"}
12 | ]
13 | include = [
14 | "extract.py",
15 | "table_app.py",
16 | "run_table_app.py",
17 | ]
18 |
19 | [tool.poetry.dependencies]
20 | python = "^3.10"
21 | surya-ocr = "~0.8.0"
22 | click = "^8.1.7"
23 | pypdfium2 = "^4.30.0"
24 | pydantic-settings = "^2.5.2"
25 | pydantic = "^2.9.2"
26 | python-dotenv = "^1.0.1"
27 | tabulate = "^0.9.0"
28 | scikit-learn = "^1.5.2"
29 |
30 | [tool.poetry.group.dev.dependencies]
31 | jupyter = "^1.1.1"
32 | datasets = "^3.0.1"
33 | streamlit = "^1.39.0"
34 | rapidfuzz = "^3.10.0"
35 |
36 | [tool.poetry.scripts]
37 | tabled_gui = "run_table_app:run_app"
38 | tabled = "extract:main"
39 |
40 | [build-system]
41 | requires = ["poetry-core"]
42 | build-backend = "poetry.core.masonry.api"
43 |
--------------------------------------------------------------------------------
/run_table_app.py:
--------------------------------------------------------------------------------
1 | import subprocess
2 | import os
3 |
4 |
5 | def run_app():
6 | cur_dir = os.path.dirname(os.path.abspath(__file__))
7 | ocr_app_path = os.path.join(cur_dir, "table_app.py")
8 | cmd = ["streamlit", "run", ocr_app_path]
9 | subprocess.run(cmd, env={**os.environ, "IN_STREAMLIT": "true"})
10 |
11 |
12 | if __name__ == "__main__":
13 | run_app()
--------------------------------------------------------------------------------
/scripts/verify_benchmark_scores.py:
--------------------------------------------------------------------------------
1 | import json
2 | import argparse
3 |
4 | import click
5 |
6 |
7 | @click.command()
8 | @click.argument("file_path", type=str)
9 | def verify_table_scores(file_path):
10 | with open(file_path, 'r') as file:
11 | data = json.load(file)
12 |
13 | avg = sum([r["score"] for r in data]) / len(data)
14 | if avg < 0.7:
15 | raise ValueError("Average score is below the required threshold of 0.7")
16 |
17 |
18 | if __name__ == "__main__":
19 | verify_table_scores()
20 |
--------------------------------------------------------------------------------
/static/images/table_example.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/VikParuchuri/tabled/4a049e83cd14471a59d557adf4329d06cc5b4778/static/images/table_example.png
--------------------------------------------------------------------------------
/table_app.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | from tabled.assignment import assign_rows_columns
4 | from tabled.fileinput import load_pdfs_images
5 | from tabled.formats.markdown import markdown_format
6 | from tabled.inference.detection import detect_tables
7 | from tabled.inference.recognition import get_cells, recognize_tables
8 |
9 | os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
10 | os.environ["IN_STREAMLIT"] = "true"
11 | import pypdfium2
12 |
13 | import io
14 | import tempfile
15 | from PIL import Image
16 |
17 | import streamlit as st
18 | from tabled.inference.models import load_detection_models, load_recognition_models, load_layout_models
19 |
20 |
21 | @st.cache_resource()
22 | def load_models():
23 | return load_detection_models(), load_recognition_models(), load_layout_models()
24 |
25 |
26 | def run_table_rec(image, highres_image, text_line, models, skip_detection=False, detect_boxes=False):
27 | if not skip_detection:
28 | table_imgs, table_bboxes, _ = detect_tables([image], [highres_image], models[2])
29 | else:
30 | table_imgs = [highres_image]
31 | table_bboxes = [[0, 0, highres_image.size[0], highres_image.size[1]]]
32 |
33 | table_text_lines = [text_line] * len(table_imgs)
34 | highres_image_sizes = [highres_image.size] * len(table_imgs)
35 | cells, needs_ocr = get_cells(table_imgs, table_bboxes, highres_image_sizes, table_text_lines, models[0], detect_boxes=detect_boxes)
36 |
37 | table_rec = recognize_tables(table_imgs, cells, needs_ocr, models[1])
38 | cells = [assign_rows_columns(tr, im_size) for tr, im_size in zip(table_rec, highres_image_sizes)]
39 |
40 | out_data = []
41 | for idx, (cell, pred, table_img) in enumerate(zip(cells, table_rec, table_imgs)):
42 | md = markdown_format(cell)
43 | out_data.append((md, table_img))
44 | return out_data
45 |
46 |
47 | def open_pdf(pdf_file):
48 | stream = io.BytesIO(pdf_file.getvalue())
49 | return pypdfium2.PdfDocument(stream)
50 |
51 |
52 | @st.cache_data()
53 | def get_page_image(pdf_file, page_num, dpi=96):
54 | doc = open_pdf(pdf_file)
55 | renderer = doc.render(
56 | pypdfium2.PdfBitmap.to_pil,
57 | page_indices=[page_num - 1],
58 | scale=dpi / 72,
59 | )
60 | png = list(renderer)[0]
61 | png_image = png.convert("RGB")
62 | return png_image
63 |
64 |
65 | @st.cache_data()
66 | def page_count(pdf_file):
67 | doc = open_pdf(pdf_file)
68 | return len(doc)
69 |
70 |
71 | st.set_page_config(layout="wide")
72 |
73 | models = load_models()
74 |
75 |
76 | st.markdown("""
77 | # Tabled Demo
78 |
79 | This app will let you try tabled, a table detection and recognition model. It will detect and recognize the tables.
80 |
81 | Find the project [here](https://github.com/VikParuchuri/tabled).
82 | """)
83 |
84 | in_file = st.sidebar.file_uploader("PDF file or image:", type=["pdf", "png", "jpg", "jpeg", "gif", "webp"])
85 | skip_detection = st.sidebar.checkbox("Skip table detection", help="Use this if tables are already cropped (the whole PDF page or image is a table)", value=False)
86 | detect_boxes = st.sidebar.checkbox("Detect cell boxes", help="Detect table cell boxes vs extract from PDF. Will also run OCR.", value=False)
87 |
88 | if in_file is None:
89 | st.stop()
90 |
91 | filetype = in_file.type
92 | col = st.columns(1)[0]
93 | container = col.container()
94 |
95 | if "pdf" in filetype:
96 | page_count = page_count(in_file)
97 | page_number = st.sidebar.number_input(f"Page number out of {page_count}:", min_value=1, value=1,
98 | max_value=page_count)
99 |
100 | pil_image = get_page_image(in_file, page_number, 96)
101 | else:
102 | pil_image = Image.open(in_file).convert("RGB")
103 | pil_image_highres = pil_image
104 | page_number = 1
105 |
106 | with col:
107 | st.image(pil_image, caption="PDF file (preview)", use_container_width=True)
108 |
109 | run_marker = st.sidebar.button("Run Tabled")
110 |
111 | if not run_marker:
112 | st.stop()
113 |
114 | # Run Tabled
115 | file_ext = in_file.name.rsplit(".")[-1]
116 | with tempfile.NamedTemporaryFile(suffix=file_ext) as temp_input:
117 | temp_input.write(in_file.getvalue())
118 | temp_input.seek(0)
119 | filename = temp_input.name
120 | images, highres_images, names, text_lines = load_pdfs_images(filename, max_pages=1, start_page=page_number - 1)
121 | out_data = run_table_rec(images[0], highres_images[0], text_lines[0], models, skip_detection=skip_detection, detect_boxes=detect_boxes)
122 |
123 | for idx, (md, table_img) in enumerate(out_data):
124 | container.markdown(f"## Table {idx}")
125 | container.image(table_img, caption=f"Table {idx}", use_container_width=True)
126 | container.markdown(md)
127 | container.code(md)
128 | container.divider()
129 |
130 |
--------------------------------------------------------------------------------
/tabled/assignment.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 | import numpy as np
4 | from surya.schema import TableResult, Bbox
5 |
6 | from tabled.heuristics import heuristic_layout
7 | from tabled.schema import SpanTableCell
8 |
9 |
10 | def is_rotated(rows, cols):
11 | # Determine if the table is rotated by looking at row and column width / height ratios
12 | # Rows should have a >1 ratio, cols <1
13 | widths = sum([r.width for r in rows])
14 | heights = sum([c.height for c in rows]) + 1
15 | r_ratio = widths / heights
16 |
17 | widths = sum([c.width for c in cols])
18 | heights = sum([r.height for r in cols]) + 1
19 | c_ratio = widths / heights
20 |
21 | return r_ratio * 2 < c_ratio
22 |
23 |
24 | def overlapper_idxs(rows, field, thresh=.3):
25 | overlapper_rows = set()
26 | for row in rows:
27 | row_id = getattr(row, field)
28 | if row_id in overlapper_rows:
29 | continue
30 |
31 | for row2 in rows:
32 | row2_id = getattr(row2, field)
33 | if row2_id == row_id or row2_id in overlapper_rows:
34 | continue
35 |
36 | if row.intersection_pct(row2) > thresh:
37 | i_bigger = row.area > row2.area
38 | overlapper_rows.add(row_id if i_bigger else row2_id)
39 | return overlapper_rows
40 |
41 |
42 | def initial_assignment(detection_result: TableResult, thresh=.5) -> List[SpanTableCell]:
43 | overlapper_rows = overlapper_idxs(detection_result.rows, field="row_id")
44 | overlapper_cols = overlapper_idxs(detection_result.cols, field="col_id")
45 |
46 | cells = []
47 | for cell in detection_result.cells:
48 | max_intersection = 0
49 | row_pred = None
50 | for row in detection_result.rows:
51 | if row.row_id in overlapper_rows:
52 | continue
53 |
54 | intersection_pct = Bbox(bbox=cell.bbox).intersection_pct(row)
55 | if intersection_pct > max_intersection and intersection_pct > thresh:
56 | max_intersection = intersection_pct
57 | row_pred = row.row_id
58 |
59 | max_intersection = 0
60 | col_pred = None
61 | for col in detection_result.cols:
62 | if col.col_id in overlapper_cols:
63 | continue
64 |
65 | intersection_pct = Bbox(bbox=cell.bbox).intersection_pct(col)
66 | if intersection_pct > max_intersection and intersection_pct > thresh:
67 | max_intersection = intersection_pct
68 | col_pred = col.col_id
69 |
70 | cells.append(
71 | SpanTableCell(
72 | bbox=cell.bbox,
73 | text=cell.text,
74 | row_ids=[row_pred],
75 | col_ids=[col_pred]
76 | )
77 | )
78 | return cells
79 |
80 |
81 | def assign_overlappers(cells: List[SpanTableCell], detection_result: TableResult, thresh=.5):
82 | overlapper_rows = overlapper_idxs(detection_result.rows, field="row_id")
83 | overlapper_cols = overlapper_idxs(detection_result.cols, field="col_id")
84 |
85 | for cell in cells:
86 | max_intersection = 0
87 | row_pred = None
88 | for row in detection_result.rows:
89 | if row.row_id not in overlapper_rows:
90 | continue
91 |
92 | intersection_pct = Bbox(bbox=cell.bbox).intersection_pct(row)
93 | if intersection_pct > max_intersection and intersection_pct > thresh:
94 | max_intersection = intersection_pct
95 | row_pred = row.row_id
96 |
97 | max_intersection = 0
98 | col_pred = None
99 | for col in detection_result.cols:
100 | if col.col_id not in overlapper_cols:
101 | continue
102 |
103 | intersection_pct = Bbox(bbox=cell.bbox).intersection_pct(col)
104 | if intersection_pct > max_intersection and intersection_pct > thresh:
105 | max_intersection = intersection_pct
106 | col_pred = col.col_id
107 |
108 | if cell.row_ids[0] is None:
109 | cell.row_ids = [row_pred]
110 | if cell.col_ids[0] is None:
111 | cell.col_ids = [col_pred]
112 |
113 |
114 | def assign_unassigned(table_cells: list, detection_result: TableResult):
115 | rotated = is_rotated(detection_result.rows, detection_result.cols)
116 | for cell in table_cells:
117 | if cell.row_ids[0] is None:
118 | closest_row = None
119 | min_dist = None
120 | for row in detection_result.rows:
121 | if rotated:
122 | dist = cell.center_x_distance(row)
123 | else:
124 | dist = cell.center_y_distance(row)
125 |
126 | if min_dist is None or dist < min_dist:
127 | closest_row = row.row_id
128 | min_dist = dist
129 | cell.row_ids = [closest_row]
130 |
131 | if cell.col_ids[0] is None:
132 | closest_col = None
133 | min_dist = None
134 | for col in detection_result.cols:
135 | if rotated:
136 | dist = cell.center_y_distance(col)
137 | else:
138 | dist = cell.center_x_distance(col)
139 |
140 | if min_dist is None or dist < min_dist:
141 | closest_col = col.col_id
142 | min_dist = dist
143 |
144 | cell.col_ids = [closest_col]
145 |
146 |
147 | def handle_rowcol_spans(table_cells: list, detection_result: TableResult, thresh=.25):
148 | rotated = is_rotated(detection_result.rows, detection_result.cols)
149 | for cell in table_cells:
150 | for c in detection_result.cols:
151 | col_intersect_pct = cell.intersection_y_pct(c) if rotated else cell.intersection_x_pct(c)
152 | other_cell_exists = len([tc for tc in table_cells if tc.col_ids[0] == c.col_id and tc.row_ids[0] == cell.row_ids[0]]) > 0
153 | if col_intersect_pct > thresh and not other_cell_exists:
154 | cell.col_ids.append(c.col_id)
155 | else:
156 | break
157 | # Assign to first column header appears in
158 | cell.col_ids = sorted(cell.col_ids)
159 |
160 | for cell in table_cells:
161 | for r in detection_result.rows:
162 | row_intersect_pct = cell.intersection_x_pct(r) if rotated else cell.intersection_y_pct(r)
163 | other_cell_exists = len([tc for tc in table_cells if tc.row_ids[0] == r.row_id and tc.col_ids[0] == cell.col_ids[0]]) > 0
164 | if row_intersect_pct > thresh and not other_cell_exists:
165 | cell.row_ids.append(r.row_id)
166 | else:
167 | break
168 |
169 |
170 | def merge_multiline_rows(detection_result: TableResult, table_cells: List[SpanTableCell]):
171 | def find_row_gap(r1, r2):
172 | return min([abs(r1.bbox[1] - r2.bbox[3]), abs(r2.bbox[1] - r1.bbox[3])])
173 |
174 | all_cols = set([tc.col_ids[0] for tc in table_cells])
175 | if len(all_cols) == 0:
176 | return
177 |
178 | merged_pairs = []
179 | row_gaps = [
180 | find_row_gap(r, r2)
181 | for r, r2 in zip(detection_result.rows, detection_result.rows[1:])
182 | ]
183 | if len(row_gaps) == 0:
184 | return
185 |
186 | gap_thresh = np.median(row_gaps)
187 |
188 | for idx, row in enumerate(detection_result.rows[1:]):
189 | prev_row = detection_result.rows[idx - 1]
190 | gap = find_row_gap(prev_row, row)
191 |
192 | # Ensure the gap between r2 and r1 is small
193 | if gap > gap_thresh:
194 | continue
195 |
196 | r1_cells = [tc for tc in table_cells if tc.row_ids[0] == prev_row.row_id]
197 | r2_cells = [tc for tc in table_cells if tc.row_ids[0] == row.row_id]
198 | r1_cols = set([tc.col_ids[0] for tc in r1_cells])
199 | r2_cols = set([tc.col_ids[0] for tc in r2_cells])
200 |
201 | # Ensure all columns in r2 are in r1
202 | if len(r2_cols - r1_cols) > 0:
203 | continue
204 |
205 | # Ensure r2 has mostly blank cells
206 | if len(r2_cols) / len(all_cols) > .5:
207 | continue
208 |
209 | merged_pairs.append((idx - 1, idx))
210 |
211 | to_remove = set()
212 | for r1_idx, r2_idx in merged_pairs:
213 | detection_result.rows[r1_idx].bbox = [
214 | min(detection_result.rows[r1_idx].bbox[0], detection_result.rows[r2_idx].bbox[0]),
215 | min(detection_result.rows[r1_idx].bbox[1], detection_result.rows[r2_idx].bbox[1]),
216 | max(detection_result.rows[r1_idx].bbox[2], detection_result.rows[r2_idx].bbox[2]),
217 | max(detection_result.rows[r1_idx].bbox[3], detection_result.rows[r2_idx].bbox[3])
218 | ]
219 | to_remove.add(r2_idx)
220 |
221 | new_rows = []
222 | row_counter = 0
223 | for idx, row in enumerate(detection_result.rows):
224 | if idx not in to_remove:
225 | row.row_id = row_counter
226 | new_rows.append(row)
227 | row_counter += 1
228 | detection_result.rows = new_rows
229 |
230 |
231 | def assign_rows_columns(detection_result: TableResult, image_size: list, heuristic_thresh=.6) -> List[SpanTableCell]:
232 | table_cells = initial_assignment(detection_result)
233 | merge_multiline_rows(detection_result, table_cells)
234 | table_cells = initial_assignment(detection_result)
235 | assign_overlappers(table_cells, detection_result)
236 | total_unassigned = len([tc for tc in table_cells if tc.row_ids[0] is None or tc.col_ids[0] is None])
237 | unassigned_frac = total_unassigned / max(len(table_cells), 1)
238 |
239 | if unassigned_frac > heuristic_thresh:
240 | table_cells = heuristic_layout(table_cells, image_size)
241 | return table_cells
242 |
243 | assign_unassigned(table_cells, detection_result)
244 | handle_rowcol_spans(table_cells, detection_result)
245 | return table_cells
246 |
--------------------------------------------------------------------------------
/tabled/extract.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 | from surya.schema import Bbox
4 |
5 | from tabled.assignment import assign_rows_columns
6 | from tabled.inference.detection import detect_tables
7 | from tabled.inference.recognition import get_cells, recognize_tables
8 | from tabled.schema import ExtractPageResult
9 |
10 |
11 | def extract_tables(
12 | images,
13 | highres_images,
14 | text_lines,
15 | det_models,
16 | layout_models,
17 | rec_models,
18 | skip_detection=False,
19 | detect_boxes=False
20 | ) -> List[ExtractPageResult]:
21 | if not skip_detection:
22 | table_imgs, table_bboxes, table_counts = detect_tables(images, highres_images, layout_models)
23 | else:
24 | table_imgs = highres_images
25 | table_bboxes = [[0, 0, img.size[0], img.size[1]] for img in highres_images]
26 | table_counts = [1] * len(highres_images)
27 |
28 | table_text_lines = []
29 | highres_image_sizes = []
30 | for i, tc in enumerate(table_counts):
31 | table_text_lines.extend([text_lines[i]] * tc)
32 | highres_image_sizes.extend([highres_images[i].size] * tc)
33 |
34 | cells, needs_ocr = get_cells(table_imgs, table_bboxes, highres_image_sizes, table_text_lines, det_models, detect_boxes=detect_boxes)
35 |
36 | table_rec = recognize_tables(table_imgs, cells, needs_ocr, rec_models)
37 | cells = [assign_rows_columns(tr, im_size) for tr, im_size in zip(table_rec, highres_image_sizes)]
38 |
39 | results = []
40 | counter = 0
41 | for count in table_counts:
42 | page_start = counter
43 | page_end = counter + count
44 | results.append(ExtractPageResult(
45 | table_imgs=table_imgs[page_start:page_end],
46 | cells=cells[page_start:page_end],
47 | rows_cols=table_rec[page_start:page_end],
48 | bboxes=[Bbox(bbox=b) for b in table_bboxes[page_start:page_end]],
49 | image_bboxes=[Bbox(bbox=[0, 0, size[0], size[1]]) for size in highres_image_sizes[page_start:page_end]]
50 | ))
51 | counter += count
52 |
53 | assert len(results) == len(images)
54 | return results
55 |
--------------------------------------------------------------------------------
/tabled/fileinput.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | from surya.input.load import load_from_folder, load_from_file
4 | from surya.settings import settings as surya_settings
5 |
6 |
7 | def load_pdfs_images(input_path, max_pages=None, start_page=None):
8 | if os.path.isdir(input_path):
9 | images, _, _ = load_from_folder(input_path, max_pages, start_page=start_page)
10 | highres_images, names, text_lines = load_from_folder(input_path, max_pages, dpi=surya_settings.IMAGE_DPI_HIGHRES,
11 | load_text_lines=True, start_page=start_page)
12 | else:
13 | images, _, _ = load_from_file(input_path, max_pages, start_page=start_page)
14 | highres_images, names, text_lines = load_from_file(input_path, max_pages, dpi=surya_settings.IMAGE_DPI_HIGHRES,
15 | load_text_lines=True, start_page=start_page)
16 |
17 | return images, highres_images, names, text_lines
--------------------------------------------------------------------------------
/tabled/formats/__init__.py:
--------------------------------------------------------------------------------
1 | from tabled.formats.csv import csv_format
2 | from tabled.formats.html import html_format
3 | from tabled.formats.markdown import markdown_format
4 |
5 |
6 | def formatter(format, page_cells):
7 | if format == "csv":
8 | return csv_format(page_cells), "csv"
9 | elif format == "markdown":
10 | return markdown_format(page_cells), "md"
11 | elif format == "html":
12 | return html_format(page_cells), "html"
13 | else:
14 | raise ValueError(f"Invalid format: {format}")
--------------------------------------------------------------------------------
/tabled/formats/common.py:
--------------------------------------------------------------------------------
1 | import re
2 | from typing import List
3 |
4 | from tabled.schema import SpanTableCell
5 |
6 |
7 | def sort_within_cell(cells, tolerance=5):
8 | vertical_groups = {}
9 | for i, cell in enumerate(cells):
10 | group_key = round((cell.bbox[1] + cell.bbox[3]) / 2 / tolerance)
11 | if group_key not in vertical_groups:
12 | vertical_groups[group_key] = []
13 | vertical_groups[group_key].append((i, cell.bbox[0]))
14 |
15 | # Sort each group horizontally and flatten the groups into a single list
16 | sorted_cell_idxs = []
17 | for _, group in sorted(vertical_groups.items()):
18 | sorted_group = sorted(group, key=lambda x: x[1])
19 | sorted_cell_idxs.extend([idx for idx, _ in sorted_group])
20 |
21 | cell_order = [sorted_cell_idxs.index(i) for i in range(len(sorted_cell_idxs))]
22 | return cell_order
23 |
24 |
25 | def sort_cells(cells: List[SpanTableCell]):
26 | cell_order = sort_within_cell(cells)
27 | for i, cell in enumerate(cells):
28 | cell.order = cell_order[i]
29 | cells.sort(key=lambda x: (x.row_ids[0], x.col_ids[0], x.order))
30 | return cells
31 |
32 |
33 | def replace_dots(text):
34 | dot_pattern = re.compile(r'(\s*\.\s*){4,}')
35 | dot_multiline_pattern = re.compile(r'.*(\s*\.\s*){4,}.*', re.DOTALL)
36 |
37 | if dot_multiline_pattern.match(text):
38 | text = dot_pattern.sub(' ', text)
39 | return text
40 |
41 |
42 | def replace_newlines(text):
43 | # Replace all newlines
44 | newline_pattern = re.compile(r'[\r\n]+')
45 | return newline_pattern.sub(' ', text).strip()
46 |
--------------------------------------------------------------------------------
/tabled/formats/csv.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 | from tabulate import tabulate
4 |
5 | from tabled.formats.common import sort_cells, replace_dots, replace_newlines
6 | from tabled.schema import SpanTableCell
7 | import csv
8 | import io
9 |
10 |
11 | def replace_all(text):
12 | return replace_newlines(replace_dots(text))
13 |
14 |
15 | def csv_format(cells: List[SpanTableCell]):
16 | cells = sort_cells(cells)
17 | unique_rows = set([cell.row_ids[0] for cell in cells])
18 | unique_cols = set([cell.col_ids[0] for cell in cells])
19 | buff = io.StringIO()
20 | writer = csv.writer(buff)
21 | for row in unique_rows:
22 | text_row = []
23 | for col in unique_cols:
24 | cell = " ".join([cell.text for cell in cells if cell.row_ids[0] == row and cell.col_ids[0] == col])
25 | cell = replace_all(cell)
26 | text_row.append(cell)
27 | writer.writerow(text_row)
28 |
29 | csv_str = buff.getvalue()
30 | return csv_str
31 |
--------------------------------------------------------------------------------
/tabled/formats/html.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 | from tabulate import tabulate
4 |
5 | from tabled.formats.common import sort_cells, replace_dots, replace_newlines
6 | from tabled.schema import SpanTableCell
7 |
8 |
9 | def replace_all(text):
10 | return replace_newlines(replace_dots(text))
11 |
12 |
13 | def html_format(cells: List[SpanTableCell]):
14 | md_rows = []
15 | cells = sort_cells(cells)
16 | unique_rows = set([cell.row_ids[0] for cell in cells])
17 | unique_cols = set([cell.col_ids[0] for cell in cells])
18 | for row in unique_rows:
19 | md_row = []
20 | for col in unique_cols:
21 | cell = " ".join([cell.text for cell in cells if cell.row_ids[0] == row and cell.col_ids[0] == col])
22 | cell = replace_all(cell)
23 | md_row.append(cell)
24 | md_rows.append(md_row)
25 |
26 | headers = "firstrow" if len(cells) > 1 else ""
27 | md = tabulate(md_rows, headers=headers, tablefmt="html", disable_numparse=True)
28 | return md
29 |
--------------------------------------------------------------------------------
/tabled/formats/markdown.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 | from tabulate import tabulate
4 |
5 | from tabled.formats.common import sort_cells, replace_dots, replace_newlines
6 | from tabled.schema import SpanTableCell
7 |
8 |
9 | def replace_special_chars(text):
10 | return text.replace("|", "\\|").replace("-", "\\-")
11 |
12 |
13 | def replace_all(text):
14 | return replace_special_chars(replace_newlines(replace_dots(text)))
15 |
16 |
17 | def markdown_format(cells: List[SpanTableCell]):
18 | md_rows = []
19 | cells = sort_cells(cells)
20 | unique_rows = set([cell.row_ids[0] for cell in cells])
21 | unique_cols = set([cell.col_ids[0] for cell in cells])
22 | for row in unique_rows:
23 | md_row = []
24 | for col in unique_cols:
25 | cell = " ".join([cell.text for cell in cells if cell.row_ids[0] == row and cell.col_ids[0] == col])
26 | cell = replace_all(cell)
27 | md_row.append(cell)
28 | md_rows.append(md_row)
29 |
30 | md = tabulate(md_rows, headers="firstrow", tablefmt="github", disable_numparse=True)
31 | return md
32 |
--------------------------------------------------------------------------------
/tabled/heuristics/__init__.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 | from tabled.heuristics.cells import assign_cells_to_columns
4 | from tabled.schema import SpanTableCell
5 |
6 |
7 | def heuristic_layout(table_cells: List[SpanTableCell], page_size, row_tol=.01) -> List[SpanTableCell]:
8 | table_rows = []
9 | table_row = []
10 | y_top = None
11 | y_bottom = None
12 | for cell in table_cells:
13 | normed_y_start = cell.bbox[1] / page_size[1]
14 | normed_y_end = cell.bbox[3] / page_size[1]
15 |
16 | if y_top is None:
17 | y_top = normed_y_start
18 | if y_bottom is None:
19 | y_bottom = normed_y_end
20 |
21 | y_dist = min(abs(normed_y_start - y_bottom), abs(normed_y_end - y_bottom))
22 | if y_dist < row_tol:
23 | table_row.append(cell)
24 | else:
25 | # New row
26 | if len(table_row) > 0:
27 | table_rows.append(table_row)
28 | table_row = [cell]
29 | y_top = normed_y_start
30 | y_bottom = normed_y_end
31 | if len(table_row) > 0:
32 | table_rows.append(table_row)
33 |
34 | return assign_cells_to_columns(table_rows, page_size)
--------------------------------------------------------------------------------
/tabled/heuristics/cells.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | from sklearn.cluster import DBSCAN
3 |
4 |
5 | def cluster_coords(coords, row_count):
6 | if len(coords) == 0:
7 | return []
8 | coords = np.array(sorted(set(coords))).reshape(-1, 1)
9 |
10 | clustering = DBSCAN(eps=.01, min_samples=max(2, row_count // 4)).fit(coords)
11 | clusters = clustering.labels_
12 |
13 | separators = []
14 | for label in set(clusters):
15 | clustered_points = coords[clusters == label]
16 | separators.append(np.mean(clustered_points))
17 |
18 | separators = sorted(separators)
19 | return separators
20 |
21 |
22 | def find_column_separators(rows, page_size, round_factor=.002, min_count=1):
23 | left_edges = []
24 | right_edges = []
25 | centers = []
26 |
27 | boxes = [c.bbox for r in rows for c in r]
28 |
29 | for cell in boxes:
30 | ncell = [cell[0] / page_size[0], cell[1] / page_size[1], cell[2] / page_size[0], cell[3] / page_size[1]]
31 | left_edges.append(ncell[0] / round_factor * round_factor)
32 | right_edges.append(ncell[2] / round_factor * round_factor)
33 | centers.append((ncell[0] + ncell[2]) / 2 * round_factor / round_factor)
34 |
35 | left_edges = [l for l in left_edges if left_edges.count(l) > min_count]
36 | right_edges = [r for r in right_edges if right_edges.count(r) > min_count]
37 | centers = [c for c in centers if centers.count(c) > min_count]
38 |
39 | sorted_left = cluster_coords(left_edges, len(rows))
40 | sorted_right = cluster_coords(right_edges, len(rows))
41 | sorted_center = cluster_coords(centers, len(rows))
42 |
43 | # Find list with minimum length
44 | separators = max([sorted_left, sorted_right, sorted_center], key=len)
45 | separators.append(1)
46 | separators.insert(0, 0)
47 | return separators
48 |
49 |
50 | def assign_cells_to_columns(rows, page_size, round_factor=.002, tolerance=.01):
51 | separators = find_column_separators(rows, page_size, round_factor=round_factor)
52 | additional_column_index = 0
53 | row_dicts = []
54 |
55 | for row in rows:
56 | new_row = {}
57 | last_col_index = -1
58 | for cell in row:
59 | left_edge = cell.bbox[0] / page_size[0]
60 | column_index = -1
61 | for i, separator in enumerate(separators):
62 | if left_edge - tolerance < separator and last_col_index < i:
63 | column_index = i
64 | break
65 | if column_index == -1:
66 | column_index = len(separators) + additional_column_index
67 | additional_column_index += 1
68 | new_row[column_index] = cell
69 | last_col_index = column_index
70 | additional_column_index = 0
71 | row_dicts.append(new_row)
72 |
73 | cells = []
74 | for row_idx, row in enumerate(row_dicts):
75 | column = 0
76 | for col_idx in sorted(row.keys()):
77 | cell = row[col_idx]
78 | cell.row_ids = [row_idx]
79 | cell.col_ids = [column]
80 | cells.append(cell)
81 | column += 1
82 |
83 | return cells
--------------------------------------------------------------------------------
/tabled/inference/detection.py:
--------------------------------------------------------------------------------
1 | from surya.layout import batch_layout_detection
2 | from surya.postprocessing.util import rescale_bbox
3 | from surya.schema import Bbox
4 |
5 | from tabled.settings import settings
6 |
7 |
8 | def merge_boxes(box1, box2):
9 | return [min(box1[0], box2[0]), min(box1[1], box2[1]), max(box1[2], box2[2]), max(box1[3], box2[3])]
10 |
11 |
12 | def merge_tables(page_table_boxes):
13 | # Merge tables that are next to each other
14 | expansion_factor = 1.02
15 | shrink_factor = .98
16 | ignore_boxes = set()
17 | for i in range(len(page_table_boxes)):
18 | if i in ignore_boxes:
19 | continue
20 | for j in range(i + 1, len(page_table_boxes)):
21 | if j in ignore_boxes:
22 | continue
23 | expanded_box1 = [page_table_boxes[i][0] * shrink_factor, page_table_boxes[i][1],
24 | page_table_boxes[i][2] * expansion_factor, page_table_boxes[i][3]]
25 | expanded_box2 = [page_table_boxes[j][0] * shrink_factor, page_table_boxes[j][1],
26 | page_table_boxes[j][2] * expansion_factor, page_table_boxes[j][3]]
27 | if Bbox(bbox=expanded_box1).intersection_pct(Bbox(bbox=expanded_box2)) > 0:
28 | page_table_boxes[i] = merge_boxes(page_table_boxes[i], page_table_boxes[j])
29 | ignore_boxes.add(j)
30 |
31 | return [b for i, b in enumerate(page_table_boxes) if i not in ignore_boxes]
32 |
33 |
34 | def detect_tables(images, highres_images, models, layout_batch_size=settings.LAYOUT_BATCH_SIZE):
35 | layout_model, layout_processor = models
36 | layout_predictions = batch_layout_detection(images, layout_model, layout_processor, batch_size=layout_batch_size)
37 |
38 | table_imgs = []
39 | table_counts = []
40 | table_bboxes = []
41 |
42 | for layout_pred, img, highres_img in zip(layout_predictions, images, highres_images):
43 | # The bbox for the entire table
44 | bbox = [l.bbox for l in layout_pred.bboxes if l.label == "Table"]
45 |
46 | if len(bbox) == 0:
47 | table_counts.append(0)
48 | continue
49 |
50 | page_table_imgs = []
51 | highres_bbox = []
52 |
53 | # Merge tables that are next to each other
54 | bbox = merge_tables(bbox)
55 |
56 | # Number of tables per page
57 | table_counts.append(len(bbox))
58 |
59 | for bb in bbox:
60 | highres_bb = rescale_bbox(bb, img.size, highres_img.size)
61 | page_table_imgs.append(highres_img.crop(highres_bb))
62 | highres_bbox.append(highres_bb)
63 |
64 | table_imgs.extend(page_table_imgs)
65 | table_bboxes.extend(highres_bbox)
66 |
67 | return table_imgs, table_bboxes, table_counts
--------------------------------------------------------------------------------
/tabled/inference/models.py:
--------------------------------------------------------------------------------
1 | from surya.model.detection.model import load_model as load_det_model, load_processor as load_det_processor
2 | from surya.model.layout.model import load_model as load_layout_model
3 | from surya.model.layout.processor import load_processor as load_layout_processor
4 | from surya.model.recognition.model import load_model as load_rec_model
5 | from surya.model.recognition.processor import load_processor as load_rec_processor
6 | from surya.model.table_rec.model import load_model as load_table_rec_model
7 | from surya.model.table_rec.processor import load_processor as load_table_rec_processor
8 |
9 |
10 | def load_detection_models():
11 | detection_model = load_det_model()
12 | detection_processor = load_det_processor()
13 | return detection_model, detection_processor
14 |
15 |
16 | def load_recognition_models():
17 | table_rec_model = load_table_rec_model()
18 | table_rec_processor = load_table_rec_processor()
19 | rec_model = load_rec_model()
20 | rec_processor = load_rec_processor()
21 | return table_rec_model, table_rec_processor, rec_model, rec_processor
22 |
23 | def load_layout_models():
24 | layout_model = load_layout_model()
25 | layout_processor = load_layout_processor()
26 | return layout_model, layout_processor
--------------------------------------------------------------------------------
/tabled/inference/recognition.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 | from surya.detection import batch_text_detection
4 | from surya.input.pdflines import get_table_blocks
5 | from surya.ocr import run_recognition
6 | from surya.schema import TableResult
7 | from surya.tables import batch_table_recognition
8 |
9 | from tabled.settings import settings
10 |
11 |
12 | def get_cells(table_imgs, table_bboxes, image_sizes, text_lines, models, detect_boxes=False, detector_batch_size=settings.DETECTOR_BATCH_SIZE):
13 | det_model, det_processor = models
14 | table_cells = []
15 | needs_ocr = []
16 |
17 | to_inference_idxs = []
18 | for idx, (highres_bbox, text_line, image_size) in enumerate(zip(table_bboxes, text_lines, image_sizes)):
19 | # The text cells inside each table
20 | table_blocks = get_table_blocks([highres_bbox], text_line, image_size)[0] if text_line is not None else None
21 |
22 | if text_line is None or detect_boxes or len(table_blocks) == 0:
23 | to_inference_idxs.append(idx)
24 | table_cells.append(None)
25 | needs_ocr.append(True)
26 | else:
27 | table_cells.append(table_blocks)
28 | needs_ocr.append(False)
29 |
30 | # Inference tables that need it
31 | if len(to_inference_idxs) > 0:
32 | det_results = batch_text_detection([table_imgs[i] for i in to_inference_idxs], det_model, det_processor, batch_size=detector_batch_size)
33 | for idx, det_result in zip(to_inference_idxs, det_results):
34 | cell_bboxes = [{"bbox": tb.bbox, "text": None} for tb in det_result.bboxes if tb.area > 0]
35 | table_cells[idx] = cell_bboxes
36 |
37 | return table_cells, needs_ocr
38 |
39 |
40 | def recognize_tables(table_imgs, table_cells, needs_ocr: List[bool], models, table_rec_batch_size=settings.TABLE_REC_BATCH_SIZE, ocr_batch_size=settings.RECOGNITION_BATCH_SIZE) -> List[TableResult]:
41 | table_rec_model, table_rec_processor, ocr_model, ocr_processor = models
42 |
43 | if sum(needs_ocr) > 0:
44 | needs_ocr_idx = [idx for idx, needs in enumerate(needs_ocr) if needs]
45 | ocr_images = [img for img, needs in zip(table_imgs, needs_ocr) if needs]
46 | ocr_cells = [[c["bbox"] for c in cells] for cells, needs in zip(table_cells, needs_ocr) if needs]
47 | ocr_langs = [None] * len(ocr_images)
48 |
49 | ocr_predictions = run_recognition(ocr_images, ocr_langs, ocr_model, ocr_processor, bboxes=ocr_cells, batch_size=ocr_batch_size)
50 |
51 | # Assign text to correct spot
52 | for orig_idx, ocr_pred in zip(needs_ocr_idx, ocr_predictions):
53 | for ocr_line, cell in zip(ocr_pred.text_lines, table_cells[orig_idx]):
54 | cell["text"] = ocr_line.text
55 |
56 | table_preds = batch_table_recognition(table_imgs, table_cells, table_rec_model, table_rec_processor, batch_size=table_rec_batch_size)
57 | return table_preds
58 |
59 |
60 |
--------------------------------------------------------------------------------
/tabled/schema.py:
--------------------------------------------------------------------------------
1 | from typing import List, Optional, Any
2 |
3 | from pydantic import BaseModel, model_validator
4 | from surya.schema import Bbox, TableResult
5 |
6 |
7 | def str_join(list, char=","):
8 | return char.join([str(x) for x in list])
9 |
10 |
11 | class SpanTableCell(Bbox):
12 | text: str
13 | row_ids: List[Optional[int]]
14 | col_ids: List[Optional[int]]
15 | order: Optional[int] = None
16 |
17 | def intersection_x_pct(self, other):
18 | if self.width == 0:
19 | return 0
20 |
21 | x_overlap = max(0, min(self.bbox[2], other.bbox[2]) - max(self.bbox[0], other.bbox[0]))
22 | return x_overlap / self.width
23 |
24 |
25 | def intersection_y_pct(self, other):
26 | if self.height == 0:
27 | return 0
28 |
29 | y_overlap = max(0, min(self.bbox[3], other.bbox[3]) - max(self.bbox[1], other.bbox[1]))
30 | return y_overlap / self.height
31 |
32 | @property
33 | def label(self):
34 | return f"{str_join(self.row_ids)}-{str_join(self.col_ids)}"
35 |
36 | def center_x_distance(self, other):
37 | return abs(self.center[0] - other.center[0])
38 |
39 | def center_y_distance(self, other):
40 | return abs(self.center[1] - other.center[1])
41 |
42 |
43 | class ExtractPageResult(BaseModel):
44 | cells: List[List[SpanTableCell]]
45 | rows_cols: List[TableResult]
46 | table_imgs: List[Any]
47 | bboxes: List[Bbox] # Bbox of the table
48 | image_bboxes: List[Bbox] # Bbox of the image/page table is inside
49 |
50 | @model_validator(mode="after")
51 | def check_cells(self):
52 | assert len(self.cells) == len(self.table_imgs), "Cells and table images must be the same length"
53 | assert len(self.cells) == len(self.rows_cols), "Cells and rows/cols must be the same length"
54 | return self
55 |
56 | @property
57 | def total(self):
58 | return len(self.cells)
59 |
--------------------------------------------------------------------------------
/tabled/settings.py:
--------------------------------------------------------------------------------
1 | from typing import Optional
2 |
3 | from dotenv import find_dotenv
4 | from pydantic_settings import BaseSettings
5 |
6 |
7 | class Settings(BaseSettings):
8 | # General
9 | IN_STREAMLIT: bool = False
10 | TORCH_DEVICE: Optional[str] = None
11 |
12 | # Batch sizes
13 | # See https://github.com/VikParuchuri/surya for default values
14 | ## Table recognition
15 | TABLE_REC_BATCH_SIZE: Optional[int] = None
16 | ## OCR
17 | RECOGNITION_BATCH_SIZE: Optional[int] = None
18 | ## Text detector
19 | DETECTOR_BATCH_SIZE: Optional[int] = None
20 | ## Layout
21 | LAYOUT_BATCH_SIZE: Optional[int] = None
22 |
23 | class Config:
24 | env_file = find_dotenv("local.env")
25 | extra = "ignore"
26 |
27 |
28 | settings = Settings()
--------------------------------------------------------------------------------