hwprint 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.
- hwprint-0.1.0/LICENSE +16 -0
- hwprint-0.1.0/PKG-INFO +160 -0
- hwprint-0.1.0/README.md +136 -0
- hwprint-0.1.0/pyproject.toml +30 -0
- hwprint-0.1.0/setup.cfg +4 -0
- hwprint-0.1.0/src/hwprint/__init__.py +5 -0
- hwprint-0.1.0/src/hwprint/cli.py +36 -0
- hwprint-0.1.0/src/hwprint/model.py +176 -0
- hwprint-0.1.0/src/hwprint.egg-info/PKG-INFO +160 -0
- hwprint-0.1.0/src/hwprint.egg-info/SOURCES.txt +13 -0
- hwprint-0.1.0/src/hwprint.egg-info/dependency_links.txt +1 -0
- hwprint-0.1.0/src/hwprint.egg-info/entry_points.txt +2 -0
- hwprint-0.1.0/src/hwprint.egg-info/requires.txt +6 -0
- hwprint-0.1.0/src/hwprint.egg-info/top_level.txt +1 -0
- hwprint-0.1.0/tests/test_basic.py +33 -0
hwprint-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Stefan Larson
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
|
|
6
|
+
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
|
|
7
|
+
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
|
|
8
|
+
persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
9
|
+
|
|
10
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
|
|
11
|
+
Software.
|
|
12
|
+
|
|
13
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
|
|
14
|
+
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
|
15
|
+
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
|
16
|
+
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
hwprint-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: hwprint
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Classify word crops on document pages as handwritten or printed
|
|
5
|
+
Author: Stefan Larson
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/gxlarson/hwprint
|
|
8
|
+
Project-URL: Repository, https://github.com/gxlarson/hwprint
|
|
9
|
+
Project-URL: Issues, https://github.com/gxlarson/hwprint/issues
|
|
10
|
+
Project-URL: Model card, https://huggingface.co/stefan-hf/hwprint
|
|
11
|
+
Keywords: handwriting,document-ai,ocr,de-identification,textract
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering :: Image Recognition
|
|
14
|
+
Requires-Python: >=3.9
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Requires-Dist: torch>=2.0
|
|
18
|
+
Requires-Dist: torchvision>=0.15
|
|
19
|
+
Requires-Dist: numpy
|
|
20
|
+
Requires-Dist: pillow
|
|
21
|
+
Requires-Dist: safetensors
|
|
22
|
+
Requires-Dist: huggingface_hub>=0.20
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# hwprint
|
|
26
|
+
|
|
27
|
+
Classifies a word on a document page as **handwritten** or **printed**, given the page image and the word's
|
|
28
|
+
bounding box. It was built for de-identification pipelines that need to find handwriting without depending on a
|
|
29
|
+
commercial OCR service's text-type flag.
|
|
30
|
+
|
|
31
|
+
## Install and use
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pip install hwprint
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Code: [github.com/gxlarson/hwprint](https://github.com/gxlarson/hwprint) · Weights and model card:
|
|
38
|
+
[huggingface.co/stefan-hf/hwprint](https://huggingface.co/stefan-hf/hwprint)
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
from PIL import Image
|
|
42
|
+
from hwprint import HWPrint
|
|
43
|
+
|
|
44
|
+
clf = HWPrint.from_pretrained("stefan-hf/hwprint") # downloads ~130 MB of weights
|
|
45
|
+
page = Image.open("page.jpg")
|
|
46
|
+
boxes = [(412, 980, 655, 1032), (120, 140, 388, 170)] # x0, y0, x1, y1 in page pixels
|
|
47
|
+
clf.predict(page, boxes) # array of P(handwritten), e.g. [0.97, 0.02]
|
|
48
|
+
clf.classify(page, boxes) # ['handwritten', 'printed']
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Word boxes can come from any OCR or text detector. For AWS Textract output there is a helper and a CLI:
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
from hwprint import textract_words
|
|
55
|
+
words = [w for w in textract_words("page.json", page.size) if w["supported"]]
|
|
56
|
+
p = clf.predict(page, [w["box"] for w in words])
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
hwprint page.jpg --textract page.json --csv out.csv
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Pass the page at its original resolution; crops are taken and resized internally. Throughput is about 2,000
|
|
64
|
+
words/s on a GPU and about 30 words/s on CPU.
|
|
65
|
+
|
|
66
|
+
## Example: page image + OCR → labels
|
|
67
|
+
|
|
68
|
+
The `examples/` folder has a complete run on one RVL-CDIP test page (a 1984 billboard inspection form):
|
|
69
|
+
|
|
70
|
+
| file | what it is |
|
|
71
|
+
|---|---|
|
|
72
|
+
| `page.jpg` | input: the scanned page |
|
|
73
|
+
| `page.textract.json` | input: the AWS Textract response for the page (only the word boxes are used) |
|
|
74
|
+
| `run_example.py` | the script below, end to end |
|
|
75
|
+
| `output.csv` | output: one row per word with its box, P(handwritten) and label |
|
|
76
|
+
| `overlay.png` | output: the page with handwritten words boxed in red and printed words in blue |
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
python examples/run_example.py examples/page.jpg examples/page.textract.json --out examples/
|
|
80
|
+
# 110 words: 33 handwritten, 77 printed, 0 skipped
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+

|
|
84
|
+
|
|
85
|
+
First rows of `output.csv`:
|
|
86
|
+
|
|
87
|
+
| text | x0 | y0 | x1 | y1 | p_handwritten | label |
|
|
88
|
+
|---|---|---|---|---|---|---|
|
|
89
|
+
| FIELDMAN | 475 | 17 | 541 | 31 | 0.021 | printed |
|
|
90
|
+
| Jerry | 543 | 7 | 614 | 49 | 0.964 | handwritten |
|
|
91
|
+
| Cathey | 621 | 7 | 694 | 51 | 0.957 | handwritten |
|
|
92
|
+
| DATE | 506 | 48 | 541 | 61 | 0.021 | printed |
|
|
93
|
+
| 7/10/84 | 603 | 36 | 676 | 70 | 0.961 | handwritten |
|
|
94
|
+
| *INSPECTION | 411 | 77 | 501 | 92 | 0.024 | printed |
|
|
95
|
+
| CONTRACT | 85 | 108 | 154 | 121 | 0.024 | printed |
|
|
96
|
+
| LANO | 173 | 96 | 238 | 123 | 0.960 | handwritten |
|
|
97
|
+
|
|
98
|
+
The `text` column is Textract's transcription; hwprint only decides handwritten vs printed. On this page it agrees
|
|
99
|
+
with Textract's own `TextType` on all 110 words.
|
|
100
|
+
|
|
101
|
+
## Model
|
|
102
|
+
|
|
103
|
+
Two ResNet-18 ensembles (3 seeds each), with probabilities averaged:
|
|
104
|
+
|
|
105
|
+
| input | crop | canvas |
|
|
106
|
+
|---|---|---|
|
|
107
|
+
| word | box + 15% of its height on each side | 64 × 256 |
|
|
108
|
+
| context | box + 1 height above and below, 3 heights left and right; extra channel marks the box | 96 × 288 |
|
|
109
|
+
|
|
110
|
+
Words wider than 8× their height (URLs, emails) are scored on their first 8 heights only.
|
|
111
|
+
|
|
112
|
+
## Label definition
|
|
113
|
+
|
|
114
|
+
- **Handwritten**: made with a pen. All signatures count, including autopen.
|
|
115
|
+
- **Printed**: machine-produced in any font, including script and handwriting-style fonts, stamps, and display type.
|
|
116
|
+
|
|
117
|
+
## Training data
|
|
118
|
+
|
|
119
|
+
- **RVL-CDIP** ([Harley et al., 2015](https://adamharley.com/rvl-cdip/)), train split only: about 17,000 word crops
|
|
120
|
+
from scanned 1980s–1990s tobacco-industry documents (IIT-CDIP). Labels come from AWS Textract's word-level
|
|
121
|
+
`TextType`, so they are noisy. Pages with near-duplicates across RVL-CDIP splits were excluded from validation and test.
|
|
122
|
+
- About 13,000 synthetic printed words: real RVL-CDIP text rendered in Google Fonts (OFL), as plain lines, table
|
|
123
|
+
cells, map labels and rubber stamps, then degraded to look like old scans or modern photos. Handwriting-style
|
|
124
|
+
fonts were left out because they imitate print-style handwriting too closely.
|
|
125
|
+
- Augmentation: grey or tinted paper, low contrast, uneven lighting, blur, noise, reverse video.
|
|
126
|
+
|
|
127
|
+
## Evaluation
|
|
128
|
+
|
|
129
|
+
All numbers use human labels; words a person could not call either way were excluded.
|
|
130
|
+
|
|
131
|
+
| test set | hwprint | Textract |
|
|
132
|
+
|---|---|---|
|
|
133
|
+
| RVL-CDIP test, 681 words (half Textract-handwritten, half Textract-printed) | **97.9%** | 94.9% |
|
|
134
|
+
| ↳ handwritten words found, of 363 | **352** | 335 |
|
|
135
|
+
| RVL-CDIP-N, 200 random Textract-handwritten words | 194 / 200 | 198 / 200 |
|
|
136
|
+
| RVL-CDIP-N, 200 random Textract-printed words | 200 / 200 | 200 / 200 |
|
|
137
|
+
| RVL-CDIP-N, 134 words where Textract and an earlier model disagreed | 86 | 113 |
|
|
138
|
+
|
|
139
|
+
RVL-CDIP-O (2,915 out-of-distribution pages, 793k words): hwprint calls 1,171 words handwritten. In a random sample of
|
|
140
|
+
those calls, 35% (95% CI 27–44%) were handwritten, and 38% of those were words Textract labelled printed. Textract
|
|
141
|
+
calls 342 words handwritten, and nearly all of them are.
|
|
142
|
+
|
|
143
|
+
## Limitations
|
|
144
|
+
|
|
145
|
+
- **Latin script only.** Training data is almost entirely English, and synthetic fonts were limited to ones with Latin
|
|
146
|
+
glyphs. It is untested on Arabic, Hebrew, Chinese, Japanese, Korean, Indic (Devanagari, Bengali, Tamil, ...), Thai,
|
|
147
|
+
Cyrillic, Greek and other scripts. Cursive-looking printed scripts may be called handwritten: in out-of-distribution
|
|
148
|
+
checks, printed Arabic words were among its false alarms. Validate on your own documents before relying on it.
|
|
149
|
+
- Best on grayscale scans like RVL-CDIP. On modern, colourful or photographed documents it finds handwriting
|
|
150
|
+
Textract misses but also raises false alarms on logos, text over photos, maps, chart labels, bridge diagrams
|
|
151
|
+
and display fonts.
|
|
152
|
+
- Upright text only. `textract_words` marks rotated and vertical words as unsupported.
|
|
153
|
+
- Very short words (1–2 characters) and isolated digits are the least reliable.
|
|
154
|
+
- Labels come from a commercial OCR system, so the model has absorbed some of its biases.
|
|
155
|
+
- For de-identification where missing handwriting is the costly error, consider flagging a word if either this
|
|
156
|
+
model or your OCR engine calls it handwritten.
|
|
157
|
+
|
|
158
|
+
## License
|
|
159
|
+
|
|
160
|
+
MIT, for code and weights. The training images come from RVL-CDIP; check its terms for your use.
|
hwprint-0.1.0/README.md
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
# hwprint
|
|
2
|
+
|
|
3
|
+
Classifies a word on a document page as **handwritten** or **printed**, given the page image and the word's
|
|
4
|
+
bounding box. It was built for de-identification pipelines that need to find handwriting without depending on a
|
|
5
|
+
commercial OCR service's text-type flag.
|
|
6
|
+
|
|
7
|
+
## Install and use
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install hwprint
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Code: [github.com/gxlarson/hwprint](https://github.com/gxlarson/hwprint) · Weights and model card:
|
|
14
|
+
[huggingface.co/stefan-hf/hwprint](https://huggingface.co/stefan-hf/hwprint)
|
|
15
|
+
|
|
16
|
+
```python
|
|
17
|
+
from PIL import Image
|
|
18
|
+
from hwprint import HWPrint
|
|
19
|
+
|
|
20
|
+
clf = HWPrint.from_pretrained("stefan-hf/hwprint") # downloads ~130 MB of weights
|
|
21
|
+
page = Image.open("page.jpg")
|
|
22
|
+
boxes = [(412, 980, 655, 1032), (120, 140, 388, 170)] # x0, y0, x1, y1 in page pixels
|
|
23
|
+
clf.predict(page, boxes) # array of P(handwritten), e.g. [0.97, 0.02]
|
|
24
|
+
clf.classify(page, boxes) # ['handwritten', 'printed']
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Word boxes can come from any OCR or text detector. For AWS Textract output there is a helper and a CLI:
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
from hwprint import textract_words
|
|
31
|
+
words = [w for w in textract_words("page.json", page.size) if w["supported"]]
|
|
32
|
+
p = clf.predict(page, [w["box"] for w in words])
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
hwprint page.jpg --textract page.json --csv out.csv
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Pass the page at its original resolution; crops are taken and resized internally. Throughput is about 2,000
|
|
40
|
+
words/s on a GPU and about 30 words/s on CPU.
|
|
41
|
+
|
|
42
|
+
## Example: page image + OCR → labels
|
|
43
|
+
|
|
44
|
+
The `examples/` folder has a complete run on one RVL-CDIP test page (a 1984 billboard inspection form):
|
|
45
|
+
|
|
46
|
+
| file | what it is |
|
|
47
|
+
|---|---|
|
|
48
|
+
| `page.jpg` | input: the scanned page |
|
|
49
|
+
| `page.textract.json` | input: the AWS Textract response for the page (only the word boxes are used) |
|
|
50
|
+
| `run_example.py` | the script below, end to end |
|
|
51
|
+
| `output.csv` | output: one row per word with its box, P(handwritten) and label |
|
|
52
|
+
| `overlay.png` | output: the page with handwritten words boxed in red and printed words in blue |
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
python examples/run_example.py examples/page.jpg examples/page.textract.json --out examples/
|
|
56
|
+
# 110 words: 33 handwritten, 77 printed, 0 skipped
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+

|
|
60
|
+
|
|
61
|
+
First rows of `output.csv`:
|
|
62
|
+
|
|
63
|
+
| text | x0 | y0 | x1 | y1 | p_handwritten | label |
|
|
64
|
+
|---|---|---|---|---|---|---|
|
|
65
|
+
| FIELDMAN | 475 | 17 | 541 | 31 | 0.021 | printed |
|
|
66
|
+
| Jerry | 543 | 7 | 614 | 49 | 0.964 | handwritten |
|
|
67
|
+
| Cathey | 621 | 7 | 694 | 51 | 0.957 | handwritten |
|
|
68
|
+
| DATE | 506 | 48 | 541 | 61 | 0.021 | printed |
|
|
69
|
+
| 7/10/84 | 603 | 36 | 676 | 70 | 0.961 | handwritten |
|
|
70
|
+
| *INSPECTION | 411 | 77 | 501 | 92 | 0.024 | printed |
|
|
71
|
+
| CONTRACT | 85 | 108 | 154 | 121 | 0.024 | printed |
|
|
72
|
+
| LANO | 173 | 96 | 238 | 123 | 0.960 | handwritten |
|
|
73
|
+
|
|
74
|
+
The `text` column is Textract's transcription; hwprint only decides handwritten vs printed. On this page it agrees
|
|
75
|
+
with Textract's own `TextType` on all 110 words.
|
|
76
|
+
|
|
77
|
+
## Model
|
|
78
|
+
|
|
79
|
+
Two ResNet-18 ensembles (3 seeds each), with probabilities averaged:
|
|
80
|
+
|
|
81
|
+
| input | crop | canvas |
|
|
82
|
+
|---|---|---|
|
|
83
|
+
| word | box + 15% of its height on each side | 64 × 256 |
|
|
84
|
+
| context | box + 1 height above and below, 3 heights left and right; extra channel marks the box | 96 × 288 |
|
|
85
|
+
|
|
86
|
+
Words wider than 8× their height (URLs, emails) are scored on their first 8 heights only.
|
|
87
|
+
|
|
88
|
+
## Label definition
|
|
89
|
+
|
|
90
|
+
- **Handwritten**: made with a pen. All signatures count, including autopen.
|
|
91
|
+
- **Printed**: machine-produced in any font, including script and handwriting-style fonts, stamps, and display type.
|
|
92
|
+
|
|
93
|
+
## Training data
|
|
94
|
+
|
|
95
|
+
- **RVL-CDIP** ([Harley et al., 2015](https://adamharley.com/rvl-cdip/)), train split only: about 17,000 word crops
|
|
96
|
+
from scanned 1980s–1990s tobacco-industry documents (IIT-CDIP). Labels come from AWS Textract's word-level
|
|
97
|
+
`TextType`, so they are noisy. Pages with near-duplicates across RVL-CDIP splits were excluded from validation and test.
|
|
98
|
+
- About 13,000 synthetic printed words: real RVL-CDIP text rendered in Google Fonts (OFL), as plain lines, table
|
|
99
|
+
cells, map labels and rubber stamps, then degraded to look like old scans or modern photos. Handwriting-style
|
|
100
|
+
fonts were left out because they imitate print-style handwriting too closely.
|
|
101
|
+
- Augmentation: grey or tinted paper, low contrast, uneven lighting, blur, noise, reverse video.
|
|
102
|
+
|
|
103
|
+
## Evaluation
|
|
104
|
+
|
|
105
|
+
All numbers use human labels; words a person could not call either way were excluded.
|
|
106
|
+
|
|
107
|
+
| test set | hwprint | Textract |
|
|
108
|
+
|---|---|---|
|
|
109
|
+
| RVL-CDIP test, 681 words (half Textract-handwritten, half Textract-printed) | **97.9%** | 94.9% |
|
|
110
|
+
| ↳ handwritten words found, of 363 | **352** | 335 |
|
|
111
|
+
| RVL-CDIP-N, 200 random Textract-handwritten words | 194 / 200 | 198 / 200 |
|
|
112
|
+
| RVL-CDIP-N, 200 random Textract-printed words | 200 / 200 | 200 / 200 |
|
|
113
|
+
| RVL-CDIP-N, 134 words where Textract and an earlier model disagreed | 86 | 113 |
|
|
114
|
+
|
|
115
|
+
RVL-CDIP-O (2,915 out-of-distribution pages, 793k words): hwprint calls 1,171 words handwritten. In a random sample of
|
|
116
|
+
those calls, 35% (95% CI 27–44%) were handwritten, and 38% of those were words Textract labelled printed. Textract
|
|
117
|
+
calls 342 words handwritten, and nearly all of them are.
|
|
118
|
+
|
|
119
|
+
## Limitations
|
|
120
|
+
|
|
121
|
+
- **Latin script only.** Training data is almost entirely English, and synthetic fonts were limited to ones with Latin
|
|
122
|
+
glyphs. It is untested on Arabic, Hebrew, Chinese, Japanese, Korean, Indic (Devanagari, Bengali, Tamil, ...), Thai,
|
|
123
|
+
Cyrillic, Greek and other scripts. Cursive-looking printed scripts may be called handwritten: in out-of-distribution
|
|
124
|
+
checks, printed Arabic words were among its false alarms. Validate on your own documents before relying on it.
|
|
125
|
+
- Best on grayscale scans like RVL-CDIP. On modern, colourful or photographed documents it finds handwriting
|
|
126
|
+
Textract misses but also raises false alarms on logos, text over photos, maps, chart labels, bridge diagrams
|
|
127
|
+
and display fonts.
|
|
128
|
+
- Upright text only. `textract_words` marks rotated and vertical words as unsupported.
|
|
129
|
+
- Very short words (1–2 characters) and isolated digits are the least reliable.
|
|
130
|
+
- Labels come from a commercial OCR system, so the model has absorbed some of its biases.
|
|
131
|
+
- For de-identification where missing handwriting is the costly error, consider flagging a word if either this
|
|
132
|
+
model or your OCR engine calls it handwritten.
|
|
133
|
+
|
|
134
|
+
## License
|
|
135
|
+
|
|
136
|
+
MIT, for code and weights. The training images come from RVL-CDIP; check its terms for your use.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "hwprint"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Classify word crops on document pages as handwritten or printed"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.9"
|
|
12
|
+
authors = [{ name = "Stefan Larson" }]
|
|
13
|
+
keywords = ["handwriting", "document-ai", "ocr", "de-identification", "textract"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Topic :: Scientific/Engineering :: Image Recognition",
|
|
17
|
+
]
|
|
18
|
+
dependencies = ["torch>=2.0", "torchvision>=0.15", "numpy", "pillow", "safetensors", "huggingface_hub>=0.20"]
|
|
19
|
+
|
|
20
|
+
[project.scripts]
|
|
21
|
+
hwprint = "hwprint.cli:main"
|
|
22
|
+
|
|
23
|
+
[tool.setuptools.packages.find]
|
|
24
|
+
where = ["src"]
|
|
25
|
+
|
|
26
|
+
[project.urls]
|
|
27
|
+
Homepage = "https://github.com/gxlarson/hwprint"
|
|
28
|
+
Repository = "https://github.com/gxlarson/hwprint"
|
|
29
|
+
Issues = "https://github.com/gxlarson/hwprint/issues"
|
|
30
|
+
"Model card" = "https://huggingface.co/stefan-hf/hwprint"
|
hwprint-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""hwprint IMAGE --textract RESPONSE.json [--repo stefan-hf/hwprint] [--csv out.csv]
|
|
2
|
+
|
|
3
|
+
Scores every WORD of a Textract response and prints / writes: id, text, textract TextType, box, p_handwritten, label.
|
|
4
|
+
"""
|
|
5
|
+
import argparse
|
|
6
|
+
import csv
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
from PIL import Image
|
|
10
|
+
|
|
11
|
+
from .model import DEFAULT_REPO, HWPrint, textract_words
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def main(argv=None):
|
|
15
|
+
ap = argparse.ArgumentParser(prog="hwprint", description="Handwritten vs printed, per word.")
|
|
16
|
+
ap.add_argument("image")
|
|
17
|
+
ap.add_argument("--textract", required=True, help="Textract JSON for the image")
|
|
18
|
+
ap.add_argument("--repo", default=DEFAULT_REPO, help="Hub repo id or local model directory")
|
|
19
|
+
ap.add_argument("--device")
|
|
20
|
+
ap.add_argument("--threshold", type=float, default=0.5)
|
|
21
|
+
ap.add_argument("--csv", help="write results here instead of stdout")
|
|
22
|
+
a = ap.parse_args(argv)
|
|
23
|
+
im = Image.open(a.image)
|
|
24
|
+
words = [w for w in textract_words(a.textract, im.size) if w["supported"]]
|
|
25
|
+
clf = HWPrint.from_pretrained(a.repo, device=a.device)
|
|
26
|
+
p = clf.predict(im, [w["box"] for w in words])
|
|
27
|
+
f = open(a.csv, "w", newline="") if a.csv else sys.stdout
|
|
28
|
+
w = csv.writer(f)
|
|
29
|
+
w.writerow(["id", "text", "textract", "x0", "y0", "x1", "y1", "p_handwritten", "label"])
|
|
30
|
+
for wd, pi in zip(words, p):
|
|
31
|
+
w.writerow([wd["id"], wd["text"], wd["textract"], *(round(v, 1) for v in wd["box"]), round(float(pi), 4),
|
|
32
|
+
"handwritten" if pi > a.threshold else "printed"])
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
if __name__ == "__main__":
|
|
36
|
+
main()
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""Inference for the hwprint word classifier.
|
|
2
|
+
|
|
3
|
+
A word is given as a page image plus its bounding box (pixels, x0 y0 x1 y1). Two crops are made and scored by
|
|
4
|
+
ResNet-18 ensembles, and the probabilities are averaged:
|
|
5
|
+
word: box + 15% of its height on every side, fitted into 64 x 256
|
|
6
|
+
ctx : box + 1 height above/below and 3 heights left/right, fitted into 96 x 288, plus a mask channel marking the box
|
|
7
|
+
Very long words (wider than MAX_ASPECT x height, e.g. URLs) are scored on their first MAX_ASPECT heights only.
|
|
8
|
+
Preprocessing reproduces training exactly; do not resize the page before calling.
|
|
9
|
+
"""
|
|
10
|
+
import json
|
|
11
|
+
import math
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
import torch
|
|
17
|
+
import torch.nn as nn
|
|
18
|
+
import torchvision
|
|
19
|
+
from PIL import Image
|
|
20
|
+
from safetensors.torch import load_file
|
|
21
|
+
|
|
22
|
+
DEFAULT_REPO = "stefan-hf/hwprint"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _fit(im, H, W):
|
|
26
|
+
"""Aspect-preserving resize into H x W on white; content capped at 254 (training convention)."""
|
|
27
|
+
s = min(H / im.height, W / im.width)
|
|
28
|
+
nw, nh = max(1, round(im.width * s)), max(1, round(im.height * s))
|
|
29
|
+
canvas = Image.new("L", (W, H), 255)
|
|
30
|
+
ox, oy = (W - nw) // 2, (H - nh) // 2
|
|
31
|
+
canvas.paste(im.resize((nw, nh), Image.BILINEAR).point(lambda v: min(v, 254)), (ox, oy))
|
|
32
|
+
return np.asarray(canvas, dtype=np.uint8), (s, ox, oy)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _resnet18():
|
|
36
|
+
m = torchvision.models.resnet18()
|
|
37
|
+
m.fc = nn.Linear(m.fc.in_features, 2)
|
|
38
|
+
return m
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class HWPrint:
|
|
42
|
+
"""Handwritten-vs-printed word classifier.
|
|
43
|
+
|
|
44
|
+
>>> clf = HWPrint.from_pretrained() # downloads weights from the Hugging Face Hub
|
|
45
|
+
>>> p = clf.predict(page_image, [(x0, y0, x1, y1), ...]) # P(handwritten) per box
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
def __init__(self, members, config, device=None):
|
|
49
|
+
self.config = config
|
|
50
|
+
self.device = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu"))
|
|
51
|
+
self.members = {}
|
|
52
|
+
for mode, sds in members.items():
|
|
53
|
+
ms = []
|
|
54
|
+
for sd in sds:
|
|
55
|
+
m = _resnet18()
|
|
56
|
+
m.load_state_dict({k: v.float() for k, v in sd.items()})
|
|
57
|
+
ms.append(m.to(self.device).eval())
|
|
58
|
+
self.members[mode] = ms
|
|
59
|
+
|
|
60
|
+
# ------------------------------------------------------------------ loading
|
|
61
|
+
@classmethod
|
|
62
|
+
def from_pretrained(cls, repo_or_path=DEFAULT_REPO, device=None, revision=None, token=None):
|
|
63
|
+
"""Load from a local directory or a Hugging Face Hub repo id."""
|
|
64
|
+
if os.path.isdir(repo_or_path):
|
|
65
|
+
d = repo_or_path
|
|
66
|
+
cfg_path, w_path = os.path.join(d, "config.json"), os.path.join(d, "model.safetensors")
|
|
67
|
+
else:
|
|
68
|
+
from huggingface_hub import hf_hub_download
|
|
69
|
+
cfg_path = hf_hub_download(repo_or_path, "config.json", revision=revision, token=token)
|
|
70
|
+
w_path = hf_hub_download(repo_or_path, "model.safetensors", revision=revision, token=token)
|
|
71
|
+
config = json.load(open(cfg_path))
|
|
72
|
+
flat = load_file(w_path)
|
|
73
|
+
members = {}
|
|
74
|
+
for mode, n in config["members"].items():
|
|
75
|
+
members[mode] = [{k[len(f"{mode}.{i}."):]: v for k, v in flat.items() if k.startswith(f"{mode}.{i}.")}
|
|
76
|
+
for i in range(n)]
|
|
77
|
+
return cls(members, config, device)
|
|
78
|
+
|
|
79
|
+
# ------------------------------------------------------------------ preprocessing
|
|
80
|
+
def _crops(self, im, boxes, mode):
|
|
81
|
+
c = self.config
|
|
82
|
+
H, W = c["input_size"][mode]
|
|
83
|
+
X = np.zeros((len(boxes), 2, H, W), dtype=np.uint8)
|
|
84
|
+
PW, PH = im.size
|
|
85
|
+
for i, (x0, y0, x1, y1) in enumerate(boxes):
|
|
86
|
+
h = max(1e-6, y1 - y0)
|
|
87
|
+
x1 = min(x1, x0 + c["max_aspect"] * h)
|
|
88
|
+
if mode == "ctx":
|
|
89
|
+
cb = (x0 - c["ctx_pad_h"] * h, y0 - c["ctx_pad_v"] * h, x1 + c["ctx_pad_h"] * h, y1 + c["ctx_pad_v"] * h)
|
|
90
|
+
else:
|
|
91
|
+
p = max(2.0, c["word_pad"] * h)
|
|
92
|
+
cb = (x0 - p, y0 - p, x1 + p, y1 + p)
|
|
93
|
+
cb = (max(0, cb[0]), max(0, cb[1]), min(PW, cb[2]), min(PH, cb[3]))
|
|
94
|
+
cb = tuple(int(round(v)) for v in cb)
|
|
95
|
+
if cb[2] <= cb[0] or cb[3] <= cb[1]:
|
|
96
|
+
continue
|
|
97
|
+
X[i, 0], (s, ox, oy) = _fit(im.crop(cb), H, W)
|
|
98
|
+
if mode == "ctx":
|
|
99
|
+
bx0, by0, bx1, by1 = x0 - cb[0], y0 - cb[1], x1 - cb[0], y1 - cb[1]
|
|
100
|
+
X[i, 1, max(0, int(oy + by0 * s)):int(np.ceil(oy + by1 * s)),
|
|
101
|
+
max(0, int(ox + bx0 * s)):int(np.ceil(ox + bx1 * s))] = 255
|
|
102
|
+
return torch.from_numpy(X)
|
|
103
|
+
|
|
104
|
+
@staticmethod
|
|
105
|
+
def _to_input(xb, mode):
|
|
106
|
+
x = xb.float() / 255.0
|
|
107
|
+
img = (x[:, :1] - 0.5) / 0.25
|
|
108
|
+
third = (x[:, 1:] - 0.5) / 0.25 if mode == "ctx" else img
|
|
109
|
+
return torch.cat([img, img, third], 1)
|
|
110
|
+
|
|
111
|
+
# ------------------------------------------------------------------ inference
|
|
112
|
+
@torch.no_grad()
|
|
113
|
+
def predict(self, image, boxes, batch_size=256, modes=None):
|
|
114
|
+
"""P(handwritten) for each box.
|
|
115
|
+
|
|
116
|
+
image: PIL image, numpy array or path (converted to grayscale)
|
|
117
|
+
boxes: iterable of (x0, y0, x1, y1) in pixels of `image`
|
|
118
|
+
modes: subset of ("ctx", "word"); default both, averaged (the evaluated configuration)
|
|
119
|
+
"""
|
|
120
|
+
if isinstance(image, (str, os.PathLike)):
|
|
121
|
+
image = Image.open(image)
|
|
122
|
+
elif isinstance(image, np.ndarray):
|
|
123
|
+
image = Image.fromarray(image)
|
|
124
|
+
im = image.convert("L")
|
|
125
|
+
boxes = [tuple(float(v) for v in b) for b in boxes]
|
|
126
|
+
if not boxes:
|
|
127
|
+
return np.zeros(0, dtype=np.float32)
|
|
128
|
+
modes = modes or list(self.members)
|
|
129
|
+
per_mode = []
|
|
130
|
+
for mode in modes:
|
|
131
|
+
X = self._crops(im, boxes, mode)
|
|
132
|
+
ps = []
|
|
133
|
+
for m in self.members[mode]:
|
|
134
|
+
out = []
|
|
135
|
+
for i in range(0, len(X), batch_size):
|
|
136
|
+
xb = self._to_input(X[i:i + batch_size].to(self.device), mode)
|
|
137
|
+
if self.device.type == "cuda":
|
|
138
|
+
with torch.autocast("cuda", dtype=torch.bfloat16):
|
|
139
|
+
out.append(m(xb).float().softmax(1)[:, 1].cpu())
|
|
140
|
+
else:
|
|
141
|
+
out.append(m(xb).softmax(1)[:, 1])
|
|
142
|
+
ps.append(torch.cat(out).numpy())
|
|
143
|
+
per_mode.append(np.mean(ps, 0))
|
|
144
|
+
return np.mean(per_mode, 0).astype(np.float32)
|
|
145
|
+
|
|
146
|
+
def classify(self, image, boxes, threshold=0.5, **kw):
|
|
147
|
+
"""List of 'handwritten' / 'printed' labels, one per box."""
|
|
148
|
+
return ["handwritten" if p > threshold else "printed" for p in self.predict(image, boxes, **kw)]
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def textract_words(textract_json, image_size, skip_rotated=True):
|
|
152
|
+
"""WORD blocks of an AWS Textract response as dicts with a pixel box.
|
|
153
|
+
|
|
154
|
+
The model was trained and evaluated on upright words only: with skip_rotated, words whose baseline is rotated
|
|
155
|
+
>= 45 degrees, or tall narrow boxes of 3+ characters (vertical text), get 'supported': False.
|
|
156
|
+
"""
|
|
157
|
+
if isinstance(textract_json, (str, os.PathLike)):
|
|
158
|
+
textract_json = json.load(open(textract_json))
|
|
159
|
+
W, H = image_size
|
|
160
|
+
out = []
|
|
161
|
+
for b in textract_json.get("Blocks", []):
|
|
162
|
+
if b.get("BlockType") != "WORD":
|
|
163
|
+
continue
|
|
164
|
+
bb = b["Geometry"]["BoundingBox"]
|
|
165
|
+
x0, y0 = max(0, bb["Left"] * W), max(0, bb["Top"] * H)
|
|
166
|
+
x1, y1 = min(W, (bb["Left"] + bb["Width"]) * W), min(H, (bb["Top"] + bb["Height"]) * H)
|
|
167
|
+
ok = x1 - x0 >= 4 and y1 - y0 >= 4
|
|
168
|
+
if skip_rotated and ok:
|
|
169
|
+
p = b["Geometry"].get("Polygon")
|
|
170
|
+
if p:
|
|
171
|
+
ang = math.degrees(math.atan2((p[1]["Y"] - p[0]["Y"]) * H, (p[1]["X"] - p[0]["X"]) * W))
|
|
172
|
+
ok = abs(ang) < 45
|
|
173
|
+
ok = ok and not (len(b.get("Text", "")) >= 3 and (y1 - y0) > 1.5 * (x1 - x0))
|
|
174
|
+
out.append({"id": b["Id"], "text": b.get("Text", ""), "box": (x0, y0, x1, y1), "supported": ok,
|
|
175
|
+
"textract": b.get("TextType")})
|
|
176
|
+
return out
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: hwprint
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Classify word crops on document pages as handwritten or printed
|
|
5
|
+
Author: Stefan Larson
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/gxlarson/hwprint
|
|
8
|
+
Project-URL: Repository, https://github.com/gxlarson/hwprint
|
|
9
|
+
Project-URL: Issues, https://github.com/gxlarson/hwprint/issues
|
|
10
|
+
Project-URL: Model card, https://huggingface.co/stefan-hf/hwprint
|
|
11
|
+
Keywords: handwriting,document-ai,ocr,de-identification,textract
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering :: Image Recognition
|
|
14
|
+
Requires-Python: >=3.9
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Requires-Dist: torch>=2.0
|
|
18
|
+
Requires-Dist: torchvision>=0.15
|
|
19
|
+
Requires-Dist: numpy
|
|
20
|
+
Requires-Dist: pillow
|
|
21
|
+
Requires-Dist: safetensors
|
|
22
|
+
Requires-Dist: huggingface_hub>=0.20
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# hwprint
|
|
26
|
+
|
|
27
|
+
Classifies a word on a document page as **handwritten** or **printed**, given the page image and the word's
|
|
28
|
+
bounding box. It was built for de-identification pipelines that need to find handwriting without depending on a
|
|
29
|
+
commercial OCR service's text-type flag.
|
|
30
|
+
|
|
31
|
+
## Install and use
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pip install hwprint
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Code: [github.com/gxlarson/hwprint](https://github.com/gxlarson/hwprint) · Weights and model card:
|
|
38
|
+
[huggingface.co/stefan-hf/hwprint](https://huggingface.co/stefan-hf/hwprint)
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
from PIL import Image
|
|
42
|
+
from hwprint import HWPrint
|
|
43
|
+
|
|
44
|
+
clf = HWPrint.from_pretrained("stefan-hf/hwprint") # downloads ~130 MB of weights
|
|
45
|
+
page = Image.open("page.jpg")
|
|
46
|
+
boxes = [(412, 980, 655, 1032), (120, 140, 388, 170)] # x0, y0, x1, y1 in page pixels
|
|
47
|
+
clf.predict(page, boxes) # array of P(handwritten), e.g. [0.97, 0.02]
|
|
48
|
+
clf.classify(page, boxes) # ['handwritten', 'printed']
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Word boxes can come from any OCR or text detector. For AWS Textract output there is a helper and a CLI:
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
from hwprint import textract_words
|
|
55
|
+
words = [w for w in textract_words("page.json", page.size) if w["supported"]]
|
|
56
|
+
p = clf.predict(page, [w["box"] for w in words])
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
hwprint page.jpg --textract page.json --csv out.csv
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Pass the page at its original resolution; crops are taken and resized internally. Throughput is about 2,000
|
|
64
|
+
words/s on a GPU and about 30 words/s on CPU.
|
|
65
|
+
|
|
66
|
+
## Example: page image + OCR → labels
|
|
67
|
+
|
|
68
|
+
The `examples/` folder has a complete run on one RVL-CDIP test page (a 1984 billboard inspection form):
|
|
69
|
+
|
|
70
|
+
| file | what it is |
|
|
71
|
+
|---|---|
|
|
72
|
+
| `page.jpg` | input: the scanned page |
|
|
73
|
+
| `page.textract.json` | input: the AWS Textract response for the page (only the word boxes are used) |
|
|
74
|
+
| `run_example.py` | the script below, end to end |
|
|
75
|
+
| `output.csv` | output: one row per word with its box, P(handwritten) and label |
|
|
76
|
+
| `overlay.png` | output: the page with handwritten words boxed in red and printed words in blue |
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
python examples/run_example.py examples/page.jpg examples/page.textract.json --out examples/
|
|
80
|
+
# 110 words: 33 handwritten, 77 printed, 0 skipped
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+

|
|
84
|
+
|
|
85
|
+
First rows of `output.csv`:
|
|
86
|
+
|
|
87
|
+
| text | x0 | y0 | x1 | y1 | p_handwritten | label |
|
|
88
|
+
|---|---|---|---|---|---|---|
|
|
89
|
+
| FIELDMAN | 475 | 17 | 541 | 31 | 0.021 | printed |
|
|
90
|
+
| Jerry | 543 | 7 | 614 | 49 | 0.964 | handwritten |
|
|
91
|
+
| Cathey | 621 | 7 | 694 | 51 | 0.957 | handwritten |
|
|
92
|
+
| DATE | 506 | 48 | 541 | 61 | 0.021 | printed |
|
|
93
|
+
| 7/10/84 | 603 | 36 | 676 | 70 | 0.961 | handwritten |
|
|
94
|
+
| *INSPECTION | 411 | 77 | 501 | 92 | 0.024 | printed |
|
|
95
|
+
| CONTRACT | 85 | 108 | 154 | 121 | 0.024 | printed |
|
|
96
|
+
| LANO | 173 | 96 | 238 | 123 | 0.960 | handwritten |
|
|
97
|
+
|
|
98
|
+
The `text` column is Textract's transcription; hwprint only decides handwritten vs printed. On this page it agrees
|
|
99
|
+
with Textract's own `TextType` on all 110 words.
|
|
100
|
+
|
|
101
|
+
## Model
|
|
102
|
+
|
|
103
|
+
Two ResNet-18 ensembles (3 seeds each), with probabilities averaged:
|
|
104
|
+
|
|
105
|
+
| input | crop | canvas |
|
|
106
|
+
|---|---|---|
|
|
107
|
+
| word | box + 15% of its height on each side | 64 × 256 |
|
|
108
|
+
| context | box + 1 height above and below, 3 heights left and right; extra channel marks the box | 96 × 288 |
|
|
109
|
+
|
|
110
|
+
Words wider than 8× their height (URLs, emails) are scored on their first 8 heights only.
|
|
111
|
+
|
|
112
|
+
## Label definition
|
|
113
|
+
|
|
114
|
+
- **Handwritten**: made with a pen. All signatures count, including autopen.
|
|
115
|
+
- **Printed**: machine-produced in any font, including script and handwriting-style fonts, stamps, and display type.
|
|
116
|
+
|
|
117
|
+
## Training data
|
|
118
|
+
|
|
119
|
+
- **RVL-CDIP** ([Harley et al., 2015](https://adamharley.com/rvl-cdip/)), train split only: about 17,000 word crops
|
|
120
|
+
from scanned 1980s–1990s tobacco-industry documents (IIT-CDIP). Labels come from AWS Textract's word-level
|
|
121
|
+
`TextType`, so they are noisy. Pages with near-duplicates across RVL-CDIP splits were excluded from validation and test.
|
|
122
|
+
- About 13,000 synthetic printed words: real RVL-CDIP text rendered in Google Fonts (OFL), as plain lines, table
|
|
123
|
+
cells, map labels and rubber stamps, then degraded to look like old scans or modern photos. Handwriting-style
|
|
124
|
+
fonts were left out because they imitate print-style handwriting too closely.
|
|
125
|
+
- Augmentation: grey or tinted paper, low contrast, uneven lighting, blur, noise, reverse video.
|
|
126
|
+
|
|
127
|
+
## Evaluation
|
|
128
|
+
|
|
129
|
+
All numbers use human labels; words a person could not call either way were excluded.
|
|
130
|
+
|
|
131
|
+
| test set | hwprint | Textract |
|
|
132
|
+
|---|---|---|
|
|
133
|
+
| RVL-CDIP test, 681 words (half Textract-handwritten, half Textract-printed) | **97.9%** | 94.9% |
|
|
134
|
+
| ↳ handwritten words found, of 363 | **352** | 335 |
|
|
135
|
+
| RVL-CDIP-N, 200 random Textract-handwritten words | 194 / 200 | 198 / 200 |
|
|
136
|
+
| RVL-CDIP-N, 200 random Textract-printed words | 200 / 200 | 200 / 200 |
|
|
137
|
+
| RVL-CDIP-N, 134 words where Textract and an earlier model disagreed | 86 | 113 |
|
|
138
|
+
|
|
139
|
+
RVL-CDIP-O (2,915 out-of-distribution pages, 793k words): hwprint calls 1,171 words handwritten. In a random sample of
|
|
140
|
+
those calls, 35% (95% CI 27–44%) were handwritten, and 38% of those were words Textract labelled printed. Textract
|
|
141
|
+
calls 342 words handwritten, and nearly all of them are.
|
|
142
|
+
|
|
143
|
+
## Limitations
|
|
144
|
+
|
|
145
|
+
- **Latin script only.** Training data is almost entirely English, and synthetic fonts were limited to ones with Latin
|
|
146
|
+
glyphs. It is untested on Arabic, Hebrew, Chinese, Japanese, Korean, Indic (Devanagari, Bengali, Tamil, ...), Thai,
|
|
147
|
+
Cyrillic, Greek and other scripts. Cursive-looking printed scripts may be called handwritten: in out-of-distribution
|
|
148
|
+
checks, printed Arabic words were among its false alarms. Validate on your own documents before relying on it.
|
|
149
|
+
- Best on grayscale scans like RVL-CDIP. On modern, colourful or photographed documents it finds handwriting
|
|
150
|
+
Textract misses but also raises false alarms on logos, text over photos, maps, chart labels, bridge diagrams
|
|
151
|
+
and display fonts.
|
|
152
|
+
- Upright text only. `textract_words` marks rotated and vertical words as unsupported.
|
|
153
|
+
- Very short words (1–2 characters) and isolated digits are the least reliable.
|
|
154
|
+
- Labels come from a commercial OCR system, so the model has absorbed some of its biases.
|
|
155
|
+
- For de-identification where missing handwriting is the costly error, consider flagging a word if either this
|
|
156
|
+
model or your OCR engine calls it handwritten.
|
|
157
|
+
|
|
158
|
+
## License
|
|
159
|
+
|
|
160
|
+
MIT, for code and weights. The training images come from RVL-CDIP; check its terms for your use.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/hwprint/__init__.py
|
|
5
|
+
src/hwprint/cli.py
|
|
6
|
+
src/hwprint/model.py
|
|
7
|
+
src/hwprint.egg-info/PKG-INFO
|
|
8
|
+
src/hwprint.egg-info/SOURCES.txt
|
|
9
|
+
src/hwprint.egg-info/dependency_links.txt
|
|
10
|
+
src/hwprint.egg-info/entry_points.txt
|
|
11
|
+
src/hwprint.egg-info/requires.txt
|
|
12
|
+
src/hwprint.egg-info/top_level.txt
|
|
13
|
+
tests/test_basic.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
hwprint
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
from PIL import Image, ImageDraw
|
|
5
|
+
|
|
6
|
+
from hwprint import HWPrint, textract_words
|
|
7
|
+
|
|
8
|
+
MODEL = os.environ.get("HWPRINT_MODEL", "stefan-hf/hwprint")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def test_predict_shapes_and_range():
|
|
12
|
+
clf = HWPrint.from_pretrained(MODEL, device="cpu")
|
|
13
|
+
page = Image.new("L", (800, 300), 255)
|
|
14
|
+
d = ImageDraw.Draw(page)
|
|
15
|
+
d.text((50, 50), "Printed words on a page", fill=0)
|
|
16
|
+
boxes = [(48, 48, 200, 64), (0, 0, 2, 2), (700, 250, 820, 320)] # normal, tiny, partly off-page
|
|
17
|
+
p = clf.predict(page, boxes)
|
|
18
|
+
assert p.shape == (3,) and np.all((p >= 0) & (p <= 1))
|
|
19
|
+
assert clf.predict(page, []).shape == (0,)
|
|
20
|
+
assert clf.classify(page, boxes[:1])[0] in ("handwritten", "printed")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def test_textract_words():
|
|
24
|
+
js = {"Blocks": [
|
|
25
|
+
{"BlockType": "WORD", "Id": "a", "Text": "hello", "TextType": "PRINTED",
|
|
26
|
+
"Geometry": {"BoundingBox": {"Left": 0.1, "Top": 0.1, "Width": 0.2, "Height": 0.05},
|
|
27
|
+
"Polygon": [{"X": 0.1, "Y": 0.1}, {"X": 0.3, "Y": 0.1}, {"X": 0.3, "Y": 0.15}, {"X": 0.1, "Y": 0.15}]}},
|
|
28
|
+
{"BlockType": "WORD", "Id": "b", "Text": "sideways", "TextType": "PRINTED",
|
|
29
|
+
"Geometry": {"BoundingBox": {"Left": 0.5, "Top": 0.1, "Width": 0.02, "Height": 0.3},
|
|
30
|
+
"Polygon": [{"X": 0.5, "Y": 0.4}, {"X": 0.5, "Y": 0.1}, {"X": 0.52, "Y": 0.1}, {"X": 0.52, "Y": 0.4}]}}]}
|
|
31
|
+
ws = textract_words(js, (1000, 1000))
|
|
32
|
+
assert [w["supported"] for w in ws] == [True, False]
|
|
33
|
+
assert np.allclose(ws[0]["box"], (100, 100, 300, 150))
|