Imperatore commited on
Commit
d37ed2d
·
verified ·
1 Parent(s): aef7085

German 1.0.0: run 2026-11-08-0749 (gold 168/84/10/0, Tatoeba 0.53%)

Browse files
Files changed (14) hide show
  1. LICENSE +202 -0
  2. NOTICE +9 -0
  3. README.md +222 -0
  4. config.json +0 -0
  5. gector-guards.json +115 -0
  6. gector-meta.json +37 -0
  7. language-rules.json +7 -0
  8. model.onnx +3 -0
  9. quickstart.ipynb +118 -0
  10. quickstart.py +236 -0
  11. tokenizer.json +0 -0
  12. tokenizer_config.json +16 -0
  13. verb-form-vocab.txt +0 -0
  14. vocab.txt +0 -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.
NOTICE ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ Proofbird GECToR grammar model (German)
2
+ Copyright 2026 Patrick Andrew Hartnett
3
+
4
+ This product includes software developed by Patrick Andrew Hartnett for Proofbird
5
+ (https://proofbird.app). Source: https://huggingface.co/proofbird/gector-bert-de
6
+
7
+ Based on dbmdz/bert-base-german-cased by the MDZ Digital Library team (dbmdz) at the
8
+ Bavarian State Library (MIT licence) and the GECToR tagging scheme
9
+ (Omelianchuk et al., 2020; Apache License 2.0).
README.md ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - de
5
+ base_model: dbmdz/bert-base-german-cased
6
+ pipeline_tag: token-classification
7
+ library_name: onnx
8
+ tags:
9
+ - grammatical-error-correction
10
+ - gector
11
+ - onnx
12
+ - on-device
13
+ datasets:
14
+ - wikimedia/wikipedia
15
+ ---
16
+
17
+ # Proofbird Grammar — German
18
+
19
+ `gector-bert-de` · on-device German grammar correction
20
+
21
+ **Version 1.0.0** · run `2026-11-08-0749` · tag [`v1.0.0`](https://huggingface.co/proofbird/gector-bert-de/tree/v1.0.0), the files the Proofbird app downloads. Pin it with `revision="v1.0.0"`. Versions: a new training run raises the first number, changed guards or rules the second, card or metadata fixes the third.
22
+
23
+ A GECToR-style sequence tagger for German grammatical error correction, exported to ONNX (fp32) to run on the CPU.
24
+ It is the on-device grammar model of [Proofbird](https://proofbird.app), a writing assistant for Windows, and it is
25
+ published here so anyone can inspect what runs on their machine.
26
+
27
+ GECToR does not rewrite text. For each token it predicts one edit tag (keep, delete, replace with a word, append a
28
+ word, change case, change a verb's form), and the edits are applied and the sentence re-tagged up to five times. The
29
+ tagger only proposes local edits; it never paraphrases.
30
+
31
+ ## Quick start
32
+
33
+ [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/#fileId=https%3A//huggingface.co/proofbird/gector-bert-de/blob/main/quickstart.ipynb)
34
+
35
+ No API key, no GPU. One file, [`quickstart.py`](quickstart.py), downloads the model and runs it with ONNX Runtime.
36
+
37
+ ```bash
38
+ pip install onnxruntime tokenizers huggingface_hub
39
+ ```
40
+
41
+ ```python
42
+ import importlib.util
43
+ from huggingface_hub import hf_hub_download
44
+
45
+ spec = importlib.util.spec_from_file_location("quickstart", hf_hub_download("proofbird/gector-bert-de", "quickstart.py"))
46
+ quickstart = importlib.util.module_from_spec(spec)
47
+ spec.loader.exec_module(quickstart)
48
+
49
+ model = quickstart.Gector("proofbird/gector-bert-de")
50
+ corrected, suggestions = model.correct("Meine Schwester sind sehr mude.")
51
+ print(corrected)
52
+ print(suggestions)
53
+ ```
54
+
55
+ ```text
56
+ Meine Schwester ist sehr müde.
57
+ [{"start": 16, "length": 4, "original": "sind", "replacement": "ist"}, {"start": 26, "length": 4, "original": "mude", "replacement": "müde"}]
58
+ ```
59
+
60
+ Each suggestion gives the character position in **your** text (`start`, `length`), what is there now (`original`) and what to put instead (`replacement`), so you can underline it and offer the fix. From the command line: `python quickstart.py "Meine Schwester sind sehr mude."` prints every step below.
61
+
62
+ ## What it corrects
63
+
64
+ Subject-verb agreement, including the verb's person after `du` and `ihr` (`Die Kinder spielt` → `spielen`,
65
+ `Du hat` → `hast`, `Ihr ist` → `seid`), capitalisation of nouns (`keine zeit` → `Zeit`), missing umlauts
66
+ (`Ich hore` → `höre`, `sehr schon` → `schön`), `ß` after a long vowel or diphthong (`Strasse` → `Straße`,
67
+ `weiss` → `weiß`) and the old spellings `daß` / `muß` → `dass` / `muss`, `das` / `dass` after a comma (in both
68
+ directions), common confusables, doubled words, and capitalisation at the start of a sentence.
69
+
70
+ ## How it was trained
71
+
72
+ - **Base encoder:** [`dbmdz/bert-base-german-cased`](https://huggingface.co/dbmdz/bert-base-german-cased) (MIT),
73
+ by the MDZ Digital Library team at the Bavarian State Library. A tagging head (5 000 edit labels) and an
74
+ error-detection head sit on top.
75
+ - **Data: synthetic only.** 3 000 000 sentences from German Wikipedia
76
+ ([`wikimedia/wikipedia`](https://huggingface.co/datasets/wikimedia/wikipedia), `20231101.de`) and 250 000 sentences
77
+ from [Tatoeba](https://tatoeba.org) were corrupted by hand-written German error rules; about 10% stay clean, so the
78
+ model learns to leave correct text alone. 34 000 additional template sentences teach patterns Wikipedia rarely
79
+ contains (`du` and `ihr` with their verb forms, `das` / `dass`, errors in a later clause).
80
+ - **No learner corpora** and no non-commercial data of any kind. No user text was used.
81
+ - One epoch (95 441 steps, batch 64, learning rate 3e-5) on one NVIDIA L4. Run id `2026-11-08-0749`.
82
+
83
+ ## How it was measured
84
+
85
+ | Check | Result |
86
+ |---|---|
87
+ | Gold set (262 hand-written sentences: 178 with one error each, 84 correct) | **168 fixed, 84 left alone, 10 missed, 0 made worse** |
88
+ | False alarms on 4 000 everyday Tatoeba sentences (held out from training) | 21 changed (0.53%); 14 of them correct an error or an old spelling in Tatoeba's own text |
89
+ | Stability: the gold re-run with one extra token in front of each sentence | 3 sentences change result |
90
+
91
+ The gold score is with the apply-side guards in `gector-guards.json` (below). The model was trained for precision: a
92
+ missed error costs less than a wrong correction. The Tatoeba changes include real fixes of Tatoeba's text (`daß` →
93
+ `dass`, `Du wird` → `wirst`, `Unsere Lehrer ist` → `sind`) and seven false alarms, for example `den Talern` →
94
+ `Tälern` and `der jüngere der Brüder` → `Jüngere`. Known misses: `nicht war` → `wahr`, an umlaut or a Konjunktiv in
95
+ the third clause of a long sentence (`und ich mochte schlafen` → `möchte`), and `hätte` → `hatte`, which the model
96
+ leaves alone because both are often right. It has not been measured on learner essays.
97
+
98
+ ## Files
99
+
100
+ | File | What it is |
101
+ |---|---|
102
+ | `model.onnx` | The tagger (fp32, opset 17). Inputs `input_ids`, `attention_mask`; outputs `logits_labels` [1, T, 5000] and `logits_d` [1, T, 2]. |
103
+ | `config.json` | The edit-label vocabulary (`id2label`). |
104
+ | `vocab.txt`, `tokenizer.json`, `tokenizer_config.json` | The base encoder's WordPiece tokenizer. |
105
+ | `gector-meta.json` | Export facts: encoder, tokenizer family, decoding defaults, run id, version. |
106
+ | `gector-guards.json` | Apply-side guards: rules that hold back an edit the model gets wrong in a known way (for example a verb edit that changes the person while the clause has no subject of that person). Part of the measured result. |
107
+ | `language-rules.json` | Language facts the runtime needs (sentence-final punctuation handling). |
108
+ | `verb-form-vocab.txt` | The German verb-form table for the `$TRANSFORM_VERB_*` tags (207 verbs, built for this model). |
109
+ | `quickstart.py` | A complete Python runner: download, tokenize, run, decode, apply, suggestions. See *Quick start*. |
110
+ | `quickstart.ipynb` | The same, as a notebook (the *Open in Colab* button). |
111
+
112
+ The Proofbird app runs the same algorithm in C# with ONNX Runtime; the files are standard, so any GECToR-style
113
+ decoder can use them.
114
+
115
+ ## How it works, step by step
116
+
117
+ The model never sees letters and never writes text. It reads numbers (token ids) and answers, for every word, which **edit** to make: one of 5 000 tags such as `$KEEP`, `$DELETE`, `$APPEND_sind`, `$REPLACE_essen` or `$TRANSFORM_VERB_P3P_P3S` (change a verb's form). `quickstart.py` does everything around it. This is the real run of the example above.
118
+
119
+ **1. Prepare the text.** `language-rules.json` says the final full stop comes off before the model sees the sentence (it goes back on at the end): `Meine Schwester sind sehr mude`.
120
+
121
+ **2. The request.** The words are looked up in the model's dictionary (`vocab.txt`). A rare word is split into pieces; the edit is read at its first piece. `[CLS]` stands for a dummy first word, `$START`, so an edit on it can add a word at the very beginning; `[SEP]` marks the end.
122
+
123
+ ```text
124
+ words $START Meine Schwester sind sehr mude
125
+ tokens [CLS] Meine Schwester sind sehr mu ##de [SEP]
126
+ input_ids [102, 4747, 5659, 341, 843, 8130, 158, 103]
127
+ attention_mask [1, 1, 1, 1, 1, 1, 1, 1]
128
+ ```
129
+
130
+ Two inputs, both whole numbers (int64), shape `[1, 8]`: one sentence of 8 tokens.
131
+
132
+ **3. The response.** Two outputs (float32): `logits_labels` `[1, 8, 5000]`, a score for each of the 5 000 edits at every token, and `logits_d` `[1, 8, 2]`, a score for "this word is correct" and "this word is wrong". A softmax turns each row into probabilities; the most probable edit at each word's first token is the one applied.
133
+
134
+ **4. Pass by pass.** The corrected sentence goes back in, until a pass changes nothing (at most five passes). Connected errors are fixed one after the other.
135
+
136
+ *Pass 1:* `Meine Schwester sind sehr mude`
137
+
138
+ | Word | Wrong | Chosen edit | Probability |
139
+ |---|---|---|---|
140
+ | $START | 0.0% | $KEEP | 100.0% |
141
+ | Meine | 0.0% | $KEEP | 100.0% |
142
+ | Schwester | 0.0% | $KEEP | 100.0% |
143
+ | sind | 24.1% | $KEEP | 76.7% |
144
+ | sehr | 0.0% | $KEEP | 100.0% |
145
+ | mude | 94.2% | **$REPLACE_müde** | 99.6% |
146
+
147
+ → `Meine Schwester sind sehr müde`
148
+
149
+ *Pass 2:* `Meine Schwester sind sehr müde`
150
+
151
+ | Word | Wrong | Chosen edit | Probability |
152
+ |---|---|---|---|
153
+ | $START | 0.0% | $KEEP | 100.0% |
154
+ | Meine | 0.0% | $KEEP | 100.0% |
155
+ | Schwester | 0.0% | $KEEP | 99.9% |
156
+ | sind | 99.8% | **$TRANSFORM_VERB_P3P_P3S** | 99.7% |
157
+ | sehr | 0.0% | $KEEP | 100.0% |
158
+ | müde | 0.0% | $KEEP | 100.0% |
159
+
160
+ → `Meine Schwester ist sehr müde`
161
+
162
+ *Pass 3:* `Meine Schwester ist sehr müde`
163
+
164
+ | Word | Wrong | Chosen edit | Probability |
165
+ |---|---|---|---|
166
+ | $START | 0.0% | $KEEP | 100.0% |
167
+ | Meine | 0.0% | $KEEP | 100.0% |
168
+ | Schwester | 0.0% | $KEEP | 100.0% |
169
+ | ist | 0.0% | $KEEP | 100.0% |
170
+ | sehr | 0.0% | $KEEP | 100.0% |
171
+ | müde | 0.0% | $KEEP | 100.0% |
172
+
173
+ → `Meine Schwester ist sehr müde` — no change, so it stops.
174
+
175
+ **5. The suggestions.** The original and the final words are compared, and each changed stretch becomes one suggestion with its position in the original text (unchanged text keeps its own spacing), as in the Quick start output above.
176
+
177
+ **6. Settings.** `Gector(repo, keep_confidence=0.0, min_error_prob=0.0)` takes the two GECToR precision knobs (the Proofbird app runs with both at 0, and at most five passes):
178
+
179
+ - `keep_confidence` adds a bonus to `$KEEP` before choosing: higher means fewer, safer edits.
180
+ - `min_error_prob` ignores an edit the model is less sure of, and leaves the whole sentence alone when no word is at least that likely to be wrong. With `min_error_prob=0.9` the example is still corrected (`Meine Schwester ist sehr m��de.`): the model is 94.2% sure one word is wrong.
181
+
182
+ ## What Proofbird adds
183
+
184
+ `quickstart.py` is the model on its own. The [Proofbird](https://proofbird.app) app runs the same algorithm in C# and adds:
185
+
186
+ - **Guards** (`gector-guards.json`, in this repository): per-language rules that hold back edits we measured as wrong in a known shape. The scores under *How it was measured* are with the guards.
187
+ - **Spelling, checked separately** by the operating system's spell checker; the guards use it so a grammar edit is not made on a word that is misspelled.
188
+ - **A card for each change** that names the error ("Subject–verb agreement") and, on request, explains it.
189
+
190
+ ## Licence and attribution
191
+
192
+ The model weights and the files in this repository are released under the
193
+ [Apache License 2.0](LICENSE). If you redistribute the model or a model built from it, keep the
194
+ [NOTICE](NOTICE) file with it (Apache-2.0, section 4(d)).
195
+
196
+ The training data carries its own terms. Wikipedia text is © Wikipedia contributors,
197
+ [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/). Tatoeba sentences are from
198
+ [tatoeba.org](https://tatoeba.org), [CC BY 2.0 FR](https://creativecommons.org/licenses/by/2.0/fr/). The base
199
+ encoder is `dbmdz/bert-base-german-cased` by the MDZ Digital Library team (dbmdz) at the Bavarian State Library, MIT
200
+ licence. The tagging scheme follows GECToR (Omelianchuk et al., 2020, *GECToR – Grammatical Error Correction: Tag,
201
+ Not Rewrite*); the German verb-form table was built for this model.
202
+
203
+ ## How to cite
204
+
205
+ If you use or build on this model, please cite it:
206
+
207
+ ```bibtex
208
+ @misc{hartnett2026gectorde,
209
+ author = {Hartnett, Patrick Andrew},
210
+ title = {Proofbird GECToR grammar model (German)},
211
+ year = {2026},
212
+ publisher = {Hugging Face},
213
+ howpublished = {\url{https://huggingface.co/proofbird/gector-bert-de}},
214
+ note = {Proofbird, https://proofbird.app}
215
+ }
216
+ ```
217
+
218
+ If you build on this model, a link back to this page is appreciated.
219
+
220
+ ## Contact
221
+
222
+ Published by Patrick Andrew Hartnett as personal work. Questions and reports: open a discussion on this repository.
config.json ADDED
The diff for this file is too large to render. See raw diff
 
gector-guards.json ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "guards": [
3
+ {
4
+ "type": "velar_orthography",
5
+ "note": "built-in (always on): reject a spurious h-insertion on a non-velar stem"
6
+ },
7
+ {
8
+ "type": "elision_echo",
9
+ "note": "built-in (always on): collapse a redundant elision echo (un'ora ora -> un'ora)"
10
+ },
11
+ {
12
+ "type": "auxiliary_number",
13
+ "note": "built-in (always on): keep 'e`' before a singular participle ('E` andata' is 3sg and correct; 'sono' would flip it to 1sg)"
14
+ },
15
+ {
16
+ "type": "suppress_append_words",
17
+ "words": "der|die|das|den|dem|ein|eine|und|in|zu|mit|auf|ist",
18
+ "note": "drop a stray appended article/preposition (the retired drop_word artifact)"
19
+ },
20
+ {
21
+ "type": "require_cue",
22
+ "pairs": "konnte>könnte|konnten>könnten|konntest>könntest|hatte>hätte|hatten>hätten|hattest>hättest|war>wäre|waren>wären|warst>wärst|wurde>würde|wurden>würden|wurdest>würdest|mochte>möchte|mochten>möchten|mochtest>möchtest",
23
+ "cues": "wenn|falls|ob|würde|würden|würdest|wäre|wären|hätte|hätten|könnte|könnten|gern|gerne|bitte|vielleicht|am liebsten|lieber",
24
+ "note": "indicative -> Konjunktiv II only with a cue in the sentence: both forms are correct German otherwise"
25
+ },
26
+ {
27
+ "type": "require_cue",
28
+ "pairs": "könnte>konnte|könnten>konnten|hätte>hatte|hätten>hatten|wäre>war|wären>waren|würde>wurde|würden>wurden|möchte>mochte|möchten>mochten",
29
+ "cues": "gestern|vorgestern|damals|früher|vorhin|neulich|einst|seinerzeit|letzte|letzten|letztes|letzter|#year|kind|jugend|schulzeit|kindheit",
30
+ "note": "Konjunktiv II -> indicative only with a past-time cue"
31
+ },
32
+ {
33
+ "type": "require_cue",
34
+ "pairs": "schon>schön",
35
+ "cues": "sehr|so|wirklich|ganz|besonders|zu|ziemlich|recht|wie|wunder",
36
+ "scope": "prev",
37
+ "note": "schon -> schön only right after an intensifier"
38
+ },
39
+ {
40
+ "type": "require_cue",
41
+ "pairs": "schön>schon",
42
+ "note": "never: 'Bleib schön fern', 'schwer, aber schön' are correct"
43
+ },
44
+ {
45
+ "type": "delete_only_duplicates",
46
+ "note": "a $DELETE is honoured only on a repeated word ('ist ist'); never on a real word ('wirklich echt?')"
47
+ },
48
+ {
49
+ "type": "redirect_replace",
50
+ "from": "mal",
51
+ "to": "Mal",
52
+ "redirect": "mal",
53
+ "whenPrevIs": "das",
54
+ "note": "the particle 'mal' after 'das' stays lowercase (Zieh dir das mal an); 'das erste Mal' has a word between"
55
+ },
56
+ {
57
+ "type": "capital_needs_known_word",
58
+ "note": "capitalise only when the word (either case) is known to the spell layer; inert without a speller"
59
+ },
60
+ {
61
+ "type": "no_replace_to_closed_class",
62
+ "words": "der|die|das|den|dem|des|ein|eine|einen|einem|einer|eines|und|oder|aber|in|im|zu|zum|zur|von|vom|mit|auf|für|an|am|bei|beim|nach|aus|um|über|unter|vor|dass|ob|wenn|als|wie|nicht|auch|noch|nur|so|sehr|es|er|sie|wir|ihr|ich|du|man|sich",
63
+ "note": "never replace a content word with a function word (the $REPLACE head guessing on an unknown token)"
64
+ },
65
+ {
66
+ "type": "redirect_replace",
67
+ "from": "hore",
68
+ "to": "hörte",
69
+ "redirect": "höre",
70
+ "whenPrevIs": "ich",
71
+ "note": "Ich hore: the umlaut fix is höre (1st person), never the past hörte"
72
+ },
73
+ {
74
+ "type": "block_replace",
75
+ "from": "spielt",
76
+ "to": "spiele",
77
+ "note": "spurious 3sg->1sg flip on correct text; no gold case needs this edit"
78
+ },
79
+ {
80
+ "type": "verb_person_needs_subject",
81
+ "pairs": "ich>1S|du>2S|er>3S|sie>3S|sie>3P|es>3S|man>3S|wir>1P|ihr>2P",
82
+ "words": "der|die|das|den|dem|des|ein|eine|einen|einem|einer|eines|kein|keine|mein|meine|dein|deine|sein|seine|ihre|ihren|ihrem|unser|unsere|euer|eure|dieser|diese|dieses|jeder|jede|jedes|alle|beide|viele|zwei|drei",
83
+ "note": "a verb's person changes only toward a subject in view; the nearest subject pronoun's form wins (Du macht -> machst, never *mache)"
84
+ },
85
+ {
86
+ "type": "block_replace",
87
+ "from": "du",
88
+ "to": "Du",
89
+ "note": "capitalising the informal pronoun is a style choice, never a fix"
90
+ },
91
+ {
92
+ "type": "block_replace",
93
+ "from": "dir",
94
+ "to": "Dir",
95
+ "note": "capitalising the informal pronoun is a style choice, never a fix"
96
+ },
97
+ {
98
+ "type": "block_replace",
99
+ "from": "dich",
100
+ "to": "Dich",
101
+ "note": "capitalising the informal pronoun is a style choice, never a fix"
102
+ },
103
+ {
104
+ "type": "block_replace",
105
+ "from": "euch",
106
+ "to": "Euch",
107
+ "note": "capitalising the informal pronoun is a style choice, never a fix"
108
+ },
109
+ {
110
+ "type": "no_unknown_replacement",
111
+ "scope": "strict",
112
+ "note": "never propose a non-word (word knowledge; strict: a misspelling re-inflected into another non-word is held too; runs last)"
113
+ }
114
+ ]
115
+ }
gector-meta.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "base": "dbmdz/bert-base-german-cased",
3
+ "encoder": "dbmdz/bert-base-german-cased",
4
+ "precision": "fp32",
5
+ "tokenizer": "wordpiece",
6
+ "logits_labels_dim": 5000,
7
+ "logits_d_dim": 2,
8
+ "onnx_inputs": [
9
+ "input_ids",
10
+ "attention_mask"
11
+ ],
12
+ "onnx_outputs": [
13
+ "logits_labels",
14
+ "logits_d"
15
+ ],
16
+ "defaults": {
17
+ "keep_confidence": 0.0,
18
+ "min_error_prob": 0.0,
19
+ "n_iteration": 5
20
+ },
21
+ "run_id": "2026-11-08-0749",
22
+ "exported_at": "2026-11-08T11:55:18+00:00",
23
+ "checkpoint": "ckpt_best.pt",
24
+ "git_commit": null,
25
+ "recipe_sha256": {
26
+ "build_dataset.py": "311ab76557eb",
27
+ "preprocess.py": "384e6c617e5e",
28
+ "train.py": "489238d21b2c",
29
+ "export_onnx.py": "dd74b65200f5",
30
+ "runrecord.py": "718118cd4cb0",
31
+ "tatoeba_split.py": "4183ce16b93d",
32
+ "corrupt_de.py": "d90103e0a8be",
33
+ "morph_de.py": "a9361cce0af0",
34
+ "language-rules.de.json": "901b350a9c75"
35
+ },
36
+ "version": "1.0.0"
37
+ }
language-rules.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "version": 1,
3
+ "language": "de",
4
+ "_comment": "Per-bundle language facts (see C# LanguageRules / ADR-004). stripTrailingTerminator true: the DE bundle follows the same BERT/WordPiece recipe as Italian — validate at eval. clauseConjunctions: connectors after a comma = independent-clause boundary for GectorAnalyzer.Correct's clause split (see the EN/IT files). German caveat: weil/wenn/dass/obwohl/während introduce verb-FINAL subordinate clauses, so the split hands the model a fragment with non-main-clause word order; the Italian precedent (perché/mentre, HARMFUL 0) suggests this is safe because GECToR only makes word-level agreement/form edits, but PRUNE these five at the DE eval if comma_context shows harm. The coordinators (aber/und/oder/denn/sondern/doch) and V2 adverbial connectors (dann/also/deshalb/...) are unproblematic. Validate against lang/de/gold comma_context at eval.",
5
+ "stripTrailingTerminator": true,
6
+ "clauseConjunctions": ["aber", "und", "oder", "denn", "sondern", "doch", "sonst", "dann", "also", "deshalb", "deswegen", "trotzdem", "dennoch", "jedoch", "außerdem", "weil", "wenn", "dass", "obwohl", "während"]
7
+ }
model.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f2703a742065cb460987a517a94e61b0e2a75bddc4f33d52563c98010be2c92d
3
+ size 452972247
quickstart.ipynb ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Proofbird grammar model (German): quick start\n",
8
+ "\n",
9
+ "Run [`proofbird/gector-bert-de`](https://huggingface.co/proofbird/gector-bert-de) in a few lines. It is small (about 450 MB), runs on a CPU in about\n",
10
+ "30 ms a sentence, and needs no API key."
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "code",
15
+ "metadata": {},
16
+ "execution_count": null,
17
+ "outputs": [],
18
+ "source": [
19
+ "!pip install -q onnxruntime tokenizers huggingface_hub"
20
+ ]
21
+ },
22
+ {
23
+ "cell_type": "markdown",
24
+ "metadata": {},
25
+ "source": [
26
+ "## 1. Load the model and correct a sentence\n",
27
+ "\n",
28
+ "`quickstart.py`, published with the model, downloads it, runs it, and returns the corrected text plus one suggestion per\n",
29
+ "change (character position, original, replacement)."
30
+ ]
31
+ },
32
+ {
33
+ "cell_type": "code",
34
+ "metadata": {},
35
+ "execution_count": null,
36
+ "outputs": [],
37
+ "source": [
38
+ "import importlib.util\n",
39
+ "from huggingface_hub import hf_hub_download\n",
40
+ "\n",
41
+ "path = hf_hub_download(\"proofbird/gector-bert-de\", \"quickstart.py\")\n",
42
+ "spec = importlib.util.spec_from_file_location(\"quickstart\", path)\n",
43
+ "quickstart = importlib.util.module_from_spec(spec)\n",
44
+ "spec.loader.exec_module(quickstart)\n",
45
+ "\n",
46
+ "model = quickstart.Gector(\"proofbird/gector-bert-de\")\n",
47
+ "corrected, suggestions = model.correct(\"Meine Schwester sind sehr mude.\")\n",
48
+ "print(corrected)\n",
49
+ "suggestions"
50
+ ]
51
+ },
52
+ {
53
+ "cell_type": "markdown",
54
+ "metadata": {},
55
+ "source": [
56
+ "## 2. See every pass\n",
57
+ "\n",
58
+ "The model does not write text. For every word it picks one of 5 000 edits; the corrected sentence goes back in until\n",
59
+ "nothing changes, so connected errors are fixed one after the other. `verbose=True` prints what each pass sent and got\n",
60
+ "back."
61
+ ]
62
+ },
63
+ {
64
+ "cell_type": "code",
65
+ "metadata": {},
66
+ "execution_count": null,
67
+ "outputs": [],
68
+ "source": [
69
+ "corrected, suggestions = model.correct(\"Meine Schwester sind sehr mude.\", verbose=True)"
70
+ ]
71
+ },
72
+ {
73
+ "cell_type": "markdown",
74
+ "metadata": {},
75
+ "source": [
76
+ "## 3. Your own text\n",
77
+ "\n",
78
+ "`model.passes` holds the same per-pass detail as a list of dictionaries, if you want to build on it."
79
+ ]
80
+ },
81
+ {
82
+ "cell_type": "code",
83
+ "metadata": {},
84
+ "execution_count": null,
85
+ "outputs": [],
86
+ "source": [
87
+ "text = \"Du hat heute keine zeit.\"\n",
88
+ "print(model.correct(text)[0])\n",
89
+ "model.passes[0][\"words\"]"
90
+ ]
91
+ },
92
+ {
93
+ "cell_type": "markdown",
94
+ "metadata": {},
95
+ "source": [
96
+ "---\n",
97
+ "Published by Patrick Andrew Hartnett. The [Proofbird](https://proofbird.app) writing assistant for Windows uses this\n",
98
+ "model on-device and adds the guards in `gector-guards.json` and an explanation for each change. If you build on this\n",
99
+ "model, a link back is appreciated."
100
+ ]
101
+ }
102
+ ],
103
+ "metadata": {
104
+ "kernelspec": {
105
+ "display_name": "Python 3",
106
+ "language": "python",
107
+ "name": "python3"
108
+ },
109
+ "language_info": {
110
+ "name": "python"
111
+ },
112
+ "colab": {
113
+ "provenance": []
114
+ }
115
+ },
116
+ "nbformat": 4,
117
+ "nbformat_minor": 5
118
+ }
quickstart.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Proofbird GECToR grammar model (German): a complete, minimal way to run it (Python).
2
+
3
+ pip install onnxruntime tokenizers huggingface_hub numpy
4
+ python quickstart.py "Meine Schwester sind sehr mude."
5
+
6
+ This is the same algorithm the Proofbird app runs (C#), minus the guards in gector-guards.json (see the model card,
7
+ "What Proofbird adds"). Published by Patrick Andrew Hartnett - https://proofbird.app
8
+ """
9
+ import argparse
10
+ import difflib
11
+ import json
12
+ import os
13
+ import re
14
+
15
+ import numpy as np
16
+ import onnxruntime as ort
17
+ from huggingface_hub import snapshot_download
18
+ from tokenizers import Tokenizer
19
+
20
+ MODEL = "proofbird/gector-bert-de"
21
+ WORD = re.compile(r"\w+(?:'\w+)?|[^\w\s]") # a word (with one apostrophe inside), or one punctuation mark
22
+
23
+
24
+ class Gector:
25
+ def __init__(self, model=MODEL, keep_confidence=0.0, min_error_prob=0.0):
26
+ """keep_confidence: a bonus added to "$KEEP" before choosing (higher = fewer, safer edits).
27
+ min_error_prob: ignore an edit, or a whole sentence, the model is less sure of than this.
28
+ Both 0 by default, as in the Proofbird app."""
29
+ self.keep_confidence, self.min_error_prob = keep_confidence, min_error_prob
30
+ path = model if os.path.isdir(model) else snapshot_download(model)
31
+ cfg = json.load(open(os.path.join(path, "config.json"), encoding="utf-8"))
32
+ self.labels = [cfg["id2label"][str(i)] for i in range(len(cfg["id2label"]))]
33
+ self.keep = self.labels.index(cfg.get("keep_label", "$KEEP"))
34
+ self.incorrect = {v: int(k) for k, v in cfg["d_id2label"].items()}[cfg.get("incorrect_label", "$INCORRECT")]
35
+ rules_path = os.path.join(path, "language-rules.json")
36
+ rules = json.load(open(rules_path, encoding="utf-8")) if os.path.exists(rules_path) else {}
37
+ # The final full stop comes off before the model and goes back on after (where the bundle says so).
38
+ self.strip = rules.get("stripTerminators", ".!?") if rules.get("stripTrailingTerminator") else ""
39
+ # Articles written glued to the next word with an apostrophe, which the model reads as two words (bundle data).
40
+ self.glued = set((rules.get("elision") or {}).get("nonElidingArticles") or rules.get("nonElidingArticles") or [])
41
+ self.verbs = {} # "<word>_<from>_<to>" -> the verb form, for $TRANSFORM_VERB_*
42
+ verb_path = os.path.join(path, "verb-form-vocab.txt")
43
+ if os.path.exists(verb_path):
44
+ for line in open(verb_path, encoding="utf-8"):
45
+ if ":" in line:
46
+ words, tags = line.strip().split(":")
47
+ w1, w2 = words.split("_")
48
+ self.verbs[f"{w1}_{tags}"] = w2
49
+ self.tokenizer = Tokenizer.from_file(os.path.join(path, "tokenizer.json"))
50
+ self.session = ort.InferenceSession(os.path.join(path, "model.onnx"), providers=["CPUExecutionProvider"])
51
+
52
+ # --- one pass: words in, one tag per word out -------------------------------------------------------------
53
+ def tag(self, words):
54
+ enc = self.tokenizer.encode(words, is_pretokenized=True) # [CLS] w1 ... wn [SEP]; [CLS] stands for $START
55
+ input_ids = np.array([enc.ids], dtype=np.int64)
56
+ logits_labels, logits_d = self.session.run(
57
+ ["logits_labels", "logits_d"],
58
+ {"input_ids": input_ids, "attention_mask": np.ones_like(input_ids)})
59
+ probs = softmax(logits_labels[0]) # [tokens, 5000]
60
+ probs[:, self.keep] += self.keep_confidence
61
+ wrong = softmax(logits_d[0])[:, self.incorrect] # [tokens]
62
+ result, seen = [], set()
63
+ for t, w in enumerate(enc.word_ids): # one label per word, read at its first token
64
+ word = 0 if t == 0 else (None if w is None else w + 1)
65
+ if word is None or word in seen:
66
+ continue
67
+ seen.add(word)
68
+ best = int(probs[t].argmax())
69
+ label = self.labels[best] if probs[t, best] >= self.min_error_prob else "$KEEP"
70
+ result.append((label, float(probs[t, best]), float(wrong[t])))
71
+ if max(r[2] for r in result) < self.min_error_prob: # no word is confidently wrong: keep the sentence
72
+ result = [("$KEEP", p, e) for _, p, e in result]
73
+ return input_ids, logits_labels.shape, result
74
+
75
+ # --- apply one tag to one word ------------------------------------------------------------------------------
76
+ def edit(self, word, label):
77
+ if label.startswith("$APPEND_"):
78
+ return word + " " + label[8:]
79
+ if word == "$START" or label == "$KEEP":
80
+ return word
81
+ if label.startswith("$REPLACE_"):
82
+ return label[9:]
83
+ if label == "$DELETE":
84
+ return ""
85
+ if label.startswith("$TRANSFORM_SUF_"): # change the ending: $TRANSFORM_SUF_<old>_<new>
86
+ old, new = label[15:].split("_", 1)
87
+ if not word.endswith(old):
88
+ return word
89
+ stem = word[: len(word) - len(old)]
90
+ return stem + new
91
+ if label.startswith("$TRANSFORM_VERB_"): # verb form from verb-form-vocab.txt
92
+ return self.verbs.get(f"{word}_{label[16:]}", word)
93
+ if label == "$TRANSFORM_CASE_CAPITAL":
94
+ return word[:1].upper() + word[1:].lower()
95
+ if label == "$TRANSFORM_CASE_LOWER":
96
+ return word.lower()
97
+ if label == "$TRANSFORM_CASE_UPPER":
98
+ return word.upper()
99
+ if label == "$TRANSFORM_AGREEMENT_PLURAL":
100
+ return word + "s"
101
+ if label == "$TRANSFORM_AGREEMENT_SINGULAR":
102
+ return word[:-1]
103
+ if label == "$TRANSFORM_SPLIT_HYPHEN":
104
+ return word.replace("-", " ")
105
+ if label.startswith("$MERGE_"):
106
+ return word + " " + label
107
+ return word
108
+
109
+ # --- the whole call: up to 5 passes, then the suggestions -------------------------------------------------
110
+ def correct(self, text, max_passes=5, verbose=False):
111
+ core, tail = text, ""
112
+ if self.strip and text.rstrip()[-1:] and text.rstrip()[-1] in self.strip:
113
+ core, tail = text.rstrip()[:-1], text[len(text.rstrip()) - 1:]
114
+ plain = core.replace("’", "'") # the models were trained on straight apostrophes
115
+ words = self.words(plain)
116
+ self.passes = [] # what each pass saw and did (for printing or a UI)
117
+ for n in range(1, max_passes + 1):
118
+ input_ids, shape, tags = self.tag(words)
119
+ edited = [self.edit(w, label) for w, (label, _, _) in zip(["$START"] + words, tags)]
120
+ tokens = (" ".join(e for e in edited if e).replace(" $MERGE_HYPHEN ", "-")
121
+ .replace(" $MERGE_SPACE ", "").split())
122
+ new_words = [x for t in rejoin(t for t in tokens if t != "$START") for x in self.words(t)]
123
+ self.passes.append({
124
+ "pass": n, "input": join(" ".join(words)), "input_ids": input_ids[0].tolist(),
125
+ "logits_labels_shape": list(shape),
126
+ "words": [{"word": w, "tag": label, "probability": round(p, 6), "wrong": round(wrong, 6),
127
+ "edit": e if e != w else None}
128
+ for w, (label, p, wrong), e in zip(["$START"] + words, tags, edited)],
129
+ "result": join(" ".join(new_words)), "changed": new_words != words})
130
+ if verbose:
131
+ print_pass(self.passes[-1])
132
+ if new_words == words:
133
+ break
134
+ words = new_words
135
+ found = self.suggestions(plain, words) # same length as core, so positions match the real text
136
+ corrected = core
137
+ for f in reversed(found): # apply right to left, so positions stay valid
138
+ f["original"] = core[f["start"]: f["start"] + f["length"]]
139
+ corrected = corrected[: f["start"]] + f["replacement"] + corrected[f["start"] + f["length"]:]
140
+ return corrected + tail, found
141
+
142
+ def words(self, text):
143
+ return [w for w, _, _ in self.spans(text)]
144
+
145
+ def spans(self, text, surface=False):
146
+ """The words of the text with their character positions. An article glued to the next word with an apostrophe
147
+ (the bundle's list) is split into the two words the model was trained on."""
148
+ out = []
149
+ for m in WORD.finditer(text):
150
+ article, sep, rest = m.group().partition("'")
151
+ if sep and rest and article.lower() in self.glued:
152
+ # the article keeps its apostrophe for comparing (so splitting it counts as a change), not for the model
153
+ first = article + "'" if surface else article
154
+ out += [(first, m.start(), m.start() + len(first)), (rest, m.end() - len(rest), m.end())]
155
+ else:
156
+ out.append((m.group(), m.start(), m.end()))
157
+ return out
158
+
159
+ def suggestions(self, original, corrected_words):
160
+ """Compare the original words with the corrected ones: one suggestion per changed stretch, with its character
161
+ position in the ORIGINAL text. Unchanged text keeps the writer's own spacing and characters."""
162
+ spans = self.spans(original, surface=True)
163
+ a = [w for w, _, _ in spans]
164
+ out = []
165
+ for op, i1, i2, j1, j2 in difflib.SequenceMatcher(a=a, b=corrected_words, autojunk=False).get_opcodes():
166
+ if op == "equal":
167
+ continue
168
+ new = join(" ".join(corrected_words[j1:j2]))
169
+ if i1 == i2: # pure insertion
170
+ if i1 < len(a): # before a word: "new "; before punctuation: " new"
171
+ start = end = spans[i1][1]
172
+ if new[-1:] in OPENING:
173
+ pass # an opening mark hugs the next word
174
+ elif i1 == 0 or a[i1][0].isalnum():
175
+ new = new + " "
176
+ else:
177
+ new = " " + new
178
+ else: # at the very end
179
+ start = end = spans[-1][2] if spans else 0
180
+ new = (" " if new[:1].isalnum() else "") + new
181
+ else:
182
+ start, end = spans[i1][1], spans[i2 - 1][2]
183
+ if new and end < len(original) and original[end].isalnum() and new[-1].isalnum():
184
+ new += " " # a glued article split off: keep a space before the next word
185
+ if not new: # pure deletion: take one neighbouring space with it
186
+ if end < len(original) and original[end] == " ":
187
+ end += 1
188
+ elif start > 0 and original[start - 1] == " ":
189
+ start -= 1
190
+ out.append({"start": start, "length": end - start, "original": original[start:end], "replacement": new})
191
+ return out
192
+
193
+
194
+ OPENING = "([{“«\"" # marks that hug the word after them
195
+ CLOSING = ".,;:!?)]}%»”" # marks that hug the word before them
196
+
197
+
198
+ def softmax(x):
199
+ e = np.exp(x - x.max(axis=-1, keepdims=True))
200
+ return e / e.sum(axis=-1, keepdims=True)
201
+
202
+
203
+ def print_pass(p):
204
+ print(f"\n--- pass {p['pass']}: \"{p['input']}\"")
205
+ print(f"request input_ids {p['input_ids']} attention_mask all 1")
206
+ print(f"response logits_labels {p['logits_labels_shape']} logits_d {p['logits_labels_shape'][:2] + [2]}")
207
+ for w in p["words"]:
208
+ print(f" {w['word']:<12} wrong {w['wrong']:6.1%} {w['tag']} {w['probability']:.1%}")
209
+ print(f"result \"{p['result']}\"" + ("" if p["changed"] else " (no change: stop)"))
210
+
211
+
212
+ def rejoin(tokens):
213
+ """A word the model ends with an apostrophe hugs the next word."""
214
+ out = []
215
+ for t in tokens:
216
+ if out and len(out[-1]) > 1 and out[-1].endswith("'") and t[:1].isalnum():
217
+ out[-1] += t
218
+ else:
219
+ out.append(t)
220
+ return out
221
+
222
+
223
+ def join(text):
224
+ """Words back to normal text: no space before closing punctuation or after an opening mark."""
225
+ text = re.sub(f" ([{re.escape(CLOSING)}])", r"\1", " ".join(text.split()))
226
+ return re.sub(f"([{re.escape(OPENING.replace(chr(34), ''))}]) ", r"\1", text)
227
+
228
+
229
+ if __name__ == "__main__":
230
+ ap = argparse.ArgumentParser()
231
+ ap.add_argument("text")
232
+ ap.add_argument("--model", default=MODEL, help="a Hugging Face repo id or a local folder")
233
+ args = ap.parse_args()
234
+ corrected, found = Gector(args.model).correct(args.text, verbose=True)
235
+ print(f"\ncorrected: \"{corrected}\"")
236
+ print("suggestions:", json.dumps(found, indent=2, ensure_ascii=False))
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "cls_token": "[CLS]",
4
+ "do_lower_case": false,
5
+ "is_local": false,
6
+ "local_files_only": false,
7
+ "mask_token": "[MASK]",
8
+ "max_len": 512,
9
+ "model_max_length": 512,
10
+ "pad_token": "[PAD]",
11
+ "sep_token": "[SEP]",
12
+ "strip_accents": null,
13
+ "tokenize_chinese_chars": true,
14
+ "tokenizer_class": "BertTokenizer",
15
+ "unk_token": "[UNK]"
16
+ }
verb-form-vocab.txt ADDED
The diff for this file is too large to render. See raw diff
 
vocab.txt ADDED
The diff for this file is too large to render. See raw diff