awtax 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- awtax-0.1.0/LICENSE +202 -0
- awtax-0.1.0/PKG-INFO +67 -0
- awtax-0.1.0/README.md +50 -0
- awtax-0.1.0/awtax/__init__.py +15 -0
- awtax-0.1.0/awtax/cli.py +51 -0
- awtax-0.1.0/awtax/extract.py +218 -0
- awtax-0.1.0/awtax/ocr.py +110 -0
- awtax-0.1.0/awtax/schema.py +72 -0
- awtax-0.1.0/awtax.egg-info/PKG-INFO +67 -0
- awtax-0.1.0/awtax.egg-info/SOURCES.txt +15 -0
- awtax-0.1.0/awtax.egg-info/dependency_links.txt +1 -0
- awtax-0.1.0/awtax.egg-info/entry_points.txt +2 -0
- awtax-0.1.0/awtax.egg-info/requires.txt +6 -0
- awtax-0.1.0/awtax.egg-info/top_level.txt +1 -0
- awtax-0.1.0/pyproject.toml +31 -0
- awtax-0.1.0/setup.cfg +4 -0
- awtax-0.1.0/tests/test_extract.py +130 -0
awtax-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
awtax-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: awtax
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Turn any tax PDF -- returns, W-2, 1099, statements, even scans -- into structured data you can check.
|
|
5
|
+
Author: Aitherium
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Aitherium/awtax
|
|
8
|
+
Keywords: tax,pdf,extraction,ocr,1040,w-2,aither-world
|
|
9
|
+
Requires-Python: >=3.10
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: pymupdf>=1.24
|
|
13
|
+
Provides-Extra: vision
|
|
14
|
+
Requires-Dist: awvision>=0.1; extra == "vision"
|
|
15
|
+
Provides-Extra: ocr
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# awtax
|
|
19
|
+
|
|
20
|
+
**Turn any tax PDF — returns, W-2, 1099, statements, even scans — into structured data you can check.**
|
|
21
|
+
|
|
22
|
+
Your own tax data gets locked inside one vendor's encrypted format, and a filed return or a
|
|
23
|
+
mailed W-2 is a PDF nobody's code can read — half of them are scans with no text layer at all.
|
|
24
|
+
Getting your own numbers back out means re-typing them or re-buying the app that sealed them.
|
|
25
|
+
|
|
26
|
+
`awtax` reads the document. It does **not** give tax advice — it hands you every figure, the page
|
|
27
|
+
it came from, and whether the arithmetic checks out.
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
git clone https://github.com/Aitherium/awtax && cd awtax && pip install -e .
|
|
31
|
+
awtax path/to/return.pdf # -> structured JSON on stdout
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
> Not on PyPI yet, so `pip install awtax` does **not** work — that name resolves
|
|
35
|
+
> to nothing today. Install from the clone until a release exists.
|
|
36
|
+
|
|
37
|
+
## What you get
|
|
38
|
+
|
|
39
|
+
- **Provider-neutral schema** — every figure carries its `page`, its `source` (`text` / `vision` /
|
|
40
|
+
`ocr`), and a `confidence`. A tax number with no provenance is a number nobody can check.
|
|
41
|
+
- **Arithmetic self-checks** — `taxable = AGI − deduction`, `refund = payments − tax`. A figure that
|
|
42
|
+
fails the identity it is defined by is **flagged**, not trusted. The CLI exits `3` when anything
|
|
43
|
+
needs review — silence is not a pass.
|
|
44
|
+
- **Scans handled** — a page with no text layer routes to [`awvision`](../awvision) (a vision model
|
|
45
|
+
reads the form fields *structurally*, far better than raw OCR), with a local `tesseract` fallback
|
|
46
|
+
for fully-offline use. If neither is available you get an explicit `needs_review` — **never a
|
|
47
|
+
silent zero.** (That silent-zero-on-a-scan failure is exactly what this fixes.)
|
|
48
|
+
|
|
49
|
+
## Scan backends (optional)
|
|
50
|
+
|
|
51
|
+
| backend | how | when |
|
|
52
|
+
|---|---|---|
|
|
53
|
+
| **awvision** (preferred) | `pip install -e '.[vision]'` from the clone, pass `--endpoint` | a vision model extracts fields as JSON |
|
|
54
|
+
| **tesseract** (offline fallback) | install the `tesseract` system binary | no network / no vision endpoint |
|
|
55
|
+
| neither | — | pages return `needs_review` with a reason |
|
|
56
|
+
|
|
57
|
+
## Where awtax stops, and the premium packs begin
|
|
58
|
+
|
|
59
|
+
awtax is the open-source **extraction core**. Preparation, deduction discovery, worksheets, ledgers
|
|
60
|
+
and CPA-ready output are the premium **TaxDesk** agent / skill / tool packs that compose on top via
|
|
61
|
+
`awpack` / `awskills`. awtax reads; the packs advise.
|
|
62
|
+
|
|
63
|
+
## Status
|
|
64
|
+
|
|
65
|
+
`0.1.0` — reads native-text 1040 pages and scanned W-2s, self-validates, degrades gracefully.
|
|
66
|
+
Known next work: 1040-vs-1040-X disambiguation on multi-form packets, richer 1099 coverage,
|
|
67
|
+
and native-text W-2 parsing. MIT licensed.
|
awtax-0.1.0/README.md
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# awtax
|
|
2
|
+
|
|
3
|
+
**Turn any tax PDF — returns, W-2, 1099, statements, even scans — into structured data you can check.**
|
|
4
|
+
|
|
5
|
+
Your own tax data gets locked inside one vendor's encrypted format, and a filed return or a
|
|
6
|
+
mailed W-2 is a PDF nobody's code can read — half of them are scans with no text layer at all.
|
|
7
|
+
Getting your own numbers back out means re-typing them or re-buying the app that sealed them.
|
|
8
|
+
|
|
9
|
+
`awtax` reads the document. It does **not** give tax advice — it hands you every figure, the page
|
|
10
|
+
it came from, and whether the arithmetic checks out.
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
git clone https://github.com/Aitherium/awtax && cd awtax && pip install -e .
|
|
14
|
+
awtax path/to/return.pdf # -> structured JSON on stdout
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
> Not on PyPI yet, so `pip install awtax` does **not** work — that name resolves
|
|
18
|
+
> to nothing today. Install from the clone until a release exists.
|
|
19
|
+
|
|
20
|
+
## What you get
|
|
21
|
+
|
|
22
|
+
- **Provider-neutral schema** — every figure carries its `page`, its `source` (`text` / `vision` /
|
|
23
|
+
`ocr`), and a `confidence`. A tax number with no provenance is a number nobody can check.
|
|
24
|
+
- **Arithmetic self-checks** — `taxable = AGI − deduction`, `refund = payments − tax`. A figure that
|
|
25
|
+
fails the identity it is defined by is **flagged**, not trusted. The CLI exits `3` when anything
|
|
26
|
+
needs review — silence is not a pass.
|
|
27
|
+
- **Scans handled** — a page with no text layer routes to [`awvision`](../awvision) (a vision model
|
|
28
|
+
reads the form fields *structurally*, far better than raw OCR), with a local `tesseract` fallback
|
|
29
|
+
for fully-offline use. If neither is available you get an explicit `needs_review` — **never a
|
|
30
|
+
silent zero.** (That silent-zero-on-a-scan failure is exactly what this fixes.)
|
|
31
|
+
|
|
32
|
+
## Scan backends (optional)
|
|
33
|
+
|
|
34
|
+
| backend | how | when |
|
|
35
|
+
|---|---|---|
|
|
36
|
+
| **awvision** (preferred) | `pip install -e '.[vision]'` from the clone, pass `--endpoint` | a vision model extracts fields as JSON |
|
|
37
|
+
| **tesseract** (offline fallback) | install the `tesseract` system binary | no network / no vision endpoint |
|
|
38
|
+
| neither | — | pages return `needs_review` with a reason |
|
|
39
|
+
|
|
40
|
+
## Where awtax stops, and the premium packs begin
|
|
41
|
+
|
|
42
|
+
awtax is the open-source **extraction core**. Preparation, deduction discovery, worksheets, ledgers
|
|
43
|
+
and CPA-ready output are the premium **TaxDesk** agent / skill / tool packs that compose on top via
|
|
44
|
+
`awpack` / `awskills`. awtax reads; the packs advise.
|
|
45
|
+
|
|
46
|
+
## Status
|
|
47
|
+
|
|
48
|
+
`0.1.0` — reads native-text 1040 pages and scanned W-2s, self-validates, degrades gracefully.
|
|
49
|
+
Known next work: 1040-vs-1040-X disambiguation on multi-form packets, richer 1099 coverage,
|
|
50
|
+
and native-text W-2 parsing. MIT licensed.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""awtax -- turn any tax PDF into structured data you can check.
|
|
2
|
+
|
|
3
|
+
Open-source extraction core. Point it at a tax PDF (a filed return, a W-2, a 1099,
|
|
4
|
+
a statement -- scans included) and get every figure out as a provider-neutral schema
|
|
5
|
+
with per-figure provenance and arithmetic self-checks. It reads a document; it does
|
|
6
|
+
not give tax advice. Preparation, deduction discovery, worksheets and filing are the
|
|
7
|
+
premium TaxDesk packs that compose on top.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from .extract import extract
|
|
12
|
+
from .schema import Document, Extraction, Figure
|
|
13
|
+
|
|
14
|
+
__all__ = ["extract", "Extraction", "Document", "Figure", "__version__"]
|
|
15
|
+
__version__ = "0.1.0"
|
awtax-0.1.0/awtax/cli.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""awtax command-line: `awtax path/to/return.pdf` -> JSON on stdout."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
from .extract import extract
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def main(argv: list[str] | None = None) -> int:
|
|
12
|
+
# GENERATED doctor intercept (gen_aw_doctor.py) -- do not edit
|
|
13
|
+
_dv = locals().get("argv")
|
|
14
|
+
if (_dv if _dv is not None else __import__("sys").argv[1:])[:1] == ["doctor"]:
|
|
15
|
+
from ._doctor import report
|
|
16
|
+
return report()
|
|
17
|
+
# GENERATED repo-state intercept (gen_aw_doctor.py) -- do not edit
|
|
18
|
+
try:
|
|
19
|
+
from awgit import state as _aw_state
|
|
20
|
+
except Exception:
|
|
21
|
+
_aw_state = None
|
|
22
|
+
if _aw_state is not None:
|
|
23
|
+
_sv = locals().get("argv")
|
|
24
|
+
if _aw_state.cli_banner(_sv if _sv is not None else __import__("sys").argv[1:]):
|
|
25
|
+
return 0
|
|
26
|
+
ap = argparse.ArgumentParser(
|
|
27
|
+
prog="awtax",
|
|
28
|
+
description="Turn any tax PDF into structured data you can check.",
|
|
29
|
+
)
|
|
30
|
+
ap.add_argument("pdf", help="path to a tax PDF (return, W-2, 1099, statement)")
|
|
31
|
+
ap.add_argument("--endpoint", default=None, help="awvision endpoint for scanned pages")
|
|
32
|
+
ap.add_argument("--model", default=None, help="vision model override")
|
|
33
|
+
ap.add_argument("--indent", type=int, default=2)
|
|
34
|
+
args = ap.parse_args(argv)
|
|
35
|
+
|
|
36
|
+
try:
|
|
37
|
+
result = extract(args.pdf, endpoint=args.endpoint, model=args.model)
|
|
38
|
+
except FileNotFoundError:
|
|
39
|
+
print(f"awtax: no such file: {args.pdf}", file=sys.stderr)
|
|
40
|
+
return 2
|
|
41
|
+
except Exception as exc: # pragma: no cover
|
|
42
|
+
print(f"awtax: failed to read {args.pdf}: {exc}", file=sys.stderr)
|
|
43
|
+
return 1
|
|
44
|
+
|
|
45
|
+
print(json.dumps(result.to_dict(), indent=args.indent))
|
|
46
|
+
# exit 3 (not 0) when anything needs human review -- silence is not a pass
|
|
47
|
+
return 3 if result.to_dict()["needs_review"] else 0
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
if __name__ == "__main__":
|
|
51
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
"""The extraction core: any tax PDF -> a provider-neutral, self-checked schema.
|
|
2
|
+
|
|
3
|
+
Native-text pages are parsed directly (PyMuPDF). Scanned pages route to awvision
|
|
4
|
+
(ocr.py). Every recognized document runs arithmetic cross-checks -- a tax number
|
|
5
|
+
that does not satisfy the identity it is defined by (taxable = AGI - deduction,
|
|
6
|
+
refund = payments - tax) is flagged, not trusted. That self-validation is what let
|
|
7
|
+
this code read a real 2024 return this session and *prove* the figures pair
|
|
8
|
+
correctly instead of asserting a fragile label->value guess.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
|
|
14
|
+
from .ocr import (
|
|
15
|
+
extract_fields_via_vision,
|
|
16
|
+
extract_text_via_local_ocr,
|
|
17
|
+
vision_available,
|
|
18
|
+
)
|
|
19
|
+
from .schema import Document, Extraction, Figure
|
|
20
|
+
|
|
21
|
+
_MONEY = re.compile(r"^-?\d[\d,]*\.?$")
|
|
22
|
+
_SCAN_TEXT_THRESHOLD = 40 # a page with fewer chars than this is treated as a scan
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _num(tok: str) -> float | None:
|
|
26
|
+
try:
|
|
27
|
+
return float(tok.replace(",", "").rstrip("."))
|
|
28
|
+
except ValueError:
|
|
29
|
+
return None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _page_text(page) -> str:
|
|
33
|
+
return page.get_text().replace("\xa0", " ").replace(" ", " ")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
# --- Form 1040 -------------------------------------------------------------
|
|
39
|
+
|
|
40
|
+
_1040_LINES = {
|
|
41
|
+
"total_income": r"total income",
|
|
42
|
+
"adjusted_gross_income": r"adjusted gross income",
|
|
43
|
+
"standard_deduction": r"standard deduction or itemized",
|
|
44
|
+
"taxable_income": r"taxable income",
|
|
45
|
+
"tax": r"Tax \(see instructions\)",
|
|
46
|
+
"total_tax": r"total tax",
|
|
47
|
+
"withholding": r"federal income tax withheld",
|
|
48
|
+
"total_payments": r"total payments",
|
|
49
|
+
"refund": r"amount you overpaid|refunded to you",
|
|
50
|
+
"amount_owed": r"amount you owe",
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _extract_1040(doc_pages, pdf, form: str = "1040") -> Document:
|
|
55
|
+
d = Document(form=form, pages=[p + 1 for p in doc_pages])
|
|
56
|
+
for pi in doc_pages:
|
|
57
|
+
page = pdf[pi]
|
|
58
|
+
words = page.get_text("words") # (x0, y0, x1, y1, text, block, line, wordno)
|
|
59
|
+
# On a real IRS 1040 the line DESCRIPTION and its filled AMOUNT are not in one
|
|
60
|
+
# token row -- the description sits in a y-BAND, and the amount is in the right
|
|
61
|
+
# column. So for each amount, reconstruct its label from every word within a
|
|
62
|
+
# small y-band and to the LEFT of the amount (its own line, whatever the
|
|
63
|
+
# baseline jitter), then match. Amount->label direction + the arithmetic
|
|
64
|
+
# cross-check below guard against a wrong pairing producing a wrong number.
|
|
65
|
+
amounts = [
|
|
66
|
+
(w[0], (w[1] + w[3]) / 2, w[4])
|
|
67
|
+
for w in words
|
|
68
|
+
if _MONEY.match(w[4]) and w[0] > 380 and ("." in w[4] or "," in w[4]) and len(w[4]) > 2
|
|
69
|
+
]
|
|
70
|
+
for ax, ay, atok in amounts:
|
|
71
|
+
band = [
|
|
72
|
+
w[4]
|
|
73
|
+
for w in words
|
|
74
|
+
if abs((w[1] + w[3]) / 2 - ay) <= 8 and w[2] <= ax and not _MONEY.match(w[4])
|
|
75
|
+
]
|
|
76
|
+
label = " ".join(band)
|
|
77
|
+
for key, pat in _1040_LINES.items():
|
|
78
|
+
if key in d.figures:
|
|
79
|
+
continue
|
|
80
|
+
if re.search(pat, label, re.I):
|
|
81
|
+
d.figures[key] = Figure(_num(atok), key, page=pi + 1, source="text")
|
|
82
|
+
break
|
|
83
|
+
if not d.figures:
|
|
84
|
+
d.warnings.append(
|
|
85
|
+
f"{form}: recognized the form but extracted no figures "
|
|
86
|
+
"(label/value pairing did not resolve) -- needs review"
|
|
87
|
+
)
|
|
88
|
+
_crosscheck_1040(d)
|
|
89
|
+
return d
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _crosscheck_1040(d: Document) -> None:
|
|
93
|
+
def g(k):
|
|
94
|
+
f = d.figures.get(k)
|
|
95
|
+
return f.value if f and isinstance(f.value, (int, float)) else None
|
|
96
|
+
|
|
97
|
+
agi, sd, ti = g("adjusted_gross_income"), g("standard_deduction"), g("taxable_income")
|
|
98
|
+
if None not in (agi, sd, ti):
|
|
99
|
+
(d.checks if abs(agi - sd - ti) < 1 else d.warnings).append(
|
|
100
|
+
f"taxable_income = AGI - deduction ({agi:.0f} - {sd:.0f} = {ti:.0f})"
|
|
101
|
+
)
|
|
102
|
+
pay, tax, ref = g("total_payments"), g("total_tax"), g("refund")
|
|
103
|
+
if None not in (pay, tax, ref):
|
|
104
|
+
(d.checks if abs(pay - tax - ref) < 1 else d.warnings).append(
|
|
105
|
+
f"refund = payments - total_tax ({pay:.0f} - {tax:.0f} = {ref:.0f})"
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
# --- W-2 -------------------------------------------------------------------
|
|
110
|
+
|
|
111
|
+
_W2_BOXES = {
|
|
112
|
+
"wages_box1": "box 1 wages, tips, other compensation",
|
|
113
|
+
"fed_withheld_box2": "box 2 federal income tax withheld",
|
|
114
|
+
"ss_wages_box3": "box 3 social security wages",
|
|
115
|
+
"ss_tax_box4": "box 4 social security tax withheld",
|
|
116
|
+
"medicare_wages_box5": "box 5 medicare wages and tips",
|
|
117
|
+
"medicare_tax_box6": "box 6 medicare tax withheld",
|
|
118
|
+
"state_wages_box16": "box 16 state wages",
|
|
119
|
+
"state_tax_box17": "box 17 state income tax",
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _extract_w2(doc_pages, pdf, *, endpoint=None, model=None) -> Document:
|
|
124
|
+
d = Document(form="W-2", pages=[p + 1 for p in doc_pages])
|
|
125
|
+
pi = doc_pages[0]
|
|
126
|
+
text = _page_text(pdf[pi])
|
|
127
|
+
if len(text.strip()) >= _SCAN_TEXT_THRESHOLD:
|
|
128
|
+
d.warnings.append("native-text W-2 parsing not yet implemented; use vision")
|
|
129
|
+
return d
|
|
130
|
+
# scanned -> vision first, then offline OCR, else needs_review (never silent zeros)
|
|
131
|
+
q = "This is a US W-2 wage and tax statement. Extract: " + "; ".join(
|
|
132
|
+
f"{k} ({desc})" for k, desc in _W2_BOXES.items()
|
|
133
|
+
)
|
|
134
|
+
fields: dict = {}
|
|
135
|
+
src = "vision"
|
|
136
|
+
if vision_available():
|
|
137
|
+
try:
|
|
138
|
+
fields = extract_fields_via_vision(pdf.name, pi, q, endpoint=endpoint, model=model)
|
|
139
|
+
except Exception as exc:
|
|
140
|
+
# any vision failure (unavailable, timeout, bad reply) degrades to OCR /
|
|
141
|
+
# needs_review -- a scanned form must never crash the whole extraction
|
|
142
|
+
d.warnings.append(f"vision path failed ({type(exc).__name__}); fell back")
|
|
143
|
+
fields = {}
|
|
144
|
+
if not fields:
|
|
145
|
+
raw = extract_text_via_local_ocr(pdf.name, pi)
|
|
146
|
+
if raw:
|
|
147
|
+
fields = _w2_from_ocr_text(raw)
|
|
148
|
+
src = "ocr"
|
|
149
|
+
if not fields:
|
|
150
|
+
d.warnings.append("scanned W-2 and no vision/OCR backend available -- needs review")
|
|
151
|
+
return d
|
|
152
|
+
for k in _W2_BOXES:
|
|
153
|
+
if k in fields and fields[k] not in (None, ""):
|
|
154
|
+
d.figures[k] = Figure(_num_any(fields[k]), k, page=pi + 1, source=src, confidence=0.8)
|
|
155
|
+
return d
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _num_any(v):
|
|
159
|
+
if isinstance(v, (int, float)):
|
|
160
|
+
return float(v)
|
|
161
|
+
return _num(str(v))
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _w2_from_ocr_text(text: str) -> dict:
|
|
165
|
+
"""Best-effort parse of raw OCR text into the box values (offline fallback)."""
|
|
166
|
+
out: dict[str, float] = {}
|
|
167
|
+
# Fallback is deliberately conservative: label-anchored, not positional guessing.
|
|
168
|
+
for line in text.splitlines():
|
|
169
|
+
low = line.lower()
|
|
170
|
+
for k, desc in _W2_BOXES.items():
|
|
171
|
+
hint = desc.split("(")[0]
|
|
172
|
+
frag = hint.replace("box 1 ", "").replace("box 2 ", "")[:12]
|
|
173
|
+
if frag and frag in low:
|
|
174
|
+
m = re.search(r"(\d[\d,]*\.\d\d)", line)
|
|
175
|
+
if m:
|
|
176
|
+
out[k] = _num(m.group(1))
|
|
177
|
+
return out
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
# --- form recognition + entry point ---------------------------------------
|
|
181
|
+
|
|
182
|
+
def _is_amended(text: str) -> bool:
|
|
183
|
+
# A 1040-X page mentions "Form 1040" in its BODY ("from Form 1040 or 1040-SR"),
|
|
184
|
+
# so a negative-lookahead on the header alone misclassifies it as a primary 1040.
|
|
185
|
+
# Detect the amendment markers directly instead.
|
|
186
|
+
return bool(re.search(r"1040-?X|Amended U\.S|Correct amount|column A\b", text, re.I))
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _classify_pages(pdf) -> dict[str, list[int]]:
|
|
190
|
+
groups: dict[str, list[int]] = {}
|
|
191
|
+
for i, page in enumerate(pdf):
|
|
192
|
+
t = _page_text(page)
|
|
193
|
+
has_1040 = re.search(r"Form\s*1040\b", t) and re.search(r"adjusted gross income", t, re.I)
|
|
194
|
+
if _is_amended(t) and (has_1040 or re.search(r"total tax", t, re.I)):
|
|
195
|
+
groups.setdefault("1040-X", []).append(i)
|
|
196
|
+
elif has_1040:
|
|
197
|
+
groups.setdefault("1040", []).append(i)
|
|
198
|
+
elif re.search(r"W-?2\b.*Wage", t) or len(t.strip()) < _SCAN_TEXT_THRESHOLD:
|
|
199
|
+
groups.setdefault("W-2", []).append(i)
|
|
200
|
+
return groups
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def extract(pdf_path: str, *, endpoint: str | None = None, model: str | None = None) -> Extraction:
|
|
204
|
+
"""Read a tax PDF into a self-checked, provider-neutral schema."""
|
|
205
|
+
import fitz # PyMuPDF
|
|
206
|
+
|
|
207
|
+
pdf = fitz.open(pdf_path)
|
|
208
|
+
result = Extraction(source_path=pdf_path, page_count=len(pdf))
|
|
209
|
+
groups = _classify_pages(pdf)
|
|
210
|
+
if "1040" in groups:
|
|
211
|
+
result.documents.append(_extract_1040(groups["1040"], pdf))
|
|
212
|
+
if "1040-X" in groups:
|
|
213
|
+
result.documents.append(_extract_1040(groups["1040-X"], pdf, form="1040-X"))
|
|
214
|
+
if "W-2" in groups:
|
|
215
|
+
result.documents.append(
|
|
216
|
+
_extract_w2(groups["W-2"], pdf, endpoint=endpoint, model=model)
|
|
217
|
+
)
|
|
218
|
+
return result
|
awtax-0.1.0/awtax/ocr.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""Reading pages that have no text layer (scans, photos of a mailed form).
|
|
2
|
+
|
|
3
|
+
awtax does NOT bundle an OCR engine. The aw* stack already has a vision brick --
|
|
4
|
+
`awvision` -- and a vision model extracts form fields *structurally* (it can answer
|
|
5
|
+
"what is in box 1?"), which is strictly better than raw OCR text you then have to
|
|
6
|
+
re-parse. So the primary path is awvision; a local OCR engine (tesseract) is only an
|
|
7
|
+
offline fallback for a stranger who has neither a vision endpoint nor a network.
|
|
8
|
+
|
|
9
|
+
Both paths are optional. If neither is available, the caller gets a clear
|
|
10
|
+
`needs_review` signal rather than a silent zero -- the exact failure mode
|
|
11
|
+
(TaxDesk's parse_w2_pdf returning all-zeros on a scan) that awtax exists to fix.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
import re
|
|
18
|
+
import shutil
|
|
19
|
+
import subprocess
|
|
20
|
+
import tempfile
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class VisionUnavailableError(RuntimeError):
|
|
25
|
+
pass
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _render_page_png(pdf_path: str, page_index: int, dpi: int = 300) -> str:
|
|
29
|
+
"""Render one page to a temp PNG, return its path. Requires PyMuPDF."""
|
|
30
|
+
import fitz # PyMuPDF
|
|
31
|
+
|
|
32
|
+
doc = fitz.open(pdf_path)
|
|
33
|
+
pix = doc[page_index].get_pixmap(dpi=dpi)
|
|
34
|
+
out = os.path.join(tempfile.gettempdir(), f"awtax_p{page_index}.png")
|
|
35
|
+
pix.save(out)
|
|
36
|
+
return out
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _coerce_json(text: str) -> dict[str, Any]:
|
|
40
|
+
"""Pull the first JSON object out of a model reply, tolerating prose around it."""
|
|
41
|
+
if isinstance(text, dict):
|
|
42
|
+
return text
|
|
43
|
+
m = re.search(r"\{.*\}", str(text), re.S)
|
|
44
|
+
if not m:
|
|
45
|
+
return {}
|
|
46
|
+
try:
|
|
47
|
+
return json.loads(m.group(0))
|
|
48
|
+
except Exception:
|
|
49
|
+
return {}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def vision_available() -> bool:
|
|
53
|
+
try:
|
|
54
|
+
import awvision # noqa: F401
|
|
55
|
+
return True
|
|
56
|
+
except Exception:
|
|
57
|
+
return False
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def local_ocr_available() -> bool:
|
|
61
|
+
return shutil.which("tesseract") is not None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def extract_fields_via_vision(
|
|
65
|
+
pdf_path: str,
|
|
66
|
+
page_index: int,
|
|
67
|
+
question: str,
|
|
68
|
+
*,
|
|
69
|
+
endpoint: str | None = None,
|
|
70
|
+
model: str | None = None,
|
|
71
|
+
) -> dict[str, Any]:
|
|
72
|
+
"""Ask the awvision plane to read a scanned page; return a JSON object of fields.
|
|
73
|
+
|
|
74
|
+
Raises VisionUnavailableError if awvision is not installed / no endpoint resolves,
|
|
75
|
+
so the caller can fall back rather than treat an outage as an empty form.
|
|
76
|
+
"""
|
|
77
|
+
try:
|
|
78
|
+
from awvision import ask_vision # type: ignore
|
|
79
|
+
except Exception as exc: # pragma: no cover - import guard
|
|
80
|
+
raise VisionUnavailableError(f"awvision not available: {exc}") from exc
|
|
81
|
+
|
|
82
|
+
png = _render_page_png(pdf_path, page_index)
|
|
83
|
+
prompt = (
|
|
84
|
+
f"{question}\n\n"
|
|
85
|
+
"Return ONLY a compact JSON object mapping each field name to its value. "
|
|
86
|
+
"Use numbers for money (no $ or commas). If a field is absent, omit it."
|
|
87
|
+
)
|
|
88
|
+
answer = ask_vision(png, prompt, endpoint=endpoint, model=model)
|
|
89
|
+
return _coerce_json(answer)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def extract_text_via_local_ocr(pdf_path: str, page_index: int) -> str:
|
|
93
|
+
"""Offline fallback: render the page and run tesseract, returning raw text.
|
|
94
|
+
|
|
95
|
+
Returns '' if tesseract is not installed -- never raises, because the caller
|
|
96
|
+
treats empty text as needs_review, not as a valid empty form.
|
|
97
|
+
"""
|
|
98
|
+
if not local_ocr_available():
|
|
99
|
+
return ""
|
|
100
|
+
png = _render_page_png(pdf_path, page_index)
|
|
101
|
+
try:
|
|
102
|
+
out = subprocess.run(
|
|
103
|
+
["tesseract", png, "stdout", "--psm", "6"],
|
|
104
|
+
capture_output=True,
|
|
105
|
+
text=True,
|
|
106
|
+
timeout=120,
|
|
107
|
+
)
|
|
108
|
+
return out.stdout or ""
|
|
109
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
110
|
+
return ""
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Provider-neutral tax-document schema.
|
|
2
|
+
|
|
3
|
+
Every extracted figure carries where it came from (page) and how confident we are,
|
|
4
|
+
because a tax number with no provenance is a number nobody can check. This is the
|
|
5
|
+
whole point of awtax: not "trust the vendor's sealed file", but "here is every value,
|
|
6
|
+
and the page it sits on".
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from dataclasses import dataclass, field, asdict
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class Figure:
|
|
16
|
+
"""One extracted monetary/identifier value with provenance."""
|
|
17
|
+
value: float | str | None
|
|
18
|
+
label: str
|
|
19
|
+
page: int | None = None # 1-indexed source page
|
|
20
|
+
source: str = "text" # 'text' (native PDF text) | 'vision' | 'ocr'
|
|
21
|
+
confidence: float = 1.0 # 0..1
|
|
22
|
+
|
|
23
|
+
def to_dict(self) -> dict[str, Any]:
|
|
24
|
+
return asdict(self)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class Document:
|
|
29
|
+
"""A single recognized tax document within a PDF (a 1040, a W-2, a 1099...)."""
|
|
30
|
+
form: str # e.g. '1040', '1040-X', 'W-2', '1099-INT'
|
|
31
|
+
tax_year: int | None = None
|
|
32
|
+
figures: dict[str, Figure] = field(default_factory=dict)
|
|
33
|
+
checks: list[str] = field(default_factory=list) # arithmetic cross-checks that PASSED
|
|
34
|
+
warnings: list[str] = field(default_factory=list) # cross-checks that FAILED / needs_review
|
|
35
|
+
pages: list[int] = field(default_factory=list)
|
|
36
|
+
|
|
37
|
+
@property
|
|
38
|
+
def needs_review(self) -> bool:
|
|
39
|
+
# A recognized form that yielded NO figures is not "clean" -- it is a failed
|
|
40
|
+
# read. Reporting it clean is the silent-zero failure awtax exists to prevent.
|
|
41
|
+
return (
|
|
42
|
+
not self.figures
|
|
43
|
+
or bool(self.warnings)
|
|
44
|
+
or any(f.confidence < 0.75 for f in self.figures.values())
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
def to_dict(self) -> dict[str, Any]:
|
|
48
|
+
return {
|
|
49
|
+
"form": self.form,
|
|
50
|
+
"tax_year": self.tax_year,
|
|
51
|
+
"pages": self.pages,
|
|
52
|
+
"figures": {k: v.to_dict() for k, v in self.figures.items()},
|
|
53
|
+
"checks": self.checks,
|
|
54
|
+
"warnings": self.warnings,
|
|
55
|
+
"needs_review": self.needs_review,
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass
|
|
60
|
+
class Extraction:
|
|
61
|
+
"""The full result of reading one tax PDF."""
|
|
62
|
+
source_path: str
|
|
63
|
+
page_count: int
|
|
64
|
+
documents: list[Document] = field(default_factory=list)
|
|
65
|
+
|
|
66
|
+
def to_dict(self) -> dict[str, Any]:
|
|
67
|
+
return {
|
|
68
|
+
"source_path": self.source_path,
|
|
69
|
+
"page_count": self.page_count,
|
|
70
|
+
"documents": [d.to_dict() for d in self.documents],
|
|
71
|
+
"needs_review": any(d.needs_review for d in self.documents),
|
|
72
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: awtax
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Turn any tax PDF -- returns, W-2, 1099, statements, even scans -- into structured data you can check.
|
|
5
|
+
Author: Aitherium
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Aitherium/awtax
|
|
8
|
+
Keywords: tax,pdf,extraction,ocr,1040,w-2,aither-world
|
|
9
|
+
Requires-Python: >=3.10
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: pymupdf>=1.24
|
|
13
|
+
Provides-Extra: vision
|
|
14
|
+
Requires-Dist: awvision>=0.1; extra == "vision"
|
|
15
|
+
Provides-Extra: ocr
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# awtax
|
|
19
|
+
|
|
20
|
+
**Turn any tax PDF — returns, W-2, 1099, statements, even scans — into structured data you can check.**
|
|
21
|
+
|
|
22
|
+
Your own tax data gets locked inside one vendor's encrypted format, and a filed return or a
|
|
23
|
+
mailed W-2 is a PDF nobody's code can read — half of them are scans with no text layer at all.
|
|
24
|
+
Getting your own numbers back out means re-typing them or re-buying the app that sealed them.
|
|
25
|
+
|
|
26
|
+
`awtax` reads the document. It does **not** give tax advice — it hands you every figure, the page
|
|
27
|
+
it came from, and whether the arithmetic checks out.
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
git clone https://github.com/Aitherium/awtax && cd awtax && pip install -e .
|
|
31
|
+
awtax path/to/return.pdf # -> structured JSON on stdout
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
> Not on PyPI yet, so `pip install awtax` does **not** work — that name resolves
|
|
35
|
+
> to nothing today. Install from the clone until a release exists.
|
|
36
|
+
|
|
37
|
+
## What you get
|
|
38
|
+
|
|
39
|
+
- **Provider-neutral schema** — every figure carries its `page`, its `source` (`text` / `vision` /
|
|
40
|
+
`ocr`), and a `confidence`. A tax number with no provenance is a number nobody can check.
|
|
41
|
+
- **Arithmetic self-checks** — `taxable = AGI − deduction`, `refund = payments − tax`. A figure that
|
|
42
|
+
fails the identity it is defined by is **flagged**, not trusted. The CLI exits `3` when anything
|
|
43
|
+
needs review — silence is not a pass.
|
|
44
|
+
- **Scans handled** — a page with no text layer routes to [`awvision`](../awvision) (a vision model
|
|
45
|
+
reads the form fields *structurally*, far better than raw OCR), with a local `tesseract` fallback
|
|
46
|
+
for fully-offline use. If neither is available you get an explicit `needs_review` — **never a
|
|
47
|
+
silent zero.** (That silent-zero-on-a-scan failure is exactly what this fixes.)
|
|
48
|
+
|
|
49
|
+
## Scan backends (optional)
|
|
50
|
+
|
|
51
|
+
| backend | how | when |
|
|
52
|
+
|---|---|---|
|
|
53
|
+
| **awvision** (preferred) | `pip install -e '.[vision]'` from the clone, pass `--endpoint` | a vision model extracts fields as JSON |
|
|
54
|
+
| **tesseract** (offline fallback) | install the `tesseract` system binary | no network / no vision endpoint |
|
|
55
|
+
| neither | — | pages return `needs_review` with a reason |
|
|
56
|
+
|
|
57
|
+
## Where awtax stops, and the premium packs begin
|
|
58
|
+
|
|
59
|
+
awtax is the open-source **extraction core**. Preparation, deduction discovery, worksheets, ledgers
|
|
60
|
+
and CPA-ready output are the premium **TaxDesk** agent / skill / tool packs that compose on top via
|
|
61
|
+
`awpack` / `awskills`. awtax reads; the packs advise.
|
|
62
|
+
|
|
63
|
+
## Status
|
|
64
|
+
|
|
65
|
+
`0.1.0` — reads native-text 1040 pages and scanned W-2s, self-validates, degrades gracefully.
|
|
66
|
+
Known next work: 1040-vs-1040-X disambiguation on multi-form packets, richer 1099 coverage,
|
|
67
|
+
and native-text W-2 parsing. MIT licensed.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
awtax/__init__.py
|
|
5
|
+
awtax/cli.py
|
|
6
|
+
awtax/extract.py
|
|
7
|
+
awtax/ocr.py
|
|
8
|
+
awtax/schema.py
|
|
9
|
+
awtax.egg-info/PKG-INFO
|
|
10
|
+
awtax.egg-info/SOURCES.txt
|
|
11
|
+
awtax.egg-info/dependency_links.txt
|
|
12
|
+
awtax.egg-info/entry_points.txt
|
|
13
|
+
awtax.egg-info/requires.txt
|
|
14
|
+
awtax.egg-info/top_level.txt
|
|
15
|
+
tests/test_extract.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
awtax
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "awtax"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Turn any tax PDF -- returns, W-2, 1099, statements, even scans -- into structured data you can check."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [{ name = "Aitherium" }]
|
|
13
|
+
keywords = ["tax", "pdf", "extraction", "ocr", "1040", "w-2", "aither-world"]
|
|
14
|
+
dependencies = [
|
|
15
|
+
"pymupdf>=1.24",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
[project.optional-dependencies]
|
|
19
|
+
# Scanned pages read best through the aw* vision brick; tesseract is the offline fallback.
|
|
20
|
+
vision = ["awvision>=0.1"]
|
|
21
|
+
ocr = [] # tesseract is a system binary, not a pip dep -- documented in README
|
|
22
|
+
|
|
23
|
+
[project.scripts]
|
|
24
|
+
awtax = "awtax.cli:main"
|
|
25
|
+
|
|
26
|
+
[project.urls]
|
|
27
|
+
Homepage = "https://github.com/Aitherium/awtax"
|
|
28
|
+
|
|
29
|
+
[tool.setuptools.packages.find]
|
|
30
|
+
where = ["."]
|
|
31
|
+
include = ["awtax*"]
|
awtax-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""awtax tests. Build a synthetic native-text 1040 page so the core is provable
|
|
2
|
+
without shipping anyone's real return, and assert the arithmetic self-check both
|
|
3
|
+
PASSES on consistent numbers and FLAGS inconsistent ones (the property that makes
|
|
4
|
+
the extraction trustworthy rather than a fragile label->value guess).
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
import tempfile
|
|
10
|
+
|
|
11
|
+
import pytest
|
|
12
|
+
|
|
13
|
+
fitz = pytest.importorskip("fitz")
|
|
14
|
+
|
|
15
|
+
from awtax import extract # noqa: E402
|
|
16
|
+
from awtax.schema import Document # noqa: E402
|
|
17
|
+
from awtax.extract import _crosscheck_1040 # noqa: E402
|
|
18
|
+
from awtax.schema import Figure # noqa: E402
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _make_1040(agi, deduction, taxable, tmp):
|
|
22
|
+
"""Render a minimal 1040-shaped page: label on the left, amount in the right column."""
|
|
23
|
+
doc = fitz.open()
|
|
24
|
+
page = doc.new_page(width=612, height=792)
|
|
25
|
+
rows = [
|
|
26
|
+
(400, "11 This is your adjusted gross income", f"{agi:,.0f}."),
|
|
27
|
+
(430, "12 Standard deduction or itemized deductions", f"{deduction:,.0f}."),
|
|
28
|
+
(460, "15 This is your taxable income", f"{taxable:,.0f}."),
|
|
29
|
+
]
|
|
30
|
+
page.insert_text((36, 60), "Form 1040 (2024)")
|
|
31
|
+
page.insert_text((36, 80), "adjusted gross income") # classifier anchor
|
|
32
|
+
for y, label, amt in rows:
|
|
33
|
+
page.insert_text((36, y), label, fontsize=9)
|
|
34
|
+
page.insert_text((500, y), amt, fontsize=9) # right column (x>380)
|
|
35
|
+
path = os.path.join(tmp, "synthetic_1040.pdf")
|
|
36
|
+
doc.save(path)
|
|
37
|
+
return path
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def test_1040_extraction_and_passing_crosscheck(tmp_path):
|
|
41
|
+
path = _make_1040(171890, 21900, 149990, str(tmp_path))
|
|
42
|
+
result = extract(path)
|
|
43
|
+
forms = {d.form: d for d in result.documents}
|
|
44
|
+
assert "1040" in forms, "1040 page should be recognized"
|
|
45
|
+
d = forms["1040"]
|
|
46
|
+
assert d.figures["adjusted_gross_income"].value == 171890
|
|
47
|
+
assert d.figures["taxable_income"].value == 149990
|
|
48
|
+
# 171890 - 21900 == 149990 -> the identity holds -> recorded as a passed check
|
|
49
|
+
assert any("taxable_income = AGI - deduction" in c for c in d.checks)
|
|
50
|
+
assert not d.warnings
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def test_crosscheck_flags_inconsistent_numbers():
|
|
54
|
+
d = Document(form="1040")
|
|
55
|
+
d.figures["adjusted_gross_income"] = Figure(100000, "agi")
|
|
56
|
+
d.figures["standard_deduction"] = Figure(20000, "sd")
|
|
57
|
+
d.figures["taxable_income"] = Figure(75000, "ti") # WRONG: should be 80000
|
|
58
|
+
_crosscheck_1040(d)
|
|
59
|
+
assert d.warnings, "an inconsistent taxable-income must be flagged, not trusted"
|
|
60
|
+
assert d.needs_review
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _make_1040x(tmp):
|
|
64
|
+
"""A Form 1040-X page: it mentions 'Form 1040' in its body, which is exactly why
|
|
65
|
+
a naive header lookahead misclassifies it as the primary return."""
|
|
66
|
+
doc = fitz.open()
|
|
67
|
+
page = doc.new_page(width=612, height=792)
|
|
68
|
+
page.insert_text((36, 60), "Form 1040-X Amended U.S. Individual Income Tax Return")
|
|
69
|
+
page.insert_text((36, 80), "adjusted gross income") # 1040 anchor (bait)
|
|
70
|
+
page.insert_text((36, 100), "amounts from Form 1040 or 1040-SR, column A Correct amount")
|
|
71
|
+
page.insert_text((36, 130), "11 Total tax", fontsize=9)
|
|
72
|
+
page.insert_text((500, 130), "25,347.", fontsize=9)
|
|
73
|
+
path = os.path.join(tmp, "synthetic_1040x.pdf")
|
|
74
|
+
doc.save(path)
|
|
75
|
+
return path
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _make_1040_offset_baseline(agi, deduction, taxable, tmp):
|
|
79
|
+
"""A 1040 page where the amount sits on a DIFFERENT text baseline than its label --
|
|
80
|
+
which is how a real IRS form renders (right-column values are not row-aligned to the
|
|
81
|
+
left labels). This is the case the naive same-row pairing missed on the real return."""
|
|
82
|
+
doc = fitz.open()
|
|
83
|
+
page = doc.new_page(width=612, height=792)
|
|
84
|
+
page.insert_text((36, 60), "Form 1040 (2024)")
|
|
85
|
+
page.insert_text((36, 80), "adjusted gross income")
|
|
86
|
+
rows = [
|
|
87
|
+
(400, "11 This is your adjusted gross income", agi),
|
|
88
|
+
(430, "12 Standard deduction or itemized deductions", deduction),
|
|
89
|
+
(460, "15 This is your taxable income", taxable),
|
|
90
|
+
]
|
|
91
|
+
for y, label, amt in rows:
|
|
92
|
+
page.insert_text((36, y), label, fontsize=9)
|
|
93
|
+
page.insert_text((505, y + 3), f"{amt:,.0f}.", fontsize=9) # +3px baseline offset
|
|
94
|
+
path = os.path.join(tmp, "synthetic_1040_offset.pdf")
|
|
95
|
+
doc.save(path)
|
|
96
|
+
return path
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def test_1040_reads_offset_baseline_and_crosschecks(tmp_path):
|
|
100
|
+
# regression for the real return: labels and values on different baselines must
|
|
101
|
+
# still pair, and the arithmetic identity must hold -> proves correct pairing.
|
|
102
|
+
path = _make_1040_offset_baseline(171890, 21900, 149990, str(tmp_path))
|
|
103
|
+
d = {x.form: x for x in extract(path).documents}["1040"]
|
|
104
|
+
assert d.figures["adjusted_gross_income"].value == 171890
|
|
105
|
+
assert d.figures["standard_deduction"].value == 21900
|
|
106
|
+
assert d.figures["taxable_income"].value == 149990
|
|
107
|
+
assert any("AGI - deduction" in c for c in d.checks)
|
|
108
|
+
assert not d.needs_review
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def test_1040x_is_not_classified_as_primary_1040(tmp_path):
|
|
112
|
+
# regression: on a real 61-page packet the amended page was read AS the 1040.
|
|
113
|
+
path = _make_1040x(str(tmp_path))
|
|
114
|
+
result = extract(path)
|
|
115
|
+
forms = {d.form for d in result.documents}
|
|
116
|
+
assert "1040-X" in forms, "the amended page must be recognized as 1040-X"
|
|
117
|
+
assert "1040" not in forms, "a 1040-X page must NOT be misread as the primary 1040"
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def test_empty_recognized_form_needs_review():
|
|
121
|
+
# a recognized form with zero figures must NOT report clean (silent-zero guard)
|
|
122
|
+
d = Document(form="1040")
|
|
123
|
+
assert d.needs_review is True
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def test_needs_review_exit_signal(tmp_path):
|
|
127
|
+
# a doc with a failed check must surface needs_review True
|
|
128
|
+
path = _make_1040(100000, 20000, 75000, str(tmp_path)) # inconsistent on purpose
|
|
129
|
+
result = extract(path)
|
|
130
|
+
assert result.to_dict()["needs_review"] is True
|